1 | use proc_macro2::TokenStream; |
2 | use quote::quote; |
3 | use syn::{Data, DeriveInput, Fields}; |
4 | |
5 | use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties}; |
6 | |
7 | pub fn display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { |
8 | let name = &ast.ident; |
9 | let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); |
10 | let variants = match &ast.data { |
11 | Data::Enum(v) => &v.variants, |
12 | _ => return Err(non_enum_error()), |
13 | }; |
14 | |
15 | let type_properties = ast.get_type_properties()?; |
16 | |
17 | let mut arms = Vec::new(); |
18 | for variant in variants { |
19 | let ident = &variant.ident; |
20 | let variant_properties = variant.get_variant_properties()?; |
21 | |
22 | if variant_properties.disabled.is_some() { |
23 | continue; |
24 | } |
25 | |
26 | // Look at all the serialize attributes. |
27 | let output = variant_properties.get_preferred_name(type_properties.case_style); |
28 | |
29 | let params = match variant.fields { |
30 | Fields::Unit => quote! {}, |
31 | Fields::Unnamed(..) => quote! { (..) }, |
32 | Fields::Named(..) => quote! { {..} }, |
33 | }; |
34 | |
35 | arms.push(quote! { #name::#ident #params => f.pad(#output) }); |
36 | } |
37 | |
38 | if arms.len() < variants.len() { |
39 | arms.push(quote! { _ => panic!("fmt() called on disabled variant." ) }); |
40 | } |
41 | |
42 | Ok(quote! { |
43 | impl #impl_generics ::core::fmt::Display for #name #ty_generics #where_clause { |
44 | fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> { |
45 | match *self { |
46 | #(#arms),* |
47 | } |
48 | } |
49 | } |
50 | }) |
51 | } |
52 | |