Skip to content
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

Clippy lints and some minor nitpicks #212

Merged
merged 6 commits into from Feb 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .clippy.toml
@@ -0,0 +1 @@
msrv = "1.32.0"
4 changes: 2 additions & 2 deletions strum/src/additional_attributes.rs
Expand Up @@ -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:
Expand All @@ -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.
Expand Down
10 changes: 5 additions & 5 deletions strum/src/lib.rs
Expand Up @@ -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]
Expand All @@ -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 {
Expand Down Expand Up @@ -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
///
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion strum_macros/src/helpers/case_style.rs
Expand Up @@ -7,6 +7,7 @@ use syn::{
Ident, LitStr,
};

#[allow(clippy::enum_variant_names)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CaseStyle {
CamelCase,
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions strum_macros/src/helpers/metadata.rs
Expand Up @@ -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>>;
}

Expand Down Expand Up @@ -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()?;

Expand Down
2 changes: 1 addition & 1 deletion strum_macros/src/helpers/mod.rs
Expand Up @@ -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\"))]",
Expand Down
8 changes: 3 additions & 5 deletions strum_macros/src/helpers/type_props.rs
Expand Up @@ -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))
}
}
24 changes: 11 additions & 13 deletions strum_macros/src/helpers/variant_props.rs
Expand Up @@ -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> {
Expand All @@ -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;
Expand Down
36 changes: 18 additions & 18 deletions strum_macros/src/lib.rs
Expand Up @@ -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.
Expand All @@ -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;
Expand Down Expand Up @@ -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),
/// }
/// }
/// }
Expand Down Expand Up @@ -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")]`.
Expand Down Expand Up @@ -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,
&macros::as_ref_str::GenerateTraitVariant::AsStaticStr,
)
.unwrap_or_else(|err| err.to_compile_error());
debug_print_generated(&ast, &toks);
Expand Down Expand Up @@ -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,
&macros::as_ref_str::GenerateTraitVariant::From,
)
.unwrap_or_else(|err| err.to_compile_error());
debug_print_generated(&ast, &toks);
Expand Down Expand Up @@ -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
/// }
/// }
Expand Down
19 changes: 7 additions & 12 deletions strum_macros/src/macros/enum_discriminants.rs
@@ -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};

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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! { { .. } }
}
};
Expand Down
10 changes: 4 additions & 6 deletions strum_macros/src/macros/enum_iter.rs
@@ -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};

Expand Down Expand Up @@ -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()
Expand Down
9 changes: 4 additions & 5 deletions strum_macros/src/macros/enum_messages.rs
@@ -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};

Expand All @@ -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.
Expand Down
11 changes: 5 additions & 6 deletions strum_macros/src/macros/enum_properties.rs
@@ -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};

Expand All @@ -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 });
Expand Down