enuminfo_macros/lib.rs
1//! A collection of procedural derive macros providing inspection, string conversion,
2//! lookup, and variant enumeration utilities for Rust enums.
3//!
4//! # Overview
5//!
6//! This crate provides four derive macros:
7//! - [`EnumIs`]: Generates boolean checker methods (`is_<variant>()`) for enum variants.
8//! - [`EnumName`]: Generates `const` methods (`name()` and `raw_name()`) returning variant names as string slices.
9//! - [`EnumFromName`]: Generates lookup constructors (`from_name()` and `from_raw_name()`) to instantiate unit enum variants from string names (with optional [`FromStr`](core::str::FromStr) support).
10//! - [`EnumVariants`]: Generates an associated constant array slice (`VARIANTS`) and helper methods (`variants()` and `variant_count()`) containing all unit variants.
11//!
12//! # Attributes Reference
13//!
14//! The following attributes can be placed on enums or their variants under the `#[enuminfo(...)]` helper attribute:
15//!
16//! | Attribute | Target | Supported Macros | Description |
17//! |---|---|---|---|
18//! | `#[enuminfo(rename_all = "...")]` | Enum | [`EnumName`], [`EnumFromName`], [`EnumVariants`] | Applies a casing convention to variant names (e.g. `"snake_case"`). |
19//! | `#[enuminfo(rename = "...")]` | Variant | [`EnumName`], [`EnumFromName`], [`EnumVariants`] | Overrides the formatted name for an individual variant. |
20//! | `#[enuminfo(ignore_from_name)]` | Variant | [`EnumFromName`] | Excludes the variant from being constructed by `from_name()`, `from_raw_name()`, or `FromStr`. |
21//! | `#[enuminfo(ignore_variant)]` | Variant | [`EnumVariants`] | Excludes the variant from the generated `VARIANTS` slice and `variant_count()`. |
22//!
23//! > **Note:** `#[enuminfo(rename = "...")]` and `#[enuminfo(rename_all = "...")]` are accepted by [`EnumVariants`] for attribute compatibility when used alongside [`EnumName`] or [`EnumFromName`], but they do not affect variant instances in `VARIANTS`.
24//!
25//! # Case Conversions (`rename_all`)
26//!
27//! The `#[enuminfo(rename_all = "...")]` container attribute modifies how variant names are matched or returned.
28//! Supported casing conventions match the standard conventions used by **`serde`**:
29//!
30//! | Option | Conversion Type | Example (`MyVariant`) |
31//! |---|---|---|
32//! | `"lowercase"` | All lower case | `"myvariant"` |
33//! | `"UPPERCASE"` | All upper case | `"MYVARIANT"` |
34//! | `"camelCase"` / `"lowerCamelCase"` | Lower camel case | `"myVariant"` |
35//! | `"snake_case"` | Snake case | `"my_variant"` |
36//! | `"SCREAMING-SNAKE-CASE"` | Screaming snake case | `"MY_SNAKE_CASE"` |
37//! | `"kebab-case"` | Kebab case | `"my-variant"` |
38//! | `"SCREAMING-KEBAB-CASE"` | Screaming kebab case | `"MY-KEBAB-CASE"` |
39//! | `"PascalCase"` / `"UpperCamelCase"` | Pascal / Upper camel case | `"MyVariant"` |
40//!
41//! If an unrecognized casing string is provided, variant names remain unmodified.
42//!
43//! # Feature Flags
44//!
45//! This crate provides several Cargo feature flags:
46//!
47//! - **`from-str`** *(enabled by default)*: Generates an implementation of [`core::str::FromStr`] for enums deriving [`EnumFromName`].
48//! - **`impl-enuminfo`**: Implements companion traits from the [`enuminfo`](https://crates.io/crates/enuminfo) crate (`EnumIs`, `EnumName`, `EnumFromName`, `EnumVariants`).
49//! - **`skip-inherent`**: Skips generating inherent `impl` blocks on the enum, generating only trait implementations when combined with `impl-enuminfo`.
50
51mod enum_from_name;
52mod enum_is;
53mod enum_name;
54mod enum_variants;
55mod rename_case;
56
57extern crate proc_macro;
58use proc_macro::TokenStream;
59
60use syn::{parse_macro_input, DeriveInput};
61
62/// Derives helper methods to check if an enum instance matches a specific variant.
63///
64/// For every variant `VariantName`, this macro implements a `const` method named
65/// `is_<variant_name>(&self) -> bool` using `snake_case` naming.
66///
67/// # Compatibility & Limitations
68///
69/// - Works on `enum` types only.
70/// - Supports **all** enum variant types: unit variants (e.g. `Quit`), tuple variants
71/// (e.g. `Write(String)`), and struct variants (e.g. `Move { x: i32, y: i32 }`).
72///
73/// # Feature Flags
74///
75/// If the `impl-enuminfo` feature is enabled, this macro additionally implements
76/// the `enuminfo::EnumIs` marker trait for the enum.
77///
78/// # Example
79///
80/// ```rust
81/// # #[cfg(not(feature = "skip-inherent"))]
82/// # {
83/// use enuminfo_macros::EnumIs;
84///
85/// #[derive(EnumIs)]
86/// enum Message {
87/// Quit,
88/// Move { x: i32, y: i32 },
89/// Write(String),
90/// }
91///
92/// let msg = Message::Move { x: 10, y: 20 };
93/// assert!(msg.is_move());
94/// assert!(!msg.is_quit());
95/// assert!(!msg.is_write());
96/// # }
97/// ```
98#[proc_macro_derive(EnumIs)]
99pub fn enum_is(input: TokenStream) -> TokenStream {
100 let input = parse_macro_input!(input as DeriveInput);
101
102 enum_is::implement_enum_is(input)
103 .unwrap_or_else(|err| err.to_compile_error())
104 .into()
105}
106
107/// Derives methods to return the string representation of an enum variant.
108///
109/// This macro implements two `const` methods on the enum:
110/// - `name(&self) -> &'static str`: Returns the formatted variant name, taking into account
111/// any container `rename_all` casing transformation and variant-level `rename` overrides.
112/// - `raw_name(&self) -> &'static str`: Returns the exact Rust identifier name as written in code.
113///
114/// # Attributes
115///
116/// - `#[enuminfo(rename_all = "...")]`: Container attribute that transforms output strings using
117/// `serde`-compatible casing names (e.g. `"snake_case"`, `"kebab-case"`, `"camelCase"`).
118/// - `#[enuminfo(rename = "custom_name")]`: Variant attribute that overrides the output string
119/// for a specific variant.
120///
121/// # Compile-Time Checks
122///
123/// Validates at compile time that all variant names (after applying `rename_all` and `rename`)
124/// are unique. If a duplicate name is detected, compilation fails with an error.
125///
126/// # Compatibility & Limitations
127///
128/// - Works on `enum` types only.
129/// - Supports **all** enum variant types: unit variants, tuple variants, and struct variants.
130///
131/// # Feature Flags
132///
133/// If the `impl-enuminfo` feature is enabled, this macro additionally implements
134/// the `enuminfo::EnumName` trait for the enum.
135///
136/// # Example
137///
138/// ```rust
139/// # #[cfg(not(feature = "skip-inherent"))]
140/// # {
141/// use enuminfo_macros::EnumName;
142///
143/// #[derive(EnumName)]
144/// #[enuminfo(rename_all = "snake_case")]
145/// enum Status {
146/// Pending,
147/// #[enuminfo(rename = "in_progress_custom")]
148/// InProgress,
149/// Completed,
150/// }
151///
152/// let status = Status::Pending;
153/// assert_eq!(status.name(), "pending");
154/// assert_eq!(status.raw_name(), "Pending");
155///
156/// let in_progress = Status::InProgress;
157/// assert_eq!(in_progress.name(), "in_progress_custom");
158/// assert_eq!(in_progress.raw_name(), "InProgress");
159/// # }
160/// ```
161#[proc_macro_derive(EnumName, attributes(enuminfo))]
162pub fn enum_name(input: TokenStream) -> TokenStream {
163 let input = parse_macro_input!(input as DeriveInput);
164
165 enum_name::implement_enum_name(input)
166 .unwrap_or_else(|err| err.to_compile_error())
167 .into()
168}
169
170/// Derives constructor lookup methods to instantiate unit enum variants from string names.
171///
172/// This macro implements two lookup methods on the enum:
173/// - `pub fn from_name(name: &str) -> Option<Self>`: Matches against the formatted variant name
174/// (respecting `rename_all` casing rules and `rename` overrides).
175/// - `pub fn from_raw_name(name: &str) -> Option<Self>`: Matches strictly against the original Rust variant identifier name.
176///
177/// Additionally, when the `from-str` feature is enabled (default), it generates an implementation
178/// of [`core::str::FromStr`] that parses formatted variant names by delegating to `from_name()`.
179///
180/// # Attributes
181///
182/// - `#[enuminfo(rename_all = "...")]`: Container attribute setting variant lookup keys using
183/// `serde`-compatible casing options.
184/// - `#[enuminfo(rename = "custom_name")]`: Variant attribute overriding the lookup key for `from_name()`.
185/// - `#[enuminfo(ignore_from_name)]`: Variant attribute excluding the variant from both `from_name()`
186/// and `from_raw_name()` (and consequently from `FromStr`).
187///
188/// # Compile-Time Checks
189///
190/// Validates at compile time that all formatted variant lookup keys are unique. If duplicates
191/// occur, compilation fails with an error.
192///
193/// # Limitations
194///
195/// This macro supports **Unit Enums** only. Variants must have no data fields:
196/// - Unit variants (e.g. `Variant`)
197/// - Empty tuple variants (e.g. `Variant()`)
198/// - Empty struct variants (e.g. `Variant {}`)
199///
200/// Variants with fields will cause a compilation error.
201///
202/// # Feature Flags
203///
204/// - `from-str` *(default)*: Generates `impl std::str::FromStr for MyEnum`.
205/// - `impl-enuminfo`: Implements the `enuminfo::EnumFromName` trait for the enum.
206///
207/// # Example
208///
209/// ```rust
210/// # #[cfg(not(feature = "skip-inherent"))]
211/// # {
212/// use enuminfo_macros::EnumFromName;
213///
214/// #[derive(Debug, PartialEq, EnumFromName)]
215/// #[enuminfo(rename_all = "lowercase")]
216/// enum Priority {
217/// Low,
218/// High,
219/// #[enuminfo(ignore_from_name)]
220/// Critical,
221/// }
222///
223/// // Formatted lookup
224/// assert_eq!(Priority::from_name("low"), Some(Priority::Low));
225///
226/// // Raw identifier lookup
227/// assert_eq!(Priority::from_raw_name("Low"), Some(Priority::Low));
228///
229/// // Ignored variants cannot be constructed by name
230/// assert_eq!(Priority::from_name("critical"), None);
231/// assert_eq!(Priority::from_raw_name("Critical"), None);
232/// # }
233/// ```
234#[proc_macro_derive(EnumFromName, attributes(enuminfo))]
235pub fn enum_from_name(input: TokenStream) -> TokenStream {
236 let input = parse_macro_input!(input as DeriveInput);
237
238 enum_from_name::implement_enum_from_name(input)
239 .unwrap_or_else(|err| err.to_compile_error())
240 .into()
241}
242
243/// Derives a static slice and enumeration helpers containing all variants of a unit enum.
244///
245/// This macro implements the following items on the enum:
246/// - `pub const VARIANTS: &'static [Self]`: An associated static slice containing all (non-ignored) unit variant instances.
247/// - `pub const fn variants() -> &'static [Self]`: Returns `Self::VARIANTS`.
248/// - `pub const fn variant_count() -> usize`: Returns the total number of variants in the static slice (`Self::VARIANTS.len()`).
249///
250/// # Attributes
251///
252/// - `#[enuminfo(ignore_variant)]`: Variant attribute that excludes the variant from the generated `VARIANTS` slice,
253/// `variants()`, and `variant_count()`.
254/// - `#[enuminfo(rename = "...")]` / `#[enuminfo(rename_all = "...")]`: Accepted on enum and variant levels
255/// for attribute compatibility when derived together with [`EnumName`] or [`EnumFromName`], but has no effect
256/// on the instances placed in `VARIANTS`.
257///
258/// # Limitations
259///
260/// This macro supports **Unit Enums** only. Variants must have no data fields:
261/// - Unit variants (e.g. `Variant`)
262/// - Empty tuple variants (e.g. `Variant()`)
263/// - Empty struct variants (e.g. `Variant {}`)
264///
265/// Variants with fields will cause a compilation error.
266///
267/// # Feature Flags
268///
269/// If the `impl-enuminfo` feature is enabled, this macro additionally implements
270/// the `enuminfo::EnumVariants` trait for the enum.
271///
272/// # Example
273///
274/// ```rust
275/// # #[cfg(not(feature = "skip-inherent"))]
276/// # {
277/// use enuminfo_macros::EnumVariants;
278///
279/// #[derive(Debug, PartialEq, EnumVariants)]
280/// enum Direction {
281/// North,
282/// South,
283/// East,
284/// West,
285/// #[enuminfo(ignore_variant)]
286/// Unknown,
287/// }
288///
289/// // Retrieve slice of all variants
290/// assert_eq!(
291/// Direction::variants(),
292/// &[Direction::North, Direction::South, Direction::East, Direction::West]
293/// );
294///
295/// // Direct access to the associated constant
296/// assert_eq!(Direction::VARIANTS.len(), 4);
297///
298/// // Get the total variant count
299/// assert_eq!(Direction::variant_count(), 4);
300/// # }
301/// ```
302#[proc_macro_derive(EnumVariants, attributes(enuminfo))]
303pub fn enum_variants(input: TokenStream) -> TokenStream {
304 let input = parse_macro_input!(input as DeriveInput);
305
306 enum_variants::implement_enum_variants(input)
307 .unwrap_or_else(|err| err.to_compile_error())
308 .into()
309}
310