1use proc_macro2::TokenStream;
2use quote::quote;
3use syn::{Data, DeriveInput, Fields};
4
5use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};
6
7pub fn to_string_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 let mut arms = Vec::new();
17 for variant in variants {
18 let ident = &variant.ident;
19 let variant_properties = variant.get_variant_properties()?;
20
21 if variant_properties.disabled.is_some() {
22 continue;
23 }
24
25 // Look at all the serialize attributes.
26 let output = variant_properties.get_preferred_name(type_properties.case_style);
27
28 let params = match variant.fields {
29 Fields::Unit => quote! {},
30 Fields::Unnamed(..) => quote! { (..) },
31 Fields::Named(..) => quote! { {..} },
32 };
33
34 arms.push(quote! { #name::#ident #params => ::std::string::String::from(#output) });
35 }
36
37 if arms.len() < variants.len() {
38 arms.push(quote! { _ => panic!("to_string() called on disabled variant.") });
39 }
40
41 Ok(quote! {
42 #[allow(clippy::use_self)]
43 impl #impl_generics ::std::string::ToString for #name #ty_generics #where_clause {
44 fn to_string(&self) -> ::std::string::String {
45 match *self {
46 #(#arms),*
47 }
48 }
49 }
50 })
51}
52