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
//! # rust-primitive_enum
//! Little utility for dealing with C-style enums
//!
//! This crate exports just the single macro `primitive_enum!`
//! that defines an enum backed by a user specified primitive
//! integer type.
//!
//! The intent is to emulate traditional C-style enums while
//! adding some handy associated functions useful in such
//! contexts (e.g. enumerating over each enum and converting
//! between the underlying types).
//!
//! # Example
//!
//! ```rust
//! #[macro_use] extern crate primitive_enum;
//!
//! primitive_enum! { MyEnum u16 ;
//!     A,
//!     B,
//!     C,
//!     D = 500,
//!     E,       // as you would expect, E maps to 501
//! }
//!
//! fn main() {
//!     use MyEnum::*;
//!
//!     // Get a slice of all enum elements:
//!     assert_eq!(
//!         MyEnum::list(),
//!         &[A, B, C, D, E],
//!     );
//!
//!     // Get the enum value given its integer value:
//!     assert_eq!(MyEnum::from(0), Some(A));
//!     assert_eq!(MyEnum::from(1000), None);
//!
//!     // User specified enum values behave as you would expect
//!     assert_eq!(D as u16, 500);
//!     assert_eq!(MyEnum::from(501), Some(E));
//!
//!     // You can also get an enum by its name
//!     assert_eq!(MyEnum::from_name("E"), Some(E));
//! }
//! ```
//!
//! # Expansion
//!
//! As of the current version, the macro
//!
//! ```rust
//! #[macro_use] extern crate primitive_enum;
//!
//! primitive_enum! { MyEnum u16 ;
//!     A,
//!     B,
//!     C,
//!     D = 500,
//!     E,
//! }
//!
//! ```
//!
//! is effectively equivalent to
//!
//! ```rust
//! #[repr(u16)]
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
//! pub enum MyEnum {
//!     A = 0,
//!     B = 1,
//!     C = 2,
//!     D = 500,
//!     E = 501,
//! }
//!
//! impl MyEnum {
//!     pub fn from(x: u16) -> Option<MyEnum> {
//!         // ...
//!         None
//!     }
//!
//!     pub fn from_name(name: &str) -> Option<MyEnum> {
//!         // ...
//!         None
//!     }
//!
//!     pub fn list() -> &'static [MyEnum] {
//!         &[
//!             MyEnum::A,
//!             MyEnum::B,
//!             MyEnum::C,
//!             MyEnum::D,
//!             MyEnum::E,
//!         ]
//!     }
//! }
//! ```
//!
//! # Doc comments
//!
//! Starting from version 1.1.0, doc comments are supported.
//!
//! ```rust
//! #[macro_use] extern crate primitive_enum;
//!
//! primitive_enum! {
//! /// Some comments about 'MyEnum'
//! MyEnum u16 ;
//!     A,
//!     B,
//!
//!     /// Some special comments about variant C
//!     C,
//!     D = 500,
//!     E,
//! }
//! ```
//!
//! Starting from version 1.1.0 this crate is implemented as a procedural macro
//! to improve space efficiency of the generated code.
//! Prior to version 1.1.0, this crate was implemented as a simple declarative macro.
//!
//! # Default trait
//!
//! Originally, enums did not automatically get the `Default` trait. But starting from version `1.2.0`
//! the enum will automatically derive `Default` if you specify `#[default]`.
//!
//! So for example, given
//!
//! ```rust
//! #[macro_use] extern crate primitive_enum;
//!
//! primitive_enum! {
//! EnumWithDefault u16 ;
//!     A,
//!     B,
//!     #[default]
//!     C,
//!     D,
//! }
//!
//! fn main() {
//!     assert_eq!(EnumWithDefault::default(), EnumWithDefault::C);
//! }
//! ```
//!
//! the resulting code is effectively eqivalent to
//!
//! ```rust
//! #[repr(u16)]
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
//! pub enum EnumWithDefault {
//!     A = 0,
//!     B = 1,
//!     #[default]
//!     C = 2,
//!     D = 3,
//! }
//!
//! impl EnumWithDefault {
//!     // ... (same as with the other example above)
//! }
//!
//! fn main() {
//!     assert_eq!(EnumWithDefault::default(), EnumWithDefault::C);
//! }
//! ```
//!
//! This crate is a clean macro implementation that
//! expands to code shown above and doesn't rely on any
//! outside dependencies or magic.

