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
extern crate proc_macro;

use proc_macro2::TokenStream;
use quote::quote;
use syn::{
    parse_macro_input, FnArg, Ident, Item, ItemTrait, Pat, PatType, ReturnType, TraitItem,
    TraitItemMethod, Type,
};

/// Generate a mock struct from a trait. The mock struct will be named after the
/// trait, with "Mock" appended.
#[proc_macro_attribute]
pub fn mock_it(
    _attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    // Parse the tokens
    let input: Item = parse_macro_input!(item as Item);

    // Make sure it's a trait
    let item_trait = match input {
        Item::Trait(item_trait) => item_trait,
        _ => panic!("Only traits can be mocked with the mock_it macro"),
    };

    // Create the mock identifier
    let trait_ident = &item_trait.ident;
    let mock_ident = Ident::new(&format!("{}Mock", trait_ident), trait_ident.span());

    // Generate the mock
    let fields = create_fields(&item_trait);
    let field_init = create_field_init(&item_trait);
    let trait_impls = create_trait_impls(&item_trait);
    let clone_impl = create_clone_impl(&item_trait);

    // Combine and tokenize the final result
    let output = quote! {
        #item_trait

        pub struct #mock_ident {
            #(#fields),*
        }

        impl #mock_ident {
            pub fn new() -> Self {
                #mock_ident {
                    #(#field_init),*
                }
            }
        }

        impl std::clone::Clone for #mock_ident {
            fn clone(&self) -> Self {
                #mock_ident {
                    #(#clone_impl),*
                }
            }
        }

        impl #trait_ident for #mock_ident {
            #(#trait_impls)*
        }
    };

    output.into()
}

/// Create the struct fields
fn create_fields(item_trait: &ItemTrait) -> impl Iterator<Item = TokenStream> + '_ {
    get_mocks(item_trait).map(|(ident, mock)| {
        quote! {
            pub #ident: #mock
        }
    })
}

/// Create the field initializers for the `new` method
fn create_field_init(item_trait: &ItemTrait) -> impl Iterator<Item = TokenStream> + '_ {
    get_trait_methods(item_trait).map(|method| {
        let ident = method.sig.ident.clone();

        quote! {
            #ident: mock_it::Mock::new()
        }
    })
}

/// Create the clone implementation
fn create_clone_impl(item_trait: &ItemTrait) -> impl Iterator<Item = TokenStream> + '_ {
    get_trait_method_types(item_trait).map(|(ident, _, _)| {
        quote! {
            #ident: self.#ident.clone()
        }
    })
}

/// Create the trait method implementations
fn create_trait_impls(item_trait: &ItemTrait) -> impl Iterator<Item = TokenStream> + '_ {
    get_trait_methods(item_trait).map(|method| {
        let (ident, args, _) = get_method_types(method);
        let arg_names: Vec<Ident> = args
            .into_iter()
            .map(|arg| match *arg.pat.clone() {
                Pat::Ident(inner) => inner.ident.clone(),
                _ => panic!("unknown argument pattern"),
            })
            .collect();
        let signature = &method.sig;

        quote! {
            #signature {
                self.#ident.called((#(#arg_names),*))
            }
        }
    })
}

/// Get the mock types for each method on the trait
fn get_mocks(item_trait: &ItemTrait) -> impl Iterator<Item = (Ident, TokenStream)> + '_ {
    get_trait_method_types(item_trait)
        .map(|(ident, args, return_type)| (ident, get_mock(args, return_type)))
}

/// Get the mock type for the arguments and return type combination
fn get_mock(args: Vec<&PatType>, return_type: Option<&Box<Type>>) -> TokenStream {
    let arg_types: Vec<&Box<Type>> = args.into_iter().map(|arg| &arg.ty).collect();
    let return_tokens = match return_type {
        Some(return_type) => quote! { #return_type },
        None => quote! { () },
    };

    quote! {
        mock_it::Mock<(#(#arg_types),*), #return_tokens>
    }
}

/// Get the identifier, arguments, and return type for each method in the trait
fn get_trait_method_types(
    item_trait: &ItemTrait,
) -> impl Iterator<Item = (Ident, Vec<&PatType>, Option<&Box<Type>>)> {
    get_trait_methods(item_trait).map(get_method_types)
}

/// Get the method's identifier, arguments, and return type
fn get_method_types(method: &TraitItemMethod) -> (Ident, Vec<&PatType>, Option<&Box<Type>>) {
    let ident = method.sig.ident.clone();
    let args: Vec<&PatType> = method
        .sig
        .inputs
        .iter()
        .filter_map(|arg| match arg {
            FnArg::Typed(inner) => Some(inner),
            _ => None,
        })
        .collect();
    let return_type = match method.sig.output {
        ReturnType::Default => None,
        ReturnType::Type(_, ref return_type) => Some(return_type),
    };

    (ident, args, return_type)
}

/// Get the methods for the given trait
fn get_trait_methods(item_trait: &ItemTrait) -> impl Iterator<Item = &TraitItemMethod> {
    item_trait.items.iter().filter_map(|item| {
        if let TraitItem::Method(item_method) = item {
            Some(item_method)
        } else {
            None
        }
    })
}