enumeraties 0.1.0

Static properties on enum variants
Documentation
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
#![forbid(unsafe_code)]
#![cfg_attr(feature = "bench", feature(test))]
//! This crate provides a macro to add static, const, or lazy-initialized
//! properties to enum variants.
//!
//! This is a variation on the
//! [`enum_properties`](https://github.com/cofinite/enum_properties) crate.
//! It extends it and allows additionally to define multiple property structs
//! onto the same enum and adds support for `static` (instead of `const`)
//! properties as well as lazily initialized properties. However, this
//! additional features set comes with a syntax that is a bit more verbose,
//! hence, if you just need a single const-initialized property, you might find
//! `enum_properties` more concise. Nevertheless, you can also combine this
//! crate with `enum_properties` using the best of both as shown in the
//! [enum_props_combo](examples/enum_props_combo.rs) example.
//!
//! See the [`props`](crate::props) macro for more details.
//!
//! # Example
//!
//! ```
//! use enumeraties::props;
//!
//! // A property struct
//! struct Prop { name: &'static str }
//!
//! // An enum
//! enum Foo {A}
//!
//! // Defining `Prop` on `Foo` via Deref
//! props! {
//!     impl Deref for Foo as const Prop {
//!         Self::A => {
//!             name: "Foo",
//!         }
//!     }
//! }
//!
//! // Accessing the property on `Foo`
//! assert_eq!(Foo::A.name, "Foo");
//! ```



/// The trait that is implemented through [`props`] macro.
///
/// This trait allows to write generic code that uses arbitrary enums that
/// happen to have specific properties defined on them.
///
/// # Example
///
/// ```
/// use enumeraties::props;
/// use enumeraties::EnumProp;
///
/// struct Prop {
///     name: &'static str,
/// }
///
/// // A generic function that works for any enum that has the `Prop` property
/// fn to_name<E>(e: E) -> &'static str
/// where
///     E: EnumProp<Prop>,
/// {
///     // The `Prop` struct can be accessed via the `property` method
///     e.property().name
/// }
///
/// // One enum that will get the props
/// enum Foo {
///     A,
///     B,
/// }
/// props! {
///     impl Deref for Foo as const Prop {
///         Self::A => {
///             name: "Foo",
///         }
///         Self::B => {
///             name: "Foobar",
///         }
///     }
/// }
///
/// // Another enum that will get the same props
/// enum Bar {
///     C,
///     D,
/// }
/// props! {
///     impl Deref for Bar as const Prop {
///         Self::C => {
///             name: "Bar",
///         }
///         Self::D => {
///             name: "Barfoo",
///         }
///     }
/// }
///
/// // Both enum can be used to call that function
/// assert_eq!(to_name(Foo::A), "Foo");
/// assert_eq!(to_name(Bar::C), "Bar");
/// ```
///
pub trait EnumProp<Prop> {
	fn property(&self) -> &'static Prop;
}

// For the macro
#[doc(hidden)]
pub use core::ops::Deref;

// Could still be feature gated
#[doc(hidden)]
pub use lazy_static; // 1.4.0

// The public front-end macro

