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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use quote::quote;
use syn::{DeriveInput, GenericParam, Lifetime, LifetimeDef};

#[proc_macro_derive(ReborrowCopyTraits)]
pub fn derive_reborrow_copy(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = syn::parse_macro_input!(input as DeriveInput);

    let name = &input.ident;

    let reborrowed_lifetime = &LifetimeDef::new(Lifetime::new(
        "'__reborrow_lifetime",
        proc_macro2::Span::call_site(),
    ));

    let mut target_ty_generics = input.generics.clone();
    for lt in target_ty_generics.lifetimes_mut() {
        *lt = reborrowed_lifetime.clone();
    }
    let target_ty_generics = target_ty_generics.split_for_impl().1;
    let mut impl_generics = input.generics.clone();
    impl_generics
        .params
        .insert(0, GenericParam::Lifetime(reborrowed_lifetime.clone()));
    let impl_generics = impl_generics.split_for_impl().0;

    let (orig_impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    let expanded = quote! {
        impl #orig_impl_generics ::core::marker::Copy for #name #ty_generics
            #where_clause {}

        impl #orig_impl_generics ::core::clone::Clone for #name #ty_generics
            #where_clause
        {
            #[inline]
            fn clone(&self) -> Self {
                *self
            }
        }

        impl #orig_impl_generics ::reborrow::IntoConst for #name #ty_generics
            #where_clause
        {
            type Target = #name #ty_generics;

            #[inline]
            fn into_const(self) -> <Self as ::reborrow::IntoConst>::Target {
                self
            }
        }

        impl #impl_generics ::reborrow::ReborrowMut<'__reborrow_lifetime> for #name #ty_generics
            #where_clause
        {
            type Target = #name #target_ty_generics;

            #[inline]
            fn rb_mut(&'__reborrow_lifetime mut self) -> <Self as ::reborrow::ReborrowMut>::Target {
                *self
            }
        }

        impl #impl_generics ::reborrow::Reborrow<'__reborrow_lifetime> for #name #ty_generics
            #where_clause
        {
            type Target = #name #target_ty_generics;

            #[inline]
            fn rb(&'__reborrow_lifetime self) -> <Self as ::reborrow::Reborrow>::Target {
                *self
            }
        }

        impl #impl_generics ::reborrow::AsGeneralizedMut<
            '__reborrow_lifetime,
            <Self as ::reborrow::ReborrowMut<'__reborrow_lifetime>>::Target,
        > for #name #ty_generics
            #where_clause
        {
            #[inline]
            fn as_generalized_mut(&'__reborrow_lifetime mut self) -> <Self as ::reborrow::ReborrowMut<'__reborrow_lifetime>>::Target {
                *self
            }
        }

        impl #impl_generics ::reborrow::AsGeneralizedRef<
            '__reborrow_lifetime,
            <Self as ::reborrow::Reborrow<'__reborrow_lifetime>>::Target,
        > for #name #ty_generics
            #where_clause
        {
            #[inline]
            fn as_generalized_ref(&'__reborrow_lifetime self) -> <Self as ::reborrow::Reborrow<'__reborrow_lifetime>>::Target {
                *self
            }
        }
    };

    expanded.into()
}

#[proc_macro_derive(ReborrowTraits, attributes(reborrow, Const))]
pub fn derive_reborrow(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = syn::parse_macro_input!(input as DeriveInput);

    let const_name = input
        .attrs
        .iter()
        .find(|&attr| {
            let segments = &attr.path.segments;
            if let Some(syn::PathSegment {
                ident,
                arguments: syn::PathArguments::None,
            }) = segments.first()
            {
                ident.to_string() == "Const"
            } else {
                false
            }
        })
        .unwrap_or_else(|| panic!("Const reborrowed type must be specified."));

    let const_name = const_name.tokens.clone();
    let const_name = *syn::parse2::<syn::TypeParen>(const_name).unwrap().elem;

    let name = &input.ident;

    let reborrowed_lifetime = &LifetimeDef::new(Lifetime::new(
        "'__reborrow_lifetime",
        proc_macro2::Span::call_site(),
    ));

    let mut target_ty_generics = input.generics.clone();
    for lt in target_ty_generics.lifetimes_mut() {
        *lt = reborrowed_lifetime.clone();
    }
    let target_ty_generics = target_ty_generics.split_for_impl().1;

    let mut impl_generics = input.generics.clone();
    impl_generics
        .params
        .insert(0, GenericParam::Lifetime(reborrowed_lifetime.clone()));
    let impl_generics = impl_generics.split_for_impl().0;

    let (orig_impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    let (rb_mut, rb, into_const) = {
        let data = input.data;

        match data {
            syn::Data::Struct(s) => match s.fields {
                syn::Fields::Named(f) => {
                    let names: Vec<_> = f.named.iter().map(|f| &f.ident).collect();
                    let (f0, f1, f2) = unzip3(
                        f.named
                            .iter()
                            .enumerate()
                            .map(|(i, f)| reborrow_exprs(i, f.clone())),
                    );

                    (
                        quote! { #name:: #target_ty_generics { #(#names: #f0,)* } },
                        quote! { #const_name:: #target_ty_generics { #(#names: #f1,)* } },
                        quote! { #const_name:: #ty_generics { #(#names: #f2,)* } },
                    )
                }
                syn::Fields::Unnamed(f) => {
                    let (f0, f1, f2) = unzip3(
                        f.unnamed
                            .iter()
                            .enumerate()
                            .map(|(i, f)| reborrow_exprs(i, f.clone())),
                    );

                    (
                        quote! { #name:: #target_ty_generics ( #(#f0,)* ) },
                        quote! { #const_name:: #target_ty_generics ( #(#f1,)* ) },
                        quote! { #const_name:: #ty_generics ( #(#f2,)* ) },
                    )
                }
                syn::Fields::Unit => (
                    quote! { #name:: #target_ty_generics },
                    quote! { #const_name:: #target_ty_generics },
                    quote! { #const_name:: #target_ty_generics },
                ),
            },
            syn::Data::Enum(_) => panic!("reborrow-derive does not support enums."),
            syn::Data::Union(_) => panic!("reborrow-derive does not support unions."),
        }
    };

    let expanded = quote! {
        impl #orig_impl_generics ::reborrow::IntoConst for #name #ty_generics
            #where_clause
        {
            type Target = #const_name #ty_generics;

            #[inline]
            fn into_const(self) -> <Self as ::reborrow::IntoConst>::Target {
                #into_const
            }
        }

        impl #impl_generics ::reborrow::ReborrowMut<'__reborrow_lifetime> for #name #ty_generics
            #where_clause
        {
            type Target = #name #target_ty_generics;

            #[inline]
            fn rb_mut(&'__reborrow_lifetime mut self) -> <Self as ::reborrow::ReborrowMut>::Target {
                #rb_mut
            }
        }

        impl #impl_generics ::reborrow::Reborrow<'__reborrow_lifetime> for #name #ty_generics
            #where_clause
        {
            type Target = #const_name #target_ty_generics;

            #[inline]
            fn rb(&'__reborrow_lifetime self) -> <Self as ::reborrow::Reborrow>::Target {
                #rb
            }
        }

        impl #impl_generics ::reborrow::AsGeneralizedMut<
            '__reborrow_lifetime,
            <Self as ::reborrow::ReborrowMut<'__reborrow_lifetime>>::Target,
        > for #name #ty_generics
            #where_clause
        {
            #[inline]
            fn as_generalized_mut(&'__reborrow_lifetime mut self) -> <Self as ::reborrow::ReborrowMut<'__reborrow_lifetime>>::Target {
                <Self as ::reborrow::ReborrowMut>::rb_mut(self)
            }
        }

        impl #impl_generics ::reborrow::AsGeneralizedRef<
            '__reborrow_lifetime,
            <Self as ::reborrow::Reborrow<'__reborrow_lifetime>>::Target,
        > for #name #ty_generics
            #where_clause
        {
            #[inline]
            fn as_generalized_ref(&'__reborrow_lifetime self) -> <Self as ::reborrow::Reborrow<'__reborrow_lifetime>>::Target {
                <Self as ::reborrow::Reborrow>::rb(self)
            }
        }
    };

    expanded.into()
}

fn unzip3<A, B, C, I: Iterator<Item = (A, B, C)>>(iter: I) -> (Vec<A>, Vec<B>, Vec<C>) {
    let mut v0 = Vec::new();
    let mut v1 = Vec::new();
    let mut v2 = Vec::new();
    for (a, b, c) in iter {
        v0.push(a);
        v1.push(b);
        v2.push(c);
    }
    (v0, v1, v2)
}

fn reborrow_exprs(
    idx: usize,
    f: syn::Field,
) -> (
    proc_macro2::TokenStream,
    proc_macro2::TokenStream,
    proc_macro2::TokenStream,
) {
    let is_reborrowable = f
        .attrs
        .iter()
        .find(|&attr| {
            let segments = &attr.path.segments;
            if let Some(syn::PathSegment {
                ident,
                arguments: syn::PathArguments::None,
            }) = segments.first()
            {
                ident.to_string() == "reborrow"
            } else {
                false
            }
        })
        .is_some();

    let idx = syn::Index::from(idx);

    let expr = f
        .ident
        .map(|ident| quote! { self.#ident })
        .unwrap_or(quote! { self.#idx });

    if !is_reborrowable {
        (quote! {#expr}, quote! {#expr}, quote! {#expr})
    } else {
        let ty = f.ty;
        (
            quote! { <#ty as ::reborrow::ReborrowMut>::rb_mut(&mut #expr) },
            quote! { <#ty as ::reborrow::Reborrow>::rb(&#expr) },
            quote! { <#ty as ::reborrow::IntoConst>::into_const(#expr) },
        )
    }
}