Appendix: Exercise solutions
local graph
Chapter 12 — Appendix: Exercise solutions
Section titled “Chapter 12 — Appendix: Exercise solutions”appendix
Section titled “appendix”Exercise solutions
Section titled “Exercise solutions”Chapter 2
Section titled “Chapter 2”1 Fill in the question marks (???), and make the following declarative macro compile.
This is one possible solution. ty seems most appropriate, though ident—for example—would also work:
macro_rules! hello_world { ($something:ty) => { impl $something { fn hello_world(&self) { println!("Hello world!") } } };}
struct Example {}hello_world!(Example);
fn main() { let e = Example {}; e.hello_world();}2 In our first declarative macro example, we use expr in some of our matches. But that was not our only option. Try to replace that with literal, tt, ident, or ty. Which ones work? Which don’t? Do you understand why?
literal will work because we are passing in literal values (e.g., my_vec!(1, 2, 3)). tt will work as well. As we said, it accepts basically anything. ident will not work because we are not passing in identifiers. A valid example—that would get accepted—might be NameOfThisStructIDeclaredInMyCode. ty will not work either, because we are not passing in types. Valid examples include string, i32, etc.
APPENDIX Exercise solutions
3 Allow trailing comments in the my_vec macro. You can do this by writing another matcher, but there’s a simple solution with even less repetition. If you need help, take a look at the vec macro from the standard library for inspiration.
This solution is based on the standard library code:
macro_rules! my_vec { () => { Vec::new() }; ((_,)? => { { let mut v = Vec::new(); x); )+ v } }; }
Alternatively, you could add another rule for matching a trailing comma. In that case, you probably want to define the transcriber body only once and make one of the rules for multiple elements use the other one internally.
4 Another thing I like for newtypes is convenient From implementations. Write a macro that generates them for our four newtypes. Alternatively, you can go for TryFrom since that is a more suitable choice when input validation is required.
To be brief, this solution only shows the From implementations. It is quite similar to our earlier code for getting the underlying value:
macro_rules! generate_from { (struct_type:ident) => { generate_from!(struct_type,String); }; (return_type:ty) => { impl From<return_type { fn from(f: $struct_type) -> Self { f.value } } } }
5 Now that we have two macros, we could make our lives even easier by creating a third macro, generate_newtypes_methods, that calls our existing two macros behind the scene:
macro_rules! generate_newtypes_methods { (struct_type:ident) => { generate_get_value_string!(struct_type,String); generate_from!($struct_type,String); }; }
Chapter 2
Section titled “Chapter 2”($struct_type:ident, $return_type:ty) => { generate_get_value_string!($struct_type, $return_type); generate_from!($struct_type, $return_type);}generate_newtypes_methods!(FirstName);generate_newtypes_methods!(Age, i32);- Expand our Account example in listings 2.12 and 2.13 with dollar and euro currencies. can use a hardcoded exchange rate of 2 dollars to 1 euro. All existing commands will require currency type.
This is one of several possible solutions. We are assuming the money in our accounts in euros:
// account code from DSL chapterenum Currency { Euro, Dollar}
impl From<&str> for Currency { fn from(value: &str) -> Self { if value.contains("euro") { Currency::Euro } else { // simple fallback to dollars Currency::Dollar } }}
impl Currency { fn calculate(&self, amount: u32) -> u32 { match self { Currency::Euro => amount, Currency::Dollar => amount * 2 } }}
macro_rules! exchange { (Give $amount:literal $currency:literal to $name:ident) => { let curr: Currency = $currency.into(); $name.add(curr.calculate($amount)) }}// others are similar to the above
fn main() { let mut the_poor = Account { money: 0, };
exchange!(Give 10 "euros" to the_poor);}
<!-- page: 276 -->
APPENDIX Exercise solutions
exchange!(Give 10 "dollars" to the_poor);exchange!(Give 1 "euro" to the_poor);
Because we want to change a string slice to a currency, we need quotation marks around "euros" and "dollars". You could also experiment with tt and ty for alternative solutions. Or add match arms that literally match the two currencies, e.g., Give $amount:literal euros to..., Give $amount:literal dollars to..., etc.
# Chapter 3
Fill in the question marks (???) and make the following derive macro compile.
Solution:
/ imports
[proc_macro_derive(UpperCaseName)]pub fn uppercase(item: TokenStream) -> TokenStream { let ast = parse_macro_input!(item as DeriveInput); let name = ast.ident; let uppercase_name = name.to_string().to_uppercase();
let add_uppercase = quote! { impl #name { fn uppercase(&self) { println!("{}", #uppercase_name); } } };
add_uppercase.into()}
The name of the macro can be deduced from the usage example. And we learned that macros return a TokenStream, that a DeriveInput can be used to parse input and that we can use hashtags to refer to variables.
2 Try changing the name of the macro inside lib.rs and running the application. What error do you get? What do you have to do to fix things?
If I change the name of the macro to “Helloz,” I will get a very helpful error:
error: cannot find derive macro `Hello` in this scope--> src/main.rs:4:10
4 | #[derive(Hello)] | ^^^^^^ help: a derive macro with a similar name...
6 | pub fn hello(item: TokenStream) -> TokenStream { | --------------------------------------------- similarly named...
But that is only the case if I stay close to the original. If I rename it to “AnotherName,” I get
<!-- page: 277 -->
# Chapter 3
error: cannot find derive macro `Hello` in this scope--> src/main.rs:4:10|4 | #[derive(Hello)]| ^^^^^
The fix is easy. Change every derive annotation to point to the new name. For example:
rust#[derive(AnotherName)]struct Example;3 Add a function called testing_testing to the output of our macro. This is an associated function, one that takes no &self parameter. It should write “One two three” to the console:
Section titled “3 Add a function called testing_testing to the output of our macro. This is an associated function, one that takes no &self parameter. It should write “One two three” to the console:”use quote::quote;use proc_macro::TokenStream;use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(Hello)]pub fn hello(item: TokenStream) -> TokenStream { let ast = parse_macro_input!(item as DeriveInput); let name = ast.ident;
let add_hello_world = quote! { impl #name { fn hello_world(&self) { println!("Hello world") }
fn testing_testing() { println!("One two three") } } };
add_hello_world.into()}4 See if you can output a greeting followed by the name of the input (e.g., “Hello, Example”). Fair warning: passing #name to print will not be enough because that’s an identifier, and you need a string. So either call to_string on the identifier and save the result in a variable or use the stringify macro to change the #name into a string for you.
Section titled “4 See if you can output a greeting followed by the name of the input (e.g., “Hello, Example”). Fair warning: passing #name to print will not be enough because that’s an identifier, and you need a string. So either call to_string on the identifier and save the result in a variable or use the stringify macro to change the #name into a string for you.”This is a bit more challenging, but don’t worry, we will encounter these complexities in upcoming chapters as well:
use quote::quote;use proc_macro::TokenStream;use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(Hello)]pub fn hello(item: TokenStream) -> TokenStream {
<!-- page: 278 -->
APPENDIX Exercise solutions
rustlet ast = parse_macro_input!(item as DeriveInput);let name = ast.ident;
let add_hello_world = quote! { impl #name { fn hello_world(&self) { println!("Hello {}", stringify!(#name)) } }};
add_hello_world.into()Forget to add the stringify!, and you will get Example doesn’t implement std::fmt::Display.
Chapter 4
Section titled “Chapter 4”- Fill in the question marks (???) and make the following macro compile.
Solution:
#[proc_macro_attribute]pub fn delete(_attr: TokenStream, _item: TokenStream) -> TokenStream { let public_version = quote! {}; public_version.into()}- Handle structs with unnamed fields. If you use matching, your new match arm will probably look a bit like this:
Struct(DataStruct { fields: Unnamed(FieldsUnnamed { ref unnamed, .. }), .. })… Note that you will need to decide whether to output a “normal” struct or an unnamed one.
Here are highlights of one possible solution (you can find the entire solution on GitHub):
use quote::{__private, quote};// other imports and some functions
fn unnamed_fields_public( fields: &Punctuated<Field, Comma>,) -> Map<Iter<Field>, fn(&Field) -> __private::TokenStream> { fields.iter().map(|f| { let ty = &f.ty; quote! { pub #ty } })}
fn generate_unnamed_output<'a>( struct_name: Ident, builder_fields: Map<Iter<'a, Field>, fn(&'a Field) -> __private::TokenStream>,) -> quote::__private::TokenStream {
<!-- page: 279 -->
# Chapter 4
quote!( pub struct #struct_name( #(#builder_fields,) * );)
#[proc_macro_attribute]pub fn public(_attr: TokenStream, item: TokenStream)-> TokenStream { let ast = parse_macro_input!(item as DeriveInput); let name = ast.ident;
let basic_output = match ast.data { // code for named fields structs Struct(DataStruct { fields: Unnamed(FieldsUnnamed { ref unnamed, .. }), .. }) => { let f = unnamed_fields_public(unnamed); generate_unnamed_output(name, f) } _ => unimplemented!("only works for structs"), };
quote!( #basic_output ).into()}
Instead of making the match output the fields, we now make it generate all our code, because while we are in the match, we know exactly what kind of struct (named or unnamed) we are dealing with. That makes it easier to generate the right kind of structure. The specific retrieval and transformation logic has been moved to separate functions. This time we are using the private TokenStream from quote to avoid the additional dependency—and you can see why we said a collect could give you a nicer signature. Map<Iter<'a, Field>, fn(&'a Field) => quote::__private::TokenStream> is not great. Alternatively, you could go for an impl Iterator, which we will sometimes do in subsequent chapters.
3 Make our macro handle enums. Two things to keep in mind: First, you do not need to add pub to the fields (only to the enum), but you do have to retrieve and re-add them (they are called variants under Enum, DataEnum). Second, your code will now also have to decide whether it has to return an enum or a struct.
Here are highlights of one possible solution (you can find the entire solution on GitHub):
// imports and some functions
fn generate_enum_output( enum_name: Ident,
<!-- page: 280 -->
APPENDIX Exercise solutions
rustvariants: &Punctuated<Variant, Comma>) -> __private::TokenStream { let as_iter = variants.into_iter();
quote! { pub enum #enum_name { #(#as_iter,)* } }}
#[proc_macro_attribute]pub fn public(_: TokenStream, item: TokenStream) -> TokenStream { let ast = parse_macro_input!(item as DeriveInput); let name = ast.ident;
let basic_output = match ast.data { // struct code Enum(DataEnum { ref variants, .. }) => { generate_enum_output(name, variants) }, _ => unimplemented!("only works for structs and enums"), };
quote! { #basic_output }.into()}The only things that are different are the location where we get our fields/variants and the fact that we do not need to add any visibility modifiers to those variants. Note the into_iter for the variants, since quote does not know how to handle Punctuated as an iterable.
4 Keep the existing attributes of the struct instead of letting them disappear. This requires little more than getting the attrs (attributes) of our item and adding them above the struct. You might have to play around with the quote syntax a bit. Just remember that—unlike before—we do not need a comma to mark the end of an attribute.
Here are highlights of one possible solution (you can find the entire solution on GitHub):
// imports and functions
#[proc_macro_attribute]pub fn public(_: TokenStream, item: TokenStream) -> TokenStream { let ast = parse_macro_input!(item as DeriveInput); let name = ast.ident; let attributes = &ast.attrs;
let basic_output = // create the output as before
quote! { #(#attributes)*
<!-- page: 281 -->
# Chapter 4
## 267
rust#basic_output).into()}As you can see, this is quite easy: retrieve the attributes property from our AST and add it, without comma, to the output as an iterable. If you are absent-minded and add a comma to separate the attributes—for example, #(#attributes,) *—you will get a compile error: expected item after attributes.
5 Combine all of these exercises into a single solution.
Section titled “5 Combine all of these exercises into a single solution.”See GitHub for the full solution. This brings everything we did earlier together in one big macro:
// imports and functions
#[proc_macro_attribute]pub fn public(_: TokenStream, item: TokenStream) -> TokenStream { let ast = parse_macro_input!(item as DeriveInput); let name = ast.ident; let attributes = &ast.attrs;
let basic_output = match ast.data { Struct(DataStruct { fields: Named(FieldsNamed { ref named, .. }), .. }) => { let f = named_fields_public(named); generate_named_output(name, f) } Struct(DataStruct { fields: Unnamed(FieldsUnnamed { ref unnamed, .. }), .. }) => { let f = unnamed_fields_public(unnamed); generate_unnamed_output(name, f) } Enum(DataEnum { ref variants, .. }) => { generate_enum_output(name, variants) }, _ => unimplemented!("only works for structs and enums"), };
quote! { #(#attributes)* #basic_output }.into()}6 Using Punctuated::<Ident, Colon> is one way to parse the field, but in the case of our public fields macro, there is an even simpler solution. Just put everything in variables, as we did with Visibility, and pass the useful things to StructField. Change our Parse implementation to use this simpler parsing.
Section titled “6 Using Punctuated::<Ident, Colon> is one way to parse the field, but in the case of our public fields macro, there is an even simpler solution. Just put everything in variables, as we did with Visibility, and pass the useful things to StructField. Change our Parse implementation to use this simpler parsing.”APPENDIX Exercise solutions
We remove the punctuated bit and simply parse field after field. We do not unwrap the colon since we do not need it, but it should always be there, so unwrapping and ignoring is a perfectly valid solution as well:
impl Parse for StructField { fn parse(input: ParseStream) -> Result<Self, syn::Error> { let _vis: Result<Visibility, _> = input.parse(); let name: Ident = input.parse().unwrap(); let _colon: Result<Colon, _> = input.parse(); let ty: Ident = input.parse().unwrap();
Ok(StructField { name, ty, }) }}Chapter 5
Section titled “Chapter 5”- 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 given name in your application code.
Our macro code expects an identifier—the struct name—so we ask syn to parse that for us. Once we have the identifier, we can pass it to the output:
// imports
#[proc_macro]pub fn hello(item: TokenStream) -> TokenStream { let ast = parse_macro_input!(item as Ident);
quote!( impl #ast { fn hello_world(&self) { println!("Hello world") } } ).into()}We need to create the struct ourselves in the application (main.rs). And now we have created a method without passing in the entire struct:
use hello_world_only_name_exercise_macro::hello;
struct Example { another_value: String}
hello!(Example);
fn main() {
<!-- page: 283 -->
# Chapter 5
let e = Example { another_value: "does not disappear".to_string(),};e.hello_world();
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 hardcode a new method for your example struct.
We need to use the field information in multiple places. So we should write a separate method to retrieve the field name and type:
fn get_field_info(ast: &DeriveInput) -> Vec<(&Ident, &Type)> { match ast.data { Struct( DataStruct { fields: Named( FieldsNamed { ref named, .. }, .. ), } ) => named, _ => unimplemented!( "only works for structs with named fields" ), } .iter() .map(|f| { let field_name = f.ident.as_ref().take().unwrap(); let type_name = &f.ty;
(field_name, type_name) }) .collect()}
Now we use this information to generate our methods. The logic is almost the same as before, except the input is now a &Vec<(&Ident, &Type)> (a reference to the vector makes it easier to pass the field information to multiple methods). And inside the map, we get the field name and type from the tuple we receive:
fn generated_methods( fields: &Vec<(&Ident, &Type)>) -> Vec<TokenStream2> { fields .iter() .map(|f| { let (field_name, type_name) = f; let method_name = Ident::new(
<!-- page: 284 -->
APPENDIX Exercise solutions
rust&format!("get_{field_name}"),Span::call_site());
quote!( pub fn #method_name(&self) -> &#type_name { &self.#field_name }).collect()Making our fields private is even easier than making them public:
fn generate_private_fields( fields: &Vec<(&Ident, &Type)>) -> Vec<TokenStream2> { fields .iter() .map(|f| { let (field_name, type_name) = f;
quote!( #field_name: #type_name ) }) .collect()}In our lib.rs file, we create the struct anew in our output with the field information we generated. We also have a hardcoded new method for creating our Example. In the next chapter, we will look into generating real constructor methods:
// imports
#[proc_macro]pub fn private(item: TokenStream) -> TokenStream { // ast and name let fields = get_field_info(&ast); let output_fields = generate_private_fields(&fields); let methods = generated_methods(&fields);
quote!( pub struct #name { #(#output_fields,)* }
impl #name { pub fn new() -> Self { Example { string_value: "value".to_string(), number_value: 2, } } } )}
<!-- page: 285 -->
# Chapter 5
rust# (#methods)*}).into()}3 Go look at the Token! source code, and see what other tokens are available. Try a different for our composing macro, and fix the application code.
A selection of the available tokens:
"&&" pub struct And/1 /// bitwise and logical AND..."&&" pub struct AndAnd/2 /// lazy AND, borrow, references...// ..."!=" pub struct Ne/2 /// not equal"!" pub struct Not/1 /// bitwise and logical NOT..."|" pub struct Or/1 /// bitwise and logical OR..."|=" pub struct OrEq/2 /// bitwise OR assignment// ...An exclamation mark might be fun. This is what changes in lib.rs. For fun profit, I am using the type (Not) that the Token macro will resolve to in the struct definition. In parse, we are using Token!(!) to get the Not type:
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;use syn::token::Not;
struct ComposeInput { expressions: Punctuated::<Ident, Not>,}
impl Parse for ComposeInput { fn parse(input: ParseStream) -> Result<Self, syn::Error> { Ok( ComposeInput { expressions: Punctuated::<Ident, Token!(!)>::parse_terminated(input).unwrap(), } ) }}The code in our application changes slightly:
// imports and example functions
fn main() { let compose = compose!(add_one ! add_one ! stringify); println!("{}", compose(5));}
<!-- page: 286 -->
APPENDIX Exercise solutions
## Chapter 6
1 We never did write any white-box tests for structs that actually have fields, so add one that runs against the final version of our code.
Here is a test for a struct with one field:
rust#[test]fn builder_struct_for_one_field_struct_should_be_present_in_out() { let input = quote! { struct StructWithOneField { string_value: String, } }; let expected = quote! { struct StructWithOneFieldBuilder { string_value: Option<String>, }
impl StructWithOneFieldBuilder { pub fn string_value(mut self, input: String) -> Self { self.string_value = Some(input); self }
pub fn build(self) -> StructWithOneField { StructWithOneField { string_value: self.string_value .expect( concat!("field not set: ", "string_value") ), } } }
impl StructWithOneField { pub fn builder() -> StructWithOneFieldBuilder { StructWithOneFieldBuilder { string_value: None, } } }; };
let actual = create_builder(input);
assert_eq!(actual.to_string(), expected.to_string());}2 We only wrote code for handling structs with named fields, not the unnamed variety, so we should cover that failure case with another trybuild compilation test.
Add the following code to our tests/fails directory, next to build_enum.rs. You can pick any name you want:
Chapter 6
use builder_macro::Builder;
#[derive(Builder)]pub struct Ano(String, i32);
fn main() {}As before, after running it for the first time, you should check the error you get back, which will look something like this:
error: proc-macro derive panicked --> tests/fails/build_anyonymous_struct.rs:4:10 |4 | #[derive(Builder)] | ^^^^^^^ | = help: message: not implemented: Only implemented for structsIf the error matches your expectations, you should add this file to your fails directory. The test should be green now.
3 In Rocket, you can add headers to functions that make them into endpoints for calls. If you add #[get("/world")] and #[catch(404)] to a function called world, you get an error that looks like this:
error[E0428]: the name `world` is defined multiple times --> hello/src/main.rs:23:1 |22 | #[get("/world")] | ------------------ previous definition of the type `world` here23 | #[catch(404)] | ^^^^^^^^^^^^^^^ `world` redefined here | = note: `world` must be defined only once in the type namespace of this moduleWhat could be causing this? Can you think of a way this problem might be avoided?
When you have two (attribute) macros and get an error regarding a duplicate definition, your first guess should be that both macros are generating custom things (functions, structs, traits) in too broad a scope, and that these definitions are colliding with each other. You can confirm your guess by expanding the code, which will in this case reveal two structs named world being created. If you remove one macro, one definition disappears. Clearly, each macro is generating a single struct. You could also go digging through the code. At the time of writing, you would end up in core/codegen/src/attribute/route/mod.rs, which has a function called codegen_route. That function is outputting this code:
/// Rocket code generated proxy structure.#[vis struct #handler_fn_name { }
<!-- page: 288 -->
APPENDIX Exercise solutions
Based on `handler_fn_name`, you can guess that this struct has the same name as the function that is annotated (i.e., `world`). Mystery solved!
Depending on the context, there are several ways to avoid this problem, and we have discussed most of them before. A more limited scope for the struct and other elements that you are creating (i.e., putting them between `{}`) is a very simple and useful solution, but it might not work depending on requirements (where will the struct be used?).
Another option is making the name more unique and less likely to collide with others. By keeping the name without uppercasing it (`world` instead of `World`, which is the standard naming convention for structs), the creators of Rocket have at the very least made collisions with structs in the user’s code base very unlikely. Unfortunately, using the name as a prefix or suffix will not work in this case, because even then the two macros will generate the same name. Random suffixes would work, though in rare cases (depending on uniqueness and bad luck), you will get very weird errors (when, once in a blue moon, the supposedly unique suffixes turn out to be the same).
The most obvious solution, though, is a better error message. The macros could check whether any other Rocket macros are present on the function. If two Rocket macros for one function do not make sense, a custom error should report this to the user. For example, `#[tokio::test]` checks whether a second test (`#[test]`) attribute has been added to a function, and throws a `second test attribute is supplied` error if this is the case. But creating custom errors is the topic for the next chapter.
## Chapter 7
1. Rewrite the public fields macro to mutate the incoming TokenStream instead of creating a brand-new one.
There are several solutions. What complicates matters a bit is that `Data`—among others—does not implement `Parse`. `FieldsNamed` does, however, so we put our public fields in curly braces. That way, we can parse them into `FieldsNamed`. And we wrap the output in the correct `Data` struct, replacing the existing `data` field of our AST (which has become mutable to make this possible). We also set the visibility to `public`. In both cases, we make good use of the `Default` trait. When that’s done, we can change it into a `TokenStream`:
rust// imports
#[proc_macro_attribute]pub fn public(_attr: TokenStream, item: TokenStream) -> TokenStream { let mut ast = parse_macro_input!(item as DeriveInput);
let fields = // get fields if named, else throw panic
let builder_fields = fields.iter().map(|f| { let name = &f.ident; let ty = &f.ty; quote! { pub #name: #ty } });
<!-- page: 289 -->
# Chapter 7
rustlet builder_fields_with_braces = quote! { #(#builder_fields,)*};
ast.data = Data::Struct(DataStruct { struct_token: Default::default(), fields: Fields::Named( parse2(builder_fields_with_braces).unwrap() ), semi_token: None,});ast.vis = Visibility::Public(Default::default());
ast.to_token_stream().into()The resulting code is actually longer than the original code. But it is better at keeping existing attributes.
2 Our function-like macro for generating methods throws unimplemented for non-struct inputs. Use syn::Error instead. You can point to the span of the name.
Section titled “2 Our function-like macro for generating methods throws unimplemented for non-struct inputs. Use syn::Error instead. You can point to the span of the name.”Here is one possible solution. In the case of an enum, we do a bit of extra effort to help the user and point specifically to the “enum token.” In other cases, we point to the name of the invalid struct or union:
// imports and unchanged functions
fn get_field_info(ast: &DeriveInput) -> Result<Vec<(&Ident, &Type)>, syn::Error> { Ok(match ast.data { Struct( DataStruct { fields: Named( FieldsNamed { ref named, .. }, .. ) } ) => named, Enum(ref d) => return Err( syn::Error::new( d.enum_token.span(), "does not work for enums" ) ), _ => return Err( syn::Error::new( ast.ident.span(), "only works for structs with named fields" ) ), }) .iter()}
<!-- page: 290 -->
APPENDIX Exercise solutions
rust.map(|f| { let field_name = f.ident.as_ref().take().unwrap(); let type_name = &f.ty;
(field_name, type_name)}).collect()}
#[proc_macro]pub fn private(item: TokenStream) -> TokenStream { let ast = parse_macro_input!(item as DeriveInput); let name = &ast.ident;
let fields = match get_field_info(&ast) { Ok(fields) => fields, Err(err) => return err.to_compile_error() .to_token_stream().into() };
// more unchanged code}3 Now avoid the unimplemented with proc_macro_error.
abort is sufficient because there is only one place our code throws an error:
// imports and unchanged functions
fn get_field_info(ast: &DeriveInput) -> Vec<(&Ident, &Type)> { match ast.data { Struct( DataStruct { fields: Named( FieldsNamed { ref named, .. }, .. ), } ) => named, Enum(ref d) => abort!( d.enum_token, "Does not work for enums!".to_string(); help = "This macro can only be used on structs" ), _ => abort!( ast.ident, "Only works for structs with named fields".to_string() ), }
.iter() .map(|f| { let field_name = f.ident.as_ref().take().unwrap(); let type_name = &f.ty;
(field_name, type_name) })}
<!-- page: 291 -->
# Chapter 7
.collect()
#[proc_macro_error]#[proc_macro]pub fn private(item: TokenStream) -> TokenStream { // unchanged}
4 Expand our “panic checks” to also transform panics in while expressions.
This is relatively easy; just add a check for Expr::While and get the statements from body. At this point, you probably want to extract part of the map logic, which is identical to the one for Expr::If. (And IDE tools can do this refactoring for you):
fn handle_expression(expression: Expr, token: Option<Semi>) -> Stmt { match expression { Expr::If(mut ex_if) => { // same code as before }, Expr::While(mut ex_while) => { let new_statements: Vec<Stmt> = ex_while.body.stmts .into_iter() .map(|s| match s { Stmt::Macro(ref expr_macro) => { let output = extract_panic_content(expr_macro);
if output.map(|v| v.is_empty()).unwrap_or(false) { emit_error!( expr_macro, "panic needs a message!" .to_string(); help = "try to add a message: panic!(...)"; note = "we will add the message to Result's Err" ); s } else { extract_panic_content(expr_macro) .map(|t| quote! { return Err(#t.to_string()); }) .map(parse2) .map(Result::unwrap) .unwrap_or(s) } }) .collect(); ex_while.body.stmts = new_statements; Stmt::Expr(Expr::While(ex_while), token) }, _ => Stmt::Expr(expression, token) }}
<!-- page: 292 -->
APPENDIX Exercise solutions
Here is some code to test our changes. What’s important is that our while does not end with a semicolon. If it does, a panic will still be thrown, because we are specifically checking while expressions, not statements:
rustuse panic_to_result_macro::panic_to_result;
#[derive(Debug)]pub struct Person { name: String, age: u32,}
#[panic_to_result]fn create_person_while_loop(name: String, age: u32) -> Person { while true { panic!("strange failure"); } Person { name, age, }}
fn main() {}
#[cfg(test)]mod tests { use super::*;
#[test] fn should_err_on_while_loop() { let actual = create_person_while_loop("S".to_string(), 32);
assert_eq!( actual.expect_err("This should be an err"), "strange failure".to_string() ); }}But ideally, for these kinds of recursive code manipulations, you should turn to syn’s Visit and Fold traits. See the brief note at the end of chapter 10.
Chapter 8
Section titled “Chapter 8”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 = "...")].
By using #[builder(rename = "...")], it is much clearer that this attribute is specific to the builder macro. We start by adding attributes(builder) to our macro:
Chapter 8
Section titled “Chapter 8”#[proc_macro_derive(Builder, attributes(builder))]pub fn builder(item: TokenStream) -> TokenStream { create_builder(item.into()).into()}The only other change is in builder_methods, where we will replace our existing mapping. We use parse_nested_meta, check whether we have a rename attribute, and extract the string, while ignoring the equals sign:
// imports, other code
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, "builder") .map(|a| { let mut content = None;
a.parse_nested_meta(|m| { if m.path.is_ident("rename") { let _: Token![:] = m.input.parse().unwrap(); let name: LitStr = m.input.parse().unwrap(); content = Some( Ident::new(&name.value(), name.span()) ); } Ok(()) }).unwrap(); content.unwrap() }); // if let... unchanged }).collect()}This is quite similar to serde, except that code is longer and uses some lower-level things like lookahead. We showed from_ast in section 8.9 of this chapter. If you follow get_multiple_renames, this is its implementation:
fn get_ser_and_de<'c, T, F, R>( cx: &'c Ctxt, attr: Symbol, meta: &ParseNestedMeta, f: F,) -> syn::Result<(VecAttr<'c, T>, VecAttr<'c, T>)>// where clause{ let mut ser_meta = VecAttr::none(cx, attr); let mut de_meta = VecAttr::none(cx, attr);
let lookahead = meta.input.lookahead1(); if lookahead.peek(Token![:]) { if let Some(both) = f(cx, attr, attr, meta)?.into() {
<!-- page: 294 -->
APPENDIX Exercise solutions
rustser_meta.insert(&meta.path, both.clone());de_meta.insert(&meta.path, both);}} else if lookahead.peek(token::Paren) { meta.parse_nested_meta(|meta| { if meta.path == SERIALIZE { if let Some(v) = f(cx, attr, SERIALIZE, &meta)?.into() { ser_meta.insert(&meta.path, v); } } // more conditionals Ok(()) })?;} else { return Err(lookahead.error());}
Ok((ser_meta, de_meta))}What we did is quite similar to the first if branch, except we did not peek to see whether we had an equals sign. We just threw an error if the format did not match our expectations.
2 Our default assertions generated a warning about naming conventions: type __not-DefaultAssertion should have an upper camel case name. Fix that warning.
This is a minor change. We turn the name in optional_default_asserts into a string, uppercase it, and give it to format_ident. The change also solves another minor bug: the warning was pointing back to the offending field because we were passing its identifier (including its span) to format_ident. That might be confusing to users, who do not need to be aware of the existence of these additional structs:
pub fn optional_default_asserts(fields: &Punctuated<Field, Comma>) -> Vec<TokenStream> { fields.iter() .map(|f| { let name = &f.ident.as_ref().unwrap().to_string(); let mut c = name.chars(); let uppercased_name = c.next() .unwrap() .to_uppercase().collect::<String>() + c.as_str();
let ty = &f.ty; let assertion_ident = format_ident!( "__{}DefaultAssertion", uppercased_name);
quote_spanned! {ty.span()=> struct #assertion_ident where #ty: core::default::Default; } }) .collect()}
<!-- page: 295 -->
# Chapter 8
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.
Based on our project after adding defaults, here is a test for the happy path:
```rust#[test]fn should_uppercase_the_attribute() { #[derive(Builder)] struct Gleipnir { #[uppercase] roots_of: String, }
let gleipnir = Gleipnir::builder() .roots_of("upper".to_string()) .build();
assert_eq!(gleipnir.roots_of, "UPPER".to_string());}We have to add the attribute to our macro entry point:
#[proc_macro_derive(Builder, attributes(builder_defaults, rename, uppercase))]pub fn builder(item: TokenStream) -> TokenStream { create_builder(item.into()).into()}To change our eventual output, we should expand original_struct_setters, where we will check for the uppercase attribute. If this attribute is present and the field is a String (we use a helper from a previous chapter to verify this), we do a to_uppercase on our optional value. If we have the attribute but the type is not a string, we return a syn::Error. In all other cases, there’s nothing to do, so we return an empty stream. Finally, we have to append the uppercase mapping to our output, before the error handling. As we noted in an earlier chapter, our Vec<Result> is automatically transformed to Result<Vec>, which is convenient:
pub fn original_struct_setters( fields: &Punctuated<Field, Comma>, use_defaults: bool) -> Result<Vec<TokenStream>, syn::Error> { 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 uppercase_attr = extract_attribute_from_field( f, "uppercase" );
let to_add = if uppercase_attr.is_some() && matches_type(field_type, "String") {APPENDIX Exercise solutions
quote! { .map(|v| v.to_uppercase()) } } else if uppercase_attr.is_some() { return Err( syn::Error::new(field_name.span(), “can only use uppercase for String type” )); } else { quote!() };
let handle_type = if use_defaults { default_fallback() } else { panic_fallback(field_name_as_string) };
Ok(quote! { #field_name: self.#field_name #to_add.#handle_type }) }) .collect()
Now all that is left is to handle the potential Err in lib.rs:
let set_fields = match original_struct_setters(fields, use_defaults) { Ok(setters) => setters, Err(err) => return err.to_compile_error().to_token_stream() };
The test should turn green. One alternative is to uppercase the field when it is set in the builder. You would need to check the uppercase attribute in builder_methods, uppercasing the string when the attribute is present: self.#field_name = Some(input.to_uppercase());
Chapter 9
Section titled “Chapter 9”1 Try to improve the input modeling. As discussed, it should be easier for users of IacInput to know that we have a bucket event. Optionally, you can also rework the creation of infrastructure using the new IacInput.
All relevant changes are in input.rs, and lib.rs. input.rs is up first. The Bucket and Lambda structs are unchanged, except that we have made has_event private. While we still need that property internally, other parts of our code won’t get access anymore.
IacInput has become an enum with two variants: Normal, which is a bucket, lambda, both, or nothing; and EventBucket, which is when we have a bucket linked with a lambda. In the latter situation, we know we have a bucket and lambda, so no option wrappers are required:
Chapter 9
Section titled “Chapter 9”rust
#[derive(Debug)]
pub enum IacInput {
Normal(Option
`has_resources` has changed, in that we now use pattern matching. And its logic is now slightly simpler: if we have the `EventBucket` variant, we know we have resources. When we have a `Normal` with no properties, we do not have any resources. In every other situation, we return `true`. The wildcard is convenient, though not without risks: if we add another variant that might not have resources, we still return `true` and the compiler will not warn us:
```rustimpl IacInput { pub fn has_resources(&self) -> bool { match self { IacInput::EventBucket(_, _) => true, IacInput::Normal(None, None) => false, _ => true, } }}In Parse, we were already checking the has_event field to see if we also had a lambda. Now, when we do not throw an error, we return the EventBucket variant and unwrap the bucket and lambda. We already verified their existence, so we can use expect:
impl Parse for IacInput { fn parse(input: ParseStream) -> Result<Self, syn::Error> { // bucket and lambda variables // unchanged logic for finding the bucket and lambda
if bucket.as_ref().map(|v| v.has_event).unwrap_or(false) { return if lambda.is_none() { Err(syn::Error::new( input.span(), "a lambda is required for an event ('=>')" )) } else { Ok(IacInput::EventBucket( bucket.expect("only here when bucket exists"), lambda.expect("just checked that this exists"), )) }; } Ok(IacInput::Normal(bucket, lambda)) }}Next, lib.rs and the changed create_infra method. (I have left out the println statements because they are not relevant.) The number of lines of code has not really changed, but in the EventBucket situation, things are now much simpler because we
APPENDIX Exercise solutions
know we have a bucket, lambda, and event. If we have a Normal variant, we also have fewer situations to think about. I have kept the if let, but you could replace that with additional pattern matching. Plus, we managed to get rid of the mutable output variable that was used to store the optional lambda output:
async fn create_infra(iac_input: IacInput) -> Result<(), IacError> { let s3_client = S3Client::new().await; let lambda_client = LambdaClient::new().await;
match iac_input { IacInput::Normal(bucket, lambda) => { if let Some(lambda) = lambda { lambda_client.create_lambda(&lambda).await?; } if let Some(bucket) = bucket { s3_client.create_bucket(&bucket).await?; } }, IacInput::EventBucket(bucket, lambda) => { let output = lambda_client.create_lambda(&lambda).await?; s3_client.create_bucket(&bucket).await?;
let lambda_arn = output.function_arn() .expect("creating a lambda should return its ARN"); lambda_client.add_bucket_permission(&lambda, &bucket.name) .await?; s3_client.link_bucket_with_lambda(&bucket, &lambda_arn) .await?; } } Ok(())}Consider splitting up the Normal variant into a None, Lambda, Bucket, and LambdaAndBucket. It will make creating the infrastructure much simpler, though this approach will probably not scale if you add a lot of resources, since you will have an explosion of possible variants.
2 Suggest the right resource (or property) when you cannot find a match (e.g., when you type “buck,” the error should suggest “bucket”). One option is to use Levenshtein distance.
We will use the code from before we added the AWS SDK because our solution only requires our parsing functionality. First, add this dependency to the macro:
edit-distance = "2.1.0"All our changes are scoped to the IacInput Parse implementation, specifically, the else if !input.is_empty(), where we have something that is not a bucket or lambda.
First, we try to parse the input as an Ident, defaulting to the original error when we encounter problems. If the parse works, we can get the string representation of the identifier and compare its distance to the keywords. We won’t return messages when
<!-- page: 299 -->
# Chapter 9
the distance is very large, because it does not make sense to suggest one of our two keywords when the input has absolutely nothing in common with either.
When we do have one or more valid suggestions, we take the one with the lowest distance to the input and add that to our error message as a suggestion. We use the span of the identifier within the ok branch because that is exactly what our macro is having problems with:
```rustmatch input.parse::<Ident>() { Ok(remainder) => { let remainder_as_string = remainder.to_string(); let distance_to_bucket = edit_distance( "bucket", &remainder_as_string ); let distance_to_lambda = edit_distance( "lambda", &remainder_as_string );
if distance_to_bucket > 10 && distance_to_lambda > 10 { return Err(syn::Error::new( remainder.span(), "only 'bucket' and 'lambda' resources are supported" )); }
let suggestion = if distance_to_bucket > distance_to_lambda { "lambda" } else { "bucket" };
return Err(syn::Error::new( remainder.span(), format!("only 'bucket' and 'lambda' resources are supported. \ Is this a typo for {}?", suggestion) )); } Err(_) => { // original error }}A possible improvement to this code would be to extract a helper to build the error since we now have three places where it is being used, and they are all very similar.
3 Currently, our code fails when the resources we add already exist. Skip creation when you detect that it is unnecessary.
We need to change s3.rs and lambda.rs to check for resource existence. The Lambda SDK has a get_function call, so we add it and only create the lambda if we get back an error.
APPENDIX Exercise solutions
We are ignoring the very real possibility that the error might be caused by a lot of things besides the function not existing. In most cases, this is fine: if there is an error, it will probably show up when we try to create the resource. One error case that can cause real bugs is the user not having the required permissions to list or read functions while still having permission to create them. In that unlikely case, the code will always try to create the resource.
When the function exists, we could (but currently do not) check the memory and time configuration, updating it if necessary with update_function_configuration(), which is probably the behavior a user would expect.
Finally, we are now returning a string instead of a CreateFunctionOutput, because we no longer have this output when the resource already exists. Instead, we return the ARN, which is what we actually need:
rust
pub async fn create_lambda(&self, lambda: &Lambda)
-> Result<String, SdkError
For buckets, we do not have a GET call in the SDK. So, instead, we list the buckets and check whether our name is in there.
We are again ignoring a few failure cases like missing “list buckets” permissions and accounts with so many buckets that a single call won’t retrieve all of them. The latter is a bit unlikely because of the (soft) AWS limit on the number of buckets (100 by default). Also, our return type has once again changed, this time to a unit type, since we don’t use the output:
```rustpub async fn create_bucket(&self, bucket: &Bucket) -> Result<(), SdkError<CreateBucketError>> { let bucket_output = self.client.list_buckets().send().await .expect("listing buckets to work"); let buckets = bucket_output.buckets();
<!-- page: 301 -->
# Chapter 9
let bucket_names: Vec<String> = buckets.iter() .map(|b| b.name().expect("bucket to have a name").to_string()) .collect();
if bucket_names.contains(&bucket.name) { eprintln!("bucket exists, skipping creation");} else { let constraint = BucketLocationConstraint::from( self.region.as_str() ); let cfg = CreateBucketConfiguration::builder() .location_constraint(constraint) .build();
self.client.create_bucket() .bucket(&bucket.name) .create_bucket_configuration(cfg) .send() .await?;};Ok(())
With the clients in order, create_infra requires a slight change because of the changed create_lambda return type. Instead of unwrapping the output and retrieving the function ARN, we can just unwrap the optional:
async fn create_infra(iac_input: IacInput) -> Result<(), IacError> { let s3_client = S3Client::new().await; let lambda_client = LambdaClient::new().await; let mut output = None;
if let Some(lambda) = &iac_input.lambda { output = Some(lambda_client.create_lambda(lambda).await?); }
if let Some(bucket) = &iac_input.bucket { s3_client.create_bucket(bucket).await?;
if bucket.has_event { let lambda_arn = output .expect("when we have an event, we should have a lambda"); let lambda = iac_input.lambda .expect("when we have an event, we should have a lambda");
lambda_client.add_bucket_permission(&lambda, &bucket.name) .await?; s3_client.link_bucket_with_lambda(bucket, &lambda_arn) .await?; } } Ok(())}
<!-- page: 302 -->
APPENDIX Exercise solutions
Two cargo run commands with the same macro input should now show the creation of the lambda, followed by skipping creation because it already exists. What's nice is that the event can still be created even if the bucket and lambda already exist. But running it an additional time will cause a complaint about the statement ID already existing (you may remember we hardcoded that particular ID). To fix that, you have to check the bucket configuration (get_bucket_notification_configuration()) to see if the configuration for our lambda ARN is already present.
4 Make it possible to add another kind of resource (from AWS or maybe from another cloud provider) to the iac! macro. (Note: No solution is provided for this exercise.)
What are you looking in here for? I already told you there is no solution for this exercise! But if you want something simple, try adding another AWS resource like SQS, which has very few required properties. Add any optional properties you like. (Maybe FIFO as a Boolean? Be sure to verify that the name of a FIFO queue ends in .fifo.)
# Chapter 10
1 Make sure that we can accept both path and exclude as macro properties.
Our starting point is the project before we added documentation. Everything we need to change is in input.rs. Instead of an if-else, we use while to loop as long as the stream is not empty. We save both the path and exclude_from in mutable values, adding them to the return value once we are done looping.
We've chosen to support traits without a separator (#[config_struct(path = "./a/config.yaml" exclude = "from")]). If we wanted a separator, we could instead turn to Punctuated:
```rustimpl Parse for ConfigInput { fn parse(input: ParseStream) -> syn::Result<Self> { let mut path = None; let mut exclude_from = None;
while !input.is_empty() { if input.peek(kw::path) { // parse the path, the equals sign, and the string path = Some(value.value()); } else if input.peek(kw::exclude) { // parse the path, the equals sign, and the string exclude_from = Some(value.value() == "from"); } else { // error } }
Ok(ConfigInput { path, exclude_from: exclude_from.unwrap_or(false), }) }}Chapter 10
Section titled “Chapter 10”2 Instead of adding exclude to our attribute macro, try to use a feature.
Section titled “2 Instead of adding exclude to our attribute macro, try to use a feature.”Here too, our starting point is the code before we added documentation. Getting of the exclude means making some changes to lib.rs, input.rs, and struct_output.rs. Other than that, we need to change our macro’s Cargo.toml to add the additional feature:
toml [features] struct = [] from = []
In `struct_output.rs`, we add one `generate_from_method` that will be compiled *when the feature is active* and one that returns an empty token stream *when it is not*: `#[cfg(not(feature = "from"))]`. In `generate_annotation_struct`, we call the generate function. Depending on the situation, either a `From` implementation or an empty stream will be added to our output:
```rust// imports and other generate functions
#[cfg(feature = "from")]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 } } }}
#[cfg(not(feature = "from"))]fn generate_from_method( _name: &Ident, _yaml_values: &HashMap<String, String>) -> TokenStream { quote!()}
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); let from = generate_from_method(name, &yaml_values);
<!-- page: 304 -->
APPENDIX Exercise solutions
rustquote! { #(#attributes)* pub struct #name { #(#fields,)* }
impl #name { pub fn new() -> Self { #name { #(#inits,)* } } }
#from}It’s a slightly different way of thinking than our previous exclude implementation. But it is equally elegant and simple to implement, thanks to the built-in support for features.