strum_macros/macros/strings/
to_string.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 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(
43            type_properties.case_style,
44            type_properties.prefix.as_ref(),
45            type_properties.suffix.as_ref(),
46        );
47
48        let params = match variant.fields {
49            Fields::Unit => quote! {},
50            Fields::Unnamed(..) => quote! { (..) },
51            Fields::Named(..) => quote! { {..} },
52        };
53
54        arms.push(quote! { #name::#ident #params => ::std::string::String::from(#output) });
55    }
56
57    if arms.len() < variants.len() {
58        arms.push(quote! { _ => panic!("to_string() called on disabled variant.") });
59    }
60
61    Ok(quote! {
62        #[allow(clippy::use_self)]
63        #[automatically_derived]
64        impl #impl_generics ::std::string::ToString for #name #ty_generics #where_clause {
65            fn to_string(&self) -> ::std::string::String {
66                match *self {
67                    #(#arms),*
68                }
69            }
70        }
71    })
72}