I am trying to make a procedural macro that adds a common set of fields to a struct.
When using the macro on a struct, I get the error: missing fields `example1` and `example2` in initializer
macros/src/lib.rs:
extern crate proc_macro;
extern crate quote;
extern crate syn;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput, Fields};
#[proc_macro_attribute]
pub fn commonfields(item: TokenStream, input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let struct_name = &input.ident;
let data = match input.data {
syn::Data::Struct(ref data) => data,
_ => panic!("commonfields macro can only be used on structs"),
};
let existing_fields = match &data.fields {
Fields::Named(fields) => fields.named.iter().map(|f| &f.ident).collect::<Vec<_>>(),
_ => panic!("commonfields macro currently only supports named fields"),
};
let new_fields = vec![
quote! { example1: String },
quote! { example2: u32 },
];
let expanded = quote! {
pub struct #struct_name {
#(
#existing_fields: String,
)*
#(
#new_fields,
)*
}
};
TokenStream::from(expanded)
}
src/pagetypes.rs:
use macros::commonfields;
use serde::{Serialize, Deserialize};
extern crate macros;
// [...]
#[derive(Serialize, Deserialize, Debug)]
#[commonfields]
pub struct PageContent {
content: String,
icon: String,
icontitle: String,
theme: String,
cat: String,
startdate: String,
enddate: String
}
full error:
error[E0063]: missing fields `example1` and `example2` in initializer of `pagetypes::PageContent`
--> src/pagetypes.rs:48:12
|
48 | pub struct PageContent {
| ^^^^^^^^^^^ missing `example1` and `example2`