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
//! This crate provides an attribute macro to associate struct-type constants with enum variants.
//!
//! ## Syntax
//!
//! Place `#[const_table]` on an enum with at least two variants, where
//!
//! * the first has named fields and defines the type of the associated constants, and
//! * all following have discriminant expressions of that type:
//!
//! ```
//! use const_table::const_table;
//!
//! #[const_table]
//! pub enum Planet {
//!     PlanetInfo {
//!         pub mass: f32,
//!         pub radius: f32,
//!     },
//!
//!     Mercury = PlanetInfo { mass: 3.303e+23, radius: 2.4397e6 },
//!     Venus = PlanetInfo { mass: 4.869e+24, radius: 6.0518e6 },
//!     Earth = PlanetInfo { mass: 5.976e+24, radius: 6.37814e6 },
//!     Mars = PlanetInfo { mass: 6.421e+23, radius: 3.3972e6 },
//!     Jupiter = PlanetInfo { mass: 1.9e+27, radius: 7.1492e7 },
//!     Saturn = PlanetInfo { mass: 5.688e+26, radius: 6.0268e7 },
//!     Uranus = PlanetInfo { mass: 8.686e+25, radius: 2.5559e7 },
//!     Neptune = PlanetInfo { mass: 1.024e+26, radius: 2.4746e7 },
//! }
//! ```
//!
//! This expands to the following:
//!
//! ```
//! #[repr(u32)]
//! #[derive(core::marker::Copy, core::clone::Clone, core::fmt::Debug, core::hash::Hash, core::cmp::PartialEq, core::cmp::Eq)]
//! pub enum Planet {
//!     Mercury,
//!     Venus,
//!     Earth,
//!     Mars,
//!     Jupiter,
//!     Saturn,
//!     Uranus,
//!     Neptune,
//! }
//!
//! pub struct PlanetInfo {
//!     pub mass: f32,
//!     pub radius: f32,
//! }
//!
//! impl Planet {
//!     const COUNT: usize = 8;
//!     pub fn iter() -> impl core::iter::DoubleEndedIterator<Item = Self> {
//!         // transmuting here is fine because... (see try_from)
//!         (0..Self::COUNT).map(|i| unsafe { core::mem::transmute(i as u32) })
//!     }
//! }
//!
//! impl core::ops::Deref for Planet {
//!     type Target = PlanetInfo;
//!     fn deref(&self) -> &Self::Target {
//!         use Planet::*;
//!         const TABLE: [PlanetInfo; 8] = [
//!             PlanetInfo { mass: 3.303e+23, radius: 2.4397e6 },
//!             PlanetInfo { mass: 4.869e+24, radius: 6.0518e6 },
//!             PlanetInfo { mass: 5.976e+24, radius: 6.37814e6 },
//!             PlanetInfo { mass: 6.421e+23, radius: 3.3972e6 },
//!             PlanetInfo { mass: 1.9e+27, radius: 7.1492e7 },
//!             PlanetInfo { mass: 5.688e+26, radius: 6.0268e7 },
//!             PlanetInfo { mass: 8.686e+25, radius: 2.5559e7 },
//!             PlanetInfo { mass: 1.024e+26, radius: 2.4746e7 },
//!         ];
//!
//!         &TABLE[*self as usize]
//!     }
//! }
//!
//! impl core::convert::TryFrom<u32> for Planet {
//!     type Error = u32;
//!     fn try_from(i: u32) -> Result<Self, Self::Error> {
//!         if (i as usize) < Self::COUNT {
//!             // transmuting here is fine because all values in range are valid, since
//!             // discriminants are assigned linearly starting at 0.
//!             Ok(unsafe { core::mem::transmute(i) })
//!         } else {
//!             Err(i)
//!         }
//!     }
//! }
//! ```
//!
//! Note the automatically inserted `repr` and `derive` attributes. You may place a different `repr` attribute as normal,
//! although only `u8`, `u16`, `u32` and `u64` are supported; an implementation of `TryFrom<T>` is provided, where `T` is
//! the chosen `repr` type. You may also `derive` additional traits on the enum.
//!
//! Any attributes placed on the first variant will be placed on the corresponding struct in the expanded code.
//!
//! Also, note that the macro places the discriminant expressions inside a scope that imports all variants of your enum.
//! This makes it convenient to make the values refer to each other, e.g. in a graph-like structure.
//!
//! Because the macro implements `Deref` for your enum, you can access fields of the target type like `Planet::Earth.mass`.
//!
//! Finally, `Planet::iter()` gives a `DoubleEndedIterator` over all variants in declaration order, and `Planet::COUNT` is
//! the total number of variants.

extern crate quote;
extern crate syn;

use proc_macro::TokenStream;
use proc_macro2::Span;

use quote::quote;
use syn::parse::Error;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{parse_macro_input, Expr, Ident, ItemEnum, ItemStruct, Variant};

