Making fields public with attribute macros
local graph
Chapter 5 — Making fields public with attribute macros
Section titled “Chapter 5 — Making fields public with attribute macros”Making fields public with attribute macros
Section titled “Making fields public with attribute macros”This chapter covers
Section titled “This chapter covers”- Understanding the differences between derive macros and attribute macros
- Finding field information in the abstract syntax tree
- Retrieving fields by using matching
- Retrieving fields with a custom struct
- Retrieving fields with a custom struct and a Parse implementation
- Adding multiple outputs in quote
- Debugging macros with log statements
- Understanding the no-panic crate
Rust likes to hide information. A function, struct, or enum is private by default, and the same goes for the fields of a struct. This is very sensible, though occasionally slightly annoying when you have a struct that has a lot of fields that are better off being public. Data Transfer Objects (DTOs) are a classic example of this and a
CHAPTER 4 Making fields public with attribute macros
Section titled “CHAPTER 4 Making fields public with attribute macros”common pattern in many programming languages, used for transferring information between systems or different parts of a single system. Because they are a simple wrapper for information, they should not contain any business logic. And “information hiding,” a primary reason for keeping fields in a struct/class private, is not applicable when your only value is exposing the information contained in fields.
For the purpose of experimentation, we will show how we can change the default behavior with a few lines of code. We will create a macro that, once added to a struct, will make it and all of its fields public. This is a very different challenge than the one we faced in the previous chapter. Back then, we were adding things to existing code. Now we have to modify what is already there. So derive macros are out, and attribute macros are in.
Attribute macros get their name from the fact that they define a new attribute. When you annotate a struct or enum with that new custom attribute, the macro will be triggered. Otherwise, writing the library and code for an attribute macro is quite similar to creating a derive macro. But there are differences as well: an attribute macro also receives a TokenStream containing additional attributes (if any). And—more importantly for this chapter—its output tokens will replace the input. That sounds like something that could do the trick.
1 Setup of an attribute macro project
Section titled “1 Setup of an attribute macro project”Let’s go through this chapter’s setup, which is very similar to the previous one:
- Create a new directory (
make-public) with another directory (make-public-macro) inside it. - Inside the nested
make-public-macrodirectory, runcargo init --libto initialize our macro. - Add the
synandquotedependencies (withcargo add syn quote) and setlibtoproc-macro = true. - Run
cargo initin the outermake-publicdirectory and add our library as a dependency.
Listing 4.1 Part of the Cargo.toml file from make-public-macro
Section titled “Listing 4.1 Part of the Cargo.toml file from make-public-macro”[dependencies]quote = "1.0.33"syn = "2.0.39"
[lib]proc-macro = trueListing 4.2 Part of the Cargo.toml from make-public
Section titled “Listing 4.2 Part of the Cargo.toml from make-public”[dependencies]make-public-macro = { path = "./make-public-macro" }
<!-- page: 069 -->
4.2 Attribute macros vs. derive macros
## 4.2 Attribute macros vs. derive macros
With the setup out of the way, we start simple by adding a bit of code to `lib.rs` in the nested directory. We define a public function that produces a `TokenStream`. It takes an `item` parameter and parses it into an abstract syntax tree (AST). That way we will once again be able to retrieve whatever we need from the original code. Just like before, the output is created using the `quote!` macro.
### Listing 4.3 Initial setup
rustextern crate core;
use quote::quote;use proc_macro::TokenStream;use syn::{parse_macro_input, DeriveInput};
#[proc_macro_attribute]pub fn public(_attr: TokenStream, item: TokenStream) -> TokenStream { let _ast = parse_macro_input!(item as DeriveInput);
let public_version = quote! {};
public_version.into()}The annotation tells Rust that this is an attribute macro.
The name of an attribute macro is determined by the name of the function (“public”). It takes two streams as parameters.
A leading underscore here because we are not using the AST yet
As before, our initial implementation takes the input and produces no output.
While the code should look familiar, there are some differences when you compare it to the previous chapter. First, we have a different attribute: #[proc_macro_attribute] instead of #[proc_macro_derive]. And, unlike before, we do not specify the name of the macro between parentheses (#[proc_macro_derive(Hello)]). Instead, the name of the function determines the attribute name. So, in our case, this macro creates a custom attribute #[public]. You can also see that we receive an additional TokenStream—which we will ignore for the time being—that contains information about our attribute (see figure 4.1).
Figure 4.1 The signature of an attribute macro

