Debian Codegraph @

src/mockable_struct.rs

raw symbols SCIP
1 // vim: tw=80
2 use proc_macro2::{Span, TokenStream};
3 use quote::{format_ident, quote};
4 use syn::{
5 *,
6 parse::{Parse, ParseStream},
7 spanned::Spanned
8 };
9
10 use crate::{
11 Attrs,
12 compile_error,
13 deanonymize,
14 deimplify,
15 demutify,
16 deselfify,
17 deselfify_args,
18 dewhereselfify,
19 find_ident_from_path,
20 gen_mock_ident,
21 AttrFormatter,
22 };
23
24 /// Make any implicit lifetime parameters explicit
25 fn add_lifetime_parameters(sig: &mut Signature) {
26 fn add_to_trait_object(generics: &mut Generics, var: &Pat, to: &mut TypeTraitObject) {
27 let mut has_lifetime = false;
28 for bound in to.bounds.iter() {
29 if let TypeParamBound::Lifetime(_) = bound {
30 has_lifetime = true;
31 }
32 }
33 if ! has_lifetime {
34 let arg_ident = match *var {
35 Pat::Wild(_) => {
36 compile_error(var.span(),
37 "Mocked methods must have named arguments");
38 format_ident!("dont_care")
39 },
40 Pat::Ident(ref pat_ident) => {
41 if let Some(r) = &pat_ident.by_ref {
42 compile_error(r.span(),
43 "Mockall does not support by-reference argument bindings");
44 }
45 if let Some((_at, subpat)) = &pat_ident.subpat {
46 compile_error(subpat.span(),
47 "Mockall does not support subpattern bindings");
48 }
49 pat_ident.ident.clone()
50 },
51 _ => {
52 compile_error(var.span(),
53 "Unsupported argument type");
54 format_ident!("dont_care")
55 }
56 };
57 let s = format!("'__mockall_{arg_ident}");
58 let span = Span::call_site();
59 let lt = Lifetime::new(&s, span);
60 to.bounds.push(TypeParamBound::Lifetime(lt.clone()));
61 generics.lt_token.get_or_insert(Token![<](span));
62 generics.gt_token.get_or_insert(Token![>](span));
63 let gpl = GenericParam::Lifetime(LifetimeParam::new(lt));
64 generics.params.push(gpl);
65 }
66 }
67
68 fn add_to_type(generics: &mut Generics, var: &Pat, ty: &mut Type) {
69 match ty {
70 Type::Array(ta) => add_to_type(generics, var, ta.elem.as_mut()),
71 Type::BareFn(_) => (),
72 Type::ImplTrait(_) => (),
73 Type::Path(_) => (),
74 Type::Ptr(_) => (),
75 Type::Reference(tr) => {
76 match tr.elem.as_mut() {
77 Type::Paren(tp) => {
78 if let Type::TraitObject(to) = tp.elem.as_mut() {
79 add_to_trait_object(generics, var, to);
80 } else {
81 add_to_type(generics, var, tr.elem.as_mut());
82 }
83 },
84 Type::TraitObject(to) => {
85 add_to_trait_object(generics, var, to);
86 // We need to wrap it in a Paren. Otherwise it won't be
87 // syntactically valid after we add a lifetime bound,
88 // due to a "ambiguous `+` in a type" error
89 *tr.elem = Type::Paren(TypeParen {
90 paren_token: token::Paren::default(),
91 elem: Box::new(Type::TraitObject(to.clone()))
92 });
93 },
94 _ => add_to_type(generics, var, tr.elem.as_mut()),
95 }
96 },
97 Type::Slice(ts) => add_to_type(generics, var, ts.elem.as_mut()),
98 Type::Tuple(tt) => {
99 for ty in tt.elems.iter_mut() {
100 add_to_type(generics, var, ty)
101 }
102 },
103 _ => compile_error(ty.span(), "unsupported type in this position")
104 }
105 }
106
107 for arg in sig.inputs.iter_mut() {
108 if let FnArg::Typed(pt) = arg {
109 add_to_type(&mut sig.generics, &pt.pat, &mut pt.ty)
110 }
111 }
112 }
113
114 /// Generate a #[derive(Debug)] Attribute
115 fn derive_debug() -> Attribute {
116 let ml = parse2(quote!(derive(Debug))).unwrap();
117 Attribute {
118 pound_token: <Token![#]>::default(),
119 style: AttrStyle::Outer,
120 bracket_token: token::Bracket::default(),
121 meta: Meta::List(ml)
122 }
123 }
124
125 /// Add "Mock" to the front of the named type
126 fn mock_ident_in_type(ty: &mut Type) {
127 match ty {
128 Type::Path(type_path) => {
129 if type_path.path.segments.len() != 1 {
130 compile_error(type_path.path.span(),
131 "mockall_derive only supports structs defined in the current module");
132 return;
133 }
134 let ident = &mut type_path.path.segments.last_mut().unwrap().ident;
135 *ident = gen_mock_ident(ident)
136 },
137 x => {
138 compile_error(x.span(),
139 "mockall_derive only supports mocking traits and structs");
140 }
141 };
142 }
143
144 /// Performs transformations on the ItemImpl to make it mockable
145 fn mockable_item_impl(mut impl_: ItemImpl, name: &Ident, generics: &Generics)
146 -> ItemImpl
147 {
148 mock_ident_in_type(&mut impl_.self_ty);
149 for item in impl_.items.iter_mut() {
150 if let ImplItem::Fn(ref mut iim) = item {
151 mockable_method(iim, name, generics);
152 }
153 }
154 impl_
155 }
156
157 /// Performs transformations on the method to make it mockable
158 fn mockable_method(meth: &mut ImplItemFn, name: &Ident, generics: &Generics)
159 {
160 demutify(&mut meth.sig.inputs);
161 deselfify_args(&mut meth.sig.inputs, name, generics);
162 add_lifetime_parameters(&mut meth.sig);
163 deimplify(&mut meth.sig.output);
164 dewhereselfify(&mut meth.sig.generics);
165 if let ReturnType::Type(_, ty) = &mut meth.sig.output {
166 deselfify(ty, name, generics);
167 deanonymize(ty);
168 }
169 sanity_check_sig(&meth.sig);
170 }
171
172 /// Performs transformations on the method to make it mockable
173 fn mockable_trait_method(
174 meth: &mut TraitItemFn,
175 name: &Ident,
176 generics: &Generics)
177 {
178 demutify(&mut meth.sig.inputs);
179 deselfify_args(&mut meth.sig.inputs, name, generics);
180 add_lifetime_parameters(&mut meth.sig);
181 deimplify(&mut meth.sig.output);
182 dewhereselfify(&mut meth.sig.generics);
183 if let ReturnType::Type(_, ty) = &mut meth.sig.output {
184 deselfify(ty, name, generics);
185 deanonymize(ty);
186 }
187 sanity_check_sig(&meth.sig);
188 }
189
190 /// Generates a mockable item impl from a trait method definition
191 fn mockable_trait(trait_: ItemTrait, name: &Ident, generics: &Generics)
192 -> ItemImpl
193 {
194 let items = trait_.items.into_iter()
195 .map(|ti| {
196 match ti {
197 TraitItem::Fn(mut tif) => {
198 mockable_trait_method(&mut tif, name, generics);
199 ImplItem::Fn(tif2iif(tif, &Visibility::Inherited))
200 },
201 TraitItem::Const(tic) => {
202 ImplItem::Const(tic2iic(tic, &Visibility::Inherited))
203 },
204 TraitItem::Type(tit) => {
205 ImplItem::Type(tit2iit(tit, &Visibility::Inherited))
206 },
207 _ => {
208 compile_error(ti.span(), "Unsupported in this context");
209 ImplItem::Verbatim(TokenStream::new())
210 }
211 }
212 }).collect::<Vec<_>>();
213 let mut trait_path = Path::from(trait_.ident);
214 let mut struct_path = Path::from(name.clone());
215 let (_, stg, _) = generics.split_for_impl();
216 let (_, ttg, _) = trait_.generics.split_for_impl();
217 if let Ok(abga) = parse2::<AngleBracketedGenericArguments>(quote!(#stg)) {
218 struct_path.segments.last_mut().unwrap().arguments =
219 PathArguments::AngleBracketed(abga);
220 }
221 if let Ok(abga) = parse2::<AngleBracketedGenericArguments>(quote!(#ttg)) {
222 trait_path.segments.last_mut().unwrap().arguments =
223 PathArguments::AngleBracketed(abga);
224 }
225 let self_ty = Box::new(Type::Path(TypePath{
226 qself: None,
227 path: struct_path,
228 }));
229 ItemImpl {
230 attrs: trait_.attrs,
231 defaultness: None,
232 unsafety: trait_.unsafety,
233 impl_token: <Token![impl]>::default(),
234 generics: generics.clone(),
235 trait_: Some((None, trait_path, <Token![for]>::default())),
236 self_ty,
237 brace_token: trait_.brace_token,
238 items
239 }
240 }
241
242 fn sanity_check_sig(sig: &Signature) {
243 for arg in sig.inputs.iter() {
244 if let FnArg::Typed(pt) = arg {
245 if let Type::ImplTrait(it) = pt.ty.as_ref() {
246 let bounds = &it.bounds;
247 let s = format!(
248 "Mockall does not support \"impl trait\" in argument position. Use \"T: {}\" instead",
249 quote!(#bounds)
250 );
251 compile_error(it.span(), &s);
252 }
253 }
254 }
255 }
256
257 /// Converts a TraitItemConst into an ImplItemConst
258 fn tic2iic(tic: TraitItemConst, vis: &syn::Visibility) -> ImplItemConst {
259 let span = tic.span();
260 let (eq_token, expr) = tic.default.unwrap_or_else(|| {
261 compile_error(span,
262 "Mocked associated consts must have a default implementation");
263 (<Token![=]>::default(), Expr::Verbatim(TokenStream::new()))
264 });
265 ImplItemConst {
266 attrs: tic.attrs,
267 vis: vis.clone(),
268 defaultness: None,
269 const_token: tic.const_token,
270 generics: tic.generics,
271 ident: tic.ident,
272 colon_token: tic.colon_token,
273 ty: tic.ty,
274 eq_token,
275 expr,
276 semi_token: tic.semi_token
277 }
278 }
279
280 /// Converts a TraitItemFn into an ImplItemFn
281 fn tif2iif(m: syn::TraitItemFn, vis: &syn::Visibility)
282 -> syn::ImplItemFn
283 {
284 let empty_block = Block {
285 brace_token: token::Brace::default(),
286 stmts: Vec::new()
287 };
288 syn::ImplItemFn{
289 attrs: m.attrs,
290 vis: vis.clone(),
291 defaultness: None,
292 sig: m.sig,
293 block: empty_block
294 }
295 }
296
297 /// Converts a TraitItemType into an ImplItemType
298 fn tit2iit(tit: TraitItemType, vis: &Visibility) -> ImplItemType {
299 let span = tit.span();
300 let (eq_token, ty) = tit.default.unwrap_or_else(|| {
301 compile_error(span,
302 "associated types in mock! must be fully specified");
303 (token::Eq::default(), Type::Verbatim(TokenStream::new()))
304 });
305 ImplItemType {
306 attrs: tit.attrs,
307 vis: vis.clone(),
308 defaultness: None,
309 type_token: tit.type_token,
310 ident: tit.ident,
311 generics: tit.generics,
312 eq_token,
313 ty,
314 semi_token: tit.semi_token,
315 }
316 }
317
318 /// Like a TraitItemFn, but with a visibility
319 struct TraitItemVFn {
320 pub vis: Visibility,
321 pub tif: TraitItemFn
322 }
323
324 impl Parse for TraitItemVFn {
325 fn parse(input: ParseStream) -> syn::parse::Result<Self> {
326 let attrs = input.call(Attribute::parse_outer)?;
327 let vis: syn::Visibility = input.parse()?;
328 let mut tif: TraitItemFn = input.parse()?;
329 tif.attrs = attrs;
330 Ok(Self{vis, tif})
331 }
332 }
333
334 pub(crate) struct MockableStruct {
335 pub attrs: Vec<Attribute>,
336 pub consts: Vec<ImplItemConst>,
337 pub generics: Generics,
338 /// Inherent methods of the mockable struct
339 pub methods: Vec<ImplItemFn>,
340 pub name: Ident,
341 pub vis: Visibility,
342 pub impls: Vec<ItemImpl>,
343 }
344
345 impl MockableStruct {
346 /// Does this struct derive Debug?
347 pub fn derives_debug(&self) -> bool {
348 self.attrs.iter()
349 .any(|attr|{
350 let mut derive_debug = false;
351 if attr.path().is_ident("derive") {
352 attr.parse_nested_meta(|meta| {
353 if meta.path.is_ident("Debug") {
354 derive_debug = true;
355 }
356 Ok(())
357 }).unwrap();
358 }
359 derive_debug
360 })
361 }
362 }
363
364 impl From<(Attrs, ItemTrait)> for MockableStruct {
365 fn from((attrs, item_trait): (Attrs, ItemTrait)) -> MockableStruct {
366 let trait_ = attrs.substitute_trait(&item_trait);
367 // Strip "must_use" from a trait definition. For traits, the "must_use"
368 // should apply only when the trait is used like "impl Trait" or "dyn
369 // Trait". So it shouldn't necessarily affect the mock struct that
370 // implements the trait.
371 let mut attrs = AttrFormatter::new(&trait_.attrs)
372 .doc(true)
373 .async_trait(true)
374 .must_use(false)
375 .format();
376 attrs.push(derive_debug());
377 let vis = trait_.vis.clone();
378 let name = gen_mock_ident(&trait_.ident);
379 let generics = trait_.generics.clone();
380 let impls = vec![mockable_trait(trait_, &name, &generics)];
381 MockableStruct {
382 attrs,
383 consts: Vec::new(),
384 vis,
385 name,
386 generics,
387 methods: Vec::new(),
388 impls
389 }
390 }
391 }
392
393 impl From<ItemImpl> for MockableStruct {
394 fn from(mut item_impl: ItemImpl) -> MockableStruct {
395 let name = match &*item_impl.self_ty {
396 Type::Path(type_path) => {
397 let n = find_ident_from_path(&type_path.path).0;
398 gen_mock_ident(&n)
399 },
400 x => {
401 compile_error(x.span(),
402 "mockall_derive only supports mocking traits and structs");
403 Ident::new("", Span::call_site())
404 }
405 };
406 let mut attrs = item_impl.attrs.clone();
407 attrs.push(derive_debug());
408 let mut consts = Vec::new();
409 let generics = item_impl.generics.clone();
410 let mut methods = Vec::new();
411 let vis = Visibility::Public(Token![pub](Span::call_site()));
412 let mut impls = Vec::new();
413 if let Some((bang, _path, _)) = &item_impl.trait_ {
414 if bang.is_some() {
415 compile_error(bang.span(), "Unsupported by automock");
416 }
417
418 // Substitute any associated types in this ItemImpl.
419 // NB: this would not be necessary if the user always fully
420 // qualified them, e.g. `<Self as MyTrait>::MyType`
421 let mut attrs = Attrs::default();
422 for item in item_impl.items.iter() {
423 match item {
424 ImplItem::Const(_iic) =>
425 (),
426 ImplItem::Fn(_meth) =>
427 (),
428 ImplItem::Type(ty) => {
429 attrs.attrs.insert(ty.ident.clone(), ty.ty.clone());
430 },
431 x => compile_error(x.span(), "Unsupported by automock")
432 }
433 }
434 attrs.substitute_item_impl(&mut item_impl);
435 impls.push(mockable_item_impl(item_impl, &name, &generics));
436 } else {
437 for item in item_impl.items.into_iter() {
438 match item {
439 ImplItem::Fn(mut meth) => {
440 mockable_method(&mut meth, &name, &item_impl.generics);
441 methods.push(meth)
442 },
443 ImplItem::Const(iic) => consts.push(iic),
444 // Rust doesn't allow types in an inherent impl
445 x => compile_error(x.span(),
446 "Unsupported by Mockall in this context"),
447 }
448 }
449 };
450 MockableStruct {
451 attrs,
452 consts,
453 generics,
454 methods,
455 name,
456 vis,
457 impls,
458 }
459 }
460 }
461
462 impl Parse for MockableStruct {
463 fn parse(input: ParseStream) -> syn::parse::Result<Self> {
464 let attrs = input.call(syn::Attribute::parse_outer)?;
465 let vis: syn::Visibility = input.parse()?;
466 let original_name: syn::Ident = input.parse()?;
467 let mut generics: syn::Generics = input.parse()?;
468 let wc: Option<syn::WhereClause> = input.parse()?;
469 generics.where_clause = wc;
470 let name = gen_mock_ident(&original_name);
471 let impl_content;
472 let _brace_token = braced!(impl_content in input);
473 let mut consts = Vec::new();
474 let mut methods = Vec::new();
475 while !impl_content.is_empty() {
476 let item: ImplItem = impl_content.parse()?;
477 match item {
478 ImplItem::Verbatim(ts) => {
479 let tivf: TraitItemVFn = parse2(ts)?;
480 let mut iim = tif2iif(tivf.tif, &tivf.vis);
481 mockable_method(&mut iim, &name, &generics);
482 methods.push(iim);
483 }
484 ImplItem::Const(iic) => consts.push(iic),
485 _ => {
486 return Err(input.error("Unsupported in this context"));
487 }
488 }
489 }
490
491 let mut impls = Vec::new();
492 while !input.is_empty() {
493 let item: Item = input.parse()?;
494 match item {
495 Item::Impl(mut ii) => {
496 for item in ii.items.iter_mut() {
497 // Convert any methods that syn couldn't parse as
498 // ImplItemFn.
499 if let ImplItem::Verbatim(ts) = item {
500 let tif: TraitItemFn = parse2(ts.clone()).unwrap();
501 let iim = tif2iif(tif, &Visibility::Inherited);
502 *item = ImplItem::Fn(iim);
503 }
504 }
505 impls.push(mockable_item_impl(ii, &name, &generics));
506 }
507 _ => return Err(input.error("Unsupported in this context")),
508 }
509 }
510
511 Ok(
512 MockableStruct {
513 attrs,
514 consts,
515 generics,
516 methods,
517 name,
518 vis,
519 impls
520 }
521 )
522 }
523 }
524
525 #[cfg(test)]
526 mod t {
527 use super::*;
528
529 mod add_lifetime_parameters {
530 use super::*;
531
532 #[test]
533 fn array() {
534 let mut meth: TraitItemFn = parse2(quote!(
535 fn foo(&self, x: [&dyn T; 1]);
536 )).unwrap();
537 add_lifetime_parameters(&mut meth.sig);
538 assert_eq!(
539 quote!(fn foo<'__mockall_x>(&self, x: [&(dyn T + '__mockall_x); 1]);)
540 .to_string(),
541 quote!(#meth).to_string()
542 );
543 }
544
545 #[test]
546 fn bare_fn_with_named_args() {
547 let mut meth: TraitItemFn = parse2(quote!(
548 fn foo(&self, x: fn(&dyn T));
549 )).unwrap();
550 add_lifetime_parameters(&mut meth.sig);
551 assert_eq!(
552 quote!(fn foo(&self, x: fn(&dyn T));).to_string(),
553 quote!(#meth).to_string()
554 );
555 }
556
557 #[test]
558 fn plain() {
559 let mut meth: TraitItemFn = parse2(quote!(
560 fn foo(&self, x: &dyn T);
561 )).unwrap();
562 add_lifetime_parameters(&mut meth.sig);
563 assert_eq!(
564 quote!(fn foo<'__mockall_x>(&self, x: &(dyn T + '__mockall_x));)
565 .to_string(),
566 quote!(#meth).to_string()
567 );
568 }
569
570 #[test]
571 fn slice() {
572 let mut meth: TraitItemFn = parse2(quote!(
573 fn foo(&self, x: &[&dyn T]);
574 )).unwrap();
575 add_lifetime_parameters(&mut meth.sig);
576 assert_eq!(
577 quote!(fn foo<'__mockall_x>(&self, x: &[&(dyn T + '__mockall_x)]);)
578 .to_string(),
579 quote!(#meth).to_string()
580 );
581 }
582
583 #[test]
584 fn tuple() {
585 let mut meth: TraitItemFn = parse2(quote!(
586 fn foo(&self, x: (&dyn T, u32));
587 )).unwrap();
588 add_lifetime_parameters(&mut meth.sig);
589 assert_eq!(
590 quote!(fn foo<'__mockall_x>(&self, x: (&(dyn T + '__mockall_x), u32));)
591 .to_string(),
592 quote!(#meth).to_string()
593 );
594 }
595
596 #[test]
597 fn with_anonymous_lifetime() {
598 let mut meth: TraitItemFn = parse2(quote!(
599 fn foo(&self, x: &(dyn T + '_));
600 )).unwrap();
601 add_lifetime_parameters(&mut meth.sig);
602 assert_eq!(
603 quote!(fn foo(&self, x: &(dyn T + '_));).to_string(),
604 quote!(#meth).to_string()
605 );
606 }
607
608 #[test]
609 fn with_parens() {
610 let mut meth: TraitItemFn = parse2(quote!(
611 fn foo(&self, x: &(dyn T));
612 )).unwrap();
613 add_lifetime_parameters(&mut meth.sig);
614 assert_eq!(
615 quote!(fn foo<'__mockall_x>(&self, x: &(dyn T + '__mockall_x));)
616 .to_string(),
617 quote!(#meth).to_string()
618 );
619 }
620
621 #[test]
622 fn with_lifetime_parameter() {
623 let mut meth: TraitItemFn = parse2(quote!(
624 fn foo<'a>(&self, x: &(dyn T + 'a));
625 )).unwrap();
626 add_lifetime_parameters(&mut meth.sig);
627 assert_eq!(
628 quote!(fn foo<'a>(&self, x: &(dyn T + 'a));).to_string(),
629 quote!(#meth).to_string()
630 );
631 }
632
633 #[test]
634 fn with_static_lifetime() {
635 let mut meth: TraitItemFn = parse2(quote!(
636 fn foo(&self, x: &(dyn T + 'static));
637 )).unwrap();
638 add_lifetime_parameters(&mut meth.sig);
639 assert_eq!(
640 quote!(fn foo(&self, x: &(dyn T + 'static));).to_string(),
641 quote!(#meth).to_string()
642 );
643 }
644
645 }
646
647 mod sanity_check_sig {
648 use super::*;
649
650 #[test]
651 #[should_panic(expected = "Mockall does not support \"impl trait\" in argument position. Use \"T: SomeTrait\" instead.")]
652 fn impl_trait() {
653 let meth: ImplItemFn = parse2(quote!(
654 fn foo(&self, x: impl SomeTrait) {}
655 )).unwrap();
656 sanity_check_sig(&meth.sig);
657 }
658 }
659 }