table_enum_macro/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use proc_macro::TokenStream;
4use proc_macro_error::proc_macro_error;
5use table_enum_core::table_enum_core;
6
7#[proc_macro_error]
8#[proc_macro]
9/// Creates a table-like enum.
10///
11/// # Example:
12///
13/// ```ignore
14/// use table_enum::table_enum;
15///
16/// table_enum! {
17///     enum BinaryOp(text: &'static str, precedence: i32, right_assoc: bool) {
18///         Add("+", 10, false),
19///         Sub("-", 10, false),
20///         Mul("*", 20, false),
21///         Div("/", 20, false),
22///         Pow("**", 30, true),
23///         ...
24///     }
25/// }
26///
27/// fn example() {
28///   println!("{}", BinaryOp.Add.text());
29/// }
30/// ```
31///
32/// There are three convenience attributes that can be added for each field:
33///
34/// ```ignore
35/// use table_enum::table_enum;
36///
37/// table_enum! {
38///     enum BinaryOp(#[constructor] text: &'static str, #[option] precedence: i32, #[default] right_assoc: bool) {
39///         Add("+", _, _),
40///         Sub("-", _, _),
41///         Mul("*", 20, _),
42///         Div("/", 20, _),
43///         Pow("**", 30, true),
44///         ...
45///     }
46/// }
47/// ```
48///
49/// The `#[option]` convenience attribute lets you write the values directly but wraps them implicitly into `Some(value)`.
50/// If instead of a value you write `_`, it becomes `None`.
51/// The return type when you invoke that field's getter is also changed to `Option<FieldType>`.
52///
53/// The #[default] field works the same way but instead of an `Option` type, `_` maps to `Default::default()`.
54/// Because `Default::default()` is not `const fn`, neither is the generated function.
55///
56/// The #[constructor] attribute allows generation of the constructor (called `new`) that takes a value of the field's type
57/// and returns Option<EnumType>
58/// No more than one field can have this attribute. All values of this field must be different.
59pub fn table_enum(input: TokenStream) -> TokenStream {
60    table_enum_core(input.into()).into()
61}