Skip to content

Instantly share code, notes, and snippets.

@swlkr
Last active August 1, 2023 16:51
Show Gist options
  • Save swlkr/06c6f0de6b1e996471f50a702de98ad3 to your computer and use it in GitHub Desktop.
Save swlkr/06c6f0de6b1e996471f50a702de98ad3 to your computer and use it in GitHub Desktop.
Generate a struct with a proc macro
/// The schema proc macro:
/// Example:
///
/// schema! {
/// Users {
/// id: "integer primary key not null"
/// }
/// }
#[proc_macro]
pub fn schema(s: TokenStream) -> TokenStream {
match schema_macro(s.into()) {
Ok(s) => s.to_token_stream().into(),
Err(e) => e.to_compile_error().into(),
}
}
/// Generates the structs for the schema macro
fn schema_macro(body: TokenStream2) -> Result<TokenStream2> {
let table = syn::parse::<Table>(body.into())?;
let name = table.name;
let fields: Vec<TokenStream2> = table
.field_values
.iter()
.map(|fv| match &fv.expr {
Expr::Lit(ExprLit { lit, .. }) => match lit {
syn::Lit::Str(s) => {
let member = &fv.member;
quote! { #[doc = #s] pub #member: &'static str }
}
_ => todo!(),
},
_ => todo!(),
})
.collect();
Ok(quote! {
#[derive(Clone, Default, Debug, Copy)]
pub struct #name {
#(#fields,)*
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment