Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,26 @@

* [#431](https://github.com/Peternator7/strum/pull/431): Fix bug where `EnumString` ignored the `parse_err_ty`
attribute when the enum had a `#[strum(default)]` variant.
* [#489](https://github.com/Peternator7/strum/pull/489): Add a new derive, `EnumStringConst`, the const counterpart to
[`EnumString`](https://docs.rs/strum_macros/latest/strum_macros/derive.EnumString.html).

Trait impls can't be `const` yet, so it generates an inherent `const fn from_str_const` instead of implementing
`FromStr`, allowing enum variants to be parsed from strings in const contexts. Only enums where every variant is a
unit variant are supported.

```rust
#[derive(EnumStringConst)]
enum Currency {
USD,
EUR,
}

const USD: Currency = match Currency::from_str_const("USD") {
Ok(c) => c,
Err(_) => panic!("invalid currency"),
};
```

* [#474](https://github.com/Peternator7/strum/pull/474): EnumDiscriminants will now copy `default` over from the
original enum to the Discriminant enum.

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ Strum has implemented the following macros:
| Macro | Description |
| --- | ----------- |
| [EnumString] | Converts strings to enum variants based on their name. |
| [EnumStringConst] | Adds a `const fn` that converts strings to enum variants based on their name. |
| [Display] | Converts enum variants to strings |
| [FromRepr] | Convert from an integer to an enum. |
| [AsRefStr] | Implement `AsRef<str>` for `MyEnum` |
Expand Down Expand Up @@ -71,6 +72,7 @@ information through strings.
Strumming is also a very whimsical motion, much like writing Rust code.

[EnumString]: https://docs.rs/strum_macros/latest/strum_macros/derive.EnumString.html
[EnumStringConst]: https://docs.rs/strum_macros/latest/strum_macros/derive.EnumStringConst.html
[Display]: https://docs.rs/strum_macros/latest/strum_macros/derive.Display.html
[AsRefStr]: https://docs.rs/strum_macros/latest/strum_macros/derive.AsRefStr.html
[IntoStaticStr]: https://docs.rs/strum_macros/latest/strum_macros/derive.IntoStaticStr.html
Expand Down
1 change: 1 addition & 0 deletions strum/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ DocumentMacroRexports! {
EnumMessage,
EnumProperty,
EnumString,
EnumStringConst,
VariantNames,
FromRepr,
IntoStaticStr,
Expand Down
50 changes: 50 additions & 0 deletions strum_macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,56 @@ pub fn from_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
toks.into()
}

/// Converts strings to enum variants based on their name in a const context.
///
/// This is the const counterpart to [`EnumString`]. Trait implementations can't be `const`
/// yet, so instead of implementing `FromStr`, this generates an inherent method on the enum:
///
/// ```text
/// const fn from_str_const(s: &str) -> Result<Self, strum::ParseError>
/// ```
///
/// Strings are matched using the same rules as `EnumString`, so `serialize`, `to_string`,
/// `serialize_all`, `ascii_case_insensitive` and `disabled` all behave the way they do there.
/// The enum must consist entirely of unit variants since there's no way to construct variants
/// with additional data in a const fn. For the same reason, `default` is not supported.
/// `parse_err_ty` and `parse_err_fn` can be used to return a custom error type, but the given
/// function must be a `const fn`.
///
/// # Example how to use `EnumStringConst`
/// ```
/// use strum_macros::EnumStringConst;
///
/// #[derive(Debug, PartialEq, EnumStringConst)]
/// enum Color {
/// Red,
/// // We can match on multiple different patterns.
/// #[strum(serialize = "blue", serialize = "b")]
/// Blue,
/// // Comparisons can be case insensitive (ASCII only).
/// #[strum(ascii_case_insensitive)]
/// Black,
/// }
///
/// const RED: Color = match Color::from_str_const("Red") {
/// Ok(color) => color,
/// Err(_) => panic!("invalid color"),
/// };
/// assert_eq!(Color::Red, RED);
/// assert_eq!(Ok(Color::Blue), Color::from_str_const("b"));
/// assert_eq!(Ok(Color::Black), Color::from_str_const("bLACk"));
/// assert!(Color::from_str_const("Yellow").is_err());
/// ```
#[proc_macro_derive(EnumStringConst, attributes(strum))]
pub fn from_string_const(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as DeriveInput);

let toks = macros::from_string_const::from_string_const_inner(&ast)
.unwrap_or_else(|err| err.to_compile_error());
debug_print_generated(&ast, &toks);
toks.into()
}

/// Converts enum variants to `&'a str`, where `'a` is the lifetime of the input enum reference.
///
/// Implements `AsRef<str>` on your enum using the same rules as
Expand Down
1 change: 1 addition & 0 deletions strum_macros/src/macros/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ mod strings;
pub use self::strings::as_ref_str;
pub use self::strings::display;
pub use self::strings::from_string;
pub use self::strings::from_string_const;
pub use self::strings::to_string;
118 changes: 118 additions & 0 deletions strum_macros/src/macros/strings/from_string_const.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
use proc_macro2::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Fields, LitByteStr};

use crate::helpers::{
missing_parse_err_attr_error, non_enum_error, non_unit_variant_error,
HasStrumVariantProperties, HasTypeProperties,
};

pub fn from_string_const_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let vis = &ast.vis;
let variants = match &ast.data {
Data::Enum(v) => &v.variants,
_ => return Err(non_enum_error()),
};

let type_properties = ast.get_type_properties()?;
let strum_module_path = type_properties.crate_module_path();

let mut match_arms = Vec::new();
let mut has_case_insensitive_arm = false;
for variant in variants {
let ident = &variant.ident;
let variant_properties = variant.get_variant_properties()?;

if variant_properties.disabled.is_some() {
continue;
}

if let Some(kw) = variant_properties.default {
return Err(syn::Error::new_spanned(
kw,
"Default is not supported by EnumStringConst because the default \
variant can't be constructed in a const fn",
));
}

if !matches!(variant.fields, Fields::Unit) {
return Err(non_unit_variant_error());
}

let is_ascii_case_insensitive = variant_properties
.ascii_case_insensitive
.unwrap_or(type_properties.ascii_case_insensitive);

for serialization in variant_properties.get_serializations(type_properties.case_style) {
// `&str` can't be matched in a const fn, so match on `s.as_bytes()` with
// byte string literals instead.
let serialization =
LitByteStr::new(serialization.value().as_bytes(), serialization.span());

if is_ascii_case_insensitive {
has_case_insensitive_arm = true;
match_arms.push(
quote! { s if eq_ignore_ascii_case(s, #serialization) => #name::#ident, },
);
} else {
match_arms.push(quote! { #serialization => #name::#ident, });
}
}
}

// Same rules as EnumString for custom error types, except that without a default
// variant, parsing is never infallible so the attributes are all-or-nothing.
let (err_ty, not_found_expr) =
match (&type_properties.parse_err_ty, &type_properties.parse_err_fn) {
(Some(ty), Some(f)) => (quote! { #ty }, quote! { #f(s) }),
(None, None) => (
quote! { #strum_module_path::ParseError },
quote! { #strum_module_path::ParseError::VariantNotFound },
),
_ => return Err(missing_parse_err_attr_error()),
};

// `str::eq_ignore_ascii_case` isn't a const fn, so roll our own over the byte
// slices. It's defined inside the generated fn to keep it out of the caller's scope.
let eq_ignore_ascii_case_fn = if has_case_insensitive_arm {
quote! {
const fn eq_ignore_ascii_case(lhs: &[u8], rhs: &[u8]) -> bool {
if lhs.len() != rhs.len() {
return false;
}

let mut i = 0;
while i < lhs.len() {
if !lhs[i].eq_ignore_ascii_case(&rhs[i]) {
return false;
}

i += 1;
}

true
}
}
} else {
quote! {}
};

Ok(quote! {
#[allow(clippy::use_self)]
#[automatically_derived]
impl #impl_generics #name #ty_generics #where_clause {
#[doc = "Try to create [Self] from a string in a const context"]
#[inline]
#vis const fn from_str_const(s: &str) -> ::core::result::Result<#name #ty_generics, #err_ty> {
#eq_ignore_ascii_case_fn

::core::result::Result::Ok(match s.as_bytes() {
#(#match_arms)*
_ => return ::core::result::Result::Err(#not_found_expr),
})
}
}
})
}
1 change: 1 addition & 0 deletions strum_macros/src/macros/strings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use syn::{Fields, Ident, Variant};
pub mod as_ref_str;
pub mod display;
pub mod from_string;
pub mod from_string_const;
pub mod to_string;

struct NonSingleFieldEnum;
Expand Down
117 changes: 117 additions & 0 deletions strum_tests/tests/from_str_const.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
use std::str::FromStr;
use strum::{EnumString, EnumStringConst, ParseError};

mod core {} // ensure macros call `::core`

#[derive(Debug, Eq, PartialEq, EnumStringConst)]
enum Color {
Red,
#[strum(serialize = "b", serialize = "blue")]
Blue,
#[strum(to_string = "purp")]
Purple,
#[strum(serialize = "blk", serialize = "Black", ascii_case_insensitive)]
Black,
#[allow(dead_code)]
#[strum(disabled)]
Green,
}

#[test]
fn color_simple() {
const RED: Result<Color, ParseError> = Color::from_str_const("Red");
assert_eq!(Ok(Color::Red), RED);
}

#[test]
fn color_serialize() {
const BLUE: Result<Color, ParseError> = Color::from_str_const("blue");
assert_eq!(Ok(Color::Blue), BLUE);
assert_eq!(Ok(Color::Blue), Color::from_str_const("b"));
}

#[test]
fn color_to_string() {
assert_eq!(Ok(Color::Purple), Color::from_str_const("purp"));
}

#[test]
fn color_ascii_case_insensitive() {
const BLACK: Result<Color, ParseError> = Color::from_str_const("bLaCk");
assert_eq!(Ok(Color::Black), BLACK);
assert_eq!(Ok(Color::Black), Color::from_str_const("BLK"));

// Only variants marked ascii_case_insensitive should match loosely.
assert_eq!(
Err(ParseError::VariantNotFound),
Color::from_str_const("red")
);
}

#[test]
fn color_not_found() {
const MISSING: Result<Color, ParseError> = Color::from_str_const("Orange");
assert_eq!(Err(ParseError::VariantNotFound), MISSING);
assert_eq!(
Err(ParseError::VariantNotFound),
Color::from_str_const("Green")
);
}

#[derive(Debug, Eq, PartialEq, EnumString, EnumStringConst)]
#[strum(serialize_all = "snake_case")]
enum Brightness {
DarkBlack,
#[strum(serialize = "Bright")]
BrightWhite,
}

#[test]
fn brightness_serialize_all() {
const DARK_BLACK: Result<Brightness, ParseError> = Brightness::from_str_const("dark_black");
assert_eq!(Ok(Brightness::DarkBlack), DARK_BLACK);
assert_eq!(
Ok(Brightness::BrightWhite),
Brightness::from_str_const("Bright")
);
}

#[test]
fn brightness_agrees_with_enum_string() {
// Both derives should parse the same strings to the same variants.
for s in ["dark_black", "Bright", "DarkBlack", "nope"] {
assert_eq!(
Brightness::from_str(s).ok(),
Brightness::from_str_const(s).ok()
);
}
}

#[derive(Debug, Eq, PartialEq, EnumStringConst)]
#[strum(
parse_err_fn = const_not_found_err,
parse_err_ty = ConstNotFoundError
)]
enum ConstCustomParseErrorEnum {
Red,
Blue,
}

#[derive(Debug, Eq, PartialEq)]
struct ConstNotFoundError;

// The given parse_err_fn has to be a const fn for from_str_const to work.
const fn const_not_found_err(_s: &str) -> ConstNotFoundError {
ConstNotFoundError
}

#[test]
fn custom_parse_error() {
const RED: Result<ConstCustomParseErrorEnum, ConstNotFoundError> =
ConstCustomParseErrorEnum::from_str_const("Red");
assert_eq!(Ok(ConstCustomParseErrorEnum::Red), RED);

const MISSING: Result<ConstCustomParseErrorEnum, ConstNotFoundError> =
ConstCustomParseErrorEnum::from_str_const("yellow");
assert_eq!(Err(ConstNotFoundError), MISSING);
}