strum_macros/macros/strings/
as_ref_str.rs

1use proc_macro2::TokenStream;
2use quote::quote;
3use syn::{parse_quote, Data, DeriveInput, Fields};
4
5use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};
6
7fn get_arms(ast: &DeriveInput) -> syn::Result<Vec<TokenStream>> {
8    let name = &ast.ident;
9    let mut arms = Vec::new();
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    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        // Use `to_string` attribute (not `as_ref_str` or something) to keep things consistent
27        // (i.e. always `enum.as_ref().to_string() == enum.to_string()`).
28        let output = variant_properties.get_preferred_name(type_properties.case_style);
29        let params = match variant.fields {
30            Fields::Unit => quote! {},
31            Fields::Unnamed(..) => quote! { (..) },
32            Fields::Named(..) => quote! { {..} },
33        };
34
35        arms.push(quote! { #name::#ident #params => #output });
36    }
37
38    if arms.len() < variants.len() {
39        arms.push(quote! {
40            _ => panic!(
41                "AsRef::<str>::as_ref() or AsStaticRef::<str>::as_static() \
42                 called on disabled variant.",
43            )
44        });
45    }
46
47    Ok(arms)
48}
49
50pub fn as_ref_str_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
51    let name = &ast.ident;
52    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
53    let arms = get_arms(ast)?;
54    Ok(quote! {
55        impl #impl_generics ::core::convert::AsRef<str> for #name #ty_generics #where_clause {
56            fn as_ref(&self) -> &str {
57                match *self {
58                    #(#arms),*
59                }
60            }
61        }
62    })
63}
64
65pub enum GenerateTraitVariant {
66    AsStaticStr,
67    From,
68}
69
70pub fn as_static_str_inner(
71    ast: &DeriveInput,
72    trait_variant: &GenerateTraitVariant,
73) -> syn::Result<TokenStream> {
74    let name = &ast.ident;
75    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
76    let arms = get_arms(ast)?;
77    let type_properties = ast.get_type_properties()?;
78    let strum_module_path = type_properties.crate_module_path();
79
80    let mut generics = ast.generics.clone();
81    generics
82        .params
83        .push(syn::GenericParam::Lifetime(syn::LifetimeParam::new(
84            parse_quote!('_derivative_strum),
85        )));
86    let (impl_generics2, _, _) = generics.split_for_impl();
87    let arms2 = arms.clone();
88    let arms3 = arms.clone();
89
90    Ok(match trait_variant {
91        GenerateTraitVariant::AsStaticStr => quote! {
92            impl #impl_generics #strum_module_path::AsStaticRef<str> for #name #ty_generics #where_clause {
93                fn as_static(&self) -> &'static str {
94                    match *self {
95                        #(#arms),*
96                    }
97                }
98            }
99        },
100        GenerateTraitVariant::From => quote! {
101            impl #impl_generics ::core::convert::From<#name #ty_generics> for &'static str #where_clause {
102                fn from(x: #name #ty_generics) -> &'static str {
103                    match x {
104                        #(#arms2),*
105                    }
106                }
107            }
108            impl #impl_generics2 ::core::convert::From<&'_derivative_strum #name #ty_generics> for &'static str #where_clause {
109                fn from(x: &'_derivative_strum #name #ty_generics) -> &'static str {
110                    match *x {
111                        #(#arms3),*
112                    }
113                }
114            }
115        },
116    })
117}