1 | use proc_macro2::{Span, TokenStream, TokenTree}; |
2 | use quote::{quote, ToTokens}; |
3 | use syn::parse_quote; |
4 | use syn::{Data, DeriveInput, Fields}; |
5 | |
6 | use crate::helpers::{non_enum_error, strum_discriminants_passthrough_error, HasTypeProperties}; |
7 | |
8 | /// Attributes to copy from the main enum's variants to the discriminant enum's variants. |
9 | /// |
10 | /// Attributes not in this list may be for other `proc_macro`s on the main enum, and may cause |
11 | /// compilation problems when copied across. |
12 | const ATTRIBUTES_TO_COPY: &[&str] = &["doc" , "cfg" , "allow" , "deny" , "strum_discriminants" ]; |
13 | |
14 | pub 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 | // Derives for the generated enum |
24 | let type_properties = ast.get_type_properties()?; |
25 | |
26 | let derives = type_properties.discriminant_derives; |
27 | |
28 | let derives = quote! { |
29 | #[derive(Clone, Copy, Debug, PartialEq, Eq, #(#derives),*)] |
30 | }; |
31 | |
32 | // Work out the name |
33 | let default_name = syn::Ident::new(&format!(" {}Discriminants" , name), Span::call_site()); |
34 | |
35 | let discriminants_name = type_properties.discriminant_name.unwrap_or(default_name); |
36 | let discriminants_vis = type_properties |
37 | .discriminant_vis |
38 | .unwrap_or_else(|| vis.clone()); |
39 | |
40 | // Pass through all other attributes |
41 | let pass_though_attributes = type_properties.discriminant_others; |
42 | |
43 | let repr = type_properties.enum_repr.map(|repr| quote!(#[repr(#repr)])); |
44 | |
45 | // Add the variants without fields, but exclude the `strum` meta item |
46 | let mut discriminants = Vec::new(); |
47 | for variant in variants { |
48 | let ident = &variant.ident; |
49 | let discriminant = variant |
50 | .discriminant |
51 | .as_ref() |
52 | .map(|(_, expr)| quote!( = #expr)); |
53 | |
54 | // Don't copy across the "strum" meta attribute. Only passthrough the whitelisted |
55 | // attributes and proxy `#[strum_discriminants(...)]` attributes |
56 | let attrs = variant |
57 | .attrs |
58 | .iter() |
59 | .filter(|attr| { |
60 | ATTRIBUTES_TO_COPY |
61 | .iter() |
62 | .any(|attr_whitelisted| attr.path().is_ident(attr_whitelisted)) |
63 | }) |
64 | .map(|attr| { |
65 | if attr.path().is_ident("strum_discriminants" ) { |
66 | let mut ts = attr.meta.require_list()?.to_token_stream().into_iter(); |
67 | |
68 | // Discard strum_discriminants(...) |
69 | let _ = ts.next(); |
70 | |
71 | let passthrough_group = ts |
72 | .next() |
73 | .ok_or_else(|| strum_discriminants_passthrough_error(attr))?; |
74 | let passthrough_attribute = match passthrough_group { |
75 | TokenTree::Group(ref group) => group.stream(), |
76 | _ => { |
77 | return Err(strum_discriminants_passthrough_error(&passthrough_group)); |
78 | } |
79 | }; |
80 | if passthrough_attribute.is_empty() { |
81 | return Err(strum_discriminants_passthrough_error(&passthrough_group)); |
82 | } |
83 | Ok(quote! { #[#passthrough_attribute] }) |
84 | } else { |
85 | Ok(attr.to_token_stream()) |
86 | } |
87 | }) |
88 | .collect::<Result<Vec<_>, _>>()?; |
89 | |
90 | discriminants.push(quote! { #(#attrs)* #ident #discriminant}); |
91 | } |
92 | |
93 | // Ideally: |
94 | // |
95 | // * For `Copy` types, we `impl From<TheEnum> for TheEnumDiscriminants` |
96 | // * For `!Copy` types, we `impl<'enum> From<&'enum TheEnum> for TheEnumDiscriminants` |
97 | // |
98 | // That way we ensure users are not able to pass a `Copy` type by reference. However, the |
99 | // `#[derive(..)]` attributes are not in the parsed tokens, so we are not able to check if a |
100 | // type is `Copy`, so we just implement both. |
101 | // |
102 | // See <https://github.com/dtolnay/syn/issues/433> |
103 | // --- |
104 | // let is_copy = unique_meta_list(type_meta.iter(), "derive") |
105 | // .map(extract_list_metas) |
106 | // .map(|metas| { |
107 | // metas |
108 | // .filter_map(get_meta_ident) |
109 | // .any(|derive| derive.to_string() == "Copy") |
110 | // }).unwrap_or(false); |
111 | |
112 | let arms = variants |
113 | .iter() |
114 | .map(|variant| { |
115 | let ident = &variant.ident; |
116 | let params = match &variant.fields { |
117 | Fields::Unit => quote! {}, |
118 | Fields::Unnamed(_fields) => { |
119 | quote! { (..) } |
120 | } |
121 | Fields::Named(_fields) => { |
122 | quote! { { .. } } |
123 | } |
124 | }; |
125 | |
126 | quote! { #name::#ident #params => #discriminants_name::#ident } |
127 | }) |
128 | .collect::<Vec<_>>(); |
129 | |
130 | let from_fn_body = quote! { match val { #(#arms),* } }; |
131 | |
132 | let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); |
133 | let impl_from = quote! { |
134 | impl #impl_generics ::core::convert::From< #name #ty_generics > for #discriminants_name #where_clause { |
135 | fn from(val: #name #ty_generics) -> #discriminants_name { |
136 | #from_fn_body |
137 | } |
138 | } |
139 | }; |
140 | let impl_from_ref = { |
141 | let mut generics = ast.generics.clone(); |
142 | |
143 | let lifetime = parse_quote!('_enum); |
144 | let enum_life = quote! { & #lifetime }; |
145 | generics.params.push(lifetime); |
146 | |
147 | // Shadows the earlier `impl_generics` |
148 | let (impl_generics, _, _) = generics.split_for_impl(); |
149 | |
150 | quote! { |
151 | impl #impl_generics ::core::convert::From< #enum_life #name #ty_generics > for #discriminants_name #where_clause { |
152 | fn from(val: #enum_life #name #ty_generics) -> #discriminants_name { |
153 | #from_fn_body |
154 | } |
155 | } |
156 | } |
157 | }; |
158 | |
159 | Ok(quote! { |
160 | /// Auto-generated discriminant enum variants |
161 | #derives |
162 | #repr |
163 | #(#[ #pass_though_attributes ])* |
164 | #discriminants_vis enum #discriminants_name { |
165 | #(#discriminants),* |
166 | } |
167 | |
168 | #impl_from |
169 | #impl_from_ref |
170 | }) |
171 | } |
172 | |