Last active
November 4, 2023 20:09
-
-
Save maxpushka/9817bd4caf133cf3f2a2fcd55516b629 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use proc_macro::TokenStream; | |
use quote::{format_ident, quote}; | |
use syn::{parse_macro_input, Data, DeriveInput, Fields}; | |
#[proc_macro_derive(FieldsFromStruct)] | |
pub fn fields_from_struct_derive(input: TokenStream) -> TokenStream { | |
let input = parse_macro_input!(input as DeriveInput); | |
let visibility = &input.vis; | |
let enum_name = format_ident!("{}Fields", input.ident); | |
let fields = if let Data::Struct(data) = input.data { | |
match data.fields { | |
Fields::Named(fields) => fields.named, | |
_ => panic!("Only named fields are supported"), | |
} | |
} else { | |
panic!("Only structs are supported"); | |
}; | |
let enum_variants = fields.into_iter().map(|f| f.ident).collect::<Vec<_>>(); | |
let expanded = quote! { | |
#[allow(non_camel_case_types)] | |
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] | |
#visibility enum #enum_name { | |
#(#enum_variants),* | |
} | |
}; | |
TokenStream::from(expanded) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment