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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ reference and migration guide.
trait impls (`From`, `AsRef`, `FromStr`, `TryFrom`) instead.
- Each generated item is now individually toggleable via
`enable`/`disable` attributes.
- `EnumStr` now derives `Display` for the enum (writes the variant's
name); toggleable via `#[enum_str(impl_display(enable/disable))]`,
disabled by `no_rendering`.
- Removed the `serde` feature; use the generated `FromStr`/`TryFrom`
impls with your own error type.
- `EnumAll` now generates `ALL`/`COUNT` constants
Expand Down
10 changes: 10 additions & 0 deletions docs/enum_str.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ impl AsRef<str> for Foo {
fn as_ref(&self) -> &str { ... }
}

impl fmt::Display for Foo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ... }
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct InvalidFoo {}
Expand Down Expand Up @@ -141,6 +145,7 @@ Skip all rendering. Equivalent to disabling:
- `ALL_ALIASES`
- `impl From<T> for &'static str`
- `impl AsRef<str> for T`
- `impl Display for T`

### `#[enum_str(no_parsing)]`

Expand Down Expand Up @@ -185,6 +190,11 @@ Enabled by default, disabled by `no_rendering`.
Control `impl AsRef<str> for T`.
Enabled by default, disabled by `no_rendering`.

### `#[enum_str(impl_display(enable/disable))]`

Control `impl std::fmt::Display for T`, which writes the variant's name.
Enabled by default, disabled by `no_rendering`.

### `#[enum_str(impl_from_str(enable/disable))]`

Control `impl FromStr for T`.
Expand Down
4 changes: 4 additions & 0 deletions enum-helper-derive/src/enum_str/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub struct EnumAttr {

pub impl_into_static_str: ImplAttr,
pub impl_as_ref_str: ImplAttr,
pub impl_display: ImplAttr,
pub impl_from_str: ImplAttr,
pub impl_try_from_str: ImplAttr,

Expand Down Expand Up @@ -51,6 +52,7 @@ impl EnumAttr {

impl_into_static_str: ImplAttr::new(ENUM_STR, IMPL_INTO_STATIC_STR),
impl_as_ref_str: ImplAttr::new(ENUM_STR, IMPL_AS_REF_STR),
impl_display: ImplAttr::new(ENUM_STR, IMPL_DISPLAY),
impl_from_str: ImplAttr::new(ENUM_STR, IMPL_FROM_STR),
impl_try_from_str: ImplAttr::new(ENUM_STR, IMPL_TRY_FROM_STR),

Expand Down Expand Up @@ -93,6 +95,8 @@ impl EnumAttr {
ret.impl_into_static_str.try_from_meta(cx, &meta)
} else if meta.path == ret.impl_as_ref_str.name() {
ret.impl_as_ref_str.try_from_meta(cx, &meta)
} else if meta.path == ret.impl_display.name() {
ret.impl_display.try_from_meta(cx, &meta)
} else if meta.path == ret.impl_from_str.name() {
ret.impl_from_str.try_from_meta(cx, &meta)
} else if meta.path == ret.impl_try_from_str.name() {
Expand Down
18 changes: 18 additions & 0 deletions enum-helper-derive/src/enum_str/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub fn generate(ir: Ir<'_>) -> TokenStream {
if ir.gen_options.fn_as_name.is_some()
|| ir.gen_options.impl_into_static_str
|| ir.gen_options.impl_as_ref_str
|| ir.gen_options.impl_display
{
blocks.push(gen_fn_inner_as_name(&ir));
}
Expand All @@ -38,6 +39,9 @@ pub fn generate(ir: Ir<'_>) -> TokenStream {
if ir.gen_options.impl_as_ref_str {
blocks.push(gen_impl_as_ref_str(&ir));
}
if ir.gen_options.impl_display {
blocks.push(gen_impl_display(&ir));
}

if ir.error.gen_error_struct {
blocks.push(gen_error_struct(&ir));
Expand Down Expand Up @@ -263,6 +267,20 @@ fn gen_impl_as_ref_str(ir: &Ir<'_>) -> TokenStream {
}
}

fn gen_impl_display(ir: &Ir<'_>) -> TokenStream {
let ident = &ir.ident;
let (impl_generics, ty_generics, where_clause) = &ir.generics.split_for_impl();

quote! {
#[automatically_derived]
impl #impl_generics ::core::fmt::Display for #ident #ty_generics #where_clause {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::Display::fmt(self.__enum_str_as_name(), f)
}
}
}
}

fn gen_error_struct(ir: &Ir) -> TokenStream {
let error_vis = &ir.error.vis;
let error_ident = &ir.error.ident;
Expand Down
1 change: 1 addition & 0 deletions enum-helper-derive/src/enum_str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub struct GenOptions {
const_all_aliases: Option<GenOption>,
impl_into_static_str: bool,
impl_as_ref_str: bool,
impl_display: bool,
impl_from_str: bool,
impl_try_from_str: bool,
}
Expand Down
2 changes: 2 additions & 0 deletions enum-helper-derive/src/enum_str/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ fn make_gen_options(input: &syn::DeriveInput, enum_attr: EnumAttr) -> GenOptions

let impl_into_static_str = enum_attr.impl_into_static_str.enabled_or(rendering);
let impl_as_ref_str = enum_attr.impl_as_ref_str.enabled_or(rendering);
let impl_display = enum_attr.impl_display.enabled_or(rendering);

let impl_from_str = enum_attr.impl_from_str.enabled_or(parsing);
let impl_try_from_str = enum_attr.impl_try_from_str.enabled_or(parsing);
Expand All @@ -189,6 +190,7 @@ fn make_gen_options(input: &syn::DeriveInput, enum_attr: EnumAttr) -> GenOptions
const_all_aliases,
impl_into_static_str,
impl_as_ref_str,
impl_display,
impl_from_str,
impl_try_from_str,
}
Expand Down
4 changes: 3 additions & 1 deletion enum-helper-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use syn::{DeriveInput, parse_macro_input};
/// - `const ALL_ALIASES: [&'static str; M]`
/// - `impl From<T> for &'static str`
/// - `impl AsRef<str> for T`
/// - `impl Display for T`
/// - `impl FromStr for T`
/// - `impl TryFrom<&str> for T`
/// - Error struct for invalid conversion from str
Expand All @@ -38,14 +39,15 @@ use syn::{DeriveInput, parse_macro_input};
/// - `#[enum_str(rename_all = "snake_case")]`: rename all variants by rule
/// - `#[enum_str(alias_all = "lowercase")]`: add aliases to all variants by rule (repeatable)
/// - `#[enum_str(default)]`: fills non-unit variant's fields with default value during parsing
/// - `#[enum_str(no_rendering)]`: skip `as_name`, `as_aliases`, `ALL_NAMES`, `ALL_ALIASES`, `From`, `AsRef`
/// - `#[enum_str(no_rendering)]`: skip `as_name`, `as_aliases`, `ALL_NAMES`, `ALL_ALIASES`, `From`, `AsRef`, `Display`
/// - `#[enum_str(no_parsing)]`: skip `FromStr`, `TryFrom`, and the error struct
/// - `#[enum_str(as_name(name = ..., vis = "...", enable/disable))]`: control the `as_name` method
/// - `#[enum_str(as_aliases(...))]`: control the `as_aliases` method
/// - `#[enum_str(all_names(...))]`: control the `ALL_NAMES` constant
/// - `#[enum_str(all_aliases(...))]`: control the `ALL_ALIASES` constant
/// - `#[enum_str(impl_into_static_str(enable/disable))]`: control `impl From<T> for &'static str`
/// - `#[enum_str(impl_as_ref_str(enable/disable))]`: control `impl AsRef<str> for T`
/// - `#[enum_str(impl_display(enable/disable))]`: control `impl std::fmt::Display for T`
/// - `#[enum_str(impl_from_str(enable/disable))]`: control `impl FromStr for T`
/// - `#[enum_str(impl_try_from_str(enable/disable))]`: control `impl TryFrom<&str> for T`
/// - `#[enum_str(error(name = ..., vis = "...", enable/disable))]`: control the error struct (default name `Invalid{Enum}`)
Expand Down
1 change: 1 addition & 0 deletions enum-helper-derive/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub const ENUM_STR: Symbol = Symbol("enum_str");
pub const ERROR_MSG: Symbol = Symbol("error_msg");
pub const ERROR: Symbol = Symbol("error");
pub const IMPL_AS_REF_STR: Symbol = Symbol("impl_as_ref_str");
pub const IMPL_DISPLAY: Symbol = Symbol("impl_display");
pub const IMPL_FROM_STR: Symbol = Symbol("impl_from_str");
pub const IMPL_INTO_STATIC_STR: Symbol = Symbol("impl_into_static_str");
pub const IMPL_TRY_FROM_STR: Symbol = Symbol("impl_try_from_str");
Expand Down
6 changes: 6 additions & 0 deletions enum-helper/tests/enum_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ fn basic_case_try_from_str() {
check!(BasicCase::try_from("baz").is_err());
}

#[test]
fn basic_case_display() {
check!(format!("{}", BasicCase::FooBar) == "FooBar");
check!(format!("{}", BasicCase::Baz) == "Baz");
}

#[derive(EnumStr, PartialEq, Eq)]
enum SpecialName {
#[allow(non_camel_case_types)]
Expand Down
23 changes: 23 additions & 0 deletions enum-helper/tests/enum_str_granular.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use assert2::check;
use core::fmt;
use enum_helper::EnumStr;

// Custom method names via `name = ...`. The generated `Into<&'static str>` and
Expand Down Expand Up @@ -54,6 +55,28 @@ fn no_parse_keeps_rendering() {
check!(NoParse::ALL_NAMES == ["Foo"]);
}

// Disabling `impl_display` removes the generated `Display` impl; the user can
// provide their own without conflict. Other rendering still works.
#[derive(EnumStr, PartialEq, Eq)]
#[enum_str(impl_display(disable))]
enum NoDisplay {
Foo,
}

impl fmt::Display for NoDisplay {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "custom")
}
}

#[test]
fn no_display_keeps_other_rendering() {
check!(NoDisplay::Foo.as_name() == "Foo");
let s: &str = NoDisplay::Foo.as_ref();
check!(s == "Foo");
check!(format!("{}", NoDisplay::Foo) == "custom");
}

// Disabling conversion impls while keeping as_name.
#[derive(EnumStr, PartialEq, Eq)]
#[enum_str(impl_into_static_str(disable), impl_as_ref_str(disable))]
Expand Down
6 changes: 6 additions & 0 deletions enum-helper/tests/enum_str_no_gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ impl AsRef<str> for NoRendering {
}
}

impl fmt::Display for NoRendering {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "test")
}
}

// no_parsing: derive must not generate FromStr/TryFrom/error struct.
// We provide our own and confirm there is no conflict.
#[derive(EnumStr, PartialEq, Eq)]
Expand Down
Loading