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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
#![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
//! - runtime representation of enumeration

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

use std::any::{TypeId, type_name};
use std::fmt::{Debug, Display};
use std::hash::Hash;
use std::marker::PhantomData;

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

impl<T: Enumeration> 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> {}

/// Error type when attempting to cast [Variant] to [Enumeration]
#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct CastError<T: Enumeration>(PhantomData<T>);

impl<T: Enumeration> Display for CastError<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Unable to cast from enumeration type from {}", type_name::<T>())
    }
}

impl<T: Enumeration> std::error::Error for CastError<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
    + 'static
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;

    #[inline(always)]
    /// 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)
    }

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

/// Provides runtime specialized representation of [Enumeration].
/// 
/// To avoid using `dyn` for mixing [Enumeration], you can use [Variant] with a trade-off for having to try casting before using it.
/// 
/// # Examples
/// ```
/// # use enumeration::prelude::*;
/// enumerate!(Foo(u8)
///     Bar
///     Baz
/// );
/// 
/// enumerate!(Color(u8)
///     Red
///     Green
///     Blue
/// );
/// 
/// let mut vec: Vec<Variant<u8>> = vec![Foo::Bar.into(), Color::Green.into(), Foo::Baz.into()]; // Variant::new(Foo::Bar) or Variant::from(Foo::Bar) works too
/// 
/// assert_eq!(vec[0].cast::<Foo>(), Ok(Foo::Bar));
/// assert!(vec[1].cast::<Foo>().is_err());
/// ```
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Variant<T: Debug> {
    type_id: TypeId,
    index: T,
}

impl<T: Enumeration> From<T> for Variant<T::Index> {
    fn from(e: T) -> Self {
        Self { type_id: TypeId::of::<T>(), index: e.to_index() }
    }
}

impl<T: Debug> Variant<T> {
    /// Construct [Variant] with [Enumeration]
    pub fn new<E: Enumeration>(e: E) -> Variant<E::Index> {
        Variant::from(e)
    }
    
    /// Returns the type id of the enumeration.
    pub fn type_id(self) -> TypeId {
        self.type_id
    }
    
    /// Returns the index of the enumeration.
    pub fn index(self) -> T {
        self.index
    }
    
    /// Try casting to the given generic parameter
    pub fn cast<E: Enumeration<Index = T>>(self) -> Result<E, CastError<E>> {
        if TypeId::of::<E>() == self.type_id {
            Ok(E::variant(self.index).unwrap())
        }
        else {
            Err(CastError(PhantomData))
        }
    }
}

/// Provides runtime specialized representation of [Enumeration] with specified [Enumeration::AssociatedValueType].
/// More details in [Variant].
/// 
/// It's basically [Variant] but with specified on what it's [Enumeration::AssociatedValueType] must be.
/// 
/// # Examples
/// ```compile_fail
/// # use enumerate::prelude::*;
/// enumerate!(Foo(u8; i32)
///     Bar = 111
///     Baz = 333
/// );
/// 
/// enumerate!(Color(u8; &'static str)
///     Red = "#FF0000"
///     Blue = "#0000FF"
///     Yellow = "#FFFF00"
///     Cyan = "#00FFFF"
/// );
/// 
/// let mut vec = vec![Color::Red.into(), Color::Blue.into()];
/// 
/// assert_eq!(vec[0].value(), "#FF0000");
/// 
/// vec.push(Foo::Bar.into()); // compile error
/// ```
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct VariantWith<T: Debug, U: 'static> {
    type_id: TypeId,
    index: T,
    value: &'static U,
}

impl<T: Enumeration> From<T> for VariantWith<T::Index, T::AssociatedValueType> {
    fn from(e: T) -> Self {
        Self { type_id: TypeId::of::<T>(), index: e.to_index(), value: e.value() }
    }
}

impl<T: Debug, U: 'static> VariantWith<T, U> {
    /// Constructs [VariantWith] with [Enumeration]
    pub fn new<E: Enumeration>(e: E) -> VariantWith<E::Index, E::AssociatedValueType> {
        VariantWith::from(e)
    }
    
    /// Returns the type id.
    pub fn type_id(self) -> TypeId {
        self.type_id
    }
    
    /// Returns the index.
    pub fn index(self) -> T {
        self.index
    }
    
    /// Returns the associated constant value without casting.
    pub fn value(self) -> &'static U {
        self.value
    }
    
    /// Try casting to the given generic parameter
    pub fn cast<E: Enumeration<Index = T, AssociatedValueType = U>>(self) -> Result<E, CastError<E>> {
        if TypeId::of::<E>() == self.type_id {
            Ok(E::variant(self.index).unwrap())
        }
        else {
            Err(CastError(PhantomData))
        }
    }
}

/// 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)?);
            
            #[inline]
            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>;

            #[inline(always)]
            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 {
            #[inline(always)]
            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)
    };
}