mirror of
https://github.com/danog/strum.git
synced 2024-11-26 20:14:40 +01:00
Clippy lints and some minor nitpicks (#212)
* add clippy.toml with an msrv * fix clippy lints * replace inefficient algorithm * replace ::std with ::core in more places and comments * fix some test warnings * fix clippy lints in tests
This commit is contained in:
parent
c676655d11
commit
672ac26005
1
.clippy.toml
Normal file
1
.clippy.toml
Normal file
@ -0,0 +1 @@
|
||||
msrv = "1.32.0"
|
@ -66,7 +66,7 @@
|
||||
//! The generated code will now return the variant with the input string captured as shown below
|
||||
//! instead of failing.
|
||||
//!
|
||||
//! ```rust,ignore
|
||||
//! ```text
|
||||
//! // Replaces this:
|
||||
//! _ => Err(strum::ParseError::VariantNotFound)
|
||||
//! // With this in generated code:
|
||||
@ -83,7 +83,7 @@
|
||||
//!
|
||||
//! - `message=".."`: Adds a message to enum variant. This is used in conjunction with the `EnumMessage`
|
||||
//! trait to associate a message with a variant. If `detailed_message` is not provided,
|
||||
//! then `message` will also be returned when get_detailed_message() is called.
|
||||
//! then `message` will also be returned when `get_detailed_message` is called.
|
||||
//!
|
||||
//! - `detailed_message=".."`: Adds a more detailed message to a variant. If this value is omitted, then
|
||||
//! `message` will be used in it's place.
|
||||
|
@ -11,8 +11,8 @@
|
||||
//!
|
||||
//! # Including Strum in Your Project
|
||||
//!
|
||||
//! Import strum and strum_macros into your project by adding the following lines to your
|
||||
//! Cargo.toml. Strum_macros contains the macros needed to derive all the traits in Strum.
|
||||
//! Import strum and `strum_macros` into your project by adding the following lines to your
|
||||
//! Cargo.toml. `strum_macros` contains the macros needed to derive all the traits in Strum.
|
||||
//!
|
||||
//! ```toml
|
||||
//! [dependencies]
|
||||
@ -30,7 +30,7 @@
|
||||
// only for documentation purposes
|
||||
pub mod additional_attributes;
|
||||
|
||||
/// The ParseError enum is a collection of all the possible reasons
|
||||
/// The `ParseError` enum is a collection of all the possible reasons
|
||||
/// an enum can fail to parse from a string.
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
|
||||
pub enum ParseError {
|
||||
@ -99,7 +99,7 @@ pub trait IntoEnumIterator: Sized {
|
||||
|
||||
/// Associates additional pieces of information with an Enum. This can be
|
||||
/// autoimplemented by deriving `EnumMessage` and annotating your variants with
|
||||
/// `#[strum(message="...")].
|
||||
/// `#[strum(message="...")]`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
@ -126,7 +126,7 @@ pub trait EnumMessage {
|
||||
fn get_serializations(&self) -> &'static [&'static str];
|
||||
}
|
||||
|
||||
/// EnumProperty is a trait that makes it possible to store additional information
|
||||
/// `EnumProperty` is a trait that makes it possible to store additional information
|
||||
/// with enum variants. This trait is designed to be used with the macro of the same
|
||||
/// name in the `strum_macros` crate. Currently, the only string literals are supported
|
||||
/// in attributes, the other methods will be implemented as additional attribute types
|
||||
|
@ -7,6 +7,7 @@ use syn::{
|
||||
Ident, LitStr,
|
||||
};
|
||||
|
||||
#[allow(clippy::enum_variant_names)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum CaseStyle {
|
||||
CamelCase,
|
||||
@ -54,7 +55,7 @@ impl Parse for CaseStyle {
|
||||
impl FromStr for CaseStyle {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(text: &str) -> Result<CaseStyle, ()> {
|
||||
fn from_str(text: &str) -> Result<Self, ()> {
|
||||
Ok(match text {
|
||||
"camel_case" | "PascalCase" => CaseStyle::PascalCase,
|
||||
"camelCase" => CaseStyle::CamelCase,
|
||||
|
@ -137,7 +137,7 @@ pub trait DeriveInputExt {
|
||||
/// Get all the strum metadata associated with an enum.
|
||||
fn get_metadata(&self) -> syn::Result<Vec<EnumMeta>>;
|
||||
|
||||
/// Get all the strum_discriminants metadata associated with an enum.
|
||||
/// Get all the `strum_discriminants` metadata associated with an enum.
|
||||
fn get_discriminants_metadata(&self) -> syn::Result<Vec<EnumDiscriminantsMeta>>;
|
||||
}
|
||||
|
||||
@ -240,7 +240,7 @@ impl Parse for Prop {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
use syn::ext::IdentExt;
|
||||
|
||||
let k = Ident::parse_any(&input)?;
|
||||
let k = Ident::parse_any(input)?;
|
||||
let _: Token![=] = input.parse()?;
|
||||
let v = input.parse()?;
|
||||
|
||||
|
@ -15,7 +15,7 @@ pub fn non_enum_error() -> syn::Error {
|
||||
syn::Error::new(Span::call_site(), "This macro only supports enums.")
|
||||
}
|
||||
|
||||
pub fn strum_discriminants_passthrough_error(span: impl Spanned) -> syn::Error {
|
||||
pub fn strum_discriminants_passthrough_error(span: &impl Spanned) -> syn::Error {
|
||||
syn::Error::new(
|
||||
span.span(),
|
||||
"expected a pass-through attribute, e.g. #[strum_discriminants(serde(rename = \"var0\"))]",
|
||||
|
@ -99,10 +99,8 @@ impl HasTypeProperties for DeriveInput {
|
||||
|
||||
impl StrumTypeProperties {
|
||||
pub fn crate_module_path(&self) -> Path {
|
||||
if let Some(path) = &self.crate_module_path {
|
||||
parse_quote!(#path)
|
||||
} else {
|
||||
parse_quote!(::strum)
|
||||
}
|
||||
self.crate_module_path
|
||||
.as_ref()
|
||||
.map_or_else(|| parse_quote!(::strum), |path| parse_quote!(#path))
|
||||
}
|
||||
}
|
||||
|
@ -29,17 +29,13 @@ impl StrumVariantProperties {
|
||||
}
|
||||
|
||||
pub fn get_preferred_name(&self, case_style: Option<CaseStyle>) -> LitStr {
|
||||
if let Some(to_string) = &self.to_string {
|
||||
to_string.clone()
|
||||
} else {
|
||||
let mut serialized = self.serialize.clone();
|
||||
serialized.sort_by_key(|s| s.value().len());
|
||||
if let Some(n) = serialized.pop() {
|
||||
n
|
||||
} else {
|
||||
self.ident_as_str(case_style)
|
||||
}
|
||||
}
|
||||
self.to_string.as_ref().cloned().unwrap_or_else(|| {
|
||||
self.serialize
|
||||
.iter()
|
||||
.max_by_key(|s| s.value().len())
|
||||
.cloned()
|
||||
.unwrap_or_else(|| self.ident_as_str(case_style))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_serializations(&self, case_style: Option<CaseStyle>) -> Vec<LitStr> {
|
||||
@ -58,8 +54,10 @@ impl StrumVariantProperties {
|
||||
|
||||
impl HasStrumVariantProperties for Variant {
|
||||
fn get_variant_properties(&self) -> syn::Result<StrumVariantProperties> {
|
||||
let mut output = StrumVariantProperties::default();
|
||||
output.ident = Some(self.ident.clone());
|
||||
let mut output = StrumVariantProperties {
|
||||
ident: Some(self.ident.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut message_kw = None;
|
||||
let mut detailed_message_kw = None;
|
||||
|
@ -30,7 +30,7 @@ fn debug_print_generated(ast: &DeriveInput, toks: &TokenStream) {
|
||||
|
||||
/// Converts strings to enum variants based on their name.
|
||||
///
|
||||
/// auto-derives `std::str::FromStr` on the enum (for Rust 1.34 and above, std::convert::TryFrom<&str>
|
||||
/// auto-derives `std::str::FromStr` on the enum (for Rust 1.34 and above, `std::convert::TryFrom<&str>`
|
||||
/// will be derived as well). Each variant of the enum will match on it's own name.
|
||||
/// This can be overridden using `serialize="DifferentName"` or `to_string="DifferentName"`
|
||||
/// on the attribute as shown below.
|
||||
@ -47,7 +47,7 @@ fn debug_print_generated(ast: &DeriveInput, toks: &TokenStream) {
|
||||
/// See the [Additional Attributes](https://docs.rs/strum/0.22/strum/additional_attributes/index.html)
|
||||
/// Section for more information on using this feature.
|
||||
///
|
||||
/// # Example howto use EnumString
|
||||
/// # Example howto use `EnumString`
|
||||
/// ```
|
||||
/// use std::str::FromStr;
|
||||
/// use strum_macros::EnumString;
|
||||
@ -78,14 +78,14 @@ fn debug_print_generated(ast: &DeriveInput, toks: &TokenStream) {
|
||||
/// impl std::str::FromStr for Color {
|
||||
/// type Err = ::strum::ParseError;
|
||||
///
|
||||
/// fn from_str(s: &str) -> ::std::result::Result<Color, Self::Err> {
|
||||
/// fn from_str(s: &str) -> ::core::result::Result<Color, Self::Err> {
|
||||
/// match s {
|
||||
/// "Red" => ::std::result::Result::Ok(Color::Red),
|
||||
/// "Green" => ::std::result::Result::Ok(Color::Green { range:Default::default() }),
|
||||
/// "blue" => ::std::result::Result::Ok(Color::Blue(Default::default())),
|
||||
/// "b" => ::std::result::Result::Ok(Color::Blue(Default::default())),
|
||||
/// s if s.eq_ignore_ascii_case("Black") => ::std::result::Result::Ok(Color::Black),
|
||||
/// _ => ::std::result::Result::Err(::strum::ParseError::VariantNotFound),
|
||||
/// "Red" => ::core::result::Result::Ok(Color::Red),
|
||||
/// "Green" => ::core::result::Result::Ok(Color::Green { range:Default::default() }),
|
||||
/// "blue" => ::core::result::Result::Ok(Color::Blue(Default::default())),
|
||||
/// "b" => ::core::result::Result::Ok(Color::Blue(Default::default())),
|
||||
/// s if s.eq_ignore_ascii_case("Black") => ::core::result::Result::Ok(Color::Black),
|
||||
/// _ => ::core::result::Result::Err(::strum::ParseError::VariantNotFound),
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
@ -160,7 +160,7 @@ pub fn as_ref_str(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
toks.into()
|
||||
}
|
||||
|
||||
/// Implements Strum::VariantNames which adds an associated constant `VARIANTS` which is an array of discriminant names.
|
||||
/// Implements `Strum::VariantNames` which adds an associated constant `VARIANTS` which is an array of discriminant names.
|
||||
///
|
||||
/// Adds an `impl` block for the `enum` that adds a static `VARIANTS` array of `&'static str` that are the discriminant names.
|
||||
/// This will respect the `serialize_all` attribute on the `enum` (like `#[strum(serialize_all = "snake_case")]`.
|
||||
@ -201,7 +201,7 @@ pub fn as_static_str(input: proc_macro::TokenStream) -> proc_macro::TokenStream
|
||||
|
||||
let toks = macros::as_ref_str::as_static_str_inner(
|
||||
&ast,
|
||||
macros::as_ref_str::GenerateTraitVariant::AsStaticStr,
|
||||
¯os::as_ref_str::GenerateTraitVariant::AsStaticStr,
|
||||
)
|
||||
.unwrap_or_else(|err| err.to_compile_error());
|
||||
debug_print_generated(&ast, &toks);
|
||||
@ -243,7 +243,7 @@ pub fn into_static_str(input: proc_macro::TokenStream) -> proc_macro::TokenStrea
|
||||
|
||||
let toks = macros::as_ref_str::as_static_str_inner(
|
||||
&ast,
|
||||
macros::as_ref_str::GenerateTraitVariant::From,
|
||||
¯os::as_ref_str::GenerateTraitVariant::From,
|
||||
)
|
||||
.unwrap_or_else(|err| err.to_compile_error());
|
||||
debug_print_generated(&ast, &toks);
|
||||
@ -490,18 +490,18 @@ pub fn from_repr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
/// // Generated code looks like more or less like this:
|
||||
/// /*
|
||||
/// impl ::strum::EnumMessage for Color {
|
||||
/// fn get_message(&self) -> ::std::option::Option<&'static str> {
|
||||
/// fn get_message(&self) -> ::core::option::Option<&'static str> {
|
||||
/// match self {
|
||||
/// &Color::Red => ::std::option::Option::Some("Red"),
|
||||
/// &Color::Green {..} => ::std::option::Option::Some("Simply Green"),
|
||||
/// &Color::Red => ::core::option::Option::Some("Red"),
|
||||
/// &Color::Green {..} => ::core::option::Option::Some("Simply Green"),
|
||||
/// _ => None
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// fn get_detailed_message(&self) -> ::std::option::Option<&'static str> {
|
||||
/// fn get_detailed_message(&self) -> ::core::option::Option<&'static str> {
|
||||
/// match self {
|
||||
/// &Color::Red => ::std::option::Option::Some("This is very red"),
|
||||
/// &Color::Green {..}=> ::std::option::Option::Some("Simply Green"),
|
||||
/// &Color::Red => ::core::option::Option::Some("This is very red"),
|
||||
/// &Color::Green {..}=> ::core::option::Option::Some("Simply Green"),
|
||||
/// _ => None
|
||||
/// }
|
||||
/// }
|
||||
|
@ -1,7 +1,7 @@
|
||||
use proc_macro2::{Span, TokenStream, TokenTree};
|
||||
use quote::{quote, ToTokens};
|
||||
use syn::parse_quote;
|
||||
use syn::{Data, DeriveInput};
|
||||
use syn::{Data, DeriveInput, Fields};
|
||||
|
||||
use crate::helpers::{non_enum_error, strum_discriminants_passthrough_error, HasTypeProperties};
|
||||
|
||||
@ -30,10 +30,7 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
};
|
||||
|
||||
// Work out the name
|
||||
let default_name = syn::Ident::new(
|
||||
&format!("{}Discriminants", name.to_string()),
|
||||
Span::call_site(),
|
||||
);
|
||||
let default_name = syn::Ident::new(&format!("{}Discriminants", name), Span::call_site());
|
||||
|
||||
let discriminants_name = type_properties.discriminant_name.unwrap_or(default_name);
|
||||
let discriminants_vis = type_properties
|
||||
@ -69,11 +66,11 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
let passthrough_attribute = match passthrough_group {
|
||||
TokenTree::Group(ref group) => group.stream(),
|
||||
_ => {
|
||||
return Err(strum_discriminants_passthrough_error(passthrough_group));
|
||||
return Err(strum_discriminants_passthrough_error(&passthrough_group));
|
||||
}
|
||||
};
|
||||
if passthrough_attribute.is_empty() {
|
||||
return Err(strum_discriminants_passthrough_error(passthrough_group));
|
||||
return Err(strum_discriminants_passthrough_error(&passthrough_group));
|
||||
}
|
||||
Ok(quote! { #[#passthrough_attribute] })
|
||||
} else {
|
||||
@ -108,14 +105,12 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
.iter()
|
||||
.map(|variant| {
|
||||
let ident = &variant.ident;
|
||||
|
||||
use syn::Fields::*;
|
||||
let params = match &variant.fields {
|
||||
Unit => quote! {},
|
||||
Unnamed(_fields) => {
|
||||
Fields::Unit => quote! {},
|
||||
Fields::Unnamed(_fields) => {
|
||||
quote! { (..) }
|
||||
}
|
||||
Named(_fields) => {
|
||||
Fields::Named(_fields) => {
|
||||
quote! { { .. } }
|
||||
}
|
||||
};
|
||||
|
@ -1,6 +1,6 @@
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use quote::quote;
|
||||
use syn::{Data, DeriveInput, Ident};
|
||||
use syn::{Data, DeriveInput, Fields, Ident};
|
||||
|
||||
use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};
|
||||
|
||||
@ -35,21 +35,19 @@ pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
let mut arms = Vec::new();
|
||||
let mut idx = 0usize;
|
||||
for variant in variants {
|
||||
use syn::Fields::*;
|
||||
|
||||
if variant.get_variant_properties()?.disabled.is_some() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let ident = &variant.ident;
|
||||
let params = match &variant.fields {
|
||||
Unit => quote! {},
|
||||
Unnamed(fields) => {
|
||||
Fields::Unit => quote! {},
|
||||
Fields::Unnamed(fields) => {
|
||||
let defaults = ::core::iter::repeat(quote!(::core::default::Default::default()))
|
||||
.take(fields.unnamed.len());
|
||||
quote! { (#(#defaults),*) }
|
||||
}
|
||||
Named(fields) => {
|
||||
Fields::Named(fields) => {
|
||||
let fields = fields
|
||||
.named
|
||||
.iter()
|
||||
|
@ -1,6 +1,6 @@
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{Data, DeriveInput};
|
||||
use syn::{Data, DeriveInput, Fields};
|
||||
|
||||
use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};
|
||||
|
||||
@ -25,11 +25,10 @@ pub fn enum_message_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
let detailed_messages = variant_properties.detailed_message.as_ref();
|
||||
let ident = &variant.ident;
|
||||
|
||||
use syn::Fields::*;
|
||||
let params = match variant.fields {
|
||||
Unit => quote! {},
|
||||
Unnamed(..) => quote! { (..) },
|
||||
Named(..) => quote! { {..} },
|
||||
Fields::Unit => quote! {},
|
||||
Fields::Unnamed(..) => quote! { (..) },
|
||||
Fields::Named(..) => quote! { {..} },
|
||||
};
|
||||
|
||||
// You can't disable getting the serializations.
|
||||
|
@ -1,6 +1,6 @@
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{Data, DeriveInput};
|
||||
use syn::{Data, DeriveInput, Fields};
|
||||
|
||||
use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};
|
||||
|
||||
@ -26,15 +26,14 @@ pub fn enum_properties_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
continue;
|
||||
}
|
||||
|
||||
use syn::Fields::*;
|
||||
let params = match variant.fields {
|
||||
Unit => quote! {},
|
||||
Unnamed(..) => quote! { (..) },
|
||||
Named(..) => quote! { {..} },
|
||||
Fields::Unit => quote! {},
|
||||
Fields::Unnamed(..) => quote! { (..) },
|
||||
Fields::Named(..) => quote! { {..} },
|
||||
};
|
||||
|
||||
for (key, value) in variant_properties.string_props {
|
||||
string_arms.push(quote! { #key => ::core::option::Option::Some( #value )})
|
||||
string_arms.push(quote! { #key => ::core::option::Option::Some( #value )});
|
||||
}
|
||||
|
||||
string_arms.push(quote! { _ => ::core::option::Option::None });
|
||||
|
@ -1,6 +1,7 @@
|
||||
use heck::ToShoutySnakeCase;
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use quote::{format_ident, quote};
|
||||
use syn::{Data, DeriveInput, PathArguments, Type, TypeParen};
|
||||
use syn::{Data, DeriveInput, Fields, PathArguments, Type, TypeParen};
|
||||
|
||||
use crate::helpers::{non_enum_error, HasStrumVariantProperties};
|
||||
|
||||
@ -66,22 +67,20 @@ pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
let mut has_additional_data = false;
|
||||
let mut prev_const_var_ident = None;
|
||||
for variant in variants {
|
||||
use syn::Fields::*;
|
||||
|
||||
if variant.get_variant_properties()?.disabled.is_some() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let ident = &variant.ident;
|
||||
let params = match &variant.fields {
|
||||
Unit => quote! {},
|
||||
Unnamed(fields) => {
|
||||
Fields::Unit => quote! {},
|
||||
Fields::Unnamed(fields) => {
|
||||
has_additional_data = true;
|
||||
let defaults = ::core::iter::repeat(quote!(::core::default::Default::default()))
|
||||
.take(fields.unnamed.len());
|
||||
quote! { (#(#defaults),*) }
|
||||
}
|
||||
Named(fields) => {
|
||||
Fields::Named(fields) => {
|
||||
has_additional_data = true;
|
||||
let fields = fields
|
||||
.named
|
||||
@ -91,7 +90,6 @@ pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
}
|
||||
};
|
||||
|
||||
use heck::ToShoutySnakeCase;
|
||||
let const_var_str = format!("{}_DISCRIMINANT", variant.ident).to_shouty_snake_case();
|
||||
let const_var_ident = format_ident!("{}", const_var_str);
|
||||
|
||||
@ -115,7 +113,7 @@ pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
quote! {}
|
||||
} else {
|
||||
#[rustversion::before(1.46)]
|
||||
fn filter_by_rust_version(s: TokenStream) -> TokenStream {
|
||||
fn filter_by_rust_version(_: TokenStream) -> TokenStream {
|
||||
quote! {}
|
||||
}
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{parse_quote, Data, DeriveInput};
|
||||
use syn::{parse_quote, Data, DeriveInput, Fields};
|
||||
|
||||
use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};
|
||||
|
||||
@ -15,7 +15,6 @@ fn get_arms(ast: &DeriveInput) -> syn::Result<Vec<TokenStream>> {
|
||||
let type_properties = ast.get_type_properties()?;
|
||||
|
||||
for variant in variants {
|
||||
use syn::Fields::*;
|
||||
let ident = &variant.ident;
|
||||
let variant_properties = variant.get_variant_properties()?;
|
||||
|
||||
@ -28,9 +27,9 @@ fn get_arms(ast: &DeriveInput) -> syn::Result<Vec<TokenStream>> {
|
||||
// (i.e. always `enum.as_ref().to_string() == enum.to_string()`).
|
||||
let output = variant_properties.get_preferred_name(type_properties.case_style);
|
||||
let params = match variant.fields {
|
||||
Unit => quote! {},
|
||||
Unnamed(..) => quote! { (..) },
|
||||
Named(..) => quote! { {..} },
|
||||
Fields::Unit => quote! {},
|
||||
Fields::Unnamed(..) => quote! { (..) },
|
||||
Fields::Named(..) => quote! { {..} },
|
||||
};
|
||||
|
||||
arms.push(quote! { #name::#ident #params => #output });
|
||||
@ -70,7 +69,7 @@ pub enum GenerateTraitVariant {
|
||||
|
||||
pub fn as_static_str_inner(
|
||||
ast: &DeriveInput,
|
||||
trait_variant: GenerateTraitVariant,
|
||||
trait_variant: &GenerateTraitVariant,
|
||||
) -> syn::Result<TokenStream> {
|
||||
let name = &ast.ident;
|
||||
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
|
||||
|
@ -69,7 +69,7 @@ pub fn from_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
Fields::Unit => quote! {},
|
||||
Fields::Unnamed(fields) => {
|
||||
let defaults =
|
||||
::std::iter::repeat(quote!(Default::default())).take(fields.unnamed.len());
|
||||
::core::iter::repeat(quote!(Default::default())).take(fields.unnamed.len());
|
||||
quote! { (#(#defaults),*) }
|
||||
}
|
||||
Fields::Named(fields) => {
|
||||
@ -100,10 +100,10 @@ pub fn from_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
|
||||
let try_from_str = try_from_str(
|
||||
name,
|
||||
impl_generics,
|
||||
ty_generics,
|
||||
&impl_generics,
|
||||
&ty_generics,
|
||||
where_clause,
|
||||
strum_module_path,
|
||||
&strum_module_path,
|
||||
);
|
||||
|
||||
Ok(quote! {
|
||||
@ -115,10 +115,10 @@ pub fn from_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
#[rustversion::before(1.34)]
|
||||
fn try_from_str(
|
||||
_name: &proc_macro2::Ident,
|
||||
_impl_generics: syn::ImplGenerics,
|
||||
_ty_generics: syn::TypeGenerics,
|
||||
_impl_generics: &syn::ImplGenerics,
|
||||
_ty_generics: &syn::TypeGenerics,
|
||||
_where_clause: Option<&syn::WhereClause>,
|
||||
_strum_module_path: syn::Path,
|
||||
_strum_module_path: &syn::Path,
|
||||
) -> TokenStream {
|
||||
Default::default()
|
||||
}
|
||||
@ -126,10 +126,10 @@ fn try_from_str(
|
||||
#[rustversion::since(1.34)]
|
||||
fn try_from_str(
|
||||
name: &proc_macro2::Ident,
|
||||
impl_generics: syn::ImplGenerics,
|
||||
ty_generics: syn::TypeGenerics,
|
||||
impl_generics: &syn::ImplGenerics,
|
||||
ty_generics: &syn::TypeGenerics,
|
||||
where_clause: Option<&syn::WhereClause>,
|
||||
strum_module_path: syn::Path,
|
||||
strum_module_path: &syn::Path,
|
||||
) -> TokenStream {
|
||||
quote! {
|
||||
#[allow(clippy::use_self)]
|
||||
|
@ -1,6 +1,6 @@
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{Data, DeriveInput};
|
||||
use syn::{Data, DeriveInput, Fields};
|
||||
|
||||
use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};
|
||||
|
||||
@ -15,7 +15,6 @@ pub fn to_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
let type_properties = ast.get_type_properties()?;
|
||||
let mut arms = Vec::new();
|
||||
for variant in variants {
|
||||
use syn::Fields::*;
|
||||
let ident = &variant.ident;
|
||||
let variant_properties = variant.get_variant_properties()?;
|
||||
|
||||
@ -27,9 +26,9 @@ pub fn to_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
|
||||
let output = variant_properties.get_preferred_name(type_properties.case_style);
|
||||
|
||||
let params = match variant.fields {
|
||||
Unit => quote! {},
|
||||
Unnamed(..) => quote! { (..) },
|
||||
Named(..) => quote! { {..} },
|
||||
Fields::Unit => quote! {},
|
||||
Fields::Unnamed(..) => quote! { (..) },
|
||||
Fields::Named(..) => quote! { {..} },
|
||||
};
|
||||
|
||||
arms.push(quote! { #name::#ident #params => ::std::string::String::from(#output) });
|
||||
|
@ -1,8 +1,6 @@
|
||||
#![allow(unused_imports)]
|
||||
use strum::*;
|
||||
use strum::{Display, EnumCount, EnumDiscriminants, EnumString};
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Eq, PartialEq, EnumString, ToString, EnumCount, EnumDiscriminants)]
|
||||
#[derive(Debug, Eq, PartialEq, EnumString, Display, EnumCount, EnumDiscriminants)]
|
||||
pub enum Color {
|
||||
/// Docs on red
|
||||
#[strum(to_string = "RedRed")]
|
||||
|
@ -1,7 +1,7 @@
|
||||
use strum::{EnumCount, EnumDiscriminants, EnumString, ToString};
|
||||
use strum::{Display, EnumCount, EnumDiscriminants, EnumString};
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Eq, PartialEq, EnumString, ToString, EnumCount, EnumDiscriminants)]
|
||||
#[derive(Debug, Eq, PartialEq, EnumString, Display, EnumCount, EnumDiscriminants)]
|
||||
enum Color {
|
||||
/// Random Docs
|
||||
#[strum(to_string = "RedRed")]
|
||||
|
@ -1,3 +1,5 @@
|
||||
#![allow(deprecated)]
|
||||
|
||||
use std::str::FromStr;
|
||||
use strum::{AsRefStr, AsStaticRef, AsStaticStr, EnumString, IntoStaticStr};
|
||||
|
||||
|
@ -179,8 +179,8 @@ fn from_test() {
|
||||
|
||||
#[test]
|
||||
fn from_ref_test() {
|
||||
assert_eq!(EnumIntoDiscriminants::A, (&EnumInto::A(true)).into());
|
||||
assert_eq!(EnumIntoDiscriminants::B, (&EnumInto::B(1)).into());
|
||||
assert_eq!(EnumIntoDiscriminants::A, (EnumInto::A(true)).into());
|
||||
assert_eq!(EnumIntoDiscriminants::B, (EnumInto::B(1)).into());
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@ -201,7 +201,7 @@ fn from_test_complex() {
|
||||
#[test]
|
||||
fn from_ref_test_complex() {
|
||||
let rara = Rara;
|
||||
assert_eq!(EnumIntoComplexVars::A, (&EnumIntoComplex::A(&rara)).into());
|
||||
assert_eq!(EnumIntoComplexVars::A, (EnumIntoComplex::A(&rara)).into());
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
|
@ -71,6 +71,18 @@ fn non_plain_camel() {
|
||||
|
||||
#[test]
|
||||
fn clap_and_structopt() {
|
||||
#[derive(Debug, StructOpt)]
|
||||
#[allow(unused)]
|
||||
struct StructOptExample {
|
||||
/// The main color
|
||||
#[structopt(
|
||||
long = "color",
|
||||
default_value = "Color::Blue",
|
||||
raw(possible_values = "Color::VARIANTS")
|
||||
)]
|
||||
color: Color,
|
||||
}
|
||||
|
||||
#[derive(Debug, EnumString, EnumVariantNames)]
|
||||
#[strum(serialize_all = "kebab_case")]
|
||||
enum Color {
|
||||
@ -91,18 +103,6 @@ fn clap_and_structopt() {
|
||||
.possible_values(Color::VARIANTS)
|
||||
.case_insensitive(true),
|
||||
);
|
||||
|
||||
#[derive(Debug, StructOpt)]
|
||||
#[allow(unused)]
|
||||
struct StructOptExample {
|
||||
/// The main color
|
||||
#[structopt(
|
||||
long = "color",
|
||||
default_value = "Color::Blue",
|
||||
raw(possible_values = "Color::VARIANTS")
|
||||
)]
|
||||
color: Color,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -1,9 +1,9 @@
|
||||
/// test serialize_all cooperation with other macroses
|
||||
/// test `serialize_all` cooperation with other macroses
|
||||
use std::str::FromStr;
|
||||
use std::string::ToString;
|
||||
use strum::{EnumString, IntoStaticStr, ToString};
|
||||
use strum::{Display, EnumString, IntoStaticStr};
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, EnumString, ToString, IntoStaticStr)]
|
||||
#[derive(Debug, Eq, PartialEq, EnumString, Display, IntoStaticStr)]
|
||||
#[strum(serialize_all = "title_case")]
|
||||
enum Foo1 {
|
||||
DarkBlack,
|
||||
@ -18,7 +18,7 @@ fn test_serialize_all_title_case() {
|
||||
assert_eq!("Dark Black", <&'static str>::from(Foo1::DarkBlack));
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, EnumString, ToString, IntoStaticStr)]
|
||||
#[derive(Debug, Eq, PartialEq, EnumString, Display, IntoStaticStr)]
|
||||
#[strum(serialize_all = "UPPERCASE")]
|
||||
enum Foo2 {
|
||||
DarkBlack,
|
||||
|
@ -1,3 +1,5 @@
|
||||
#![allow(deprecated)]
|
||||
|
||||
use std::str::FromStr;
|
||||
use std::string::ToString;
|
||||
use strum::{EnumString, ToString};
|
||||
|
Loading…
Reference in New Issue
Block a user