From 68d7fba35babb9f2621811c994f7e456b67f072f Mon Sep 17 00:00:00 2001 From: Peter Glotfelty Date: Sun, 3 Mar 2019 23:27:59 -0800 Subject: [PATCH] Ran rustfmt on the whole tree and added a note about compatibility (#44) * Ran rustfmt on the whole tree and added a note about compatibility * Removing a doc-comment --- .travis.yml | 1 + README.md | 32 ++++++++++++++---------- strum/Cargo.toml | 2 +- strum/src/lib.rs | 8 +++--- strum_macros/Cargo.toml | 2 +- strum_macros/src/display.rs | 12 ++++----- strum_macros/src/enum_count.rs | 3 ++- strum_macros/src/enum_discriminants.rs | 13 ++++++---- strum_macros/src/enum_iter.rs | 6 ++--- strum_macros/src/enum_messages.rs | 18 +++++++------- strum_macros/src/enum_properties.rs | 33 ++++++++++++++----------- strum_macros/src/from_string.rs | 8 +++--- strum_macros/src/helpers.rs | 6 +++-- strum_macros/src/to_string.rs | 12 ++++----- strum_tests/Cargo.toml | 2 +- strum_tests/src/lib.rs | 16 ++++++++++++ strum_tests/src/main.rs | 3 ++- strum_tests/tests/enum_discriminants.rs | 4 +-- 18 files changed, 107 insertions(+), 74 deletions(-) diff --git a/.travis.yml b/.travis.yml index f61a824..28d1103 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,6 +3,7 @@ rust: - stable - beta - nightly + - 1.26.0 matrix: allow_failures: - rust: nightly diff --git a/README.md b/README.md index db8e14b..59203ec 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,12 @@ Strum is a set of macros and traits for working with enums and strings easier in Rust. +# Compatibility + +Strum is compatible with versions of rustc >= 1.26.0. That's the earliest version of stable rust that supports +impl trait. Pull Requests that improve compatibility with older versions are welcome, but new feature work +will focus on the current version of rust with an effort to avoid breaking compatibility with older versions. + # Including Strum in Your Project Import strum and strum_macros into your project by adding the following lines to your @@ -14,8 +20,8 @@ Cargo.toml. Strum_macros contains the macros needed to derive all the traits in ```toml [dependencies] -strum = "0.13.0" -strum_macros = "0.13.0" +strum = "0.14.0" +strum_macros = "0.14.0" ``` And add these lines to the root of your project, either lib.rs or main.rs. @@ -97,7 +103,7 @@ Strum has implemented the following macros: Section for more information on using this feature. 2. `Display` / `ToString`: prints out the given enum. This enables you to perform round trip - style conversions from enum into string and back again for unit style variants. `ToString` and + style conversions from enum into string and back again for unit style variants. `ToString` and `Display` choose which serialization to used based on the following criteria: 1. If there is a `to_string` property, this value will be used. There can only be one per variant. @@ -131,12 +137,12 @@ Strum has implemented the following macros: } ``` -3. `AsRefStr`: this derive implements `AsRef` on your enum using the same rules as - `ToString` for determining what string is returned. The difference is that `as_ref()` returns +3. `AsRefStr`: this derive implements `AsRef` on your enum using the same rules as + `ToString` for determining what string is returned. The difference is that `as_ref()` returns a `&str` instead of a `String` so you don't allocate any additional memory with each call. 4. `IntoStaticStr`: this trait implements `From` and `From<&'a YourEnum>` for `&'static str`. This is - useful for turning an enum variant into a static string. The Rust `std` provides a blanket impl of the + useful for turning an enum variant into a static string. The Rust `std` provides a blanket impl of the reverse direction - i.e. `impl Into<&'static str> for YourEnum`. ```rust @@ -154,23 +160,23 @@ Strum has implemented the following macros: // The following won't work because the lifetime is incorrect so we can use.as_static() instead. // let wrong: &'static str = state.as_ref(); let right: &'static str = state.into(); - println!("{}", right); + println!("{}", right); } fn main() { print_state(&"hello world".to_string()) } - ``` + ``` -4. `AsStaticStr`: **Deprecated since version 0.13.0. Prefer IntoStaticStr instead.** +4. `AsStaticStr`: **Deprecated since version 0.13.0. Prefer IntoStaticStr instead.** This is similar to `AsRefStr`, but returns a `'static` reference to a string which is helpful - in some scenarios. This macro implements `strum::AsStaticRef` which adds a method `.to_static()` that + in some scenarios. This macro implements `strum::AsStaticRef` which adds a method `.to_static()` that returns a `&'static str`. ```rust extern crate strum; #[macro_use] extern crate strum_macros; - + use strum::AsStaticRef; #[derive(AsStaticStr)] @@ -181,7 +187,7 @@ Strum has implemented the following macros: fn print_state<'a>(s:&'a str) { let right: &'static str = State::Initial(s).as_static(); - println!("{}", right); + println!("{}", right); } ``` @@ -408,7 +414,7 @@ Strum has implemented the following macros: ```rust extern crate strum; - #[macro_use] + #[macro_use] extern crate strum_macros; use strum::{IntoEnumIterator, EnumCount}; diff --git a/strum/Cargo.toml b/strum/Cargo.toml index 603d0e0..5232df1 100644 --- a/strum/Cargo.toml +++ b/strum/Cargo.toml @@ -13,7 +13,7 @@ homepage = "https://github.com/Peternator7/strum" readme = "../README.md" [dev-dependencies] -strum_macros = { path = "../strum_macros", version = "0.13.0" } +strum_macros = { path = "../strum_macros", version = "0.14.0" } [badges] travis-ci = { repository = "Peternator7/strum" } \ No newline at end of file diff --git a/strum/src/lib.rs b/strum/src/lib.rs index e34a839..e4c4ad9 100644 --- a/strum/src/lib.rs +++ b/strum/src/lib.rs @@ -122,9 +122,9 @@ //! 3. `AsRefStr`: this derive implements `AsRef` on your enum using the same rules as //! `ToString` for determining what string is returned. The difference is that `as_ref()` returns //! a borrowed `str` instead of a `String` so you can save an allocation. -//! +//! //! 4. `IntoStaticStr`: this trait implements `From` and `From<&'a YourEnum>` for `&'static str`. This is -//! useful for turning an enum variant into a static string. The Rust `std` provides a blanket impl of the +//! useful for turning an enum variant into a static string. The Rust `std` provides a blanket impl of the //! reverse direction - i.e. `impl Into<&'static str> for YourEnum`. //! //! ```rust @@ -142,13 +142,13 @@ //! // The following won't work because the lifetime is incorrect so we can use.as_static() instead. //! // let wrong: &'static str = state.as_ref(); //! let right: &'static str = state.into(); -//! println!("{}", right); +//! println!("{}", right); //! } //! //! fn main() { //! print_state(&"hello world".to_string()) //! } -//! ``` +//! ``` //! //! 4. `EnumIter`: iterate over the variants of an Enum. Any additional data on your variants will be //! set to `Default::default()`. The macro implements `strum::IntoEnumIter` on your enum and diff --git a/strum_macros/Cargo.toml b/strum_macros/Cargo.toml index 364acc8..6994a69 100644 --- a/strum_macros/Cargo.toml +++ b/strum_macros/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "strum_macros" -version = "0.13.0" +version = "0.14.0" authors = ["Peter Glotfelty "] license = "MIT" diff --git a/strum_macros/src/display.rs b/strum_macros/src/display.rs index c0223bd..0529153 100644 --- a/strum_macros/src/display.rs +++ b/strum_macros/src/display.rs @@ -41,19 +41,19 @@ pub fn display_inner(ast: &syn::DeriveInput) -> TokenStream { }; let params = match variant.fields { - Unit => quote!{}, - Unnamed(..) => quote!{ (..) }, - Named(..) => quote!{ {..} }, + Unit => quote! {}, + Unnamed(..) => quote! { (..) }, + Named(..) => quote! { {..} }, }; - arms.push(quote!{ #name::#ident #params => f.write_str(#output) }); + arms.push(quote! { #name::#ident #params => f.write_str(#output) }); } if arms.len() < variants.len() { - arms.push(quote!{ _ => panic!("fmt() called on disabled variant.")}) + arms.push(quote! { _ => panic!("fmt() called on disabled variant.")}) } - quote!{ + quote! { impl #impl_generics ::std::fmt::Display for #name #ty_generics #where_clause { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> { match *self { diff --git a/strum_macros/src/enum_count.rs b/strum_macros/src/enum_count.rs index 6687cec..c22cfa5 100644 --- a/strum_macros/src/enum_count.rs +++ b/strum_macros/src/enum_count.rs @@ -6,6 +6,7 @@ pub(crate) fn enum_count_inner(ast: &syn::DeriveInput) -> TokenStream { syn::Data::Enum(ref v) => v.variants.len(), _ => panic!("EnumCount can only be used with enums"), }; + // Used in the quasi-quotation below as `#name` let name = &ast.ident; let const_name = &syn::Ident::new( @@ -17,7 +18,7 @@ pub(crate) fn enum_count_inner(ast: &syn::DeriveInput) -> TokenStream { let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); quote! { - // The generated impl + // Implementation impl #impl_generics ::strum::EnumCount for #name #ty_generics #where_clause { fn count() -> usize { #n diff --git a/strum_macros/src/enum_discriminants.rs b/strum_macros/src/enum_discriminants.rs index 2108f67..3135b1f 100644 --- a/strum_macros/src/enum_discriminants.rs +++ b/strum_macros/src/enum_discriminants.rs @@ -19,6 +19,7 @@ pub fn enum_discriminants_inner(ast: &syn::DeriveInput) -> TokenStream { let discriminant_attrs = get_meta_list(type_meta.iter(), "strum_discriminants") .flat_map(|meta| extract_list_metas(meta).collect::>()) .collect::>(); + let derives = get_meta_list(discriminant_attrs.iter().map(|&m| m), "derive") .flat_map(extract_list_metas) .filter_map(get_meta_ident) @@ -44,7 +45,8 @@ pub fn enum_discriminants_inner(ast: &syn::DeriveInput) -> TokenStream { filter_metas(discriminant_attrs.iter().map(|&m| m), |meta| match meta { syn::Meta::List(ref metalist) => metalist.ident != "derive" && metalist.ident != "name", _ => true, - }).map(|meta| quote! { #[ #meta ] }) + }) + .map(|meta| quote! { #[ #meta ] }) .collect::>(); // Add the variants without fields, but exclude the `strum` meta item @@ -60,7 +62,7 @@ pub fn enum_discriminants_inner(ast: &syn::DeriveInput) -> TokenStream { }) }); - discriminants.push(quote!{ #(#attrs)* #ident }); + discriminants.push(quote! { #(#attrs)* #ident }); } // Ideally: @@ -89,7 +91,7 @@ pub fn enum_discriminants_inner(ast: &syn::DeriveInput) -> TokenStream { use syn::Fields::*; let params = match variant.fields { - Unit => quote!{}, + Unit => quote! {}, Unnamed(ref _fields) => { quote! { (..) } } @@ -99,7 +101,8 @@ pub fn enum_discriminants_inner(ast: &syn::DeriveInput) -> TokenStream { }; quote! { #name::#ident #params => #discriminants_name::#ident } - }).collect::>(); + }) + .collect::>(); let from_fn_body = quote! { match val { #(#arms),* } }; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); @@ -129,7 +132,7 @@ pub fn enum_discriminants_inner(ast: &syn::DeriveInput) -> TokenStream { } }; - quote!{ + quote! { /// Auto-generated discriminant enum variants #derives #(#pass_though_attributes)* diff --git a/strum_macros/src/enum_iter.rs b/strum_macros/src/enum_iter.rs index 1cb3af6..51c4744 100644 --- a/strum_macros/src/enum_iter.rs +++ b/strum_macros/src/enum_iter.rs @@ -37,7 +37,7 @@ pub fn enum_iter_inner(ast: &syn::DeriveInput) -> TokenStream { use syn::Fields::*; let ident = &variant.ident; let params = match variant.fields { - Unit => quote!{}, + Unit => quote! {}, Unnamed(ref fields) => { let defaults = ::std::iter::repeat(quote!(::std::default::Default::default())) .take(fields.unnamed.len()); @@ -52,13 +52,13 @@ pub fn enum_iter_inner(ast: &syn::DeriveInput) -> TokenStream { } }; - arms.push(quote!{#idx => ::std::option::Option::Some(#name::#ident #params)}); + arms.push(quote! {#idx => ::std::option::Option::Some(#name::#ident #params)}); } let variant_count = arms.len(); arms.push(quote! { _ => ::std::option::Option::None }); let iter_name = syn::parse_str::(&format!("{}Iter", name)).unwrap(); - quote!{ + quote! { #[allow(missing_docs)] #vis struct #iter_name #ty_generics { idx: usize, diff --git a/strum_macros/src/enum_messages.rs b/strum_macros/src/enum_messages.rs index f380de6..b8c1c0d 100644 --- a/strum_macros/src/enum_messages.rs +++ b/strum_macros/src/enum_messages.rs @@ -23,9 +23,9 @@ pub fn enum_message_inner(ast: &syn::DeriveInput) -> TokenStream { use syn::Fields::*; let params = match variant.fields { - Unit => quote!{}, - Unnamed(..) => quote!{ (..) }, - Named(..) => quote!{ {..} }, + Unit => quote! {}, + Unnamed(..) => quote! { (..) }, + Named(..) => quote! { {..} }, }; // You can't disable getting the serializations. @@ -36,7 +36,7 @@ pub fn enum_message_inner(ast: &syn::DeriveInput) -> TokenStream { } let count = serialization_variants.len(); - serializations.push(quote!{ + serializations.push(quote! { &#name::#ident #params => { static ARR: [&'static str; #count] = [#(#serialization_variants),*]; &ARR @@ -53,7 +53,7 @@ pub fn enum_message_inner(ast: &syn::DeriveInput) -> TokenStream { let params = params.clone(); // Push the simple message. - let tokens = quote!{ &#name::#ident #params => ::std::option::Option::Some(#msg) }; + let tokens = quote! { &#name::#ident #params => ::std::option::Option::Some(#msg) }; arms.push(tokens.clone()); if detailed_messages.is_none() { @@ -65,19 +65,19 @@ pub fn enum_message_inner(ast: &syn::DeriveInput) -> TokenStream { let params = params.clone(); // Push the simple message. detailed_arms - .push(quote!{ &#name::#ident #params => ::std::option::Option::Some(#msg) }); + .push(quote! { &#name::#ident #params => ::std::option::Option::Some(#msg) }); } } if arms.len() < variants.len() { - arms.push(quote!{ _ => ::std::option::Option::None }); + arms.push(quote! { _ => ::std::option::Option::None }); } if detailed_arms.len() < variants.len() { - detailed_arms.push(quote!{ _ => ::std::option::Option::None }); + detailed_arms.push(quote! { _ => ::std::option::Option::None }); } - quote!{ + quote! { impl #impl_generics ::strum::EnumMessage for #name #ty_generics #where_clause { fn get_message(&self) -> ::std::option::Option<&str> { match self { diff --git a/strum_macros/src/enum_properties.rs b/strum_macros/src/enum_properties.rs index bc63ea9..97a9395 100644 --- a/strum_macros/src/enum_properties.rs +++ b/strum_macros/src/enum_properties.rs @@ -20,7 +20,8 @@ fn extract_properties(meta: &[Meta]) -> Vec<(&syn::Ident, &syn::Lit)> { } } _ => None, - }).flat_map(|prop| prop) + }) + .flat_map(|prop| prop) .filter_map(|prop| match *prop { NestedMeta::Meta(Meta::List(MetaList { ref ident, @@ -34,14 +35,16 @@ fn extract_properties(meta: &[Meta]) -> Vec<(&syn::Ident, &syn::Lit)> { } } _ => None, - }).flat_map(|prop| prop) + }) + .flat_map(|prop| prop) // Only look at key value pairs .filter_map(|prop| match *prop { NestedMeta::Meta(Meta::NameValue(MetaNameValue { ref ident, ref lit, .. })) => Some((ident, lit)), _ => None, - }).collect() + }) + .collect() } pub fn enum_properties_inner(ast: &syn::DeriveInput) -> TokenStream { @@ -66,9 +69,9 @@ pub fn enum_properties_inner(ast: &syn::DeriveInput) -> TokenStream { use syn::Fields::*; let params = match variant.fields { - Unit => quote!{}, - Unnamed(..) => quote!{ (..) }, - Named(..) => quote!{ {..} }, + Unit => quote! {}, + Unnamed(..) => quote! { (..) }, + Named(..) => quote! { {..} }, }; for (key, value) in extract_properties(&meta) { @@ -76,19 +79,19 @@ pub fn enum_properties_inner(ast: &syn::DeriveInput) -> TokenStream { let key = key.to_string(); match value { Str(ref s, ..) => { - string_arms.push(quote!{ #key => ::std::option::Option::Some( #s )}) + string_arms.push(quote! { #key => ::std::option::Option::Some( #s )}) } - Bool(b) => bool_arms.push(quote!{ #key => ::std::option::Option::Some( #b )}), - Int(i, ..) => num_arms.push(quote!{ #key => ::std::option::Option::Some( #i )}), + Bool(b) => bool_arms.push(quote! { #key => ::std::option::Option::Some( #b )}), + Int(i, ..) => num_arms.push(quote! { #key => ::std::option::Option::Some( #i )}), _ => {} } } - string_arms.push(quote!{ _ => ::std::option::Option::None }); - bool_arms.push(quote!{ _ => ::std::option::Option::None }); - num_arms.push(quote!{ _ => ::std::option::Option::None }); + string_arms.push(quote! { _ => ::std::option::Option::None }); + bool_arms.push(quote! { _ => ::std::option::Option::None }); + num_arms.push(quote! { _ => ::std::option::Option::None }); - arms.push(quote!{ + arms.push(quote! { &#name::#ident #params => { match prop { #(#string_arms),* @@ -98,10 +101,10 @@ pub fn enum_properties_inner(ast: &syn::DeriveInput) -> TokenStream { } if arms.len() < variants.len() { - arms.push(quote!{ _ => ::std::option::Option::None }); + arms.push(quote! { _ => ::std::option::Option::None }); } - quote!{ + quote! { impl #impl_generics ::strum::EnumProperty for #name #ty_generics #where_clause { fn get_str(&self, prop: &str) -> ::std::option::Option<&'static str> { match self { diff --git a/strum_macros/src/from_string.rs b/strum_macros/src/from_string.rs index a688369..2960fe1 100644 --- a/strum_macros/src/from_string.rs +++ b/strum_macros/src/from_string.rs @@ -42,7 +42,7 @@ pub fn from_string_inner(ast: &syn::DeriveInput) -> TokenStream { panic!("Default only works on unit structs with a single String parameter"); } - default = quote!{ + default = quote! { default => ::std::result::Result::Ok(#name::#ident (default.into())) }; } else { @@ -59,7 +59,7 @@ pub fn from_string_inner(ast: &syn::DeriveInput) -> TokenStream { } let params = match variant.fields { - Unit => quote!{}, + Unit => quote! {}, Unnamed(ref fields) => { let defaults = ::std::iter::repeat(quote!(Default::default())).take(fields.unnamed.len()); @@ -74,12 +74,12 @@ pub fn from_string_inner(ast: &syn::DeriveInput) -> TokenStream { } }; - arms.push(quote!{ #(#attrs)|* => ::std::result::Result::Ok(#name::#ident #params) }); + arms.push(quote! { #(#attrs)|* => ::std::result::Result::Ok(#name::#ident #params) }); } arms.push(default); - quote!{ + quote! { impl #impl_generics ::std::str::FromStr for #name #ty_generics #where_clause { type Err = ::strum::ParseError; fn from_str(s: &str) -> ::std::result::Result< #name #ty_generics , Self::Err> { diff --git a/strum_macros/src/helpers.rs b/strum_macros/src/helpers.rs index 265500f..2ce74a8 100644 --- a/strum_macros/src/helpers.rs +++ b/strum_macros/src/helpers.rs @@ -107,7 +107,8 @@ pub fn extract_attrs(meta: &[Meta], attr: &str, prop: &str) -> Vec { } } _ => None, - }).flat_map(|nested| nested) + }) + .flat_map(|nested| nested) // Get all the inner elements as long as they start with ser. .filter_map(|meta| match *meta { NestedMeta::Meta(Meta::NameValue(MetaNameValue { @@ -122,7 +123,8 @@ pub fn extract_attrs(meta: &[Meta], attr: &str, prop: &str) -> Vec { } } _ => None, - }).collect() + }) + .collect() } pub fn unique_attr(attrs: &[Meta], attr: &str, prop: &str) -> Option { diff --git a/strum_macros/src/to_string.rs b/strum_macros/src/to_string.rs index a8a94a9..8c97650 100644 --- a/strum_macros/src/to_string.rs +++ b/strum_macros/src/to_string.rs @@ -41,19 +41,19 @@ pub fn to_string_inner(ast: &syn::DeriveInput) -> TokenStream { }; let params = match variant.fields { - Unit => quote!{}, - Unnamed(..) => quote!{ (..) }, - Named(..) => quote!{ {..} }, + Unit => quote! {}, + Unnamed(..) => quote! { (..) }, + Named(..) => quote! { {..} }, }; - arms.push(quote!{ #name::#ident #params => ::std::string::String::from(#output) }); + arms.push(quote! { #name::#ident #params => ::std::string::String::from(#output) }); } if arms.len() < variants.len() { - arms.push(quote!{ _ => panic!("to_string() called on disabled variant.")}) + arms.push(quote! { _ => panic!("to_string() called on disabled variant.")}) } - quote!{ + quote! { impl #impl_generics ::std::string::ToString for #name #ty_generics #where_clause { fn to_string(&self) -> ::std::string::String { match *self { diff --git a/strum_tests/Cargo.toml b/strum_tests/Cargo.toml index 56c2a18..87e700f 100644 --- a/strum_tests/Cargo.toml +++ b/strum_tests/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "strum_tests" -version = "0.13.0" +version = "0.14.0" authors = ["Peter Glotfelty "] [dependencies] diff --git a/strum_tests/src/lib.rs b/strum_tests/src/lib.rs index 8b13789..ed73ccb 100644 --- a/strum_tests/src/lib.rs +++ b/strum_tests/src/lib.rs @@ -1 +1,17 @@ +extern crate strum; +#[macro_use] +extern crate strum_macros; +#[allow(dead_code)] +#[derive(Debug, Eq, PartialEq, EnumString, ToString, EnumCount, EnumDiscriminants)] +pub enum Color { + /// Docs on red + #[strum(to_string = "RedRed")] + Red, + #[strum(serialize = "b", to_string = "blue")] + Blue { hue: usize }, + #[strum(serialize = "y", serialize = "yellow")] + Yellow, + #[strum(disabled = "true")] + Green(String), +} diff --git a/strum_tests/src/main.rs b/strum_tests/src/main.rs index 67e2e36..d2a1123 100644 --- a/strum_tests/src/main.rs +++ b/strum_tests/src/main.rs @@ -3,8 +3,9 @@ extern crate strum; extern crate strum_macros; #[allow(dead_code)] -#[derive(Debug, Eq, PartialEq, EnumString, ToString)] +#[derive(Debug, Eq, PartialEq, EnumString, ToString, EnumCount, EnumDiscriminants)] enum Color { + /// Random Docs #[strum(to_string = "RedRed")] Red, #[strum(serialize = "b", to_string = "blue")] diff --git a/strum_tests/tests/enum_discriminants.rs b/strum_tests/tests/enum_discriminants.rs index e64a668..a0b3f46 100644 --- a/strum_tests/tests/enum_discriminants.rs +++ b/strum_tests/tests/enum_discriminants.rs @@ -124,7 +124,7 @@ fn split_attributes_test() { #[strum_discriminants( name(PassThroughBoo), derive(Display, EnumIter, EnumString), - strum(serialize_all = "snake_case"), + strum(serialize_all = "snake_case") )] enum PassThrough { DarkBlack(bool), @@ -168,7 +168,7 @@ fn from_ref_test() { struct Rara; #[derive(Debug, Eq, PartialEq, EnumDiscriminants)] -#[strum_discriminants(name(EnumIntoComplexVars),)] +#[strum_discriminants(name(EnumIntoComplexVars))] enum EnumIntoComplex<'a, T: 'a> { A(&'a T), }