A “Hello, World” procedural macro
local graph
Chapter 4 — A “Hello, World” procedural macro
Section titled “Chapter 4 — A “Hello, World” procedural macro”A “Hello, World” procedural macro
Section titled “A “Hello, World” procedural macro”This chapter covers
Section titled “This chapter covers”- Setting up a procedural macro
- Getting the name of a struct by parsing a stream of tokens
- Generating hardcoded output
- Using variables in generated code
- Inspecting generated code with
cargo expand - Writing a macro without help from
synandquote - Understanding how Rust’s internal macros are special
We now come to the meat of our book: procedural macros. As we explained earlier, both procedural and declarative macros are forms of metaprogramming and allow you to manipulate and extend code. But they go about it differently. Declarative macros offer a domain-specific language (DSL) that allows you to generate code based on a combination of matchers and transcribers. Procedural macros, on the
CHAPTER 3 A “Hello, World” procedural macro
Section titled “CHAPTER 3 A “Hello, World” procedural macro”other hand, deal with lower-level information. They receive a stream of tokens containing every detail of the code you want to work with.
In my mind, the difference between declarative and procedural macros—and when you should use them—is a bit like SQL and general-purpose programming languages when it comes to querying databases. SQL is powerful, expressive, and user friendly. It should be your first choice for querying. But at a certain level of complexity and for some kinds of tasks, it breaks down. It becomes complicated and difficult to read and extend. At that point, it can be worthwhile to replace SQL with a general-purpose language. Querying might require more effort and setup, but you will have more options and power. So the advice here is to start with declarative macros. They are simple and powerful, require only minimal setup, and have better IDE support to boot. If you want to do things that declarative macros can’t (for example, manipulating existing structs), you should turn to procedural macros.
3.1 Basic setup of a procedural macro project
Section titled “3.1 Basic setup of a procedural macro project”We start simple, with a macro that adds a “Hello, World” printing method to a struct or enum (see figure 3.1 for the project setup). Adding new functionality to a struct is a good use case for a derive macro. On the other hand, if we wanted to modify existing code, we would have to look elsewhere, since these macros are incapable of doing that. Derive macros are activated by adding the #[derive] annotation to your code, putting the name of the macro between brackets. No doubt you have encountered these annotations before when you wanted to add Debug (#[derive(Debug)]) or Clone (#[derive(Clone)]) functionality to your code.

