Debian Codegraph @

src/mock_function.rs

raw symbols SCIP
1 // vim: tw=80
2 use proc_macro2::{Span, TokenStream};
3 use quote::{ToTokens, format_ident, quote};
4 use syn::{
5 *,
6 punctuated::Punctuated,
7 spanned::Spanned
8 };
9
10
11 use crate::{
12 AttrFormatter,
13 HashSet,
14 compile_error,
15 concretize_args,
16 declosurefy,
17 expectation_visibility,
18 gen_keyid,
19 is_concretize,
20 lifetimes_to_generic_params,
21 lifetimes_to_generics,
22 merge_generics,
23 pat_is_self,
24 split_lifetimes,
25 staticize,
26 supersuperfy,
27 supersuperfy_generics,
28 };
29
30 /// Convert a trait object reference into a reference to a Boxed trait
31 ///
32 /// # Returns
33 ///
34 /// Returns `true` if it was necessary to box the type.
35 fn dedynify(ty: &mut Type) -> bool {
36 if let Type::Reference(ref mut tr) = ty {
37 if let Type::TraitObject(ref tto) = tr.elem.as_ref() {
38 if let Some(lt) = &tr.lifetime {
39 if lt.ident == "static" {
40 // For methods that return 'static references, the user can
41 // usually actually supply one, unlike nonstatic references.
42 // dedynify is unneeded and harmful in such cases.
43 //
44 // But we do need to add parens to prevent parsing errors
45 // when methods like returning add a `+ Send` to the output
46 // type.
47 *tr.elem = parse2(quote!((#tto))).unwrap();
48 return false;
49 }
50 }
51
52 *tr.elem = parse2(quote!(Box<#tto>)).unwrap();
53 return true;
54 }
55 }
56 false
57 }
58
59 /// Convert a special reference type like "&str" into a reference to its owned
60 /// type like "&String".
61 fn destrify(ty: &mut Type) {
62 if let Type::Reference(ref mut tr) = ty {
63 if let Some(lt) = &tr.lifetime {
64 if lt.ident == "static" {
65 // For methods that return 'static references, the user can
66 // usually actually supply one, unlike nonstatic references.
67 // destrify is unneeded and harmful in such cases.
68 return;
69 }
70 }
71
72 let path_ty: TypePath = parse2(quote!(Path)).unwrap();
73 let pathbuf_ty: Type = parse2(quote!(::std::path::PathBuf)).unwrap();
74
75 let str_ty: TypePath = parse2(quote!(str)).unwrap();
76 let string_ty: Type = parse2(quote!(::std::string::String)).unwrap();
77
78 let cstr_ty: TypePath = parse2(quote!(CStr)).unwrap();
79 let cstring_ty: Type = parse2(quote!(::std::ffi::CString)).unwrap();
80
81 let osstr_ty: TypePath = parse2(quote!(OsStr)).unwrap();
82 let osstring_ty: Type = parse2(quote!(::std::ffi::OsString)).unwrap();
83
84 match tr.elem.as_ref() {
85 Type::Path(ref path) if *path == cstr_ty =>
86 *tr.elem = cstring_ty,
87 Type::Path(ref path) if *path == osstr_ty =>
88 *tr.elem = osstring_ty,
89 Type::Path(ref path) if *path == path_ty =>
90 *tr.elem = pathbuf_ty,
91 Type::Path(ref path) if *path == str_ty =>
92 *tr.elem = string_ty,
93 Type::Slice(ts) => {
94 let inner = (*ts.elem).clone();
95 let mut segments = Punctuated::new();
96 segments.push(format_ident!("std").into());
97 segments.push(format_ident!("vec").into());
98 let mut v: PathSegment = format_ident!("Vec").into();
99 let mut abga_args = Punctuated::new();
100 abga_args.push(GenericArgument::Type(inner));
101 v.arguments = PathArguments::AngleBracketed(
102 AngleBracketedGenericArguments {
103 colon2_token: None,
104 lt_token: Token![<](Span::call_site()),
105 args: abga_args,
106 gt_token: Token![>](Span::call_site()),
107 }
108 );
109 segments.push(v);
110
111 *tr.elem = Type::Path(TypePath {
112 qself: None,
113 path: Path {
114 leading_colon: Some(Token![::](Span::call_site())),
115 segments
116 }
117 });
118 },
119 _ => (), // Nothing to do
120 };
121 }
122 }
123
124 /// Return the owned version of the input.
125 fn ownify(ty: &Type) -> Type {
126 if let Type::Reference(ref tr) = &ty {
127 if tr.lifetime.as_ref().map_or(false, |lt| lt.ident == "static")
128 {
129 // Just a static expectation
130 ty.clone()
131 } else {
132 *tr.elem.clone()
133 }
134 } else {
135 ty.clone()
136 }
137 }
138
139 /// Add Send + Sync to a where clause
140 fn send_syncify(wc: &mut Option<WhereClause>, bounded_ty: Type) {
141 let mut bounds = Punctuated::new();
142 bounds.push(TypeParamBound::Trait(TraitBound {
143 paren_token: None,
144 modifier: TraitBoundModifier::None,
145 lifetimes: None,
146 path: Path::from(format_ident!("Send"))
147 }));
148 bounds.push(TypeParamBound::Trait(TraitBound {
149 paren_token: None,
150 modifier: TraitBoundModifier::None,
151 lifetimes: None,
152 path: Path::from(format_ident!("Sync"))
153 }));
154 if wc.is_none() {
155 *wc = Some(WhereClause {
156 where_token: <Token![where]>::default(),
157 predicates: Punctuated::new()
158 });
159 }
160 wc.as_mut().unwrap()
161 .predicates.push(
162 WherePredicate::Type(
163 PredicateType {
164 lifetimes: None,
165 bounded_ty,
166 colon_token: Default::default(),
167 bounds
168 }
169 )
170 );
171 }
172
173 /// Build a MockFunction.
174 #[derive(Clone, Copy, Debug)]
175 pub(crate) struct Builder<'a> {
176 attrs: &'a [Attribute],
177 call_levels: Option<usize>,
178 concretize: bool,
179 levels: usize,
180 parent: Option<&'a Ident>,
181 sig: &'a Signature,
182 struct_: Option<&'a Ident>,
183 struct_generics: Option<&'a Generics>,
184 trait_: Option<&'a Ident>,
185 vis: &'a Visibility
186 }
187
188 impl<'a> Builder<'a> {
189 pub fn attrs(&mut self, attrs: &'a[Attribute]) -> &mut Self {
190 self.attrs = attrs;
191 if attrs.iter()
192 .any(is_concretize)
193 {
194 self.concretize = true;
195 }
196 self
197 }
198
199 pub fn build(self) -> MockFunction {
200 let mut argnames = Vec::new();
201 let mut argty = Vec::new();
202 let mut is_static = true;
203 let mut predexprs = Vec::new();
204 let mut predty = Vec::new();
205 let mut refpredty = Vec::new();
206
207 let (mut declosured_generics, declosured_inputs, call_exprs, sig) =
208 if self.concretize {
209 let (x, y, z, sig) = concretize_args(&self.sig.generics, self.sig);
210 (x, y, z, sig)
211 } else {
212 let (x, y, z) = declosurefy(&self.sig.generics, &self.sig.inputs);
213 (x, y, z, self.sig.clone())
214 };
215 // TODO: make concretize and declosurefy work for the same function
216
217 for fa in declosured_inputs.iter() {
218 if let FnArg::Typed(pt) = fa {
219 let argname = (*pt.pat).clone();
220 assert!(!pat_is_self(&argname));
221 let aty = supersuperfy(&pt.ty, self.levels);
222 if let Type::Reference(ref tr) = aty {
223 predexprs.push(quote!(#argname));
224 predty.push((*tr.elem).clone());
225 let tr2 = Type::Reference(TypeReference {
226 and_token: tr.and_token,
227 lifetime: None,
228 mutability: None,
229 elem: tr.elem.clone()
230 });
231 refpredty.push(tr2);
232 } else {
233 predexprs.push(quote!(&#argname));
234 predty.push(aty.clone());
235 let tr = TypeReference {
236 and_token: Token![&](Span::call_site()),
237 lifetime: None,
238 mutability: None,
239 elem: Box::new(aty.clone())
240 };
241 refpredty.push(Type::Reference(tr));
242 };
243 argnames.push(argname);
244 argty.push(aty.clone());
245 } else {
246 is_static = false;
247 }
248 }
249 let (output, boxed) = match self.sig.output {
250 ReturnType::Default => (
251 Type::Tuple(TypeTuple {
252 paren_token: token::Paren::default(),
253 elems: Punctuated::new(),
254 }),
255 false,
256 ),
257 ReturnType::Type(_, ref ty) => {
258 let mut output_ty = supersuperfy(ty, self.levels);
259 destrify(&mut output_ty);
260 let boxed = dedynify(&mut output_ty);
261 (output_ty, boxed)
262 }
263 };
264 supersuperfy_generics(&mut declosured_generics, self.levels);
265 let owned_output = ownify(&output);
266 let mut return_ref = false;
267 let mut return_refmut = false;
268 if let Type::Reference(ref tr) = &output {
269 if tr.lifetime.as_ref().map_or(true, |lt| lt.ident != "static")
270 {
271 if tr.mutability.is_none() {
272 return_ref = true;
273 } else {
274 return_refmut = true;
275 }
276 }
277 };
278 if is_static && (return_ref || return_refmut) {
279 compile_error(self.sig.span(),
280 "Mockall cannot mock static methods that return non-'static references. It's unclear what the return value's lifetime should be.");
281 }
282 let struct_generics = self.struct_generics.cloned()
283 .unwrap_or_default();
284 let (type_generics, salifetimes, srlifetimes) = split_lifetimes(
285 struct_generics.clone(),
286 &declosured_inputs,
287 &ReturnType::Type(<Token![->]>::default(),
288 Box::new(owned_output.clone()))
289 );
290 let srltg = lifetimes_to_generics(&srlifetimes);
291 let (call_generics, malifetimes, mrlifetimes) = split_lifetimes(
292 declosured_generics,
293 &declosured_inputs,
294 &ReturnType::Type(<Token![->]>::default(),
295 Box::new(owned_output.clone()))
296 );
297 let mrltg = lifetimes_to_generics(&mrlifetimes);
298 let cgenerics = merge_generics(&type_generics, &call_generics);
299 let egenerics = merge_generics(
300 &merge_generics(&cgenerics, &srltg),
301 &mrltg);
302 let alifetimes = salifetimes.into_iter()
303 .collect::<HashSet<LifetimeParam>>()
304 .union(&malifetimes.into_iter().collect::<HashSet<_>>())
305 .cloned()
306 .collect();
307
308 let fn_params = egenerics.type_params()
309 .map(|tp| tp.ident.clone())
310 .collect();
311 let call_levels = self.call_levels.unwrap_or(self.levels);
312
313 MockFunction {
314 alifetimes,
315 argnames,
316 argty,
317 attrs: self.attrs.to_vec(),
318 call_exprs,
319 call_generics,
320 call_vis: expectation_visibility(self.vis, call_levels),
321 concretize: self.concretize,
322 egenerics,
323 cgenerics,
324 fn_params,
325 is_static,
326 mod_ident: self.parent.unwrap_or(&Ident::new("FIXME", Span::call_site())).clone(),
327 output,
328 owned_output,
329 boxed,
330 predexprs,
331 predty,
332 refpredty,
333 return_ref,
334 return_refmut,
335 sig,
336 struct_: self.struct_.cloned(),
337 struct_generics,
338 trait_: self.trait_.cloned(),
339 type_generics,
340 privmod_vis: expectation_visibility(self.vis, self.levels)
341 }
342 }
343
344 /// How many levels of modules beneath the original function this one is
345 /// nested.
346 pub fn call_levels(&mut self, levels: usize) -> &mut Self {
347 self.call_levels = Some(levels);
348 self
349 }
350
351 /// How many levels of modules beneath the original function this one's
352 /// private module is nested.
353 pub fn levels(&mut self, levels: usize) -> &mut Self {
354 self.levels = levels;
355 self
356 }
357
358 /// # Arguments
359 ///
360 /// * sig: The signature of the mockable function
361 /// * v: The visibility of the mockable function
362 pub fn new(sig: &'a Signature, vis: &'a Visibility) -> Self {
363 Builder {
364 attrs: &[],
365 concretize: false,
366 levels: 0,
367 call_levels: None,
368 parent: None,
369 sig,
370 struct_: None,
371 struct_generics: None,
372 trait_: None,
373 vis
374 }
375 }
376
377 /// Supply the name of the parent module
378 pub fn parent(&mut self, ident: &'a Ident) -> &mut Self {
379 self.parent = Some(ident);
380 self
381 }
382
383 /// Supply the name of the parent struct, if any
384 pub fn struct_(&mut self, ident: &'a Ident) -> &mut Self {
385 self.struct_= Some(ident);
386 self
387 }
388
389 /// Supply the Generics of the parent struct, if any
390 pub fn struct_generics(&mut self, generics: &'a Generics) -> &mut Self {
391 self.struct_generics = Some(generics);
392 self
393 }
394
395 /// Supply the name of the method's trait, if any
396 pub fn trait_(&mut self, ident: &'a Ident) -> &mut Self {
397 self.trait_ = Some(ident);
398 self
399 }
400 }
401
402 #[derive(Clone)]
403 pub(crate) struct MockFunction {
404 /// Lifetimes of the mocked method that relate to the arguments but not the
405 /// return value
406 alifetimes: Punctuated<LifetimeParam, token::Comma>,
407 /// Names of the method arguments
408 argnames: Vec<Pat>,
409 /// Types of the method arguments
410 argty: Vec<Type>,
411 /// any attributes on the original function, like #[inline]
412 pub attrs: Vec<Attribute>,
413 /// Expressions that should be used for Expectation::call's arguments
414 call_exprs: Vec<TokenStream>,
415 /// Generics used for the expectation call
416 call_generics: Generics,
417 /// Visibility of the mock function itself
418 call_vis: Visibility,
419 /// Are we turning generic arguments into concrete trait objects?
420 concretize: bool,
421 /// Generics of the Expectation object
422 egenerics: Generics,
423 /// Generics of the Common object
424 cgenerics: Generics,
425 /// The mock function's generic types as a list of types
426 fn_params: Vec<Ident>,
427 /// Is this for a static method or free function?
428 is_static: bool,
429 /// name of the function's parent module
430 mod_ident: Ident,
431 /// Output type of the Method, supersuperfied.
432 output: Type,
433 /// Owned version of the output type of the Method, supersuperfied.
434 ///
435 /// If the real output type is a non-'static reference, then it will differ
436 /// from this field.
437 owned_output: Type,
438 /// True if the `owned_type` is boxed by `Box<>`.
439 boxed: bool,
440 /// Expressions that create the predicate arguments from the call arguments
441 predexprs: Vec<TokenStream>,
442 /// Types used for Predicates. Will be almost the same as args, but every
443 /// type will be a non-reference type.
444 predty: Vec<Type>,
445 /// Does the function return a non-'static reference?
446 return_ref: bool,
447 /// Does the function return a mutable reference?
448 return_refmut: bool,
449 /// References to every type in `predty`.
450 refpredty: Vec<Type>,
451 /// The signature of the mockable function
452 sig: Signature,
453 /// Name of the parent structure, if any
454 struct_: Option<Ident>,
455 /// Generics of the parent structure
456 struct_generics: Generics,
457 /// Name of this method's trait, if the method comes from a trait
458 trait_: Option<Ident>,
459 /// Type generics of the mock structure
460 type_generics: Generics,
461 /// Visibility of the expectation and its methods
462 privmod_vis: Visibility
463 }
464
465 impl MockFunction {
466 /// Return the mock function itself
467 ///
468 /// # Arguments
469 ///
470 /// * `modname`: Name of the parent struct's private module
471 // Supplying modname is an unfortunately hack. Ideally MockFunction
472 // wouldn't need to know that.
473 pub fn call(&self, modname: Option<&Ident>) -> impl ToTokens {
474 let attrs = AttrFormatter::new(&self.attrs)
475 .must_use(true)
476 .format();
477 let call_exprs = &self.call_exprs;
478 let (_, tg, _) = if self.is_method_generic() || self.is_static() {
479 &self.egenerics
480 } else {
481 &self.call_generics
482 }.split_for_impl();
483 let tbf = tg.as_turbofish();
484 let name = self.name();
485 let desc = self.desc();
486 let no_match_msg = quote!(std::format!(
487 "{}: No matching expectation found", #desc));
488 let sig = &self.sig;
489 let (vis, dead_code) = if self.trait_.is_some() {
490 (&Visibility::Inherited, quote!())
491 } else {
492 let dead_code = if let Visibility::Inherited = self.call_vis {
493 // This private method may be a helper only used by the struct's
494 // other methods, which we are mocking. If so, the mock method
495 // will be dead code. But we can't simply eliminate it, because
496 // it might also be used by other code in the same module.
497 quote!(#[allow(dead_code)])
498 } else {
499 quote!()
500 };
501 (&self.call_vis, dead_code)
502 };
503 // Add #[no_mangle] attribute to preserve the function name
504 // as-is, without mangling, for compatibility with C functions.
505 let no_mangle = if let Some(ref abi) = self.sig.abi {
506 if let Some(ref name) = abi.name {
507 if name.value().ne("Rust") {
508 quote!(#[no_mangle])
509 } else {
510 quote!()
511 }
512 } else {
513 // This is the same as extern "C"
514 quote!(#[no_mangle])
515 }
516 } else {
517 quote!()
518 };
519 let substruct_obj: TokenStream = if let Some(trait_) = &self.trait_ {
520 let ident = format_ident!("{}_expectations", trait_);
521 quote!(#ident.)
522 } else {
523 quote!()
524 };
525 let call = if self.return_refmut {
526 Ident::new("call_mut", Span::call_site())
527 } else {
528 Ident::new("call", Span::call_site())
529 };
530 let mut deref = quote!();
531 if self.boxed {
532 if self.return_ref {
533 deref = quote!(&**);
534 } else if self.return_refmut {
535 deref = quote!(&mut **);
536 }
537 }
538 if self.is_static {
539 let outer_mod_path = self.outer_mod_path(modname);
540 quote!(
541 // Don't add a doc string. The original is included in #attrs
542 #(#attrs)*
543 #dead_code
544 #no_mangle
545 #vis #sig {
546 use ::mockall::{ViaDebug, ViaNothing};
547 let no_match_msg = #no_match_msg;
548 #deref {
549 let __mockall_guard = #outer_mod_path::get_expectations()
550 .lock().unwrap();
551 /*
552 * TODO: catch panics, then gracefully release the mutex
553 * so it won't be poisoned. This requires bounding any
554 * generic parameters with UnwindSafe
555 */
556 /* std::panic::catch_unwind(|| */
557 __mockall_guard.#call #tbf(#(#call_exprs,)*)
558 /*)*/
559 }.expect(&no_match_msg)
560 }
561 )
562 } else {
563 quote!(
564 // Don't add a doc string. The original is included in #attrs
565 #(#attrs)*
566 #dead_code
567 #no_mangle
568 #vis #sig {
569 use ::mockall::{ViaDebug, ViaNothing};
570 let no_match_msg = #no_match_msg;
571 #deref self.#substruct_obj #name.#call #tbf(#(#call_exprs,)*)
572 .expect(&no_match_msg)
573 }
574
575 )
576 }
577 }
578
579 /// Return this method's contribution to its parent's checkpoint method
580 pub fn checkpoint(&self) -> impl ToTokens {
581 let attrs = AttrFormatter::new(&self.attrs)
582 .doc(false)
583 .format();
584 let inner_mod_ident = self.inner_mod_ident();
585 if self.is_static {
586 quote!(
587 #(#attrs)*
588 {
589 let __mockall_timeses = #inner_mod_ident::get_expectations().lock()
590 .unwrap()
591 .checkpoint()
592 .collect::<Vec<_>>();
593 }
594 )
595 } else {
596 let name = &self.name();
597 quote!(#(#attrs)* { self.#name.checkpoint(); })
598 }
599 }
600
601 /// Return a function that creates a Context object for this function
602 ///
603 /// # Arguments
604 ///
605 /// * `modname`: Name of the parent struct's private module
606 // Supplying modname is an unfortunately hack. Ideally MockFunction
607 // wouldn't need to know that.
608 pub fn context_fn(&self, modname: Option<&Ident>) -> impl ToTokens {
609 let attrs = AttrFormatter::new(&self.attrs)
610 .doc(false)
611 .format();
612 let context_docstr = format!("Create a [`Context`]({}{}/struct.Context.html) for mocking the `{}` method",
613 modname.map(|m| format!("{m}/")).unwrap_or_default(),
614 self.inner_mod_ident(),
615 self.name());
616 let context_ident = format_ident!("{}_context", self.name());
617 let (_, tg, _) = self.type_generics.split_for_impl();
618 let outer_mod_path = self.outer_mod_path(modname);
619 let v = &self.call_vis;
620 quote!(
621 #(#attrs)*
622 #[doc = #context_docstr]
623 #v fn #context_ident() -> #outer_mod_path::Context #tg
624 {
625 #outer_mod_path::Context::default()
626 }
627 )
628 }
629
630 /// Generate a code fragment that will print a description of the invocation
631 fn desc(&self) -> impl ToTokens {
632 let argnames = &self.argnames;
633 let name = if let Some(s) = &self.struct_ {
634 format!("{}::{}", s, self.sig.ident)
635 } else {
636 format!("{}::{}", self.mod_ident, self.sig.ident)
637 };
638 let fields = vec!["{:?}"; argnames.len()].join(", ");
639 let fstr = format!("{name}({fields})");
640 quote!(std::format!(#fstr, #((&&::mockall::ArgPrinter(&#argnames)).debug_string()),*))
641 }
642
643 /// Generate code for the expect_ method
644 ///
645 /// # Arguments
646 ///
647 /// * `modname`: Name of the parent struct's private module
648 /// * `self_args`: If supplied, these are the
649 /// AngleBracketedGenericArguments of the self type of the
650 /// trait impl. e.g. The `T` in `impl Foo for Bar<T>`.
651 // Supplying modname is an unfortunately hack. Ideally MockFunction
652 // wouldn't need to know that.
653 pub fn expect(&self, modname: &Ident, self_args: Option<&PathArguments>)
654 -> impl ToTokens
655 {
656 let attrs = AttrFormatter::new(&self.attrs)
657 .doc(false)
658 .format();
659 let name = self.name();
660 let expect_ident = format_ident!("expect_{}", name);
661 let expectation_obj = self.expectation_obj(self_args);
662 let funcname = &self.sig.ident;
663 let (_, tg, _) = if self.is_method_generic() {
664 &self.egenerics
665 } else {
666 &self.call_generics
667 }.split_for_impl();
668 let (ig, _, wc) = self.call_generics.split_for_impl();
669 let mut wc = wc.cloned();
670 if self.is_method_generic() && (self.return_ref || self.return_refmut) {
671 // Add Senc + Sync, required for downcast, since Expectation
672 // stores an Option<#owned_output>
673 send_syncify(&mut wc, self.owned_output.clone());
674 }
675 let tbf = tg.as_turbofish();
676 let vis = &self.call_vis;
677
678 #[cfg(not(feature = "nightly_derive"))]
679 let must_use = quote!(#[must_use =
680 "Must set return value when not using the \"nightly\" feature"
681 ]);
682 #[cfg(feature = "nightly_derive")]
683 let must_use = quote!();
684
685 let substruct_obj = if let Some(trait_) = &self.trait_ {
686 let ident = format_ident!("{trait_}_expectations");
687 quote!(#ident.)
688 } else {
689 quote!()
690 };
691 let docstr = format!("Create an [`Expectation`]({}/{}/struct.Expectation.html) for mocking the `{}` method",
692 modname, self.inner_mod_ident(), funcname);
693 quote!(
694 #must_use
695 #[doc = #docstr]
696 #(#attrs)*
697 #vis fn #expect_ident #ig(&mut self)
698 -> &mut #modname::#expectation_obj
699 #wc
700 {
701 self.#substruct_obj #name.expect #tbf()
702 }
703 )
704 }
705
706 /// Return the name of this function's expecation object
707 fn expectation_obj(&self, self_args: Option<&PathArguments>)
708 -> impl ToTokens
709 {
710 let inner_mod_ident = self.inner_mod_ident();
711 if let Some(PathArguments::AngleBracketed(abga)) = self_args {
712 // staticize any lifetimes that might be present in the Expectation
713 // object but not in the self args. These come from the method's
714 // return type.
715 let mut abga2 = abga.clone();
716 for _ in self.egenerics.lifetimes() {
717 let lt = Lifetime::new("'static", Span::call_site());
718 let la = GenericArgument::Lifetime(lt);
719 abga2.args.insert(0, la);
720 }
721 assert!(!self.is_method_generic(),
722 "specific impls with generic methods are TODO");
723 quote!(#inner_mod_ident::Expectation #abga2)
724 } else {
725 // staticize any lifetimes. This is necessary for methods that
726 // return non-static types, because the Expectation itself must be
727 // 'static.
728 let segenerics = staticize(&self.egenerics);
729 let (_, tg, _) = segenerics.split_for_impl();
730 quote!(#inner_mod_ident::Expectation #tg)
731 }
732 }
733
734 /// Return the name of this function's expecations object
735 pub fn expectations_obj(&self) -> impl ToTokens {
736 let inner_mod_ident = self.inner_mod_ident();
737 if self.is_method_generic() {
738 quote!(#inner_mod_ident::GenericExpectations)
739 } else {
740 quote!(#inner_mod_ident::Expectations)
741 }
742 }
743
744 pub fn field_definition(&self, modname: Option<&Ident>) -> TokenStream {
745 let name = self.name();
746 let attrs = AttrFormatter::new(&self.attrs)
747 .doc(false)
748 .format();
749 let expectations_obj = &self.expectations_obj();
750 if self.is_method_generic() {
751 quote!(#(#attrs)* #name: #modname::#expectations_obj)
752 } else {
753 // staticize any lifetimes. This is necessary for methods that
754 // return non-static types, because the Expectation itself must be
755 // 'static.
756 let segenerics = staticize(&self.egenerics);
757 let (_, tg, _) = segenerics.split_for_impl();
758 quote!(#(#attrs)* #name: #modname::#expectations_obj #tg)
759 }
760 }
761
762 /// Human-readable name of the mock function
763 fn funcname(&self) -> String {
764 if let Some(si) = &self.struct_ {
765 format!("{}::{}", si, self.name())
766 } else {
767 format!("{}", self.name())
768 }
769 }
770
771 fn hrtb(&self) -> Option<BoundLifetimes> {
772 if self.alifetimes.is_empty() {
773 None
774 } else {
775 let lifetimes = lifetimes_to_generic_params(&self.alifetimes);
776 Some(BoundLifetimes {
777 lifetimes,
778 lt_token: <Token![<]>::default(),
779 gt_token: <Token![>]>::default(),
780 .. Default::default()
781 })
782 }
783 }
784
785 fn is_expectation_generic(&self) -> bool {
786 self.egenerics.params.iter().any(|p| {
787 matches!(p, GenericParam::Type(_))
788 }) || self.egenerics.where_clause.is_some()
789 }
790
791 /// Is the mock method generic (as opposed to a non-generic method of a
792 /// generic mock struct)?
793 pub fn is_method_generic(&self) -> bool {
794 self.call_generics.params.iter().any(|p| {
795 matches!(p, GenericParam::Type(_))
796 }) || self.call_generics.where_clause.is_some()
797 }
798
799 fn outer_mod_path(&self, modname: Option<&Ident>) -> Path {
800 let mut path = if let Some(m) = modname {
801 Path::from(PathSegment::from(m.clone()))
802 } else {
803 Path { leading_colon: None, segments: Punctuated::new() }
804 };
805 path.segments.push(PathSegment::from(self.inner_mod_ident()));
806 path
807 }
808
809 fn inner_mod_ident(&self) -> Ident {
810 format_ident!("__{}", &self.name())
811 }
812
813 pub fn is_static(&self) -> bool {
814 self.is_static
815 }
816
817 pub fn name(&self) -> &Ident {
818 &self.sig.ident
819 }
820
821 /// Generate code for this function's private module
822 pub fn priv_module(&self) -> impl ToTokens {
823 let attrs = AttrFormatter::new(&self.attrs)
824 .doc(false)
825 .format();
826 let common = &Common{f: self};
827 let context = &Context{f: self};
828 let expectation: Box<dyn ToTokens> = if self.return_ref {
829 Box::new(RefExpectation{f: self})
830 } else if self.return_refmut {
831 Box::new(RefMutExpectation{f: self})
832 } else {
833 Box::new(StaticExpectation{f: self})
834 };
835 let expectations: Box<dyn ToTokens> = if self.return_ref {
836 Box::new(RefExpectations{f: self})
837 } else if self.return_refmut {
838 Box::new(RefMutExpectations{f: self})
839 } else {
840 Box::new(StaticExpectations{f: self})
841 };
842 let generic_expectations = GenericExpectations{f: self};
843 let guard: Box<dyn ToTokens> = if self.is_expectation_generic() {
844 Box::new(GenericExpectationGuard{f: self})
845 } else {
846 Box::new(ConcreteExpectationGuard{f: self})
847 };
848 let matcher = &Matcher{f: self};
849 let std_mutexguard = if self.is_static {
850 quote!(use ::std::sync::MutexGuard;)
851 } else {
852 quote!()
853 };
854 let inner_mod_ident = self.inner_mod_ident();
855 let rfunc: Box<dyn ToTokens> = if self.return_ref {
856 Box::new(RefRfunc{f: self})
857 } else if self.return_refmut {
858 Box::new(RefMutRfunc{f: self})
859 } else {
860 Box::new(StaticRfunc{f: self})
861 };
862 quote!(
863 #(#attrs)*
864 #[allow(missing_docs)]
865 #[allow(clippy::too_many_arguments, clippy::indexing_slicing)]
866 pub mod #inner_mod_ident {
867 use super::*;
868 use ::mockall::CaseTreeExt;
869 #std_mutexguard
870 use ::std::{
871 boxed::Box,
872 mem,
873 ops::{DerefMut, Range},
874 sync::Mutex,
875 vec::Vec,
876 };
877 #rfunc
878 #matcher
879 #common
880 #expectation
881 #expectations
882 #generic_expectations
883 #guard
884 #context
885 }
886 )
887 }
888 }
889
890 /// Holds parts of the expectation that are common for all output types
891 struct Common<'a> {
892 f: &'a MockFunction
893 }
894
895 impl<'a> ToTokens for Common<'a> {
896 fn to_tokens(&self, tokens: &mut TokenStream) {
897 let argnames = &self.f.argnames;
898 let predty = &self.f.predty;
899 let hrtb = self.f.hrtb();
900 let funcname = self.f.funcname();
901 let (ig, tg, wc) = self.f.cgenerics.split_for_impl();
902 let lg = lifetimes_to_generics(&self.f.alifetimes);
903 let refpredty = &self.f.refpredty;
904 let with_generics_idents = (0..self.f.predty.len())
905 .map(|i| format_ident!("MockallMatcher{i}"))
906 .collect::<Vec<_>>();
907 let with_generics = with_generics_idents.iter()
908 .zip(self.f.predty.iter())
909 .map(|(id, mt)|
910 quote!(#id: #hrtb ::mockall::Predicate<#mt> + Send + 'static, )
911 ).collect::<TokenStream>();
912 let with_args = self.f.argnames.iter()
913 .zip(with_generics_idents.iter())
914 .map(|(argname, id)| quote!(#argname: #id, ))
915 .collect::<TokenStream>();
916 let boxed_withargs = argnames.iter()
917 .map(|aa| quote!(Box::new(#aa), ))
918 .collect::<TokenStream>();
919 let with_method = if self.f.concretize {
920 quote!(
921 // No `with` method when concretizing generics
922 )
923 } else {
924 quote!(
925 fn with<#with_generics>(&mut self, #with_args)
926 {
927 let mut __mockall_guard = self.matcher.lock().unwrap();
928 *__mockall_guard.deref_mut() =
929 Matcher::Pred(Box::new((#boxed_withargs)));
930 }
931 )
932 };
933
934 quote!(
935 /// Holds the stuff that is independent of the output type
936 struct Common #ig #wc {
937 matcher: Mutex<Matcher #tg>,
938 seq_handle: Option<::mockall::SeqHandle>,
939 times: ::mockall::Times
940 }
941
942 impl #ig std::default::Default for Common #tg #wc
943 {
944 fn default() -> Self {
945 Common {
946 matcher: Mutex::new(Matcher::default()),
947 seq_handle: None,
948 times: ::mockall::Times::default()
949 }
950 }
951 }
952
953 impl #ig Common #tg #wc {
954 fn call(&self, desc: &str) {
955 self.times.call()
956 .unwrap_or_else(|m| {
957 let desc = std::format!(
958 "{}", self.matcher.lock().unwrap());
959 panic!("{}: Expectation({}) {}", #funcname, desc,
960 m);
961 });
962 self.verify_sequence(desc);
963 if ::mockall::ExpectedCalls::TooFew != self.times.is_satisfied() {
964 self.satisfy_sequence()
965 }
966 }
967
968 fn in_sequence(&mut self, __mockall_seq: &mut ::mockall::Sequence)
969 -> &mut Self
970 {
971 assert!(self.times.is_exact(),
972 "Only Expectations with an exact call count have sequences");
973 self.seq_handle = Some(__mockall_seq.next_handle());
974 self
975 }
976
977 fn is_done(&self) -> bool {
978 self.times.is_done()
979 }
980
981 #[allow(clippy::ptr_arg)]
982 fn matches #lg (&self, #( #argnames: &#predty, )*) -> bool {
983 self.matcher.lock().unwrap().matches(#(#argnames, )*)
984 }
985
986 /// Forbid this expectation from ever being called.
987 fn never(&mut self) {
988 self.times.never();
989 }
990
991 fn satisfy_sequence(&self) {
992 if let Some(__mockall_handle) = &self.seq_handle {
993 __mockall_handle.satisfy()
994 }
995 }
996
997 /// Expect this expectation to be called any number of times
998 /// contained with the given range.
999 fn times<MockallR>(&mut self, __mockall_r: MockallR)
1000 where MockallR: Into<::mockall::TimesRange>
1001 {
1002 self.times.times(__mockall_r)
1003 }
1004
1005 #with_method
1006
1007 fn withf<MockallF>(&mut self, __mockall_f: MockallF)
1008 where MockallF: #hrtb Fn(#( #refpredty, )*)
1009 -> bool + Send + 'static
1010 {
1011 let mut __mockall_guard = self.matcher.lock().unwrap();
1012 *__mockall_guard.deref_mut() =
1013 Matcher::Func(Box::new(__mockall_f));
1014 }
1015
1016 fn withf_st<MockallF>(&mut self, __mockall_f: MockallF)
1017 where MockallF: #hrtb Fn(#( #refpredty, )*)
1018 -> bool + 'static
1019 {
1020 let mut __mockall_guard = self.matcher.lock().unwrap();
1021 *__mockall_guard.deref_mut() =
1022 Matcher::FuncSt(
1023 ::mockall::Fragile::new(Box::new(__mockall_f))
1024 );
1025 }
1026
1027 fn verify_sequence(&self, desc: &str) {
1028 if let Some(__mockall_handle) = &self.seq_handle {
1029 __mockall_handle.verify(desc)
1030 }
1031 }
1032 }
1033
1034 impl #ig Drop for Common #tg #wc {
1035 fn drop(&mut self) {
1036 if !::std::thread::panicking() {
1037 let desc = std::format!(
1038 "{}", self.matcher.lock().unwrap());
1039 match self.times.is_satisfied() {
1040 ::mockall::ExpectedCalls::TooFew => {
1041 panic!("{}: Expectation({}) called {} time(s) which is fewer than expected {}",
1042 #funcname,
1043 desc,
1044 self.times.count(),
1045 self.times.minimum());
1046 },
1047 ::mockall::ExpectedCalls::TooMany => {
1048 panic!("{}: Expectation({}) called {} time(s) which is more than expected {}",
1049 #funcname,
1050 desc,
1051 self.times.count(),
1052 self.times.maximum());
1053 },
1054 _ => ()
1055 }
1056 }
1057 }
1058 }
1059 ).to_tokens(tokens);
1060 }
1061 }
1062
1063 /// Generates methods that are common for all Expectation types
1064 struct CommonExpectationMethods<'a> {
1065 f: &'a MockFunction
1066 }
1067
1068 impl<'a> ToTokens for CommonExpectationMethods<'a> {
1069 fn to_tokens(&self, tokens: &mut TokenStream) {
1070 let argnames = &self.f.argnames;
1071 let hrtb = self.f.hrtb();
1072 let lg = lifetimes_to_generics(&self.f.alifetimes);
1073 let predty = &self.f.predty;
1074 let with_generics_idents = (0..self.f.predty.len())
1075 .map(|i| format_ident!("MockallMatcher{i}"))
1076 .collect::<Vec<_>>();
1077 let with_generics = with_generics_idents.iter()
1078 .zip(self.f.predty.iter())
1079 .map(|(id, mt)|
1080 quote!(#id: #hrtb ::mockall::Predicate<#mt> + Send + 'static, )
1081 ).collect::<TokenStream>();
1082 let with_args = self.f.argnames.iter()
1083 .zip(with_generics_idents.iter())
1084 .map(|(argname, id)| quote!(#argname: #id, ))
1085 .collect::<TokenStream>();
1086 let v = &self.f.privmod_vis;
1087 let with_method = if self.f.concretize {
1088 quote!(
1089 // No `with` method when concretizing generics
1090 )
1091 } else {
1092 quote!(
1093 /// Set matching criteria for this Expectation.
1094 ///
1095 /// The matching predicate can be anything implemening the
1096 /// [`Predicate`](../../../mockall/trait.Predicate.html) trait. Only
1097 /// one matcher can be set per `Expectation` at a time.
1098 #v fn with<#with_generics>(&mut self, #with_args) -> &mut Self
1099 {
1100 self.common.with(#(#argnames, )*);
1101 self
1102 }
1103 )
1104 };
1105 quote!(
1106 /// Add this expectation to a
1107 /// [`Sequence`](../../../mockall/struct.Sequence.html).
1108 #v fn in_sequence(&mut self, __mockall_seq: &mut ::mockall::Sequence)
1109 -> &mut Self
1110 {
1111 self.common.in_sequence(__mockall_seq);
1112 self
1113 }
1114
1115 fn is_done(&self) -> bool {
1116 self.common.is_done()
1117 }
1118
1119 /// Validate this expectation's matcher.
1120 #[allow(clippy::ptr_arg)]
1121 fn matches #lg (&self, #(#argnames: &#predty, )*) -> bool {
1122 self.common.matches(#(#argnames, )*)
1123 }
1124
1125 /// Forbid this expectation from ever being called.
1126 #v fn never(&mut self) -> &mut Self {
1127 self.common.never();
1128 self
1129 }
1130
1131 /// Create a new, default, [`Expectation`](struct.Expectation.html)
1132 #v fn new() -> Self {
1133 Self::default()
1134 }
1135
1136 /// Expect this expectation to be called exactly once. Shortcut for
1137 /// [`times(1)`](#method.times).
1138 #v fn once(&mut self) -> &mut Self {
1139 self.times(1)
1140 }
1141
1142 /// Restrict the number of times that that this method may be called.
1143 ///
1144 /// The argument may be:
1145 /// * A fixed number: `.times(4)`
1146 /// * Various types of range:
1147 /// - `.times(5..10)`
1148 /// - `.times(..10)`
1149 /// - `.times(5..)`
1150 /// - `.times(5..=10)`
1151 /// - `.times(..=10)`
1152 /// * The wildcard: `.times(..)`
1153 #v fn times<MockallR>(&mut self, __mockall_r: MockallR) -> &mut Self
1154 where MockallR: Into<::mockall::TimesRange>
1155 {
1156 self.common.times(__mockall_r);
1157 self
1158 }
1159
1160 #with_method
1161
1162 /// Set a matching function for this Expectation.
1163 ///
1164 /// This is equivalent to calling [`with`](#method.with) with a
1165 /// function argument, like `with(predicate::function(f))`.
1166 #v fn withf<MockallF>(&mut self, __mockall_f: MockallF) -> &mut Self
1167 where MockallF: #hrtb Fn(#(&#predty, )*)
1168 -> bool + Send + 'static
1169 {
1170 self.common.withf(__mockall_f);
1171 self
1172 }
1173
1174 /// Single-threaded version of [`withf`](#method.withf).
1175 /// Can be used when the argument type isn't `Send`.
1176 #v fn withf_st<MockallF>(&mut self, __mockall_f: MockallF) -> &mut Self
1177 where MockallF: #hrtb Fn(#(&#predty, )*)
1178 -> bool + 'static
1179 {
1180 self.common.withf_st(__mockall_f);
1181 self
1182 }
1183 ).to_tokens(tokens);
1184 }
1185 }
1186
1187 /// Holds the moethods of the Expectations object that are common for all
1188 /// Expectation types
1189 struct CommonExpectationsMethods<'a> {
1190 f: &'a MockFunction
1191 }
1192
1193 impl<'a> ToTokens for CommonExpectationsMethods<'a> {
1194 fn to_tokens(&self, tokens: &mut TokenStream) {
1195 let (ig, tg, wc) = self.f.egenerics.split_for_impl();
1196 let v = &self.f.privmod_vis;
1197 quote!(
1198 /// A collection of [`Expectation`](struct.Expectations.html)
1199 /// objects. Users will rarely if ever use this struct directly.
1200 #[doc(hidden)]
1201 #v struct Expectations #ig ( Vec<Expectation #tg>) #wc;
1202
1203 impl #ig Expectations #tg #wc {
1204 /// Verify that all current expectations are satisfied and clear
1205 /// them.
1206 #v fn checkpoint(&mut self) -> std::vec::Drain<Expectation #tg>
1207 {
1208 self.0.drain(..)
1209 }
1210
1211 /// Create a new expectation for this method.
1212 #v fn expect(&mut self) -> &mut Expectation #tg
1213 {
1214 self.0.push(Expectation::default());
1215 let __mockall_l = self.0.len();
1216 &mut self.0[__mockall_l - 1]
1217 }
1218
1219 #v const fn new() -> Self {
1220 Self(Vec::new())
1221 }
1222 }
1223 impl #ig Default for Expectations #tg #wc
1224 {
1225 fn default() -> Self {
1226 Expectations::new()
1227 }
1228 }
1229 ).to_tokens(tokens);
1230 }
1231 }
1232
1233 /// The ExpectationGuard structure for static methods with no generic types
1234 struct ExpectationGuardCommonMethods<'a> {
1235 f: &'a MockFunction
1236 }
1237
1238 impl<'a> ToTokens for ExpectationGuardCommonMethods<'a> {
1239 fn to_tokens(&self, tokens: &mut TokenStream) {
1240 if !self.f.is_static {
1241 return;
1242 }
1243
1244 let argnames = &self.f.argnames;
1245 let argty = &self.f.argty;
1246 let (_, tg, _) = self.f.egenerics.split_for_impl();
1247 let keyid = gen_keyid(&self.f.egenerics);
1248 let expectations = if self.f.is_expectation_generic() {
1249 quote!(self.guard
1250 .store
1251 .get_mut(&::mockall::Key::new::#keyid())
1252 .unwrap()
1253 .downcast_mut::<Expectations #tg>()
1254 .unwrap())
1255 } else {
1256 quote!(self.guard)
1257 };
1258 let hrtb = self.f.hrtb();
1259 let output = &self.f.output;
1260 let predty = &self.f.predty;
1261 let with_generics_idents = (0..self.f.predty.len())
1262 .map(|i| format_ident!("MockallMatcher{i}"))
1263 .collect::<Vec<_>>();
1264 let with_generics = with_generics_idents.iter()
1265 .zip(self.f.predty.iter())
1266 .map(|(id, mt)|
1267 quote!(#id: #hrtb ::mockall::Predicate<#mt> + Send + 'static, )
1268 ).collect::<TokenStream>();
1269 let with_args = self.f.argnames.iter()
1270 .zip(with_generics_idents.iter())
1271 .map(|(argname, id)| quote!(#argname: #id, ))
1272 .collect::<TokenStream>();
1273 let v = &self.f.privmod_vis;
1274 let with_method = if self.f.concretize {
1275 quote!()
1276 } else {
1277 quote!(
1278 /// Just like
1279 /// [`Expectation::with`](struct.Expectation.html#method.with)
1280 #v fn with<#with_generics> (&mut self, #with_args)
1281 -> &mut Expectation #tg
1282 {
1283 #expectations.0[self.i].with(#(#argnames, )*)
1284 }
1285 )
1286 };
1287 quote!(
1288 /// Just like
1289 /// [`Expectation::in_sequence`](struct.Expectation.html#method.in_sequence)
1290 #v fn in_sequence(&mut self,
1291 __mockall_seq: &mut ::mockall::Sequence)
1292 -> &mut Expectation #tg
1293 {
1294 #expectations.0[self.i].in_sequence(__mockall_seq)
1295 }
1296
1297 /// Just like
1298 /// [`Expectation::never`](struct.Expectation.html#method.never)
1299 #v fn never(&mut self) -> &mut Expectation #tg {
1300 #expectations.0[self.i].never()
1301 }
1302
1303 /// Just like
1304 /// [`Expectation::once`](struct.Expectation.html#method.once)
1305 #v fn once(&mut self) -> &mut Expectation #tg {
1306 #expectations.0[self.i].once()
1307 }
1308
1309 /// Just like
1310 /// [`Expectation::return_const`](struct.Expectation.html#method.return_const)
1311 #v fn return_const<MockallOutput>
1312 (&mut self, __mockall_c: MockallOutput)
1313 -> &mut Expectation #tg
1314 where MockallOutput: Clone + Into<#output> + Send + 'static
1315 {
1316 #expectations.0[self.i].return_const(__mockall_c)
1317 }
1318
1319 /// Just like
1320 /// [`Expectation::return_const_st`](struct.Expectation.html#method.return_const_st)
1321 #v fn return_const_st<MockallOutput>
1322 (&mut self, __mockall_c: MockallOutput)
1323 -> &mut Expectation #tg
1324 where MockallOutput: Clone + Into<#output> + 'static
1325 {
1326 #expectations.0[self.i].return_const_st(__mockall_c)
1327 }
1328
1329 /// Just like
1330 /// [`Expectation::returning`](struct.Expectation.html#method.returning)
1331 #v fn returning<MockallF>(&mut self, __mockall_f: MockallF)
1332 -> &mut Expectation #tg
1333 where MockallF: #hrtb FnMut(#(#argty, )*)
1334 -> #output + Send + 'static
1335 {
1336 #expectations.0[self.i].returning(__mockall_f)
1337 }
1338
1339 /// Just like
1340 /// [`Expectation::return_once`](struct.Expectation.html#method.return_once)
1341 #v fn return_once<MockallF>(&mut self, __mockall_f: MockallF)
1342 -> &mut Expectation #tg
1343 where MockallF: #hrtb FnOnce(#(#argty, )*)
1344 -> #output + Send + 'static
1345 {
1346 #expectations.0[self.i].return_once(__mockall_f)
1347 }
1348
1349 /// Just like
1350 /// [`Expectation::return_once_st`](struct.Expectation.html#method.return_once_st)
1351 #v fn return_once_st<MockallF>(&mut self, __mockall_f: MockallF)
1352 -> &mut Expectation #tg
1353 where MockallF: #hrtb FnOnce(#(#argty, )*)
1354 -> #output + 'static
1355 {
1356 #expectations.0[self.i].return_once_st(__mockall_f)
1357 }
1358
1359
1360 /// Just like
1361 /// [`Expectation::returning_st`](struct.Expectation.html#method.returning_st)
1362 #v fn returning_st<MockallF>(&mut self, __mockall_f: MockallF)
1363 -> &mut Expectation #tg
1364 where MockallF: #hrtb FnMut(#(#argty, )*)
1365 -> #output + 'static
1366 {
1367 #expectations.0[self.i].returning_st(__mockall_f)
1368 }
1369
1370 /// Just like
1371 /// [`Expectation::times`](struct.Expectation.html#method.times)
1372 #v fn times<MockallR>(&mut self, __mockall_r: MockallR)
1373 -> &mut Expectation #tg
1374 where MockallR: Into<::mockall::TimesRange>
1375 {
1376 #expectations.0[self.i].times(__mockall_r)
1377 }
1378
1379 #with_method
1380
1381 /// Just like
1382 /// [`Expectation::withf`](struct.Expectation.html#method.withf)
1383 #v fn withf<MockallF>(&mut self, __mockall_f: MockallF)
1384 -> &mut Expectation #tg
1385 where MockallF: #hrtb Fn(#(&#predty, )*)
1386 -> bool + Send + 'static
1387 {
1388 #expectations.0[self.i].withf(__mockall_f)
1389 }
1390
1391 /// Just like
1392 /// [`Expectation::withf_st`](struct.Expectation.html#method.withf_st)
1393 #v fn withf_st<MockallF>(&mut self, __mockall_f: MockallF)
1394 -> &mut Expectation #tg
1395 where MockallF: #hrtb Fn(#(&#predty, )*)
1396 -> bool + 'static
1397 {
1398 #expectations.0[self.i].withf_st(__mockall_f)
1399 }
1400 ).to_tokens(tokens);
1401 }
1402 }
1403
1404 /// The ExpectationGuard structure for static methods with no generic types
1405 struct ConcreteExpectationGuard<'a> {
1406 f: &'a MockFunction
1407 }
1408
1409 impl<'a> ToTokens for ConcreteExpectationGuard<'a> {
1410 fn to_tokens(&self, tokens: &mut TokenStream) {
1411 if !self.f.is_static {
1412 return;
1413 }
1414
1415 let common_methods = ExpectationGuardCommonMethods{f: self.f};
1416 let (_, tg, _) = self.f.egenerics.split_for_impl();
1417 let ltdef = LifetimeParam::new(
1418 Lifetime::new("'__mockall_lt", Span::call_site())
1419 );
1420 let mut e_generics = self.f.egenerics.clone();
1421 e_generics.lt_token.get_or_insert(<Token![<]>::default());
1422 e_generics.params.push(GenericParam::Lifetime(ltdef));
1423 e_generics.gt_token.get_or_insert(<Token![>]>::default());
1424 let (e_ig, e_tg, e_wc) = e_generics.split_for_impl();
1425 let (ei_ig, _, _) = e_generics.split_for_impl();
1426 let v = &self.f.privmod_vis;
1427 quote!(
1428 #[doc(hidden)]
1429 #v fn get_expectations() -> &'static ::std::sync::Mutex<Expectations> {
1430 static EXPECTATIONS:
1431 ::std::sync::Mutex<Expectations #tg> =
1432 ::std::sync::Mutex::new(Expectations::new());
1433 &EXPECTATIONS
1434 }
1435
1436 /// Like an [`&Expectation`](struct.Expectation.html) but
1437 /// protected by a Mutex guard. Useful for mocking static
1438 /// methods. Forwards accesses to an `Expectation` object.
1439 // We must return the MutexGuard to the caller so he can
1440 // configure the expectation. But we can't bundle both the
1441 // guard and the &Expectation into the same structure; the
1442 // borrow checker won't let us. Instead we'll record the
1443 // expectation's position within the Expectations vector so we
1444 // can proxy its methods.
1445 //
1446 // ExpectationGuard is only defined for expectations that return
1447 // 'static return types.
1448 #v struct ExpectationGuard #e_ig #e_wc {
1449 guard: MutexGuard<'__mockall_lt, Expectations #tg>,
1450 i: usize
1451 }
1452
1453 #[allow(clippy::unused_unit)]
1454 impl #ei_ig ExpectationGuard #e_tg #e_wc
1455 {
1456 // Should only be called from the mockall_derive generated
1457 // code
1458 #[doc(hidden)]
1459 #v fn new(mut __mockall_guard: MutexGuard<'__mockall_lt, Expectations #tg>)
1460 -> Self
1461 {
1462 __mockall_guard.expect(); // Drop the &Expectation
1463 let __mockall_i = __mockall_guard.0.len() - 1;
1464 ExpectationGuard{guard: __mockall_guard, i: __mockall_i}
1465 }
1466
1467 #common_methods
1468 }
1469 ).to_tokens(tokens);
1470 }
1471 }
1472
1473 /// The ExpectationGuard structure for static methods with generic types
1474 struct GenericExpectationGuard<'a> {
1475 f: &'a MockFunction
1476 }
1477
1478 impl<'a> ToTokens for GenericExpectationGuard<'a> {
1479 fn to_tokens(&self, tokens: &mut TokenStream) {
1480 if !self.f.is_static {
1481 return;
1482 }
1483
1484 let common_methods = ExpectationGuardCommonMethods{f: self.f};
1485 let (_, tg, _) = self.f.egenerics.split_for_impl();
1486 let keyid = gen_keyid(&self.f.egenerics);
1487 let ltdef = LifetimeParam::new(
1488 Lifetime::new("'__mockall_lt", Span::call_site())
1489 );
1490 let mut egenerics = self.f.egenerics.clone();
1491 egenerics.lt_token.get_or_insert(<Token![<]>::default());
1492 egenerics.params.push(GenericParam::Lifetime(ltdef));
1493 egenerics.gt_token.get_or_insert(<Token![>]>::default());
1494 let (e_ig, e_tg, e_wc) = egenerics.split_for_impl();
1495 let fn_params = &self.f.fn_params;
1496 let tbf = tg.as_turbofish();
1497 let v = &self.f.privmod_vis;
1498 quote!(
1499 #[doc(hidden)]
1500 #v fn get_expectations() -> &'static ::std::sync::Mutex<GenericExpectations> {
1501 static CELL: ::std::sync::OnceLock<::std::sync::Mutex<GenericExpectations>> = ::std::sync::OnceLock::new();
1502 CELL.get_or_init(|| ::std::sync::Mutex::new(GenericExpectations::new()))
1503 }
1504
1505 /// Like an [`&Expectation`](struct.Expectation.html) but
1506 /// protected by a Mutex guard. Useful for mocking static
1507 /// methods. Forwards accesses to an `Expectation` object.
1508 #v struct ExpectationGuard #e_ig #e_wc{
1509 guard: MutexGuard<'__mockall_lt, GenericExpectations>,
1510 i: usize,
1511 _phantom: ::std::marker::PhantomData<(#(#fn_params,)*)>,
1512 }
1513
1514 #[allow(clippy::unused_unit)]
1515 impl #e_ig ExpectationGuard #e_tg #e_wc
1516 {
1517 // Should only be called from the mockall_derive generated
1518 // code
1519 #[doc(hidden)]
1520 #v fn new(mut __mockall_guard: MutexGuard<'__mockall_lt, GenericExpectations>)
1521 -> Self
1522 {
1523 let __mockall_ee: &mut Expectations #tg =
1524 __mockall_guard.store.entry(
1525 ::mockall::Key::new::#keyid()
1526 ).or_insert_with(||
1527 Box::new(Expectations #tbf ::new()))
1528 .downcast_mut()
1529 .unwrap();
1530 __mockall_ee.expect(); // Drop the &Expectation
1531 let __mockall_i = __mockall_ee.0.len() - 1;
1532 ExpectationGuard{guard: __mockall_guard, i: __mockall_i,
1533 _phantom: ::std::marker::PhantomData}
1534 }
1535
1536 #common_methods
1537 }
1538 ).to_tokens(tokens);
1539 }
1540 }
1541
1542 /// Generates Context, which manages the context for expectations of static
1543 /// methods.
1544 struct Context<'a> {
1545 f: &'a MockFunction
1546 }
1547
1548 impl<'a> ToTokens for Context<'a> {
1549 fn to_tokens(&self, tokens: &mut TokenStream) {
1550 if !self.f.is_static {
1551 return;
1552 }
1553
1554 let ltdef = LifetimeParam::new(
1555 Lifetime::new("'__mockall_lt", Span::call_site())
1556 );
1557 let mut egenerics = self.f.egenerics.clone();
1558 egenerics.lt_token.get_or_insert(<Token![<]>::default());
1559 egenerics.params.push(GenericParam::Lifetime(ltdef));
1560 egenerics.gt_token.get_or_insert(<Token![>]>::default());
1561 let (_, e_tg, _) = egenerics.split_for_impl();
1562 let (ty_ig, ty_tg, ty_wc) = self.f.type_generics.split_for_impl();
1563 let mut meth_generics = self.f.call_generics.clone();
1564 let ltdef = LifetimeParam::new(
1565 Lifetime::new("'__mockall_lt", Span::call_site())
1566 );
1567 meth_generics.params.push(GenericParam::Lifetime(ltdef));
1568 let (meth_ig, _meth_tg, meth_wc) = meth_generics.split_for_impl();
1569 let ctx_fn_params = self.f.struct_generics.type_params()
1570 .map(|tp| tp.ident.clone())
1571 .collect::<Punctuated::<Ident, Token![,]>>();
1572 let v = &self.f.privmod_vis;
1573
1574 #[cfg(not(feature = "nightly_derive"))]
1575 let must_use = quote!(#[must_use =
1576 "Must set return value when not using the \"nightly\" feature"
1577 ]);
1578 #[cfg(feature = "nightly_derive")]
1579 let must_use = quote!();
1580
1581 #[cfg(not(feature = "nightly_derive"))]
1582 let clear_poison = quote!();
1583 #[cfg(feature = "nightly_derive")]
1584 let clear_poison = quote!(
1585 #[allow(clippy::incompatible_msrv)]
1586 get_expectations().clear_poison();
1587 );
1588
1589 quote!(
1590 /// Manages the context for expectations of static methods.
1591 ///
1592 /// Expectations on this method will be validated and cleared when
1593 /// the `Context` object drops. The `Context` object does *not*
1594 /// provide any form of synchronization, so multiple tests that set
1595 /// expectations on the same static method must provide their own.
1596 #[must_use = "Context only serves to create expectations" ]
1597 #v struct Context #ty_ig #ty_wc {
1598 // Prevent "unused type parameter" errors
1599 // Surprisingly, PhantomData<Fn(generics)> is Send even if
1600 // generics are not, unlike PhantomData<generics>
1601 _phantom: ::std::marker::PhantomData<
1602 Box<dyn Fn(#ctx_fn_params) + Send>
1603 >
1604 }
1605 impl #ty_ig Context #ty_tg #ty_wc {
1606 /// Verify that all current expectations for this method are
1607 /// satisfied and clear them.
1608 #v fn checkpoint(&self) {
1609 Self::do_checkpoint()
1610 }
1611 #[doc(hidden)]
1612 #v fn do_checkpoint() {
1613 let __mockall_timeses = get_expectations()
1614 .lock()
1615 .unwrap()
1616 .checkpoint()
1617 .collect::<Vec<_>>();
1618 }
1619
1620 /// Create a new expectation for this method.
1621 #must_use
1622 #v fn expect #meth_ig ( &self,) -> ExpectationGuard #e_tg
1623 #meth_wc
1624 {
1625 ExpectationGuard::new(get_expectations().lock().unwrap())
1626 }
1627 }
1628 impl #ty_ig Default for Context #ty_tg #ty_wc {
1629 fn default() -> Self {
1630 Context {_phantom: std::marker::PhantomData}
1631 }
1632 }
1633 impl #ty_ig Drop for Context #ty_tg #ty_wc {
1634 fn drop(&mut self) {
1635 if ::std::thread::panicking() {
1636 // Clear poison since we're about to clear the Mutex's
1637 // contents anyway.
1638 #clear_poison
1639 // Drain all expectations so other tests can run with a
1640 // blank slate. But ignore errors so we don't
1641 // double-panic.
1642 let _ = get_expectations()
1643 .lock()
1644 .map(|mut g| g.checkpoint().collect::<Vec<_>>());
1645 } else {
1646 // Verify expectations are satisfied
1647 Self::do_checkpoint();
1648 }
1649 }
1650 }
1651 ).to_tokens(tokens);
1652 }
1653 }
1654
1655 struct Matcher<'a> {
1656 f: &'a MockFunction
1657 }
1658
1659 impl<'a> ToTokens for Matcher<'a> {
1660 fn to_tokens(&self, tokens: &mut TokenStream) {
1661 let (ig, tg, wc) = self.f.cgenerics.split_for_impl();
1662 let argnames = &self.f.argnames;
1663 let braces = argnames.iter()
1664 .fold(String::new(), |mut acc, _argname| {
1665 if acc.is_empty() {
1666 acc.push_str("{}");
1667 } else {
1668 acc.push_str(", {}");
1669 }
1670 acc
1671 });
1672 let fn_params = &self.f.fn_params;
1673 let hrtb = self.f.hrtb();
1674 let indices = (0..argnames.len())
1675 .map(|i| {
1676 syn::Index::from(i)
1677 }).collect::<Vec<_>>();
1678 let lg = lifetimes_to_generics(&self.f.alifetimes);
1679 let pred_matches = argnames.iter().enumerate()
1680 .map(|(i, argname)| {
1681 let idx = syn::Index::from(i);
1682 quote!(__mockall_pred.#idx.eval(#argname),)
1683 }).collect::<TokenStream>();
1684 let preds = if self.f.concretize {
1685 quote!(())
1686 } else {
1687 self.f.predty.iter()
1688 .map(|t| quote!(Box<dyn #hrtb ::mockall::Predicate<#t> + Send>,))
1689 .collect::<TokenStream>()
1690 };
1691 let predty = &self.f.predty;
1692 let refpredty = &self.f.refpredty;
1693 let predmatches_body = if self.f.concretize {
1694 quote!()
1695 } else {
1696 quote!(Matcher::Pred(__mockall_pred) => [#pred_matches].iter().all(|__mockall_x| *__mockall_x),)
1697 };
1698 let preddbg_body = if self.f.concretize {
1699 quote!()
1700 } else {
1701 quote!(
1702 Matcher::Pred(__mockall_p) => {
1703 write!(__mockall_fmt, #braces,
1704 #(__mockall_p.#indices,)*)
1705 }
1706 )
1707 };
1708 quote!(
1709 enum Matcher #ig #wc {
1710 Always,
1711 Func(Box<dyn #hrtb Fn(#( #refpredty, )*) -> bool + Send>),
1712 // Version of Matcher::Func for closures that aren't Send
1713 FuncSt(::mockall::Fragile<Box<dyn #hrtb Fn(#( #refpredty, )*) -> bool>>),
1714 Pred(Box<(#preds)>),
1715 // Prevent "unused type parameter" errors
1716 // Surprisingly, PhantomData<Fn(generics)> is Send even if
1717 // generics are not, unlike PhantomData<generics>
1718 _Phantom(Box<dyn Fn(#(#fn_params,)*) + Send>)
1719 }
1720 impl #ig Matcher #tg #wc {
1721 #[allow(clippy::ptr_arg)]
1722 fn matches #lg (&self, #( #argnames: &#predty, )*) -> bool {
1723 match self {
1724 Matcher::Always => true,
1725 Matcher::Func(__mockall_f) =>
1726 __mockall_f(#(#argnames, )*),
1727 Matcher::FuncSt(__mockall_f) =>
1728 (__mockall_f.get())(#(#argnames, )*),
1729 #predmatches_body
1730 _ => unreachable!()
1731 }
1732 }
1733 }
1734
1735 impl #ig Default for Matcher #tg #wc {
1736 #[allow(unused_variables)]
1737 fn default() -> Self {
1738 Matcher::Always
1739 }
1740 }
1741
1742 impl #ig ::std::fmt::Display for Matcher #tg #wc {
1743 fn fmt(&self, __mockall_fmt: &mut ::std::fmt::Formatter<'_>)
1744 -> ::std::fmt::Result
1745 {
1746 match self {
1747 Matcher::Always => write!(__mockall_fmt, "<anything>"),
1748 Matcher::Func(_) => write!(__mockall_fmt, "<function>"),
1749 Matcher::FuncSt(_) => write!(__mockall_fmt, "<single threaded function>"),
1750 #preddbg_body
1751 _ => unreachable!(),
1752 }
1753 }
1754 }
1755 ).to_tokens(tokens);
1756 }
1757 }
1758
1759 struct RefRfunc<'a> {
1760 f: &'a MockFunction
1761 }
1762
1763 impl<'a> ToTokens for RefRfunc<'a> {
1764 fn to_tokens(&self, tokens: &mut TokenStream) {
1765 let fn_params = &self.f.fn_params;
1766 let (ig, tg, wc) = self.f.egenerics.split_for_impl();
1767 let lg = lifetimes_to_generics(&self.f.alifetimes);
1768 let owned_output = &self.f.owned_output;
1769
1770 #[cfg(not(feature = "nightly_derive"))]
1771 let default_err_msg =
1772 "Returning default values requires the \"nightly\" feature";
1773 #[cfg(feature = "nightly_derive")]
1774 let default_err_msg =
1775 "Can only return default values for types that impl std::Default";
1776
1777 quote!(
1778 enum Rfunc #ig #wc {
1779 Default(Option<#owned_output>),
1780 Const(#owned_output),
1781 // Prevent "unused type parameter" errors Surprisingly,
1782 // PhantomData<Fn(generics)> is Send even if generics are not,
1783 // unlike PhantomData<generics>
1784 _Phantom(Mutex<Box<dyn Fn(#(#fn_params,)*) + Send>>)
1785 }
1786
1787 impl #ig Rfunc #tg #wc {
1788 fn call #lg (&self)
1789 -> std::result::Result<&#owned_output, &'static str>
1790 {
1791 match self {
1792 Rfunc::Default(Some(ref __mockall_o)) => {
1793 ::std::result::Result::Ok(__mockall_o)
1794 },
1795 Rfunc::Default(None) => {
1796 Err(#default_err_msg)
1797 },
1798 Rfunc::Const(ref __mockall_o) => {
1799 ::std::result::Result::Ok(__mockall_o)
1800 },
1801 Rfunc::_Phantom(_) => unreachable!()
1802 }
1803 }
1804 }
1805
1806 impl #ig std::default::Default for Rfunc #tg #wc
1807 {
1808 fn default() -> Self {
1809 use ::mockall::ReturnDefault;
1810 Rfunc::Default(::mockall::DefaultReturner::<#owned_output>
1811 ::maybe_return_default())
1812 }
1813 }
1814 ).to_tokens(tokens);
1815 }
1816 }
1817
1818 struct RefMutRfunc<'a> {
1819 f: &'a MockFunction
1820 }
1821
1822 impl<'a> ToTokens for RefMutRfunc<'a> {
1823 fn to_tokens(&self, tokens: &mut TokenStream) {
1824 let argnames = &self.f.argnames;
1825 let argty = &self.f.argty;
1826 let fn_params = &self.f.fn_params;
1827 let (ig, tg, wc) = self.f.egenerics.split_for_impl();
1828 let lg = lifetimes_to_generics(&self.f.alifetimes);
1829 let owned_output = &self.f.owned_output;
1830 let output = &self.f.output;
1831
1832 #[cfg(not(feature = "nightly_derive"))]
1833 let default_err_msg =
1834 "Returning default values requires the \"nightly\" feature";
1835 #[cfg(feature = "nightly_derive")]
1836 let default_err_msg =
1837 "Can only return default values for types that impl std::Default";
1838
1839 quote!(
1840 #[allow(clippy::unused_unit)]
1841 enum Rfunc #ig #wc {
1842 Default(Option<#owned_output>),
1843 Mut((Box<dyn FnMut(#(#argty, )*) -> #owned_output + Send + Sync>),
1844 Option<#owned_output>),
1845 // Version of Rfunc::Mut for closures that aren't Send
1846 MutSt((::mockall::Fragile<
1847 Box<dyn FnMut(#(#argty, )*) -> #owned_output >>
1848 ), Option<#owned_output>
1849 ),
1850 Var(#owned_output),
1851 // Prevent "unused type parameter" errors Surprisingly,
1852 // PhantomData<Fn(generics)> is Send even if generics are not,
1853 // unlike PhantomData<generics>
1854 _Phantom(Mutex<Box<dyn Fn(#(#fn_params,)*) + Send>>)
1855 }
1856
1857 impl #ig Rfunc #tg #wc {
1858 fn call_mut #lg (&mut self, #(#argnames: #argty, )*)
1859 -> std::result::Result<#output, &'static str>
1860 {
1861 match self {
1862 Rfunc::Default(Some(ref mut __mockall_o)) => {
1863 ::std::result::Result::Ok(__mockall_o)
1864 },
1865 Rfunc::Default(None) => {
1866 Err(#default_err_msg)
1867 },
1868 Rfunc::Mut(ref mut __mockall_f, ref mut __mockall_o) =>
1869 {
1870 *__mockall_o = Some(__mockall_f(#(#argnames, )*));
1871 if let Some(ref mut __mockall_o2) = __mockall_o {
1872 ::std::result::Result::Ok(__mockall_o2)
1873 } else {
1874 unreachable!()
1875 }
1876 },
1877 Rfunc::MutSt(ref mut __mockall_f, ref mut __mockall_o)=>
1878 {
1879 *__mockall_o = Some((__mockall_f.get_mut())(
1880 #(#argnames, )*)
1881 );
1882 if let Some(ref mut __mockall_o2) = __mockall_o {
1883 ::std::result::Result::Ok(__mockall_o2)
1884 } else {
1885 unreachable!()
1886 }
1887 },
1888 Rfunc::Var(ref mut __mockall_o) => {
1889 ::std::result::Result::Ok(__mockall_o)
1890 },
1891 Rfunc::_Phantom(_) => unreachable!()
1892 }
1893 }
1894 }
1895
1896 impl #ig std::default::Default for Rfunc #tg #wc
1897 {
1898 fn default() -> Self {
1899 use ::mockall::ReturnDefault;
1900 Rfunc::Default(::mockall::DefaultReturner::<#owned_output>
1901 ::maybe_return_default())
1902 }
1903 }
1904 ).to_tokens(tokens);
1905 }
1906 }
1907
1908 struct StaticRfunc<'a> {
1909 f: &'a MockFunction
1910 }
1911
1912 impl<'a> ToTokens for StaticRfunc<'a> {
1913 fn to_tokens(&self, tokens: &mut TokenStream) {
1914 let argnames = &self.f.argnames;
1915 let argty = &self.f.argty;
1916 let fn_params = &self.f.fn_params;
1917 let (ig, tg, wc) = self.f.egenerics.split_for_impl();
1918 let hrtb = self.f.hrtb();
1919 let lg = lifetimes_to_generics(&self.f.alifetimes);
1920 let output = &self.f.output;
1921 quote!(
1922 #[allow(clippy::unused_unit)]
1923 enum Rfunc #ig #wc {
1924 Default,
1925 // Indicates that a `return_once` expectation has already
1926 // returned
1927 Expired,
1928 Mut(Box<dyn #hrtb FnMut(#(#argty, )*) -> #output + Send>),
1929 // Version of Rfunc::Mut for closures that aren't Send
1930 MutSt(::mockall::Fragile<
1931 Box<dyn #hrtb FnMut(#(#argty, )*) -> #output >>
1932 ),
1933 Once(Box<dyn #hrtb FnOnce(#(#argty, )*) -> #output + Send>),
1934 // Version of Rfunc::Once for closure that aren't Send
1935 OnceSt(::mockall::Fragile<
1936 Box<dyn #hrtb FnOnce(#(#argty, )*) -> #output>>
1937 ),
1938 // Prevent "unused type parameter" errors Surprisingly,
1939 // PhantomData<Fn(generics)> is Send even if generics are not,
1940 // unlike PhantomData<generics>
1941 _Phantom(Box<dyn Fn(#(#fn_params,)*) + Send>)
1942 }
1943
1944 impl #ig Rfunc #tg #wc {
1945 fn call_mut #lg (&mut self, #( #argnames: #argty, )* )
1946 -> std::result::Result<#output, &'static str>
1947 {
1948 match self {
1949 Rfunc::Default => {
1950 use ::mockall::ReturnDefault;
1951 ::mockall::DefaultReturner::<#output>
1952 ::return_default()
1953 },
1954 Rfunc::Expired => {
1955 Err("called twice, but it returns by move")
1956 },
1957 Rfunc::Mut(__mockall_f) => {
1958 ::std::result::Result::Ok(__mockall_f( #(#argnames, )* ))
1959 },
1960 Rfunc::MutSt(__mockall_f) => {
1961 ::std::result::Result::Ok((__mockall_f.get_mut())(#(#argnames,)*))
1962 },
1963 Rfunc::Once(_) => {
1964 if let Rfunc::Once(mut __mockall_f) =
1965 mem::replace(self, Rfunc::Expired) {
1966 ::std::result::Result::Ok(__mockall_f( #(#argnames, )* ))
1967 } else {
1968 unreachable!()
1969 }
1970 },
1971 Rfunc::OnceSt(_) => {
1972 if let Rfunc::OnceSt(mut __mockall_f) =
1973 mem::replace(self, Rfunc::Expired) {
1974 ::std::result::Result::Ok((__mockall_f.into_inner())(#(#argnames,)*))
1975 } else {
1976 unreachable!()
1977 }
1978 },
1979 Rfunc::_Phantom(_) => unreachable!()
1980 }
1981 }
1982 }
1983
1984 impl #ig std::default::Default for Rfunc #tg #wc
1985 {
1986 fn default() -> Self {
1987 Rfunc::Default
1988 }
1989 }
1990 ).to_tokens(tokens);
1991 }
1992 }
1993
1994 /// An expectation type for functions that take a &self and return a reference
1995 struct RefExpectation<'a> {
1996 f: &'a MockFunction
1997 }
1998
1999 impl<'a> ToTokens for RefExpectation<'a> {
2000 fn to_tokens(&self, tokens: &mut TokenStream) {
2001 let argnames = &self.f.argnames;
2002 let argty = &self.f.argty;
2003 let common_methods = CommonExpectationMethods{f: self.f};
2004 let desc = self.f.desc();
2005 let funcname = self.f.funcname();
2006 let (ig, tg, wc) = self.f.egenerics.split_for_impl();
2007
2008 let (_, common_tg, _) = self.f.cgenerics.split_for_impl();
2009 let lg = lifetimes_to_generics(&self.f.alifetimes);
2010 let output = &self.f.output;
2011 let owned_output = &self.f.owned_output;
2012 let v = &self.f.privmod_vis;
2013 quote!(
2014 /// Expectation type for methods taking a `&self` argument and
2015 /// returning immutable references. This is the type returned by
2016 /// the `expect_*` methods.
2017 #v struct Expectation #ig #wc {
2018 common: Common #common_tg,
2019 rfunc: Rfunc #tg,
2020 }
2021
2022 #[allow(clippy::unused_unit)]
2023 impl #ig Expectation #tg #wc {
2024 /// Call this [`Expectation`] as if it were the real method.
2025 #v fn call #lg (&self, #(#argnames: #argty, )*) -> #output
2026 {
2027 use ::mockall::{ViaDebug, ViaNothing};
2028 self.common.call(&#desc);
2029 self.rfunc.call().unwrap_or_else(|m| {
2030 let desc = std::format!(
2031 "{}", self.common.matcher.lock().unwrap());
2032 panic!("{}: Expectation({}) {}", #funcname, desc,
2033 m);
2034 })
2035 }
2036
2037 /// Return a reference to a constant value from the `Expectation`
2038 #v fn return_const(&mut self, __mockall_o: #owned_output)
2039 -> &mut Self
2040 {
2041 self.rfunc = Rfunc::Const(__mockall_o);
2042 self
2043 }
2044
2045 #common_methods
2046 }
2047 impl #ig Default for Expectation #tg #wc
2048 {
2049 fn default() -> Self {
2050 Expectation {
2051 common: Common::default(),
2052 rfunc: Rfunc::default()
2053 }
2054 }
2055 }
2056 ).to_tokens(tokens);
2057 }
2058 }
2059
2060 /// For methods that take &mut self and return a reference
2061 struct RefMutExpectation<'a> {
2062 f: &'a MockFunction
2063 }
2064
2065 impl<'a> ToTokens for RefMutExpectation<'a> {
2066 fn to_tokens(&self, tokens: &mut TokenStream) {
2067 let common_methods = CommonExpectationMethods{f: self.f};
2068 let argnames = &self.f.argnames;
2069 let argty = &self.f.argty;
2070 let desc = self.f.desc();
2071 let funcname = self.f.funcname();
2072 let (ig, tg, wc) = self.f.egenerics.split_for_impl();
2073 let (_, common_tg, _) = self.f.cgenerics.split_for_impl();
2074 let lg = lifetimes_to_generics(&self.f.alifetimes);
2075 let owned_output = &self.f.owned_output;
2076 let v = &self.f.privmod_vis;
2077 quote!(
2078 /// Expectation type for methods taking a `&mut self` argument and
2079 /// returning references. This is the type returned by the
2080 /// `expect_*` methods.
2081 #v struct Expectation #ig #wc {
2082 common: Common #common_tg,
2083 rfunc: Rfunc #tg
2084 }
2085
2086 #[allow(clippy::unused_unit)]
2087 impl #ig Expectation #tg #wc {
2088 /// Simulating calling the real method for this expectation
2089 #v fn call_mut #lg (&mut self, #(#argnames: #argty, )*)
2090 -> &mut #owned_output
2091 {
2092 use ::mockall::{ViaDebug, ViaNothing};
2093 self.common.call(&#desc);
2094 let desc = std::format!(
2095 "{}", self.common.matcher.lock().unwrap());
2096 self.rfunc.call_mut(#(#argnames, )*).unwrap_or_else(|m| {
2097 panic!("{}: Expectation({}) {}", #funcname, desc,
2098 m);
2099 })
2100 }
2101
2102 /// Convenience method that can be used to supply a return value
2103 /// for a `Expectation`. The value will be returned by mutable
2104 /// reference.
2105 #v fn return_var(&mut self, __mockall_o: #owned_output) -> &mut Self
2106 {
2107 self.rfunc = Rfunc::Var(__mockall_o);
2108 self
2109 }
2110
2111 /// Supply a closure that the `Expectation` will use to create its
2112 /// return value. The return value will be returned by mutable
2113 /// reference.
2114 #v fn returning<MockallF>(&mut self, __mockall_f: MockallF)
2115 -> &mut Self
2116 where MockallF: FnMut(#(#argty, )*) -> #owned_output + Send + Sync + 'static
2117 {
2118 self.rfunc = Rfunc::Mut(Box::new(__mockall_f), None);
2119 self
2120 }
2121
2122 /// Single-threaded version of [`returning`](#method.returning).
2123 /// Can be used when the argument or return type isn't `Send`.
2124 #v fn returning_st<MockallF>(&mut self, __mockall_f: MockallF)
2125 -> &mut Self
2126 where MockallF: FnMut(#(#argty, )*) -> #owned_output + 'static
2127 {
2128 self.rfunc = Rfunc::MutSt(
2129 ::mockall::Fragile::new(Box::new(__mockall_f)), None);
2130 self
2131 }
2132
2133 #common_methods
2134 }
2135 impl #ig Default for Expectation #tg #wc
2136 {
2137 fn default() -> Self {
2138 Expectation {
2139 common: Common::default(),
2140 rfunc: Rfunc::default()
2141 }
2142 }
2143 }
2144 ).to_tokens(tokens);
2145 }
2146 }
2147
2148 /// An expectation type for functions return a `'static` value
2149 struct StaticExpectation<'a> {
2150 f: &'a MockFunction
2151 }
2152
2153 impl<'a> ToTokens for StaticExpectation<'a> {
2154 fn to_tokens(&self, tokens: &mut TokenStream) {
2155 let common_methods = CommonExpectationMethods{f: self.f};
2156 let argnames = &self.f.argnames;
2157 let argty = &self.f.argty;
2158 let desc = self.f.desc();
2159 let hrtb = self.f.hrtb();
2160 let funcname = self.f.funcname();
2161 let (ig, tg, wc) = self.f.egenerics.split_for_impl();
2162 let (_, common_tg, _) = self.f.cgenerics.split_for_impl();
2163 let lg = lifetimes_to_generics(&self.f.alifetimes);
2164 let output = &self.f.output;
2165 let v = &self.f.privmod_vis;
2166
2167 quote!(
2168 /// Expectation type for methods that return a `'static` type.
2169 /// This is the type returned by the `expect_*` methods.
2170 #v struct Expectation #ig #wc {
2171 common: Common #common_tg,
2172 rfunc: Mutex<Rfunc #tg>,
2173 }
2174
2175 #[allow(clippy::unused_unit)]
2176 impl #ig Expectation #tg #wc {
2177 /// Call this [`Expectation`] as if it were the real method.
2178 #[doc(hidden)]
2179 #v fn call #lg (&self, #(#argnames: #argty, )* ) -> #output
2180 {
2181 use ::mockall::{ViaDebug, ViaNothing};
2182 self.common.call(&#desc);
2183 self.rfunc.lock().unwrap().call_mut(#(#argnames, )*)
2184 .unwrap_or_else(|message| {
2185 let desc = std::format!(
2186 "{}", self.common.matcher.lock().unwrap());
2187 panic!("{}: Expectation({}) {}", #funcname, desc,
2188 message);
2189 })
2190 }
2191
2192 /// Return a constant value from the `Expectation`
2193 ///
2194 /// The output type must be `Clone`. The compiler can't always
2195 /// infer the proper type to use with this method; you will
2196 /// usually need to specify it explicitly. i.e.
2197 /// `return_const(42i32)` instead of `return_const(42)`.
2198 // We must use Into<#output> instead of #output because where
2199 // clauses don't accept equality constraints.
2200 // https://github.com/rust-lang/rust/issues/20041
2201 #[allow(unused_variables)]
2202 #v fn return_const<MockallOutput>(&mut self,
2203 __mockall_c: MockallOutput)
2204 -> &mut Self
2205 where MockallOutput: Clone + Into<#output> + Send + 'static
2206 {
2207 self.returning(move |#(#argnames, )*| __mockall_c.clone().into())
2208 }
2209
2210 /// Single-threaded version of
2211 /// [`return_const`](#method.return_const). This is useful for
2212 /// return types that are not `Send`.
2213 ///
2214 /// The output type must be `Clone`. The compiler can't always
2215 /// infer the proper type to use with this method; you will
2216 /// usually need to specify it explicitly. i.e.
2217 /// `return_const(42i32)` instead of `return_const(42)`.
2218 ///
2219 /// It is a runtime error to call the mock method from a
2220 /// different thread than the one that originally called this
2221 /// method.
2222 // We must use Into<#output> instead of #output because where
2223 // clauses don't accept equality constraints.
2224 // https://github.com/rust-lang/rust/issues/20041
2225 #[allow(unused_variables)]
2226 #v fn return_const_st<MockallOutput>(&mut self,
2227 __mockall_c: MockallOutput)
2228 -> &mut Self
2229 where MockallOutput: Clone + Into<#output> + 'static
2230 {
2231 self.returning_st(move |#(#argnames, )*| __mockall_c.clone().into())
2232 }
2233
2234 /// Supply an `FnOnce` closure that will provide the return
2235 /// value for this Expectation. This is useful for return types
2236 /// that aren't `Clone`. It will be an error to call this
2237 /// method multiple times.
2238 #v fn return_once<MockallF>(&mut self, __mockall_f: MockallF)
2239 -> &mut Self
2240 where MockallF: #hrtb FnOnce(#(#argty, )*)
2241 -> #output + Send + 'static
2242 {
2243 {
2244 let mut __mockall_guard = self.rfunc.lock().unwrap();
2245 *__mockall_guard.deref_mut() =
2246 Rfunc::Once(Box::new(__mockall_f));
2247 }
2248 self
2249 }
2250
2251 /// Single-threaded version of
2252 /// [`return_once`](#method.return_once). This is useful for
2253 /// return types that are neither `Send` nor `Clone`.
2254 ///
2255 /// It is a runtime error to call the mock method from a
2256 /// different thread than the one that originally called this
2257 /// method. It is also a runtime error to call the method more
2258 /// than once.
2259 #v fn return_once_st<MockallF>(&mut self, __mockall_f:
2260 MockallF) -> &mut Self
2261 where MockallF: #hrtb FnOnce(#(#argty, )*)
2262 -> #output + 'static
2263 {
2264 {
2265 let mut __mockall_guard = self.rfunc.lock().unwrap();
2266 *__mockall_guard.deref_mut() = Rfunc::OnceSt(
2267 ::mockall::Fragile::new(Box::new(__mockall_f)));
2268 }
2269 self
2270 }
2271
2272 /// Supply a closure that will provide the return value for this
2273 /// `Expectation`. The method's arguments are passed to the
2274 /// closure by value.
2275 #v fn returning<MockallF>(&mut self, __mockall_f: MockallF)
2276 -> &mut Self
2277 where MockallF: #hrtb FnMut(#(#argty, )*)
2278 -> #output + Send + 'static
2279 {
2280 {
2281 let mut __mockall_guard = self.rfunc.lock().unwrap();
2282 *__mockall_guard.deref_mut() =
2283 Rfunc::Mut(Box::new(__mockall_f));
2284 }
2285 self
2286 }
2287
2288 /// Single-threaded version of [`returning`](#method.returning).
2289 /// Can be used when the argument or return type isn't `Send`.
2290 ///
2291 /// It is a runtime error to call the mock method from a
2292 /// different thread than the one that originally called this
2293 /// method.
2294 #v fn returning_st<MockallF>(&mut self, __mockall_f: MockallF)
2295 -> &mut Self
2296 where MockallF: #hrtb FnMut(#(#argty, )*)
2297 -> #output + 'static
2298 {
2299 {
2300 let mut __mockall_guard = self.rfunc.lock().unwrap();
2301 *__mockall_guard.deref_mut() = Rfunc::MutSt(
2302 ::mockall::Fragile::new(Box::new(__mockall_f)));
2303 }
2304 self
2305 }
2306
2307 #common_methods
2308 }
2309 impl #ig Default for Expectation #tg #wc
2310 {
2311 fn default() -> Self {
2312 Expectation {
2313 common: Common::default(),
2314 rfunc: Mutex::new(Rfunc::default())
2315 }
2316 }
2317 }
2318 ).to_tokens(tokens);
2319 }
2320 }
2321
2322 /// An collection of RefExpectation's
2323 struct RefExpectations<'a> {
2324 f: &'a MockFunction
2325 }
2326
2327 impl<'a> ToTokens for RefExpectations<'a> {
2328 fn to_tokens(&self, tokens: &mut TokenStream) {
2329 let common_methods = CommonExpectationsMethods{f: self.f};
2330 let argnames = &self.f.argnames;
2331 let argty = &self.f.argty;
2332 let (ig, tg, wc) = self.f.egenerics.split_for_impl();
2333 let lg = lifetimes_to_generics(&self.f.alifetimes);
2334 let output = &self.f.output;
2335 let predexprs = &self.f.predexprs;
2336 let v = &self.f.privmod_vis;
2337 quote!(
2338 #common_methods
2339 impl #ig Expectations #tg #wc {
2340 /// Simulate calling the real method. Every current expectation
2341 /// will be checked in FIFO order and the first one with
2342 /// matching arguments will be used.
2343 #v fn call #lg (&self, #(#argnames: #argty, )* )
2344 -> Option<#output>
2345 {
2346 self.0.iter()
2347 .find(|__mockall_e|
2348 __mockall_e.matches(#(#predexprs, )*) &&
2349 (!__mockall_e.is_done() || self.0.len() == 1))
2350 .map(move |__mockall_e|
2351 __mockall_e.call(#(#argnames),*)
2352 )
2353 }
2354
2355 }
2356 ).to_tokens(tokens);
2357 }
2358 }
2359
2360 /// An collection of RefMutExpectation's
2361 struct RefMutExpectations<'a> {
2362 f: &'a MockFunction
2363 }
2364
2365 impl<'a> ToTokens for RefMutExpectations<'a> {
2366 fn to_tokens(&self, tokens: &mut TokenStream) {
2367 let common_methods = CommonExpectationsMethods{f: self.f};
2368 let argnames = &self.f.argnames;
2369 let argty = &self.f.argty;
2370 let (ig, tg, wc) = self.f.egenerics.split_for_impl();
2371 let lg = lifetimes_to_generics(&self.f.alifetimes);
2372 let output = &self.f.output;
2373 let predexprs = &self.f.predexprs;
2374 let v = &self.f.privmod_vis;
2375 quote!(
2376 #common_methods
2377 impl #ig Expectations #tg #wc {
2378 /// Simulate calling the real method. Every current expectation
2379 /// will be checked in FIFO order and the first one with
2380 /// matching arguments will be used.
2381 #v fn call_mut #lg (&mut self, #(#argnames: #argty, )* )
2382 -> Option<#output>
2383 {
2384 let __mockall_n = self.0.len();
2385 self.0.iter_mut()
2386 .find(|__mockall_e|
2387 __mockall_e.matches(#(#predexprs, )*) &&
2388 (!__mockall_e.is_done() || __mockall_n == 1))
2389 .map(move |__mockall_e|
2390 __mockall_e.call_mut(#(#argnames, )*)
2391 )
2392 }
2393
2394 }
2395 ).to_tokens(tokens);
2396 }
2397 }
2398
2399 /// An collection of Expectation's for methods returning static values
2400 struct StaticExpectations<'a> {
2401 f: &'a MockFunction
2402 }
2403
2404 impl<'a> ToTokens for StaticExpectations<'a> {
2405 fn to_tokens(&self, tokens: &mut TokenStream) {
2406 let common_methods = CommonExpectationsMethods{f: self.f};
2407 let argnames = &self.f.argnames;
2408 let argty = &self.f.argty;
2409 let (ig, tg, wc) = self.f.egenerics.split_for_impl();
2410 let lg = lifetimes_to_generics(&self.f.alifetimes);
2411 let output = &self.f.output;
2412 let predexprs = &self.f.predexprs;
2413 let v = &self.f.privmod_vis;
2414 quote!(
2415 #common_methods
2416 impl #ig Expectations #tg #wc {
2417 /// Simulate calling the real method. Every current expectation
2418 /// will be checked in FIFO order and the first one with
2419 /// matching arguments will be used.
2420 #v fn call #lg (&self, #(#argnames: #argty, )* )
2421 -> Option<#output>
2422 {
2423 self.0.iter()
2424 .find(|__mockall_e|
2425 __mockall_e.matches(#(#predexprs, )*) &&
2426 (!__mockall_e.is_done() || self.0.len() == 1))
2427 .map(move |__mockall_e|
2428 __mockall_e.call(#(#argnames, )*)
2429 )
2430 }
2431
2432 }
2433 ).to_tokens(tokens);
2434 }
2435 }
2436
2437 struct GenericExpectations<'a> {
2438 f: &'a MockFunction
2439 }
2440
2441 impl<'a> ToTokens for GenericExpectations<'a> {
2442 fn to_tokens(&self, tokens: &mut TokenStream) {
2443 if ! self.f.is_expectation_generic() {
2444 return;
2445 }
2446 if ! self.f.is_static() && ! self.f.is_method_generic() {
2447 return;
2448 }
2449
2450 let ge = StaticGenericExpectations{f: self.f};
2451 let v = &self.f.privmod_vis;
2452 quote!(
2453 /// A collection of [`Expectation`](struct.Expectations.html)
2454 /// objects for a generic method. Users will rarely if ever use
2455 /// this struct directly.
2456 #[doc(hidden)]
2457 #[derive(Default)]
2458 #v struct GenericExpectations{
2459 store: std::collections::hash_map::HashMap<::mockall::Key,
2460 Box<dyn ::mockall::AnyExpectations>>
2461 }
2462 impl GenericExpectations {
2463 /// Verify that all current expectations are satisfied and clear
2464 /// them. This applies to all sets of generic parameters!
2465 #v fn checkpoint(&mut self) ->
2466 std::collections::hash_map::Drain<::mockall::Key,
2467 Box<dyn ::mockall::AnyExpectations>>
2468 {
2469 self.store.drain()
2470 }
2471
2472 #v fn new() -> Self {
2473 Self::default()
2474 }
2475 }
2476 #ge
2477 ).to_tokens(tokens);
2478 }
2479 }
2480
2481 /// Generates methods for GenericExpectations for methods returning static
2482 /// values
2483 struct StaticGenericExpectations<'a> {
2484 f: &'a MockFunction
2485 }
2486
2487 impl<'a> ToTokens for StaticGenericExpectations<'a> {
2488 fn to_tokens(&self, tokens: &mut TokenStream) {
2489 let argnames = &self.f.argnames;
2490 let argty = &self.f.argty;
2491 let (ig, tg, wc) = self.f.egenerics.split_for_impl();
2492 let keyid = gen_keyid(&self.f.egenerics);
2493 let mut any_wc = wc.cloned();
2494 if self.f.return_ref || self.f.return_refmut {
2495 // Add Senc + Sync, required for downcast, since Expectation
2496 // stores an Option<#owned_output>
2497 send_syncify(&mut any_wc, self.f.owned_output.clone());
2498 }
2499 let tbf = tg.as_turbofish();
2500 let output = &self.f.output;
2501 let v = &self.f.privmod_vis;
2502 let (call, get, self_, downcast) = if self.f.return_refmut {
2503 (format_ident!("call_mut"),
2504 format_ident!("get_mut"),
2505 quote!(&mut self),
2506 format_ident!("downcast_mut"))
2507 } else {
2508 (format_ident!("call"),
2509 format_ident!("get"),
2510 quote!(&self),
2511 format_ident!("downcast_ref"))
2512 };
2513 quote!(
2514 impl #ig ::mockall::AnyExpectations for Expectations #tg #any_wc {}
2515 impl GenericExpectations {
2516 /// Simulating calling the real method.
2517 #v fn #call #ig (#self_, #(#argnames: #argty, )* )
2518 -> Option<#output> #wc
2519 {
2520 self.store.#get(&::mockall::Key::new::#keyid())
2521 .map(|__mockall_e| {
2522 __mockall_e.#downcast::<Expectations #tg>()
2523 .unwrap()
2524 .#call(#(#argnames, )*)
2525 }).flatten()
2526 }
2527
2528 /// Create a new Expectation.
2529 #v fn expect #ig (&mut self) -> &mut Expectation #tg #any_wc
2530 {
2531 self.store.entry(::mockall::Key::new::#keyid())
2532 .or_insert_with(|| Box::new(Expectations #tbf::new()))
2533 .downcast_mut::<Expectations #tg>()
2534 .unwrap()
2535 .expect()
2536 }
2537 }
2538 ).to_tokens(tokens)
2539 }
2540 }
2541