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