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

use proc_macro::TokenStream;
use quote::{Tokens, ToTokens};

#[proc_macro_derive(INSObject)]
pub fn impl_object(input: TokenStream) -> TokenStream {
    // Construct a string representation of the type definition
    let s = input.to_string();

    // Parse the string representation
    let ast = syn::parse_macro_input(&s).unwrap();

    // Build the impl
    let name = &ast.ident;
    let link_name = format!("OBJC_CLASS_$_{}", name);
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();

    let mut gen = Tokens::new();
    quote!(
        unsafe impl #impl_generics ::objc::Message for #name #ty_generics #where_clause { }
    ).to_tokens(&mut gen);

    quote!(
        impl #impl_generics INSObject for #name #ty_generics #where_clause {
            fn class() -> &'static ::objc::runtime::Class {
                extern {
                    #[link_name = #link_name]
                    static OBJC_CLASS: ::objc::runtime::Class;
                }
                unsafe {
                    &OBJC_CLASS
                }
            }
        }
    ).to_tokens(&mut gen);

    quote!(
        impl #impl_generics ::std::cmp::PartialEq for #name #ty_generics #where_clause {
            fn eq(&self, other: &Self) -> bool {
                INSObject::is_equal(self, other)
            }
        }
    ).to_tokens(&mut gen);

    quote!(
        impl #impl_generics ::std::hash::Hash for #name #ty_generics #where_clause {
            fn hash<H>(&self, state: &mut H) where H: ::std::hash::Hasher {
                INSObject::hash_code(self).hash(state);
            }
        }
    ).to_tokens(&mut gen);

    quote!(
        impl #impl_generics ::std::fmt::Debug for #name #ty_generics #where_clause {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                let s = INSObject::description(self);
                ::std::fmt::Display::fmt(&*s, f)
            }
        }
    ).to_tokens(&mut gen);

    // Return the generated impl
    gen.parse().unwrap()
}