strum_macros/macros/strings/
as_ref_str.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
use proc_macro2::TokenStream;
use quote::quote;
use syn::{parse_quote, Data, DeriveInput, Fields};

use crate::helpers::{
    non_enum_error, non_single_field_variant_error, HasStrumVariantProperties, HasTypeProperties,
};

fn get_arms<F>(ast: &DeriveInput, transparent_fn: F) -> syn::Result<Vec<TokenStream>>
where
    F: Fn(&TokenStream) -> TokenStream,
{
    let name = &ast.ident;
    let mut arms = Vec::new();
    let variants = match &ast.data {
        Data::Enum(v) => &v.variants,
        _ => return Err(non_enum_error()),
    };

    let type_properties = ast.get_type_properties()?;

    for variant in variants {
        let ident = &variant.ident;
        let variant_properties = variant.get_variant_properties()?;

        if variant_properties.disabled.is_some() {
            continue;
        }

        if let Some(..) = variant_properties.transparent {
            let arm = super::extract_single_field_variant_and_then(name, variant, |tok| {
                transparent_fn(tok)
            })
            .map_err(|_| non_single_field_variant_error("transparent"))?;

            arms.push(arm);
            continue;
        }

        // Look at all the serialize attributes.
        // Use `to_string` attribute (not `as_ref_str` or something) to keep things consistent
        // (i.e. always `enum.as_ref().to_string() == enum.to_string()`).
        let output = variant_properties
            .get_preferred_name(type_properties.case_style, type_properties.prefix.as_ref());
        let params = match variant.fields {
            Fields::Unit => quote! {},
            Fields::Unnamed(..) => quote! { (..) },
            Fields::Named(..) => quote! { {..} },
        };

        arms.push(quote! { #name::#ident #params => #output });
    }

    if arms.len() < variants.len() {
        arms.push(quote! {
            _ => panic!(
                "AsRef::<str>::as_ref() or AsStaticRef::<str>::as_static() \
                 called on disabled variant.",
            )
        });
    }

    Ok(arms)
}

pub fn as_ref_str_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
    let name = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
    let arms = get_arms(ast, |tok| {
        quote! { ::core::convert::AsRef::<str>::as_ref(#tok) }
    })?;

    Ok(quote! {
        impl #impl_generics ::core::convert::AsRef<str> for #name #ty_generics #where_clause {
            #[inline]
            fn as_ref(&self) -> &str {
                match *self {
                    #(#arms),*
                }
            }
        }
    })
}

pub enum GenerateTraitVariant {
    AsStaticStr,
    From,
}

pub fn as_static_str_inner(
    ast: &DeriveInput,
    trait_variant: &GenerateTraitVariant,
) -> syn::Result<TokenStream> {
    let name = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
    let arms = &get_arms(ast, |tok| {
        quote! { ::core::convert::From::from(#tok) }
    })?;

    let type_properties = ast.get_type_properties()?;
    let strum_module_path = type_properties.crate_module_path();

    let mut generics = ast.generics.clone();
    generics
        .params
        .push(syn::GenericParam::Lifetime(syn::LifetimeParam::new(
            parse_quote!('_derivative_strum),
        )));
    let (impl_generics2, _, _) = generics.split_for_impl();

    Ok(match trait_variant {
        GenerateTraitVariant::AsStaticStr => quote! {
            impl #impl_generics #strum_module_path::AsStaticRef<str> for #name #ty_generics #where_clause {
                #[inline]
                fn as_static(&self) -> &'static str {
                    match *self {
                        #(#arms),*
                    }
                }
            }
        },
        GenerateTraitVariant::From if !type_properties.const_into_str => quote! {
            impl #impl_generics ::core::convert::From<#name #ty_generics> for &'static str #where_clause {
                #[inline]
                fn from(x: #name #ty_generics) -> &'static str {
                    match x {
                        #(#arms),*
                    }
                }
            }
            impl #impl_generics2 ::core::convert::From<&'_derivative_strum #name #ty_generics> for &'static str #where_clause {
                #[inline]
                fn from(x: &'_derivative_strum #name #ty_generics) -> &'static str {
                    match *x {
                        #(#arms),*
                    }
                }
            }
        },
        GenerateTraitVariant::From => quote! {
            impl #impl_generics #name #ty_generics #where_clause {
                pub const fn into_str(&self) -> &'static str {
                    match self {
                        #(#arms),*
                    }
                }
            }

            impl #impl_generics ::core::convert::From<#name #ty_generics> for &'static str #where_clause {
                fn from(x: #name #ty_generics) -> &'static str {
                    match x {
                        #(#arms),*
                    }
                }
            }
            impl #impl_generics2 ::core::convert::From<&'_derivative_strum #name #ty_generics> for &'static str #where_clause {
                fn from(x: &'_derivative_strum #name #ty_generics) -> &'static str {
                    x.into_str()
                }
            }
        },
    })
}