Skip to content
ImagineWorld

Builder with attributes

node_idnode-book_write-powerful-rust-macros_chapter-09-builder-with-attributes
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleBuilder with attributes
governed_byCORPUS
constitutional_citationCONSTITUTION
figure_reviewassets/wpm-fig-9-01-class-hierarchy-diagram-showing-attribute-branching-to.png, UNRESOLVED-marker-p183, assets/wpm-fig-9-02-simplified-view-of-the-meta-property-for.png, assets/wpm-fig-9-03-flowchart-showing-examplestruct-builder-examplestructbuilder-firstprop-build.png, assets/wpm-fig-9-07-diagram-showing-attribute-meta-metalist-with-annotations.png
local graph
  • Working with field-level custom attributes to rename methods
  • Using root-level custom attributes to decide on error handling
  • Making a builder easier to use with type state
  • Exploring how derive and attribute macros differ
  • Parsing (document) attributes inside function-like macros

Every macro we created thus far had its behavior set in stone. Nothing was customizable. But sometimes you want overridable behavior, because that greatly increases flexibility, or you may need it to meet some requirements. In this chapter, we focus on customization via attributes, which are available for both derive and attribute macros. We will see how we can add information to a macro attribute and other parts of your code, like the individual properties of a struct.

As always, we need a project to illustrate these possibilities. Instead of introducing something new, let’s save some time by expanding on the builder example we created previously. How can we make it more versatile? Perhaps we can start by allowing users to rename the setter methods that will appear on our builder. This is

quite typical functionality (Serde, for example, allows renames), because sometimes there is a mismatch between what your data looks like and what you need it to be to conform to standards or requirements. Even if the default works for most cases, it’s something you may want to make possible.

The setup for this chapter is easy since we already have a macro ready to go. If you’re following along, disabling the existing tests might be a good idea, as we won’t make an effort to keep those running. We will, however, still write test scenarios for our new code, which we will add to main.rs in the usage folder.

What we need is a test that shows we can rename a property. This should also change the relevant setter method name. These two assertions come together in the test in the following listing.

Listing 8.1 Verifying the desired behavior with a test

Section titled “Listing 8.1 Verifying the desired behavior with a test”
#[test]
fn should_generate_builder_for_struct_with_one_renamed_property() {
#[derive(Builder)]
struct Gleipnir {
#[rename("tops_of")]
roots_of: String,
}
let gleipnir = Gleipnir::builder()
.tops_of("mountains".to_string())
.build();
assert_eq!(
gleipnir.roots_of,
"mountains".to_string()
);
}

This attribute is new and specifies a custom name.

Because of this, the builder method is now called tops_of instead of roots_of.

The actual property remains as is.

The one new thing in this test is the #[rename("tops_of")] attribute, which we are using inside a struct annotated with #[derive(Builder)]. Try to run this test. You will get back an error: cannot find attribute rename in this scope. This is because we haven’t told Rust that our macro has attributes. Modify the lib.rs file in builder-macro.

#[proc_macro_derive(Builder, attributes(rename))]
pub fn builder(item: TokenStream) -> TokenStream {
create_builder(item.into()).into()
}

attributes(rename) tells the derive macro that it has an attribute called “rename.”

8.1 A rename attribute

A derive macro’s attributes are called “derive macro helper attributes.” They are inert, meaning they will not remove themselves during attribute processing. You can see this for yourself by running cargo expand on a derive macro with attributes—the output still contains the attributes. This makes sense, as derive macros cannot change their input. The only purpose of these attributes is to be fed into a derive macro that can use them to change behavior and output.

All attributes, including our rename, should be specified in the macro declaration under attributes (as seen earlier). rename is now a known attribute. But it is still without implementation, causing the test to fail with no method named tops_of found.... We are ready to start fixing that.

8.1.2 Implementing the attribute’s behavior

Section titled “8.1.2 Implementing the attribute’s behavior”

Our game plan is as follows:

  1. Loop over our fields as before.
  2. Check whether we have a rename attribute.
  3. Change the method name if we do.
  4. Fallback to our default if we don’t.

Before we continue, a quick refresher: the following are all the properties of syn::Field. You have already learned to work with vis, ident, and ty. colon_token simply indicates whether there is a : in the field definition (in example: String, that Option will be Some). mutability is a new field in syn version 2 and is—at the time of writing—always None. That means attrs, the attributes placed above the field, is the only relevant property we haven’t used yet. And now we will:

pub struct Field {
pub vis: Visibility,
pub ident: Option<Ident>,
pub ty: Type,
pub colon_token: Option<Token![:]>,
pub mutability: FieldMutability,
pub attrs: Vec<Attribute>,
}

Since we want to modify the generation of methods, expanding builder_methods makes sense. The relevant code is in the following listing.

pub fn builder_methods(fields: &Punctuated<Field, Comma>)
-> impl Iterator<Item = TokenStream2> + '_ {
fields.iter().map(|f| {
let (field_name, field_type) = get_name_and_type(f);
quote! {
pub fn #field_name(&mut self, input: #field_type) -> &mut Self {
self.#field_name = Some(input);
<!-- page: 178 -->
# CHAPTER 8 Builder with attributes
rust
self
}
})
}

We need to make quite a few changes to use attributes, but the good news is that all the changes are scoped to the fields.rs file. lib.rs will remain untouched. We will start simple and write a helper that uses find to look within the field’s attributes for a name that matches our string.

Listing 8.4 Helper method in fields.rs to find a field attribute with a given name

Section titled “Listing 8.4 Helper method in fields.rs to find a field attribute with a given name”
fn extract_attribute_from_field<'a>(f: &'a Field, name: &'a str)
-> Option<&'a syn::Attribute> {
f.attrs.iter().find(|&attr| attr.path().is_ident(name))
}

The path method gives back the attribute’s path, which is the part right after the #[ bit (i.e., “rename”). Because this is an identifier, we should use its is_ident to compare with our string. Alternatively, we could have done a bit more work and compared path segments: attr.path().segments.len() == 1 && attr.path().segments[0].ident == *name. This works because there is a generic implementation of equality for Ident, PartialEq<T>, for anything where T: AsRef<str>. find will return the attribute wrapped in Some, defaulting to None if nothing was found.

Now on to the meat of our code in builder_methods. We are still iterating over the fields and retrieving name and type, except we now have additional logic for retrieving the attribute, analyzing it, and deciding on output depending on the result of that analysis.

Listing 8.5 New builder_methods code in fields.rs