[!visual-conversion] Diagram explaining attribute macro signature with labeled parts: macro declaration, … Cropped from the scan (PDF page 069, printed p. ?): Diagram explaining attribute macro signature with labeled parts: macro declaration, item contents, output TokenStream, and macro attributes.
The starting point of our code is the same as that of the previous chapter: a macro that does not produce any output. But this time we do have an effect on our existing code by not returning anything. Try adding the code in the following listing to your application main.rs and running cargo expand.
Listing 4.4 Running cargo expand with this main.rs
Section titled “Listing 4.4 Running cargo expand with this main.rs”use make_public_macro::public;
#[public]struct Example {}
fn main() {}The Example struct is now gone! Spooky.
Listing 4.5 Our struct pulling a disappearing act
Section titled “Listing 4.5 Our struct pulling a disappearing act”#![feature(prelude_import)]#[prelude_import]use std::prelude::rust_2021::*;#[macro_use]extern crate std;
use make_public_macro::public;
fn main() {}As we said earlier, Rust expects an attribute macro output to replace the input, which does make things slightly more complex than they were before.
4.3 First steps in public visibility
Section titled “4.3 First steps in public visibility”Back to the task at hand: we can now add properties to our struct to make things more concrete.
Listing 4.6 Our example struct
Section titled “Listing 4.6 Our example struct”#[public]struct Example { first: String, pub second: u32,}We would like for our macro to output this struct with the following changes: the struct should become public, first should become public, and second should stay public.
We can approach the problem in the same way as before. So we start with the easiest implementation, one that only works for this specific struct.
<!-- page: 071 -->
# 4.4 Getting and using fields
## Listing 4.7 A hardcoded implementation
rustextern crate core;
use quote::quote;use proc_macro::TokenStream;use syn::{parse_macro_input, DeriveInput};
#[proc_macro_attribute]pub fn public(_attr: TokenStream, item: TokenStream) -> TokenStream { let ast = parse_macro_input!(item as DeriveInput);
let public_version = quote! { pub struct Example { pub first: String, pub second: u32, } };
public_version.into()}That obviously works. Now, as a next step, we previously learned how we can retrieve the name of the input struct. By applying that knowledge here, we will be able to accept any kind of struct that has the same fields as our example.
Listing 4.8 Hardcoded properties with the struct name retrieved from the input
Section titled “Listing 4.8 Hardcoded properties with the struct name retrieved from the input”#[proc_macro_attribute]pub fn public(_attr: TokenStream, item: TokenStream) -> TokenStream { let ast = parse_macro_input!(item as DeriveInput); let name = ast.ident;
let public_version = quote! { pub struct #name { pub first: String, pub second: u32, } };
public_version.into()}Applying what we already know, we retrieve the name of our struct and pass it to quote. We are finally using our AST, and we have taken another small step in making our struct more generally usable. Nice. What we would like to do next is to retrieve and use the incoming fields. They come from the same place as the name: our AST.
4.4 Getting and using fields
Section titled “4.4 Getting and using fields”As noted before, the parameter item contains all relevant code, meaning the entire struct can be accessed via the ast variable. That variable is of type DeriveInput, which is a representation of the kind of input we might receive from a derive macro. And
<!-- page: 072 -->
62 CHAPTER 4 Making fields public with attribute macros
yes, we are writing an attribute macro. But the type works because these two share some important input targets: structs, enums, and unions. And while attribute macros can also target traits and functions, that’s not currently important to us. If you prefer a more fitting type, `syn::ItemStruct` should be a drop-in replacement, but it does have the downside that it is hidden behind the “full” feature flag. So we would need to change our `syn` import to use it.
What does `DeriveInput` contain? This is the source code (https://docs.rs/syn/latest/src/syn/derive.rs.html#4-14):
rustpub struct DeriveInput { pub attrs: Vec<Attribute>, pub vis: Visibility, pub ident: Ident, pub generics: Generics, pub data: Data,}DeriveInput is a struct to represent derive macro input.
It has the item’s attributes.
Its visibility modifier
The identifier
Any generics
Other information (content)
You know Rust, so you can guess the meaning of most of these properties:
attrscontains any attributes defined on the struct; for example,#[derive(Debug)].vishas the visibility of our struct (public, visible in crate, or just private, i.e., “inherited”).identhas the name (identifier) of our struct.genericscontains information if our struct is generic (Example<T>). But that’s not the case here.datais where we can find details about the data within our struct.
data sounds the most useful to us; what does data contain? Go down the syn rabbit hole, and you will find that Data is an enum with three options: Struct, Enum, and Union. That makes sense, since DeriveInput was created specifically for derive macros, which, unlike attribute macros, can only be used for these three targets:
pub enum Data { Struct(DataStruct), Enum(DataEnum), Union(DataUnion),}Data is an enum with three variants.
Struct is the variant we need. What does the DataStruct nested inside contain? Dig just a little deeper. You will see that it has a struct_token, which contains the struct keyword (not useful); semi_token, which is an optionally present semicolon (not interesting); and the fields of the struct (see figure 4.2):
pub struct DataStruct { pub struct_token: Token![struct],
<!-- page: 073 -->
pub fields: Fields,pub semi_token: Option<Token![;]>,}

> [!visual-conversion] Tree diagram showing DeriveInput branching to Attributes, Visibility, Identifier, Generics, …> Cropped from the scan (PDF page 073, printed p. ?): Tree diagram showing DeriveInput branching to Attributes, Visibility, Identifier, Generics, Data, then Data to Struct, then Struct to Token, Fields, Optional semicolon.
Figure 4.2 Finding the roots of the world tree: from DeriveInput to Fields for our Example struct
Now that we know where to find our fields, let's extract them from the data. For now, we just want this working for structs, so we will ignore enums and unions during matching. We will also use matching to drill down to the named fields—fields that have both a name and a type, first: String, for example. The “..” in the following code helps us ignore properties inside DataStruct and FieldsNamed that do not interest us, including the unnamed fields, which we will discuss later. If you forget to add those two dots, you will get back an error similar to Struct pattern does not mention fields someField and anotherField. That is Rust telling you that a couple of fields are missing from your match:
let fields = match ast.data { Struct( DataStruct { fields: Named(
<!-- page: 074 -->
# CHAPTER 4 Making fields public with attribute macros
rustFieldsNamed { ref named, ..}, ..}) => named,=> unimplemented! { "only works for structs with named fields"},};Matching makes it easy to only extract named fields from our input.
When we do not receive a struct with named fields, we panic.
Now we have named fields with this type: Punctuated<Field, Token![,]>. Punctuated can be just about anything that has punctuation. In this case, the punctuation generics show that Fields are separated by a comma Token. And fields in a struct are indeed separated by a comma. Useful to know is that Punctuated implements IntoIterator, so we can iterate over it. Dig down, and you will see that we will be iterating over the first generic, Field, which makes sense. A comma is not very interesting to iterate over.
We have all the struct fields, and we can loop over them. Next question: what is in Field? Again, we turn to the source code and see that it contains lots of familiar things: attrs, vis, and ident, as well as a property called ty, which contains the field’s type (see figure 4.3).
Fields{ first: String, pub second u32 } ↓Named ↓┌─────────────┐ ┌──────────────────────────────┐│ Brace token │ │ Punctuated ││ { │ │ first: String, ││ │ │ pub second ││ │ │ u32 │└─────────────┘ └──────────────────────────────┘ ↓ ┌─────────┬─────────┬─────────┬─────────┬─────────┐ ↓ ↓ ↓ ↓ ↓┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────┐ ┌─────────┐│ Attributes │ │ Visibility │ │ Identifier │ │ Colon │ │ Type ││ None │ │ pub │ │ second │ │ : │ │ u32 │└─────────────┘ └─────────────┘ └─────────────┘ └─────────┘ └─────────┘Figure 4.3
From Fields to Punctuated for the second field of Example (simplified view)

[!visual-conversion] Flowchart showing parsing of struct fields from Fields to Punctuated, … Cropped from the scan (PDF page 074, printed p. ?): Flowchart showing parsing of struct fields from Fields to Punctuated, with branches for Attributes, Visibility, Identifier, Colon, and Type.
4.4 Getting and using fields
Section titled “4.4 Getting and using fields”Now what? What is our goal? Well, we want to refill the struct with now prefaced with a public visibility indicator. For our Example, the pub first: String using quote. Once that is done, we want to So all we need to do is retrieve the name and type. Any other information about visibility, since we always set pub—is irrelevant.
NOTE We are ignoring the other attributes that the struct might mean; other macros might not work as expected for our struct. We’ll see how we can fix that later.
You can see the implementation of this idea in the following code. We iterate over the fields and use map to extract the identifier and type. With quote, we generate a TokenStream with the public prefix, the name, and the type of the given field:
let builder_fields = fields.iter().map(|f| { let name = &f.ident; let ty = &f.ty; quote! { pub #name: #ty }});Now that we have an individual field within map, we can retrieve the name.
With quote, we give back a TokenStream containing the input plus a pub prefix for every field.
By now we know that anything that is not a literal should be prefixed by a hashtag in our output. That way, quote knows it needs to replace the given value with the value inside the identically named variable. Note that quote cannot access a variable’s properties, so doing something like quote! { pub #f.ident: #f.ty } will only result in confusing errors, as #f will be “resolved” and a literal value .ident will be added to the output. Also interesting is that we don’t need to collect the output of the map—because quote knows how to handle maps that produce TokenStreams. If you want to simplify a function signature, you can still call collect to get a Vec<TokenStream> output, though. We will see examples of that later.
Now all we have to do is add the map of streams to the struct that we are returning. And we need to tell Rust that these streams will be separated by a comma, or Rust will complain about syntax. quote offers a convenience for this, which looks quite similar to how you would handle multiple elements in a declarative macro: #(#name-of-your-variable,)* (i.e., take this variable, which contains zero or more values, and after every retrieved element, add a comma). Do note that you need two hashtags for repetition in quote. Forget the outer one, and you will be greeted by this error: “the trait ToTokens is not implemented for Map…”
Listing 4.9 Our public fields macro
Section titled “Listing 4.9 Our public fields macro”use quote::quote;use proc_macro::TokenStream;use syn::{parse_macro_input, DeriveInput, DataStruct, FieldsNamed};use syn::Data::Struct;use syn::Fields::Named;
#[proc_macro_attribute]pub fn public(_attr: TokenStream, item: TokenStream) -> TokenStream {
<!-- page: 076 -->
# CHAPTER 4 Making fields public with attribute macros
rustlet ast = parse_macro_input!(item as DeriveInput);let name = ast.ident;
let fields = match ast.data { Struct( DataStruct { fields: Named( FieldsNamed { ref named, .. }, .. ) } ) => named, _ => unimplemented!( "only works for structs with named fields" ),};
let builder_fields = fields.iter().map(|f| { let name = &f.ident; let ty = &f.ty; quote! { pub #name: #ty }});
let public_version = quote! { pub struct #name { #(#builder_fields,)* }};
public_version.into()If we have a struct with named fields, we retrieve the fields.
From these fields, we get the name and type, and return a TokenStream containing pub, the name, and the type for each element.
In our output, we tell quote that builder_fields is a list of elements that should be added to the struct, separated by commas.
As you can see, quote is as versatile as you need it to be. We can add a single, simple TokenStream with #name, or we can add multiple elements in one go. In more complex macros, the output is often composed of a whole range of variables brought together in one final output. And those variables might also be the result of a composition of quote of undetermined complexity. In any case, thanks to the previous code, simple structs like Example now have all their fields set to public. Privacy is officially dead!
4.5 Possible extensions
Section titled “4.5 Possible extensions”There are lots of ways we could now expand our macro to make it more useful. For example, instead of panicking when we receive an enum, we could write code to handle it. Do remember that the variants of an enum are automatically public when the enum itself is public, meaning it is probably easier to just add pub to an enum rather than using a custom macro.
We have also been ignoring unnamed fields, which do appear in structs like, for example, struct Example(u32, String);. If we wrote our struct like this, we would have reached our unimplemented match. So how would we handle these structures? The first step would be to dig out the unnamed fields, which would be very similar to how we retrieved the named fields. We could do that in an additional match arm.
Once we have the fields, we can output them in the correct style—for example, pub struct Example(pub u32, pub String);. Finally, you would have to differentiate between a named and unnamed struct and decide on the kind of output to return. Luckily, this is a simple binary choice: a struct is either named or unnamed.
Somewhat surprisingly, our code will correctly handle empty structs but only when they are followed by brackets or curly braces. A struct without them like struct Empty; would not have anything in the way of fields at all, so it would end up in our unimplemented arm.
There are a few more potential problems (besides not handling unions). For example, our macro won’t make fields of nested structs public. As luck would have it, just adding #[public] to the nested items is an easy fix.
A much bigger problem is that when we have other macros annotating our struct, they are deleted by ours. Try adding a #[derive(Debug)] below our annotation and running cargo expand. Do you see how the additional annotation vanishes into thin air? We are simply superb at making things disappear. As macros are executed in order, from top to bottom, the simple workaround is adding the derive above our #[public]. Now everything will work as expected. Except—please do not do this. Instead, do things the proper way and retrieve and reattach all the available attributes.
Moreover, while we are keeping the generics of our named fields, we are recreating the struct’s signature, meaning that its generics disappear. Fixing that would require using and re-adding the generics field from DeriveInput. You can try out several of these extensions in the exercises later.
4.6 More than one way to parse a stream
Section titled “4.6 More than one way to parse a stream”The previously described approach shows one way to create procedural macros. It uses syn for parsing your tokens, quote for creating new ones, and matching plus functions for everything in between. However, if gluing things together with functions is not your thing, there are alternatives, like a more “struct-focused” approach. As an example, we will revisit our public macro and show some options.
4.6.1 Delegating tasks to a custom struct
Section titled “4.6.1 Delegating tasks to a custom struct”First, we could delegate getting and outputting the fields to a StructField. Start by adding a dependency to proc-macro2, which we will need shortly.
Listing 4.10 Two familiar dependencies in our library toml file and a new one
[dependencies]quote = "1.0.33"syn = "2.0.39"proc-macro2 = "1.0.69"Now take a look at the new implementation. There are two big changes. Instead of using the primitives from syn directly, we have our struct gather/organize all required information (i.e., name and type). By convention, a method called new should be used
68 CHAPTER 4 Making fields public with attribute macros
for creating a struct, so we create one and call it when iterating over our fields. map(StructField::new) is a convenient shorthand—also known as point-free style—for map(|f| StructField::new(f)).
Listing 4.11 An implementation that uses structs to do most of the gluing
Section titled “Listing 4.11 An implementation that uses structs to do most of the gluing”use proc_macro::TokenStream;use quote::{quote, ToTokens};// previous imports
struct StructField { name: Ident, ty: Type,}
impl StructField { fn new(field: &Field) -> Self { Self { name: field.ident.as_ref().unwrap().clone(), ty: field.ty.clone(), } }}
impl ToTokens for StructField { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let n = &self.name; let t = &self.ty; quote!(pub #n: #t).to_tokens(tokens) }}
#[proc_macro_attribute]pub fn public(_attr: TokenStream, item: TokenStream) -> TokenStream { // unchanged: get fields let builder_fields = fields.iter().map(StructField::new); // unchanged: quote for output}This struct contains the data we need for every field of the struct.
Our new contains code for retrieving name and type from a field.
ToTokens outputs a token stream with the field set to public. Because it is part of the quote library, it uses
proc_macro2::TokenStream.
During iteration, we map every Field to StructField by calling new.
builder_fields contains our custom structs. How can quote transform this into a TokenStream? It can’t, because it has no idea how to change a random struct to a bunch of tokens. One solution would be to write a second method that turns the struct into a TokenStream and call it during iteration. But there’s a trait for that! ToTokens, from quote, turns the implementor into TokenStream, so we will use that trait instead.
The code inside to_tokens is similar to what we were doing before in our mapping, except to_tokens requires us to give all our new tokens to a mutable parameter of type proc_macro2::TokenStream, which, as we briefly mentioned, is a community-built token stream that wraps around the built-in stream and adds additional features. It is used internally by quote, which is why we always have to add into to the result of
4.6 More than one way to parse a stream
Section titled “4.6 More than one way to parse a stream”quote when returning our tokens. Now that we use it explicitly in the signature of an impl block, we have to add it to our project’s dependencies. What also would have worked is using quote::__private::TokenStream, but let’s go with the cleaner approach. And with that, our builder_fields is automatically turned into a TokenStream, and our final quote code does not need to change.
This is more code—and complexity—than we had before, but there are positives as well. There is a separation of concerns: we have made a struct responsible for the retrieval and outputting of a field. This can enable reuse and could prove to be more readable and structured. In this basic example, it is probably overengineering, but some structuring of data into structs might prove useful in a bigger procedural macro.
4.6.2 Implementing the Parse trait
Section titled “4.6.2 Implementing the Parse trait”We could go one step further and incorporate an additional built-in from syn, the Parse trait, which is used for changing a TokenStream into a struct or enum. In the next code listing, we add an implementation of this trait and its method parse, which receives syn::parse::ParseStream as input. Just think of that as a sort of TokenStream.
Listing 4.12 Parsing instead of using new
Section titled “Listing 4.12 Parsing instead of using new”// imports
struct StructField { name: Ident, ty: Ident,}
// ToTokens implementation remains unchanged
impl Parse for StructField { fn parse(input: ParseStream) -> Result<Self, syn::Error> { let _vis: Result<Visibility, _> = input.parse(); let list = Punctuated::<Ident, Colon>::parse_terminated(input) .unwrap(); Ok(StructField { name: list.first().unwrap().clone(), ty: list.last().unwrap().clone(), }) }}
#[proc_macro_attribute]pub fn public(_attr: TokenStream, item: TokenStream) -> TokenStream { // unchanged let builder_fields = fields.iter() .map(|f| { syn::parse2::<StructField>(f.to_token_stream()) .unwrap() }); // unchanged}The new method has been made redundant by parse.
Instead of Type, ty is now an Ident, because that is what we are receiving from our Parse.
We try to parse the visibility into a variable of type Result<Visibility, _> to get rid of it, moving the pointer to the next token.
A field without visibility is a kind of Punctuated, so we call parse_terminated to parse the rest of the field.
The first element should be the name and the type should be last. Because we parsed the field as identifiers separated by a colon, ty is now Ident.
Iterates over the fields and uses parse2. The Result might be any number of things, so we have to say that we want a StructField.
<!-- page: 080 -->
70 CHAPTER 4 Making fields public with attribute macros
We expect to receive a `ParseStream` representation of a single field in our parse implementation. That means the first thing we will receive is a token indicating the field’s visibility. We are not interested in that value, but handling it now will make the rest of our parsing easier. So we call `parse` on the input and tell it that we want to bind this `Visibility` to a variable `_vis`. `parse` might fail, so `Visibility` is wrapped in a `Result`, which we won’t even unwrap because this was just to get rid of the value. Now our `ParseStream` no longer contains the field’s visibility modifier, and we can continue (see figure 4.4).
**NOTE** Perhaps you thought visibility was an optional part of the field definition, which is certainly what I used to think. But look back at the AST diagrams and source code: `ParseStream` always has a `Visibility`. By default, it’s just `Inherited`, which—according to the documentation—“usually means private.”
In our next step, `Punctuated::<Ident, Colon>` tells Rust that we expect something that consists of identifiers separated by a colon (`:`). That, after all, is what a field declaration looks like without its visibility: `field_name: FieldType`. And, as our example shows, the first element should be the name and the last element the type. So we can add those to our struct. Note that because of `Punctuated`, `ty` is now parsed as an `Ident`, which is perfectly valid.
If visibility was still part of our stream at this stage, Rust would complain with `Error("expected identifier")`, because it expected a list of identifiers and got a `Visibility` type. But even though we avoid that error, this is still not a production-ready macro. We are expecting simple, unannotated, named fields. Nothing else. And that is only part of the range of content that a struct might have, albeit an important part. But this will do for now.
All that remains is to pass in the field tokens for parsing. We can use `syn::parse2` to accomplish that task. It accepts a `TokenStream` and can return any type that implements `Parse`. But since a lot of things implement `Parse`, we have to tell the function what return type we would like. In our case, that is a `StructField`. `parse2::<StructField>` is probably the most elegant way to relay this info. One clumsy alternative is `map(|f| { let field: StructField = parse2(f.to_token_stream()).unwrap(); field })`.

> [!visual-conversion] Flowchart showing parsing steps for 'pub second: u32' with boxes …> Cropped from the scan (PDF page 080, printed p. ?): Flowchart showing parsing steps for 'pub second: u32' with boxes and arrows.Figure 4.4 Parsing the second field
<!-- page: 081 -->
4.6 More than one way to parse a stream
71
**NOTE** Why `parse2`? `parse` also exists and is very similar, but it accepts an ordinary `TokenStream`, whereas `parse2` takes the `proc_macro2` variant (hence the names). By the way, `parse_macro_input!` is just syntactic sugar for `parse`.
`.map(|f| parse2::<StructField>(f.to_token_stream()))` is not great, though. We have some nicely parsed data from `syn`, and we are turning it back into a `TokenStream`. You could avoid this ugliness by, for example, parsing all the fields (or the entire input) into custom structs instead of parsing every individual field.
### 4.6.3 Going low, low, low with cursor
As a final example, we could also have chosen `cursor` for low-level control over our parsing:
rustimpl Parse for StructField { fn parse(input: ParseStream) -> Result<Self, syn::Error> { let first = input.cursor().ident().unwrap();
let res = if first.0.to_string().contains("pub") { let second = first.1.ident().unwrap(); let third = second.1.punct().unwrap().1.ident().unwrap(); Ok(StructField { name: second.0, ty: third.0, }) } else { let second = first.1.punct().unwrap().1.ident().unwrap(); Ok(StructField { name: first.0, ty: second.0, }) };
let _: Result<proc_macro2::TokenStream, _> = input.parse(); res }}We call cursor on our input parameter and tell it the first thing it will encounter is an identifier. cursor does not differentiate between names, types, visibility, etc., so this will capture either the visibility or the name of the field. If the name contains the string “pub,” we probably have the visibility, which means the next identifier is the name, which we get by calling first.1.ident() and unwrapping the result. Our variable second should have the name and the rest of our data. Our type is behind a colon, so we expect to find punctuation (punct()) followed by the identifier. Now that we have both name and type, we give them to StructField. The other conditional branch is similar. When we do not have an explicit visibility modifier, we already have the name and only need to retrieve the type.
The final let _: Result<proc_macro2::TokenStream, _> = input.parse(); is icky, though. cursor is giving us immutable access to the existing stream. This is
72 CHAPTER 4 Making fields public with attribute macros
great—except that after calling your parsing method, parse2 does a check to make sure there’s nothing left unhandled inside your stream. And, in our case, we did not—could not, even—change anything, so we will get a confusing Error("unexpected token") error. So we just call parse and make it give back a Result, which we ignore. This is a bit similar to ignoring the visibility in our previous example (listing 4.12).
What style should you prefer? It depends. Functions and matching are relatively easy and seem ideal for smaller macros or writing a proof of concept. Structs can give additional structure to your solution and offer a nice way to delegate responsibility: every struct does a bit of the parsing and outputting. They are also very useful when you are passing things into macros that do not count as proper Rust code, like DSLs. Default parsers are obviously not well equipped to deal with seemingly random input that only has meaning within your particular domain. So instead, you write your own structs and capture relevant information. cursor, meanwhile, gives low-level control and a lot of power, but it is verbose and less easy to use. It should probably not be your first choice.
In this book, many chapters focus on functions as the glue for building macros, because this style is convenient for brief examples. But because structs are often used “in the wild,” we will also have examples using that style.
4.7 Even more ways to develop and debug
Section titled “4.7 Even more ways to develop and debug”In previous chapters, we talked about development and debugging tools like cargo expand. In this chapter, we also did a lot of digging through source code, which helped us understand more of what data is available when syn has parsed your input. Another useful tool worth mentioning is—please don’t slam this book shut—printing to the console, because seeing the structure of your AST via types is useful, but printing it tells you what is actually in there, which is very useful when you are uncertain about what you are receiving.
Two things to note: first, to debug-print DeriveInput and other types from syn, you will need to activate the extra-traits feature of syn:
syn = { version = "2.0.39", features=["extra-traits"] }Second, there is a good chance that standard output will get captured and won’t show up in your console. The easy workaround is to use error printing, which should always find its way back to you:
let ast = parse_macro_input!(item as DeriveInput);eprintln!("{}", &ast);Next, you can see an abbreviated output from this command when we add the eprintln command to our macro. There is a lot of information in there, and learning to read it takes some time. But you should recognize many types that we discussed in this chapter—Ident, Struct, DataStruct, FieldsNamed, etc.:
DeriveInput { vis: Inherited,
<!-- page: 083 -->
ident: Ident { ident: "Example", span: #0 bytes(67..74),},...data: Struct( DataStruct { struct_token: Struct, fields: Named( FieldsNamed { named: [ Field { attrs: [], vis: Inherited, ident: Some( Ident { ident: "first", span: #0 bytes(81..86), }, ), colon_token: Some( Colon, ), ... }, ], }, ), },),
## 4.8 From the real world
Lots of libraries use attribute macros to do cool things. For example, Tokio, a widely used asynchronous runtime for Rust, uses its `#[tokio::main]` macro to transform your main into something that can handle asynchronous calls. This is the source code entry point:
rust#[proc_macro_attribute]pub fn main(args: TokenStream, item: TokenStream) -> TokenStream { entry::main(args, item, true)}Wait, just main? Then why do all code examples show #[tokio::main]? Well, probably to make it clear to the reader that this is Tokio’s main macro. But since the bit before :: only signifies from which crate we are getting the macro, use tokio::main; plus #[main] is also perfectly valid (the more you know …).
There are also lots of examples of libraries using the Parse and ToTokens traits. Here are some examples from Rocket, a web framework that uses a lot of macros for generating endpoints, among other things. Want to respond to a GET call? Just add the custom #[get("/add/endpoint")] annotation:
impl Parse for Invocation { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { Ok(Invocation { ty_stream_ty: (input.parse()?, input.parse::<syn::Token![,]>()?).0,
<!-- page: 084 -->
# CHAPTER 4 Making fields public with attribute macros
ruststream_mac: (input.parse()?, input.parse::<syn::Token![,]>()?).0,stream_trait: (input.parse()?, input.parse::<syn::Token![,]>()?).0,input: input.parse()?,})}
impl ToTokens for UriExpr { fn to_tokens(&self, t: &mut TokenStream) { match self { UriExpr::Uri(uri) => uri.to_tokens(t), UriExpr::Expr(e) => e.to_tokens(t), } }}As you can see, the Parse implementation has better error handling than our code (it uses ? instead of unwrapping). Good error handling is advisable for a production-grade macro, so we will get back to that in a later chapter. Even so, occasionally you see panics appearing in the wild. Yew, a web framework that has a cool macro for writing and verifying HTML, has unimplemented! (“only structs are supported”) appearing in two places.
As a final example, take a look at no-panic (https://github.com/dtolnay/no-panic), a macro that makes your compiler prove that a given function never panics—which is pretty amazing. How could that possibly work? Consider the following code:
struct Dropper {}impl Drop for Dropper { fn drop(&mut self) { println!("Dropping!") }}
fn some_fun() { let d = Dropper {}; panic!("panic"); core::mem::forget(d);}
fn main() { some_fun();}Implements Drop for our Dropper struct
After creating a Dropper instance, panic!
core::mem::forget(d) causes Rust to forget about d. So if it runs, the drop will not be executed.
We have a struct called Dropper that implements Drop, the trait that you can use in Rust when custom cleanup of a resource is required. When you run the code, some_fun will trigger a panic, followed by an unwinding of the stack. At that point, Drop from Dropper is invoked to clean up our struct.
But if we comment out the panic, we reach forget on the next line. That will make Rust forget about the Dropper struct and its Drop implementation. In that case, Drop will not be called. (Remember, we stop executing when a panic is encountered. So, in the first case, we never reach forget. But—by default at least—Rust does do a cleanup
4.8 From the real world
of resources on panic.) This has an interesting implication. If the compiler can “prove” that there is no chance that some_fun will panic, the logical conclusion is that Drop will never be called because of the forget call! As a consequence, Rust can safely optimize away the Drop implementation, since it is never used.
This library and others similar to it do a neat trick: they create a struct, implement Drop and call a nonexisting C function within the implementation, and add a fo call. That means we will get a linking error if the code is not optimized away. And code is not removed when a panic is possible before the forget call, because, in that case, Rust might have to call Drop after all. Neat, huh?
struct __NoPanic;extern "C" { #[link_name = "does_not_exist"] fn trigger() -> !;}impl Drop for __NoPanic { fn drop(&mut self) { unsafe { trigger(); } }}The code from the library itself is fairly brief (some 150 lines of code). The following is a selection with some annotations. Among other things, I removed some error handling because we haven’t discussed that yet. And for now, all you need to know about parse_quote is that it is similar to the regular quote macro:
#[proc_macro_attribute]pub fn no_panic(args: TokenStream, input: TokenStream) -> TokenStream { let expanded = match parse(args, input.clone()) { Ok(function) => expand_no_panic(function), // error handling }; TokenStream::from(expanded)}The macro entry point. Calls a custom parse function and forwards an Ok result to
expand_no_panic.
fn parse(args: TokenStream2, input: TokenStream2) -> Result<ItemFn> { let function: ItemFn = syn::parse2(input)?; let _: Nothing = syn::parse2::<Nothing>(args)?; Ok(function)}
ItemFnis a syn built-in for parsing functions, similar to howDeriveInputhelps us with enums and structs.
fn expand_no_panic(mut function: ItemFn) -> TokenStream2 { // ... let stmts = function.block.stmts; let message = format!( "\n\nERROR[no-panic]: detected panic in function `{}`\n", function.sig.ident, ); function.block = Box::new(parse_quote!({ struct __NoPanic;This function is doing the heavy lifting. In the
ItemFntype,function.blockhas the body of the function. The__NoPanicstuff is added to that body.
CHAPTER 4 Making fields public with attribute macros
Section titled “CHAPTER 4 Making fields public with attribute macros”extern "C" { #[link_name = #message] fn trigger() -> !;}
impl core::ops::Drop for __NoPanic { // ...}
let __guard = __NoPanic;let __result = (move || #ret { #move_self #( let #arg_pat = #arg_val; )* #(#stmts)*})();core::mem::forget(__guard);__result));
quote!(#function)This function is doing the heavy lifting. In the ItemFn type, function.block has the body of the function. The __NoPanic stuff is added to that body.
You should recognize a lot of familiar elements in this code. We start with the declaration of our macro using the attribute macro. Because the function name determines the name of the macro, we know that we need to write #[no_panic] when using this macro. We receive two token streams as parameters and use parse2 to parse the input into ItemFn, a syn built-in for parsing functions that we will study in more detail in an upcoming chapter. The args are not used and so are parsed into an ignored variable of type Nothing. If there is anything inside this TokenStream, parsing into Nothing will fail (hence the name). By the way, the double specification of types (Nothing and syn::parse2::<Nothing>) is redundant. Either will do.
expand_no_panic contains the bulk of what we discussed previously. It adds the fake linked C function and tries to forget it. As a bonus, the link_name of the fake C function is used as a message to report the detected panic when Drop is not optimized away. The implementation, contained within function.block.stmts (stmts stands for “statements”), is added to our new implementation, which overwrites the existing one. With our new code in place, the final expression (quote!(#function)) returns the partially overwritten function as a TokenStream.
Exercises
Section titled “Exercises”See the appendix for solutions.
- Fill in the question marks (???) and make the following macro compile:
#[???]pub fn ???(_attr: TokenStream, _item: TokenStream) -> TokenStream { let public_version = quote! {}; public_version.into()}
<!-- page: 087 -->
# Summary
The following code fragment shows a usage example:
rust#[delete]struct EmptyStruct {}-
Handle structs with unnamed fields. If you use matching, your new match arm will probably look a bit like this:
Struct(DataStruct { fields: Unnamed (FieldsUnnamed { ref unnamed, .. }), .. }). Note that you will need to decide whether to output a “normal” struct or an unnamed one. -
Make our macro handle enums. Two things to keep in mind: First, you do not need to add
pubto the fields (only to the enum), but you do have to retrieve and re-add them (they are called variants underEnum,DataEnum). Second, your code will now also have to decide whether it has to return an enum or a struct. -
Keep the existing attributes of the struct instead of letting them disappear. This requires little more than getting the
attrs(attributes) of ouritemand adding them above the struct. You might have to play around with thequotesyntax a bit. Just remember that—unlike before—we do not need a comma to mark the end of an attribute. -
Combine all of these exercises into a single solution.
-
Using
Punctuated::<Ident, Colon>is one way to parse the field, but in the case of our public fields macro, there is an even simpler solution. Just put everything in variables, as we did withvisibility, and pass the useful things toStructField. Change ourParseimplementation to use this simpler parsing.
Summary
Section titled “Summary”- Like derive macros, attribute macros can be used on enums, structs, and unions. Additionally, they can be added to traits and functions.
- Unlike derive macros, attribute macros overwrite their input, making it possible to change existing code.
- Attribute macros get their name from defining a new custom attribute.
- We can use the
synparsing result (our AST) to retrieve all kinds of information, like the fields of a struct. quoteallows us to combine multiple token streams into a single output.- We can use matching and functions to glue together our parsing and outputting.
- For more structure and larger macros, you might consider creating custom structs and delegating the parsing and outputting to them.