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
extern crate proc_macro;
extern crate proc_macro2;
#[macro_use]
extern crate quote;
#[macro_use]
extern crate syn;

use proc_macro::TokenStream;
use proc_macro2::{TokenStream as TokenStream2, Literal as Literal2};
use syn::{Data, DeriveInput, Fields, GenericParam, Generics};

#[proc_macro_derive(Hash32)]
pub fn derive_hash32(input: TokenStream) -> TokenStream {
    let input: DeriveInput = syn::parse(input).unwrap();

    let name = input.ident;
    let generics = add_trait_bounds(input.generics);
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    let const_ = format_ident!("__IMPL_HASH32_FOR_{}", name);
    let hash = compute_hash(&input.data);
    quote!(
        #[allow(non_upper_case_globals)]
        const #const_: () = {
            extern crate hash32;

            impl #impl_generics hash32::Hash for #name #ty_generics #where_clause {
                fn hash<H: hash32::Hasher>(&self, _h: &mut H) -> () {
                    #hash
                }
             }
        };
    )
    .into()
}

// Add a bound `T: Hash` to every type parameter T.
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!(hash32::Hash));
        }
    }
    generics
}

fn compute_hash(data: &Data) -> TokenStream2 {
    match *data {
        Data::Struct(ref data) => match data.fields {
            Fields::Named(ref fields) => {
                let fnames = fields.named.iter().map(|f| &f.ident);
                quote! {
                    #(
                        hash32::Hash::hash(&self.#fnames, _h);
                    )*
                }
            }
            Fields::Unnamed(ref fields) => {
                let indices = (0..fields.unnamed.len()).map(|index| Literal2::usize_unsuffixed(index));
                quote! {
                    #(
                        hash32::Hash::hash(&self.#indices, _h);
                    )*
                }
            }
            Fields::Unit => quote! {},
        },
        Data::Enum(..) | Data::Union(..) => {
            panic!("#[derive(Hash)] doesn't currently support `enum` and `union`")
        }
    }
}