extern crate proc_macro;
use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Span, TokenStream, TokenTree};
use std::iter::FromIterator;

macro_rules! error {
    ($message:expr $(,)?) => {
        return format!("compile_error!({:?})", $message).parse().unwrap()
    };
}

fn at_punc(peek: &Option<TokenTree>, punc_char: char) -> bool {
    match peek {
        Some(TokenTree::Punct(p)) => p == &punc_char,
        _ => false,
    }
}

fn ident_token(name: &str) -> TokenTree {
    TokenTree::Ident(Ident::new(name, Span::call_site()))
}

fn punct_token(ch: char) -> TokenTree {
    TokenTree::Punct(Punct::new(ch, proc_macro::Spacing::Alone))
}

fn punct_cont_token(ch: char) -> TokenTree {
    TokenTree::Punct(Punct::new(ch, proc_macro::Spacing::Joint))
}

fn punc2_tokens(ch1: char, ch2: char) -> Vec<TokenTree> {
    vec![
        TokenTree::Punct(Punct::new(ch1, proc_macro::Spacing::Joint)),
        TokenTree::Punct(Punct::new(ch2, proc_macro::Spacing::Alone)),
    ]
}

fn int_token(value: i32) -> TokenTree {
    TokenTree::Literal(Literal::i32_unsuffixed(value))
}

fn group_token(delimiter: Delimiter, tokens: Vec<TokenTree>) -> TokenTree {
    TokenTree::Group(Group::new(delimiter, TokenStream::from_iter(tokens)))
}

fn paren_token(tokens: Vec<TokenTree>) -> TokenTree {
    group_token(Delimiter::Parenthesis, tokens)
}

fn bracket_token(tokens: Vec<TokenTree>) -> TokenTree {
    group_token(Delimiter::Bracket, tokens)
}

fn brace_token(tokens: Vec<TokenTree>) -> TokenTree {
    group_token(Delimiter::Brace, tokens)
}

fn concat<T>(mut v1: Vec<T>, mut v2: Vec<T>) -> Vec<T> {
    v1.append(&mut v2);
    v1
}

fn check_for_default(triples: &mut Vec<(TokenStream, Ident, TokenTree)>) -> Result<bool, String> {
    let mut found_default = false;
    for (attributes, _variant_name, _variant_value) in triples.into_iter() {
        if attributes.to_string().contains("default") {
            if found_default {
                // TODO: Currently, rustc panics when user specifies more than one default.
                // Ideally, we should just pass what we get from the user and let the compiler handle the
                // error. But it looks like there might already be a pr out to address this issue.
                // Remove this error handling logic when the fix pr is merged and released.
                // See https://github.com/rust-lang/rust/issues/118119
                // and https://github.com/rust-lang/rust/pull/118131
                return Err(format!("Multiple variants marked as default"));
            }
            found_default = true;
        }
    }
    Ok(found_default)
}

