1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#![warn(missing_docs)]

//! Provides extension to rust enum
//!
//! This crate provides `Enumeration` trait for rust `enum` with the following features
//! - implementation for common traits (Clone, Copy, Hash, etc.)
//! - getting number of variants through constant `Enumeration::VARIANT_COUNT`
//! - casting between index (of type `Enumeration::Index`) and enumeration
//! - attaching a constant value to each of the variants

/// Convenience re-export of common members
pub mod prelude {
    pub use super::enumerate;
    pub use super::Enumeration;
}

use std::fmt::{Debug, Display};
use std::hash::Hash;

/// Error type when casting from [Enumeration::Index] to [Enumeration].
///
/// Generated by using [Enumeration::variant()].
#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct OutOfRangeError<T: Enumeration>(pub T::Index);

impl<T: Enumeration> std::fmt::Display for OutOfRangeError<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Out of enumeration index range (0 to {}): {}",
            T::VARIANT_COUNT,
            self.0
        )
    }
}

impl<T: Enumeration + Debug> std::error::Error for OutOfRangeError<T> {}

/// A trait to extend enum.
///
/// You should not implement this directly, instead use [enumerate!].
/// The rest of the library assumes the constants are correct.
///
/// This trait provides support for
/// - implementation for common traits ([Clone], [Copy], [Hash], etc.)
/// - getting number of variants through constant [Self::VARIANT_COUNT]
/// - casting between index (of type [Self::Index]) and enumeration
/// - attaching a constant value to each of the variants
pub trait Enumeration:
    std::convert::TryFrom<Self::Index, Error = OutOfRangeError<Self>>
    + Into<Self::Index>
    + Clone
    + Copy
    + Debug
    + Hash
    + PartialEq
    + Eq
    + PartialOrd
    + Ord
where
    Self::AssociatedValueType: 'static + Debug,
    Self::Index: Debug + Display,
{
    /// The type of index this enumeration can cast to.
    type Index;

    /// The type of associated constant value of the variants of this enumeration.
    type AssociatedValueType;

    /// The number of variants of this enumeration.
    const VARIANT_COUNT: Self::Index;

    /// Default for associated constant value.
    const DEFAULT_VARIANT_ASSOCIATED_VALUE: Option<Self::AssociatedValueType>;

    /// Get the reference to the static associated constant value of the variant or the default constant value [Self::DEFAULT_VARIANT_ASSOCIATED_VALUE].
    fn value(&self) -> &'static Self::AssociatedValueType;

    /// Cast index to the respective enumeration.
    ///
    /// # Errors
    ///
    /// If the index is out of range (zero to [Self::VARIANT_COUNT] (exclusive)), this function will return [OutOfRangeError]
    fn variant(index: Self::Index) -> Result<Self, Self::Error> {
        Self::try_from(index)
    }

    /// Cast this enumeration to respective index.
    fn to_index(self) -> Self::Index {
        self.into()
    }
}

