Hiding information and creating mini-DSLs with function-like macros
local graph
Chapter 6 — Hiding information and creating mini-DSLs with function-like macros
Section titled “Chapter 6 — Hiding information and creating mini-DSLs with function-like macros”5 Hiding information and creating mini-DSLs with function-like macros
Section titled “5 Hiding information and creating mini-DSLs with function-like macros”This chapter covers
Section titled “This chapter covers”- Hiding information to improve code
- Using function-like macros to modify and extend code
- Using function-like macros to manipulate structs and functions
- Debugging macros by getting the compiler or IDE to help you
- Writing DSLs with flexible function-like macros
- Deciding what macro fits a use case
The third and final type of procedural macro is the function-like macro, which—unlike the other two—is not limited to annotating structs, enums, and the like. Here, two examples will demonstrate its power. In our first example, we will stay close to familiar grounds by sticking to manipulating structs. Wilder experiments can wait until later in this chapter when we take another look at composing functions.
5.1 Hiding information
Section titled “5.1 Hiding information”Like a professional skateboarder or a sophist trying to impress an Athenian audience, we will do a cool 180 flip: instead of telling you to expose fields, this time we will argue that you need a macro to hide them. This is not as strange as it sounds, since the answer to every question in programming is, “It depends.” Yes, as we mentioned in the previous chapter, structs with public fields are great when you just want to transfer information between systems. But in many other cases, structs and classes are more at ease with hiding information. This makes code easier to understand and reason about. If, for example, a module exposes only a single function to accomplish a task, you may never need to learn anything about the potentially hundreds of methods, structs, and variables that it needs to accomplish its work. Not having to take into account all the implementation details makes your life easier.
Another related reason for hiding fields is safety. Granted, this is less of a problem in Rust, because the compiler is very good at detecting dangerous (mutating) actions. But in languages like Java, C#, or JavaScript, you’d be wise to hide fields and methods so nobody can change them and mess things up. This becomes even more important in an environment where multiple threads could access the same objects and mutate them, causing all kinds of weird problems—hence the reason for functional programming’s focus on immutability. If your objects cannot be manipulated by others, your code is safer and easier to understand.
Even in Rust, these practices have their place, at the very least from the perspective of easier reasoning about code. In fact, the language provides programmers with very good tooling for hiding information in structs, files, modules, etc. Information hiding is clearly dear to the creators’ hearts. Thus, our first example will focus on writing a macro that adds methods for allowing immutable access to fields via references. This is useful when structs contain fields that should be consulted or used but not manipulated.
5.1.1 Setup of the information-hiding macro
Section titled “5.1.1 Setup of the information-hiding macro”The Cargo.toml and project structure remain the same as before, except this time the name of the nested directory (the macro) is private-macro. That means the outer directory (the application) will have to import this dependency with private-macro = { path = "./private-macro" }. lib.rs and main.rs require more changes. main.rs is shown in the following listing.
Listing 5.1 Our application code
Section titled “Listing 5.1 Our application code”use private_macro::private; // An import activates our macro.
private!( struct Example { string_value: String,We call the macro by writing its name followed by an exclamation mark. We pass along any relevant data.
80 CHAPTER 5 Hiding information and creating mini-DSLs with function-like macros
number_value: i32,});
fn main() { let e = Example { string_value: "value".to_string(), number_value: 2, }; e.get_string_value(); e.get_number_value();}Once we have an instance, we can use the generated methods to get references to our fields (a &String and a &i32).
Instead of decorating a struct with the derive annotation, we call a function-like macro by writing its name followed by an exclamation mark and passing on useful data between parentheses. This is similar to how a declarative macro is used, which also means it can be hard to see the difference between these two. And to make the two even more indistinguishable, Rust also allows you to choose between parentheses, square brackets, and curly braces for arguments. Since we want to add a method to a struct, we simply pass in the entire struct as an argument. Next, inside the main function, we expect that we can build the Example struct and call its generated methods.
On to lib.rs: the following listing shows the first version of our code. Can you spot the essential differences from derive/attribute macros?
Listing 5.2 First version of our macro implementation
Section titled “Listing 5.2 First version of our macro implementation”use quote::quote;use proc_macro::TokenStream;use syn::{parse_macro_input, DeriveInput};
#[proc_macro]pub fn private(item: TokenStream) -> TokenStream { let ast = parse_macro_input!(item as DeriveInput); let name = ast.ident;
quote!( struct #name {} impl #name {} ).into()}A function-like macro requires #[proc_macro]. The macro name is determined by the name of the decorated function.
The output replaces the input, so we recreate the struct in our output.
The “getter” methods that we will generate will be added to this impl.
First, we have #[proc_macro] instead of #[proc_macro_derive(Hello)] or #[proc_macro_attribute]. And since we cannot define the name explicitly, the function name (i.e., private) will do.
Next, unlike attribute macros—but like derive macros—we only receive one parameter. That is because the additional TokenStream contained information about the attribute you were creating, and function-like macros do not create a custom attribute.
5.1 Hiding information
Section titled “5.1 Hiding information”Finally, function-like macros are similar to their attribute brothers—and different from derives—in that their output tokens replace the input (see figure 5.1). And it makes perfect sense for the input of a function-like macro to replace the output. With other macros, we receive structured data (a struct, an enum), but a function-like macro allows you to pass in anything, even stuff that is not valid Rust. If that input were to remain in your source code, the compiler would complain loudly about invalid syntax, which is probably not what you want.
[!visual-conversion] Diagram showing a function-like macro signature with labeled parts: macro … Cropped from the scan (PDF page 091, printed p. ?): Diagram showing a function-like macro signature with labeled parts: macro name, input TokenStream, and output TokenStream replacing input.
Figure 5.1 The signature of a function-like macro
That means we have to recreate the struct we gave to the macro. In our current version, we take the name and use it to create an empty struct and empty implementation.
5.1.2 Recreating the struct
Section titled “5.1.2 Recreating the struct”As it stands, our application will not compile, even if we comment out the method calls—because the fields are gone! That’s a major déjà vu: we are once again deleting things that were already there. Bad, macro, bad! So let’s improve our code by fixing the struct recreation. This is pretty easy to fix: just give back what you receive when you create your output. There are at least two ways to do this: we either return the incoming TokenStream in our output or we give back the AST.
In the code in listing 5.3, we choose the first approach. Because the incoming stream is moved by parse_macro_input, we clone the stream and use the Into trait to change the built-in TokenStream into a type that implements the ToTokens trait required by the quote macro. Once we have our transformed clone, all that remains is to pass it to the output.
Listing 5.3 Second version of our macro implementation
Section titled “Listing 5.3 Second version of our macro implementation”// imports
#[proc_macro]pub fn private(item: TokenStream) -> TokenStream {
<!-- page: 092 -->
82 CHAPTER 5 Hiding information and creating mini-DSLs with function-like macros
rustlet item_as_stream: quote::__private::TokenStream = item .clone() .into();let ast = parse_macro_input!(item as DeriveInput);let name = ast.ident;
quote!( #item_as_stream impl #name {}).into()Clones the incoming (standard) TokenStream and turns it into a private TokenStream that implements ToTokens
Passes this clone to the output
The AST path is even simpler, since (a) DeriveInput implements ToTokens and (b) we can use a reference to retrieve the name of the struct, thus avoiding a partial move. So the latter approach is actually preferable. Alternatively, you could also solve the deletion problem by not having it in the first place. As it currently stands, there is no reason for us to pass in the entire struct—so we could just pass in the name of the struct. But in this particular example, that will not work, as we will soon find out.
Partial moves
Section titled “Partial moves”A partial move is one of those tricky Rust topics, right up there with—well—macros. In essence, this is an example of Rust being conservative with ownership and forcing you to think carefully about what you do with it. Say we have a struct and a function that steals things:
#[derive(Debug)]struct Car { wheels: u8, gps: String, infotainment: String,}
fn steal(item: String) { println!("I am stealing {}", item);}
fn main() { let car = Car { wheels: 4, gps: "Garmin".to_string(), infotainment: "Android".to_string(), }; println!("My car before the theft: {:?}", car); steal(car.gps); // println!("My car after the theft: {:?}", car); // does not compile}This code runs. But add the final println, and Rust starts complaining about a partial move. What is happening? Well, steal takes a property, the gps, from the car. By
5.1 Hiding information
Section titled “5.1 Hiding information”taking that string as an argument, it is “moved” into the function, thereby making the function the sole owner of that string. So the GPS is now the property of steal (and will be dropped after the println statement inside that function finishes executing).
When we get to the final commented-out print, the compiler complains: “You are asking me to print this car and all its properties. But how can I print the GPS when someone already stole—and dropped—it?” Regretfully, the compiler is right: ownership of a part of the struct has been moved—meaning the struct can no longer be used, though we can still retrieve (and, for example, print) any values that haven’t moved yet, like infotainment. A simple solution for avoiding partial moves is to clone. If we create a clone of car and steal the GPS from there, our original is still fine and printable. Cloning has performance implications, but sometimes it might be the only solution. A better solution is to use references whenever possible. At the very least, that will minimize the number of times you need a clone. Other times, you can pull a clever trick, like using take on an Option:
#[derive(Debug)]struct Car { wheels: u8, gps: Option<String>, infotainment: String,}
// steal function unchanged
fn main() { let mut car = Car { wheels: 4, gps: Some("Garmin".to_string()), infotainment: "Android".to_string() }; println!("My car before the theft: {:?}", car); steal(car.gps.take().unwrap()); // works, though the gps is now missing (None) println!("My car after theft: {:?}", car);}But for us mortals, using references where possible and only cloning when needed are a great start!
5.1.3 Generating the helper methods
Section titled “5.1.3 Generating the helper methods”Now we can focus on generating methods, and the code in listing 5.4 shows a mix of mostly familiar building blocks. Since the methods return references to the fields and their names are based on those fields, we need to extract field information to generate these new methods. This is the reason why only passing in the name, as suggested earlier, will not work: our macro needs more detailed knowledge of the struct. So we will iterate over the fields and map each one to a stream of tokens containing code for one method. In the solution to an exercise from the previous chapter (you’ve solved all
<!-- page: 094 -->
84 CHAPTER 5 Hiding information and creating mini-DSLs with function-like macros
those, right?), we had an ugly return type (Map<Iter<'a, Field>, fn(&'a Field) -> quote::__private::TokenStream>). That is why we use a collect this time, which allows us to return a nice, clean Vec.
That’s the overview. Now focus on the code inside map. Besides the field name and type, we want to create a method name that consists of the field name prefixed with get (e.g., get_string_value). You might think that the solution is simply to generate a string with that exact value. Sadly, passing a string to quote will generate an error—for example: expected identifier, found "get_string_value".
In retrospect, the reason is obvious. We are outputting a stream of tokens and asking Rust to add it to our code. Rust starts checking the code, including the parts we generated, and finds the keyword fn. That can only mean that the next token is a function name, which is always of type identifier. Instead it finds a string (get_string_value).
For the same reason, we need field_name to be an identifier, since we will use it to get a reference (&self.field_name), and Rust would complain if we tried to get a field from self using a string.
So we need an identifier. We can create one with a constructor (the new method), which requires two arguments: a string reference—which we have—and a span. In an earlier chapter, we mentioned that spans are a way to link back to the original code, which is useful for reporting errors to the user. When you create a new identifier, Rust wants to know what it should reference in the original code if something goes wrong. There are several ways to create a suitable span for our method name:
- One simple and valid option is to take the field_name span and reuse it for our method name. Reusing spans is also useful when you want to “link” an existing piece of code with generated code.
- call_site() is one of the associated functions of Span. This span “will be resolved as if . . . written directly at the macro call location,” meaning it resolves at the place where you invoke the macro—the application code.
- mixed_site() is another associated function. The difference is that it obeys the same hygiene rules as a declarative macro. Depending on the role of the identifier, the span will resolve at either the place of invocation (call site) or the location where the macro was defined. The pull request author (https://github.com/rust-lang/rust/pull/64690) thought it was a sensible default since it provides some additional safety. Still, it does not really match our intent here. We actually want our generated methods to be used within the application.
<!-- page: 095 -->
# 5.1 Hiding information
## More on call_site and mixed_site
Okay, so maybe the difference between `call_site()` and `mixed_site()` is not clear yet. Some code will help. Say we had a macro that generated a local variable and decided to use `mixed_site` for the span of the variable’s identifier:
rust#[proc_macro]pub fn local(_: TokenStream) -> TokenStream { let greeting = Ident::new("greeting", Span::mixed_site()); quote!( let #greeting = "Heya! It's me, Imoen!"; ).into()}We can now call the macro and try to print the variable. Note that this particular macro is invoked inside a function, not outside, as local variables can only exist within functions:
fn main() { local!(); println!("{}", greeting);}This will cause an error telling you that greeting was not found in this scope. What went wrong? As you probably suspect, it’s because of hygiene. As stated, mixed_site has the same hygiene rules as declarative macros. And in declarative macros, local variables are not exposed to the outside world. In the parlance of the documentation: a local variable’s span only exists “at the definition site” of the macro but not at the call site, which is, in our case, the main function. Change the greeting span to call_site, and the application compiles and runs. Now the span exists at the place of invocation, main, where we are trying to print it.
I can almost hear some curious reader wondering what quote is doing. After all, we could have used it to generate the right span for us:
#[proc_macro]pub fn private(item: TokenStream) -> TokenStream { quote!( let greeting = "Heya! It's me, Imoen!"; ).into()}And this works automatically, meaning quote probably uses call_site, which it does. From the source code:
pub fn push_ident(tokens: &mut TokenStream, s: &str) { let span = Span::call_site(); push_ident_spanned(tokens, span, s);}
<!-- page: 096 -->
Back on topic: while all three options could work, we have gone with `call_site()` for our example. Besides creating a name, we also retrieve the field identifier and field type. These three variables are then used to generate the method (see figure 5.2).
## Listing 5.4 A method for generating methods
rust// other importsuse syn::{DataStruct, FieldsNamed, Ident, Field};use syn::__private::{Span, TokenStream2};use syn::Data::Struct;use syn::Fields::Named;
fn generated_methods(ast: &DeriveInput) -> Vec<TokenStream2> { let named_fields = match ast.data { Struct( DataStruct { fields: Named( FieldsNamed { ref named, .. }, .. ), .. } => named, _ => unimplemented!( "only works for structs with named fields" ), );
named_fields.iter() .map(|f| { let field_name = f.ident.as_ref().take().unwrap(); let type_name = &f.ty; let method_name = Ident::new( &format!("get_{}", field_name), Span::call_site(), );
quote! { fn #method_name(&self) -> &#type_name { &self.#field_name } } }) .collect() }}This is code from an earlier chapter, where we had to retrieve fields to make them public.
We need the name and type of the field to generate the method.
We generate the method name as an identifier using format and new.
We use method_name, field_name and type_name to generate the method.
This is optional: to get a simple Vec return type, we collect the results.
<!-- page: 097 -->
# 5.1 Hiding information
## Figure 5.2 Mapping our first field from the Example struct

> [!visual-conversion] Flowchart showing field processing to generate TokenStream and method code> Cropped from the scan (PDF page 097, printed p. ?): Flowchart showing field processing to generate TokenStream and method code
Now all we have to do is call the function and pass the result to the generated impl block. Remember, we have a vector of token streams to add, so we need to use the correct notation to tell this to quote: `#(#name_of_variable)*`. Previously, we had a comma in there because fields are separated by commas. That is not the case for method declarations. With our macro fully up to date, the code should compile.
### Listing 5.5 Using our new method in our macro
rust// imports
#[proc_macro]pub fn private(item: TokenStream) -> TokenStream { let item_as_stream: quote::__private::TokenStream = item.clone() .into(); let ast = parse_macro_input!(item as DeriveInput); let name = &ast.ident; let methods = generated_methods(&ast); // Generates the method token streams quote! { #item_as_stream }}<!-- page: 098 -->
88 CHAPTER 5 Hiding information and creating mini-DSLs with function-like macros
rustimpl #name { #(#methods)*}).into()Adds all of them to our implementation block
There are still some loose ends to tie up: the methods we are generating are not public, the fields can still be accessed directly (not safe!), and we should also have a (new) method for creating a struct with private fields. We leave all that for the exercises.
5.2 Debugging by writing normal code
Section titled “5.2 Debugging by writing normal code”At times, you can get confusing or unfamiliar error messages from your macro without having a clue of what to do next. Rereading the error message carefully might help (yes, this section contains some “well, duh” advice), but if that does not help, another option is to write what you want to generate as normal code. That’s because most of what you put between the quote parentheses is accepted as the truth of God by IDEs and compilers (at least until you try to use it in an application)—a serious downside for everyone who, like me, counts on IDE support to avoid stupid mistakes. Luckily, once you try to create the same piece of code in ordinary Rust, your tooling has your back again. As an example, say I had written the following piece of code for our “private” macro:
quote! { fn #method_name(&self) -> #type_name { self.#field_name }}This is the (abbreviated) error that I would get:
error[E0507]: cannot move out of `self.string_value` which is behind a shared reference 3 | / private! { 4 | | struct Example { 5 | | string_value: String, 6 | | number_value: i32, 7 | | } 8 | | }; | |_^ move occurs because `self.string_value` has type `String`, which does not implement the `Copy` traitIf that error message does not “click” for me, I might be stuck. Somewhere in my generated code, something is going wrong. But what? Instead of staring at my macro or the message, what if I just wrote the method I wanted to generate for a dummy struct, based on the piece of code that I am passing to quote?
struct Test { value: String}
<!-- page: 099 -->
impl Test { fn get_value(&self) -> String { self.value }}
Well, if I did that, my IDE would start pointing me to `self.value` as the source of my problems. After adding an ampersand, it would point out that there is a mismatch with the returned type. Step by step, the errors melt away, putting us in a better place to continue work on the macro.
A final piece of obvious but still valuable advice is to work step by step, as we have done in these last few chapters. If there is a problem right after adding a single piece of functionality, the source of the error is obvious. And the satisfaction of already having something up and running is a nice bonus.
## 5.3 Composing
We saw how to use a function-like macro as a stand-in for a derive (or attribute) macro. Now let’s turn to an example where function-like is the *only* good fit. In an earlier chapter, we talked about composition and how to write a declarative macro for composing functions. We also talked about limitations in the symbols we could use for chaining expressions together in declarative macros (i.e., we could not mimic Haskell, which allows for composing functions by using `..`, though we also explained that the `tt` type does not suffer from the same limitations). The second example of this chapter is composition. But this time *we will have our dots*.
Again, we won’t go over the entire setup. You’ve seen it all before. Instead, take a look at the application code in `main.rs`, where we see two of the example functions from chapter 2, “Declarative macros.” Inside `main` we combine these functions with dots (`.`) using the `compose` macro that we are going to write. Note that it would not be possible to pass this info to a derive or attribute macro, because those two expect a struct, enum, function (i.e., a bit of valid Rust code).
### Listing 5.6 Our application, featuring some familiar functions
rustuse function_like_compose_macro::compose;
fn add_one(n: i32) -> i32 { n + 1}
fn stringify(n: i32) -> String { n.to_string()}
fn main() { let composed = compose!( add_one . add_one . stringify );}We use
compose, our function-like macro, to combine three functions.
90 CHAPTER 5 Hiding information and creating mini-DSLs with function-like macros
println!("{:?}", composed#E);}How does this work? Turn to lib.rs. (Because there is a bit more code than usual—about 60 lines—we will first look at the macro entry point in isolation.) First, we parse the input into a custom struct of type ComposeInput. DeriveInput is ill equipped to deal with our current input, since we are definitely not receiving a struct or enum as input. More generally, this kind of composing is not natively supported by Rust, so there is no reason to assume that a prebuild parser would be able to handle it for us.
Listing 5.7 Our compose macro entry point
Section titled “Listing 5.7 Our compose macro entry point”#[proc_macro]pub fn compose(item: TokenStream) -> TokenStream { let ci: ComposeInput = parse_macro_input!(item); // Parses our input into a custom struct
quote!({ fn compose_two<FIRST, SECOND, THIRD, F, G>(first: F, second: G) -> impl Fn(FIRST) -> THIRD where F: Fn(FIRST) -> SECOND, G: Fn(SECOND) -> THIRD, { move |x| second(first(x)) } #ci }).into()}Next, we produce output. Our application code did not contain the compose_two function from our declarative macro example, so we generate it. The custom struct is responsible for input and output, so we just pass it along behind the compose_two declaration. The additional pair of curly braces is essential. Whatever we return has to be bound to a variable (let composed = ...). And without the curly braces, we are returning two things: a function plus a call to it. With the curly braces, we create one block scope and only return that.
Generating compose_two
Section titled “Generating compose_two”Putting the compose_two function inside the block scope has an additional advantage in that it hides the function declaration from other parts of our code. Remember, we are creating this output for every invocation of our macro. So if we call compose! four times, we have four compose_two functions in their own, limited scopes, hidden from each other.
But always generating the same function is a bit inefficient. Can’t we just export compose_two and reference it in our generated code? Well, no: a proc-macro library
5.3 Composing
can only export procedural macros. One way to work around this limitation would be to put the proc-macro library in another library. That outer library has our proc-macro as a dependency and simply exports compose_two and reexports the macro (e.g., pub use function_like_compose_macro::compose;). If your code takes a dependency on this new library, you can import both the function and the macro and avoid generating the same code all the time.
Perhaps you are now thinking of monomorphization. Monomorphization is Rust compilation creating a copy of a generic function for every concrete type that needs it. So, when you write a generic function with signature foo<T>(t: T) -> T and call it once with an i32 and once with u8 as a type for T, Rust will replace that generic function with two versions: one in which foo accepts and returns an i32 and another where it takes and gives back a u8. This transformation generally leads to faster code but also large binary sizes, especially when generic functions are invoked with a lot of different types.
In any case, monomorphization does lessen the usefulness of our reexport technique, as a function will be generated for every type regardless. Even so, in the current setup, a compose_two is generated even when we have multiple invocations with the same types. And that, at least, does not happen with monomorphization.
A minor detail: this time we did not create a temporary variable for our output to call into() on. Instead, we did all that in one go. And because IDEs are not fond of curly braces followed by method calls (plus, we would have two pairs of curly braces wrapping), I used parentheses.
Now all that is left is to take a look at the custom struct that is doing all the heavy lifting. The Parse input is simple enough: we expect to get function names separated by dots. That sounds like Punctuated! Identifiers will suffice for the function names (see figure 5.3). And to get the dot, we can use the Token macro, which can handle around 100 different symbols. Behind the scenes, Token!(.) will generate Dot, so we could also import that type. Or we could even mix and match these two if we are so inclined.
Find identifiers separated by periods.
plaintext compose!(add_one . add_one . stringify) | |------------------------- | | | add_one . add_one . stringify
Figure 5.3 Parsing our application example with `Punctuated::<Ident, Token!(.)>::parse_terminated`
```mermaidflowchart TD C["compose(add_one, add_one, stringify)"] --> A1[add_one] C --> A2[add_one] C --> S[stringify][!visual-conversion] compose() argument tree Converted from a print tree diagram (PDF page 101): compose(add_one, add_one, stringify) branches to add_one, add_one, and stringify.
Listing 5.8 Our custom struct
Section titled “Listing 5.8 Our custom struct”rust use proc_macro::TokenStream; use proc_macro2::Ident; use quote::{quote, ToTokens}; use syn::{parse_macro_input, Token}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated;
struct ComposeInput { expressions: Punctuated::<Ident, Token!(.)>, }
impl Parse for ComposeInput { fn parse(input: ParseStream) -> Result<Self, syn::Error> { Ok( ComposeInput { expressions: Punctuated::<Ident, Token!(.)>::parse_terminated(input).unwrap(), } ) } }
impl ToTokens for ComposeInput { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let mut total = None; let mut as_identents: Vec<&Ident> = self.expressions.iter().collect(); let last_ident = as_identents.pop().unwrap();
as_identents.iter() .rev() .for_each(|i| { if let Some(current_total) = &total { total = Some(quote!( compose_two(#i, #current_total) )); } else { total = Some(quote!( compose_two(#i, #last_ident) )); } }); total.to_tokens(tokens);}}
The `ToTokens` implementation is a bit more complex (and there are definitely other ways of writing this). Because we want to retrieve the last identifier (function) in the list, we iterate over the expressions, create a mutable variable, and pop the final identifier.5.4 Anything you can do, I can do better
Next, we iterate over our functions in reverse order with for_each. If total, which contains our output, is empty, we are at our first element and should combine it with last_ident using compose_two, putting that entire TokenStream into total. This is why we popped the last element: so we would know when we need to combine the first two elements of the reversed vector. Once past this first composition, things become simpler: we keep taking the current element and putting it into a compose_two with the current total. The resulting TokenStream becomes our new total (see figure 5.4). Finally, we pass all our gathered tokens along using to_tokens. As before, we need proc_macro2 identifiers and token streams because quote uses the proc_macro2 variants instead of the built-in versions.
[figure owed: ]
[!visual-conversion] Flowchart showing identifier processing with as_idents, pop, and compose_two operations. Cropped from the scan (PDF page 103, printed p. ?): Flowchart showing identifier processing with as_idents, pop, and compose_two operations.
Figure 5.4 Going through the identifiers in to_tokens
We are now able to use periods in our composing macro. Once again, syn made it easy to parse our input, even though it was not valid Rust, and quote helped us elegantly combine outputs.
5.4 Anything you can do, I can do better
Section titled “5.4 Anything you can do, I can do better”Because they are the most powerful macro, you might decide to just use function-like macros for every purpose. That would be unwise. Surely it means something that derive macros, the most limited of the three, are perhaps the most popular of the three: a
94 CHAPTER 5 Hiding information and creating mini-DSLs with function-like macros
limitation can also be a strength. For instance, derive macros are predictable in their effects, both for users and creators, since they only add without changing or deleting. So if you only want to add functionality to a struct or enum, and the problem is too complex for a declarative macro, you have already found the right tool for the job.
Derive macros have the limitation and advantage of only working for structs, enums, and unions, while attribute macros work on these plus traits and functions. Again, this makes them more predictable. As a user, I know not to use derive macros on functions. As a creator, the “input token space”—if you will—is much more narrow than that of a function-like macro. That is, I am reasonably sure that I will get a struct or an enum, and I know what those look like.
So if you only want to add functionality to a struct or enum, go with the derive macro. If you need to alter them, default to an attribute macro. And when you want to change functionality and need the macro to apply to other categories as well, go for function-like (see figure 5.5).
[figure owed: ]
[!visual-conversion] Diagram showing three macro types: Derive macro, Attribute macro, Function-like … Cropped from the scan (PDF page 104, printed p. ?): Diagram showing three macro types: Derive macro, Attribute macro, Function-like macro, with their signatures and effects.
Figure 5.5 An overview of our procedural macro signatures, usage, and effects
5.5 From the real world
Section titled “5.5 From the real world”Without going into detail, here are a few examples of crates that put macros to creative use. SQLx (https://github.com/launchbadge/sqlx) is a “Rust SQL crate featuring compile-time checked queries,” a common choice for interacting with relational databases when you do not want to add the complexity of an object-relational mapping. You can write SQL queries by calling the query method. But to get the advertised compile-time checks, you should look for a macro with the same name:
rust let countries = sqlx::query!( “SELECT country, COUNT(*) as count FROM users
5.5 From the real world
95
sql GROUP BY country WHERE organization = ?”, organization ) .fetch_all(&pool) .await?;
Yew (https://yew.rs) is a “framework for creating reliable and efficient web applications.” Among its features is the `html` macro, which allows you to write HTML that is checked at compile time. For example, if you forget to close the nested `div`, you will get an error telling you this opening tag has no corresponding closing tag:
```rustuse yew::prelude::*;
html! { <div id="my_div"> <div id="nested"/> </div>};Taking a bit of a side tour, here is a Yew example where the library authors decide to create a span by calling mixed_site(). (It also contains an example of the format_ident macro, which we will use in our next chapter.) The choice makes sense in this context since the authors do not want this builder to conflict with anything in the client application:
impl ToTokens for DerivePropsInput { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { // ... let builder_name = format_ident!( "{}Builder", props_name, span = Span::mixed_site() ); let check_all_props_name = format_ident!( "Check{}All", props_name, span = Span::mixed_site() ); // ... }}Meanwhile, Leptos (https://leptos.dev/) has a view macro that allows you to mix HTML and Rust. As an example, the following code creates an incrementing button. Here too you will get warnings about mismatches in tags or problems with Rust code inside the macro:
#[component]fn App(cx: Scope) -> impl IntoView { let (count, set_count) = create_signal(cx, 0);
view! { cx, <button on:click=move |_| { set_count.update(|n| *n += 1);
<!-- page: 106 -->
96 CHAPTER 5 Hiding information and creating mini-DSLs with function-like macros
> "Click me: "> {count}> </button>
## Exercises
See the appendix for solutions.
1. Write a function-like macro to generate a struct method that prints "Hello, world". It should only take the struct name as an input. Remember to declare a struct with the correct name in your application code.
2. Our private macro creates convenience methods, but the fields can still be public and directly accessible and our newly generated methods are not public. Change the macro so that it sets all fields to private and generates public methods. You can ignore the complexity of re-adding the struct attributes and hard-code a new method for your example struct.
3. Go look at the Token! source code, and see what other tokens are available. Try a different one for our composing macro, and fix the application code.
## Summary
- Function-like macros replace their input.- Just like declarative macros, you use them by writing their name followed by an exclamation mark.- Their input is placed in the parentheses that follow.- They are not limited to structs and the like, instead taking anything you want to pass along as input.- Writing a function-like macro is very much like writing other procedural macros. But since their inputs are more varied, they may require more parsing effort.- One way to deal with the input is creating a custom struct for gathering all information. The syn library has a lot of useful goodies to help you on your way with this.- When you’re stuck thanks to a compile error in your generated code, try writing out the code you want to generate and see if the compiler or IDE gives you any useful advice.- You should think about requirements when deciding on the kind of macro you need: Where will you use it? Does it have to change existing code?- Whenever possible, go for the simplest option.