#[proc_macro]
pub fn primitive_enum(tokens: TokenStream) -> TokenStream {
    let mut iter = tokens.into_iter();
    let mut peek = iter.next();

    ////////////////////////////////////////////////////////////////////
    // Part 1: Parse Contents
    ////////////////////////////////////////////////////////////////////

    let enum_attributes = {
        let mut tokens = Vec::<TokenTree>::new();
        while at_punc(&peek, '#') {
            tokens.push(peek.unwrap());
            peek = iter.next();
            if peek.is_none() {
                error!("Dangling '#'");
            }
            tokens.push(peek.unwrap());
            peek = iter.next();
        }
        tokens
    };

    let enum_identifier = match peek {
        Some(TokenTree::Ident(ident)) => {
            peek = iter.next();
            ident
        }
        Some(token) => error!(format!("Expected enum name but got {:?}", token)),
        None => error!("Expected enum name but got end of macro"),
    };

    let repr_type = {
        let mut tokens = Vec::<TokenTree>::new();
        while peek.is_some() && !at_punc(&peek, ';') {
            tokens.push(peek.unwrap());
            peek = iter.next();
        }
        tokens
    };

    match peek {
        Some(TokenTree::Punct(p)) if p == ';' => {
            peek = iter.next();
        }
        Some(token) => error!(format!("Expected ';' but got {:?}", token)),
        None => error!("Expected ';' but got end of macro"),
    }

    let (triples, has_default) = {
        // Each triple contains information about a variant of the enum.
        // (Attributes, Identifier, Value-Expression)
        let mut triples = Vec::<(TokenStream, Ident, TokenTree)>::new();
        let mut base_value: Option<Vec<TokenTree>> = None;
        let mut offset = 0;
        while peek.is_some() {
            let variant_attributes = {
                let mut tokens = Vec::<TokenTree>::new();
                while at_punc(&peek, '#') {
                    tokens.push(peek.unwrap());
                    peek = iter.next();
                    if peek.is_none() {
                        error!("Dangling '#'");
                    }
                    tokens.push(peek.unwrap());
                    peek = iter.next();
                }
                TokenStream::from_iter(tokens)
            };
            let variant_name = match peek {
                Some(TokenTree::Ident(ident)) => {
                    peek = iter.next();
                    ident
                }
                Some(token) => error!(format!("Expected variant identifier but got {:?}", token)),
                None => error!("Expected variant identifier but got end of macro"),
            };
            if at_punc(&peek, '=') {
                // Explicit assignment
                peek = iter.next(); // consume '='
                let mut expr_tokens = Vec::<TokenTree>::new();
                while peek.is_some() && !at_punc(&peek, ',') {
                    expr_tokens.push(peek.unwrap());
                    peek = iter.next();
                }
                base_value = Some(expr_tokens);
                offset = 0;
            }
            let value = match &base_value {
                Some(base_value_tokens) => {
                    let base_value_rep = if base_value_tokens.len() == 1 {
                        base_value_tokens[0].clone()
                    } else {
                        TokenTree::Group(Group::new(
                            proc_macro::Delimiter::Parenthesis,
                            TokenStream::from_iter(base_value_tokens.clone()),
                        ))
                    };

                    if offset == 0 {
                        base_value_rep
                    } else {
                        paren_token(vec![base_value_rep, punct_token('+'), int_token(offset)])
                    }
                }
                None => int_token(offset),
            };
            if at_punc(&peek, ',') {
                peek = iter.next();
            } else if let Some(token) = peek {
                error!(format!("Expected ',' but got {:?}", token));
            }
            offset += 1;
            triples.push((variant_attributes, variant_name, value));
        }
        // make sure there's a default, even if the user didn't specify one
        let has_default = match check_for_default(&mut triples) {
            Err(message) => error!(message),
            Ok(has_default) => has_default,
        };
        (triples, has_default)
    };

    ////////////////////////////////////////////////////////////////////
    // Part 2: Code Generation
    ////////////////////////////////////////////////////////////////////

    // Make sure doc comments get passed to the enum itself
    let mut out = enum_attributes;

    // Basically:
    //   #[repr(`repr_type`)]
    // This would be a lot more elegant with `quote`, but it seems to still
    // be considered an unstable API as of April 2023
    // https://github.com/rust-lang/rust/issues/54722
    out.push(punct_token('#'));
    out.push(bracket_token(vec![
        ident_token("repr"),
        paren_token(repr_type.clone()),
    ]));
    // #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    out.push(punct_token('#'));
    out.push(bracket_token(vec![
        ident_token("derive"),
        paren_token({
            let mut derive_list: Vec<TokenTree> = vec![
                ident_token("Debug"),
                punct_token(','),
                ident_token("Clone"),
                punct_token(','),
                ident_token("Copy"),
                punct_token(','),
                ident_token("PartialEq"),
                punct_token(','),
                ident_token("Eq"),
                punct_token(','),
                ident_token("Hash"),
            ];
            if has_default {
                derive_list.push(punct_token(','));
                derive_list.push(ident_token("Default"));
            }
            derive_list
        }),
    ]));

    out.push(ident_token("pub"));
    out.push(ident_token("enum"));
    out.push(TokenTree::Ident(enum_identifier.clone()));
    out.push(brace_token({
        let mut tokens = Vec::<TokenTree>::new();
        for triple in &triples {
            tokens.extend(triple.0.clone());
            tokens.push(TokenTree::Ident(triple.1.clone()));
            tokens.push(punct_token('='));
            tokens.push(triple.2.clone());
            tokens.push(punct_token(','));
        }
        tokens.extend("\n".parse::<TokenStream>().unwrap());
        tokens
    }));

    out.push(ident_token("impl"));
    out.push(TokenTree::Ident(enum_identifier.clone()));
    out.push(brace_token({
        let mut tokens = Vec::new();

        // pub fn from(x: u16) -> Option<MyEnum>
        tokens.extend(vec![
            ident_token("pub"),
            ident_token("fn"),
            ident_token("from"),
        ]);
        tokens.push(paren_token(concat(
            vec![ident_token("x"), punct_token(':')],
            repr_type.clone(),
        )));
        tokens.extend(punc2_tokens('-', '>'));
        tokens.push(ident_token("Option"));
        tokens.push(punct_token('<'));
        tokens.push(TokenTree::Ident(enum_identifier.clone()));
        tokens.push(punct_token('>'));
        tokens.push(brace_token({
            // NOTE: You might be wondering why we use a chain of if statements instead
            // of a match statement.
            // The problem is that if a user provides an expression for one of the
            // values, it may not always be possible to infer the exact literal value
            // during macro expansion (e.g. what if a const variable is used?).
            // And when we have to use user provided expressions for some of the values,
            // it's tricky to find a match pattern that will allow us to match against it.
            // And besides, the Rust compiler is probably smart enough to optimize
            // a chain of if statements that tests a variable against a bunch of constants
            // as much as a simple match.
            let mut tokens = Vec::new();
            for (_, variant_name, variant_value) in &triples {
                tokens.push(ident_token("if"));
                tokens.push(ident_token("x"));
                tokens.extend(punc2_tokens('=', '='));
                tokens.push(variant_value.clone());
                tokens.push(brace_token(vec![
                    ident_token("return"),
                    ident_token("Some"),
                    paren_token(vec![
                        TokenTree::Ident(enum_identifier.clone()),
                        punct_cont_token(':'),
                        punct_token(':'),
                        TokenTree::Ident(variant_name.clone()),
                    ]),
                ]));
            }
            tokens.push(ident_token("None"));
            tokens
        }));

        // pub fn from_name(name: &str) -> Option<MyEnum>
        tokens.extend(vec![
            ident_token("pub"),
            ident_token("fn"),
            ident_token("from_name"),
        ]);
        tokens.push(paren_token(vec![
            ident_token("name"),
            punct_token(':'),
            punct_token('&'),
            ident_token("str"),
        ]));
        tokens.extend(punc2_tokens('-', '>'));
        tokens.push(ident_token("Option"));
        tokens.push(punct_token('<'));
        tokens.push(TokenTree::Ident(enum_identifier.clone()));
        tokens.push(punct_token('>'));
        tokens.push(brace_token({
            let mut tokens = Vec::new();
            for (_, variant_name, _) in &triples {
                tokens.push(ident_token("if"));
                tokens.push(ident_token("name"));
                tokens.extend(punc2_tokens('=', '='));
                tokens.push(TokenTree::Literal(Literal::string(
                    &variant_name.to_string(),
                )));
                tokens.push(brace_token(vec![
                    ident_token("return"),
                    ident_token("Some"),
                    paren_token(vec![
                        TokenTree::Ident(enum_identifier.clone()),
                        punct_cont_token(':'),
                        punct_token(':'),
                        TokenTree::Ident(variant_name.clone()),
                    ]),
                ]));
            }
            tokens.push(ident_token("None"));
            tokens
        }));

        // pub fn list() -> &'static [MyEnum]
        tokens.extend(vec![
            ident_token("pub"),
            ident_token("fn"),
            ident_token("list"),
        ]);
        tokens.push(paren_token(vec![]));
        tokens.extend(punc2_tokens('-', '>'));
        tokens.push(punct_token('&'));
        tokens.push(punct_cont_token('\''));
        tokens.push(ident_token("static"));
        tokens.push(bracket_token(vec![TokenTree::Ident(
            enum_identifier.clone(),
        )]));
        tokens.push(brace_token(vec![
            punct_token('&'),
            bracket_token({
                let mut tokens = Vec::new();
                for (_, variant_name, _) in &triples {
                    tokens.push(TokenTree::Ident(enum_identifier.clone()));
                    tokens.push(punct_cont_token(':'));
                    tokens.push(punct_token(':'));
                    tokens.push(TokenTree::Ident(variant_name.clone()));
                    tokens.push(punct_token(','));
                }
                tokens
            }),
        ]));

        tokens
    }));

    return TokenStream::from_iter(out.into_iter());
}