spire_enum_macros 1.2.0

Procedural macros distributed by the crate `spire_enum`.
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
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
//! This crate contains procedural macros distributed by the crate [`spire_enum`](https://crates.io/crates/spire_enum).
//!
//! It is not recommended to use this crate directly, instead, use [`spire_enum`](https://crates.io/crates/spire_enum) instead.
//!
//! For more information, read the main crate's [documentation](https://github.com/Houtamelo/spire_enum/blob/main/README.md).
#![forbid(unsafe_code)]

mod delegate_impl;
mod delegated_enum;
mod enum_refs;
mod ident_map;
mod macros;
mod shared;
mod tables;

use convert_case::{Case, Casing};
use ident_map::*;
use itertools::Itertools;
use macros::*;
use parsel::{Parse, ToTokens, ast::*, try_parse_quote};
use proc_macro::TokenStream as TokenStream1;
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use shared::*;
use syn::{
    Attribute as SynAttribute,
    Block,
    Error,
    Expr,
    ExprClosure,
    FnArg,
    GenericParam,
    Lifetime,
    LifetimeParam,
    Meta as SynMeta,
    Pat,
    PatIdent,
    PatType,
    Path,
    Receiver,
    Result,
    Type,
    TypeGroup,
    TypeParam,
    TypeParamBound,
    TypeParen,
    TypePath,
    TypePtr,
    TypeReference,
    TypeTuple,
    Visibility,
    WhereClause,
    WherePredicate,
    custom_keyword,
    parse::ParseStream,
    parse_quote,
    spanned::Spanned,
};

/// See the [crate-level](crate) documentation
#[proc_macro_attribute]
pub fn delegated_enum(settings_stream: TokenStream1, enum_stream: TokenStream1) -> TokenStream1 {
    delegated_enum::run(settings_stream, enum_stream)
        .unwrap_or_else(|err| err.into_compile_error())
        .into()
}

/// See the [crate-level](crate) documentation
#[proc_macro_attribute]
pub fn delegate_impl(_input_stream: TokenStream1, impl_stream: TokenStream1) -> TokenStream1 {
    delegate_impl::run(impl_stream)
        .unwrap_or_else(|err| err.into_compile_error())
        .into()
}

