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