strum_macros/macros/
enum_discriminants.rs1use proc_macro2::{Span, TokenStream, TokenTree};
2use quote::{quote, ToTokens};
3use syn::parse_quote;
4use syn::{Data, DeriveInput, Fields};
5
6use crate::helpers::{non_enum_error, strum_discriminants_passthrough_error, HasTypeProperties};
7
8const ATTRIBUTES_TO_COPY: &[&str] = &["doc", "cfg", "allow", "deny", "strum_discriminants"];
13
14pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
15 let name = &ast.ident;
16 let vis = &ast.vis;
17
18 let variants = match &ast.data {
19 Data::Enum(v) => &v.variants,
20 _ => return Err(non_enum_error()),
21 };
22
23 let type_properties = ast.get_type_properties()?;
25 let strum_module_path = type_properties.crate_module_path();
26
27 let derives = type_properties.discriminant_derives;
28
29 let derives = quote! {
30 #[derive(Clone, Copy, Debug, PartialEq, Eq, #(#derives),*)]
31 };
32
33 let default_name = syn::Ident::new(&format!("{}Discriminants", name), Span::call_site());
35
36 let discriminants_name = type_properties.discriminant_name.unwrap_or(default_name);
37 let discriminants_vis = type_properties
38 .discriminant_vis
39 .as_ref()
40 .unwrap_or_else(|| &vis);
41
42 let pass_though_attributes = type_properties.discriminant_others;
44
45 let repr = type_properties.enum_repr.map(|repr| quote!(#[repr(#repr)]));
46
47 let mut discriminants = Vec::new();
49 for variant in variants {
50 let ident = &variant.ident;
51 let discriminant = variant
52 .discriminant
53 .as_ref()
54 .map(|(_, expr)| quote!( = #expr));
55
56 let attrs = variant
59 .attrs
60 .iter()
61 .filter(|attr| {
62 ATTRIBUTES_TO_COPY
63 .iter()
64 .any(|attr_whitelisted| attr.path().is_ident(attr_whitelisted))
65 })
66 .map(|attr| {
67 if attr.path().is_ident("strum_discriminants") {
68 let mut ts = attr.meta.require_list()?.to_token_stream().into_iter();
69
70 let _ = ts.next();
72
73 let passthrough_group = ts
74 .next()
75 .ok_or_else(|| strum_discriminants_passthrough_error(attr))?;
76 let passthrough_attribute = match passthrough_group {
77 TokenTree::Group(ref group) => group.stream(),
78 _ => {
79 return Err(strum_discriminants_passthrough_error(&passthrough_group));
80 }
81 };
82 if passthrough_attribute.is_empty() {
83 return Err(strum_discriminants_passthrough_error(&passthrough_group));
84 }
85 Ok(quote! { #[#passthrough_attribute] })
86 } else {
87 Ok(attr.to_token_stream())
88 }
89 })
90 .collect::<Result<Vec<_>, _>>()?;
91
92 discriminants.push(quote! { #(#attrs)* #ident #discriminant});
93 }
94
95 let arms = variants
115 .iter()
116 .map(|variant| {
117 let ident = &variant.ident;
118 let params = match &variant.fields {
119 Fields::Unit => quote! {},
120 Fields::Unnamed(_fields) => {
121 quote! { (..) }
122 }
123 Fields::Named(_fields) => {
124 quote! { { .. } }
125 }
126 };
127
128 quote! { #name::#ident #params => #discriminants_name::#ident }
129 })
130 .collect::<Vec<_>>();
131
132 let from_fn_body = quote! { match val { #(#arms),* } };
133
134 let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
135 let impl_from = quote! {
136 impl #impl_generics ::core::convert::From< #name #ty_generics > for #discriminants_name #where_clause {
137 #[inline]
138 fn from(val: #name #ty_generics) -> #discriminants_name {
139 #from_fn_body
140 }
141 }
142 };
143 let impl_from_ref = {
144 let mut generics = ast.generics.clone();
145
146 let lifetime = parse_quote!('_enum);
147 let enum_life = quote! { & #lifetime };
148 generics.params.push(lifetime);
149
150 let (impl_generics, _, _) = generics.split_for_impl();
152
153 quote! {
154 impl #impl_generics ::core::convert::From< #enum_life #name #ty_generics > for #discriminants_name #where_clause {
155 #[inline]
156 fn from(val: #enum_life #name #ty_generics) -> #discriminants_name {
157 #from_fn_body
158 }
159 }
160 }
161 };
162
163 let impl_into_discriminant = match type_properties.discriminant_vis {
165 None | Some(syn::Visibility::Public(..)) => quote! {
167 impl #impl_generics #strum_module_path::IntoDiscriminant for #name #ty_generics #where_clause {
168 type Discriminant = #discriminants_name;
169
170 #[inline]
171 fn discriminant(&self) -> Self::Discriminant {
172 <Self::Discriminant as ::core::convert::From<&Self>>::from(self)
173 }
174 }
175 },
176 _ => quote! {},
181 };
182
183 Ok(quote! {
184 #derives
186 #repr
187 #(#[ #pass_though_attributes ])*
188 #discriminants_vis enum #discriminants_name {
189 #(#discriminants),*
190 }
191
192 #impl_into_discriminant
193 #impl_from
194 #impl_from_ref
195 })
196}