/// Given an enum, generates a struct that contains one of each of the enum's variant types,
/// and several implementations for the generated type as well.
///
/// The variant's types are used as keys to access their respective values.
///
/// The type generated by this macro does not allocate any heap memory, thus it is `no_std` compatible.
///
/// ## Example
///
/// ```rust ignore
/// use spire_enum_macros::variant_type_table;
///
/// #[variant_type_table]
/// pub enum Setting {
///     WindowSize(WindowSize),
///     TextSpeed(Percentage),
///     ProfileName(String),
/// }
/// ```
///
/// Generates:
///
/// ```rust ignore
/// pub struct SettingVariantTypeTable {
///     pub window_size: WindowSize,
///     pub text_speed: Percentage,
///     pub profile_name: String,
/// }
/// ```
///
/// ## Generated Impls
///
/// The code of all generated impls includes documentation, this is merely a summary.
///
/// ```rust ignore
/// // Constructor
/// // - Fields: snake-case variant names
/// // - Vars: variant types
/// pub const fn new( #(#Fields: #Vars),* ) -> Self;
///
/// // Get a reference/mut-reference to a given variant based on the generic type.
/// // - Var: any of the enum's variant types
/// pub fn get<Var>(&self) -> &Var;
/// pub fn get_mut<Var>(&mut self) -> &mut Var;
///
/// // Set the value of a given variant.
/// pub fn set::<Var>(&mut self, value: Var);
/// pub fn set_enum(&mut self, value: Enum);
///
/// // Iter by reference/mut-reference
/// // - EnumRef/Mut: an enum where all variants have the same name as the input enum,
/// // but contain a reference to the variant's type instead of owning it.
/// pub fn iter<'a>(&'a self) -> impl Iterator<Item = EnumRef<'a>>;
/// pub fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = EnumMut<'a>>;
///
/// // IntoIter impl
/// fn into_iter(self) -> impl Iterator<Item = Enum>;
/// ```
///
/// ## Example - Using generated impls
/// ```rust ignore
/// let table = SettingVariantTypeTable {
///     window_size: WindowSize(1920, 1080),
///     text_speed: Percentage(20.0),
///     profile_name: String::from("default_player"),
/// };
///
/// // You can get references to the values using `get<T>` and `get_mut<T>`
/// let window_size: &WindowSize = table.get::<WindowSize>();
///
/// for setting in table.iter() {
///     match setting {
///         SettingRef::WindowSize(size) => assert_eq!(size, &WindowSize(1920, 1080)),
///         SettingRef::TextSpeed(speed) => assert_eq!(speed, &Percentage(20.0)),
///         SettingRef::ProfileName(name) => assert_eq!(name, &"default_player"),
///     }
/// }
/// ```
///
/// ## Settings
/// Here are the ways you may customize the output code, settings should be comma-separated.
///
/// ```rust ignore
/// #[variant_generic_table(
///     // By default, the table type name is `[EnumName]VariantTypeTable`,
///     // this allows you to customize the type name.
///     ty_name = MyCustomName,
///     // By default, generated code is included in a module named `[enum_name_snake_case]_variant_type_table`,
///     // this allows you to customize the module name.
///     mod_name = my_custom_module,
///     // Add attributes to the generated table type.
///     // - The attribute list should be comma-separated.
///     // - There is no need to surround the attributes with `#[  ]`.
///     attrs(
///         derive(Clone, Debug), // will make the table derive Clone and Debug.
///         some_other_attribute,
///     ),
///     // Shorthand for attrs(derive(Clone, Debug))
///     derive(Clone, Debug),
/// )]
/// ```
///
/// ## Limitations
/// - Each variant should have exactly a single field (named or unnamed).
/// - Each variant's type must be unique (no two variants can share the same type).
///
/// ## Limitations - Generics
/// Any number of generics is allowed, as well as their bounds/where clauses.
///
/// Variants with uncovered generic types aren't allowed, example:
/// ```rust ignore
/// // won't compile
/// enum Foo<T> {
///     Bar(T), // T is uncovered
///     Baz(String),
/// }
///
/// // ok
/// enum Foo<T> {
///     Bar(Box<T>), // T is covered in Box<T>
///     Baz(String),
/// }
///
/// // won't compile, `Bar` and `Baz` could have the same type if `T` == `E`
/// enum Foo<T, E> {
///     Bar(Box<T>),
///     Baz(Box<E>),
/// }
///
/// // ok
/// enum Foo<T, E> {
///     Bar(Box<T>),
///     Baz(Rc<E>),
/// }
/// ```
///
/// This limitation comes from how `Table::get::<Var>()` is implemented,
/// uncovered generics result in implementations that conflict with all types,
/// since T can be anything.
///
/// If you need a similar table but storing a generic value instead of each variant's type, check [`macro@variant_generic_table`].
#[proc_macro_attribute]
pub fn variant_type_table(input_stream: TokenStream1, enum_stream: TokenStream1) -> TokenStream1 {
    tables::variant_type_to_variant_type::run(input_stream, enum_stream)
        .unwrap_or_else(|err| err.into_compile_error())
        .into()
}

