1#![cfg_attr(
8 not(test),
9 deny(
10 clippy::indexing_slicing,
11 clippy::unwrap_used,
12 clippy::expect_used,
13 clippy::panic,
14 )
15)]
16#![warn(missing_docs)]
17
18use proc_macro::TokenStream;
21use proc_macro2::{Span, TokenStream as TokenStream2};
22use quote::quote;
23use std::collections::{HashMap, HashSet};
24use syn::fold::{self, Fold};
25use syn::punctuated::Punctuated;
26use syn::spanned::Spanned;
27use syn::{
28 parse_macro_input, parse_quote, DeriveInput, Ident, Lifetime, MetaList, Token, Type,
29 TypeParamBound, TypePath, WherePredicate,
30};
31use synstructure::Structure;
32mod visitor;
33
34#[proc_macro_derive(ZeroFrom, attributes(zerofrom))]
50pub fn zf_derive(input: TokenStream) -> TokenStream {
51 let input = parse_macro_input!(input as DeriveInput);
52 TokenStream::from(zf_derive_impl(&input))
53}
54
55fn has_attr(attrs: &[syn::Attribute], name: &str) -> bool {
56 attrs.iter().any(|a| {
57 if let Ok(i) = a.parse_args::<Ident>() {
58 if i == name {
59 return true;
60 }
61 }
62 false
63 })
64}
65
66fn get_may_borrow_attr(attrs: &[syn::Attribute]) -> Result<HashSet<Ident>, Span> {
70 let mut params = HashSet::new();
71 for attr in attrs {
72 if let Ok(list) = attr.parse_args::<MetaList>() {
73 if list.path.is_ident("may_borrow") {
74 if let Ok(list) =
75 list.parse_args_with(Punctuated::<Ident, Token![,]>::parse_terminated)
76 {
77 params.extend(list)
78 } else {
79 return Err(attr.span());
80 }
81 }
82 }
83 }
84 Ok(params)
85}
86
87fn zf_derive_impl(input: &DeriveInput) -> TokenStream2 {
88 let mut tybounds = input
89 .generics
90 .type_params()
91 .map(|ty| {
92 let mut ty = ty.clone();
94 ty.default = None;
95 ty
96 })
97 .collect::<Vec<_>>();
98 let typarams = tybounds
99 .iter()
100 .map(|ty| ty.ident.clone())
101 .collect::<Vec<_>>();
102 let lts = input.generics.lifetimes().count();
103 let name = &input.ident;
104 let structure = Structure::new(input);
105
106 let may_borrow_attrs = match get_may_borrow_attr(&input.attrs) {
107 Ok(mb) => mb,
108 Err(span) => {
109 return syn::Error::new(
110 span,
111 "#[zerofrom(may_borrow)] on the struct takes in a comma separated list of type parameters, like so: `#[zerofrom(may_borrow(A, B, C, D)]`",
112 ).to_compile_error();
113 }
114 };
115
116 let generics_env: HashMap<Ident, Option<Ident>> = tybounds
121 .iter_mut()
122 .map(|param| {
123 let maybe_new_param = if has_attr(¶m.attrs, "may_borrow")
125 || may_borrow_attrs.contains(¶m.ident)
126 {
127 let mut bounds = core::mem::take(&mut param.bounds);
130 while let Some(bound) = bounds.pop() {
131 if let TypeParamBound::Trait(ref trait_bound) = bound {
132 if trait_bound.path.get_ident().map(|ident| ident == "Sized") == Some(true)
133 && trait_bound.maybe.is_some()
134 {
135 continue;
136 }
137 }
138 param.bounds.push(bound);
139 }
140 Some(Ident::new(
141 &format!("{}ZFParamC", param.ident),
142 param.ident.span(),
143 ))
144 } else {
145 None
146 };
147 (param.ident.clone(), maybe_new_param)
148 })
149 .collect();
150
151 let generics_may_borrow = generics_env.values().any(|x| x.is_some());
153
154 if lts == 0 && !generics_may_borrow {
155 let has_clone = structure
156 .variants()
157 .iter()
158 .flat_map(|variant| variant.bindings().iter())
159 .any(|binding| has_attr(&binding.ast().attrs, "clone"));
160 let (clone, clone_trait) = if has_clone {
161 (quote!(this.clone()), quote!(Clone))
162 } else {
163 (quote!(*this), quote!(Copy))
164 };
165 let bounds: Vec<WherePredicate> = typarams
166 .iter()
167 .map(|ty| parse_quote!(#ty: #clone_trait + 'static))
168 .collect();
169 quote! {
170 impl<'zf, #(#tybounds),*> zerofrom::ZeroFrom<'zf, #name<#(#typarams),*>> for #name<#(#typarams),*> where #(#bounds),* {
171 fn zero_from(this: &'zf Self) -> Self {
172 #clone
173 }
174 }
175 }
176 } else {
177 if lts > 1 {
178 return syn::Error::new(
179 input.generics.span(),
180 "derive(ZeroFrom) cannot have multiple lifetime parameters",
181 )
182 .to_compile_error();
183 }
184
185 let mut zf_bounds: Vec<WherePredicate> = vec![];
186 let body = structure.each_variant(|vi| {
187 vi.construct(|f, i| {
188 let binding = format!("__binding_{i}");
189 let field = Ident::new(&binding, Span::call_site());
190
191 if has_attr(&f.attrs, "clone") {
192 quote! {
193 #field.clone()
194 }
195 } else {
196 let fty = replace_lifetime(&f.ty, custom_lt("'zf"));
198 let lifetime_ty =
200 replace_lifetime_and_type(&f.ty, custom_lt("'zf_inner"), &generics_env);
201
202 let (has_ty, has_lt) = visitor::check_type_for_parameters(&f.ty, &generics_env);
203 if has_ty {
204 if has_lt {
209 zf_bounds
210 .push(parse_quote!(#fty: zerofrom::ZeroFrom<'zf, #lifetime_ty>));
211 } else {
212 zf_bounds.push(parse_quote!(#fty: zerofrom::ZeroFrom<'zf, #fty>));
213 }
214 }
215 if has_ty || has_lt {
216 quote! {
219 <#fty as zerofrom::ZeroFrom<'zf, #lifetime_ty>>::zero_from(#field)
220 }
221 } else {
222 quote! { *#field }
224 }
225 }
226 })
227 });
228 let (maybe_zf_lifetime, maybe_zf_inner_lifetime) = if lts == 0 {
231 (quote!(), quote!())
232 } else {
233 (quote!('zf,), quote!('zf_inner,))
234 };
235
236 let mut typarams_c = typarams.clone();
238
239 if generics_may_borrow {
240 for typaram_c in &mut typarams_c {
241 if let Some(Some(replacement)) = generics_env.get(typaram_c) {
242 let typaram_t = core::mem::replace(typaram_c, replacement.clone());
244 zf_bounds
245 .push(parse_quote!(#typaram_c: zerofrom::ZeroFrom<'zf_inner, #typaram_t>));
246 tybounds.push(parse_quote!(#typaram_c));
247 }
248 }
249 }
250
251 quote! {
252 impl<'zf, 'zf_inner, #(#tybounds),*> zerofrom::ZeroFrom<'zf, #name<#maybe_zf_inner_lifetime #(#typarams_c),*>> for #name<#maybe_zf_lifetime #(#typarams),*>
253 where
254 #(#zf_bounds,)* {
255 fn zero_from(this: &'zf #name<#maybe_zf_inner_lifetime #(#typarams_c),*>) -> Self {
256 match *this { #body }
257 }
258 }
259 }
260 }
261}
262
263fn custom_lt(s: &str) -> Lifetime {
264 Lifetime::new(s, Span::call_site())
265}
266
267fn replace_lifetime(x: &Type, lt: Lifetime) -> Type {
269 struct ReplaceLifetime(Lifetime);
270
271 impl Fold for ReplaceLifetime {
272 fn fold_lifetime(&mut self, _: Lifetime) -> Lifetime {
273 self.0.clone()
274 }
275 }
276 ReplaceLifetime(lt).fold_type(x.clone())
277}
278
279fn replace_lifetime_and_type(
282 x: &Type,
283 lt: Lifetime,
284 generics_env: &HashMap<Ident, Option<Ident>>,
285) -> Type {
286 struct ReplaceLifetimeAndTy<'a>(Lifetime, &'a HashMap<Ident, Option<Ident>>);
287
288 impl Fold for ReplaceLifetimeAndTy<'_> {
289 fn fold_lifetime(&mut self, _: Lifetime) -> Lifetime {
290 self.0.clone()
291 }
292 fn fold_type_path(&mut self, i: TypePath) -> TypePath {
293 if i.qself.is_none() {
294 if let Some(ident) = i.path.get_ident() {
295 if let Some(Some(replacement)) = self.1.get(ident) {
296 return parse_quote!(#replacement);
297 }
298 }
299 }
300 fold::fold_type_path(self, i)
301 }
302 }
303 ReplaceLifetimeAndTy(lt, generics_env).fold_type(x.clone())
304}