diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bbc2176..d172e5f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 0.16.0 + +* Added serialize UPPERCASE +* Added "case-styles" to match the formatting convention they imply such as `kebab-case` and `camelCase`. +* Added Enum Variant Names to improve compatibility with `structopt` and `clap`. [#56](https://github.com/Peternator7/strum/pull/56) +* Added derive re-export to `strum` to allow re-exporting macros from main crate. [#57](https://github.com/Peternator7/strum/pull/57) +* Bumped syn and quote to `1.0`. This raises minimal compatible rust version to `1.31`. +* Did internal refactoring to improve organization of code. Shouldn't change user-facing api though. +* Added license file to subdirectories so they are included in crate distros. + ## 0.15.0 ### Added diff --git a/README.md b/README.md index 87fb1f81..75ecd2d5 100644 --- a/README.md +++ b/README.md @@ -4,17 +4,14 @@ [![Latest Version](https://img.shields.io/crates/v/strum.svg)](https://crates.io/crates/strum) [![Rust Documentation](https://docs.rs/strum/badge.svg)](https://docs.rs/strum) -Strum is a set of macros and traits for working with -enums and strings easier in Rust. +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 +Strum is compatible with versions of rustc >= 1.31.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. -Versions of rust prior to 1.31.0 don't support importing procedural macros by path. See [this wiki page](https://github.com/Peternator7/strum/wiki/Macro-Renames) if you are finding that one of Strum's macros collides with a macro being imported by a different crate. *You do not need this in versions of rust >= 1.31.0* - # Including Strum in Your Project Import strum and strum_macros into your project by adding the following lines to your @@ -22,8 +19,8 @@ Cargo.toml. Strum_macros contains the macros needed to derive all the traits in ```toml [dependencies] -strum = "0.15.0" -strum_macros = "0.15.0" +strum = "0.16.0" +strum_macros = "0.16.0" ``` And add these lines to the root of your project, either lib.rs or main.rs. @@ -38,6 +35,23 @@ extern crate strum_macros; use strum_macros::{Display, EnumIter}; // etc. ``` +# Strum Macros + +Strum has implemented the following macros: + +| Macro | Description | +| --- | ----------- | +| [EnumString] | Converts strings to enum variants based on their name | +| [Display] | Converts enum variants to strings | +| [AsRefStr] | Converts enum variants to `&'static str` | +| [IntoStaticStr] | Implements `From for &'static str` on an enum | +| [EnumVariantNames] | Adds a `variants` method returning an array of discriminant names | +| [EnumIter] | Creates a new type that iterates of the variants of an enum. | +| [EnumProperty] | Add custom properties to enum variants. | +| [EnumMessage] | Add a verbose message to an enum variant. | +| [EnumDiscriminants] | Generate a new type with only the discriminant names. | +| [EnumCount] | Add a constant `usize` equal to the number of variantes. | + # Contributing Thanks for your interest in contributing. The project is divided into 3 parts, the traits are in the @@ -51,600 +65,21 @@ To see the generated code, set the STRUM_DEBUG environment variable before compi `STRUM_DEBUG=1` will dump all of the generated code for every type. `STRUM_DEBUG=YourType` will only dump the code generated on a type named `YourType`. -# Strum Macros - -Strum has implemented the following macros: - -| Macro | Description | -| --- | ----------- | -| [EnumString](#EnumString) | Converts strings to enum variants based on their name | -| [Display](#Display) | Converts enum variants to strings | -| [AsRefStr](#AsRefStr) | Converts enum variants to `&'static str` | -| [IntoStaticStr](#IntoStaticStr) | Implements `From for &'static str` on an enum | -| [EnumVariantNames](#EnumVariantNames) | Adds a `variants` method returning an array of discriminant names | -| [EnumIter](#EnumIter) | Creates a new type that iterates of the variants of an enum. | -| [EnumProperty](#EnumProperty) | Add custom properties to enum variants. | -| [EnumMessage](#EnumMessage) | Add a verbose message to an enum variant. | -| [EnumDiscriminants](#EnumDiscriminants) | Generate a new type with only the discriminant names. | -| [EnumCount](#EnumCount) | Add a constant `usize` equal to the number of variantes. | - -## EnumString - -auto-derives `std::str::FromStr` on the enum. 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. -Multiple deserializations can be added to the same variant. If the variant contains additional data, -they will be set to their default values upon deserialization. - -The `default` attribute can be applied to a tuple variant with a single data parameter. When a match isn't -found, the given variant will be returned and the input string will be captured in the parameter. - -Here is an example of the code generated by deriving `EnumString`. - -```rust -extern crate strum; -#[macro_use] extern crate strum_macros; -#[derive(EnumString)] -enum Color { - Red, - - // The Default value will be inserted into range if we match "Green". - Green { range:usize }, - - // We can match on multiple different patterns. - #[strum(serialize="blue",serialize="b")] - Blue(usize), - - // Notice that we can disable certain variants from being found - #[strum(disabled="true")] - Yellow, -} - -/* -//The generated code will look like: -impl std::str::FromStr for Color { - type Err = ::strum::ParseError; - - fn from_str(s: &str) -> ::std::result::Result { - match s { - "Red" => ::std::result::Result::Ok(Color::Red), - "Green" => ::std::result::Result::Ok(Color::Green { range:Default::default() }), - "blue" | "b" => ::std::result::Result::Ok(Color::Blue(Default::default())), - _ => ::std::result::Result::Err(::strum::ParseError::VariantNotFound), - } - } -} -*/ -``` - -Note that the implementation of `FromStr` by default only matches on the name of the -variant. There is an option to match on different case conversions through the -`#[strum(serialize_all = "snake_case")]` type attribute. See the **Additional Attributes** -Section for more information on using this feature. - -## Display - -Print out the given enum. This enables you to perform round trip style conversions -from enum into string and back again for unit style variants. -`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. -2. Of the various `serialize` properties, the value with the longest length is chosen. If that - behavior isn't desired, you should use `to_string`. -3. The name of the variant will be used if there are no `serialize` or `to_string` attributes. - -```rust -// You need to bring the type into scope to use it!!! -use std::string::ToString; - -#[derive(Display, Debug)] -enum Color { - #[strum(serialize="redred")] - Red, - Green { range:usize }, - Blue(usize), - Yellow, -} - -// It's simple to iterate over the variants of an enum. -fn debug_colors() { - let red = Color::Red; - assert_eq!(String::from("redred"), red.to_string()); -} - -fn main() { - debug_colors(); -} -``` - -## AsRefStr - -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. - -## IntoStaticStr - -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 reverse direction - i.e. `impl Into<&'static str> for YourEnum`. - -```rust -extern crate strum; -#[macro_use] extern crate strum_macros; - -#[derive(IntoStaticStr)] -enum State<'a> { - Initial(&'a str), - Finished -} - -fn print_state<'a>(s:&'a str) { - let state = State::Initial(s); - // 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); -} - -fn main() { - print_state(&"hello world".to_string()) -} -``` - -## EnumVariantNames - -Adds an `impl` block for the `enum` that adds a static `variants()` method that returns an 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")]`, see **Additional Attributes** below). - -**Note:** This is compatible with the format [clap](https://docs.rs/clap/2) expects for `enums`, meaning this works: - -```rust -use strum::{EnumString, EnumVariantNames}; - -#[derive(EnumString, EnumVariantNames)] -#[strum(serialize_all = "kebab_case")] -enum Color { - Red, - Blue, - Yellow, - RebeccaPurple, -} - -fn main() { - // This is what you get: - assert_eq!( - &Color::variants(), - &["red", "blue", "yellow", "rebecca-purple"] - ); - - // Use it with clap like this: - let args = clap::App::new("app") - .arg(Arg::with_name("color") - .long("color") - .possible_values(&Color::variants()) - .case_insensitive(true)) - .get_matches(); - - // ... -} -``` - -This also works with [structopt](https://docs.rs/structopt/0.2) (assuming the same definition of `Color` as above): - -```rust -#[derive(Debug, StructOpt)] -struct Cli { - /// The main color - #[structopt(long = "color", default_value = "Color::Blue", raw(possible_values = "&Color::variants()"))] - color: Color, -} -``` - -## 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 creates a new type called `YourEnumIter` that is the iterator object. -You cannot derive `EnumIter` on any type with a lifetime bound (`<'a>`) because the iterator would surely -create [unbounded lifetimes](https://doc.rust-lang.org/nightly/nomicon/unbounded-lifetimes.html). - -```rust -// You need to bring the type into scope to use it!!! -use strum::IntoEnumIterator; - -#[derive(EnumIter,Debug)] -enum Color { - Red, - Green { range:usize }, - Blue(usize), - Yellow, -} - -// It's simple to iterate over the variants of an enum. -fn debug_colors() { - for color in Color::iter() { - println!("My favorite color is {:?}", color); - } -} - -fn main() { - debug_colors(); -} -``` - -## EnumMessage - -Encode strings into the enum itself. This macro implements the `strum::EnumMessage` trait. -`EnumMessage` looks for `#[strum(message="...")]` attributes on your variants. -You can also provided a `detailed_message="..."` attribute to create a seperate more detailed message than the first. - -The generated code will look something like: - -```rust -// You need to bring the type into scope to use it!!! -use strum::EnumMessage; - -#[derive(EnumMessage,Debug)] -enum Color { - #[strum(message="Red",detailed_message="This is very red")] - Red, - #[strum(message="Simply Green")] - Green { range:usize }, - #[strum(serialize="b",serialize="blue")] - Blue(usize), -} - -/* -// Generated code -impl ::strum::EnumMessage for Color { - fn get_message(&self) -> ::std::option::Option<&str> { - match self { - &Color::Red => ::std::option::Option::Some("Red"), - &Color::Green {..} => ::std::option::Option::Some("Simply Green"), - _ => None - } - } - - fn get_detailed_message(&self) -> ::std::option::Option<&str> { - match self { - &Color::Red => ::std::option::Option::Some("This is very red"), - &Color::Green {..}=> ::std::option::Option::Some("Simply Green"), - _ => None - } - } - - fn get_serializations(&self) -> &[&str] { - match self { - &Color::Red => { - static ARR: [&'static str; 1] = ["Red"]; - &ARR - }, - &Color::Green {..}=> { - static ARR: [&'static str; 1] = ["Green"]; - &ARR - }, - &Color::Blue (..) => { - static ARR: [&'static str; 2] = ["b", "blue"]; - &ARR - }, - } - } -} -*/ -``` - -## EnumProperty - -Enables the encoding of arbitary constants into enum variants. This method -currently only supports adding additional string values. Other types of literals are still -experimental in the rustc compiler. The generated code works by nesting match statements. -The first match statement matches on the type of the enum, and the inner match statement -matches on the name of the property requested. This design works well for enums with a small -number of variants and properties, but scales linearly with the number of variants so may not -be the best choice in all situations. - -Here's an example: - -```rust -# extern crate strum; -# #[macro_use] extern crate strum_macros; -# use std::fmt::Debug; -// You need to bring the type into scope to use it!!! -use strum::EnumProperty; - -#[derive(EnumProperty,Debug)] -enum Color { - #[strum(props(Red="255",Blue="255",Green="255"))] - White, - #[strum(props(Red="0",Blue="0",Green="0"))] - Black, - #[strum(props(Red="0",Blue="255",Green="0"))] - Blue, - #[strum(props(Red="255",Blue="0",Green="0"))] - Red, - #[strum(props(Red="0",Blue="0",Green="255"))] - Green, -} - -fn main() { - let my_color = Color::Red; - let display = format!("My color is {:?}. It's RGB is {},{},{}", my_color - , my_color.get_str("Red").unwrap() - , my_color.get_str("Green").unwrap() - , my_color.get_str("Blue").unwrap()); -} -``` - -## EnumDiscriminants - -Given an enum named `MyEnum`, generates another enum called `MyEnumDiscriminants` with the same variants, without any data fields. -This is useful when you wish to determine the variant of an enum from a String, but the variants contain any -non-`Default` fields. By default, the generated enum has the following derives: -`Clone, Copy, Debug, PartialEq, Eq`. You can add additional derives using the -`#[strum_discriminants(derive(AdditionalDerive))]` attribute. - -Here's an example: - -```rust -extern crate strum; -#[macro_use] extern crate strum_macros; - -// Bring trait into scope -use std::str::FromStr; - -#[derive(Debug)] -struct NonDefault; - -#[allow(dead_code)] -#[derive(Debug, EnumDiscriminants)] -#[strum_discriminants(derive(EnumString))] -enum MyEnum { - Variant0(NonDefault), - Variant1 { a: NonDefault }, -} - -fn main() { - assert_eq!( - MyEnumDiscriminants::Variant0, - MyEnumDiscriminants::from_str("Variant0").unwrap() - ); -} -``` - -You can also rename the generated enum using the `#[strum_discriminants(name(OtherName))]` -attribute: - -```rust -extern crate strum; -#[macro_use] extern crate strum_macros; -// You need to bring the type into scope to use it!!! -use strum::IntoEnumIterator; - -#[allow(dead_code)] -#[derive(Debug, EnumDiscriminants)] -#[strum_discriminants(derive(EnumIter))] -#[strum_discriminants(name(MyVariants))] -enum MyEnum { - Variant0(bool), - Variant1 { a: bool }, -} - -fn main() { - assert_eq!( - vec![MyVariants::Variant0, MyVariants::Variant1], - MyVariants::iter().collect::>() - ); -} -``` - -When using `#[strum_discriminants()], the derive parameter may be followed by -additional attributes and these will be expanded as attributes on the generated -enum e.g. `#[strum_discriminants(name(SomeOtherName), derive(Serialize), serde(rename_all = "SCREAMING_SNAKE_CASE"))]` - -The derived enum also has the following trait implementations: - -* `impl From for MyEnumDiscriminants` -* `impl<'_enum> From<&'_enum MyEnum> for MyEnumDiscriminants` - -These allow you to get the *Discriminants* enum variant from the original enum: - -```rust -extern crate strum; -#[macro_use] extern crate strum_macros; - -#[derive(Debug, EnumDiscriminants)] -#[strum_discriminants(name(MyVariants))] -enum MyEnum { - Variant0(bool), - Variant1 { a: bool }, -} - -fn main() { - assert_eq!(MyVariants::Variant0, MyEnum::Variant0(true).into()); -} -``` - -## EnumCount - -For a given enum generates implementation of `strum::EnumCount`, -which returns number of variants via `strum::EnumCount::count` method, -also for given `enum MyEnum` generates `const MYENUM_COUNT: usize` -which gives the same value as `strum::EnumCount` (which is usefull for array sizes, etc.). - -```rust -extern crate strum; -#[macro_use] -extern crate strum_macros; - -use strum::{IntoEnumIterator, EnumCount}; - -#[derive(Debug, EnumCount, EnumIter)] -enum Week { - Sunday, - Monday, - Tuesday, - Wednesday, - Thursday, - Friday, - Saturday, -} - -fn main() { - assert_eq!(7, Week::count()); - assert_eq!(Week::count(), WEEK_COUNT); - assert_eq!(Week::iter().count(), WEEK_COUNT); -} -``` - -## ToString - -**Deprecated** Prefer using [`Display`](#Display). All types that implement `std::fmt::Display` have a default implementation of `ToString`.** - -## AsStaticStr - -**Deprecated since version 0.13.0.** Prefer [IntoStaticStr](#IntoStaticStr) instead. - -# Additional Attributes - -Strum supports several custom attributes to modify the generated code. At the enum level, the -`#[strum(serialize_all = "snake_case")]` attribute can be used to change the case used when -serializing to and deserializing from strings: - -```rust -extern crate strum; -#[macro_use] -extern crate strum_macros; - -#[derive(Debug, Eq, PartialEq, ToString)] -#[strum(serialize_all = "snake_case")] -enum Brightness { - DarkBlack, - Dim { - glow: usize, - }, - #[strum(serialize = "bright")] - BrightWhite, -} - -fn main() { - assert_eq!( - String::from("dark_black"), - Brightness::DarkBlack.to_string().as_ref() - ); - assert_eq!( - String::from("dim"), - Brightness::Dim { glow: 0 }.to_string().as_ref() - ); - assert_eq!( - String::from("bright"), - Brightness::BrightWhite.to_string().as_ref() - ); -} -``` - -Custom attributes are applied to a variant by adding `#[strum(parameter="value")]` to the variant. - -- `serialize="..."`: Changes the text that `FromStr()` looks for when parsing a string. This attribute can - be applied multiple times to an element and the enum variant will be parsed if any of them match. - -- `to_string="..."`: Similar to `serialize`. This value will be included when using `FromStr()`. More importantly, - this specifies what text to use when calling `variant.to_string()` with the `ToString` derivation, or when calling `variant.as_ref()` with `AsRefStr`. - -- `default="true"`: Applied to a single variant of an enum. The variant must be a Tuple-like - variant with a single piece of data that can be create from a `&str` i.e. `T: From<&str>`. - The generated code will now return the variant with the input string captured as shown below - instead of failing. - - ```rust,ignore - // Replaces this: - _ => Err(strum::ParseError::VariantNotFound) - // With this in generated code: - default => Ok(Variant(default.into())) - ``` - The plugin will fail if the data doesn't implement From<&str>. You can only have one `default` - on your enum. - -- `disabled="true"`: removes variant from generated code. - -- `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. - -- `detailed_message=".."`: Adds a more detailed message to a variant. If this value is omitted, then - `message` will be used in it's place. - -- `props(key="value")`: Enables associating additional information with a given variant. - -# Examples - -Using `EnumMessage` for quickly implementing `Error` - -```rust -extern crate strum; -#[macro_use] -extern crate strum_macros; -use std::error::Error; -use std::fmt::*; -use strum::EnumMessage; - -#[derive(Debug, EnumMessage)] -enum ServerError { - #[strum(message="A network error occured")] - #[strum(detailed_message="Try checking your connection.")] - NetworkError, - #[strum(message="User input error.")] - #[strum(detailed_message="There was an error parsing user input. Please try again.")] - InvalidUserInputError, -} - -impl Display for ServerError { - fn fmt(&self, f: &mut Formatter) -> Result { - write!(f, "{}", self.get_message().unwrap()) - } -} - -impl Error for ServerError { - fn description(&self) -> &str { - self.get_detailed_message().unwrap() - } -} -``` - -Using `EnumString` to tokenize a series of inputs: - -```rust -extern crate strum; -#[macro_use] -extern crate strum_macros; -use std::str::FromStr; - -#[derive(Eq, PartialEq, Debug, EnumString)] -enum Tokens { - #[strum(serialize="fn")] - Function, - #[strum(serialize="(")] - OpenParen, - #[strum(serialize=")")] - CloseParen, - #[strum(default="true")] - Ident(String) -} - -fn main() { - let toks = ["fn", "hello_world", "(", ")"].iter() - .map(|tok| Tokens::from_str(tok).unwrap()) - .collect::>(); - - assert_eq!(toks, vec![Tokens::Function, - Tokens::Ident(String::from("hello_world")), - Tokens::OpenParen, - Tokens::CloseParen]); -} -``` - # Name Strum is short for STRing enUM because it's a library for augmenting enums with additional information through strings. Strumming is also a very whimsical motion, much like writing Rust code. + +[Macro-Renames]: https://github.com/Peternator7/strum/wiki/Macro-Renames +[EnumString]: https://github.com/Peternator7/strum/wiki/Derive-EnumString +[Display]: https://github.com/Peternator7/strum/wiki/Derive-Display +[AsRefStr]: https://github.com/Peternator7/strum/wiki/Derive-AsRefStr +[IntoStaticStr]: https://github.com/Peternator7/strum/wiki/Derive-IntoStaticStr +[EnumVariantNames]: https://github.com/Peternator7/strum/wiki/Derive-EnumVariantNames +[EnumIter]: https://github.com/Peternator7/strum/wiki/Derive-EnumIter +[EnumProperty]: https://github.com/Peternator7/strum/wiki/Derive-EnumProperty +[EnumMessage]: https://github.com/Peternator7/strum/wiki/Derive-EnumMessage +[EnumDiscriminants]: https://github.com/Peternator7/strum/wiki/Derive-EnumDiscriminants +[EnumCount]: https://github.com/Peternator7/strum/wiki/Derive-EnumCount diff --git a/strum/Cargo.toml b/strum/Cargo.toml index 38fecdf4..3745b6e9 100644 --- a/strum/Cargo.toml +++ b/strum/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "strum" -version = "0.15.0" -authors = ["Peter Glotfelty "] +version = "0.16.0" +authors = ["Peter Glotfelty "] license = "MIT" description = "Helpful macros for working with enums and strings" @@ -13,10 +13,10 @@ homepage = "https://github.com/Peternator7/strum" readme = "../README.md" [dependencies] -strum_macros = { path = "../strum_macros", optional = true, version = "0.15.0" } +strum_macros = { path = "../strum_macros", optional = true, version = "0.16.0" } [dev-dependencies] -strum_macros = { path = "../strum_macros", version = "0.15.0" } +strum_macros = { path = "../strum_macros", version = "0.16.0" } [badges] travis-ci = { repository = "Peternator7/strum" } diff --git a/strum/LICENSE b/strum/LICENSE new file mode 100644 index 00000000..588b4a7d --- /dev/null +++ b/strum/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Peter Glotfelty + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/strum/src/lib.rs b/strum/src/lib.rs index dd02217d..67f33ab0 100644 --- a/strum/src/lib.rs +++ b/strum/src/lib.rs @@ -16,8 +16,8 @@ //! //! ```toml //! [dependencies] -//! strum = "0.15.0" -//! strum_macros = "0.15.0" +//! strum = "0.16.0" +//! strum_macros = "0.16.0" //! ``` //! //! And add these lines to the root of your project, either lib.rs or main.rs. @@ -36,16 +36,27 @@ //! //! | Macro | Description | //! | --- | ----------- | -//! | [EnumString](https://github.com/Peternator7/strum#EnumString) | Converts strings to enum variants based on their name | -//! | [Display](https://github.com/Peternator7/strum#Display) | Converts enum variants to strings | -//! | [AsRefStr](https://github.com/Peternator7/strum#AsRefStr) | Converts enum variants to `&'static str` | -//! | [IntoStaticStr](https://github.com/Peternator7/strum#IntoStaticStr) | Implements `From for &'static str` on an enum | -//! | [EnumIter](https://github.com/Peternator7/strum#EnumIter) | Creates a new type that iterates of the variants of an enum. | -//! | [EnumProperty](https://github.com/Peternator7/strum#EnumProperty) | Add custom properties to enum variants. | -//! | [EnumMessage](https://github.com/Peternator7/strum#EnumMessage) | Add a verbose message to an enum variant. | -//! | [EnumDiscriminants](https://github.com/Peternator7/strum#EnumDiscriminants) | Generate a new type with only the discriminant names. | -//! | [EnumCount](https://github.com/Peternator7/strum#EnumCount) | Add a constant `usize` equal to the number of variantes. | +//! | [EnumString] | Converts strings to enum variants based on their name | +//! | [Display] | Converts enum variants to strings | +//! | [AsRefStr] | Converts enum variants to `&'static str` | +//! | [IntoStaticStr] | Implements `From for &'static str` on an enum | +//! | [EnumVariantNames] | Adds a `variants` method returning an array of discriminant names | +//! | [EnumIter] | Creates a new type that iterates of the variants of an enum. | +//! | [EnumProperty] | Add custom properties to enum variants. | +//! | [EnumMessage] | Add a verbose message to an enum variant. | +//! | [EnumDiscriminants] | Generate a new type with only the discriminant names. | +//! | [EnumCount] | Add a constant `usize` equal to the number of variants. | //! +//! [EnumString]: https://github.com/Peternator7/strum/wiki/Derive-EnumString +//! [Display]: https://github.com/Peternator7/strum/wiki/Derive-Display +//! [AsRefStr]: https://github.com/Peternator7/strum/wiki/Derive-AsRefStr +//! [IntoStaticStr]: https://github.com/Peternator7/strum/wiki/Derive-IntoStaticStr +//! [EnumVariantNames]: https://github.com/Peternator7/strum/wiki/Derive-EnumVariantNames +//! [EnumIter]: https://github.com/Peternator7/strum/wiki/Derive-EnumIter +//! [EnumProperty]: https://github.com/Peternator7/strum/wiki/Derive-EnumProperty +//! [EnumMessage]: https://github.com/Peternator7/strum/wiki/Derive-EnumMessage +//! [EnumDiscriminants]: https://github.com/Peternator7/strum/wiki/Derive-EnumDiscriminants +//! [EnumCount]: https://github.com/Peternator7/strum/wiki/Derive-EnumCount /// The ParseError enum is a collection of all the possible reasons /// an enum can fail to parse from a string. diff --git a/strum_macros/Cargo.toml b/strum_macros/Cargo.toml index 65c03dd7..7bb82898 100644 --- a/strum_macros/Cargo.toml +++ b/strum_macros/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "strum_macros" -version = "0.15.0" -authors = ["Peter Glotfelty "] +version = "0.16.0" +authors = ["Peter Glotfelty "] license = "MIT" description = "Helpful macros for working with enums and strings" @@ -18,9 +18,9 @@ name = "strum_macros" [dependencies] heck = "0.3" -proc-macro2 = "0.4" -quote = "0.6" -syn = { version = "0.15", features = ["parsing", "extra-traits"] } +proc-macro2 = "1.0" +quote = "1.0" +syn = { version = "1.0", features = ["parsing", "extra-traits"] } [features] verbose-enumstring-name = [] diff --git a/strum_macros/LICENSE b/strum_macros/LICENSE new file mode 100644 index 00000000..588b4a7d --- /dev/null +++ b/strum_macros/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Peter Glotfelty + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/strum_macros/src/case_style.rs b/strum_macros/src/case_style.rs deleted file mode 100644 index afdb2fa8..00000000 --- a/strum_macros/src/case_style.rs +++ /dev/null @@ -1,45 +0,0 @@ -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CaseStyle { - CamelCase, - KebabCase, - MixedCase, - ShoutySnakeCase, - SnakeCase, - TitleCase, - UpperCase, - LowerCase, - ScreamingKebabCase, - PascalCase, -} - -impl<'s> From<&'s str> for CaseStyle { - fn from(text: &'s str) -> CaseStyle { - match text { - "lowercase" => CaseStyle::LowerCase, - "camel_case" | "PascalCase" => CaseStyle::PascalCase, - "kebab_case" | "kebab-case" => CaseStyle::KebabCase, - "mixed_case" => CaseStyle::MixedCase, - "shouty_snake_case" | "shouty_snek_case" | "SCREAMING_SNAKE_CASE" => { - CaseStyle::ShoutySnakeCase - } - "snake_case" | "snek_case" => CaseStyle::SnakeCase, - "title_case" => CaseStyle::TitleCase, - "UPPERCASE" => CaseStyle::UpperCase, - "camelCase" => CaseStyle::CamelCase, - "SCREAMING-KEBAB-CASE" => CaseStyle::ScreamingKebabCase, - _ => panic!( - "Unexpected case style for serialize_all: `{}`. Valid values are: `{:?}`", - text, - [ - "camel_case", - "kebab_case", - "mixed_case", - "shouty_snake_case", - "snake_case", - "title_case", - "UPPERCASE", - ] - ), - } - } -} diff --git a/strum_macros/src/helpers.rs b/strum_macros/src/helpers.rs deleted file mode 100644 index dcec9567..00000000 --- a/strum_macros/src/helpers.rs +++ /dev/null @@ -1,182 +0,0 @@ -use heck::{CamelCase, KebabCase, MixedCase, ShoutySnakeCase, SnakeCase, TitleCase}; -use syn::{Attribute, Ident, Meta, MetaList}; - -use case_style::CaseStyle; - -pub fn extract_meta(attrs: &[Attribute]) -> Vec { - attrs - .iter() - .filter_map(|attribute| attribute.interpret_meta()) - .collect() -} - -pub fn filter_metas<'meta, MetaIt, F>(metas: MetaIt, filter: F) -> impl Iterator -where - MetaIt: Iterator, - F: Fn(&Meta) -> bool, -{ - metas.filter_map(move |meta| if filter(meta) { Some(meta) } else { None }) -} - -pub fn filter_meta_lists<'meta, MetaIt, F>( - metas: MetaIt, - filter: F, -) -> impl Iterator -where - MetaIt: Iterator, - F: Fn(&MetaList) -> bool, -{ - metas.filter_map(move |meta| match meta { - Meta::List(ref metalist) => { - if filter(metalist) { - Some(metalist) - } else { - None - } - } - _ => None, - }) -} - -/// Returns the `MetaList`s with the given attr name. -/// -/// For example, `get_meta_list(type_meta.iter(), "strum_discriminant")` for the following snippet -/// will return an iterator with `#[strum_discriminant(derive(EnumIter))]` and -/// `#[strum_discriminant(name(MyEnumVariants))]`. -/// -/// ```rust,ignore -/// #[derive(Debug)] -/// #[strum_discriminant(derive(EnumIter))] -/// #[strum_discriminant(name(MyEnumVariants))] -/// enum MyEnum { A } -/// ``` -pub fn get_meta_list<'meta, MetaIt>( - metas: MetaIt, - attr: &'meta str, -) -> impl Iterator -where - MetaIt: Iterator, -{ - filter_meta_lists(metas, move |metalist| metalist.ident == attr) -} - -/// Returns the `MetaList` that matches the given name from the list of `Meta`s, or `None`. -/// -/// # Panics -/// -/// Panics if more than one `Meta` exists with the name. -pub fn unique_meta_list<'meta, MetaIt>(metas: MetaIt, attr: &'meta str) -> Option<&'meta MetaList> -where - MetaIt: Iterator, -{ - let mut curr = get_meta_list(metas.into_iter(), attr).collect::>(); - if curr.len() > 1 { - panic!("More than one `{}` attribute found on type", attr); - } - - curr.pop() -} - -/// Returns an iterator of the `Meta`s from the given `MetaList`. -pub fn extract_list_metas<'meta>(metalist: &'meta MetaList) -> impl Iterator { - use syn::NestedMeta; - metalist.nested.iter().filter_map(|nested| match *nested { - NestedMeta::Meta(ref meta) => Some(meta), - _ => None, - }) -} - -/// Returns the `Ident` of the `Meta::Word`, or `None`. -pub fn get_meta_ident<'meta>(meta: &'meta Meta) -> Option<&'meta Ident> { - match *meta { - Meta::Word(ref ident) => Some(ident), - _ => None, - } -} - -pub fn extract_attrs(meta: &[Meta], attr: &str, prop: &str) -> Vec { - use syn::{Lit, MetaNameValue, NestedMeta}; - meta.iter() - // Get all the attributes with our tag on them. - .filter_map(|meta| match *meta { - Meta::List(ref metalist) => { - if metalist.ident == attr { - Some(&metalist.nested) - } else { - None - } - } - _ => None, - }) - .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 { - ref ident, - lit: Lit::Str(ref s), - .. - })) => { - if ident == prop { - Some(s.value()) - } else { - None - } - } - _ => None, - }) - .collect() -} - -pub fn unique_attr(attrs: &[Meta], attr: &str, prop: &str) -> Option { - let mut curr = extract_attrs(attrs, attr, prop); - if curr.len() > 1 { - panic!("More than one property: {} found on variant", prop); - } - - curr.pop() -} - -pub fn is_disabled(attrs: &[Meta]) -> bool { - let v = extract_attrs(attrs, "strum", "disabled"); - match v.len() { - 0 => false, - 1 => v[0] == "true", - _ => panic!("Can't have multiple values for 'disabled'"), - } -} - -pub fn convert_case(ident: &Ident, case_style: Option) -> String { - let ident_string = ident.to_string(); - if let Some(case_style) = case_style { - match case_style { - CaseStyle::PascalCase => ident_string.to_camel_case(), - CaseStyle::KebabCase => ident_string.to_kebab_case(), - CaseStyle::MixedCase => ident_string.to_mixed_case(), - CaseStyle::ShoutySnakeCase => ident_string.to_shouty_snake_case(), - CaseStyle::SnakeCase => ident_string.to_snake_case(), - CaseStyle::TitleCase => ident_string.to_title_case(), - CaseStyle::UpperCase => ident_string.to_uppercase(), - CaseStyle::LowerCase => ident_string.to_lowercase(), - CaseStyle::ScreamingKebabCase => ident_string.to_kebab_case().to_uppercase(), - CaseStyle::CamelCase => { - let camel_case = ident_string.to_camel_case(); - let mut pascal = String::with_capacity(camel_case.len()); - let mut it = camel_case.chars(); - if let Some(ch) = it.next() { - pascal.extend(ch.to_lowercase()); - } - pascal.extend(it); - pascal - } - } - } else { - ident_string - } -} - -#[test] -fn test_convert_case() { - let id = Ident::new("test_me", proc_macro2::Span::call_site()); - assert_eq!("testMe", convert_case(&id, Some(CaseStyle::CamelCase))); - assert_eq!("TestMe", convert_case(&id, Some(CaseStyle::PascalCase))); -} diff --git a/strum_macros/src/helpers/case_style.rs b/strum_macros/src/helpers/case_style.rs new file mode 100644 index 00000000..ca9c0e21 --- /dev/null +++ b/strum_macros/src/helpers/case_style.rs @@ -0,0 +1,92 @@ +use heck::{CamelCase, KebabCase, MixedCase, ShoutySnakeCase, SnakeCase, TitleCase}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CaseStyle { + CamelCase, + KebabCase, + MixedCase, + ShoutySnakeCase, + SnakeCase, + TitleCase, + UpperCase, + LowerCase, + ScreamingKebabCase, + PascalCase, +} + +impl<'s> From<&'s str> for CaseStyle { + fn from(text: &'s str) -> CaseStyle { + match text { + "camel_case" | "PascalCase" => CaseStyle::PascalCase, + "camelCase" => CaseStyle::CamelCase, + "snake_case" | "snek_case" => CaseStyle::SnakeCase, + "kebab_case" | "kebab-case" => CaseStyle::KebabCase, + "SCREAMING-KEBAB-CASE" => CaseStyle::ScreamingKebabCase, + "shouty_snake_case" | "shouty_snek_case" | "SCREAMING_SNAKE_CASE" => { + CaseStyle::ShoutySnakeCase + } + "title_case" => CaseStyle::TitleCase, + "mixed_case" => CaseStyle::MixedCase, + "lowercase" => CaseStyle::LowerCase, + "UPPERCASE" => CaseStyle::UpperCase, + _ => panic!( + "Unexpected case style for serialize_all: `{}`. Valid values are: `{:?}`", + text, + [ + "camelCase", + "PascalCase", + "kebab-case", + "snake_case", + "SCREAMING_SNAKE_CASE", + "SCREAMING-KEBAB-CASE", + "lowercase", + "UPPERCASE", + "title_case", + "mixed_case", + ] + ), + } + } +} + +pub trait CaseStyleHelpers { + fn convert_case(&self, case_style: Option) -> String; +} + +impl CaseStyleHelpers for syn::Ident { + fn convert_case(&self, case_style: Option) -> String { + let ident_string = self.to_string(); + if let Some(case_style) = case_style { + match case_style { + CaseStyle::PascalCase => ident_string.to_camel_case(), + CaseStyle::KebabCase => ident_string.to_kebab_case(), + CaseStyle::MixedCase => ident_string.to_mixed_case(), + CaseStyle::ShoutySnakeCase => ident_string.to_shouty_snake_case(), + CaseStyle::SnakeCase => ident_string.to_snake_case(), + CaseStyle::TitleCase => ident_string.to_title_case(), + CaseStyle::UpperCase => ident_string.to_uppercase(), + CaseStyle::LowerCase => ident_string.to_lowercase(), + CaseStyle::ScreamingKebabCase => ident_string.to_kebab_case().to_uppercase(), + CaseStyle::CamelCase => { + let camel_case = ident_string.to_camel_case(); + let mut pascal = String::with_capacity(camel_case.len()); + let mut it = camel_case.chars(); + if let Some(ch) = it.next() { + pascal.extend(ch.to_lowercase()); + } + pascal.extend(it); + pascal + } + } + } else { + ident_string + } + } +} + +#[test] +fn test_convert_case() { + let id = syn::Ident::new("test_me", proc_macro2::Span::call_site()); + assert_eq!("testMe", id.convert_case(Some(CaseStyle::CamelCase))); + assert_eq!("TestMe", id.convert_case(Some(CaseStyle::PascalCase))); +} diff --git a/strum_macros/src/helpers/meta_helpers.rs b/strum_macros/src/helpers/meta_helpers.rs new file mode 100644 index 00000000..1274e2ff --- /dev/null +++ b/strum_macros/src/helpers/meta_helpers.rs @@ -0,0 +1,30 @@ +use syn::{Meta, MetaList}; + +pub trait MetaHelpers { + fn try_metalist(&self) -> Option<&MetaList>; + fn try_path(&self) -> Option<&syn::Path>; + fn try_namevalue(&self) -> Option<&syn::MetaNameValue>; +} + +impl MetaHelpers for syn::Meta { + fn try_metalist(&self) -> Option<&MetaList> { + match self { + Meta::List(list) => Some(list), + _ => None, + } + } + + fn try_path(&self) -> Option<&syn::Path> { + match self { + Meta::Path(path) => Some(path), + _ => None, + } + } + + fn try_namevalue(&self) -> Option<&syn::MetaNameValue> { + match self { + Meta::NameValue(pair) => Some(pair), + _ => None, + } + } +} diff --git a/strum_macros/src/helpers/meta_iterator_helpers.rs b/strum_macros/src/helpers/meta_iterator_helpers.rs new file mode 100644 index 00000000..918f1170 --- /dev/null +++ b/strum_macros/src/helpers/meta_iterator_helpers.rs @@ -0,0 +1,66 @@ +use super::MetaHelpers; +use super::MetaListHelpers; +use syn::Meta; + +pub trait MetaIteratorHelpers { + fn find_attribute(&self, attr: &str) -> std::vec::IntoIter<&Meta>; + fn find_properties(&self, attr: &str, prop: &str) -> Vec; + + fn find_unique_property(&self, attr: &str, prop: &str) -> Option { + let mut curr = self.find_properties(attr, prop); + if curr.len() > 1 { + panic!("More than one property: {} found on variant", prop); + } + + curr.pop() + } + + fn is_disabled(&self) -> bool { + let v = self.find_properties("strum", "disabled"); + match v.len() { + 0 => false, + 1 => v[0] == "true", + _ => panic!("Can't have multiple values for 'disabled'"), + } + } +} + +//impl MetaIteratorHelpers for [Meta] +impl MetaIteratorHelpers for [T] +where + T: std::borrow::Borrow, +{ + fn find_attribute(&self, attr: &str) -> std::vec::IntoIter<&Meta> { + self.iter() + .filter_map(|meta| meta.borrow().try_metalist()) + .filter(|list| list.path.is_ident(attr)) + .flat_map(|list| list.expand_inner()) + .collect::>() + .into_iter() + } + + fn find_properties(&self, attr: &str, prop: &str) -> Vec { + use syn::{Lit, MetaNameValue}; + self.iter() + // Only look at MetaList style attributes `[strum(...)]` + .filter_map(|meta| meta.borrow().try_metalist()) + .filter(|list| list.path.is_ident(attr)) + .flat_map(|list| list.expand_inner()) + // Match all the properties with a given ident `[strum(serialize = "value")]` + .filter_map(|meta| match *meta { + Meta::NameValue(MetaNameValue { + ref path, + lit: Lit::Str(ref s), + .. + }) => { + if path.is_ident(prop) { + Some(s.value()) + } else { + None + } + } + _ => None, + }) + .collect() + } +} diff --git a/strum_macros/src/helpers/metalist_helpers.rs b/strum_macros/src/helpers/metalist_helpers.rs new file mode 100644 index 00000000..4b6709b3 --- /dev/null +++ b/strum_macros/src/helpers/metalist_helpers.rs @@ -0,0 +1,18 @@ +use syn::Meta; + +pub trait MetaListHelpers { + fn expand_inner(&self) -> Vec<&Meta>; +} + +impl MetaListHelpers for syn::MetaList { + fn expand_inner(&self) -> Vec<&Meta> { + use syn::NestedMeta; + self.nested + .iter() + .filter_map(|nested| match *nested { + NestedMeta::Meta(ref meta) => Some(meta), + _ => None, + }) + .collect() + } +} diff --git a/strum_macros/src/helpers/mod.rs b/strum_macros/src/helpers/mod.rs new file mode 100644 index 00000000..1d68efd3 --- /dev/null +++ b/strum_macros/src/helpers/mod.rs @@ -0,0 +1,18 @@ +use syn::{Attribute, Meta}; + +pub mod case_style; +mod meta_helpers; +mod meta_iterator_helpers; +mod metalist_helpers; + +pub use self::case_style::CaseStyleHelpers; +pub use self::meta_helpers::MetaHelpers; +pub use self::meta_iterator_helpers::MetaIteratorHelpers; +pub use self::metalist_helpers::MetaListHelpers; + +pub fn extract_meta(attrs: &[Attribute]) -> Vec { + attrs + .iter() + .filter_map(|attribute| attribute.parse_meta().ok()) + .collect() +} diff --git a/strum_macros/src/lib.rs b/strum_macros/src/lib.rs index 4634b9ad..1b85ef75 100644 --- a/strum_macros/src/lib.rs +++ b/strum_macros/src/lib.rs @@ -17,18 +17,8 @@ extern crate quote; extern crate proc_macro; extern crate proc_macro2; -mod as_ref_str; -mod case_style; -mod display; -mod enum_count; -mod enum_discriminants; -mod enum_iter; -mod enum_messages; -mod enum_properties; -mod enum_variant_names; -mod from_string; mod helpers; -mod to_string; +mod macros; use proc_macro2::TokenStream; use std::env; @@ -57,7 +47,7 @@ fn debug_print_generated(ast: &syn::DeriveInput, toks: &TokenStream) { pub fn from_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); - let toks = from_string::from_string_inner(&ast); + let toks = macros::from_string::from_string_inner(&ast); debug_print_generated(&ast, &toks); toks.into() } @@ -73,7 +63,7 @@ pub fn from_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { pub fn as_ref_str(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); - let toks = as_ref_str::as_ref_str_inner(&ast); + let toks = macros::as_ref_str::as_ref_str_inner(&ast); debug_print_generated(&ast, &toks); toks.into() } @@ -89,7 +79,7 @@ pub fn as_ref_str(input: proc_macro::TokenStream) -> proc_macro::TokenStream { pub fn variant_names(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); - let toks = enum_variant_names::enum_variant_names_inner(&ast); + let toks = macros::enum_variant_names::enum_variant_names_inner(&ast); debug_print_generated(&ast, &toks); toks.into() } @@ -105,7 +95,10 @@ pub fn variant_names(input: proc_macro::TokenStream) -> proc_macro::TokenStream pub fn as_static_str(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); - let toks = as_ref_str::as_static_str_inner(&ast, as_ref_str::GenerateTraitVariant::AsStaticStr); + let toks = macros::as_ref_str::as_static_str_inner( + &ast, + macros::as_ref_str::GenerateTraitVariant::AsStaticStr, + ); debug_print_generated(&ast, &toks); toks.into() } @@ -121,7 +114,10 @@ pub fn as_static_str(input: proc_macro::TokenStream) -> proc_macro::TokenStream pub fn into_static_str(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); - let toks = as_ref_str::as_static_str_inner(&ast, as_ref_str::GenerateTraitVariant::From); + let toks = macros::as_ref_str::as_static_str_inner( + &ast, + macros::as_ref_str::GenerateTraitVariant::From, + ); debug_print_generated(&ast, &toks); toks.into() } @@ -137,7 +133,7 @@ pub fn into_static_str(input: proc_macro::TokenStream) -> proc_macro::TokenStrea pub fn to_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); - let toks = to_string::to_string_inner(&ast); + let toks = macros::to_string::to_string_inner(&ast); debug_print_generated(&ast, &toks); toks.into() } @@ -153,7 +149,7 @@ pub fn to_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { pub fn display(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); - let toks = display::display_inner(&ast); + let toks = macros::display::display_inner(&ast); debug_print_generated(&ast, &toks); toks.into() } @@ -169,7 +165,7 @@ pub fn display(input: proc_macro::TokenStream) -> proc_macro::TokenStream { pub fn enum_iter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); - let toks = enum_iter::enum_iter_inner(&ast); + let toks = macros::enum_iter::enum_iter_inner(&ast); debug_print_generated(&ast, &toks); toks.into() } @@ -185,7 +181,7 @@ pub fn enum_iter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { pub fn enum_messages(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); - let toks = enum_messages::enum_message_inner(&ast); + let toks = macros::enum_messages::enum_message_inner(&ast); debug_print_generated(&ast, &toks); toks.into() } @@ -201,7 +197,7 @@ pub fn enum_messages(input: proc_macro::TokenStream) -> proc_macro::TokenStream pub fn enum_properties(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); - let toks = enum_properties::enum_properties_inner(&ast); + let toks = macros::enum_properties::enum_properties_inner(&ast); debug_print_generated(&ast, &toks); toks.into() } @@ -217,7 +213,7 @@ pub fn enum_properties(input: proc_macro::TokenStream) -> proc_macro::TokenStrea pub fn enum_discriminants(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); - let toks = enum_discriminants::enum_discriminants_inner(&ast); + let toks = macros::enum_discriminants::enum_discriminants_inner(&ast); debug_print_generated(&ast, &toks); toks.into() } @@ -232,7 +228,7 @@ pub fn enum_discriminants(input: proc_macro::TokenStream) -> proc_macro::TokenSt )] pub fn enum_count(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); - let toks = enum_count::enum_count_inner(&ast); + let toks = macros::enum_count::enum_count_inner(&ast); debug_print_generated(&ast, &toks); toks.into() } diff --git a/strum_macros/src/enum_count.rs b/strum_macros/src/macros/enum_count.rs similarity index 100% rename from strum_macros/src/enum_count.rs rename to strum_macros/src/macros/enum_count.rs diff --git a/strum_macros/src/enum_discriminants.rs b/strum_macros/src/macros/enum_discriminants.rs similarity index 74% rename from strum_macros/src/enum_discriminants.rs rename to strum_macros/src/macros/enum_discriminants.rs index 3135b1f3..ff16b881 100644 --- a/strum_macros/src/enum_discriminants.rs +++ b/strum_macros/src/macros/enum_discriminants.rs @@ -1,9 +1,8 @@ +use crate::helpers::{MetaHelpers, MetaIteratorHelpers, MetaListHelpers}; use proc_macro2::{Span, TokenStream}; use syn; -use helpers::{ - extract_list_metas, extract_meta, filter_metas, get_meta_ident, get_meta_list, unique_meta_list, -}; +use helpers::extract_meta; pub fn enum_discriminants_inner(ast: &syn::DeriveInput) -> TokenStream { let name = &ast.ident; @@ -16,13 +15,13 @@ pub fn enum_discriminants_inner(ast: &syn::DeriveInput) -> TokenStream { // Derives for the generated enum let type_meta = extract_meta(&ast.attrs); - let discriminant_attrs = get_meta_list(type_meta.iter(), "strum_discriminants") - .flat_map(|meta| extract_list_metas(meta).collect::>()) + let discriminant_attrs = type_meta + .find_attribute("strum_discriminants") .collect::>(); - let derives = get_meta_list(discriminant_attrs.iter().map(|&m| m), "derive") - .flat_map(extract_list_metas) - .filter_map(get_meta_ident) + let derives = discriminant_attrs + .find_attribute("derive") + .map(|meta| meta.path()) .collect::>(); let derives = quote! { @@ -30,21 +29,32 @@ pub fn enum_discriminants_inner(ast: &syn::DeriveInput) -> TokenStream { }; // Work out the name - let default_name = syn::Ident::new( + let default_name = syn::Path::from(syn::Ident::new( &format!("{}Discriminants", name.to_string()), Span::call_site(), - ); + )); - let discriminants_name = unique_meta_list(discriminant_attrs.iter().map(|&m| m), "name") - .map(extract_list_metas) - .and_then(|metas| metas.filter_map(get_meta_ident).next()) + let discriminants_name = discriminant_attrs + .iter() + .filter_map(|meta| meta.try_metalist()) + .filter(|list| list.path.is_ident("name")) + // We want exactly zero or one items. Start with the assumption we have zero, i.e. None + // Then set our output to the first value we see. If fold is called again and we already + // have a value, panic. + .fold(None, |acc, val| match acc { + Some(_) => panic!("Expecting a single attribute 'name' in EnumDiscriminants."), + None => Some(val), + }) + .map(|meta| meta.expand_inner()) + .and_then(|metas| metas.into_iter().map(|meta| meta.path()).next()) .unwrap_or(&default_name); // Pass through all other attributes - let pass_though_attributes = - filter_metas(discriminant_attrs.iter().map(|&m| m), |meta| match meta { - syn::Meta::List(ref metalist) => metalist.ident != "derive" && metalist.ident != "name", - _ => true, + let pass_though_attributes = discriminant_attrs + .iter() + .filter(|meta| { + let path = meta.path(); + !path.is_ident("derive") && !path.is_ident("name") }) .map(|meta| quote! { #[ #meta ] }) .collect::>(); @@ -56,10 +66,9 @@ pub fn enum_discriminants_inner(ast: &syn::DeriveInput) -> TokenStream { // Don't copy across the "strum" meta attribute. let attrs = variant.attrs.iter().filter(|attr| { - attr.interpret_meta().map_or(true, |meta| match meta { - syn::Meta::List(ref metalist) => metalist.ident != "strum", - _ => true, - }) + attr.parse_meta() + .map(|meta| !meta.path().is_ident("strum")) + .unwrap_or(true) }); discriminants.push(quote! { #(#attrs)* #ident }); @@ -103,6 +112,7 @@ pub fn enum_discriminants_inner(ast: &syn::DeriveInput) -> TokenStream { quote! { #name::#ident #params => #discriminants_name::#ident } }) .collect::>(); + let from_fn_body = quote! { match val { #(#arms),* } }; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); diff --git a/strum_macros/src/enum_iter.rs b/strum_macros/src/macros/enum_iter.rs similarity index 96% rename from strum_macros/src/enum_iter.rs rename to strum_macros/src/macros/enum_iter.rs index 51c4744c..afc6d8bb 100644 --- a/strum_macros/src/enum_iter.rs +++ b/strum_macros/src/macros/enum_iter.rs @@ -1,7 +1,7 @@ use proc_macro2::TokenStream; use syn; -use helpers::{extract_meta, is_disabled}; +use helpers::{extract_meta, MetaIteratorHelpers}; pub fn enum_iter_inner(ast: &syn::DeriveInput) -> TokenStream { let name = &ast.ident; @@ -31,7 +31,7 @@ pub fn enum_iter_inner(ast: &syn::DeriveInput) -> TokenStream { let mut arms = Vec::new(); let enabled = variants .iter() - .filter(|variant| !is_disabled(&extract_meta(&variant.attrs))); + .filter(|variant| !extract_meta(&variant.attrs).is_disabled()); for (idx, variant) in enabled.enumerate() { use syn::Fields::*; diff --git a/strum_macros/src/enum_messages.rs b/strum_macros/src/macros/enum_messages.rs similarity index 89% rename from strum_macros/src/enum_messages.rs rename to strum_macros/src/macros/enum_messages.rs index b8c1c0d2..24ec4511 100644 --- a/strum_macros/src/enum_messages.rs +++ b/strum_macros/src/macros/enum_messages.rs @@ -1,7 +1,7 @@ use proc_macro2::TokenStream; use syn; -use helpers::{extract_attrs, extract_meta, is_disabled, unique_attr}; +use helpers::{extract_meta, MetaIteratorHelpers}; pub fn enum_message_inner(ast: &syn::DeriveInput) -> TokenStream { let name = &ast.ident; @@ -17,8 +17,8 @@ pub fn enum_message_inner(ast: &syn::DeriveInput) -> TokenStream { for variant in variants { let meta = extract_meta(&variant.attrs); - let messages = unique_attr(&meta, "strum", "message"); - let detailed_messages = unique_attr(&meta, "strum", "detailed_message"); + let messages = meta.find_unique_property("strum", "message"); + let detailed_messages = meta.find_unique_property("strum", "detailed_message"); let ident = &variant.ident; use syn::Fields::*; @@ -30,7 +30,7 @@ pub fn enum_message_inner(ast: &syn::DeriveInput) -> TokenStream { // You can't disable getting the serializations. { - let mut serialization_variants = extract_attrs(&meta, "strum", "serialize"); + let mut serialization_variants = meta.find_properties("strum", "serialize"); if serialization_variants.len() == 0 { serialization_variants.push(ident.to_string()); } @@ -45,7 +45,7 @@ pub fn enum_message_inner(ast: &syn::DeriveInput) -> TokenStream { } // But you can disable the messages. - if is_disabled(&meta) { + if meta.is_disabled() { continue; } diff --git a/strum_macros/src/enum_properties.rs b/strum_macros/src/macros/enum_properties.rs similarity index 65% rename from strum_macros/src/enum_properties.rs rename to strum_macros/src/macros/enum_properties.rs index 97a93959..6b80ffba 100644 --- a/strum_macros/src/enum_properties.rs +++ b/strum_macros/src/macros/enum_properties.rs @@ -2,46 +2,23 @@ use proc_macro2::TokenStream; use syn; use syn::Meta; -use helpers::{extract_meta, is_disabled}; +use crate::helpers::{extract_meta, MetaHelpers, MetaIteratorHelpers, MetaListHelpers}; -fn extract_properties(meta: &[Meta]) -> Vec<(&syn::Ident, &syn::Lit)> { - use syn::{MetaList, MetaNameValue, NestedMeta}; +fn extract_properties(meta: &[Meta]) -> Vec<(&syn::Path, &syn::Lit)> { meta.iter() - .filter_map(|meta| match *meta { - Meta::List(MetaList { - ref ident, - ref nested, - .. - }) => { - if ident == "strum" { - Some(nested) - } else { - None - } - } - _ => None, - }) - .flat_map(|prop| prop) - .filter_map(|prop| match *prop { - NestedMeta::Meta(Meta::List(MetaList { - ref ident, - ref nested, - .. - })) => { - if ident == "props" { - Some(nested) - } else { - None - } - } - _ => None, - }) - .flat_map(|prop| prop) - // Only look at key value pairs + // Filter down to the strum(..) attribute + .filter_map(|meta| meta.try_metalist()) + .filter(|list| list.path.is_ident("strum")) + .flat_map(|list| list.expand_inner()) + // Filter down to the `strum(props(..))` attribute + .filter_map(|meta| meta.try_metalist()) + .filter(|inner_list| inner_list.path.is_ident("props")) + .flat_map(|inner_list| inner_list.expand_inner()) + // Expand all the pairs `strum(props(key = value, ..))` .filter_map(|prop| match *prop { - NestedMeta::Meta(Meta::NameValue(MetaNameValue { - ref ident, ref lit, .. - })) => Some((ident, lit)), + syn::Meta::NameValue(syn::MetaNameValue { + ref path, ref lit, .. + }) => Some((path, lit)), _ => None, }) .collect() @@ -63,7 +40,7 @@ pub fn enum_properties_inner(ast: &syn::DeriveInput) -> TokenStream { let mut bool_arms = Vec::new(); let mut num_arms = Vec::new(); // But you can disable the messages. - if is_disabled(&meta) { + if meta.is_disabled() { continue; } @@ -76,7 +53,7 @@ pub fn enum_properties_inner(ast: &syn::DeriveInput) -> TokenStream { for (key, value) in extract_properties(&meta) { use syn::Lit::*; - let key = key.to_string(); + let key = key.segments.last().unwrap().ident.to_string(); match value { Str(ref s, ..) => { string_arms.push(quote! { #key => ::std::option::Option::Some( #s )}) diff --git a/strum_macros/src/enum_variant_names.rs b/strum_macros/src/macros/enum_variant_names.rs similarity index 76% rename from strum_macros/src/enum_variant_names.rs rename to strum_macros/src/macros/enum_variant_names.rs index d3b36458..a1d436d6 100644 --- a/strum_macros/src/enum_variant_names.rs +++ b/strum_macros/src/macros/enum_variant_names.rs @@ -1,8 +1,8 @@ use proc_macro2::TokenStream; use syn; -use case_style::CaseStyle; -use helpers::{convert_case, extract_meta, unique_attr}; +use crate::helpers::case_style::CaseStyle; +use crate::helpers::{extract_meta, CaseStyleHelpers, MetaIteratorHelpers}; pub fn enum_variant_names_inner(ast: &syn::DeriveInput) -> TokenStream { let name = &ast.ident; @@ -14,12 +14,13 @@ pub fn enum_variant_names_inner(ast: &syn::DeriveInput) -> TokenStream { // Derives for the generated enum let type_meta = extract_meta(&ast.attrs); - let case_style = unique_attr(&type_meta, "strum", "serialize_all") + let case_style = type_meta + .find_unique_property("strum", "serialize_all") .map(|style| CaseStyle::from(style.as_ref())); let names = variants .iter() - .map(|v| convert_case(&v.ident, case_style)) + .map(|v| v.ident.convert_case(case_style)) .collect::>(); quote! { diff --git a/strum_macros/src/macros/mod.rs b/strum_macros/src/macros/mod.rs new file mode 100644 index 00000000..9b707fbb --- /dev/null +++ b/strum_macros/src/macros/mod.rs @@ -0,0 +1,13 @@ +pub mod enum_count; +pub mod enum_discriminants; +pub mod enum_iter; +pub mod enum_messages; +pub mod enum_properties; +pub mod enum_variant_names; + +mod strings; + +pub use self::strings::as_ref_str; +pub use self::strings::display; +pub use self::strings::from_string; +pub use self::strings::to_string; diff --git a/strum_macros/src/as_ref_str.rs b/strum_macros/src/macros/strings/as_ref_str.rs similarity index 89% rename from strum_macros/src/as_ref_str.rs rename to strum_macros/src/macros/strings/as_ref_str.rs index b22525c5..524754f3 100644 --- a/strum_macros/src/as_ref_str.rs +++ b/strum_macros/src/macros/strings/as_ref_str.rs @@ -1,8 +1,8 @@ use proc_macro2::TokenStream; use syn; -use case_style::CaseStyle; -use helpers::{convert_case, extract_attrs, extract_meta, is_disabled, unique_attr}; +use crate::helpers::case_style::CaseStyle; +use helpers::{extract_meta, CaseStyleHelpers, MetaIteratorHelpers}; fn get_arms(ast: &syn::DeriveInput) -> Vec { let name = &ast.ident; @@ -13,7 +13,8 @@ fn get_arms(ast: &syn::DeriveInput) -> Vec { }; let type_meta = extract_meta(&ast.attrs); - let case_style = unique_attr(&type_meta, "strum", "serialize_all") + let case_style = type_meta + .find_unique_property("strum", "serialize_all") .map(|style| CaseStyle::from(style.as_ref())); for variant in variants { @@ -21,23 +22,23 @@ fn get_arms(ast: &syn::DeriveInput) -> Vec { let ident = &variant.ident; let meta = extract_meta(&variant.attrs); - if is_disabled(&meta) { + if meta.is_disabled() { continue; } // Look at all the serialize attributes. // Use `to_string` attribute (not `as_ref_str` or something) to keep things consistent // (i.e. always `enum.as_ref().to_string() == enum.to_string()`). - let output = if let Some(n) = unique_attr(&meta, "strum", "to_string") { + let output = if let Some(n) = meta.find_unique_property("strum", "to_string") { n } else { - let mut attrs = extract_attrs(&meta, "strum", "serialize"); + let mut attrs = meta.find_properties("strum", "serialize"); // We always take the longest one. This is arbitary, but is *mostly* deterministic attrs.sort_by_key(|s| s.len()); if let Some(n) = attrs.pop() { n } else { - convert_case(ident, case_style) + ident.convert_case(case_style) } }; diff --git a/strum_macros/src/display.rs b/strum_macros/src/macros/strings/display.rs similarity index 79% rename from strum_macros/src/display.rs rename to strum_macros/src/macros/strings/display.rs index 05291535..b2f24d3a 100644 --- a/strum_macros/src/display.rs +++ b/strum_macros/src/macros/strings/display.rs @@ -1,8 +1,8 @@ use proc_macro2::TokenStream; use syn; -use case_style::CaseStyle; -use helpers::{convert_case, extract_attrs, extract_meta, is_disabled, unique_attr}; +use crate::helpers::case_style::CaseStyle; +use helpers::{extract_meta, CaseStyleHelpers, MetaIteratorHelpers}; pub fn display_inner(ast: &syn::DeriveInput) -> TokenStream { let name = &ast.ident; @@ -13,7 +13,8 @@ pub fn display_inner(ast: &syn::DeriveInput) -> TokenStream { }; let type_meta = extract_meta(&ast.attrs); - let case_style = unique_attr(&type_meta, "strum", "serialize_all") + let case_style = type_meta + .find_unique_property("strum", "serialize_all") .map(|style| CaseStyle::from(style.as_ref())); let mut arms = Vec::new(); @@ -22,21 +23,21 @@ pub fn display_inner(ast: &syn::DeriveInput) -> TokenStream { let ident = &variant.ident; let meta = extract_meta(&variant.attrs); - if is_disabled(&meta) { + if meta.is_disabled() { continue; } // Look at all the serialize attributes. - let output = if let Some(n) = unique_attr(&meta, "strum", "to_string") { + let output = if let Some(n) = meta.find_unique_property("strum", "to_string") { n } else { - let mut attrs = extract_attrs(&meta, "strum", "serialize"); + let mut attrs = meta.find_properties("strum", "serialize"); // We always take the longest one. This is arbitary, but is *mostly* deterministic attrs.sort_by_key(|s| s.len()); if let Some(n) = attrs.pop() { n } else { - convert_case(ident, case_style) + ident.convert_case(case_style) } }; diff --git a/strum_macros/src/from_string.rs b/strum_macros/src/macros/strings/from_string.rs similarity index 78% rename from strum_macros/src/from_string.rs rename to strum_macros/src/macros/strings/from_string.rs index 2960fe14..0346587f 100644 --- a/strum_macros/src/from_string.rs +++ b/strum_macros/src/macros/strings/from_string.rs @@ -1,8 +1,8 @@ use proc_macro2::TokenStream; use syn; -use case_style::CaseStyle; -use helpers::{convert_case, extract_attrs, extract_meta, is_disabled, unique_attr}; +use crate::helpers::case_style::CaseStyle; +use crate::helpers::{extract_meta, CaseStyleHelpers, MetaIteratorHelpers}; pub fn from_string_inner(ast: &syn::DeriveInput) -> TokenStream { let name = &ast.ident; @@ -13,7 +13,8 @@ pub fn from_string_inner(ast: &syn::DeriveInput) -> TokenStream { }; let type_meta = extract_meta(&ast.attrs); - let case_style = unique_attr(&type_meta, "strum", "serialize_all") + let case_style = type_meta + .find_unique_property("strum", "serialize_all") .map(|style| CaseStyle::from(style.as_ref())); let mut has_default = false; @@ -26,13 +27,21 @@ pub fn from_string_inner(ast: &syn::DeriveInput) -> TokenStream { let meta = extract_meta(&variant.attrs); // Look at all the serialize attributes. - let mut attrs = extract_attrs(&meta, "strum", "serialize"); - attrs.extend(extract_attrs(&meta, "strum", "to_string")); - if is_disabled(&meta) { + // let mut attrs = find_properties(&meta, "strum", "serialize"); + // attrs.extend(find_properties(&meta, "strum", "to_string")); + + let mut attrs = meta.find_properties("strum", "serialize"); + attrs.extend(meta.find_properties("strum", "to_string")); + + // if is_disabled(&meta) { + if meta.is_disabled() { continue; } - if unique_attr(&meta, "strum", "default").map_or(false, |s| s == "true") { + if meta + .find_unique_property("strum", "default") + .map_or(false, |s| s == "true") + { if has_default { panic!("Can't have multiple default variants"); } @@ -55,7 +64,7 @@ pub fn from_string_inner(ast: &syn::DeriveInput) -> TokenStream { // If we don't have any custom variants, add the default serialized name. if attrs.len() == 0 { - attrs.push(convert_case(ident, case_style)); + attrs.push(ident.convert_case(case_style)); } let params = match variant.fields { diff --git a/strum_macros/src/macros/strings/mod.rs b/strum_macros/src/macros/strings/mod.rs new file mode 100644 index 00000000..e416f4b3 --- /dev/null +++ b/strum_macros/src/macros/strings/mod.rs @@ -0,0 +1,4 @@ +pub mod as_ref_str; +pub mod display; +pub mod from_string; +pub mod to_string; diff --git a/strum_macros/src/to_string.rs b/strum_macros/src/macros/strings/to_string.rs similarity index 79% rename from strum_macros/src/to_string.rs rename to strum_macros/src/macros/strings/to_string.rs index 8c97650d..dfa4e6a3 100644 --- a/strum_macros/src/to_string.rs +++ b/strum_macros/src/macros/strings/to_string.rs @@ -1,8 +1,8 @@ use proc_macro2::TokenStream; use syn; -use case_style::CaseStyle; -use helpers::{convert_case, extract_attrs, extract_meta, is_disabled, unique_attr}; +use crate::helpers::case_style::CaseStyle; +use crate::helpers::{extract_meta, CaseStyleHelpers, MetaIteratorHelpers}; pub fn to_string_inner(ast: &syn::DeriveInput) -> TokenStream { let name = &ast.ident; @@ -13,7 +13,8 @@ pub fn to_string_inner(ast: &syn::DeriveInput) -> TokenStream { }; let type_meta = extract_meta(&ast.attrs); - let case_style = unique_attr(&type_meta, "strum", "serialize_all") + let case_style = type_meta + .find_unique_property("strum", "serialize_all") .map(|style| CaseStyle::from(style.as_ref())); let mut arms = Vec::new(); @@ -22,21 +23,21 @@ pub fn to_string_inner(ast: &syn::DeriveInput) -> TokenStream { let ident = &variant.ident; let meta = extract_meta(&variant.attrs); - if is_disabled(&meta) { + if meta.is_disabled() { continue; } // Look at all the serialize attributes. - let output = if let Some(n) = unique_attr(&meta, "strum", "to_string") { + let output = if let Some(n) = meta.find_unique_property("strum", "to_string") { n } else { - let mut attrs = extract_attrs(&meta, "strum", "serialize"); + let mut attrs = meta.find_properties("strum", "serialize"); // We always take the longest one. This is arbitary, but is *mostly* deterministic attrs.sort_by_key(|s| s.len()); if let Some(n) = attrs.pop() { n } else { - convert_case(ident, case_style) + ident.convert_case(case_style) } };