/// Similar to [`macro@variant_type_table`], except the values associated with each variant
/// are a generic parameter, instead of each variant's type.
///
/// Given an enum, generates a struct that contains a generic value
/// mapped to one of each of the enum's variant types,
/// and several implementations for the generated type as well.
///
/// The variant's types are used as keys to access their associated values.
///
/// The type generated by this macro does not allocate any heap memory, thus it is `no_std` compatible.
///
/// ## Example
///
/// ```rust ignore
/// use spire_enum_macros::variant_generic_table;
///
/// #[variant_generic_table]
/// pub enum Setting {
///     WindowSize(WindowSize),
///     TextSpeed(Percentage),
///     ProfileName(String),
/// }
/// ```
///
/// Generates:
///
/// ```rust ignore
/// pub struct SettingVariantGenericTable<T> {
///     pub window_size: T,
///     pub text_speed: T,
///     pub profile_name: T,
/// }
/// ```
///
/// ## Generated Impls
///
/// The code emitted with all generated impls includes documentation, this is merely a summary.
///
/// ```rust ignore
/// // Constructors
/// // - Fields: snake-case variant names
/// pub const fn new( #(#Fields: T),* ) -> Self;
/// pub fn filled_with(T) -> Self where T: Clone;
///
/// // Get a reference/mut-reference to the value associated with a given variant based on the generic type.
/// // - Var: any of the enum's variant types
/// pub fn get<Var>(&self) -> &T;
/// pub fn get_mut<Var>(&mut self) -> &mut T;
///
/// // Set the value associated with a given variant's type.
/// pub fn set::<Var>(&mut self, value: T);
///
/// // Iter by reference/mut-reference
/// // - EnumRef/Mut: an enum where all variants have the same name as the input enum,
/// // but contain a reference to a value `T`.
/// pub fn iter<'a>(&'a self) -> impl Iterator<Item = EnumRef<'a, T>>;
/// pub fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = EnumMut<'a, T>>;
///
/// // IntoIter impl
/// fn into_iter(self) -> impl Iterator<Item = T>;
/// ```
///
/// ## Example - Using generated impls
/// ```rust ignore
/// let table = SettingVariantGenericTable::new(
///     "window_size",
///     "text_speed",
///     "profile_name",
/// );
///
/// // You can get references to the values using `get<T>` and `get_mut<T>`
/// let window_size_name: &str = table.get::<WindowSize>();
///
/// for setting in table.iter() {
///     match setting {
///         SettingRef::WindowSize(name) => assert_eq!(name, "window_size"),
///         SettingRef::TextSpeed(name) => assert_eq!(name, "text_speed"),
///         SettingRef::ProfileName(name) => assert_eq!(name,"profile_name"),
///     }
/// }
/// ```
///
/// ## Settings
/// Here are the ways you may customize the output code, settings should be comma-separated.
///
/// ```rust ignore
/// #[variant_generic_table(
///     // By default, the table type name is `[EnumName]VariantGenericTable`,
///     // this allows you to customize the type name.
///     ty_name = MyCustomName,
///     // By default, generated code is included in a module named `[enum_name_snake_case]_variant_generic_table`,
///     // this allows you to customize the module name.
///     mod_name = my_custom_module,
///     // Add attributes to the generated table type.
///     // - The attribute list should be comma-separated.
///     // - There is no need to surround the attributes with `#[  ]`.
///     attrs(
///         derive(Clone, Debug), // will make the table derive Clone and Debug.
///         some_other_attribute,
///     ),
///     // Shorthand for attrs(derive(Clone, Debug))
///     derive(Clone, Debug),
/// )]
/// ```
///
/// ## Limitations
/// - Each variant should have exactly a single field (named or unnamed).
/// - Each variant's type must be unique (no two variants can share the same type).
///
/// ## Limitations - Generics
/// Any number of generics is allowed, as well as their bounds/where clauses.
///
/// Variants with uncovered generic types aren't allowed, example:
/// ```rust ignore
/// // won't compile
/// enum Foo<T> {
///     Bar(T), // T is uncovered
///     Baz(String),
/// }
///
/// // ok
/// enum Foo<T> {
///     Bar(Box<T>), // T is covered in Box<T>
///     Baz(String),
/// }
///
/// // won't compile, `Bar` and `Baz` could have the same type if `T` == `E`
/// enum Foo<T, E> {
///     Bar(Box<T>),
///     Baz(Box<E>),
/// }
///
/// // ok
/// enum Foo<T, E> {
///     Bar(Box<T>),
///     Baz(Rc<E>),
/// }
/// ```
///
/// This limitation comes from how `Table::get::<Var>()` is implemented,
/// uncovered generics result in implementations that conflict with all types,
/// since T can be anything.
///
/// If you need a similar table but with unit variants, check [`macro@discriminant_generic_table`].
/// If you need a similar table but storing each variant's type, check [`macro@variant_type_table`].
#[proc_macro_attribute]
pub fn variant_generic_table(
    input_stream: TokenStream1,
    enum_stream: TokenStream1,
) -> TokenStream1 {
    tables::variant_type_to_generic::run(input_stream, enum_stream)
        .unwrap_or_else(|err| err.into_compile_error())
        .into()
}

