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