Skip to content
ImagineWorld

Macros and the outside world

node_idnode-book_write-powerful-rust-macros_chapter-11-macros-and-the-outside-world
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleMacros and the outside world
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 11 — Macros and the outside world

Section titled “Chapter 11 — Macros and the outside world”
  • Using a single library to expose multiple macros
  • Adding or disabling functionality with features
  • Using attributes for control over what code will be generated
  • Documenting and publishing a macro library
  • Moving on to explore interesting macro subjects beyond this book

In previous chapters, we have often made excuses for taking shortcuts, explaining how “production-grade” macros would do things better or differently. In this, our last, chapter, we will create a macro for making available YAML config that tries to do everything right. While its functionality will be very limited, it will have proper testing, error handling, documentation, and the like, making it (almost) ready for use by other people.

And that is great because publishing a library means your macro might find use among other developers, enriching the ecosystem of the language you love. Even libraries written within a company, with a specific use case in mind, might benefit

from being open source. People might discover bugs or send pull requests with fixes and improvements, helping you to improve the quality of your code, to everyone’s benefit. This chapter also offers an opportunity to bring together a few miscellaneous topics, like features, which can help you make your macro as lightweight as possible.

Let’s go over the first version of our macro, which exposes a function-like macro called config. Calling that macro generates a struct called Config, which contains a HashMap<String,String>. We also generate a new method for filling the map with configuration properties.

That means the following YAML configuration, plus a call to new, results in the creation of a map containing keys user and password, with the corresponding values "admin" and "pass":

user: "admin"
password: "pass"

For simplicity’s sake, we won’t allow nested YAML structures—only plain keys with string values.

We are once again going for a project with two directories (config-macro and config-macro-usage) and the optional Cargo workspace. There is also a configuration directory on the same level as these two directories, with an example config.yaml file contained within.

user: "admin"
password: "admin"

In our usage directory, the trybuild dependency has been added for compilation testing.

Listing 10.2 The config-macro-usage Cargo.toml dependencies

Section titled “Listing 10.2 The config-macro-usage Cargo.toml dependencies”
[dependencies]
config-macro = { path = "../config-macro", features = ["struct"] }
[dev-dependencies]
trybuild = "1.0.85"

The macro itself has serde and serde_yaml, used for reading the YAML.

[dependencies]
quote = "1.0.33"
<!-- page: 249 -->
# 10.1 A function-like configuration macro
toml
syn = { version = "2.0.39", features = ["extra-traits"] }
proc-macro2 = "1.0.69"
serde = "1.0.192"
serde_yaml = "0.9.27"

The workspace looks like the following listing.

Listing 10.4 The config-macro-usage Cargo.toml

Section titled “Listing 10.4 The config-macro-usage Cargo.toml”
[workspace]
resolver = "2"
members = [
"config-macro",
"config-macro-usage"
]

