-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathmock_function.rs
2553 lines (2377 loc) · 96.5 KB
/
mock_function.rs
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// vim: tw=80
use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, format_ident, quote};
use syn::{
*,
punctuated::Punctuated,
spanned::Spanned
};
use crate::{
AttrFormatter,
HashSet,
compile_error,
concretize_args,
declosurefy,
expectation_visibility,
gen_keyid,
is_concretize,
lifetimes_to_generic_params,
lifetimes_to_generics,
merge_generics,
pat_is_self,
split_lifetimes,
staticize,
supersuperfy,
supersuperfy_generics,
};
/// Convert a trait object reference into a reference to a Boxed trait
///
/// # Returns
///
/// Returns `true` if it was necessary to box the type.
fn dedynify(ty: &mut Type) -> bool {
if let Type::Reference(ref mut tr) = ty {
if let Type::TraitObject(ref tto) = tr.elem.as_ref() {
if let Some(lt) = &tr.lifetime {
if lt.ident == "static" {
// For methods that return 'static references, the user can
// usually actually supply one, unlike nonstatic references.
// dedynify is unneeded and harmful in such cases.
//
// But we do need to add parens to prevent parsing errors
// when methods like returning add a `+ Send` to the output
// type.
*tr.elem = parse2(quote!((#tto))).unwrap();
return false;
}
}
*tr.elem = parse2(quote!(Box<#tto>)).unwrap();
return true;
}
}
false
}
/// Convert a special reference type like "&str" into a reference to its owned
/// type like "&String".
fn destrify(ty: &mut Type) {
if let Type::Reference(ref mut tr) = ty {
if let Some(lt) = &tr.lifetime {
if lt.ident == "static" {
// For methods that return 'static references, the user can
// usually actually supply one, unlike nonstatic references.
// destrify is unneeded and harmful in such cases.
return;
}
}
let path_ty: TypePath = parse2(quote!(Path)).unwrap();
let pathbuf_ty: Type = parse2(quote!(::std::path::PathBuf)).unwrap();
let str_ty: TypePath = parse2(quote!(str)).unwrap();
let string_ty: Type = parse2(quote!(::std::string::String)).unwrap();
let cstr_ty: TypePath = parse2(quote!(CStr)).unwrap();
let cstring_ty: Type = parse2(quote!(::std::ffi::CString)).unwrap();
let osstr_ty: TypePath = parse2(quote!(OsStr)).unwrap();
let osstring_ty: Type = parse2(quote!(::std::ffi::OsString)).unwrap();
match tr.elem.as_ref() {
Type::Path(ref path) if *path == cstr_ty =>
*tr.elem = cstring_ty,
Type::Path(ref path) if *path == osstr_ty =>
*tr.elem = osstring_ty,
Type::Path(ref path) if *path == path_ty =>
*tr.elem = pathbuf_ty,
Type::Path(ref path) if *path == str_ty =>
*tr.elem = string_ty,
Type::Slice(ts) => {
let inner = (*ts.elem).clone();
let mut segments = Punctuated::new();
segments.push(format_ident!("std").into());
segments.push(format_ident!("vec").into());
let mut v: PathSegment = format_ident!("Vec").into();
let mut abga_args = Punctuated::new();
abga_args.push(GenericArgument::Type(inner));
v.arguments = PathArguments::AngleBracketed(
AngleBracketedGenericArguments {
colon2_token: None,
lt_token: Token),
args: abga_args,
gt_token: Token),
}
);
segments.push(v);
*tr.elem = Type::Path(TypePath {
qself: None,
path: Path {
leading_colon: Some(Token)),
segments
}
});
},
_ => (), // Nothing to do
};
}
}
/// Return the owned version of the input.
fn ownify(ty: &Type) -> Type {
if let Type::Reference(ref tr) = &ty {
if tr.lifetime.as_ref().is_some_and(|lt| lt.ident == "static")
{
// Just a static expectation
ty.clone()
} else {
*tr.elem.clone()
}
} else {
ty.clone()
}
}
/// Add Send + Sync to a where clause
fn send_syncify(wc: &mut Option<WhereClause>, bounded_ty: Type) {
let mut bounds = Punctuated::new();
bounds.push(TypeParamBound::Trait(TraitBound {
paren_token: None,
modifier: TraitBoundModifier::None,
lifetimes: None,
path: Path::from(format_ident!("Send"))
}));
bounds.push(TypeParamBound::Trait(TraitBound {
paren_token: None,
modifier: TraitBoundModifier::None,
lifetimes: None,
path: Path::from(format_ident!("Sync"))
}));
if wc.is_none() {
*wc = Some(WhereClause {
where_token: <Token![where]>::default(),
predicates: Punctuated::new()
});
}
wc.as_mut().unwrap()
.predicates.push(
WherePredicate::Type(
PredicateType {
lifetimes: None,
bounded_ty,
colon_token: Default::default(),
bounds
}
)
);
}
/// Build a MockFunction.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Builder<'a> {
attrs: &'a [Attribute],
call_levels: Option<usize>,
concretize: bool,
levels: usize,
parent: Option<&'a Ident>,
sig: &'a Signature,
struct_: Option<&'a Ident>,
struct_generics: Option<&'a Generics>,
trait_: Option<&'a Ident>,
vis: &'a Visibility
}
impl<'a> Builder<'a> {
pub fn attrs(&mut self, attrs: &'a[Attribute]) -> &mut Self {
self.attrs = attrs;
if attrs.iter()
.any(is_concretize)
{
self.concretize = true;
}
self
}
pub fn build(self) -> MockFunction {
let mut argnames = Vec::new();
let mut argty = Vec::new();
let mut is_static = true;
let mut predexprs = Vec::new();
let mut predty = Vec::new();
let mut refpredty = Vec::new();
let (mut declosured_generics, declosured_inputs, call_exprs, sig) =
if self.concretize {
let (x, y, z, sig) = concretize_args(&self.sig.generics, self.sig);
(x, y, z, sig)
} else {
let (x, y, z) = declosurefy(&self.sig.generics, &self.sig.inputs);
(x, y, z, self.sig.clone())
};
// TODO: make concretize and declosurefy work for the same function
for fa in declosured_inputs.iter() {
if let FnArg::Typed(pt) = fa {
let argname = (*pt.pat).clone();
assert!(!pat_is_self(&argname));
let aty = supersuperfy(&pt.ty, self.levels);
if let Type::Reference(ref tr) = aty {
predexprs.push(quote!(#argname));
predty.push((*tr.elem).clone());
let tr2 = Type::Reference(TypeReference {
and_token: tr.and_token,
lifetime: None,
mutability: None,
elem: tr.elem.clone()
});
refpredty.push(tr2);
} else {
predexprs.push(quote!(&#argname));
predty.push(aty.clone());
let tr = TypeReference {
and_token: Token),
lifetime: None,
mutability: None,
elem: Box::new(aty.clone())
};
refpredty.push(Type::Reference(tr));
};
argnames.push(argname);
argty.push(aty.clone());
} else {
is_static = false;
}
}
let (output, boxed) = match self.sig.output {
ReturnType::Default => (
Type::Tuple(TypeTuple {
paren_token: token::Paren::default(),
elems: Punctuated::new(),
}),
false,
),
ReturnType::Type(_, ref ty) => {
let mut output_ty = supersuperfy(ty, self.levels);
destrify(&mut output_ty);
let boxed = dedynify(&mut output_ty);
(output_ty, boxed)
}
};
supersuperfy_generics(&mut declosured_generics, self.levels);
let owned_output = ownify(&output);
let mut return_ref = false;
let mut return_refmut = false;
if let Type::Reference(ref tr) = &output {
#[allow(clippy::unnecessary_map_or)]
if tr.lifetime.as_ref().map_or(true, |lt| lt.ident != "static")
{
if tr.mutability.is_none() {
return_ref = true;
} else {
return_refmut = true;
}
}
};
if is_static && (return_ref || return_refmut) {
compile_error(self.sig.span(),
"Mockall cannot mock static methods that return non-'static references. It's unclear what the return value's lifetime should be.");
}
let struct_generics = self.struct_generics.cloned()
.unwrap_or_default();
let (type_generics, salifetimes, srlifetimes) = split_lifetimes(
struct_generics.clone(),
&declosured_inputs,
&ReturnType::Type(<Token![->]>::default(),
Box::new(owned_output.clone()))
);
let srltg = lifetimes_to_generics(&srlifetimes);
let (call_generics, malifetimes, mrlifetimes) = split_lifetimes(
declosured_generics,
&declosured_inputs,
&ReturnType::Type(<Token![->]>::default(),
Box::new(owned_output.clone()))
);
let mrltg = lifetimes_to_generics(&mrlifetimes);
let cgenerics = merge_generics(&type_generics, &call_generics);
let egenerics = merge_generics(
&merge_generics(&cgenerics, &srltg),
&mrltg);
let alifetimes = salifetimes.into_iter()
.collect::<HashSet<LifetimeParam>>()
.union(&malifetimes.into_iter().collect::<HashSet<_>>())
.cloned()
.collect();
let fn_params = egenerics.type_params()
.map(|tp| tp.ident.clone())
.collect();
let call_levels = self.call_levels.unwrap_or(self.levels);
MockFunction {
alifetimes,
argnames,
argty,
attrs: self.attrs.to_vec(),
call_exprs,
call_generics,
call_vis: expectation_visibility(self.vis, call_levels),
concretize: self.concretize,
egenerics,
cgenerics,
fn_params,
is_static,
mod_ident: self.parent.unwrap_or(&Ident::new("FIXME", Span::call_site())).clone(),
output,
owned_output,
boxed,
predexprs,
predty,
refpredty,
return_ref,
return_refmut,
sig,
struct_: self.struct_.cloned(),
struct_generics,
trait_: self.trait_.cloned(),
type_generics,
privmod_vis: expectation_visibility(self.vis, self.levels)
}
}
/// How many levels of modules beneath the original function this one is
/// nested.
pub fn call_levels(&mut self, levels: usize) -> &mut Self {
self.call_levels = Some(levels);
self
}
/// How many levels of modules beneath the original function this one's
/// private module is nested.
pub fn levels(&mut self, levels: usize) -> &mut Self {
self.levels = levels;
self
}
/// # Arguments
///
/// * sig: The signature of the mockable function
/// * v: The visibility of the mockable function
pub fn new(sig: &'a Signature, vis: &'a Visibility) -> Self {
Builder {
attrs: &[],
concretize: false,
levels: 0,
call_levels: None,
parent: None,
sig,
struct_: None,
struct_generics: None,
trait_: None,
vis
}
}
/// Supply the name of the parent module
pub fn parent(&mut self, ident: &'a Ident) -> &mut Self {
self.parent = Some(ident);
self
}
/// Supply the name of the parent struct, if any
pub fn struct_(&mut self, ident: &'a Ident) -> &mut Self {
self.struct_= Some(ident);
self
}
/// Supply the Generics of the parent struct, if any
pub fn struct_generics(&mut self, generics: &'a Generics) -> &mut Self {
self.struct_generics = Some(generics);
self
}
/// Supply the name of the method's trait, if any
pub fn trait_(&mut self, ident: &'a Ident) -> &mut Self {
self.trait_ = Some(ident);
self
}
}
#[derive(Clone)]
pub(crate) struct MockFunction {
/// Lifetimes of the mocked method that relate to the arguments but not the
/// return value
alifetimes: Punctuated<LifetimeParam, token::Comma>,
/// Names of the method arguments
argnames: Vec<Pat>,
/// Types of the method arguments
argty: Vec<Type>,
/// any attributes on the original function, like #[inline]
pub attrs: Vec<Attribute>,
/// Expressions that should be used for Expectation::call's arguments
call_exprs: Vec<TokenStream>,
/// Generics used for the expectation call
call_generics: Generics,
/// Visibility of the mock function itself
call_vis: Visibility,
/// Are we turning generic arguments into concrete trait objects?
concretize: bool,
/// Generics of the Expectation object
egenerics: Generics,
/// Generics of the Common object
cgenerics: Generics,
/// The mock function's generic types as a list of types
fn_params: Vec<Ident>,
/// Is this for a static method or free function?
is_static: bool,
/// name of the function's parent module
mod_ident: Ident,
/// Output type of the Method, supersuperfied.
output: Type,
/// Owned version of the output type of the Method, supersuperfied.
///
/// If the real output type is a non-'static reference, then it will differ
/// from this field.
owned_output: Type,
/// True if the `owned_type` is boxed by `Box<>`.
boxed: bool,
/// Expressions that create the predicate arguments from the call arguments
predexprs: Vec<TokenStream>,
/// Types used for Predicates. Will be almost the same as args, but every
/// type will be a non-reference type.
predty: Vec<Type>,
/// Does the function return a non-'static reference?
return_ref: bool,
/// Does the function return a mutable reference?
return_refmut: bool,
/// References to every type in `predty`.
refpredty: Vec<Type>,
/// The signature of the mockable function
sig: Signature,
/// Name of the parent structure, if any
struct_: Option<Ident>,
/// Generics of the parent structure
struct_generics: Generics,
/// Name of this method's trait, if the method comes from a trait
trait_: Option<Ident>,
/// Type generics of the mock structure
type_generics: Generics,
/// Visibility of the expectation and its methods
privmod_vis: Visibility
}
impl MockFunction {
/// Return the mock function itself
///
/// # Arguments
///
/// * `modname`: Name of the parent struct's private module
// Supplying modname is an unfortunately hack. Ideally MockFunction
// wouldn't need to know that.
pub fn call(&self, modname: Option<&Ident>) -> impl ToTokens {
let attrs = AttrFormatter::new(&self.attrs)
.must_use(true)
.format();
let call_exprs = &self.call_exprs;
let (_, tg, _) = if self.is_method_generic() || self.is_static() {
&self.egenerics
} else {
&self.call_generics
}.split_for_impl();
let tbf = tg.as_turbofish();
let name = self.name();
let desc = self.desc();
let no_match_msg = quote!(std::format!(
"{}: No matching expectation found", #desc));
let sig = &self.sig;
let (vis, dead_code) = if self.trait_.is_some() {
(&Visibility::Inherited, quote!())
} else {
let dead_code = if let Visibility::Inherited = self.call_vis {
// This private method may be a helper only used by the struct's
// other methods, which we are mocking. If so, the mock method
// will be dead code. But we can't simply eliminate it, because
// it might also be used by other code in the same module.
quote!(#[allow(dead_code)])
} else {
quote!()
};
(&self.call_vis, dead_code)
};
// Add #[no_mangle] attribute to preserve the function name
// as-is, without mangling, for compatibility with C functions.
let no_mangle = if let Some(ref abi) = self.sig.abi {
if let Some(ref name) = abi.name {
if name.value().ne("Rust") {
quote!(#[no_mangle])
} else {
quote!()
}
} else {
// This is the same as extern "C"
quote!(#[no_mangle])
}
} else {
quote!()
};
let substruct_obj: TokenStream = if let Some(trait_) = &self.trait_ {
let ident = format_ident!("{}_expectations", trait_);
quote!(#ident.)
} else {
quote!()
};
let call = if self.return_refmut {
Ident::new("call_mut", Span::call_site())
} else {
Ident::new("call", Span::call_site())
};
let mut deref = quote!();
if self.boxed {
if self.return_ref {
deref = quote!(&**);
} else if self.return_refmut {
deref = quote!(&mut **);
}
}
if self.is_static {
let outer_mod_path = self.outer_mod_path(modname);
quote!(
// Don't add a doc string. The original is included in #attrs
#(#attrs)*
#dead_code
#no_mangle
#vis #sig {
use ::mockall::{ViaDebug, ViaNothing};
let no_match_msg = #no_match_msg;
#deref {
let __mockall_guard = #outer_mod_path::get_expectations()
.lock().unwrap();
/*
* TODO: catch panics, then gracefully release the mutex
* so it won't be poisoned. This requires bounding any
* generic parameters with UnwindSafe
*/
/* std::panic::catch_unwind(|| */
__mockall_guard.#call #tbf(#(#call_exprs,)*)
/*)*/
}.expect(&no_match_msg)
}
)
} else {
quote!(
// Don't add a doc string. The original is included in #attrs
#(#attrs)*
#dead_code
#no_mangle
#vis #sig {
use ::mockall::{ViaDebug, ViaNothing};
let no_match_msg = #no_match_msg;
#deref self.#substruct_obj #name.#call #tbf(#(#call_exprs,)*)
.expect(&no_match_msg)
}
)
}
}
/// Return this method's contribution to its parent's checkpoint method
pub fn checkpoint(&self) -> impl ToTokens {
let attrs = AttrFormatter::new(&self.attrs)
.doc(false)
.format();
let inner_mod_ident = self.inner_mod_ident();
if self.is_static {
quote!(
#(#attrs)*
{
let __mockall_timeses = #inner_mod_ident::get_expectations().lock()
.unwrap()
.checkpoint()
.collect::<Vec<_>>();
}
)
} else {
let name = &self.name();
quote!(#(#attrs)* { self.#name.checkpoint(); })
}
}
/// Return a function that creates a Context object for this function
///
/// # Arguments
///
/// * `modname`: Name of the parent struct's private module
// Supplying modname is an unfortunately hack. Ideally MockFunction
// wouldn't need to know that.
pub fn context_fn(&self, modname: Option<&Ident>) -> impl ToTokens {
let attrs = AttrFormatter::new(&self.attrs)
.doc(false)
.format();
let context_docstr = format!("Create a [`Context`]({}{}/struct.Context.html) for mocking the `{}` method",
modname.map(|m| format!("{m}/")).unwrap_or_default(),
self.inner_mod_ident(),
self.name());
let context_ident = format_ident!("{}_context", self.name());
let (_, tg, _) = self.type_generics.split_for_impl();
let outer_mod_path = self.outer_mod_path(modname);
let v = &self.call_vis;
quote!(
#(#attrs)*
#[doc = #context_docstr]
#v fn #context_ident() -> #outer_mod_path::Context #tg
{
#outer_mod_path::Context::default()
}
)
}
/// Generate a code fragment that will print a description of the invocation
fn desc(&self) -> impl ToTokens {
let argnames = &self.argnames;
let name = if let Some(s) = &self.struct_ {
format!("{}::{}", s, self.sig.ident)
} else {
format!("{}::{}", self.mod_ident, self.sig.ident)
};
#[allow(clippy::literal_string_with_formatting_args)]
let fields = vec!["{:?}"; argnames.len()].join(", ");
let fstr = format!("{name}({fields})");
quote!(std::format!(#fstr, #((&&::mockall::ArgPrinter(&#argnames)).debug_string()),*))
}
/// Generate code for the expect_ method
///
/// # Arguments
///
/// * `modname`: Name of the parent struct's private module
/// * `self_args`: If supplied, these are the
/// AngleBracketedGenericArguments of the self type of the
/// trait impl. e.g. The `T` in `impl Foo for Bar<T>`.
// Supplying modname is an unfortunately hack. Ideally MockFunction
// wouldn't need to know that.
pub fn expect(&self, modname: &Ident, self_args: Option<&PathArguments>)
-> impl ToTokens
{
let attrs = AttrFormatter::new(&self.attrs)
.doc(false)
.format();
let name = self.name();
let expect_ident = format_ident!("expect_{}", name);
let expectation_obj = self.expectation_obj(self_args);
let funcname = &self.sig.ident;
let (_, tg, _) = if self.is_method_generic() {
&self.egenerics
} else {
&self.call_generics
}.split_for_impl();
let (ig, _, wc) = self.call_generics.split_for_impl();
let mut wc = wc.cloned();
if self.is_method_generic() && (self.return_ref || self.return_refmut) {
// Add Senc + Sync, required for downcast, since Expectation
// stores an Option<#owned_output>
send_syncify(&mut wc, self.owned_output.clone());
}
let tbf = tg.as_turbofish();
let vis = &self.call_vis;
#[cfg(not(feature = "nightly_derive"))]
let must_use = quote!(#[must_use =
"Must set return value when not using the \"nightly\" feature"
]);
#[cfg(feature = "nightly_derive")]
let must_use = quote!();
let substruct_obj = if let Some(trait_) = &self.trait_ {
let ident = format_ident!("{trait_}_expectations");
quote!(#ident.)
} else {
quote!()
};
let docstr = format!("Create an [`Expectation`]({}/{}/struct.Expectation.html) for mocking the `{}` method",
modname, self.inner_mod_ident(), funcname);
quote!(
#must_use
#[doc = #docstr]
#(#attrs)*
#vis fn #expect_ident #ig(&mut self)
-> &mut #modname::#expectation_obj
#wc
{
self.#substruct_obj #name.expect #tbf()
}
)
}
/// Return the name of this function's expecation object
fn expectation_obj(&self, self_args: Option<&PathArguments>)
-> impl ToTokens
{
let inner_mod_ident = self.inner_mod_ident();
if let Some(PathArguments::AngleBracketed(abga)) = self_args {
// staticize any lifetimes that might be present in the Expectation
// object but not in the self args. These come from the method's
// return type.
let mut abga2 = abga.clone();
for _ in self.egenerics.lifetimes() {
let lt = Lifetime::new("'static", Span::call_site());
let la = GenericArgument::Lifetime(lt);
abga2.args.insert(0, la);
}
assert!(!self.is_method_generic(),
"specific impls with generic methods are TODO");
quote!(#inner_mod_ident::Expectation #abga2)
} else {
// staticize any lifetimes. This is necessary for methods that
// return non-static types, because the Expectation itself must be
// 'static.
let segenerics = staticize(&self.egenerics);
let (_, tg, _) = segenerics.split_for_impl();
quote!(#inner_mod_ident::Expectation #tg)
}
}
/// Return the name of this function's expecations object
pub fn expectations_obj(&self) -> impl ToTokens {
let inner_mod_ident = self.inner_mod_ident();
if self.is_method_generic() {
quote!(#inner_mod_ident::GenericExpectations)
} else {
quote!(#inner_mod_ident::Expectations)
}
}
pub fn field_definition(&self, modname: Option<&Ident>) -> TokenStream {
let name = self.name();
let attrs = AttrFormatter::new(&self.attrs)
.doc(false)
.format();
let expectations_obj = &self.expectations_obj();
if self.is_method_generic() {
quote!(#(#attrs)* #name: #modname::#expectations_obj)
} else {
// staticize any lifetimes. This is necessary for methods that
// return non-static types, because the Expectation itself must be
// 'static.
let segenerics = staticize(&self.egenerics);
let (_, tg, _) = segenerics.split_for_impl();
quote!(#(#attrs)* #name: #modname::#expectations_obj #tg)
}
}
/// Human-readable name of the mock function
fn funcname(&self) -> String {
if let Some(si) = &self.struct_ {
format!("{}::{}", si, self.name())
} else {
format!("{}", self.name())
}
}
fn hrtb(&self) -> Option<BoundLifetimes> {
if self.alifetimes.is_empty() {
None
} else {
let lifetimes = lifetimes_to_generic_params(&self.alifetimes);
Some(BoundLifetimes {
lifetimes,
lt_token: <Token![<]>::default(),
gt_token: <Token![>]>::default(),
.. Default::default()
})
}
}
fn is_expectation_generic(&self) -> bool {
self.egenerics.params.iter().any(|p| {
matches!(p, GenericParam::Type(_))
}) || self.egenerics.where_clause.is_some()
}
/// Is the mock method generic (as opposed to a non-generic method of a
/// generic mock struct)?
pub fn is_method_generic(&self) -> bool {
self.call_generics.params.iter().any(|p| {
matches!(p, GenericParam::Type(_))
}) || self.call_generics.where_clause.is_some()
}
fn outer_mod_path(&self, modname: Option<&Ident>) -> Path {
let mut path = if let Some(m) = modname {
Path::from(PathSegment::from(m.clone()))
} else {
Path { leading_colon: None, segments: Punctuated::new() }
};
path.segments.push(PathSegment::from(self.inner_mod_ident()));
path
}
fn inner_mod_ident(&self) -> Ident {
format_ident!("__{}", &self.name())
}
pub fn is_static(&self) -> bool {
self.is_static
}
pub fn name(&self) -> &Ident {
&self.sig.ident
}
/// Generate code for this function's private module
pub fn priv_module(&self) -> impl ToTokens {
let attrs = AttrFormatter::new(&self.attrs)
.doc(false)
.format();
let common = &Common{f: self};
let context = &Context{f: self};
let expectation: Box<dyn ToTokens> = if self.return_ref {
Box::new(RefExpectation{f: self})
} else if self.return_refmut {
Box::new(RefMutExpectation{f: self})
} else {
Box::new(StaticExpectation{f: self})
};
let expectations: Box<dyn ToTokens> = if self.return_ref {
Box::new(RefExpectations{f: self})
} else if self.return_refmut {
Box::new(RefMutExpectations{f: self})
} else {
Box::new(StaticExpectations{f: self})
};
let generic_expectations = GenericExpectations{f: self};
let guard: Box<dyn ToTokens> = if self.is_expectation_generic() {
Box::new(GenericExpectationGuard{f: self})
} else {
Box::new(ConcreteExpectationGuard{f: self})
};
let matcher = &Matcher{f: self};
let std_mutexguard = if self.is_static {
quote!(use ::std::sync::MutexGuard;)
} else {
quote!()
};
let inner_mod_ident = self.inner_mod_ident();
let rfunc: Box<dyn ToTokens> = if self.return_ref {
Box::new(RefRfunc{f: self})
} else if self.return_refmut {
Box::new(RefMutRfunc{f: self})
} else {
Box::new(StaticRfunc{f: self})
};
quote!(
#(#attrs)*
#[allow(missing_docs)]
#[allow(clippy::too_many_arguments, clippy::indexing_slicing)]
pub mod #inner_mod_ident {
use super::*;
use ::mockall::CaseTreeExt;
#std_mutexguard
use ::std::{
boxed::Box,
mem,
ops::{DerefMut, Range},
sync::Mutex,
vec::Vec,
};
#rfunc
#matcher
#common
#expectation
#expectations
#generic_expectations
#guard
#context
}
)
}
}
/// Holds parts of the expectation that are common for all output types
struct Common<'a> {
f: &'a MockFunction
}
impl ToTokens for Common<'_> {
fn to_tokens(&self, tokens: &mut TokenStream) {
let argnames = &self.f.argnames;
let predty = &self.f.predty;
let hrtb = self.f.hrtb();
let funcname = self.f.funcname();
let (ig, tg, wc) = self.f.cgenerics.split_for_impl();
let lg = lifetimes_to_generics(&self.f.alifetimes);
let refpredty = &self.f.refpredty;
let with_generics_idents = (0..self.f.predty.len())
.map(|i| format_ident!("MockallMatcher{i}"))
.collect::<Vec<_>>();
let with_generics = with_generics_idents.iter()
.zip(self.f.predty.iter())
.map(|(id, mt)|
quote!(#id: #hrtb ::mockall::Predicate<#mt> + Send + 'static, )
).collect::<TokenStream>();
let with_args = self.f.argnames.iter()
.zip(with_generics_idents.iter())
.map(|(argname, id)| quote!(#argname: #id, ))
.collect::<TokenStream>();
let boxed_withargs = argnames.iter()
.map(|aa| quote!(Box::new(#aa), ))
.collect::<TokenStream>();
let with_method = if self.f.concretize {
quote!(
// No `with` method when concretizing generics
)
} else {
quote!(
fn with<#with_generics>(&mut self, #with_args)
{
let mut __mockall_guard = self.matcher.lock().unwrap();
*__mockall_guard.deref_mut() =
Matcher::Pred(Box::new((#boxed_withargs)));
}
)
};
quote!(
/// Holds the stuff that is independent of the output type
struct Common #ig #wc {
matcher: Mutex<Matcher #tg>,
seq_handle: Option<::mockall::SeqHandle>,
times: ::mockall::Times
}
impl #ig std::default::Default for Common #tg #wc
{
fn default() -> Self {
Common {
matcher: Mutex::new(Matcher::default()),
seq_handle: None,
times: ::mockall::Times::default()
}
}
}
impl #ig Common #tg #wc {
fn call(&self, desc: &str) {
self.times.call()
.unwrap_or_else(|m| {
let desc = std::format!(
"{}", self.matcher.lock().unwrap());
panic!("{}: Expectation({}) {}", #funcname, desc,
m);
});
self.verify_sequence(desc);
if ::mockall::ExpectedCalls::TooFew != self.times.is_satisfied() {
self.satisfy_sequence()
}
}
fn in_sequence(&mut self, __mockall_seq: &mut ::mockall::Sequence)
-> &mut Self
{
assert!(self.times.is_exact(),
"Only Expectations with an exact call count have sequences");
self.seq_handle = Some(__mockall_seq.next_handle());
self
}
fn is_done(&self) -> bool {
self.times.is_done()
}
#[allow(clippy::ptr_arg)]
#[allow(clippy::ref_option)]
fn matches #lg (&self, #( #argnames: &#predty, )*) -> bool {
self.matcher.lock().unwrap().matches(#(#argnames, )*)
}
/// Forbid this expectation from ever being called.
fn never(&mut self) {
self.times.never();
}
fn satisfy_sequence(&self) {
if let Some(__mockall_handle) = &self.seq_handle {
__mockall_handle.satisfy()
}
}
/// Expect this expectation to be called any number of times