Section titled “Listing 8.5 New builder_methods code in fields.rs”
// earlier imports
use syn::{Meta, LitStr};
pub fn builder_methods(fields: &Punctuated<Field, Comma>)
-> Vec<TokenStream> {
fields.iter()
.map(|f| {
let (field_name, field_type) = get_name_and_type(f);
let attr = extract_attribute_from_field(f, "rename") // Calls the helper
.map(|a| &a.meta)
.map(|m| {
match m {
Meta::List(nested) => {
let a: LitStr = nested
.parse_args()
.unwrap();

← Calls the helper

Ident::new(&a.value(), a.span()) } Meta::Path() => { panic!( “expected brackets with name of prop” ) }, Meta::NameValue() => { panic!( “did not expect name + value” ) } };

if let Some(attr) = attr { quote! { pub fn #attr(mut self, input: #field_type) -> Self { self.#field_name = Some(input); self } } } else { quote! { pub fn #field_name(mut self, input: #field_type) -> Self { self.#field_name = Some(input); self } } } }).collect()

We use our helper to retrieve the attribute if it exists. But that is not enough. We also need to do some additional mapping to retrieve what we are really interested in: the desired method name (see figure 8.1). Most of an attribute’s interesting information is located inside meta, an enum with three variants: List, Path, and NamedValue:

  • NamedValue is when you put keys with values in the brackets behind your attribute (e.g., #[rename(name=tops_of)]).
  • Path is when you have (a path of) attribute information without brackets.
  • List is for a list of values between brackets: #[rename(“first”,“second”)].

In our case, the last one, a list of exactly one element, is correct. We will keep things simple by panicking when we receive the wrong attribute format. But I would be amiss if I didn’t point out that meta has a couple of useful methods for this very situation. require_list will return the nested MetaList if it is present or an Err if we received a different enum variant. And there are similar methods for the other two: require_path_only and require_name_value. So require_list is a great alternative for a simple panic.

mermaid graph TD A[Attribute\npound_token: Token[#]\nstyle: AttrStyle\nbracket_token: token::Bracket\nmeta: Meta] —> B[Path] A —> C[List\npath: Path\ndelimiter: MacroDelimiter\ntokens: TokenStream] A —> D[NameValue] C —> E[LitStr\n(Type that matches TokenStream content)] C —>|parse_args on ‘tokens’| E

Figure 8.1 Diving into the Attribute type
List contains tokens, which is a TokenStream with the information we want. The easiest way to get a useful type out of that stream is to use the `parse_args` method, specifying the expected return type. For us, `LitStr` is a convenient return as we literally—feeble pun intended—expect a string!
Now all that is left is to transform this literal into an identifier we can use to construct the method name. For that we use the `value` helper method and the span of the existing literal, passing them to the new method. It may seem like retrieving the token, changing it into a string, and taking a reference (i.e., `&nested_lit.token().to_string()`) would also work. Unfortunately, that code will error: `"\"tops_of\""` is not a valid identifier. Those escapes around your literal are not what you want for your identifier, and `value` gets rid of them for you.
Once we are done changing the attribute into a custom method name, we use `if let` to get the value from the `Option` if it is present. In every other case, we default to our previous implementation, where the field and method names are the same.
## 8.1.3 Parsing variations
As always, there are many possible variations for this macro and its implementation. For example, maybe you think the quotation marks around `"tops_of"` are a needless distraction when invoking the macro. Maybe you prefer it without quotes, like
![](assets/wpm-fig-9-01-class-hierarchy-diagram-showing-attribute-branching-to.png)
> [!visual-conversion] Class hierarchy diagram showing Attribute branching to Path, List, and …
> Cropped from the scan (PDF page 180, printed p. ?): Class hierarchy diagram showing Attribute branching to Path, List, and NameValue, with List further branching to LitStr.
<!-- page: 181 -->
# 8.1 A rename attribute
`#[rename(tops_of)]`. In that case, we don't have a `LitStr` wrapping and the token inside our brackets are exactly what we need. So the alternative code within `mat` looks like the following.
## Listing 8.6 Alternative code within our match
rust
Meta::List(nested) => {
&nested.tokens
}

With an ident instead of a string, we could also have turned to parse_nested_meta, a method on Attribute. In that case, instead of two nested maps (map(|a| &a.meta) plus the map that does a match), we would have what appears in the following listing.

Listing 8.7 Alternative with parse_nested_meta

Section titled “Listing 8.7 Alternative with parse_nested_meta”
let mut content = None;
a.parse_nested_meta(|m| {
let i = &m.path.segments.first().unwrap().ident;
content = Some(Ident::new(&i.to_string(), i.span()));
Ok(())
}).unwrap();
content.unwrap()

Calls parse_nested_meta to get the content of the attribute

We know that a rename should contain a single identifier, so we retrieve it.

This returns a unit result, which we should handle (in this case by unwrapping).

content should now be an Option<Ident>, so we unwrap it and return the identifier.

In major version 1 of syn, there was another useful parse_meta method under the parsing feature, but that seems to have been removed.

To make sure that everything works, you can add additional tests to main.rs, such as one with multiple properties but only one of them with a custom name or a test where multiple properties have custom names.

#[test]
fn should_generate_builder_for_struct_with_two_props_one_custom_name() {
#[derive(Builder)]
struct Gleipnir {
#[rename("tops_of")]
roots_of: String,
breath_of_a_fish: u8,
}
let gleipnir = Gleipnir::builder()
.tops_of("mountains".to_string())
.breath_of_a_fish(1)
.build();
}
<!-- page: 182 -->
CHAPTER 8 Builder with attributes
rust
assert_eq!(gleipnir.roots_of, "mountains".to_string());
assert_eq!(gleipnir.breath_of_a_fish, 1);
}

These tests, and the existing ones, should compile and succeed.

Before moving on, we will explore the alternative of using a key plus value for our rename attribute. Several libraries use yet another approach, creating a single library attribute with the specific command added between parentheses—for example, #[serde(rename = "name")]. But we’ll leave that for the exercises.

Start with a unit test to verify the required behavior. (You should disable the other tests. We are going to replace the existing attribute behavior.)

Listing 8.9 Testing for an alternative attribute-naming strategy

Section titled “Listing 8.9 Testing for an alternative attribute-naming strategy”
#[cfg(test)]
mod tests {
#[test]
fn should_generate_builder_for_struct_with_one_renamed_prop() {
#[derive(Builder)]
struct Gleipnir {
#[rename = "tops_of"]
roots_of: String,
}
let gleipnir = Gleipnir::builder()
.tops_of("mountains".to_string())
.build();
assert_eq!(gleipnir.roots_of, "mountains".to_string());
}
}

Instead of parentheses, we use an equals sign to separate the “command” from its value.

Now for the implementation. Again, we only have to focus on fields.rs and builder_methods. While there are only a few essential changes, the solution does take a more “streaming” approach to mapping. Instead of using if let, we map until we have our output, using unwrap_or_else to get the default. unwrap_or is an alternative, but unwrap_or_else accepts a closure and is lazily evaluated, which could give a minor performance boost, especially if there are a lot of renames.

Listing 8.10 Implementation for the alternative approach

Section titled “Listing 8.10 Implementation for the alternative approach”
// other code, imports
pub fn builder_methods(fields: &Punctuated<Field, Comma>) -> Vec<TokenStream> {
fields.iter()
<!-- page: 183 -->
# 8.2 Alternative naming for attributes
.map(|f| {
let (field_name, field_type) = get_name_and_type(f);
extract_attribute_from_field(f, "rename")
.map(|a| &a.meta)
.map(|m| {
match m {
Meta::NameValue(
MetaNameValue { value: Expr::Lit(ExprLit {
lit: Lit::Str(literal_string), ..
}), ..
}) => {
Ident::new(
&literal_string.value(),
literal_string.span()
)
}
_ => panic!(
"expected key and value for rename attribute"
),
}
})
.map(|attr| {
quote! {
pub fn #attr(mut self, input: #field_type) -> Self
{
self.#field_name = Some(input);
self
}
}
})
.unwrap_or_else(|| {
quote! {
pub fn #field_name(mut self, input: #field_type)
-> Self {
self.#field_name = Some(input);
self
}
}
})
}).collect()
}
Besides the additional mappings, the only real difference with the previous code is that we now have to look for NameValue in the metadata (see figure 8.2). As mentioned, that is the variant we get for key-value attributes. The match is quite long (Meta::NameValue(MetaNameValue { value: Expr::Lit(ExprLit { lit: Lit::Str(literal_string), .. }), .. })), and if you find it to be too complicated, you can split it up into multiple, nested matches. Personally, I like how I can get to the desired value with a single, readable pattern match.
**Figure 8.2**
> [!warning] figure not recoverable
> The transcription references an image on PDF page 183 (printed p. ?) that has no matching grounding block; no crop was produced.
**Annotations:**
- **We look for the string value inside Meta::NameValue.**
- **Continues mapping and creates the TokenStream**
- **Defaults to the normal output with unwrap_or_else**
<!-- page: 184 -->
CHAPTER 8 Builder with attributes
![](assets/wpm-fig-9-02-simplified-view-of-the-meta-property-for.png)
> [!visual-conversion] Simplified view of the meta property for our use case
> Cropped from the scan (PDF page 184, printed p. ?): Simplified view of the meta property for our use case
Figure 8.2 Simplified view of the meta property for our use case
## Lazy and eager evaluations
Eager and lazy evaluations are two approaches to writing code. *Eager evaluation* means the code you write will be invoked when it is encountered. *Lazy evaluation* means that evaluation is postponed until it proves necessary. In listing 8.10, `unwrap_or_else` is lazy because the closure that creates the default `TokenStream` will only be called if we end up in the `unwrap_or_else` call. If every field has a `rename` attribute, and we never end up in `unwrap_or_else`, we never pay the cost that comes with creating the default stream. `unwrap_or`, on the other hand, is eager, meaning that if we used that method, the default `TokenStream` would be constructed every time, even when that is unnecessary.
Eager evaluation can have the advantage of being simpler to reason about. There is simplicity in the knowledge that everything is always ready for use. Besides offering possible performance advantages, lazy evaluation is the only approach suitable to
<!-- page: 185 -->
some programming constructs, like infinite data structures. If you have a stream that will produce data without ever stopping, eager evaluation would call it forever, whereas with a lazy approach, you would only invoke that stream when you really need data. Languages often have a built-in preference for one kind of evaluation, even if this is seldom exclusive. JavaScript is generally eager, whereas Haskell is lazy. We have actually already encountered lazy evaluation in this book. The `lazy_static` crate has a macro for “declaring lazily evaluated statics.”
## 8.3 Sensible defaults
Remember how we talked about proper error handling, in a previous chapter? How you should not panic or throw exceptions at every turn? Then why on earth do we panic whenever a user forgets to fill in a field?
There are alternatives. Instead of panicking, we could output a `Result` when calling `build`, giving back an `Err` if a field is missing. This is standard Rust practice for method calls that might fail. Or we could try to make panics impossible—a radical idea that we will save for later. Another idea, which we will explore now, is to use defaults as a fallback. We will use the nifty `Default` trait to do that. In the unlikely event that you have never heard of this trait before: by implementing `Default`, you specify a default value for a given type. Most built-in types already have sensible defaults out of the box, like numbers (`0`), strings (`empty`), Booleans (`false`), and `Option` (`None`). Defaults are also easily implemented with a derive macro.
In this section, we add an attribute to our macro, which will determine whether to use defaults. The following listing shows a test.
### Listing 8.11 A test for defaults
rust
#[test]
fn should_use_defaults_when_attribute_is_present() {
#[derive(Builder)]
#[builder_defaults]
struct ExampleStructTwoFields {
string_value: String,
int_value: i32,
}
let example: ExampleStructTwoFields =
ExampleStructTwoFields::builder()
.build();
assert_eq!(example.string_value, String::default());
assert_eq!(example.int_value, Default::default());
}

When you try to run this test, it fails because Rust does not know about an attribute called builder_defaults. This is easy to fix.

#[proc_macro_derive(Builder, attributes(rename, builder_defaults))]
pub fn builder(item: TokenStream) -> TokenStream {
create_builder(item.into()).into()
}

Now our test panics because we haven’t written our implementation yet. So we should retrieve the attribute. If it is present, we fall back to defaults. The code change in our lib.rs file is simple: it checks whether we have to use defaults and passes the Boolean on to the method that needs it.

Listing 8.13 lib.rs code changes: checking the attributes for builder_defaults

Section titled “Listing 8.13 lib.rs code changes: checking the attributes for builder_defaults”
// mode, imports
use syn::Attribute;
const DEFAULTS_ATTRIBUTE_NAME: &str = "builder_defaults";
pub fn create_builder(item: TokenStream) -> TokenStream {
let ast: DeriveInput = parse2(item).unwrap();
let name = ast.ident;
let builder = format_ident!("{}", Builder, name);
let use_defaults = use_defaults(&ast.attrs); // Sends the root attributes to a helper
// ...
let set_fields = original_struct_setters(
fields,
use_defaults // And passes its Boolean result to the function that needs it
);
// ...
}
fn use_defaults(attrs: &[Attribute]) -> bool {
attrs
.iter()
.any(|attribute|
attribute.path().is_ident(DEFAULTS_ATTRIBUTE_NAME))
}

As you can see, attributes are present both at the root level of DeriveInput and at the field level. Previously, we were adding attributes to individual fields. This time we placed one on top of our struct. So we should look in the root. Our use_defaults helper is simple. It checks whether any attribute identifier matches the name builder_defaults. The result is given to original_struct_setters, the only method that needs to know about it. Meanwhile, in fields.rs, we have more work to do, because we want to behave differently depending on this Boolean value.

// imports and other code
<!-- page: 187 -->
8.3 Sensible defaults
175
rust
pub fn original_struct_setters(fields: &Punctuated<Field, Comma>,
use_defaults: bool)
-> Vec<TokenStream> {
fields.iter().map(|f| {
let field_name = &f.ident;
let field_name_as_string = field_name
.as_ref().unwrap().to_string();
let handle_type = if use_defaults {
default_fallback()
} else {
panic_fallback(field_name_as_string)
};
quote! {
#field_name: self.#field_name.#handle_type
}
})
.collect()
}
fn panic_fallback(field_name_as_string: String) -> TokenStream {
quote! {
.expect(concat!("field not set: ", #field_name_as_string))
}
}
fn default_fallback() -> TokenStream {
quote! {
unwrap_or_default()
}
}

We have added some code and refactored a bit. We moved the “panic” generation, the fallback, to a separate method:

fn panic_fallback(field_name_as_string: String) -> TokenStream {
quote! {
expect(concat!("Field not set: ", #field_name_as_string))
}
}

As we mentioned before, it is perfectly fine for streams to be bits of code that cannot function on their own. That is the case here. This expect is not valid, standalone Rust code, but we will combine it with other bits of code until it can be parsed as valid. We also need to generate code for the default fallback. What is nice is that Option has an unwrap_or_default() method created just for this use case:

fn default_fallback() -> TokenStream {
quote! {
unwrap_or_default()
}
}

If use_defaults is true, generates a default fallback
Otherwise, we fall back to panics.

Now we need to use the “defaults” Boolean to determine the behavior, which we do with a simple if-else, combining the result with code for filling in the field. By combining all these fragments, we are one step closer to valid Rust, though we still need to do some transformations in lib.rs before everything is in place:

pub fn original_struct_setters(fields: &Punctuated<Field, Comma>,
use_defaults: bool) -> Vec<TokenStream> {
fields.iter().map(|f| {
let field_name = &f.ident;
let field_name_as_string = field_name
.as_ref().unwrap().to_string();
let handle_type = if use_defaults {
default_fallback()
} else {
panic_fallback(field_name_as_string)
};
quote! {
#field_name: self.#field_name.#handle_type
}
}).collect()
}

For our convenience, we are returning a Vec instead of a Map or impl. All three are valid inputs for quote, but Map now becomes a lot more annoying to use. As we are passing the use_defaults Boolean to map, this means that the function inside that map is now capturing a variable from its environment. That makes it a closure, which means our previous signature (Map<Iter<Field>, fn(&Field) TokenStream>) is invalid, as fn is a function pointer, not a closure. Change it to Fn, and you will get a complaint about sizes not being known at compile time. In brief, the following listing shows everything we have to do to keep our Map.

Listing 8.15 Do not pass go, do not collect: alternative to returning a Vec

Section titled “Listing 8.15 Do not pass go, do not collect: alternative to returning a Vec”
pub fn original_struct_setters<'a>(fields: &'a Punctuated<Field, Comma>,
use_defaults: bool)
-> Map<Iter<'a, Field>, Box<dyn Fn(&Field) -> TokenStream>> {
fields.iter().map(Box::new(move |f| {
// same as before
}))
}

The signature requires an Fn because of the closure and a Box to let Rust know the compile-time size. That means we actually have to box our closure: Box::new(move |f| ...). The move is needed because of our original problem; that is, we need to take ownership of use_defaults. So it’s a lot of busy work, a complex signature, and possibly worse performance because of the boxing.

8.4 A better error message for defaults

On the other hand, impl Iterator<Item = TokenStream> + '_ is still an acceptable alternative solution. Its signature stays the same, and we only have to add a move to our mapping for the same reason as stated previously.

With one of these solutions in action, the test that we wrote should compile and pass. If you want to make sure no previous code was broken, add a test that still panics for missing properties.

What happens when we have properties that do not implement Default? Add trybuild to the project, copy the compilation_tests.rs we used before, and put this under tests/fails.

Listing 8.16 Testing what happens when a property does not implement Default

Section titled “Listing 8.16 Testing what happens when a property does not implement Default”
use builder_macro::Builder;
struct DoesNotImplementDefault;
// This struct does not implement Default.
#[derive(Builder)]
#[builder_defaults]
struct ExampleStruct {
not: DoesNotImplementDefault
}
// But we use it in a struct that uses the default fallback.
fn main() {}

Rust throws an error:

????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
<!-- page: 190 -->
# CHAPTER 8 Builder with attributes
## Listing 8.17 Example usage of quote_spanned with a where clause
rust
quote_spanned! {ty.span() =>
struct ExampleStruct where SomeType: core::default::Default;
}

We are also passing in the full path for Default, core::default::Default, which avoids confusion with other traits with the same name that live in other crates (or in the user’s codebase). This is a best practice that we have been avoiding until now for simplicity’s sake and that will feature in more detail in a later chapter.

What we want to do now is loop through our fields with iter and map, adding structs with where clauses that claim a field’s type implements Default. If this is not the case, well—feel the wrath of the compiler, which will use the span we passed in (the one from the offending type) to point the user to their mistake. The struct’s name starts with two underscores, another best practice for avoiding collisions with user code.

// other imports
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned;
pub fn optional_default_asserts(fields: &Punctuated<Field, Comma>)
-> Vec<TokenStream> {
fields.iter()
.map(|f| {
let name = &f.ident.as_ref().unwrap();
let ty = &f.ty;
let assertion_ident = format_ident!(
"__{}DefaultAssertion",
name
);
quote_spanned! {ty.span() =>
struct #assertion_ident where #ty: core::default::Default;
}
})
.collect()
}

We need this trait to be present when calling span().

Creates an identifier for our empty struct

Tells Rust that it implements Default, passing along the span of the field’s type

Now all we need to do is to add this vec to our final output, using the hashtag style for multiple items, when the “default” annotation is present. Otherwise, we add an empty vector of tokens, which generates nothing at all.

Listing 8.19 Code in lib.rs (builder-code)

Section titled “Listing 8.19 Code in lib.rs (builder-code)”
pub fn create_builder(item: TokenStream) -> TokenStream {
// ...
let default_assertions = if use_defaults {
<!-- page: 191 -->
8.5 Build back better
rust
optional_default_asserts(fields)
} else {
vec![]
};
quote! {
// generate the struct, builder, etc.
#(#optional_default_assertions)*
}

If defaults are in use, we want to add the assertions. If not, an empty vector is all we need.

Adds the default assertion structs

Now if you try to pass in a nested struct that does not implement Default, you get a more informative error pointing to the exact location of the offender:

error[E0277]: the trait bound `DoesNotImplementDefault: Default` is not satisfied
--> tests/fails/no_default.rs:9:10
|
9 | not: DoesNotImplementDefault
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Default` is not implemented for `DoesNotImplementDefault`
|
= help: see issue #48214
help: ...

As a footnote to this section: I stumbled upon a variation to this approach while answering a Stack Overflow question. A user was using a macro to generate a function that required a trait implementation for its argument. One problem they were having was that the error message for when the type did not implement the trait was unhelpful. It pointed to the macro invocation. Sound familiar? The solution was a nice variation on using spans for error messages. Instead of hardcoding the trait, generate an identifier with the span of the type that does not implement the trait:

let trait_ident = Ident::new("MyTrait", problematic_type.span());

Now if you use trait_ident in a where clause and something goes wrong, Rust will point to the span and the faulty type.

How about a slight detour before soldiering on with attributes? I promise it is somewhat relevant—and, even if it’s not, the technique is interesting.

8.5.1 Avoiding illegal states and the type state pattern

Section titled “8.5.1 Avoiding illegal states and the type state pattern”

What may be bothering you is how we seem to have only three choices to deal with missing properties: defaults, panics, and a Result return type. We have implemented the first two, and the latter option sounds nice and idiomatic. But it is not a perfect fit because there is no reason to allow mistakes in building our example structs. You either have all their required properties or you don’t. In the former case, the operation is always a success. In the latter case, it never is. That means there is no reason to

allow anyone to skip properties when our fallback is panicking. And the “default variation” forces developers to implement a trait, as well as carries a risk: did the user really want a default, or did they forget to set the property? (See figure 8.3.)

plaintext ExampleStruct first_prop second_prop | builder() | ExampleStructBuilder | |-------------------|-------------------| | | | first_prop() build() second_prop()

Figure 8.3 Current situation: too much room for errors. We generate a builder that can immediately call build, even without setting the fields.
The best solution would be to move our check to the type system, to *make illegal states unrepresentable*. What I mean by that is that the best kind of application does not allow programmers to create run-time problems. Instead, we can try to mold the type system, to make the compiler stop users when they make mistakes. Any type system offers this functionality to users in a basic form. It can, for example, make sure that numeric things like age cannot be strings, negative numbers, or very large.
This may sound familiar, because we talked about this idea when we were discussing newtypes, which are one way to extend the power of your type system, making it more specific to your domain. Specifically, in the case of our builder, we want to force users to fill in every required property, only allowing them to call build when this has been done.
We can use the *type state pattern* to do that, encoding the state of our system in a type parameter. A simple example might help illustrate the idea. We have a traffic light that is either green or red. When it is red, turning red a second time does not make sense (see figure 8.4).
```plaintext
TrafficLight
state: Red
|
|-------------------|
| |
turn_green() turn_red()
| |
TrafficLight TrafficLight
state: Green state: Red?

Figure 8.4 It makes no sense for a traffic light to turn red when it already is that color. We are allowing illegal states.

[figure owed: ]

[!visual-conversion] Flowchart showing ExampleStruct → builder() → ExampleStructBuilder → first_prop(), build(), … Cropped from the scan (PDF page 192, printed p. ?): Flowchart showing ExampleStruct → builder() → ExampleStructBuilder → first_prop(), build(), second_prop()

stateDiagram-v2
    Red : TrafficLight (state Red)
    Green : TrafficLight (state Green)
    RedQ : TrafficLight (state Red?)
    Red --> Green : turn_green()
    Red --> RedQ : turn_red()

[!visual-conversion] TrafficLight state transition Converted from a print state-transition diagram (PDF page 192): TrafficLight in state Red can turn_green() into state Green or turn_red() into state Red?.

8.5 Build back better

No, a red light should only change to green—green only to red (green → red → green → ; it’s a state machine) (see figure 8.5).

Listing 8.20 shows some code for enforcing this behavior at compile time, using a marker trait, a trait that has no methods or properties but serves to “mark” types as being something and some structs that implement that marker. Because Rust does not allow unused generic properties, we have to add PhantomData<T> (from the standard library) to TrafficLight as a signal: “I have compile-time plans for this generic.” Next, we write implementation blocks that differ depending on the type of our generic. Only when the generic parameter is Green do we have the turn_red method, which returns a traffic light with the Red struct as a parameter. And the implementation block for TrafficLight<Red> only has turn_green, which returns TrafficLight<Green>.

stateDiagram-v2
    G : TrafficLight of Green
    R : TrafficLight of Red
    G --> R : turn_red()
    R --> G : turn_green()

[!visual-conversion] TrafficLight<Green> ⇄ TrafficLight<Red> Converted from a print state-machine diagram (PDF page 193): TrafficLight<Green> and TrafficLight<Red> alternate via turn_red() and turn_green(). Figure 8.5 The situation presented here is preferable: only valid states are allowed.

rust trait Light {}

struct Green {} struct Red {}

impl Light for Green {} impl Light for Red {}

struct TrafficLight<T: Light> { marker: PhantomData }

impl TrafficLight { fn turn_red(&self) -> TrafficLight { TrafficLight { marker: Default::default(), } } }

impl TrafficLight { fn turn_green(&self) -> TrafficLight { TrafficLight { marker: Default::default(), } } }

fn main() { let light = TrafficLight { marker: Default::default() }; }

We will use the Light marker trait, plus the Green and Red structs, to encode state.
Our traffic light has a generic parameter that implements Light (i.e., the previous structs).
Here we put our structs to good use (e.g., only `TrafficLight<Green>` implements `turn_red`).
<!-- page: 194 -->
CHAPTER 8 Builder with attributes
```rust
light.turn_red().turn_green();
}

Rust infers that we started green and only allows this sequence of calls.

The result? A traffic light guaranteed by the compiler to only have valid state transitions! Graydon Hoare would be proud.

NOTE As the story goes, Hoare—the creator of Rust—was inspired to create the language when an elevator in his apartment failed to work because of a software glitch.

8.5.2 Combining the builder pattern with type state

Section titled “8.5.2 Combining the builder pattern with type state”

We can do the same for our builder (see figure 8.6). We should

  • Create a marker trait.
  • Create a struct without properties for every field we receive (we can call them “field structs”) and make it implement the marker trait.
  • Make our builder accept a generic type that implements the marker trait.
  • Make the builder method of our struct return a builder with the generic type set to the first “field struct” (in the case of Gleipnir, this is roots_of).
  • Create an implementation block for the builder with that specific generic parameter with a method that accepts a field (roots_of) and returns a builder with the next generic parameter (breath_of_a_fish).
  • Rinse and repeat for all fields.
  • The final field does not return the “next” generic parameter since there is none. Instead, it returns a builder with a build method.

Our setup is that of the previous sections, with the attribute-related things (rename and defaults) stripped out so they don’t distract us. The following listing shows a test that should compile because the fields are all called in the correct order.

Listing 8.21 builder-usage test with correct order of attributes

Section titled “Listing 8.21 builder-usage test with correct order of attributes”
// macro import
fn main() {}
#[cfg(test)]
mod tests {

Figure 8.6 Desired situation: illegal states are unrepresentable. We generate a struct with a different generic type parameter for every method, only allowing the last one to call build.

flowchart TD
    ES["ExampleStruct<br/>first_prop<br/>second_prop"] -->|builder()| B1["ExampleStructBuilder FirstProp"]
    B1 -->|first_prop()| B2["ExampleStructBuilder SecondProp"]
    B2 -->|second_prop()| B3["ExampleStructBuilder Final"]

[!visual-conversion] Typestate builder progression Converted from a print flowchart (PDF page 194): ExampleStruct (first_prop, second_prop) steps through builder(), first_prop(), and second_prop() via ExampleStructBuilder FirstProp, SecondProp, and Final.

#[test]
fn should_work_with_correct_order() {
#[derive(Builder)]
struct Gleipnir {
roots_of: String,
breath_of_a_fish: u8,
anything_else: bool,
}
let gleipnir = Gleipnir::builder()
.roots_of("mountains".to_string())
.breath_of_a_fish(1)
.anything_else(true)
.build();
assert_eq!(gleipnir.roots_of, "mountains".to_string());
}

That tests the compilation and saving of at least one field value. For the error scenario, we add a test in the tests folder, with this code under fails/missing_prop.rs.

Listing 8.22 builder-usage compile test, under tests

Section titled “Listing 8.22 builder-usage compile test, under tests”
use builder_macro::Builder;
#[derive(Builder)]
struct Gleipnir {
roots_of: String,
breath_of_a_fish: u8,
anything_else: bool,
}
fn main() {
Gleipnir::builder()
.roots_of("mountains".to_string())
.breath_of_a_fish(1)
// missing final property
.build();
}

This should fail with a compile-time error because we forgot to add one of the attributes (namely, anything_else). Meanwhile, our builder-macro remains the same. The builder code has a lot of changes, though. lib.rs becomes simpler because more responsibility has been delegated to separate functions. All of those functions now need a reference to the name of a struct. We will see why in a moment.

pub fn create_builder(item: TokenStream) -> TokenStream {
// ... get the struct name and its fields
let builder = builder_definition(&name, fields);
}
<!-- page: 196 -->
# CHAPTER 8 Builder with attributes
rust
let builder_method_for_struct = builder_impl_for_struct(&name, fields);
let marker_and_structs = marker_trait_and_structs(&name, fields);
let builder_methods = builder_methods(&name, fields);
quote! {
#builder
#builder_method_for_struct
#marker_and_structs
#builder_methods
}

Before moving on to the meat of the implementation, listing 8.24 shows util.rs, which provides a way to create the identifier for the builder struct and field struct. By using these functions, we can avoid some duplication, and we make changing the names of our builders and additional structs, if we think of better names, much simpler.

use proc_macro2::Ident;
use quote::format_ident;
pub fn create_builder_ident(name: &Ident) -> Ident {
format_ident!("{}", "Builder", name)
}
pub fn create_field_struct_name(builder: &Ident, field: &Ident) -> Ident {
format_ident!("{}", "Of{}", field_name, builder_name)
}

We are going to have to split up the code in fields in separate fragments because it contains about 170 lines of code. We will be ignoring get_name_and_type, panic_fallback and original_struct_setters, which are basically unchanged.

First, we create the marker trait and structs. We add a marker trait and generate a struct plus implementation of the trait for every field. We need one additional struct for calling build. The trait (MarkerTraitForBuilder) and final struct (FinalBuilder) are hardcoded for brevity’s sake. In a production-grade macro, it would probably be best to add the name of the struct and __ as a prefix to make it more unique. Also, the structs start with a lowercase letter and have underscores, due to the field names, which is something Rust will complain about with a compiler warning.

Listing 8.25 marker_trait_and_structs in fields.rs

Section titled “Listing 8.25 marker_trait_and_structs in fields.rs”
pub fn marker_trait_and_structs(name: &Ident, fields: &Punctuated<Field, Comma>)
-> TokenStream {
let builder_name = create_builder_ident(name);
<!-- page: 197 -->
## 8.5 Build back better
rust
let structs_and_impls = fields.iter().map(|f| {
let field_name = &f.ident.clone().unwrap();
let struct_name = create_field_struct_name(
&builder_name,
field_name
);
quote! {
pub struct #struct_name {}
impl MarkerTraitForBuilder for #struct_name {}
}
});
quote! {
pub trait MarkerTraitForBuilder {}
#(#structs_and_impls)*
pub struct FinalBuilder {}
impl MarkerTraitForBuilder for FinalBuilder {}
}

Creates the right identifier

Creates the struct and implements the hardcoded marker

Adds the trait, structs, and implementations

Adds a struct that implements the marker for calling build

The builder definition is also fairly easy. We have moved more responsibility into the method and added the generic parameter and PhantomData marker. But that’s about it.

Listing 8.26 builder_definition in fields.rs

Section titled “Listing 8.26 builder_definition in fields.rs”
pub fn builder_definition(name: &Ident, fields: &Punctuated<Field, Comma>)
-> TokenStream {
let builder_fields = fields.iter().map(|f| {
let (field_name, field_type) = get_name_and_type(f);
quote! { #field_name: Option<#field_type> }
});
let builder_name = create_builder_ident(name);
quote! {
pub struct #builder_name<T: MarkerTraitForBuilder> {
marker: std::marker::PhantomData<T>,
#(#builder_fields,)*
}
}
}

This is our previous code.

The builder now has a generic parameter that implements the trait we just defined, plus a marker property.

Now for something more complex. In listing 8.27, we generate the builder method, which creates the empty builder struct. The “inits” are the same as before, and we need both the struct_name and builder_name for our output. But we also need a generic for the builder struct. As we said that this should refer to the first field of our struct, we retrieve the first field (and hope there is at least one; in a real use case, we would have to check whether it’s empty and act accordingly) and use a utility to get the right struct name.

Listing 8.27 builder_impl_for_struct in fields.rs

Section titled “Listing 8.27 builder_impl_for_struct in fields.rs”
pub fn builder_impl_for_struct(name: &Ident, fields: &Punctuated<Field, Comma>) TokenStream {
let builder_inits = fields.iter().map(|f| {
let field_name = &f.ident;
quote! { #field_name: None }
});
let first_field_name = fields.first().map(|f| {
f.ident.clone().unwrap()
}).unwrap();
let builder_name = create_builder_ident(name);
let generic = create_field_struct_name(
&builder_name,
&first_field_name
);
quote! {
impl #struct_name {
pub fn builder() -> #builder_name<#generic> {
#builder_name {
marker: Default::default(),
#(#builder_inits,)*
}
}
}
}
}

This assumes we have at least one field.

Uses the field identifier we found to build the right “field struct” identifier

The builder now has a generic type parameter and marker.

Finally, we should generate methods for setting fields. This method is huge, so we will split it up into three parts. In the first, we gather some information. original_struct_setters gives us field setters for when we will eventually call build, while get_assignments_for_fields sets all field properties for the builder struct. And for reasons that may become clear in the next code fragment, I prefer to start with the final field, so we reverse the field vector.

Listing 8.28 builder_methods in fields.rs: setup

Section titled “Listing 8.28 builder_methods in fields.rs: setup”
pub fn builder_methods(name: &Ident, fields: &Punctuated<Field, Comma>)
-> TokenStream {
let builder_name = create_builder_ident(name);
let set_fields = original_struct_setters(fields);
let assignments_for_all_fields = get_assignments_for_fields(fields);
let mut previous_field = None;
let reversed_names_and_types: Vec<&Field> = fields
.iter()
.rev()
.collect();
// ...
}
<!-- page: 199 -->
# 8.5 Build back better
In the next fragment, we have a map, with conditional branching. When we start iterating, previous_field will be empty, so we will end up in the else (and while this was not really on purpose, this is the more optimal choice of branching for performance, putting the least likely option last). Since the first field in our reversed list is actually the last field of our struct, we should create an implementation block with a setter for the final “field struct.”
Because we set the previous_field in both branches of the condition, every subsequent call will end up in the if branch. Here, like before, we want to generate a setter for the current generic. But this time, the return type should point to the generic parameter of the next field. And since we reversed the vector, we have that one available, stored away in previous_field.
## Listing 8.29 builder_methods in fields.rs: generating the methods
```rust
pub fn builder_methods(struct_name: &Ident, fields: &Punctuated<Field, Comma>)
-> TokenStream {
// ...
let methods: Vec<TokenStream> = reversed_names_and_types
.iter()
.map(|f| {
if let Some(next_in_list) = previous_field {
previous_field = Some(f);
builder_for_field(
&builder_name,
&assignments_for_all_fields,
f,
next_in_list
)
} else {
previous_field = Some(f);
builder_for_final_field(
&builder_name,
&assignments_for_all_fields,
f
)
}
})
.collect();
quote! {
#(#methods)*
impl #builder_name<FinalBuilder> {
pub fn build(self) -> #struct_name {
#struct_name {
#(#set_fields,)*
}
}
}
}
}

We already have a field? That means there is another field after this one, so we return a builder whose generic parameter points to the next “field struct” in our list.

There is no “previous”? That means we have the last field—that is, the first element of our vector. We should point to the final “field struct.”

What follows is the implementation of the two functions that were called in the map. The difference between them is subtle. Both generate a method that is added to the builder, which sets a specific field and returns the builder, using the “assignments” to fill in all its properties. This is necessary because we cannot simply return self thanks to the generic type parameter.

The main difference is that the first method (builder_for_field) points to the builder with a type referring to the next field (next_field_struct_name), while the second method (builder_for_final_field) produces one with generic type FinalBuilder.

Listing 8.30 The two functions used in builder_methods

Section titled “Listing 8.30 The two functions used in builder_methods”

rust fn builder_for_field( builder_name: &Ident, field_assignments: &Vec, current_field: &Field, next_field_in_list: &Field ) -> TokenStream { let (field_name, field_type) = get_name_and_type(current_field); let (next_field_name, _) = get_name_and_type(next_field_in_list); let current_field_struct_name = create_field_struct_name( &builder_name, field_name.as_ref().unwrap() ); let next_field_struct_name = create_field_struct_name( &builder_name, next_field_name.as_ref().unwrap() );

quote! {
impl #builder_name<#current_field_struct_name> {
pub fn #field_name(mut self, input: #field_type) ->
#builder_name<#next_field_struct_name> {
self.#field_name = Some(input);
#builder_name {
marker: Default::default(),
#(#field_assignments,)*
}
}
}
}

}

fn builder_for_final_field( builder_name: &Ident, field_assignments: &Vec, field: &Field ) -> TokenStream { let (field_name, field_type) = get_name_and_type(field); let field_struct_name = create_field_struct_name( &builder_name, field_name.as_ref().unwrap() ); }

rust quote! { impl #builder_name<#field_struct_name> { pub fn #field_name(mut self, input: #field_type) -> #builder_name { self.#field_name = Some(input); #builder_name { marker: Default::default(), #(#field_assignments,)* } } } }

Finally, the function brings everything together, adding the individual implementation blocks as well as the build method.
## Listing 8.31 builder_methods in fields.rs: output
```rust
quote! {
#(#methods)*
impl #builder_name<FinalBuilder> {
pub fn build(self) -> #struct_name {
#struct_name {
#(#set_fields,)*
}
}
}
}

The test in builder-usage should now succeed. And, depending on how well your IDE handles macros, you should only get suggestions for the right methods when using the builder: roots_of, breath_of_a_fish, anything_else, and finally build. As our compile test shows, you won’t get the builder to compile if you skip a property. Rust even gives you a clue as to what is wrong, thanks to the generic parameters:

error[E0599]: no method named `build` found for struct
`GleipnirBuilder<anything_elseOfGleipnirBuilder>` in the current scope
--> tests/fails/missing_prop.rs:16:10
4 | #[derive(Builder)]
| -------- method `build` not found for this struct
...
16 | .build();
| ^^^^^^ method not found in
| `GleipnirBuilder<anything_elseOfGleipnirBuilder>`
|
= note: the method was found for
- `GleipnirBuilder<FinalBuilder>`

This is really cool. You are forcing users of the macro to do the right thing, keeping them from shooting themselves in the foot. And everything is done automatically by a

macro, with all the complexity hidden away. Furthermore, the run-time impact should be minimal. The marker trait, empty structs, phantom markers, and generic type parameters only play a role at compile time and can be optimized away. And most of the other code was already present in our previous, more naive builder.

A possible extension to this example: what if you had optional values in your struct (i.e., values wrapped in an option or values where the Default implementation is good enough if the user does not pass anything along)? In that case, you could force the user to fill in all required values, but once the final required value is filled in, they should be able to call any of the optional setters as well as build.

This is a macro with a lot of moving parts, so you may be wondering how to approach such a complex task. In this particular case, I first sketched out my solution with normal Rust code, identifying all the different parts and how they fit together. Then I wrote code for things that were prerequisites, as well as being relatively simple to generate (the marker trait and structs, for example), looking at the output to check my work. That done, I wrote the rest of the code and made the macro compile. Finally, I ran cargo expand on an example struct to identify any remaining problems. For example, I forgot to save the “previous field” value in the else branch, so all the setters were pointing to build instead of the next setter!

Gently tying this back to the original builder code, we can see that patterns like this could be used in complex macros. For example, the if-else approach to our error handling (panic or default) is fine right now because it is limited to one location. But what if it appeared in a lot of methods? We would have a lot of ugly conditionals in our code, scattering one piece of logic (our fallback behavior) across the application. That makes mistakes easier and refactoring harder. Instead, you could centralize this behavior while making it easier to use.

One idea would be to have a strategy trait with methods for everything that requires a conditional, like generating the proper fallback. Then you could have an enum representing the different approaches that implement the trait.

NOTE The strategy pattern is a design pattern from the Gang of Four. It creates separate objects for algorithms and hides the concrete choice behind an interface. This makes it easier to switch out algorithms without changing any other part of your codebase. Here we use a trait instead of an interface and a single enum with two variants instead of multiple objects.

Listing 8.32 The Strategy trait and an enum that implements its method

Section titled “Listing 8.32 The Strategy trait and an enum that implements its method”
trait Strategy {
fn fallback(&self, field_type: &Type, field_name_as_string: String)
<!-- page: 203 -->
8.6 Avoiding scattered conditionals
191
rust
-> TokenStream;
}
enum ConcreteStrategy {
Default,
Panic,
}
impl Strategy for ConcreteStrategy {
fn fallback(&self, field_type: &Type, field_name_as_string: String)
-> TokenStream {
match self {
ConcreteApproach::Default => {
quote! {
unwrap_or_default()
}
}
ConcreteApproach::Panic => {
// similar
}
}
}
}

Within the macro, you decide on a strategy based on the presence of our defaults attribute, get back the right enum variant, and pass it to the right methods.

Listing 8.33 Example of passing on and using the strategy

fn original_struct_setters<T>(strategy: &T, fields: &Punctuated<Field, Comma>)
-> Vec<TokenStream> where T: Strategy {
fields.iter()
.map(|f| {
let (field_name, field_type) = get_name_and_type(f);
let field_name_as_string = field_name
.as_ref()
.unwrap()
.to_string();
let handle_type = strategy.fallback(
field_type,
field_name_as_string
);
quote! {
#field_name: self.#field_name.#handle_type
}
})
.collect()
}

This is more than enough abstraction for our current macro. But in a more complex setup, where there is more need to steer developers, we could add type state, returning intermediate states from our methods, with only the final state returning the

CHAPTER 8 Builder with attributes

output TokenStream. That way, everything that is needed for the macro to work has to be present. A useful attribute that helps steer the user is #[must_use], which throws a warning when a required return value goes unused.

We already mentioned that only derive and attribute macros support attributes. (Function-like macros are powerful enough that you could mimic them, as we shall soon see.) But we only discussed derive macros. Are there any differences between the two?

The answer is yes. While derive macro attributes are inert, attribute macros (including any additional attributes) are active, meaning they remove themselves during attribute processing. That is probably the most sensible action, because, for example, an attribute macro might not produce any output (see chapter 9’s core example). Does it make sense to keep an attribute in your source code when the item it was attached to has disappeared? Another difference is that you have some additional freedom in the exact format of your attribute macro attributes, whereas for a derive macro, you need to specify attributes in a specific property (attributes).

For a simple attribute macro example, we can go back to our “public fields” macro, where we add an “exclude” property that allows you to add properties that should not be made public. We won’t go over the entire (unchanged) setup, but listings 8.34 and 8.35 are the two files under src. As you can see, we modified our macro invocation. Instead of a simple #[public], we now have additional information within parentheses, #[public(exclude(fourth, third))]. We also added a public “constructor” so we can create the struct in other modules. In the following listing, we expect first to become public and the visibility of the other properties to stay unchanged.

use make_public_macro::public;
#[public(exclude(fourth, third))]
struct Example {
first: String,
pub second: u32,
third: bool,
fourth: String,
}
impl Example {
pub fn new() -> Self {
Example {
first: "first".to_string(),
// etc.
}
}
}

We exclude properties third and fourth so they will not be made public.

We need a public method for creating the struct since some properties are private.

In our main file, we will have a simple test to check compilation.

Listing 8.35 main.rs, with some usage of our example struct

Section titled “Listing 8.35 main.rs, with some usage of our example struct”
use crate::example::Example;
mod example;
fn main() {
let e = Example::new();
println!("{}", e.first);
println!("{}", e.second);
// println!("{}", e.third);
}

These will work, because we will make them public.

Here we expect an error: field third of struct Example is private.

Now let’s move on to the library code and some notable differences. With a derive macro, we had attributes in the root of the token stream or on individual fields. With an attribute macro, you can still find attributes on the individual fields, and other attributes can still be found in the root of the AST. But one thing is very much unlike a derive macro: our annotation is extremely flexible. A derive macro is always #[derive(...)]; an attribute macro’s invocation can be molded. But where does all the information about that attribute end up if it is not in the root of the AST? Well, it’s finally time to look inside the first TokenStream parameter of this macro. And if you were to print it for our current example, you would get back something like this:

[Ident { ident: "exclude" }, Group { delimiter: Parenthesis,
stream: TokenStream [Literal { kind: Str, symbol: "fourth, third",
suffix: None }]

Look at that! It’s the property we added to our macro.

Now that we know where to look, we can move on to the macro entry point. Notice how we are now passing the attr parameter to a second parse_macro_input invocation, putting the result in a custom struct called ExcludedFields. Then we use a custom method that we added to that struct to detect whether the field was excluded. If it was, we give back the existing visibility. Otherwise, we make the field public.

Listing 8.36 Our public function with a custom struct for parsing the first parameter

Section titled “Listing 8.36 Our public function with a custom struct for parsing the first parameter”
// imports
#[proc_macro_attribute]
pub fn public(attr: TokenStream, item: TokenStream) -> TokenStream {
let ast = parse_macro_input!(item as DeriveInput);
let excluded_fields = parse_macro_input!(
attr as ExcludedFields
);
let name = ast.ident;
let fields = // still retrieving the fields
}

We parse the attributes TokenStream into a custom struct.

<!-- page: 206 -->
# CHAPTER 8 Builder with attributes
rust
let builder_fields = fields.iter().map(|f| {
let name = &f.ident;
let ty = &f.ty;
let vis = &f.vis;
if excluded_fields.matches_ident(name) {
quote! { #vis #name: #ty }
} else {
quote! { pub #name: #ty }
}
});
// return output

We use a custom method to determine whether the field was excluded.

Okay, so it is already clear that, this time around, we have taken a struct approach to parsing our input, with ExcludedFields as a wrapper for a vector of strings. The struct implements Parse because, otherwise, we could not pass it to parse_macro_input. As we know, there is currently only one attribute, and it looks like this: exclude(...). So we know we are dealing with a MetaList and parse it as such. Meta, being one level higher up, would have worked equally well, but that would be pointless, since we are only interested in getting a list, not a path or name value. That means we can skip one layer of abstraction by going directly for MetaList (see figure 8.7).

Figure 8.7 Attribute, Meta, or MetaList

Once we have the meta list, we check the path property to see if our exclude annotation is present. If it is, we parse as a Punctuated of identifiers using parse_terminated and change those into strings.

[!visual-conversion] Diagram showing Attribute → Meta → MetaList with annotations about … Cropped from the scan (PDF page 206, printed p. ?): Diagram showing Attribute → Meta → MetaList with annotations about parse implementation and acceptable targets.

Listing 8.37 ExcludedFields implementation for syn major version 2

Section titled “Listing 8.37 ExcludedFields implementation for syn major version 2”
const EXCLUDE_ATTRIBUTE_NAME: &str = "exclude";
struct ExcludedFields {
fields: Vec<String>
}
impl ExcludedFields {
fn matches_ident(&self, name: &Option<Ident>) -> bool {
name.as_ref().map(|n| n.to_string())
.map(|n| self.fields.iter().any(|f| *f == n))
.unwrap_or_else(|| false)
}
}
impl Parse for ExcludedFields {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
match input.parse::<MetaList>() {
Ok(meta_list) => {
if meta_list.path
.segments
.iter()
.find(|s| s.ident == EXCLUDE_ATTRIBUTE_NAME)
.is_some()
{
let parser = Punctuated::<Ident, Token![,]>::parse_terminated;
let identifiers = parser.parse(
meta_list.clone().tokens.into()
).unwrap();
let fields = identifiers.iter()
.map(|v| v.to_string())
.collect();
Ok(ExcludedFields { fields })
} else {
Ok(ExcludedFields { fields: vec![] })
}
}
Err(_) => Ok(
ExcludedFields { fields: vec![] }
)
}
}
}

Had we gone for exclude("fourth", "third"), it would have been a Punctuated of LitStr and the map would call the value method. The other code would stay unchanged.

Note that this is code written for syn major version 2. In version 1, you had a useful—but limiting—struct called AttributeArgs, which was an alias for Vec<NestedMeta>. To get the excluded items, you could do something like in the following listing (note the “match guard” in the first match).

<!-- page: 208 -->
## Listing 8.38 Parsing AttributeArgs and MetaList in syn 1
rust
fn properties_to_exclude(args: AttributeArgs) -> Vec<String> {
args.iter()
.flat_map(|a| {
match a {
Meta(List(MetaList {
path: Path { segments, .. },
nested,
..
})) if segments.iter()
.find(|s| s.ident == EXCLUDE_ATTRIBUTE_NAME)
.is_some() => {
nested
.iter()
.map(|v| match v {
Lit(Str(l)) => l.value(),
_ => unimplemented!(
"expected at least one args between brackets"
),
})
.collect()
},
_ => vec![],
}
})
.collect()
}

This is quite similar, but not the same, as our current implementation. The big difference is that, inside the if branch, we use the nested property of MetaList (which, in this code example, contains a list of LitStr).

A more up-to-date alternative to our current approach is to use syn::meta::parser. The implementation in listing 8.39 is quite similar to a documentation example. We parse_macro_input!(attr with attr_parser) to pass in a custom parser for the attributes, which we defined one line above using syn::meta::parser. Actual parsing is a task for our custom struct, which checks whether we have an exclude attribute in the path property, throwing an error if we receive something else. Within the attribute, we dive one level deeper with parse_nested_meta and retrieve the identifiers, adding them to our vector of fields.

#[derive(Default)]
struct AlternativeExcludedFields {
fields: Vec<String>,
}
impl AlternativeExcludedFields {
fn matches_ident(&self, name: &Option<Ident>) -> bool {
<!-- page: 209 -->
// same as ExcludedFields
}
impl AlternativeExcludedFields {
fn parse(&mut self, meta: ParseNestedMeta) -> Result<(), syn::Error> {
if meta.path.is_ident(EXCLUDE_ATTRIBUTE_NAME) {
meta.parse_nested_meta(|meta| {
let ident = &meta.path.segments.first().unwrap().ident;
self.fields.push(ident.to_string());
Ok(())
})
} else {
Err(meta.error("unsupported property"))
}
}
}
#[proc_macro_attribute]
pub fn public(attr: TokenStream, item: TokenStream) -> TokenStream {
let ast = parse_macro_input!(item as DeriveInput);
let mut excluded_fields = AlternativeExcludedFields::default();
let attr_parser = syn::meta::parser(|meta| excluded_fields.parse(meta));
parse_macro_input!(attr with attr_parser);
// everything else is the same
}
One nice thing is that the library takes care of empty attribute streams for us, whereas earlier we had to catch an `Err` and return an empty `Vec`. It should also produce “sensible error messages on unexpected input” (https://docs.rs/syn/latest/syn/meta/fn.parser.html).
## 8.8 Other attributes
There are other kinds of attributes that we have not looked at in this chapter. The `syn` documentation lists six types of attributes in total:
- Outer attributes like `#[repr(transparency)]`, positioned outside or in front of an item
- Inner attributes—for example, `#![feature(proc_macro)]`—placed inside the item
- Outer and inner one-line doc comments (`///` and `//!`)
- Outer and inner documentation blocks (`/** */` and `/*! */`)
There’s nothing special when it comes to the four kinds of documentation attributes. In fact, as the documentation notes, comments are transformed into normal-looking attributes (`#[doc = r"your comment text here"]`) before macros enter the equation. We will use a tiny example to show additional ways of parsing documentation and, by extension, attributes. Since we said function-like macros can mimic attributes if they want to, we will write one of those.
<!-- page: 210 -->
The following listing shows our “usage code,” a simple macro invocation on a struct with all four kinds of comments.
## Listing 8.40 main.rs with an example struct for our function-like macro
rust
use other_attributes_macro::analyze;
analyze!(
/// outer comment
/** comment block */
struct Example {
//! inner comment
/*! inner comment block */
val: String
}
);
fn main() {}

Next we parse this input into a struct. The outer comments are the first ones we encounter, and to parse them we can combine Attribute::parse_outer with call to automatically turn the comments into a vector of (two) attributes. The most interesting field in Attribute is meta, which contains the comment content—so, in this case, outer comment and comment block. You can also see traces of the transformation into #[doc = r"..."] that happened before we entered the scene:

Meta::NameValue { path: Path { ..., segments: [PathSegment { ident: Ident { ident: "doc" } }] }, eq_token: Eq, value: Expr::Lit { attrs: [], lit: Lit::Str { token: " outer comment" } } }

To get to the inner comments, we have to get rid of some things, like the struct keyword and identifier (Example), which is what we do with the first two parse calls. Next, we use a macro from syn that is specifically designed to handle curly braces: braced, which is only available when the parsing feature of syn is enabled. braced will put the entire content of the curly braces from input in the variable we passed along, content. Next, we use Attribute::parse_inner to retrieve the inner comments. This, again, returns a Vec<Attribute>.

Listing 8.41 lib.rs with code for parsing the comments

Section titled “Listing 8.41 lib.rs with code for parsing the comments”
#[derive(Debug)]
struct StructWithComments {
ident: Ident,
field_name: Ident,
field_type: Type,
outer_attributes: Vec<Attribute>,
inner_attributes: Vec<Attribute>,
}
impl Parse for StructWithComments {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
<!-- page: 211 -->
# 8.9 From the real world
Uses Attribute::parse_outer, together with call, to parse the outer attributes
rust
let outer_attributes = input.call(Attribute::parse_outer)
.unwrap();
let _: Token![struct] = input.parse().unwrap();
let ident: Ident = input.parse().unwrap();
let content;
let _ = braced!(content in input);
let inner_attributes = content.call(Attribute::parse_inner)
.unwrap();
let field_name: Ident = content.parse().unwrap();
let _: Colon = content.parse().unwrap();
let field_type: Type = content.parse().unwrap();
Ok(StructWithComments {
ident,
field_name,
field_type,
outer_attributes,
inner_attributes,
})

Calls the braced macro to get the content within the curly braces ({ })

And Attribute::parse_inner will help us get the inner attributes.

#[proc_macro]
pub fn analyze(item: TokenStream) -> TokenStream {
let _: StructWithComments = parse_macro_input!(item);
quote!().into()
}

We finish our Parse implementation by retrieving the field name and type. As we wanted to give a brief introduction to parsing comments, as well as show some additional utilities for that kind of parsing, we did not take into account complexities like multiple fields, nor do we bother returning any output from the macro.

NOTE As a reminder, when you parse a TokenStream into a struct, syn expects you to parse everything it finds. If you only retrieve the inner attributes from the braced content and do nothing with the rest, you would receive an unexpected token error pointing to the first thing you’re not parsing. In our example, we parse everything to avoid this. But when you are not interested in the remainder of the content, you can put everything that remains into an ignored token stream: let _: TokenStream2 = content.parse().unwrap();. You can even leave the stream in its Result.

Let’s look at some real-world examples, starting with a simple one from Tokio. When you are inside the test macro (#[test]), a check is done to verify that you are not adding the test annotation multiple times:

if let Some(attr) = input.attrs.iter().find(|a| a.path.is_ident("test")) {
let msg = "second test attribute is supplied";
Err(syn::Error::new_spanned(attr, msg))
}
<!-- page: 212 -->
CHAPTER 8 Builder with attributes
rust
} else {
// ...
}

Meanwhile, Yew has logic that decides whether the attributes of the original struct should be used in its builder struct. Like Tokio, it uses the is_ident method to compare with strings:

impl Parse for DerivePropsInput {
fn parse(input: ParseStream) -> Result<Self> {
let input: DeriveInput = input.parse()?;
// ...
let preserved_attrs = input
.attrs
.iter()
.filter(|a| should_preserve_attr(a))
.cloned()
.collect();
Ok(Self {
// ...
preserved_attrs,
})
}
}
fn should_preserve_attr(attr: &Attribute) -> bool {
let path = &attr.path;
path.is_ident("allow") || path.is_ident("deny") || path.is_ident("cfg")
}

Serde, as noted, starts every additional attribute with serde, as seen in its derive entry point:

#[proc_macro_derive(Deserialize, attributes(serde))]
pub fn derive_deserialize(input: TokenStream) -> TokenStream {
let mut input = parse_macro_input!(input as DeriveInput);
// ...
}

And it has a lot of code to handle the different kinds of metadata. The following is a very partial fragment. It starts by checking whether the attribute is that of serde. When that’s done, the macro needs to know what is inside the parentheses, so it uses parse_nested_meta (from syn version 1; several libraries, at the time of writing, still use version 1) and reacts to things like RENAME:

pub fn from_ast(cx: &Ctxt, item: &syn::DeriveInput) -> Self {
// ...
for attr in &item.attrs {
if attr.path() != SERDE {
continue;
}
if let Err(err) = attr.parse_nested_meta(|meta| {
if meta.path == RENAME {
<!-- page: 213 -->
# Exercises
rust
let (ser, de) = get_renames(cx, RENAME, &meta)?;
// ...
} else if meta.path == RENAME_ALL {
let one_name = meta.input.peek(Token![=]);
let (ser, de) = get_renames(cx, RENAME_ALL, &meta)?;
// ...
} else if meta.path == DEFAULT {
if meta.input.peek(Token![=]) {
// ...
} else {
// ...
}
} else {
let path = meta.path.to_token_stream()
.to_string()
.replace(' ', "");
return Err(
meta.error(
format_args!(
"unknown serde container attribute `{}`", path
)
)
);
}
Ok(())
}) {
cx.syn_error(err);
}
// ...

You will find lots more attribute-handling code in popular crates, even if few are as extensively customizable as Serde. Its code will even feature briefly in the solution to the first exercise.

See the appendix for solutions.

  1. In our rename discussion, we used a simple name for our attribute. However, some libraries specify the crate name within the attribute and have the specific command wrapped inside parentheses—for example, #[serde(rename = "name")]. Rewrite our #[rename("...")] to instead use #[builder(rename = "...")].

  2. Our default assertions generated a warning about naming conventions, type __notDefaultAssertion should have an upper camel case name. Fix that warning.

  3. Add an uppercase field-level attribute to our builder project, which will uppercase String types. As an extension, you could return an informative (syn?) error when the attribute is used on a field that is not a String.

  • Macros can have attributes that allow you to further customize their behavior.
  • Attributes can be placed on top of a struct or enum or inside (above a field). Depending on this positioning, they will be found in the root of the AST or under the fields property.
  • Attribute macros, have a custom attribute that might contain additional instructions, unlike derive macros, whose attribute is set in stone.
  • Function-like macros can mimic attributes and parse them.
  • With the type state pattern, we can eliminate illegal states, making our code easier and safer to use.
  • The strategy pattern gives us a way to centralize a piece of logic, making it possible to change or swap out algorithms.