[!visual-conversion] Flowchart for basic setup of a procedural macro project Cropped from the scan (PDF page 052, printed p. ?): Flowchart for basic setup of a procedural macro project
Figure 3.1 Basic setup of a procedural macro project
3.1 Basic setup of a procedural macro project
Section titled “3.1 Basic setup of a procedural macro project”Creating a procedural macro takes some work, so bear with me while we go through the setup. First, we need a hello-world directory with another directory called hello-world-macro inside the former. In hello-world-macro, we will put the macro project; in the root, we will add an application (see figure 3.2).
You are probably used to creating new Rust projects with cargo init. However, for our macro, we do not need an application but a library. Developers who want to use our macro will import our library as a dependency. So run cargo init --lib in the hello-world-macro subdirectory of the project.
We have to modify the generated Cargo.toml. The most important change is adding a lib section, with the proc-macro property set to true. This tells Rust that this library will expose one or more procedural macros and will make some tooling available to us. We also want to add quote and syn as dependencies. These are not strictly required, but they will make our lives much easier.
Listing 3.1 The lib section and dependencies of hello-world-macro
Section titled “Listing 3.1 The lib section and dependencies of hello-world-macro”[package]name = "hello-world-macro"version = "0.1.0"edition = "2021"
[dependencies]quote = "1.0.33"syn = "2.0.39"
[lib]proc-macro = trueNOTE We do not require Cargo workspaces to get this working, though we will see examples of such a setup later on.
Inside the automatically generated lib.rs file, we add a basic implementation that does not really do anything yet. We will discuss the code in the next section. For now, let us continue our setup.
Listing 3.2 The initial lib.rs file from our hello-world-macro library
Section titled “Listing 3.2 The initial lib.rs file from our hello-world-macro library”use quote::quote;use proc_macro::TokenStream;
#[proc_macro_derive(Hello)]pub fn hello(_item: TokenStream) -> TokenStream {app code] HW --> M1[src/main.rs] HW --> C1[Cargo.toml] HW --> C2[Cargo.lock] HW -->|contains directory| HWM[hello-world-macro
macro code] HWM --> L1[src/lib.rs] HWM --> C3[Cargo.toml] HWM --> C4[Cargo.lock] ```
[!visual-conversion] Procedural-macro project structure Converted from a print project-structure diagram (PDF page 053): the root holds the hello-world app (src/main.rs, Cargo.toml, Cargo.lock) and a hello-world-macro directory (src/lib.rs, Cargo.toml, Cargo.lock).
Figure 3.2 Our project structure
CHAPTER 3 A “Hello, World” procedural macro
Section titled “CHAPTER 3 A “Hello, World” procedural macro”let add_hello_world = quote! {};add_hello_world.into()}The library is now ready. In the outer hello-world directory, we will set up a Rust example application with cargo init. This time, we add a dependency on the macro library we just created using a relative path. The name of the dependency is important and should match the name of the package you are importing (the path and directory name can be different, though). Try changing the dependency name to “foo-bar,” and do a cargo run. You will get something like error: no matching package named foo-bar found. Since our application is located one level above the macro directory, in the root of the project, our path is ./hello-world-macro. Some later chapters will have a nested directory for both the application and the library. In that case, we will have to go up one level (path = "../fill-in-the-name-of-your-macro").
Listing 3.3 The Cargo.toml file from our outer Rust application
Section titled “Listing 3.3 The Cargo.toml file from our outer Rust application”[package]name = "hello-world"version = "0.1.0"edition = "2021"
[dependencies]hello-world-macro = { path = "./hello-world-macro" }Finally, modify the default main.rs. You should now be able to compile and run your application with cargo run. It currently prints nothing (except for a warning that Example is never constructed).
Listing 3.4 The initial main.rs file from the outer application
Section titled “Listing 3.4 The initial main.rs file from the outer application”#[macro_use]extern crate hello_world_macro;
#[derive(Hello)]struct Example;
fn main() {}NOTE If you don’t like this setup or all the manual work, you could use cargo generate (https://github.com/cargo-generate/cargo-generate), which has a template (https://github.com/waynr/proc-macro-template) for generating macro setups. For learning purposes, setting things up manually at least once is advisable. But once you’ve got the hang of it, you can use the util/create_setup.sh script in the code repository (https://github.com/VanOvermeire/rust-macros-book), which automatically sets up projects in the various styles used in this book.
3.2 Analyzing the procedural macro setup
Section titled “3.2 Analyzing the procedural macro setup”Now let us analyze the setup. The nested directory with lib.rs is the only piece of code we really need:
use quote::quote;use proc_macro::TokenStream;
#[proc_macro_derive(Hello)]pub fn hello(_item: TokenStream) -> TokenStream { let add_hello_world = quote! {}; add_hello_world.into()}- Declares this function to be a derive macro named “Hello”
- Generates a new (currently empty) TokenStream using the quote macro
- Uses the Into trait to change this TokenStream into the normal/standard library TokenStream with the same name
Below the import of dependencies, we have #[proc_macro_derive(Hello)]. This is an attribute, a piece of metadata that informs Rust that something should happen. In our case, it tells Rust that this function is an entry point to a derive macro (see figure 3.3). This annotation requires a name between parentheses—“Hello” in our example—which will be used when invoking the macro: #[derive(Hello)]. The name of the function, on the other hand, is not used externally. So pick anything you want.
Figure 3.3 The signature of a derive macro
Moving on, we have the function signature. It has a single parameter of type TokenStream, which we are not using yet. Therefore, it has been prefixed with an underscore. In earlier chapters, we already mentioned how procedural macros operate on a stream of tokens, a representation of the code that we want to modify—a struct, for example. Everything there is to know about that struct will be contained inside this TokenStream. Meanwhile, the TokenStream that we are returning will be used by Rust to generate additional code.

[!visual-conversion] Diagram explaining derive macro signature with annotations for macro declaration, … Cropped from the scan (PDF page 055, printed p. ?): Diagram explaining derive macro signature with annotations for macro declaration, name, input/output, and public requirement.
CHAPTER 3 A “Hello, World” procedural macro
Section titled “CHAPTER 3 A “Hello, World” procedural macro”A high-level overview
Section titled “A high-level overview”Here is a high-level overview of what Rust does when you tell it to compile your application (and I am not an expert on the details). There are two steps involved: lexing and parsing. Lexing—also called tokenization—is the first step and is used to turn your code as a raw text stream into a stream of tokens. For example, pass the expression 1 + 11 to a macro, and the resulting stream will look like this (ignoring spans and suffixes for now):
TokenStream [Literal { kind: Integer, symbol: “1” }, Punct { ch: ’+’, spacing: Alone }, Literal { kind: Integer, symbol: “11” }]
Our raw text has been turned into three tokens (the two numbers and the + sign).
Parsing turns this information into an Abstract Syntax Tree (AST; http://mng.bz/5IKZ), a tree-like representation of all relevant data in your program. This AST makes it easier for the Rust compiler (as well as compilers in other languages) to do its work (i.e., creating an executable that computers can understand). In the previous example, an AST might interpret the plus sign as the root, with the two Literals (numbers) as its branches. Meanwhile, spans are used to link back to the original text, which is useful for things like error messages. Once the AST has been constructed, macros can be processed by the compiler.
While these are interesting little facts, you do not need to know the details of this process to write procedural macros. The most important takeaway is that Rust gives us code as parsed tokens. In return, we graciously give back information in the same format. Rust knows how to use these tokens. After all, all “normal” code is also turned into tokens, which means it is easy to turn your tokens into additional application code.
You can find more information in the Rust Compiler Development Guide (https://rustc-dev-guide.rust-lang.org/), The Little Book of Rust Macros (https://veykril.github.io/tlborm/), and The Rust Reference (https://doc.rust-lang.org/stable/reference/).
This brings us to the body of our function, where we are calling the `quote` macro from the dependency with the same name. We are not passing any parameters into `quote`, which means we are generating an empty `TokenStream`. Because `quote` is actually using the `proc_macro2 TokenStream` (a wrapper around the built-in type), we still have to use the `Into` trait to transform it into a “normal” `proc_macro TokenStream`: `add_hello_world.into()`. So the end result is a macro that generates nothing. Zero run-time overhead would be the marketer’s pitch for this version of our library. But there is no obligation for a macro to generate code, so this is acceptable in Rust.
Now take a look at `main.rs`:
```rust#[macro_use]extern crate hello_world_macro;
#[derive(Hello)]struct Example;
fn main() {}- Makes the macros inside the
hello_world_macrodirectory available for use - Adds the “Hello” derive macro …
- …to our empty Example struct
3.2 Analyzing the procedural macro setup
Section titled “3.2 Analyzing the procedural macro setup”The first two lines tell Rust that we will want to use macros from this dependency, similar to how we import declarative macros. (This time we need to specify the dependency using underscores. In our Cargo.toml we used hyphens.) This is the older style for importing procedural macros. Nowadays, you should import them with a use one-liner (e.g., use hello_world_macro::Hello;). In this chapter, we primarily use the older style, which is still used in a lot of crates and therefore still worth knowing. But in subsequent chapters, we will switch to the newer (Rust 2018) style.
Next, the #[derive(Hello)] attribute tells Rust to run our derive macro named “Hello” for the Example struct, passing that struct along as an input of type TokenStream. The (currently empty) output code will be added to our main.rs file.
Earlier we said that the outer application was not strictly necessary. Instead, it is a convenience—a “consumer” that helps us verify that our code compiles. This is useful because Rust’s compiler will not catch errors in code generated by our library. To make this more concrete, say we make a typo when adding the parameter for the derive macro function and write TokenStrea. If we run cargo check, Rust will point out that the TokenStrea does not exist. Failure prevented! But suppose we write invalid Rust within the quote macro invocation:
rust #[proc_macro_derive(Hello)] pub fn hello(item: TokenStream) -> TokenStream { let add_hello_world = quote! { fn this should not work () {} }; add_hello_world.into() }
Running `cargo check` inside our macro library still succeeds! But when we do a check in the outer application, we get an error:error: expected one of ( or <, found should
—> src/main.rs:4:10
|
4 | #[derive(Hello)]
| ^^^^^^ expected one of ( or <
|
= note: this error originates in the derive macro Hello
Apparently, Rust thinks that `fn this` means we want to create a function called `this`. A function and its name are followed by either parentheses containing the parameters or generics (which are surrounded by `< >`). Instead, the word `should` appears. The lesson here is that `cargo check` inside your procedural macro library will only check for mistakes in your *library code*, not in the *code it generates*.
This makes sense because within the library we are not using the generated code. All Rust cares about is that we declared `TokenStream` to be the return type of our function. And as long as we return *any* stream of tokens, even an invalid one, it is happy. Even if it did care, the compiler has no way of knowing in what context your generated code
<!-- page: 058 -->
# CHAPTER 3 A “Hello, World” procedural macro
will be used, which makes checking hard. So instead, we use a simple application with a basic usage example to generate code and force the compiler to stop being lazy and do some work. In later chapters, we will turn to tests for asserting the proper working of our macro.
## 3.3 Generating output
How about actually producing some code? Start by adding the following to `lib.rs`.
### Listing 3.5 Parsing the input and producing hardcoded output
```rust// earlier imports
#[proc_macro_derive(Hello)]pub fn hello(_item: TokenStream) -> TokenStream { let add_hello_world = quote! { impl Example { fn hello_world(&self) { println!("Hello, World") } } };
add_hello_world.into()}Returns a hardcoded implementation block
We are still not doing anything with the incoming tokens. But we are using quote to generate new code. Right now, that new code is a hardcoded implementation block for the Example struct we added to main.rs. This means we can now call this method and the following code should run. Do remember that the target for cargo run should be the application or else you will get a bin target must be available for cargo run since a library cannot be executed.
Listing 3.6 Calling our generated function in our main file
Section titled “Listing 3.6 Calling our generated function in our main file”// the macro import
#[derive(Hello)]struct Example;
fn main() { let e = Example {}; e.hello_world();}Prints “Hello, World” when executed
The only downside is that our code only works for structs named “Example.” Rename the struct, and Rust will complain that it cannot find type Example in this scope as it can’t match the implementation block to an existing type. The solution is to retrieve the name of the struct from the incoming tokens and use it for the impl that we are
3.3 Generating output
Section titled “3.3 Generating output”generating. In the terminology of macros, both declarative and procedural, this name is an identifier. And since our tokens represent the code that we decorated (a struct and its contents), we will need the topmost identifier. Once we have the name, we can combine it with quote to produce more interesting output.
Listing 3.7 Parsing the input and using it in our output
Section titled “Listing 3.7 Parsing the input and using it in our output”use quote::quote;use proc_macro::TokenStream;use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(Hello)]pub fn hello(item: TokenStream) -> TokenStream { let ast = parse_macro_input!(item as DeriveInput); let name = ast.ident;
let add_hello_world = quote! { impl #name { fn hello_world(&self) { println!("Hello, World") } } };
add_hello_world.into()}We start by parsing the input tokens into an AST by using parse_macro_input, provided by the syn crate. syn offers a lot of tools to help you parse Rust tokens, and this declarative macro is one tool in its arsenal. The as DeriveInput is a bit of custom syntactic sugar. Behind the scenes, the argument after as is used to determine the type that will be generated. We have gone for DeriveInput. As the name suggests, this is any kind of input that you might get when writing a derive macro. So it basically contains either an enum or a struct.
Once we have the DeriveInput, we can get the name of the struct by retrieving the topmost ident (ifier), which we save in a variable called name. If we want to use name in our output, we need a special syntax to tell quote that this is not a literal value but should be replaced with the content of a variable with a matching name. You can do that by prefixing the name of your variable with a hashtag (i.e., #name), which, in our case, will be replaced with the identifier Example. As you can see, generating output with quote is delightfully easy (see figure 3.4).
Figure 3.4 Using the name variable in quote for our Example struct
Note: The image content (Figure 3.4) is described textually as per the instruction to avoid including actual images. The diagram shows a flow from "name: Example" to applying the value to quote, resulting in the generated code block. The text annotations in the image are preserved as part of the description.

> [!visual-conversion] Flowchart showing name substitution in quote macro: name: Example → …> Cropped from the scan (PDF page 059, printed p. ?): Flowchart showing name substitution in quote macro: name: Example → Apply value → impl #name → After applying → impl Example
<!-- page: 060 -->
CHAPTER 3 A “Hello, World” procedural macro
Run the code again, and it should produce the same output method as before, even if you change the name of your struct.
## 3.4 Experimenting with our code
Now let us run some experiments. Does our macro work with enums? Yes! Add the following to `main.rs`.
### Listing 3.8 Invoking our macro for an enum
rust// previous code
#[derive(Hello)]enum Pet { Cat,}
fn main() { // previous code
let p = Pet::Cat; p.hello_world();}How about functions? Unfortunately, this doesn’t work, not only because impl cannot be used for functions but also because derive is not allowed for functions. The error brings this point across quite clearly: derive may only be applied to structs, enums and unions.
NOTE Though unions are a valid
derivetarget, they do not feature in this book, mostly because they are much less ubiquitous than structs and enums, existing almost solely for compatibility with C over a foreign function interface (FFI).
Would our generated code overwrite existing implementation blocks? Thankfully, no. As we mentioned in an earlier chapter, Rust supports multiple impl blocks. So the following works.
Listing 3.9 Multiple implementation blocks
Section titled “Listing 3.9 Multiple implementation blocks”// earlier code
impl Example { fn another_function(&self) { println!("Something else"); }}
fn main() { let e = Example {}; e.hello_world();}
<!-- page: 061 -->
e.another_function();// other code}
Other things might still go wrong though. For example, if you were to define an additional hello_world function, you would get an error duplicate definitions for hello_world. You’d better hope no users of your macro will ever think to add a function with that name! Name overlap is a real risk—and something we will talk about later in this book.
## 3.5 cargo expand
In our previous chapter, we introduced a couple of ways to debug macros and to show what they expand to. But we skipped over one very useful tool: cargo expand (https://github.com/dtolnay/cargo-expand), which was unstable for some time but can now be used with stable Rust. You can install it with `cargo install cargo-expand`, after which you can run `cargo expand` in the root of the application directory or the `src` folder. This will print your application code after macro expansion. In listing 3.10, you can see that all macros, including `println!`, were expanded after running `cargo expand` in the root of our project. (Except, that `format_args!` was not expanded. That’s a Rust problem [https://github.com/dtolnay/cargo-expand/issues/173], and fixing it is a work in progress.)
### Listing 3.10 cargo expand output (with changed formatting)
rust#![feature(prelude_import)]#[prelude_import]use std::prelude::rust_2021::*;
// imports
struct Example;
impl Example { fn hello_world(&self) { ::std::io::_print( format_args!("Hello, World\n") ); }}
// Pet enum and its expanded code
// main functionAs we saw earlier, a prelude contains globally available functions, traits, etc. Rust is adding annotations and an import to make them available. This is why, for example, Clone works without import.
The derive annotation has disappeared.
The code from expanding
#[derive(Hello)]
An expanded
println!
Our derive annotation has disappeared since it is not needed anymore, now that macro expansion is done. In its place, the macro-generated code has been added.
CHAPTER 3 A “Hello, World” procedural macro
Section titled “CHAPTER 3 A “Hello, World” procedural macro”cargo expand is a useful tool for a visual inspection of our code, and it runs even when our output is invalid, making it useful for debugging compilation problems. Say I had mistyped self in our quote macro invocation. I would get a compilation error and the following output, showing that something was very wrong with the function parameter. If the error still wasn’t clear, I could pipe the output to a file (cargo expand > somefile.rs) and have my IDE help me track down the problem. Or I could temporarily replace my main.rs and get pointed to the incorrect lines by cargo check:
impl ExampleStruct { fn hello_world(sel: ()) { { ::std::io::_print(format_args!("Hello, World\n")); } }}You can also use expand within the hello-world-macro library, but that will only show you how the macros you use—not the ones you create for others—are expanded, similar to how check will only point out errors in your code and not in generated code. So, most of the time, you want to use the expand command in applications that utilize your library and its macro.
3.6 The same macro—without syn and quote
Section titled “3.6 The same macro—without syn and quote”The quote and syn libraries are very useful but not strictly necessary for writing macros. Listing 3.11 is the same application without them. To retrieve the name, we iterate over the incoming stream and take the second element with nth(1). That item is a TokenTree containing the name of the struct or enum. The first element, contained in nth(0), has the type (i.e., struct or enum) and is not relevant in this situation—so we skip it. With the ident_name function, we take the tree and return the name identifier or throw an error if we cannot find it.
DEFINITION A TokenTree sits somewhere between a TokenStream and simple tokens. Basically, a TokenStream is a sequence of TokenTrees, which are themselves (recursively) composed of more trees and/or tokens. This is why we can iterate over our stream, pick an element, and assure Rust that the type is TokenTree. The tt fragment specifier for declarative macros, which we encountered in the previous chapter, is also a TokenTree.
To generate output, we use the format macro to inject our name variable in a string. For the transformation from string to TokenStream, we can use parse. We expect this to work, so we just use an unwrap on the Result that our parsing returns. This approach might seem very doable. We have removed two dependencies at the cost of a little bit of extra code. But even with such a basic example, we had to put in work to get the identifier and to output the new code. And with more complete examples, the complexity and additional burden of work would only grow.
3.6 The same macro—without syn and quote
Section titled “3.6 The same macro—without syn and quote”Listing 3.11 Without syn and quote
Section titled “Listing 3.11 Without syn and quote”use proc_macro::{TokenStream, TokenTree};
#[proc_macro_derive(Hello)]pub fn hello_alt(item: TokenStream) -> TokenStream { fn ident_name(item: TokenTree) -> String { match item { TokenTree::Ident(i) => i.to_string(), _ => panic!("no ident") } } let name = ident_name(item.into_iter().nth(1).unwrap());
format!("impl {{ }} {{ fn hello_world(&self) \ {{ println!(\"Hello, World\") }} }} {}", name) .parse() .unwrap()}If we have a TokenTree containing an identifier, we return it as a string.
As an input for the previous function, we provide the second element of the TokenStream, which should be the name.
We use
format!to add the retrieved name to a string representation of our impl block. Then we parse to turn it into a TokenStream. This will only fail if we made a mistake, in which caseunwrappanicking is fine.
Even so, compilation speed is a reason why you might want to opt out of using syn. While it is a very powerful library, it is also big and slow to compile. So if our example was a real macro, and we only needed the name of the struct/enum, our naive example would compile a lot faster. Several libraries try to offer a lightweight alternative to syn—venial (https://github.com/PoignardAzur/venial), for example.
Listing 3.12 is what our macro looks like with that library. Don’t forget to add venial = "0.5.0" to the dependencies if you are following along. The code looks very similar to what we had before. We use parse_declaration, which gives back an enum Declaration. With pattern matching, we retrieve the name from that enum.
Listing 3.12 Using a lightweight parser like venial
Section titled “Listing 3.12 Using a lightweight parser like venial”use quote::quote;use proc_macro::TokenStream;use venial::{parse_declaration, Declaration, Struct, Enum};
#[proc_macro_derive(Hello)]pub fn hello(item: TokenStream) -> TokenStream { let declaration = parse_declaration(item.into()).unwrap();
let name = match declaration { Declaration::Struct(Struct { name, .. }) => name, Declaration::Enum(Enum { name, .. }) => name, _ => panic!("only implemented for struct and enum") };
let add_hello_world = quote! { impl #name { fn hello_world(&self) {Retrieves the name if we receive an enum or a struct; panics in all other cases
CHAPTER 3 A “Hello, World” procedural macro
println!("Hello, World")}};
add_hello_world.into()}Even in this simple example, build times measured with cargo build --timings drop from 3.1 seconds to 1.8 on my machine. Still, in this book, we will use syn because it is well known, widely used, and very powerful. Plus, once you are familiar with how it handles the TokenStream parsing, switching to a lightweight alternative should not be too hard: many of the parsing concepts are always the same.
3.7 From the real world
Section titled “3.7 From the real world”We will save further library explorations for subsequent chapters and limit ourselves to a few observations for now. First, the developers of Rocket (https://rocket.rs/) are actually kind enough to teach you that macros can be imported in two ways (the ones we described in this chapter):
//! And to import all macros, attributes, and derives via `#[macro_use]`//! in the crate root://!//! ```rust//! #[macro_use] extern crate rocket;//! # #[get("/")] fn hello() { }//! # fn main() { rocket::build().mount("/", routes![hello]); }//! ```//!//! Or, alternatively, selectively import from the top-level scope://!//! ```rust//! # extern crate rocket;//!//! use rocket::{get, routes};//! # #[get("/")] fn hello() { }//! # fn main() { rocket::build().mount("/", routes![hello]); }//! ```Second, you may also be wondering how the standard library parses and outputs macros, since it cannot use external libraries like syn and quote. Instead, the standard library uses built-ins with similar concepts and names. For example, rustc_ast, the Rust abstract syntax tree, is used for parsing input. Outputting code is done with rustc_expand. And rustc_span contains utilities like Ident and Span. It is both familiar and alien when you are used to working with syn and quote. But it is not meant for external usage.
Finally, since procedural macros have to be placed in a library, in the root of the crate (or else you will get functions tagged with #[proc_macro_derive] must currently reside in the root of the crate), lib.rs is a great starting point for
exploring other people’s procedural macro code. You will see what macros they have and can dig in when needed.
Exercises
Section titled “Exercises”See the appendix for solutions.
- Fill in the question marks (???) and make the following derive macro compile:
#[proc_macro_derive(???)]pub fn uppercase(item: TokenStream) -> ??? { let ast = parse_macro_input!(item as ???); let name = ast.ident; let uppercase_name = name.to_string().to_uppercase();
let add_uppercase = quote! { impl ??? { fn uppercase(&self) { println!("{}", #uppercase_name); } } }; add_uppercase.into()}The following code fragment shows a usage example:
#[derive(UpperCaseName)]struct Example;
fn main() { let e = Example {}; e.uppercase(); // this prints 'EXAMPLE'}-
Try changing the name of the macro inside
lib.rsand running the application. What error do you get? What do you have to do to fix things? -
Add a function called
testing_testingto the output of our macro. This is an associated function, one that takes no&selfparameter. It should write “One two three” to the console. -
See if you can output a greeting followed by the name of the input (e.g., “Hello Example”). Fair warning: passing
#nameto print will not be enough, because that’s an identifier, and you need a string. So either callto_stringon the identifier and save the result in a variable or use thestringifymacro to change the#nameinto a string for you.
Summary
Section titled “Summary”- Derive macros, the first kind of procedural macro, allow us to add functionality to structs and enums.
- To write procedural macros, we need to create a library with a function that accepts a
TokenStreaminput and outputs anotherTokenStream.
CHAPTER 3 A “Hello, World” procedural macro
Section titled “CHAPTER 3 A “Hello, World” procedural macro”- That output is the code that will be generated and added to our application.
- To verify our macro, we cannot rely solely on
cargo checkwithin the library, because that will only check the code within the library itself, not the code we generate. Therefore, it is useful to have an application that uses and tests our macro. At the very least, this way we can verify that the generated code compiles. - You can write procedural macros with standard Rust tooling, but
synis of great help parsing input, andquotehas a macro to generate output. - You can retrieve values from your input and pass them into your output.
cargo expandis a great tool that allows you to see the code generated by macros in your code.