#[proc_macro_attribute]
pub fn const_table(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let mut errors = proc_macro2::TokenStream::new();

    let input_item = parse_macro_input!(item as syn::Item);
    let input_item = if let syn::Item::Enum(e) = input_item {
        e
    } else {
        let span = input_item.span();
        let message = "the const_table attribute may only be applied to enums";
        return Error::new(span, message).to_compile_error().into();
    };

    if !input_item.generics.params.is_empty() {
        let span = input_item.generics.params.span();
        let message = "a const_table enum cannot be generic";
        errors.extend(Error::new(span, message).to_compile_error());
    }

    let (enum_attrs, repr_type) = {
        let mut attrs = Vec::with_capacity(input_item.attrs.len());
        let mut repr = None;

        for attr in input_item.attrs {
            if attr.path.is_ident("derive") {
                let mut conflict_found = false;
                if let Ok(syn::Meta::List(derive_attr)) = attr.parse_meta() {
                    for arg in &derive_attr.nested {
                        if let syn::NestedMeta::Meta(syn::Meta::Path(p)) = arg {
                            if p.is_ident("Copy") || p.is_ident("Clone") ||
                                p.is_ident("Debug") || p.is_ident("Hash") ||
                                p.is_ident("PartialEq") || p.is_ident("Eq")
                            {
                                let span = p.span();
                                let message = format!("the {} trait is already implemented by the const_table macro", p.get_ident().unwrap());
                                errors.extend(Error::new(span, message).to_compile_error());
                                conflict_found = true;
                            }
                        }
                    }
                }

                if conflict_found {
                    continue;
                }
            }

            if attr.path.is_ident("repr") {
                let ident: Ident = attr.parse_args().unwrap();
                if ident != "u8" && ident != "u16" && ident != "u32" && ident != "u64" {
                    let span = attr.tokens.span();
                    let message = "unsupported repr hint for a const_table enum: expected one of u8, u16, u32 or u64 (default is u32)";
                    errors.extend(Error::new(span, message).to_compile_error());
                    continue;
                }

                repr = Some(ident);
            } else {
                attrs.push(attr);
            }
        }

        (attrs, repr.unwrap_or_else(|| Ident::new("u32", Span::call_site())))
    };

    let mut input_variants = input_item.variants.iter();
    let first_variant = input_variants.next();

    let (variants, value_exprs): (Punctuated<Variant, syn::token::Comma>, Vec<Expr>) = input_variants.map(|variant| {
        if !variant.fields.is_empty() {
            let span = variant.fields.span();
            let message = "in a const_table enum, only the first variant should have fields";
            errors.extend(Error::new(span, message).to_compile_error());
        }

        if let Some((_, expr)) = &variant.discriminant {
            let v = Variant {
                discriminant: None,
                fields: syn::Fields::Unit,
                ..(*variant).clone()
            };

            (v, expr.clone())
        } else {
            let span = variant.span();
            let message = "in a const_table enum, all but the first variant should have a discriminant expression";
            errors.extend(Error::new(span, message).to_compile_error());

            let empty_expr = Expr::Tuple(syn::ExprTuple {
                attrs: Vec::new(), paren_token: syn::token::Paren { span: variant.ident.span() }, elems: Punctuated::new()
            });

            (variant.clone(), empty_expr)
        }
    }).unzip();

    if variants.is_empty() {
        let span = input_item.brace_token.span;
        let message = "a const_table enum needs at least one variant with a discriminant expression";
        errors.extend(Error::new(span, message).to_compile_error());
        return errors.into();
    }

    let struct_decl = if let Some(v) = first_variant {
        use syn::Fields::Named;
        if let Named(fields) = &v.fields {
            ItemStruct {
                attrs: v.attrs.clone(),
                vis: input_item.vis.clone(),
                struct_token: syn::token::Struct {
                    span: Span::call_site(),
                },
                ident: v.ident.clone(),
                generics: Default::default(),
                fields: Named((*fields).clone()),
                semi_token: None,
            }
        } else {
            let span = v.span();
            let message = "the first variant of a const_table enum should have named fields to specify the table layout";
            errors.extend(Error::new(span, message).to_compile_error());
            return errors.into();
        }
    } else {
        let span = input_item.brace_token.span;
        let message = "a const_table enum needs at least one variant with named fields to specify the table layout";
        errors.extend(Error::new(span, message).to_compile_error());
        return errors.into();
    };
    let struct_name = &struct_decl.ident;

    let table_size = variants.len();
    let enum_decl = ItemEnum {
        attrs: enum_attrs,
        variants,
        ..input_item
    };
    let enum_name = &enum_decl.ident;

    let expanded = quote! {
        #errors

        #[repr(#repr_type)]
        #[derive(core::marker::Copy, core::clone::Clone, core::fmt::Debug, core::hash::Hash, core::cmp::PartialEq, core::cmp::Eq)]
        #enum_decl

        #struct_decl

        impl #enum_name {
            pub const COUNT: usize = #table_size;
            pub fn iter() -> impl core::iter::DoubleEndedIterator<Item = Self> {
                // transmuting here is fine because... (see try_from)
                (0..Self::COUNT).map(|i| unsafe { core::mem::transmute(i as #repr_type) })
            }
        }

        impl core::ops::Deref for #enum_name {
            type Target = #struct_name;
            fn deref(&self) -> &Self::Target {
                use #enum_name::*;
                const TABLE: [#struct_name; #table_size] = [ #(#value_exprs),* ];
                &TABLE[*self as usize]
            }
        }

        impl core::convert::TryFrom<#repr_type> for #enum_name {
            type Error = #repr_type;
            fn try_from(i: #repr_type) -> core::result::Result<Self, #repr_type> {
                if (i as usize) < Self::COUNT {
                    // transmuting here is fine because all values in range are valid, since
                    // discriminants are assigned linearly starting at 0.
                    core::result::Result::Ok(unsafe { core::mem::transmute(i) })
                } else {
                    core::result::Result::Err(i)
                }
            }
        }
    };
    expanded.into()
}