Skip to main content

enum_repr/
lib.rs

1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6
7#![warn(clippy::pedantic)]
8#![recursion_limit = "128"]
9
10//! Generate enum repr conversions compatible with type aliases.
11//!
12//! Generate with `#[EnumRepr(type = "TYPE")]`.
13//!
14//! Functions generated are
15//! ```ignore
16//! fn repr(&self) -> EnumReprType
17//! fn from_repr(x: EnumReprType) -> Option<Self>
18//! ```
19//! and the respective `From` and `TryFrom` implementations.
20//! The real enum discriminant is usually forced to be `#[repr(isize)]`.
21//! If `u*` or `i*` types are used for the discriminant, the actual enum
22//! representation is made to be `#[repr(that_type_specified)]`.
23//! The list of types recognized as `u*` and `i*` currently is as follows:
24//! `i8`, `i16`, `i32`, `i64`, `i128`, `u8`, `u16`, `u32`, `u64`, `u128`.
25//! If the type is specified through a type alias, `#[repr(isize)]` is used.
26//! Inability to specify type aliases as enum representations is this crate's
27//! reason to exist.
28//!
29//! The code generated does not require std.
30//!
31//! # Examples
32//! ```
33//! extern crate enum_repr;
34//! extern crate libc;
35//!
36//! use libc::{IPPROTO_IP, IPPROTO_IPV6};
37//!
38//! use enum_repr::EnumRepr;
39//!
40//! #[EnumRepr(type = "::libc::c_int")]
41//! #[derive(Debug, PartialEq)]
42//! pub enum IpProto {
43//!     IP = IPPROTO_IP,
44//!     IPv6 = IPPROTO_IPV6,
45//!     // …
46//! }
47//!
48//! assert_eq!(IpProto::IP.repr(), IPPROTO_IP);
49//! assert_eq!(IpProto::from_repr(IPPROTO_IPV6), Some(IpProto::IPv6));
50//! assert!(IpProto::from_repr(12345).is_none());
51//! ```
52//!
53//! ```
54//! # extern crate enum_repr;
55//! # extern crate libc;
56//! #
57//! # use libc::*;
58//! #
59//! # use enum_repr::EnumRepr;
60//! #
61//! #[EnumRepr(type = "c_int")]
62//! # #[derive(Debug, Eq, Hash, PartialEq)]
63//! pub enum InetDomain {
64//!     Inet = 2,
65//!     // …
66//! }
67//!
68//! #[EnumRepr(type = "c_int")]
69//! # #[derive(Debug, Eq, Hash, PartialEq)]
70//! pub enum SocketType {
71//!     Stream = 1,
72//!     // …
73//! }
74//!
75//! // …
76//!
77//! unsafe {
78//!     assert!(
79//!        socket(InetDomain::Inet.repr(), SocketType::Stream.repr(), 0) != -1
80//!     );
81//! }
82//! ```
83//!
84//! ```no_run
85//! # extern crate enum_repr;
86//! # extern crate libc;
87//! #
88//! # use libc::*;
89//! #
90//! # use enum_repr::EnumRepr;
91//! #
92//! // compatible with documentation and other attributes
93//!
94//! /// Represents a layer 3 network protocol.
95//! #[EnumRepr(type = "c_int")]
96//! #[derive(Debug, PartialEq)]
97//! pub enum IpProto {
98//!     IP = IPPROTO_IP,
99//!     IPv6 = IPPROTO_IPV6,
100//!     // …
101//! }
102//! ```
103//!
104//! Discriminants can be implicit if `implicit = true`:
105//! ```
106//! # extern crate enum_repr;
107//! # extern crate libc;
108//! #
109//! # use libc::*;
110//! #
111//! # use enum_repr::EnumRepr;
112//! #
113//!
114//! #[EnumRepr(type = "c_int", implicit = true)]
115//! #[derive(Debug, PartialEq)]
116//! pub enum Test {
117//!     A,
118//!     B,
119//!     C = 5,
120//!     D,
121//! }
122//!
123//! assert_eq!(Test::B.repr(), 1);
124//! assert_eq!(Test::from_repr(6), Some(Test::D));
125//! assert!(Test::from_repr(2).is_none());
126//! ```
127//!
128//! Using implicit discriminants without setting the flag is an error:
129//! ```compile_fail
130//! # extern crate enum_repr;
131//! # extern crate libc;
132//! #
133//! # use libc::*;
134//! #
135//! # use enum_repr::EnumRepr;
136//! #
137//!
138//! #[EnumRepr(type = "c_int")]
139//! pub enum Test {
140//!     A,
141//!     B = 3
142//! }
143//! ```
144//!
145//! Take extra care to avoid collisions when using implicit discriminants:
146//! ```compile_fail
147//! # #![deny(overflowing_literals)]
148//! # extern crate enum_repr;
149//! #
150//! # use enum_repr::EnumRepr;
151//! #
152//! #[EnumRepr(type = "u8", implicit = true)]
153//! enum Test {
154//!     A = 1,
155//!     B,
156//!     C,
157//!     D = 3,
158//! }
159//! ```
160//!
161//! Out of bound discriminants fail to compile:
162//! ```compile_fail
163//! # #![deny(overflowing_literals)]
164//! # extern crate enum_repr;
165//! #
166//! # use enum_repr::EnumRepr;
167//! #
168//! #[EnumRepr(type = "u8")]
169//! enum Test {
170//!     A = 256
171//! }
172//! ```
173//!
174//! Even if they are implicit:
175//! ```compile_fail
176//! # #![deny(overflowing_literals)]
177//! # extern crate enum_repr;
178//! #
179//! # use enum_repr::EnumRepr;
180//! #
181//! #[EnumRepr(type = "u8", implicit = true)]
182//! enum Test {
183//!     A = 255,
184//!     B
185//! }
186//! ```
187//!
188//! Discriminants of a wrong type fail to compile as well:
189//! ```compile_fail
190//! # #![deny(overflowing_literals)]
191//! # extern crate enum_repr;
192//! #
193//! # use enum_repr::EnumRepr;
194//! #
195//! const C: u16 = 256;
196//!
197//! #[EnumRepr(type = "u8")]
198//! enum Test {
199//!     A = C
200//! }
201//! ```
202//!
203//! Using the actual enum discriminant representation:
204//! ```
205//! # extern crate enum_repr;
206//! #
207//! # use std::mem::size_of;
208//! #
209//! # use enum_repr::EnumRepr;
210//! #
211//! #[EnumRepr(type = "u8")]
212//! #[derive(Debug, PartialEq)]
213//! enum Test {
214//!     A = 1
215//! }
216//!
217//! assert_eq!(size_of::<u8>(), size_of::<Test>());
218//! ```
219
220use proc_macro2::{Span, TokenStream};
221use quote::{ToTokens, quote};
222use syn::{
223    Expr, Fields, Ident, ItemEnum, LitBool, LitStr, Path, Variant, parse_quote, punctuated, token,
224};
225// use syn::*;
226
227/// The code generator
228#[allow(non_snake_case)]
229#[proc_macro_attribute]
230pub fn EnumRepr(
231    args: proc_macro::TokenStream,
232    input: proc_macro::TokenStream,
233) -> proc_macro::TokenStream {
234    EnumRepr_impl(args.into(), input.into()).into()
235}
236
237#[allow(non_snake_case)]
238fn EnumRepr_impl(args: TokenStream, input: TokenStream) -> TokenStream {
239    let input = syn::parse2::<ItemEnum>(input).expect("#[EnumRepr] must only be used on enums");
240    validate(&input.variants);
241
242    let (repr_ty, implicit) = match get_args(args) {
243        Ok(v) => v,
244        Err(e) => panic!("invalid arguments: {e}"),
245    };
246    let compiler_repr_ty = if let Some(repr_ty) = repr_ty.get_ident() {
247        match repr_ty.to_string().as_str() {
248            "i8" | "i16" | "i32" | "i64" | "i128" | "u8" | "u16" | "u32" | "u64" | "u128"
249            | "usize" => Some(repr_ty.clone()),
250
251            _ => None,
252        }
253    } else {
254        None
255    };
256    let compiler_repr_ty = compiler_repr_ty.unwrap_or(Ident::new("isize", Span::call_site()));
257
258    let new_enum = convert_enum(&input, &compiler_repr_ty, implicit);
259    let mut ret: TokenStream = new_enum.into_token_stream();
260
261    let generated = generate_code(&input, &repr_ty);
262    ret.extend(generated);
263    ret
264}
265
266fn generate_code(input: &ItemEnum, repr_ty: &Path) -> TokenStream {
267    let ty = input.ident.clone();
268    let vis = input.vis.clone();
269    let (names, discrs) = extract_variants(input);
270
271    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
272
273    quote! {
274        impl #impl_generics #ty #ty_generics #where_clause {
275            #vis fn repr(&self) -> #repr_ty {
276                match self {
277                    #( #ty::#names => #discrs as #repr_ty ),*
278                }
279            }
280
281            #vis fn from_repr(x: #repr_ty) -> Option<#ty> {
282                match x {
283                    #( x if x == #discrs as #repr_ty => Some(#ty::#names), )*
284                    _ => None
285                }
286            }
287
288            #[doc(hidden)]
289            #[allow(dead_code)]
290            fn _enum_repr_typecheck() {
291                #( let _x: #repr_ty = #discrs; )*
292                unreachable!("don't call me!")
293            }
294        }
295
296        impl From<#ty> for #repr_ty {
297            fn from(value: #ty) -> Self {
298                #ty::repr(&value)
299            }
300        }
301
302        impl TryFrom<#repr_ty> for #ty {
303            type Error = ();
304            fn try_from(value: #repr_ty) -> Result<Self, Self::Error> {
305                Self::from_repr(value).ok_or(())
306            }
307        }
308    }
309}
310
311fn extract_variants(input: &ItemEnum) -> (Vec<Ident>, Vec<Expr>) {
312    let mut prev_expr: Option<Expr> = None;
313    let (names, discrs): (Vec<_>, Vec<_>) = input
314        .variants
315        .iter()
316        .map(|x| {
317            let expr = match x.discriminant.as_ref() {
318                Some(discr) => discr.1.clone(),
319                None => match prev_expr {
320                    Some(ref old_expr) => parse_quote!( 1 + #old_expr ),
321                    None => parse_quote!(0),
322                },
323            };
324            prev_expr = Some(expr.clone());
325            (x.ident.clone(), expr)
326        })
327        .unzip();
328    (names, discrs)
329}
330
331fn get_args(args: TokenStream) -> syn::Result<(Path, bool)> {
332    let mut repr_type: Option<Path> = None;
333    let mut implicit: Option<bool> = None;
334    let parser = syn::meta::parser(|meta| {
335        if meta.path.is_ident("type") {
336            if repr_type.is_some() {
337                return Err(meta.error("duplicate property"));
338            }
339            let str = meta.value()?.parse::<LitStr>()?;
340            repr_type = Some(str.parse::<Path>()?);
341            Ok(())
342        } else if meta.path.is_ident("implicit") {
343            if implicit.is_some() {
344                return Err(meta.error("duplicate property"));
345            }
346            implicit = Some(meta.value()?.parse::<LitBool>()?.value);
347            Ok(())
348        } else {
349            Err(meta.error("unsupported property"))
350        }
351    });
352    syn::parse::Parser::parse2(parser, args)?;
353    match repr_type {
354        Some(repr_ty) => Ok((repr_ty, implicit.unwrap_or(false))),
355        None => panic!("\"type\" parameter is required"),
356    }
357}
358
359fn validate(vars: &punctuated::Punctuated<Variant, token::Comma>) {
360    for i in vars {
361        match i.fields {
362            Fields::Named(_) | Fields::Unnamed(_) => panic!(
363                "the enum's fields must \
364                    be in the \"ident = discriminant\" form"
365            ),
366            Fields::Unit => (),
367        }
368    }
369}
370
371fn convert_enum(input: &ItemEnum, compiler_repr_ty: &Ident, implicit: bool) -> ItemEnum {
372    let mut variants = input.variants.clone();
373
374    let mut prev_expr: Option<Expr> = None;
375    variants.iter_mut().for_each(|ref mut var| {
376        let discr_opt = var.discriminant.clone();
377        let (eq, new_expr): (syn::token::Eq, Expr) = if let Some(discr) = discr_opt {
378            let old_expr = discr.1.into_token_stream();
379            (discr.0, parse_quote!( (#old_expr) as #compiler_repr_ty ))
380        } else {
381            #[allow(clippy::manual_assert)]
382            if !implicit {
383                panic!("use implicit = true to enable implicit discriminants")
384            }
385
386            let expr = if let Some(old_expr) = prev_expr.clone() {
387                parse_quote!( (1 + (#old_expr)) as #compiler_repr_ty )
388            } else {
389                parse_quote!( 0 as #compiler_repr_ty )
390            };
391
392            (
393                syn::token::Eq {
394                    spans: [Span::call_site()],
395                },
396                expr,
397            )
398        };
399        prev_expr = Some(new_expr.clone());
400        var.discriminant = Some((eq, new_expr));
401    });
402
403    let mut attrs = input.attrs.clone();
404    attrs.push(parse_quote!( #[repr(#compiler_repr_ty)] ));
405
406    let ret = input.clone();
407    ItemEnum {
408        variants,
409        attrs,
410        ..ret
411    }
412}
413
414#[cfg(test)]
415mod tests {
416    use quote::quote;
417
418    use super::EnumRepr_impl;
419
420    #[test]
421    #[should_panic(expected = "duplicate property")]
422    fn duplicate_type() {
423        let input_args = quote! { type = "u8", type = "u8" }.into();
424        let input_body = quote! { enum A { A = 1 } }.into();
425        EnumRepr_impl(input_args, input_body);
426    }
427
428    #[test]
429    #[should_panic(expected = "duplicate property")]
430    fn duplicate_implicit() {
431        let input_args = quote! { implicit = false, implicit = false }.into();
432        let input_body = quote! { enum A { A = 1 } }.into();
433        EnumRepr_impl(input_args, input_body);
434    }
435}