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
//! This crate provides procedural derive macros to simplify the usage of `evmap`.
//!
//! Currently, only `#[derive(ShallowCopy)]` is supported; see below.
#![warn(missing_docs, rust_2018_idioms, broken_intra_doc_links)]

#[allow(unused_extern_crates)]
extern crate proc_macro;

use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{
    parse_macro_input, parse_quote, Data, DeriveInput, Fields, GenericParam, Generics, Index,
};

/// Implementation for `#[derive(ShallowCopy)]`
///
/// evmap provides the [`ShallowCopy`](evmap::shallow_copy::ShallowCopy) trait, which allows you to
/// cheaply alias types that don't otherwise implement `Copy`. Basic implementations are provided
/// for common types such as `String` and `Vec`, but it must be implemented manually for structs
/// using these types.
///
/// This macro attempts to simplify this task. It only works on types whose members all implement
/// `ShallowCopy`. If this is not possible, consider using
/// [`CopyValue`](evmap::shallow_copy::CopyValue), `Box`, or `Arc` instead.
///
/// ## Usage example
/// ```
/// # use evmap_derive::ShallowCopy;
/// #[derive(ShallowCopy)]
/// struct Thing { field: i32 }
///
/// #[derive(ShallowCopy)]
/// struct Generic<T> { field: T }
///
/// #[derive(ShallowCopy)]
/// enum Things<T> { One(Thing), Two(Generic<T>) }
/// ```
///
/// ## Generated implementations
/// The generated implementation calls
/// [`shallow_copy`](evmap::shallow_copy::ShallowCopy::shallow_copy) on all the members of the
/// type, and lifts the `ManuallyDrop` wrappers to the top-level return type.
///
/// For generic types, the derive adds `ShallowCopy` bounds to all the type parameters.
///
/// For instance, for the following code...
/// ```
/// # use evmap_derive::ShallowCopy;
/// #[derive(ShallowCopy)]
/// struct Generic<T> { field: T }
/// ```
/// ...the derive generates...
/// ```
/// # use evmap::shallow_copy::ShallowCopy;
/// # use std::mem::ManuallyDrop;
/// # struct Generic<T> { field: T }
/// impl<T: ShallowCopy> ShallowCopy for Generic<T> {
///     unsafe fn shallow_copy(&self) -> ManuallyDrop<Self> {
///         ManuallyDrop::new(Self {
///             field: ManuallyDrop::into_inner(ShallowCopy::shallow_copy(&self.field))
///         })
///     }
/// }
/// ```
#[proc_macro_derive(ShallowCopy)]
pub fn derive_shallow_copy(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident;
    let generics = add_trait_bounds(input.generics);
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
    let copy = fields(&input.data, &name);
    proc_macro::TokenStream::from(quote! {
        impl #impl_generics evmap::shallow_copy::ShallowCopy for #name #ty_generics #where_clause {
            unsafe fn shallow_copy(&self) -> std::mem::ManuallyDrop<Self> {
                #copy
            }
        }
    })
}

fn add_trait_bounds(mut generics: Generics) -> Generics {
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
            type_param
                .bounds
                .push(parse_quote!(evmap::shallow_copy::ShallowCopy));
        }
    }
    generics
}

fn fields(data: &Data, type_name: &Ident) -> TokenStream {
    match data {
        Data::Struct(data) => match &data.fields {
            Fields::Named(fields) => {
                let recurse = fields.named.iter().map(|f| {
                    let name = &f.ident;
                    quote_spanned! {f.span()=>
                        #name: std::mem::ManuallyDrop::into_inner(
                            evmap::shallow_copy::ShallowCopy::shallow_copy(&self.#name)
                        )
                    }
                });
                quote! {
                    std::mem::ManuallyDrop::new(Self { #(#recurse,)* })
                }
            }
            Fields::Unnamed(fields) => {
                let recurse = fields.unnamed.iter().enumerate().map(|(i, f)| {
                    let index = Index::from(i);
                    quote_spanned! {f.span()=>
                        std::mem::ManuallyDrop::into_inner(
                            evmap::shallow_copy::ShallowCopy::shallow_copy(&self.#index)
                        )
                    }
                });
                quote! {
                    std::mem::ManuallyDrop::new(#type_name(#(#recurse,)*))
                }
            }
            Fields::Unit => quote!(std::mem::ManuallyDrop::new(#type_name)),
        },
        Data::Enum(data) => {
            let recurse = data.variants.iter().map(|f| {
                let (names, fields) = match &f.fields {
                    Fields::Named(fields) => {
                        let field_names = f.fields.iter().map(|field| {
                            let ident = field.ident.as_ref().unwrap();
                            quote_spanned! {
                                field.span()=> #ident
                            }
                        });
                        let recurse = fields.named.iter().map(|f| {
                            let name = f.ident.as_ref().unwrap();
                            quote_spanned! {f.span()=>
                                #name: std::mem::ManuallyDrop::into_inner(
                                    evmap::shallow_copy::ShallowCopy::shallow_copy(#name)
                                )
                            }
                        });
                        (quote! { {#(#field_names,)*} }, quote! { { #(#recurse,)* } })
                    }
                    Fields::Unnamed(fields) => {
                        let field_names = f.fields.iter().enumerate().map(|(i, field)| {
                            let ident = format_ident!("x{}", i);
                            quote_spanned! {
                                field.span()=> #ident
                            }
                        });
                        let recurse = fields.unnamed.iter().enumerate().map(|(i, f)| {
                            let ident = format_ident!("x{}", i);
                            quote_spanned! {f.span()=>
                                std::mem::ManuallyDrop::into_inner(
                                    evmap::shallow_copy::ShallowCopy::shallow_copy(#ident)
                                )
                            }
                        });
                        (quote! { (#(#field_names,)*) }, quote! { (#(#recurse,)*) })
                    }
                    Fields::Unit => (quote!(), quote!()),
                };
                let name = &f.ident;
                quote_spanned! {f.span()=>
                    #type_name::#name#names => std::mem::ManuallyDrop::new(#type_name::#name#fields)
                }
            });
            quote! {
                match self {
                    #(#recurse,)*
                }
            }
        }
        Data::Union(_) => unimplemented!("Unions are not supported"),
    }
}