1
0
mirror of https://github.com/danog/strum.git synced 2024-12-02 09:27:57 +01:00

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
This commit is contained in:
Peter Glotfelty 2019-03-03 23:27:59 -08:00 committed by GitHub
parent 7605c67ec6
commit 68d7fba35b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 107 additions and 74 deletions

View File

@ -3,6 +3,7 @@ rust:
- stable
- beta
- nightly
- 1.26.0
matrix:
allow_failures:
- rust: nightly

View File

@ -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.

View File

@ -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" }

View File

@ -1,6 +1,6 @@
[package]
name = "strum_macros"
version = "0.13.0"
version = "0.14.0"
authors = ["Peter Glotfelty <peglotfe@microsoft.com>"]
license = "MIT"

View File

@ -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 {

View File

@ -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

View File

@ -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::<Vec<_>>())
.collect::<Vec<&syn::Meta>>();
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::<Vec<_>>();
// 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::<Vec<_>>();
})
.collect::<Vec<_>>();
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)*

View File

@ -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::<syn::Ident>(&format!("{}Iter", name)).unwrap();
quote!{
quote! {
#[allow(missing_docs)]
#vis struct #iter_name #ty_generics {
idx: usize,

View File

@ -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 {

View File

@ -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 {

View File

@ -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> {

View File

@ -107,7 +107,8 @@ pub fn extract_attrs(meta: &[Meta], attr: &str, prop: &str) -> Vec<String> {
}
}
_ => 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<String> {
}
}
_ => None,
}).collect()
})
.collect()
}
pub fn unique_attr(attrs: &[Meta], attr: &str, prop: &str) -> Option<String> {

View File

@ -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 {

View File

@ -1,6 +1,6 @@
[package]
name = "strum_tests"
version = "0.13.0"
version = "0.14.0"
authors = ["Peter Glotfelty <peglotfe@microsoft.com>"]
[dependencies]

View File

@ -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),
}

View File

@ -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")]

View File

@ -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),
}