|
| 1 | +use proc_macro2::{Ident, Span}; |
| 2 | +use quote::{quote, ToTokens}; |
| 3 | +use std::collections::HashMap; |
| 4 | +use syn::parse::Parse; |
| 5 | + |
| 6 | +#[derive(Debug, Hash, PartialEq, Eq)] |
| 7 | +pub enum EnumStyle { |
| 8 | + BitfieldEnum, |
| 9 | + NewtypeEnum, |
| 10 | + NewtypeGlobalEnum, |
| 11 | + RustifiedEnum, |
| 12 | + RustifiedNonExhaustiveEnum, |
| 13 | + ConstifiedEnumModule, |
| 14 | + ConstifiedEnum, |
| 15 | +} |
| 16 | + |
| 17 | +#[derive(Debug, Default)] |
| 18 | +pub struct EnumStyleMap(pub HashMap<EnumStyle, Vec<String>>); |
| 19 | + |
| 20 | +impl std::hash::Hash for EnumStyleMap { |
| 21 | + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { |
| 22 | + for (k, v) in &self.0 { |
| 23 | + k.hash(state); |
| 24 | + v.hash(state); |
| 25 | + } |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +impl EnumStyle { |
| 30 | + fn from_str(s: &str) -> Option<Self> { |
| 31 | + use EnumStyle::*; |
| 32 | + Some(match s { |
| 33 | + "BitfieldEnum" => BitfieldEnum, |
| 34 | + "NewtypeEnum" => NewtypeEnum, |
| 35 | + "NewtypeGlobalEnum" => NewtypeGlobalEnum, |
| 36 | + "RustifiedEnum" => RustifiedEnum, |
| 37 | + "RustifiedNonExhaustiveEnum" => RustifiedNonExhaustiveEnum, |
| 38 | + "ConstifiedEnumModule" => ConstifiedEnumModule, |
| 39 | + "ConstifiedEnum" => ConstifiedEnum, |
| 40 | + _ => return None, |
| 41 | + }) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +impl Parse for EnumStyle { |
| 46 | + fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { |
| 47 | + let style_ident: Ident = input.parse()?; |
| 48 | + let style = style_ident.to_string(); |
| 49 | + EnumStyle::from_str(&style).ok_or(syn::Error::new( |
| 50 | + style_ident.span(), |
| 51 | + format!("unknown enum style `{}`", style), |
| 52 | + )) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl ToTokens for EnumStyle { |
| 57 | + fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { |
| 58 | + use EnumStyle::*; |
| 59 | + let variant_ident = match self { |
| 60 | + BitfieldEnum => "BitfieldEnum", |
| 61 | + NewtypeEnum => "NewtypeEnum", |
| 62 | + NewtypeGlobalEnum => "NewtypeGlobalEnum", |
| 63 | + RustifiedEnum => "RustifiedEnum", |
| 64 | + RustifiedNonExhaustiveEnum => "RustifiedNonExhaustiveEnum", |
| 65 | + ConstifiedEnumModule => "ConstifiedEnumModule", |
| 66 | + ConstifiedEnum => "ConstifiedEnum", |
| 67 | + }; |
| 68 | + let var = Ident::new(variant_ident, Span::call_site()); |
| 69 | + tokens.extend(quote! { #var }); |
| 70 | + } |
| 71 | +} |
0 commit comments