strum_macros/macros/strings/
display.rs

1use proc_macro2::TokenStream;
2use quote::quote;
3use syn::{Data, DeriveInput, Fields};
4
5use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};
6
7pub 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        if variant_properties.to_string.is_none() && variant_properties.default.is_some() {
36            match &variant.fields {
37                Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
38                    arms.push(quote! { #name::#ident(ref s) => f.pad(s) });
39                }
40                _ => {
41                    return Err(syn::Error::new_spanned(
42                        variant,
43                        "Default only works on newtype structs with a single String field",
44                    ))
45                }
46            }
47        } else {
48            arms.push(quote! { #name::#ident #params => f.pad(#output) });
49        }
50    }
51
52    if arms.len() < variants.len() {
53        arms.push(quote! { _ => panic!("fmt() called on disabled variant.") });
54    }
55
56    Ok(quote! {
57        impl #impl_generics ::core::fmt::Display for #name #ty_generics #where_clause {
58            fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> {
59                match *self {
60                    #(#arms),*
61                }
62            }
63        }
64    })
65}