In config-macro-usage, main.rs contains an example of how to use the macro, as well as some happy path tests. There is also a tests directory with compilation failure tests, which are also left out for brevity’s sake but can be found in this book’s code repository (https://github.com/VanOvermeire/rust-macros-book).

Listing 10.5 Usage example and tests in main.rs

Section titled “Listing 10.5 Usage example and tests in main.rs”
fn main() {
config!();
let cfg = Config::new();
let user = cfg.0.get("user").unwrap();
println!("{}", user);
}
// some happy path tests

Let’s turn to the implementation.

The macro code contains nothing that you haven’t seen before, so we will be brief. We have gone for a modular approach by already creating input.rs and output.rs files in addition to lib.rs.

Start with lib.rs, which reads the token stream input using a struct from input.rs and produces output via a helper function. It also contains some of the core logic of our macro: finding and reading YAML. We look for the file with the default or overridden path and pass that file to serde_yaml for transforming it into a HashMap<String, String>. Errors are properly handled, and panics are avoided.

Listing 10.6 lib.rs coordinates helper functions

Section titled “Listing 10.6 lib.rs coordinates helper functions”
// imports, mod input, mod output
fn find_yaml_values(input: ConfigInput)
-> Result<HashMap<String, String>, syn::Error> {
<!-- page: 250 -->
# CHAPTER 10 Macros and the outside world
rust
let file_name = input.path
.unwrap_or_else(|| {
"./configuration/config.yaml".to_string()
});
let file = fs::File::open(&file_name)
.map_err(|err| {
syn::Error::new(
Span::call_site(),
format!(
"could not read config with path {}: {}",
&file_name,
err
)
)
})?;
Ok(serde_yaml::from_reader(file)
.map_err(|e| {
syn::Error::new(Span::call_site(), e.to_string())
})?)

Uses the override, or falls back to the default, for the configuration location

Opens the file, returning an informative error if that fails

Uses serde_yaml to read the content into a HashMap

#[proc_macro]
pub fn config(item: TokenStream) -> TokenStream {
let input: ConfigInput = parse_macro_input!(item);
match find_yaml_values(input) {
Ok(values) => generate_config_struct(values).into(),
Err(e) => e.into_compile_error().into()
}
}

Parses the input using a custom struct

Uses find_yaml_values to read the config and passes it along to a function that generates output

input.rs parses the incoming TokenStream. Currently, it expects one optional argument: a path for overriding the location of the configuration file, for which we created a custom keyword. Because we anticipate the possibility of other arguments in the future, we have gone for a key-value-style approach (path = "./path.yaml"), which makes it easier to add additional keys later on. We have also made sure to use proper error handling.

// syn imports
pub(crate) mod kw {
syn::custom_keyword!(path);
}
#[derive(Debug)]
pub struct ConfigInput {
pub path: Option<String>,
}
impl Parse for ConfigInput {
fn parse(input: ParseStream) -> syn::Result<Self> {
<!-- page: 251 -->
# 10.1 A function-like configuration macro
if input.is_empty() {
return Ok(ConfigInput {
path: None,
});
}
if !input.peek(kw::path) {
return Err(
syn::Error::new(
input.span(),
"config macro only allows for 'path' input",
)
);
}
let _: kw::path = input.parse()
.expect("checked that this exists");
let _: Token! (=) = input.parse()
.map_err(|_| syn::Error::new(
input.span(),
"expected equals sign after path"
))?;
let value: LitStr = input.parse()
.map_err(|_| syn::Error::new(
input.span(),
"expected value after the equals sign"
))?;
Ok(ConfigInput {
path: Some(value.value()),
})
output.rs also has a very familiar feel. That, at least, is what I am hoping for, after all those earlier chapters. It takes the values from the configuration file, creating a struct and a new method.
## Listing 10.8 output.rs creates the right output
// imports
fn generate_inserts(yaml_values: HashMap<String, String>) -> Vec<TokenStream> {
yaml_values.iter().map(|v| {
let key = v.0;
let value = v.1;
quote!(map.insert(#key.to_string(), #value.to_string());)
}).collect()
}
pub fn generate_config_struct(yaml_values: HashMap<String, String>) -> TokenStream {
let inserts = generate_inserts(yaml_values);
}
This function generates all the individual inserts into the map that we have to do.
<!-- page: 252 -->
# CHAPTER 10 Macros and the outside world
rust
quote! {
pub struct Config(
pub std::collections::HashMap<String, String>
);
impl Config {
pub fn new() -> Self {
let mut map = std::collections::HashMap::new();
#(#inserts)*
Config(map)
}
}
}

Here, we generate the struct and implementation.

With that, we can generate a struct from configuration.

The one thing that’s new and interesting about this code is that we are using the full path for HashMap (e.g., struct Config(pub std::collections::HashMap<String, String>); and similar inside new). Why? There are two reasons.

First, HashMap is not included in the Rust prelude, so it will not be available by default in our user’s code. So without the full path, Rust won’t know where this type is coming from. This will cause our code to fail with an error and cause the compiler to suggest importing the standard HashMap:

error[E0412]: cannot find type `HashMap` in this scope
--> config-macro-usage/src/main.rs:5:5
|
5 | config!();
| ^^^^^^^^^^ not found in this scope

Think of what is happening. We are adding code to a Rust file in an application. And if we add struct Config(HashMap<String, String>);, without the path, we are referring to a type that is unfamiliar within the user’s code, not our code. The users will have to fix the problem, probably by importing std::collections::HashMap. Maybe some of them even get lucky and there already is an import. In that case, they remain blissfully unaware of any macro compilation problems.

Still, user action is not a good outcome. Not only is it not very user friendly, but it also very directly exposes the fact that we are using a HashMap, which is an implementation detail we might like to hide if possible. With HashMap hidden, changing to a different type will be easier if that proves necessary, requiring no changes to existing application code. So by including the full path of things, we make life easier for our clients and enable the hiding of (some) implementation details.

The second reason is that users may already be using a HashMap but not the one we were expecting. Maybe they created a struct with the same name:

struct HashMap {}
<!-- page: 253 -->
# 10.1 A function-like configuration macro
If our macro did not use a full path, those users would be greeted with a `error` caused by `std::collections::HashMap` expecting generic arguments the local one does not have:
rust
error[E0107]: this struct takes 0 generic arguments but 2 generic arguments were supplied

This is something we have to avoid because the chance of a collision with the application code and library code grows with the size of both the project and our macro. So it’s good practice to always use full paths in generated code. Even when it comes to things included in Rust’s prelude (like std::vec::Vec), this may be worthwhile, because even these might not be available in certain environments or might be overridden by things declared in application code.

Throughout this book, I have often used String as a type and not string slices (&str), partly because String is an easy and familiar type and, sometimes, because it was the only correct choice. In several other cases, strings helped avoid complexity that was irrelevant to the discussion.

But just for this once, let’s consider string slices, since they are a valid alternative and not that difficult to use in this particular example. After all, we are generating a new method that has the same parameter values baked in. Those literals are static, meaning we can have slices with static lifetimes: &'static [String]. From that signature, only generate_config has to change, and it no longer requires &mut to take:

fn generate_config(path: &[String], values: &[String]) -> Vec<String> {
let mut result = Vec::new();
for (key, value) in path.iter().zip(values.iter()) {
result.push(format!("{}: {}", key, value));
}
result
}
fn main() {
let path = vec!["key1".to_string(), "key2".to_string()];
let values = vec!["value1".to_string(), "value2".to_string()];
let config = generate_config(&path, &values);
println!("{}", config.join(", "));
}

And

fer- have ome bliss-

but it ermen- a dif- existing for our ome w

CHAPTER 10 Macros and the outside world

quote! {
pub struct Config(
pub std::collections::HashMap<String, String>
);
impl Config {
pub fn new() -> Self {
let mut map = std::collections::HashMap::new();
#(#inserts)*
Config(map)
}
}
}

Here, we generate the struct and implementation.

With that, we can generate a struct from configuration.

The one thing that’s new and interesting about this code is that we are using the full path for HashMap (e.g., struct Config(pub std::collections::HashMap<String, String>); and similar inside new). Why? There are two reasons.

First, HashMap is not included in the Rust prelude, so it will not be available by default in our user’s code. So without the full path, Rust won’t know where this type is coming from. This will cause our code to fail with an error and cause the compiler to suggest importing the standard HashMap:

error[E0412]: cannot find type `HashMap` in this scope
--> config-macro-usage/src/main.rs:5:5
|
5 | config!();
| ^^^^^^^^^^ not found in this scope

Think of what is happening. We are adding code to a Rust file in an application. And if we add struct Config(HashMap<String, String>), without the path, we are referring to a type that is unfamiliar within the user’s code, not our code. The users will have to fix the problem, probably by importing std::collections::HashMap. Maybe some of them even get lucky and there already is an import. In that case, they remain blissfully unaware of any macro compilation problems.

Still, user action is not a good outcome. Not only is it not very user friendly, but it also very directly exposes the fact that we are using a HashMap, which is an implementation detail we might like to hide if possible. With HashMap hidden, changing to a different type will be easier if that proves necessary, requiring no changes to existing application code. So by including the full path of things, we make life easier for our clients and enable the hiding of (some) implementation details.

The second reason is that users may already be using a HashMap but not the one we were expecting. Maybe they created a struct with the same name:

struct HashMap {}
<!-- page: 255 -->
# 10.1 A function-like configuration macro
If our macro did not use a full path, those users would be greeted with a confusing error caused by `std::collections::HashMap` expecting generic arguments, while the local one does not have:
error[E0107]: this struct takes 0 generic arguments but 2 generic arguments were supplied

This is something we have to avoid because the chance of a collision with the application code and library code grows with the size of both the project and our macro. So it’s good practice to always use full paths in generated code. Even when it comes to things included in Rust’s prelude (like std::vec::Vec), this may be worthwhile, because even these might not be available in certain environments or might be overridden by things declared in application code.

Throughout this book, I have often used String as a type and not string slices (str), partly because String is an easy and familiar type and, sometimes, because it was the only correct choice. In several other cases, strings helped avoid complexity that was not relevant to the discussion.

But just for this once, let’s consider string slices, since they are a valid alternative and not that difficult to use in this particular example. After all, we are generating a new method that has the hardcoded values baked in. Those literals are static, meaning we can have slices with static lifetimes: struct Config(pub std::collections::HashMap<&'static str, &'static str>). Apart from that signature, only generate_insert has to change, as it no longer requires to_string calls:

fn generate_inserts(yaml_values: HashMap<String, String>)
-> Vec<TokenStream> {
yaml_values.iter().map(|v| {
let key = v.0;
let value = v.1;
quote!(map.insert(#key, #value);)
}).collect()
}
pub fn generate_config_struct(yaml_values: HashMap<String, String>)
-> TokenStream {
let inserts = generate_inserts(yaml_values);
quote! {
pub struct Config(
pub std::collections::HashMap<&'static str, &'static str>
);
// unchanged new method
}
}
<!-- page: 256 -->
## 10.2 Adding another macro
Currently, we are exposing a nice function-like macro. But what if our users prefer to modify an existing struct with an attribute macro, instead of generating a new struct? Well, why not offer this option as well? While a proc-macro library can only expose procedural macros (and not normal functions, structs, etc.), there is no limit to the number of macros one library can have, as seen briefly in section 9.9.
Now, let's do this ourselves. We won't show the new usage examples or tests, focusing only on what has changed in the macro directory. We reuse the ConfigInput struct for parsing the attribute TokenStream. If it contains a custom path (`(path = _)`), we can automatically handle that. To retrieve relevant details of the annotated struct, we turn to DeriveInput, for the same reasons as before (i.e., it is available by default and suits our use case), passing it into the output generator.
### Listing 10.9 An additional macro
rust
#[proc_macro_attribute]
pub fn config_struct(attr: TokenStream, item: TokenStream)
-> TokenStream {
let input: ConfigInput = parse_macro_input!(
attr
);
let ast: DeriveInput = parse_macro_input!(
item
);
match find_yaml_values(input) {
Ok(values) => generate_annotation_struct(ast, values)
.into(),
Err(e) => e.into_compile_error()
.into()
}
}

input.rs has not changed at all; it just works. But output.rs has to generate a different kind of output: it needs to recreate the struct, its new method, and field declarations.

// imports and earlier code
fn generate_fields(yaml_values: &HashMap<String, String>)
-> Vec<TokenStream> {
yaml_values.iter().map(|v| {
let key = Ident::new(v.0, Span::call_site());
quote! {
pub #key: String
}
}).collect()
}
<!-- page: 257 -->
fn generate_inits(yaml_values: &HashMap<String, String>)
-> Vec<TokenStream> {
yaml_values.iter().map(|v| {
let key = Ident::new(v.0, Span::call_site());
let value = v.1;
quote! {
#key: #value.to_string()
}
}).collect()
}
pub fn generate_annotation_struct(
input: DeriveInput,
yaml_values: HashMap<String, String>
) -> TokenStream {
let attributes = &input.attrs;
let name = &input.ident;
let fields = generate_fields(&yaml_values);
let inits = generate_inits(&yaml_values);
quote! {
#(#attributes)*
pub struct #name {
#(#fields,)*
}
impl #name {
pub fn new() -> Self {
#name {
#(#inits,)*
}
}
}
}
}
By now, all of this is child's play—except that I forgot for a moment that I had to turn the keys into identifiers, meaning I was greeted by an expected identifier error. Make sure to use Ident from proc_macro2 as well. If your IDE selects the one from proc_macro, you will be warned that the trait bound proc_macro::Ident: ToTokens is not satisfied. quote expects a ToTokens implementation to change your code into a TokenStream. And that implementation is missing from the other kind of Ident.
With this bit of code in place, we can choose between config! or #[config_struct]—or both! But that is probably not advisable.
# 10.3 Features
One downside of having multiple macros that do the same work is that we are forcing users to pull in a lot of code that they might not need. To avoid that, we can turn to features. You are probably familiar with them, but just to be sure: features—sometimes also called feature flags—allow us to make parts of our code optional. Only if users
<!-- page: 258 -->
decide they want a specific feature and activate it will that part of the library be pulled into our project.
Let's make the attribute macro optional, hiding it behind a feature called struct (because we need a struct to use it). First, we add it to the macro's Cargo.toml.
## Listing 10.11 Features in Cargo.toml
toml
[features]
struct = []

Next, to make things simpler, we move all the code-generating functions (generate_fields, generate_inits, generate_annotation_struct) for the attribute macro from output.rs to a separate file. Call it struct_output.rs.

Now we add feature configuration to our library. The entry point for our attribute macro is now annotated with #[cfg(feature = “struct”)], meaning it will only be included when the struct feature is enabled. We can do the same for the DeriveInput import. More importantly, our new file/module struct_output is only imported when the feature is active. This is why we moved those functions to a separate file: it enables hiding all three in one go. To avoid one additional import, I have used the full path for the import of struct_output::generate_annotation_struct.

// other imports, mod input, mod output
#[cfg(feature = "struct")]
use syn::DeriveInput;
#[cfg(feature = "struct")]
mod struct_output;
// find_yaml_values
// function-like macro
#[cfg(feature = "struct")]
#[proc_macro_attribute]
pub fn config_struct(attr: TokenStream, item: TokenStream)
-> TokenStream {
let input: ConfigInput = parse_macro_input!(attr);
let ast: DeriveInput = parse_macro_input!(item);
match find_yaml_values(&input) {
Ok(values) => struct_output::generate_annotation_struct(
ast, values, &input.exclude_from
).into(),
Err(e) => e.into_compile_error().into()
}
}

The imports are now only activated when the “struct” flag is set.

The same goes for our macro entry point.

Full path for this, or else we would need an additional feature-dependent import

You can verify the correctness of our code by running this code in config-macro-usage.

<!-- page: 259 -->
# 10.3 Features
## Listing 10.13 A usage example
rust
use config_macro::config_struct;
#[config_struct]
#[derive(Debug)]
struct ConfigStruct {}
fn main() {
let config = ConfigStruct::new();
println!("{}", config:?);
}

Adds a Debug derive to enable printing

This will fail because the attribute macro is now unknown. The function-like macro, on the other hand, would keep on working. Change the dependency on our macro library to config-macro = { path = "../config-macro", features = ["struct"] }, and everything works again.

This does mean that users who prefer this macro over the function-like one are unable to exclude the latter. So we could hide it behind a feature as well—maybe called functional. Does this mean our code would, by default, expose no macros (which is technically allowed but still pretty strange)? In that case, adding a default feature could be a good idea. That way, users can get rid of it with config-macro = { path = "../config-macro", features = ["struct"], default-features = false }, but we still expose at least one macro by default:

[features]
default = ["functional"]
struct = []
functional = []

That covers keeping out unneeded library code. But what about the code that we are generating? Let’s suppose that the attribute macro also generated a From implementation for our struct, which allowed turning it into a HashMap, just in case someone prefers that over accessing fields:

let cfg = MyConfigStruct::new();
let as_map: HashMap<String, String> = cfg.into();

Not everyone is going to use that method, but as things stand, it is being generated nonetheless.

NOTE Yes, Rust might decide to optimize your code by removing unused functions and the like. But there is no guarantee that this will happen. And it still takes time to get rid of unused code. So not having it in the first place can be worthwhile.

Maybe we can avoid that. One option would be to add an attribute to our macro that signifies we want to exclude some code generation. Let’s call it exclude. For the

moment, the only allowed value is from, which will make sure the From implementation is not generated:

#[config_struct(exclude = "from")]
struct ConfigStruct {}

To support this attribute, we need to alter our input.rs parsing a bit. We add the exclude keyword, an exclude_from Boolean property, and code to parse the exclude. If its string value equals from, we set the property to true. In every other case, it is false. The code in the following listing has the downside of only allowing a single property: either path or exclude. Take a look at the exercises if you want to fix that.

Listing 10.14 An additional property for ConfigInput

Section titled “Listing 10.14 An additional property for ConfigInput”
// syn imports
pub(crate) mod kw {
syn::custom_keyword!(path);
syn::custom_keyword!(exclude); // We add the "exclude" keyword.
}
#[derive(Debug)]
pub struct ConfigInput {
pub path: Option<String>,
pub exclude_from: bool, // And we need an additional property to capture the exclusion information.
}
impl Parse for ConfigInput {
fn parse(input: ParseStream) -> syn::Result<Self> {
if input.is_empty() {
// similar to earlier code; exclude is false
} else if input.peek(kw::path) {
// similar to earlier code; exclude is false
} else if input.peek(kw::exclude) {
let _: kw::exclude = input.parse()?;
.expect("checked that this exists");
let _: Token!(=) = input.parse()?;
.map_err(|_| syn::Error::new(
input.span(),
"expected equals sign after path"
))?;
let value: LitStr = input.parse()?;
.map_err(|_| syn::Error::new(
input.span(),
"expected value after the equals sign"
))?;
let exclude_from = value.value() == "from"; // If the keyword is present and matches the string "from," sets the property to true.
Ok(ConfigInput {
path: None,
exclude_from,
})
}
}
}
<!-- page: 261 -->
// error case
}
The other changes are located in struct_output.rs. Two functions (generate_inserts_for_from and generate_from_method) help us generate the proper From. Meanwhile, generate_annotation_struct receives a Boolean from lib.rs, where we pull it from ConfigInput. Based on its value, we either call the new functions to generate output or generate an empty token stream. The generated code/empty stream is passed on to our final quote.
**Listing 10.15 Additional methods and changes in struct_output.rs**
// imports, generate_fields, generate_inits
fn generate_inserts_for_from(yaml_values: &HashMap<String, String>) -> Vec<TokenStream> {
yaml_values.iter().map(|v| {
let key = v.0;
let key_as_ident = Ident::new(key, Span::call_site());
quote!(map.insert(#key.to_string(), value.#key_as_ident);)
}).collect()
}
fn generate_from_method(
name: &Ident,
yaml_values: &HashMap<String, String>
) -> TokenStream {
let inserts = generate_inserts_for_from(yaml_values);
quote! {
impl From <#name> for std::collections::HashMap<String,String> {
fn from(value: #name) -> Self {
let mut map = std::collections::HashMap::new();
#(#inserts)*
map
}
}
}
}
pub fn generate_annotation_struct(
input: DeriveInput,
yaml_values: HashMap<String, String>,
exclude_from_method: &bool
) -> TokenStream {
// all the other token streams
let from = if !exclude_from_method {
generate_from_method(name, &yaml_values)
} else {
quote!()
};
quote! {
Generates the From if the Boolean is false, or else gives back an empty stream
}
}
<!-- page: 262 -->
CHAPTER 10 Macros and the outside world
rust
// struct and method generation
#from
}

The one advantage of using this alternative is that it is extremely flexible. After all, it’s handcrafted code—it could do anything. We could, say, retrieve some environment variables, compare them with a local file, and determine what to generate based on the outcome. But in many cases, including this one, you can accomplish your goals with a feature (see the exercises). And you should probably prefer built-in tooling over custom solutions unless you have a very good reason not to.

NOTE In Rust, features should be additive, meaning they add functionality but never disable functionality that was already present in the crate. Cargo relies on this when resolving dependencies. Our macro obeys that rule, as its two features (struct and functional) add macros. But if, theoretically, we used a feature to exclude a From implementation that was present in the default set, we would be breaking this rule.

If you want to write a macro that other people will use, documentation is essential. No one likes exploring a crate or project that leaves you in the dark when it comes to usage. And while it is not my job to tell you what is worthwhile documenting—that depends on the situation—I can show you some of the available options.

Besides ordinary code comments (//) for internal use, we have outer documentation (///), which is used to document a single item. That is, we can add item-specific documentation to our macros. The following listing is a short example of the config macro.

Listing 10.16 Outer documentation for config

Section titled “Listing 10.16 Outer documentation for config”
/// This function-like macro will generate a struct called `Config`
/// which contains a `HashMap<String,String>` with all
/// the yaml config properties.
#[proc_macro]
pub fn config(item: TokenStream) -> TokenStream {
// implementation
}

If you run cargo doc --open, you will see that documentation was generated specifically for config.

We mentioned the existence of doctests in chapter 6. We can add one of them to our other macro. Because these tests are run when you do a cargo test, you should make sure they actually work—hence the import and the specific configuration path, since lib.rs is in a different location compared to my usage examples. And note the change I made to cfg. Without it, Rust did not generate documentation for this struct

because it was hidden behind a feature. Adding the doc profile is one way to make it visible.

Listing 10.17 Outer documentation for config_struct

Section titled “Listing 10.17 Outer documentation for config_struct”
/// This macro allows manipulation of an existing struct
/// to serve as a 'config' struct.
/// It will replace any existing fields with those present
/// in the configuration.
///
/// ```rust
/// use config_macro::config_struct;
///
/// #[config_struct(path = "./configuration/config.yaml")]
/// struct Example {}
///
/// // Example now has a new method
/// let e = Example::new();
///
/// // e now contains a 'user' field that we can access
/// println!("{}", e.user);
/// ```
#[cfg(any(feature = "struct", doc))]
#[proc_macro_attribute]
pub fn config_struct(attr: TokenStream, item: TokenStream)
-> TokenStream {
// implementation
}

The attribute is activated when the struct feature is active or the doc profile is active.

Now our documentation looks like the example in figure 10.1, with more information (like the previous test) available behind the hyperlinks.


Crate config_macro 📄

source · [-]

config
This function-like macro will generate a struct called Config, which contains a HashMap<String,String> with all the yaml configuration properties. The macro will also generate a new method for this struct, which will add the key-values to the struct

config_struct
This macro allows manipulation of an existing struct to serve as a ‘config’ struct. It will replace any existing fields with those present in the configuration. It will also generate a new method to fill in the fields (This macro has to be enabled using the ‘struct’ feature.)


Figure 10.1 Outer documentation with hyperlinks to the more detailed information

Meanwhile, inner documentation (//!) is used to document an entire file or crate. We could add the following to lib.rs:

//! ## Documentation from lib.rs
//! Here is documentation placed directly within lib.rs...
// imports, code

Another neat trick is that you can import documentation from an external Markdown document. That may keep your Rust files cleaner, avoid duplicating information, and prove easier to write. The following shows an example README.md file located in the config-macro directory:

# Config Macro
## Overview
This crate contains macros that allow you to transform yaml config into a struct that you can use in your application.
## Usage
Left out for brevity's sake.

We should now add this command to the top of our lib.rs:

#![doc = include_str!("../README.md")]
//! ## Documentation from lib.rs
//! Here is documentation placed directly within lib.rs.
// imports, code

The imported text will appear above the inline inner documentation. This gives us some general documentation for our crate, added above the specific (outer) documentation that we wrote earlier (see figure 10.2).

Our macro is now tested, handles errors responsibly, has documentation, and—also pretty important—does something people might find useful. Maybe it is time to publish it to crates.io with the cargo publish command.

NOTE Please don’t publish this example, though. I doubt the Rust community would appreciate hundreds of identical config macros with limited functionality.

This crate contains macros that allow you to transform yaml config into a struct that you can use in your application.

Call either the function-like config! macro or annotate a (preferably empty) struct with the attribute macro #[config_struct]. By default, the macro looks for configuration under configuration/config.yaml. This can be overwritten by using the ‘path’ attribute: config!(path = "a/path/to.yaml") or #[config_struct(path = "a/path/to.yaml")].

use config_macro::config;
config!(path = "../configuration/config.yaml");
// we can now call new and access the hashmap of values
let c = Config::new();

The annotation macro is hidden behind the ‘struct’ feature flag.

Currently only works with YAML files, and does not support nesting. So this works:

user: "admin"

But this won’t:

database:
user: "admin"

Furthermore, we will read all properties in the config as Strings.

Here is documentation placed directly within lib.rs…

  • config This function-like macro will generate a struct called Config, which contains a HashMap<String,String> with all the yaml configuration properties. The macro will also generate a new method for this struct, which will add the key-values to the struct
  • config_struct This macro allows manipulation of an existing struct to serve as a ‘config’ struct It will replace any existing fields with those present in the configuration. It will also generate a new method to fill in the fields (This macro has to be enabled using the ‘struct’ feature.)

Figure 10.2 Outer documentation

<!-- page: 266 -->
# CHAPTER 10 Macros and the outside world
Before we do that, we should add some more information to our `Cargo.toml` file in the `config-macro` directory. In the following listing, a selection of useful fields has been added.
## Listing 10.18 config-macro Cargo.toml additions
toml
[package]
name = "config-macro"
version = "0.1.0"
edition = "2021"
description = "Macros for using config as a struct within your app"
license = "MIT"
homepage = "https://github.com/some-page"
repository = "https://github.com/some-page"
readme = "README.md"
keywords = ["configuration", "yaml", "macro"]

This is actually the default, so adding it here is not required.

# dependencies, lib, features

In general, Rust advises not committing a Cargo.lock when you write a library, so it might be best to add that file to your .gitignore at this point. If you’ve already committed the file, remove it from your Git and update .gitignore afterward.

You may also have noticed that I’ve placed my documentation and publish information in the config-macro directory. The reason is that there is little use in publishing our usage or configuration directories. Those are for testing the library but offer no functionality, so you may want to publish the config-macro directory, not the entire project. Two final pointers: you will need credentials to publish to crates.io, and cargo publish has a -dry-run, which might be useful to try out first.

NOTE Publishing is one reason why we have chosen a setup with two directories for this chapter, as it is currently impossible to publish crates with path dependencies. This means that the “three directories” setup we showed in earlier chapters is harder to publish because, in that case, our macro entry point is in one library, and its implementation is pulled in via a path dependency. That does not make publishing in that scenario impossible, but until—if ever—publishing with path dependencies becomes allowed, it does create complications.

Once the crate is published and becomes stable, reaching version 1, developers will expect you to use semantic versioning (also known as semver) when you update your library. This means that bug fixes increase the patch version (e.g., 1.1.0 => 1.1.1), functionality that is backward compatible increases the minor (e.g., 1.1.0 => 1.2.0), and backward-incompatible changes increase the major version (e.g., 1.0.0 => 2.0.0). This is especially important in Rust because Cargo allows you to specify dependencies solely by major: trybuild = "1", for example. Introducing a breaking change without bumping the major version might cause projects to suddenly and unexpectedly break.

Many Rust crates have excellent documentation. Go to the lib.rs of the libraries we discussed in this book, and you will find both inner documentation for the crate and outer documentation for the most important functionality. I will let you explore their documentation on your own.

Instead, we can briefly talk about features and multiple macros. Have you ever had this happen? You add serde to a project and put a derive(Deserialize) on a struct, and Rust does not know what to do because you forgot that the macro is hidden behind a feature. Unsurprisingly, you will find the list of serde features under serde/Cargo.toml, including one called derive. This also activates the serde_derive dependency:

[features]
default = ["std"]
# Provide derive(Serialize, Deserialize) macros.
derive = ["serde_derive"]
# etc.

In serde/lib.rs, you find a reexport of the two derive macros, hidden behind that feature:

#[cfg(feature = "serde_derive")]
#[macro_use]
extern crate serde_derive;
#[cfg(feature = "serde_derive")]
pub use serde_derive::{Deserialize, Serialize};

Leptos, to take one other example, has a leptos_macro directory where lib.rs exports a derive macro (Params), two attribute macros (server and component), and two function-like macros (template and view). It has feature flags for things like server-side rendering and tracing.

To finish this final chapter, we will explore in detail how #[tokio::main] works from the beginning until the end. Under the tokio directory of the Tokio repository, we find a list of features, including the macros feature. It points to the tokio-macros dependency.

[features]
macros = ["tokio-macros"]
# ...
[dependencies]
tokio-macros = { version = "1.7.0", path = "../tokio-macros", optional = true }

Head to the tokio-macros directory. In its Cargo.toml, we find that this is indeed a procedural macro library (proc-macro = true), with the usual dependencies (syn, quote, and proc-macro2). Moving on to lib.rs, we see it exposes several attribute

macros, including #[tokio::test] and #[tokio::main]. Each macro has extensive outer documentation—about 170 lines of it, in the case of main. We can see that both the attributes and the decorated item of this attribute macro are used by the entry::main function. The workaround mentioned in listing 10.20 is an ambiguity caused by this function being called main. And, in Rust, that name serves a special purpose as an entry point.

Listing 10.20 lib.rs of the tokio-macros directory

Section titled “Listing 10.20 lib.rs of the tokio-macros directory”
/// Marks async function to be executed by the selected runtime.
/// ...
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
entry::main(args, item, true)
}

Within entry::main, the item is first parsed into an ItemFn. In other words, Tokio expects a function, turning a syn error into a compilation error if that is not the case. Next, and only after doing a few checks, the configuration is created based on the attributes that are parsed by AttributeArgs (which, as mentioned, is no longer available in syn version 2).

If both input and configuration are valid, parse_knobs will create an output stream.

Listing 10.21 The macro entry point in entry.rs

Section titled “Listing 10.21 The macro entry point in entry.rs”
pub(crate) fn main(args: TokenStream, item: TokenStream, multi_thread: bool)
-> TokenStream {
let input: syn::ItemFn = match syn::parse(item.clone()) {
Ok(it) => it,
Err(e) => return token_stream_with_error(item, e),
};
let config = if input.sig.ident == "main"
&& !input.sig.inputs.is_empty() {
let msg = "the main function cannot accept arguments";
Err(syn::Error::new_spanned(&input.sig.ident, msg))
} else {
AttributeArgs::parse_terminated
.parse(args)
.and_then(|args| build_config(
input.clone(),
args,
false,
multi_thread))
};
match config {
Ok(config) => parse_knobs(input, false, config),
Err(e) => token_stream_with_error(
parse_knobs(input, false, DEFAULT_ERROR_CONFIG),
e
)
}
}

Parses the input as a function or returns an error

If the function signature is valid, parses the attributes and builds the configuration

Produces output if both function and config are valid

<!-- page: 269 -->
# 10.6 From the real world
Listing 10.22 shows build_config, which we will have to show in two parts. After making sure the expected async keyword is present, a new, mutable configuration is created. Next, the code loops over the available arguments, adding its key-value pairs (NameValue) to the configuration, one by one. If an unknown identifier is found, an error is returned.
## Listing 10.22 build_config in entry.rs (part 1)
rust
fn build_config(
input: syn::ItemFn, args: AttributeArgs,
is_test: bool, rt_multi_thread: bool,
) -> Result<FinalConfig, syn::Error> {
if input.sig.asyncness.is_none() {
let msg = "the `async` keyword is missing ...";
return Err(syn::Error::new_spanned(input.sig.fn_token, msg));
}
let mut config = Configuration::new(is_test, rt_multi_thread);
let macro_name = config.macro_name();
for arg in args {
match arg {
syn::NestedMeta::Meta(syn::Meta::NameValue(namevalue)) => {
let ident = namevalue.path.get_ident()
.ok_or_else(|| {
syn::Error::new_spanned(
&namevalue,
"Must have specified ident"
)
})?
.to_string().to_lowercase();
match ident.as_str() {
"worker_threads" => {
config.set_worker_threads(
namevalue.lit.clone(),
syn::spanned::Spanned::span(&namevalue.lit),
)?;
}
// more matching
name => {
let msg = format!(
"Unknown attribute {} is specified ...",
name,
);
return Err(syn::Error::new_spanned(namevalue, msg));
}
}
}
// ...
}
}
}
<!-- page: 270 -->
# CHAPTER 10 Macros and the outside world
The next code listing shows that, despite Tokio only allowing key-value pairs for attributes, the match does check if path values are present. Why? To give back a helpful error! The given path attribute is checked against known names. That way, the error can give a hint on how you should set that particular argument. For example, adding `#[tokio::main(multi_thread)]` to a function results in error: Set the runtime flavor with `#[tokio::main(flavor = "multi_thread")]`. For unknown path arguments, as well as miscellaneous unrecognized arguments, a generic “unknown attribute” error is thrown, pointing to the correct token.
## Listing 10.23 build_config in entry.rs (part 2)
rust
fn build_config(
input: syn::ItemFn, args: AttributeArgs,
is_test: bool, rt_multi_thread: bool,
) -> Result<FinalConfig, syn::Error> {
// ...
syn::NestedMeta::Meta(syn::Meta::Path(path)) => {
let name = path
.get_ident()
.ok_or_else(|| syn::Error::new_spanned(
&path,
"Must have specified ident"
))?
.to_string()
.to_lowercase();
let msg = match name.as_str() {
"threaded_scheduler" | "multi_thread" => {
format!(
"Set the runtime flavor with ...",
macro_name
)
}
// same for other possible attributes and unknown ones
};
return Err(syn::Error::new_spanned(path, msg));
}
other => {
return Err(syn::Error::new_spanned(
other,
"Unknown attribute inside the macro",
));
}
}
config.build()

Tokio does not accept path arguments. But, if one is present, it tries to give back a helpful error.

A generic error for unknown arguments, pointing to the faulty token (other)

parse_knobs is also too long to show in full, so I have left out some things that are only relevant for the test macro and some code for handling a rename of the tokio package. First, the signature of the input is modified, removing the async. This is because Rust does not allow its main functions to be asynchronous. So, after removing

the async, Tokio builds a Runtime and blocks on the existing code (contained within body), removing the need for asynchronicity. Two more things to note:

  • The header is optionally generated, depending on the incoming Boolean value, similar to what we did in this chapter with exclude.
  • Some Clippy linting is disabled, like a warning for the use of expect in the building of Runtime. You do not want to show users a warning that they can’t do anything about.
fn parse_knobs(mut input: syn::ItemFn, is_test: bool, config: FinalConfig)
-> TokenStream {
input.sig.asyncness = None;
let mut rt = // ...
if let Some(v) = config.worker_threads {
rt = quote! { #rt.worker_threads(#v) };
}
// more config
let header = if is_test {
quote! {
#[::core::prelude::v1::test]
}
} else {
quote! {}
};
let body = &input.block;
let brace_token = input.block.brace_token;
let body_ident = quote! { body };
let block_expr = quote_spanned! {last_stmt_end_span=>
#[allow(clippy::expect_used,
[clippy::diverging_sub_expression])]
{
return #rt
.enable_all()
.build()
.expect("Failed building the Runtime")
.block_on(#body_ident);
}
};
input.block = syn::parse2(quote! {
{
#body
#block_expr
}
}).expect("Parsing failure");
input.block.brace_token = brace_token;
let result = quote! {
#header
#input

Creates the basic runtime configuration

Adds some additional information if it is present

The header is conditionally added to the generated code.

Builds the Runtime and blocks on the existing content of the function

CHAPTER 10 Macros and the outside world

};
result.into()
}

Returns after adding everything to result

With that, you know—in broad terms—how this quite famous macro does its work.

Congratulations on making it to the end of this book! Together, we have explored declarative and procedural macros in a wide variety of use cases. Sometimes we added methods to structs and enums; in other cases, we changed their fields or modified function signatures and returns. Plus, you also learned about testing, error handling, and documentation and saw a lot of real-world examples.

That being said, some interesting tools and functions did not make the cut. syn-structure (https://docs.rs/synstructure/latest/synstructure), for example, is a tool that helps you implement derive macros. proc-macro-crate (https://crates.io/crates/proc-macro-crate) helps you find the name of the crate that your macro is declared in, even if it was changed in the user’s application. And hidden behind syn feature flags are visit (https://docs.rs/syn/latest/syn/visit/index.html) and fold (https://docs.rs/syn/latest/syn/fold/index.html), two powerful helpers for stepping through nodes like an expression. You will find some information on how to use those two in the documentation. You can also check out the blog post (https://mng.bz/DdjR) I wrote about Fold for some inspiration or guidance. Plus, there are lots more libraries that use macros in unusual, interesting, creative ways, that are ready to be explored. If you run into trouble, you will find a lot of helpful people ready to answer macro questions on both Stack Overflow and Reddit.

Thank you for reading. I hope all of this was of some use to you. And, to end with the words of AWS’s Werner Vogels: “Now go build!”

See the appendix for solutions.

  1. Make sure that we can accept both path and exclude as macro properties.
  2. Instead of adding exclude to our attribute macro, use a feature.
  • A macro library can only export procedural macros, but there is no limit on number or type.
  • Features can hide optional functionality, making sure users only pull in the library code that they need.
  • When it comes to avoiding useless generated code, you can use feature flags or your own custom attributes.
  • A production-grade macro should have good test coverage and error handling.
  • It should also have proper documentation, preferably including doctests.