| 39 | /// Procedural macro to derive a wrapper with optional fields around a struct. |
| 40 | #[proc_macro_derive(Config, attributes(config))] |
| 41 | pub fn config_derive(input: TokenStream) -> TokenStream { |
| 42 | let input = syn::parse_macro_input!(input as syn::DeriveInput); |
| 43 | |
| 44 | match input.data { |
| 45 | syn::Data::Struct(ref struct_data) => { |
| 46 | let struct_name = input.ident; |
| 47 | let fields = struct_data.fields.iter().map(|field| { |
| 48 | let attrs = ConfigAttrs::from( |
| 49 | field.attrs.iter().filter(|attr| attr.path().is_ident("config")), |
| 50 | ); |
| 51 | (field.ident.as_ref().unwrap(), &field.ty, attrs) |
| 52 | }); |
| 53 | |
| 54 | let from_lua_fields = fields.clone().map(|(field_name, field_type, attrs)| { |
| 55 | let field_type = attrs.from_type.as_ref().unwrap_or(field_type); |
| 56 | let field_value = if attrs.is_flat { |
| 57 | quote! { |
| 58 | table.get::<_, #field_type>(stringify!(#field_name))?.into() |
| 59 | } |
| 60 | } else { |
| 61 | quote! { |
| 62 | table |
| 63 | .get::<_, Option<#field_type>>(stringify!(#field_name))? |
| 64 | .map(Into::into) |
| 65 | .unwrap_or_default() |
| 66 | } |
| 67 | }; |
| 68 | |
| 69 | quote! { |
| 70 | #field_name: #field_value |
| 71 | } |
| 72 | }); |
| 73 | |
| 74 | let update_from_lua_fields = fields.map(|(field_name, _field_type, attrs)| { |
| 75 | match (attrs.is_flat, attrs.from_type) { |
| 76 | (true, None) => { |
| 77 | quote! { |
| 78 | self.#field_name.update_from_lua(table.get(stringify!(#field_name))?, lua)?; |
| 79 | } |
| 80 | } |
| 81 | (true, Some(from_type)) => { |
| 82 | quote! { |
| 83 | self.#field_name = table.get::<_, #from_type>(stringify!(#field_name))?.into(); |
| 84 | } |
| 85 | } |
| 86 | (false, None) => { |
| 87 | quote! { |
| 88 | if let Some(value) = table.get::<_, Option<mlua::Value>>(stringify!(#field_name))? { |
| 89 | self.#field_name.update_from_lua(value, lua)?; |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | (false, Some(from_type)) => { |
| 94 | quote! { |
| 95 | if let Some(value) = table.get::<_, Option<#from_type>>(stringify!(#field_name))? { |
| 96 | self.#field_name = value.into(); |
| 97 | } |
| 98 | } |