-
Notifications
You must be signed in to change notification settings - Fork 120
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add support for #derive[FromStr] for enums #176
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,8 @@ | ||
use crate::utils::{DeriveType, HashMap}; | ||
use crate::utils::{SingleFieldData, State}; | ||
use convert_case::{Case, Casing}; | ||
use proc_macro2::TokenStream; | ||
use quote::quote; | ||
use quote::{format_ident, quote}; | ||
use syn::{parse::Result, DeriveInput}; | ||
|
||
/// Provides the hook to expand `#[derive(FromStr)]` into an implementation of `FromStr` | ||
|
@@ -12,6 +14,14 @@ pub fn expand(input: &DeriveInput, trait_name: &'static str) -> Result<TokenStre | |
trait_name.to_lowercase(), | ||
)?; | ||
|
||
if state.derive_type == DeriveType::Enum { | ||
Ok(enum_from(input, state, trait_name)) | ||
} else { | ||
Ok(struct_from(&state, trait_name)) | ||
} | ||
} | ||
|
||
pub fn struct_from(state: &State, trait_name: &'static str) -> TokenStream { | ||
// We cannot set defaults for fields, once we do we can remove this check | ||
if state.fields.len() != 1 || state.enabled_fields().len() != 1 { | ||
panic_one_field(trait_name); | ||
|
@@ -32,7 +42,7 @@ pub fn expand(input: &DeriveInput, trait_name: &'static str) -> Result<TokenStre | |
let initializers = [quote!(#casted_trait::from_str(src)?)]; | ||
let body = single_field_data.initializer(&initializers); | ||
|
||
Ok(quote! { | ||
quote! { | ||
impl#impl_generics #trait_path for #input_type#ty_generics #where_clause | ||
{ | ||
type Err = <#field_type as #trait_path>::Err; | ||
|
@@ -41,7 +51,81 @@ pub fn expand(input: &DeriveInput, trait_name: &'static str) -> Result<TokenStre | |
Ok(#body) | ||
} | ||
} | ||
}) | ||
} | ||
} | ||
|
||
fn enum_from( | ||
input: &DeriveInput, | ||
state: State, | ||
trait_name: &'static str, | ||
) -> TokenStream { | ||
let mut variants_caseinsensitive = HashMap::default(); | ||
for variant_state in state.enabled_variant_data().variant_states { | ||
let variant = variant_state.variant.unwrap(); | ||
if !variant.fields.is_empty() { | ||
panic!("Only enums with no fields can derive({})", trait_name) | ||
} | ||
|
||
variants_caseinsensitive | ||
.entry(variant.ident.to_string().to_lowercase()) | ||
.or_insert_with(Vec::new) | ||
.push(variant.ident.clone()); | ||
} | ||
|
||
let input_type = &input.ident; | ||
let visibility = &input.vis; | ||
|
||
let err_name = format_ident!("Parse{}Error", input_type); | ||
let err_message = | ||
format!("invalid {}", input_type.to_string().to_case(Case::Lower)); | ||
|
||
let mut cases = vec![]; | ||
|
||
// if a case insensitve match is unique match do that | ||
// otherwise do a case sensitive match | ||
for (ref canonical, ref variants) in variants_caseinsensitive { | ||
if variants.len() == 1 { | ||
let variant = &variants[0]; | ||
cases.push(quote! { | ||
#canonical => #input_type::#variant, | ||
}) | ||
} else { | ||
for variant in variants { | ||
let variant_str = variant.to_string(); | ||
cases.push(quote! { | ||
#canonical if(src == #variant_str) => #input_type::#variant, | ||
}) | ||
} | ||
Comment on lines
+93
to
+98
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this edge case is missing a test |
||
} | ||
} | ||
|
||
let trait_path = state.trait_path; | ||
|
||
quote! { | ||
|
||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
#visibility struct #err_name; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not sure I like creating a type out of nothing here, but I did not like the other options better:
|
||
|
||
impl std::fmt::Display for #err_name { | ||
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
fmt.write_str(#err_message) | ||
} | ||
} | ||
|
||
impl std::error::Error for #err_name {} | ||
|
||
impl #trait_path for #input_type | ||
{ | ||
type Err = #err_name; | ||
#[inline] | ||
fn from_str(src: &str) -> ::core::result::Result<Self, Self::Err> { | ||
Ok(match src.to_lowercase().as_str() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I considered adding |
||
#(#cases)* | ||
_ => return Err(#err_name{}), | ||
}) | ||
} | ||
} | ||
} | ||
} | ||
|
||
fn panic_one_field(trait_name: &str) -> ! { | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should fix the current compilation issue in the feature tests.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks, I just forced pushed a change that bumps
syn
to 1.0.81 (which is the version in the lock file) and changed the code to use .is_empty() instead which means it does not need the extra traitsThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bah looks like I also need to ditch the
x == from_str(x.to_string())
test as I can't#derive[Display]
if the display feature is not set.