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
to_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream>7 pub 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 // display variants like Green("lime") as "lime"
26 if variant_properties.to_string.is_none() && variant_properties.default.is_some() {
27 match &variant.fields {
28 Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
29 arms.push(quote! { #name::#ident(ref s) => ::std::string::String::from(s) });
30 continue;
31 }
32 _ => {
33 return Err(syn::Error::new_spanned(
34 variant,
35 "Default only works on newtype structs with a single String field",
36 ))
37 }
38 }
39 }
40
41 // Look at all the serialize attributes.
42 let output = variant_properties.get_preferred_name(type_properties.case_style);
43
44 let params = match variant.fields {
45 Fields::Unit => quote! {},
46 Fields::Unnamed(..) => quote! { (..) },
47 Fields::Named(..) => quote! { {..} },
48 };
49
50 arms.push(quote! { #name::#ident #params => ::std::string::String::from(#output) });
51 }
52
53 if arms.len() < variants.len() {
54 arms.push(quote! { _ => panic!("to_string() called on disabled variant.") });
55 }
56
57 Ok(quote! {
58 #[allow(clippy::use_self)]
59 impl #impl_generics ::std::string::ToString for #name #ty_generics #where_clause {
60 fn to_string(&self) -> ::std::string::String {
61 match *self {
62 #(#arms),*
63 }
64 }
65 }
66 })
67 }
68