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

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

#[proc_macro_attribute]
pub fn create(_attrs: TokenStream, token_stream: TokenStream) -> TokenStream {
    let mut original = syn::parse_macro_input!(token_stream as syn::ItemStruct);
    let original_name = original.ident.clone();

    original.ident = original_struct_ident(&original_name);

    let modified_name = &original.ident;
    let original_vis = &original.vis;

    TokenStream::from(quote! {
        #original_vis struct #original_name(#original_vis faux::MaybeFaux<#modified_name>);

        impl #original_name {
            pub fn faux() -> Self {
                #original_name(faux::MaybeFaux::faux())
            }
        }

        #[allow(non_camel_case_types)]
        #original
    })
}

#[proc_macro_attribute]
pub fn methods(attrs: TokenStream, token_stream: TokenStream) -> TokenStream {
    let mut impl_block = syn::parse_macro_input!(token_stream as syn::ItemImpl);

    if let Some(_) = impl_block.trait_ {
        panic!("#[faux::methods] does no support trait implementations")
    }

    let ty = match impl_block.self_ty.as_ref() {
        syn::Type::Path(type_path) => type_path,
        _ => panic!(
            "#[faux::methods] does not support implementing types that are not a simple path"
        ),
    };

    let ident = &ty.path.segments.last().unwrap().ident;

    let original_struct = {
        let mut ty = if attrs.is_empty() {
            ty.clone()
        } else {
            let ty = ty.clone();
            let mut path = syn::parse_macro_input!(attrs as syn::Path);
            path.segments.extend(ty.path.segments);
            syn::TypePath { path, ..ty }
        };

        ty.path.segments.last_mut().unwrap().ident = original_struct_ident(ident);
        ty
    };

    let mut original = impl_block.clone();
    publicize_methods(&mut original);

    let self_return: syn::ReturnType = syn::parse2(quote! { -> Self}).unwrap();
    let ty_return: syn::ReturnType = syn::parse2(quote! { -> #ty }).unwrap();
    let ignore_unused_mut_attr = syn::Attribute {
        pound_token: Default::default(),
        style: syn::AttrStyle::Outer,
        bracket_token: Default::default(),
        path: syn::parse2(quote! { allow }).unwrap(),
        tokens: "(unused_mut)".parse().unwrap(),
    };

    let mut when_methods: Vec<syn::ImplItem> = impl_block
        .items
        .iter_mut()
        .filter_map(|item| match item {
            syn::ImplItem::Method(m) => Some(m),
            _ => None,
        })
        .filter_map(|mut m| {
	    // in case a method has `mut self` as a parameter since we
	    // are not modifying self directly; only proxying to
	    // either mock or real instance
	    m.attrs.push(ignore_unused_mut_attr.clone());
            let args = method_args(m);
            let arg_idents: Vec<_> = args.iter().map(|(ident, _)| ident).collect();
            let arg_types: Vec<_> = args.iter().map(|(_, ty)| ty).collect();
            let ident = &m.sig.ident;
            let output = &m.sig.output;
            let error_msg = format!(
                "'{}::{}' is not mocked",
                ty.to_token_stream(),
                ident
            );
            let is_method = args.len() != m.sig.inputs.len();
	    let is_private = m.vis == syn::Visibility::Inherited;
	    let returns_self = m.sig.output == self_return || m.sig.output == ty_return;
	    let mut block = if !is_method {
		// associated function; cannot be mocked
		// proxy to real associated function
		quote! {{
                    <#original_struct>::#ident(#(#arg_idents),*)
                }}
	    } else {
		let call_mock = if is_private {
		    quote! {
			panic!("attempted to call private method on mocked instance")
		    }
		} else {
		    quote! {
			let mut q = q.try_lock().unwrap();
                        use std::any::Any as _;
			match q.get_mock(#ty::#ident.type_id()).expect(#error_msg) {
			    faux::Mock::OnceUnsafe(mock) => unsafe { mock.call((#(#arg_idents),*)) },
			    faux::Mock::OnceSafe(mock) => {
				// make all the inputs have a static lifetime
				// needed to allow the Mock::OnceUnsafe branch to exist
				let input: (#(#arg_types),*) = unsafe {
				    std::mem::transmute((#(#arg_idents),*))
				};
				mock.call(input)
			    },
			}
		    }
		};
		quote! {{
                    match self {
			// not a mock; proxy to real instance
			#ty(faux::MaybeFaux::Real(r)) => r.#ident(#(#arg_idents),*),
			// not allowed; panic at runtime
			#ty(faux::MaybeFaux::Faux(q)) => {
			    #call_mock
			},
                    }
                }}
	    };

	    // wrap inside MaybeFaux if we are returning ourselves
	    if returns_self {
		block = quote! {{ #ty(faux::MaybeFaux::Real(#block)) }}
	    }

            m.block = syn::parse2(block).unwrap();

	    // return _when_{} methods for all mocked methods
            if is_method && !is_private {
                let mock_ident = syn::Ident::new(
                    &format!("_when_{}", ident),
                    proc_macro2::Span::call_site(),
                );
		let empty = Box::new( syn::parse2(quote! { () }) .unwrap());
		let output = match output {
		    syn::ReturnType::Default => &empty,
		    syn::ReturnType::Type(_, ty) => ty,
		};
                let tokens = quote! {
                    pub fn #mock_ident(&mut self) -> faux::When<(#(#arg_types),*), #output> {
			use std::any::Any as _;
			match &mut self.0 {
			    faux::MaybeFaux::Faux(faux) => faux::When::new(
				#ty::#ident.type_id(),
				faux.get_mut().unwrap()
			    ),
			    faux::MaybeFaux::Real(_) => panic!("not allowed to mock a real instance!"),
			}
		    }
		};

                Some(syn::parse2(tokens).unwrap())
            } else {
                None
            }
        })
        .collect();

    impl_block.items.append(&mut when_methods);

    let mod_ident = syn::Ident::new(
        &format!("_faux_real_impl_{}", ident),
        proc_macro2::Span::call_site(),
    );

    let first_path = &original_struct.path.segments.first().unwrap().ident;

    let alias_path = if *first_path == syn::Ident::new("crate", first_path.span()) {
        quote! { #original_struct }
    } else {
        quote! { super::#original_struct }
    };

    TokenStream::from(quote! {
    #impl_block

    mod #mod_ident {
            use super::*;

            type #ty = #alias_path;

            #original
    }
    })
}

fn method_args(method: &mut syn::ImplItemMethod) -> Vec<(syn::Ident, syn::Type)> {
    method
        .sig
        .inputs
        .iter_mut()
        .filter_map(|a| match a {
            syn::FnArg::Typed(arg) => Some(arg),
            _ => None,
        })
        .enumerate()
        .map(|(index, arg)| {
            let ident = syn::Ident::new(&format!("_x{}", index), proc_macro2::Span::call_site());
            arg.pat = Box::new(syn::Pat::Ident(syn::PatIdent {
                attrs: vec![],
                by_ref: None,
                mutability: None,
                subpat: None,
                ident: ident.clone(),
            }));
            (ident, *arg.ty.clone())
        })
        .collect()
}

#[proc_macro_hack]
pub fn when(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let expr = syn::parse_macro_input!(input as syn::ExprField);
    let base = expr.base;
    let method = match expr.member {
        syn::Member::Named(ident) => ident,
        syn::Member::Unnamed(_) => panic!("not a method call"),
    };
    let when = syn::Ident::new(&format!("_when_{}", method), proc_macro2::Span::call_site());

    TokenStream::from(quote!( { #base.#when() }))
}

fn original_struct_ident(original: &syn::Ident) -> syn::Ident {
    syn::Ident::new(&format!("_FauxOriginal_{}", original), original.span())
}

fn publicize_methods(impl_block: &mut syn::ItemImpl) {
    impl_block
        .items
        .iter_mut()
        .filter_map(|item| match item {
            syn::ImplItem::Method(m) => Some(m),
            _ => None,
        })
        .for_each(|mut method| {
            method.vis = syn::parse2(quote! { pub }).unwrap();
        });
}