/// Similar to [`macro@variant_generic_table`], except this is meant for enums with unit variants.
///
/// Given an enum, generates a struct that contains a generic value
/// mapped to one of each of the enum's variants,
/// and several implementations for the generated type as well.
///
/// The variants are used as keys to access their associated values.
///
/// The type generated by this macro does not allocate any heap memory, thus it is `no_std` compatible.
///
/// ## Example
///
/// ```rust ignore
/// use spire_enum_macros::discriminant_generic_table;
///
/// #[discriminant_generic_table]
/// pub enum VolumeSetting {
///     Main,
///     Music,
///     Sfx,
/// }
/// ```
///
/// Generates:
///
/// ```rust ignore
/// pub struct VolumeSettingDiscriminantTable<T> {
///     pub main: T,
///     pub music: T,
///     pub sfx: T,
/// }
/// ```
///
/// ## Generated Impls
///
/// The code emitted with all generated impls includes documentation, this is merely a summary.
///
/// ```rust ignore
/// // Constructors
/// // - Fields: snake-case variant names
/// pub const fn new( #(#Fields: T),* ) -> Self;
/// pub fn filled_with(T) -> Self where T: Clone;
/// pub fn from_fn(impl FnMut(Enum) -> T) -> Self;
///
/// // Get a reference/mut-reference to the value associated with a given variant.
/// // These methods can also be invoked by using indexing (e.g. `&table[VolumeSetting::Main]`)
/// pub const fn get(&self, Enum) -> &T;
/// pub const fn get_mut(&mut self, Enum) -> &mut T;
///
/// // Set the value associated with a given variant.
/// pub fn set(&mut self, var: Enum, value: T);
///
/// // Iter by reference/mut-reference
/// pub fn iter(&lf self) -> impl Iterator<Item = (Enum, &T)>;
/// pub fn iter_mut(&mut self) -> impl Iterator<Item = (Enum, &mut T)>;
///
/// // IntoIter impl
/// fn into_iter(self) -> impl Iterator<Item = (Enum, T)>;
/// ```
///
/// ## Example - Using generated impls
/// ```rust ignore
/// let table = VolumeSettingDiscriminantTable::new(
///     "main",
///     "music",
///     "sfx",
/// );
///
/// assert_eq!(table[VolumeSetting::Sfx], "sfx");
///
/// for (setting, name) in table.iter() {
///     match setting {
///         VolumeSetting::Main => assert_eq!(name, "main"),
///         VolumeSetting::Music => assert_eq!(name, "music"),
///         VolumeSetting::Sfx => assert_eq!(name, "sfx"),
///     }
/// }
/// ```
///
/// ## Settings
/// Here are the ways you may customize the output code, settings should be comma-separated.
///
/// ```rust ignore
/// #[variant_generic_table(
///     // By default, the table type name is `[EnumName]DiscriminantTable`,
///     // this allows you to customize the type name.
///     ty_name = MyCustomName,
///     // By default, generated code is included in a module named `[enum_name_snake_case]_discriminant_table`,
///     // this allows you to customize the module name.
///     mod_name = my_custom_module,
///     // Add attributes to the generated table type.
///     // - The attribute list should be comma-separated.
///     // - There is no need to surround the attributes with `#[  ]`.
///     attrs(
///         derive(Clone, Debug), // will make the table derive Clone and Debug.
///         some_other_attribute,
///     ),
///     // Shorthand for attrs(derive(Clone, Debug))
///     derive(Clone, Debug),
/// )]
/// ```
///
/// ## Limitations
/// All variants should be unit variants (they cannot have any fields).
///
/// If you need a similar table but with non-unit variants, check [`macro@variant_generic_table`] or [`macro@variant_type_table`].
#[proc_macro_attribute]
pub fn discriminant_generic_table(
    input_stream: TokenStream1,
    enum_stream: TokenStream1,
) -> TokenStream1 {
    tables::discriminant_to_generic::run(input_stream, enum_stream)
        .unwrap_or_else(|err| err.into_compile_error())
        .into()
}

fn delegate_macro_ident(enum_ident: &Ident) -> Ident {
    use convert_case::{Case, Casing};
    let mut ident = enum_ident.to_string();
    ident = ident.to_case(Case::Snake);
    ident.insert_str(0, "delegate_");
    Ident::new(&ident, Span::call_site())
}