/// Adds a property onto an enum
///
/// # Const, Static, Lazy
///
/// This macro allows implement properties in three different ways:
/// * as `const`, a constant
/// * as `static`, a global variable
/// * as `lazy`, a lazily initialized static
///
/// `const` and `static` are very similar, but have subtle difference:
/// the property type put into a `static` must implement `Send`. However,
/// with a `static` it is guaranteed that for each variant there is exactly one
/// unique property value and thus a unique reference address.
/// With `const` the compiler is allowed to merge properties (if they are equal)
/// or to inline and instantiated the same logical property multiple times,
/// i.e. the same logical property might be accessed via different reference
/// addresses.
/// In the very most cases, the actual reference address should not be of any
/// concern and thus it is recommended to use `const` over `static`.
///
/// One notable use-case for `static` is when the property contains interior
/// mutability.
/// In these cases, `const` shouldn't even compile.
///
/// `lazy`, on the other hand, is quite different from the `const` and `static`.
/// While `const` and `static` require constant initialized values computed at
/// compile-time, `lazy` allows to evaluate the value lazily at runtime,
/// instead. However, this feature incurs some overhead at each access, because
/// it must be checked that the value was indeed already initialized.
/// And of course, the first access to a `lazy` value, will incur the additional
/// delay to initialize the value.
///
///
/// # Syntax
///
/// This macro comes with essentially three different syntaxes: to implement
/// `Deref` (for the primary property), add an inherent access method
/// (for secondary properties), or just implementing `EnumProp` onto it (e.g.,
/// if only used by generic code).
///
/// ## Implementing [Deref](core::ops::Deref)
///
/// Syntax:
///
/// ```text
/// impl Deref for <ENUM> as (const|static|lazy) <PROPERTY> {
///     <VARIANT> => {
///         <FIELD> : <VALUE>,
///         ...
///     },
///     ...
/// }
/// ```
///
/// Example:
///
/// ```
/// # use enumeraties::props;
/// struct Prop { name: &'static str }
/// enum Foo {A}
/// props! {
///     impl Deref for Foo as const Prop {
///         Self::A => {
///             name: "Foo",
///         }
///     }
/// }
/// // Direct access due to deref
/// assert_eq!(Foo::A.name, "Foo");
/// ```
///
///
/// ## Implementing an inherent method
///
/// Syntax:
///
/// ```text
/// impl <ENUM> : <VIS> fn <FN_NAME> as (const|static|lazy) <PROPERTY> {
///     <VARIANT> => {
///         <FIELD> : <VALUE>,
///         ...
///     },
///     ...
/// }
/// ```
///
/// Example:
///
/// ```
/// # use enumeraties::props;
/// struct Prop { name: &'static str }
/// enum Foo {A}
/// props! {
///     // Of course, an arbitrary function names can be used instead of `getter`
///     impl Foo : fn getter as const Prop {
///         Self::A => {
///             name: "Foo",
///         }
///     }
/// }
/// // Access via inherent method
/// assert_eq!(Foo::A.getter().name, "Foo");
/// ```
///
/// ## Implementing only `EnumProp`
///
/// Syntax:
///
/// ```text
/// impl EnumProp for <ENUM> as (const|static|lazy) <PROPERTY> {
///     <VARIANT> => {
///         <FIELD> : <VALUE>,
///         ...
///     },
///     ...
/// }
/// ```
///
/// Example:
///
/// ```
/// # use enumeraties::props;
/// struct Prop { name: &'static str }
/// enum Foo {A}
/// props! {
///     impl EnumProp for Foo as const Prop {
///         Self::A => {
///             name: "Foo",
///         }
///     }
/// }
/// // Access via universal function call
/// use enumeraties::EnumProp;
/// assert_eq!(EnumProp::<Prop>::property(&Foo::A).name, "Foo");
/// ```
///
#[macro_export]
macro_rules! props {
	(
		// A lazy/const impl that will be promoted to `Deref` (also impls `EnumProp`)
		impl Deref for $enum_name:ty as $modifier:ident $prop_name:path { $($matching:tt)* }
	) => {
		// Add the EnumProp impl
		$crate::internal_props_impl_macro!{
			@EnumProp
			mod($modifier) ($prop_name) for $enum_name {
				$($matching)*
			}
		}

		// Add the deref forwarding
		impl $crate::Deref for $enum_name {
			type Target = $prop_name;
			fn deref(&self) -> &Self::Target {
				$crate::EnumProp::<$prop_name>::property(self)
			}
		}
	};
	(
		// The lazy/const impl via inherent method (also impls `EnumProp`)
		impl $enum_name:ty : $fn_vis:vis fn $fn_name:ident as $modifier:ident $prop_name:path { $($matching:tt)* }
	) => {
		// Add the EnumProp impl
		$crate::internal_props_impl_macro!{
			@EnumProp
			mod($modifier) ($prop_name) for $enum_name {
				$($matching)*
			}
		}

		// Add the inherent method forwarding
		impl $enum_name {
			$fn_vis fn $fn_name(&self) -> &'static $prop_name {
				$crate::EnumProp::<$prop_name>::property(self)
			}
		}
	};
	(
		// The lazy/const impl `EnumProp` only
		impl EnumProp for $enum_name:ty as $modifier:ident $prop_name:path { $($matching:tt)* }
	) => {
		// Add the EnumProp impl
		$crate::internal_props_impl_macro!{
			@EnumProp
			mod($modifier) ($prop_name) for $enum_name {
				$($matching)*
			}
		}
	};
}

// The internal marco impl, used by `props`, do not use, its API may change
// at any time
#[doc(hidden)]
#[macro_export]
macro_rules! internal_props_impl_macro {
	(
		// The enum prop impl, entry rule
		@EnumProp
		mod($modifier:ident) ($prop_name:path) for $enum_name:ty {
			$(
				// True match branches, could be simplified to `ident`, but then
				// one can on longer identify e.g. `Beta(42)` (maybe one shouldn't)
				$branch:pat => {
					$(
						$struct_fields:tt
					)*
				} $(,)?
			)*
		}
	) => {
		impl $crate::EnumProp<$prop_name> for $enum_name {
			fn property(&self) -> &'static $prop_name {
				#[deny(unreachable_patterns)] // Remember the `Self` prefix
				match self {
					$(
						$branch => {
							$crate::internal_props_impl_macro!(
								@Branch mod($modifier) $prop_name {
									$( $struct_fields )*
								}
							)
						},
					)*
				}
			}
		}
	};

	(
		// A single *const* prop value
		@Branch
		mod(const) $prop_name:path {
			$(
				$field:ident : $value:expr
			),* $(,)?
		}
	) => {{
		// A const reference, given that all `$value`s are const-init

		// Notice, having the explicit constant gives clearer error messages.

		// `BAR` is rather arbitrary here, maybe different name would be better
		const BAR : $prop_name = {
			$prop_name {
				$(
					$field : $value ,
				)*
			}
		};

		& BAR
	}};

	(
		// A single *static* prop value
		@Branch
		mod(static) $prop_name:path {
			$(
				$field:ident : $value:expr
			),* $(,)?
		}
	) => {{
		// A static reference given, that all `$value`s are const-init

		// `BAZ` is rather arbitrary here, maybe different name would be better
		static BAZ : $prop_name = {
			$prop_name {
				$(
					$field : $value ,
				)*
			}
		};

		& BAZ
	}};

	(
		// A single *const* prop value
		@Branch
		mod(lazy) $prop_name:path {
			$(
				$field:ident : $value:expr
			),* $(,)?
		}
	) => {{
		// A static reference via lazy_static.

		// `FOO` is rather arbitrary here, maybe different name would be better
		$crate::lazy_static::lazy_static!{
			static ref FOO: $prop_name = {
				$prop_name {
					$(
						$field : $value ,
					)*
				}
			};
		}

		&*FOO
	}};
}

// Some testing modules

mod benchs;
mod test_static;


#[cfg(test)]
mod tests {
	#[test]
	fn it_works() {
		let result = 2 + 2;
		assert_eq!(result, 4);
	}
}