/// This macro helps to create enum with trait [Enumeration].
///
/// You have to pass in
/// - attributes (optional)
/// - a visibility qualifier (optional)
/// - a name
/// - a type this enumeration can cast to
/// - a type for associated constant values (optional)
///     - a default value for associated constant values (optional)
/// - at least a variant
///     - attributes (before variant) (optional)
///     - with associated constant value (only if the type is given) (optional only if default is given)
///
/// Note that commas after each variant isn't a must (`;` works too).
/// You can also specify enum after visibility
///
/// All patterns that start with @ is for internal macro implementation only.
///
/// # Simple usage
/// ```
/// # use enumeration::enumerate;
/// enumerate!(pub Foo(u8)
///     Bar
///     Baz
/// );
/// ```
///
/// produces
///
/// ```
/// # #[derive(Copy, Clone, Hash, Debug, PartialEq, Eq, PartialOrd, Ord)]
/// pub enum Foo {
///     Bar,
///     Baz,
/// }
/// ```
///
/// with [Enumeration] implementation.
///
/// # Syntax
/// You might notice that there is no comma after each variant.
/// The macro offers multiple syntax branch that will improve readability and comply to [official Rust syntax guidelines](https://rust-lang.github.io/api-guidelines/about.html).
///
/// ```
/// # use enumeration::enumerate;
/// enumerate!(pub enum Foo(u8) // enum is optional but suggested by official Rust syntax guidelines (https://rust-lang.github.io/api-guidelines/macros.html#input-syntax-is-evocative-of-the-output-c-evocative)
///     Bar, // comma is optional
///     Baz; // semicolon works too!
/// );
/// ```
///
/// # Casting between index and enumeration
/// ```
/// # use enumeration::enumerate;
/// enumerate!(Foo(u8)
///     Bar
///     Baz
/// );
///
/// # #[test]
/// # fn test() -> Result<Foo, enumeration::OutOfRangeError> {
/// assert_eq!(Foo::variant(0)?, Foo::Bar);
/// assert_eq!(Foo::variant(1)?, Foo::Baz);
/// assert_eq!(Foo::Bar.index(), 0);
/// assert_eq!(Foo::Baz.index(), 1);
/// assert!(Foo::variant(2).is_err());
/// # }
/// ```
///
/// # Associated constant values
/// ```
/// # use enumeration::enumerate;
/// enumerate!(Foo(u8; i32)
///     Bar = 10
///     Baz = 20
/// );
/// ```
///
/// produces
///
/// ```
/// # use enumeration::Enumeration;
/// # #[derive(Copy, Clone, Hash, Debug, PartialEq, Eq, PartialOrd, Ord)]
/// enum Foo {
///     Bar,
///     Baz,
/// }
///
/// # enumeration::impl_try_from_into!(u8, Foo);
/// #
/// impl Enumeration for Foo {
/// #     type Index = u8; type AssociatedValueType = i32; const VARIANT_COUNT: u8 = 2; const DEFAULT_VARIANT_ASSOCIATED_VALUE: Option<i32> = None;
/// #
///     fn value(&self) -> &'static i32 {
/// #         #[allow(non_upper_case_globals)]
///         const Bar: i32 = 10;
/// #         #[allow(non_upper_case_globals)]
///         const Baz: i32 = 20;
///         
///         match self {
///             Foo::Bar => &Bar,
///             Foo::Baz => &Baz,
///         }
///     }
/// }
///
/// fn example() {
///     println!("{}", Foo::Bar.value()); // prints 10
///     println!("{}", Foo::Baz.value()); // prints 20
/// }
/// ```
///
/// # Default constant value
/// ```
/// # use enumeration::enumerate;
/// enumerate!(Foo(u8; i32 = 20)
///     Bar
///     Baz = 10
/// );
/// ```
///
/// produces
///
/// ```
/// # use enumeration::Enumeration;
/// # #[derive(Copy, Clone, Hash, Debug, PartialEq, Eq, PartialOrd, Ord)]
/// enum Foo {
///     Bar,
///     Baz,
/// }
///
/// # enumeration::impl_try_from_into!(u8, Foo);
/// #
/// impl Enumeration for Foo {
/// #     type Index = u8; type AssociatedValueType = i32; const VARIANT_COUNT: u8 = 2;
///     const DEFAULT_VARIANT_ASSOCIATED_VALUE: Option<i32> = Some(20);
///
///     fn value(&self) -> &'static i32 {
/// #         #[allow(non_upper_case_globals)]
///         const Bar: Option<i32> = None;
/// #         #[allow(non_upper_case_globals)]
///         const Baz: Option<i32> = Some(10);
///         
///         match self {
///             Foo::Bar => Bar.as_ref().or(Self::DEFAULT_VARIANT_ASSOCIATED_VALUE.as_ref()).unwrap(),
///             Foo::Baz => Baz.as_ref().or(Self::DEFAULT_VARIANT_ASSOCIATED_VALUE.as_ref()).unwrap(),
///         }
///     }
/// }
///
/// fn example() {
///     println!("{}", Foo::Bar.value()); // prints 20
///     println!("{}", Foo::Baz.value()); // prints 10
/// }
/// ```
///
/// Note that default constant value is only created once, so the reference to it will always be same.
///
/// The macro will emit error if neither associated constant value nor default constant value is provided.
///
/// ```compile_fail
/// # use enumeration::enumerate;
/// enumerate!(Foo(u8; i32)
///     Bar
///     Baz = 10
/// );
/// ```
///
/// # Visibility
/// ```
/// # use enumeration::enumerate;
/// enumerate!(pub Foo(u8)
///     Bar
/// );
///
/// enumerate!(Baz(u8)
///     FooBar
/// );
/// ```
///
/// # Attributes
/// Attributes can be attached to enumeration itself, default constant value and each of the variants.
/// It's most useful for documentation.
///
/// ```
/// # use enumeration::enumerate;
/// enumerate!(#[doc="An enumeration named Foo"] pub Foo(u8; #[doc="Overwrite default constant value's documentation"] i32 = 0)
///     #[doc="Bar"] Bar
///     #[doc="Baz"] Baz
/// );
/// ```
///
/// # Examples
/// ```
/// # use enumeration::enumerate;
/// enumerate!(pub Color(u8; &'static str)
///     Red = "#FF0000"
///     Blue = "#0000FF"
///     Yellow = "#FFFF00"
///     Cyan = "#00FFFF"
/// );
///
/// enumerate!(State(u8)
///     None
///     Stationary
///     Moving
/// );
/// ```
#[macro_export]
macro_rules! enumerate {
    ($(#[$enum_attr:meta])* $visibility:vis $name:ident ($t:ident) $($(#[$attr:meta])* $variant:ident $(,)? $(;)?)*) => {
        $crate::enumerate!($(#[$enum_attr])* $visibility $name ($t; () = ()) $($(#[$attr])* $variant = ())*);
    };

    ($(#[$enum_attr:meta])* $visibility:vis enum $name:ident ($t:ident) $($(#[$attr:meta])* $variant:ident $(,)? $(;)?)*) => {
        $crate::enumerate!($(#[$enum_attr])* $visibility $name ($t; () = ()) $($(#[$attr])* $variant = ())*);
    };

    ($(#[$enum_attr:meta])* $visibility:vis enum $name:ident ($t:ident; $(#[$default_attr:meta])* $associated_value_type:ty $(= $default_value:expr)?) $($(#[$attr:meta])* $variant:ident $(= $associated_value:expr)? $(,)? $(;)?)*) => {
        $crate::enumerate!($(#[$enum_attr])* $visibility $name ($t; $(#[$default_attr])* $associated_value_type $(= $default_value)?) $($(#[$attr])* $variant = $(= $associated_value)?)*);
    };

    ($(#[$enum_attr:meta])* $visibility:vis $name:ident ($t:ident; $(#[$default_attr:meta])* $associated_value_type:ty $(= $default_value:expr)?) $($(#[$attr:meta])* $variant:ident $(= $associated_value:expr)? $(,)? $(;)?)*) => {
        $(#[$enum_attr])*
        #[repr($t)]
        #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
        $visibility enum $name {
            $($(#[$attr])* $variant,)*
        }

        impl $crate::Enumeration for $name {
            type Index = $t;
            type AssociatedValueType = $associated_value_type;
            const VARIANT_COUNT: $t = $crate::count!($($variant)*);
            $(#[$default_attr])*
            const DEFAULT_VARIANT_ASSOCIATED_VALUE: Option<Self::AssociatedValueType> = $crate::option!($($default_value)?);

            fn value(&self) -> &'static Self::AssociatedValueType {
                $crate::validate!($associated_value_type, $($default_value)?, $(($($attr)* : $variant : $($associated_value)?))*);

                match self {
                    $(Self::$variant => $variant.as_ref().or(Self::DEFAULT_VARIANT_ASSOCIATED_VALUE.as_ref()).unwrap(),)*
                }
            }
        }

        $crate::impl_try_from_into!($t, $name);
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_try_from_into {
    ($t:ty, $name:ident) => {
        impl std::convert::TryFrom<$t> for $name {
            type Error = $crate::OutOfRangeError<$name>;

            fn try_from(value: $t) -> Result<Self, $crate::OutOfRangeError<$name>> {
                #[allow(unused_comparisons)]
                if value >= 0 && value < <Self as $crate::Enumeration>::VARIANT_COUNT {
                    Ok(unsafe { std::mem::transmute(value) })
                } else {
                    Err($crate::OutOfRangeError(value))
                }
            }
        }

        impl Into<$t> for $name {
            fn into(self) -> $t {
                unsafe { std::mem::transmute(self) }
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! count {
    () => {
        0
    };

    ($head:tt $($rest:tt)*) => {
        1 + $crate::count!($($rest)*)
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! validate {
    ($t:ty, , ($($attr:meta)* : $variant:ident :)) => {
        compile_error!("Neither associated constant value nor default constant value provided")
    };

    ($t:ty, $default:expr, ($($attr:meta)* : $variant:ident :)) => {
        #[allow(non_upper_case_globals)]
        const $variant: Option<$t> = None;
    };

    ($t:ty, $($default:expr)?, ($($attr:meta)* : $variant:ident : $associated_value:expr)) => {
        #[allow(non_upper_case_globals)]
        const $variant: Option<$t> = Some($associated_value);
    };

    ($t:ty, $($default:expr)?, ($($attr:meta)* : $variant:ident : $($associated_value:expr)?) $(($($at:meta)* : $v:ident : $($a:expr)?))+) => {
        $crate::validate!($t, $($default)?, ($($attr)* : $variant : $($associated_value)?));
        $crate::validate!($t, $($default)?, $(($($at)* : $v : $($a)?))+);
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! option {
    () => {
        None
    };

    ($value:expr) => {
        Some($value)
    };
}