I am using struct to build the schema of the database, so I need to meta information of struct.
Suppose my schema struct is defined like below:
#[derive(ParseStruct)]
pub struct User {
#[field_attr( unique = true, default = "", index=["@hash", "@count"] )]
pub name: String,
#[field_attr( unique = true, default = "" )]
pub username: String,
pub description: Option<String>,
pub age: u32
}
I want to parse into the following struct:
pub struct Schema<T>{
name: String, // the struct name
origin: T, // the struct to be parse, like the User struct above.
fields: Vec<Field>, // the struct's fields
}
pub struct Field {
field_name: String,
field_type: String,
field_attrs: FieldAttribute
}
pub struct FieldAttribute {
unique: bool,
default: String,
index: Vec<String> // Index of the database
}
I wrote a beginning, but I don’t know how to continue writing:
#[proc_macro_derive(ParseStruct)]
pub fn parse_struct_derive(input: TokenStream) -> TokenStream {
let ast = syn::parse(input).unwrap();
let name = &ast.ident;
let gen = quote! {
impl #name {
fn parsed_schema()-> Schema {
// return the parsed schema
//...
}
}
};
gen.into()
}
Expected result:
use parse_struct::ParseStruct;
#[derive(ParseStruct)]
struct User{
#[field_attr( unique = true, default = "", index=["@hash", "@count"] )]
pub name: String
}
fn main() {
let schema = User::parsed_schema();
println!("{:#?}",schema);
}
I don't know how to implement it.
I have only recently begun to learn derive macro and have not fully mastered it yet. It is difficult to find useful tutorials about derive macro on the Internet.
Please help me, thanks.