Debian Codegraph @

src/lib.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // vim: tw=80
2 //! Proc Macros for use with Mockall
3 //!
4 //! You probably don't want to use this crate directly. Instead, you should use
5 //! its reexports via the [`mockall`](https://docs.rs/mockall/latest/mockall)
6 //! crate.
7
8 #![cfg_attr(feature = "nightly_derive", feature(proc_macro_diagnostic))]
9 #![cfg_attr(test, deny(warnings))]
10
11 use cfg_if::cfg_if;
12 use proc_macro2::{Span, TokenStream};
13 use quote::{ToTokens, format_ident, quote};
14 use std::{
15 env,
16 hash::BuildHasherDefault
17 };
18 use syn::{
19 *,
20 punctuated::Punctuated,
21 spanned::Spanned
22 };
23
24 mod automock;
25 mod mock_function;
26 mod mock_item;
27 mod mock_item_struct;
28 mod mock_trait;
29 mod mockable_item;
30 mod mockable_struct;
31 use crate::automock::Attrs;
32 use crate::mockable_struct::MockableStruct;
33 use crate::mock_item::MockItem;
34 use crate::mock_item_struct::MockItemStruct;
35 use crate::mockable_item::MockableItem;
36
37 // Define deterministic aliases for these common types.
38 type HashMap<K, V> = std::collections::HashMap<K, V, BuildHasherDefault<std::collections::hash_map::DefaultHasher>>;
39 type HashSet<K> = std::collections::HashSet<K, BuildHasherDefault<std::collections::hash_map::DefaultHasher>>;
40
41 cfg_if! {
42 // proc-macro2's Span::unstable method requires the nightly feature, and it
43 // doesn't work in test mode.
44 // https://github.com/alexcrichton/proc-macro2/issues/159
45 if #[cfg(all(feature = "nightly_derive", not(test)))] {
46 fn compile_error(span: Span, msg: &str) {
47 span.unstable()
48 .error(msg)
49 .emit();
50 }
51 } else {
52 fn compile_error(_span: Span, msg: &str) {
53 panic!("{msg}. More information may be available when mockall is built with the \"nightly\" feature.");
54 }
55 }
56 }
57
58 /// Does this Attribute represent Mockall's "concretize" pseudo-attribute?
59 fn is_concretize(attr: &Attribute) -> bool {
60 if attr.path().segments.last().unwrap().ident == "concretize" {
61 true
62 } else if attr.path().is_ident("cfg_attr") {
63 match &attr.meta {
64 Meta::List(ml) => {
65 ml.tokens.to_string().contains("concretize")
66 },
67 // cfg_attr should always contain a list
68 _ => false,
69 }
70 } else {
71 false
72 }
73 }
74
75 /// replace generic arguments with concrete trait object arguments
76 ///
77 /// # Return
78 ///
79 /// * A Generics object with the concretized types removed
80 /// * An array of transformed argument types, suitable for matchers and
81 /// returners
82 /// * An array of expressions that should be passed to the `call` function.
83 fn concretize_args(gen: &Generics, sig: &Signature) ->
84 (Generics, Punctuated<FnArg, Token![,]>, Vec<TokenStream>, Signature)
85 {
86 let args = &sig.inputs;
87 let mut hm = HashMap::default();
88 let mut needs_muts = HashMap::default();
89
90 let mut save_types = |ident: &Ident, tpb: &Punctuated<TypeParamBound, Token![+]>| {
91 if !tpb.is_empty() {
92 let mut pat = quote!(&(dyn #tpb));
93 let mut needs_mut = false;
94 if let Some(TypeParamBound::Trait(t)) = tpb.first() {
95 if t.path.segments.first().map(|seg| &seg.ident == "FnMut")
96 .unwrap_or(false)
97 {
98 // For FnMut arguments, the rfunc needs a mutable reference
99 pat = quote!(&mut (dyn #tpb));
100 needs_mut = true;
101 }
102 }
103 if let Ok(newty) = parse2::<Type>(pat) {
104 // substitute T arguments
105 let subst_ty: Type = parse2(quote!(#ident)).unwrap();
106 needs_muts.insert(subst_ty.clone(), needs_mut);
107 hm.insert(subst_ty, (newty.clone(), None));
108
109 // substitute &T arguments
110 let subst_ty: Type = parse2(quote!(&#ident)).unwrap();
111 needs_muts.insert(subst_ty.clone(), needs_mut);
112 hm.insert(subst_ty, (newty, None));
113 } else {
114 compile_error(tpb.span(),
115 "Type cannot be made into a trait object");
116 }
117
118 if let Ok(newty) = parse2::<Type>(quote!(&mut (dyn #tpb))) {
119 // substitute &mut T arguments
120 let subst_ty: Type = parse2(quote!(&mut #ident)).unwrap();
121 needs_muts.insert(subst_ty.clone(), needs_mut);
122 hm.insert(subst_ty, (newty, None));
123 } else {
124 compile_error(tpb.span(),
125 "Type cannot be made into a trait object");
126 }
127
128 // I wish we could substitute &[T] arguments. But there's no way
129 // for the mock method to turn &[T] into &[&dyn T].
130 if let Ok(newty) = parse2::<Type>(quote!(&[&(dyn #tpb)])) {
131 let subst_ty: Type = parse2(quote!(&[#ident])).unwrap();
132 needs_muts.insert(subst_ty.clone(), needs_mut);
133 hm.insert(subst_ty, (newty, Some(tpb.clone())));
134 } else {
135 compile_error(tpb.span(),
136 "Type cannot be made into a trait object");
137 }
138 }
139 };
140
141 for g in gen.params.iter() {
142 if let GenericParam::Type(tp) = g {
143 save_types(&tp.ident, &tp.bounds);
144 // else there had better be a where clause
145 }
146 }
147 if let Some(wc) = &gen.where_clause {
148 for pred in wc.predicates.iter() {
149 if let WherePredicate::Type(pt) = pred {
150 let bounded_ty = &pt.bounded_ty;
151 if let Ok(ident) = parse2::<Ident>(quote!(#bounded_ty)) {
152 save_types(&ident, &pt.bounds);
153 } else {
154 // We can't yet handle where clauses this complicated
155 }
156 }
157 }
158 }
159
160 let outg = Generics {
161 lt_token: None,
162 gt_token: None,
163 params: Punctuated::new(),
164 where_clause: None
165 };
166 let outargs = args.iter().map(|arg| {
167 if let FnArg::Typed(pt) = arg {
168 let mut call_pt = pt.clone();
169 demutify_arg(&mut call_pt);
170 if let Some((newty, _)) = hm.get(&pt.ty) {
171 FnArg::Typed(PatType {
172 attrs: Vec::default(),
173 pat: call_pt.pat,
174 colon_token: pt.colon_token,
175 ty: Box::new(newty.clone())
176 })
177 } else {
178 FnArg::Typed(PatType {
179 attrs: Vec::default(),
180 pat: call_pt.pat,
181 colon_token: pt.colon_token,
182 ty: pt.ty.clone()
183 })
184 }
185 } else {
186 arg.clone()
187 }
188 }).collect();
189
190 // Finally, Reference any concretizing arguments
191 // use filter_map to remove the &self argument
192 let call_exprs = args.iter().filter_map(|arg| {
193 match arg {
194 FnArg::Typed(pt) => {
195 let mut pt2 = pt.clone();
196 demutify_arg(&mut pt2);
197 let pat = &pt2.pat;
198 if pat_is_self(pat) {
199 None
200 } else if let Some((_, newbound)) = hm.get(&pt.ty) {
201 if let Type::Reference(tr) = &*pt.ty {
202 if let Type::Slice(_ts) = &*tr.elem {
203 // Assume _ts is the generic type or we wouldn't be
204 // here
205 Some(quote!(
206 &(0..#pat.len())
207 .map(|__mockall_i| &#pat[__mockall_i] as &(dyn #newbound))
208 .collect::<Vec<_>>()
209 ))
210 } else {
211 Some(quote!(#pat))
212 }
213 } else if needs_muts.get(&pt.ty).cloned().unwrap_or(false) {
214 Some(quote!(&mut #pat))
215 } else {
216 Some(quote!(&#pat))
217 }
218 } else {
219 Some(quote!(#pat))
220 }
221 },
222 FnArg::Receiver(_) => None,
223 }
224 }).collect();
225
226 // Add any necessary "mut" qualifiers to the Signature
227 let mut altsig = sig.clone();
228 for arg in altsig.inputs.iter_mut() {
229 if let FnArg::Typed(pt) = arg {
230 if needs_muts.get(&pt.ty).cloned().unwrap_or(false) {
231 if let Pat::Ident(pi) = &mut *pt.pat {
232 pi.mutability = Some(Token![mut](pi.mutability.span()));
233 } else {
234 compile_error(pt.pat.span(),
235 "This Pat type is not yet supported by Mockall when used as an argument to a concretized function.")
236 }
237 }
238 }
239 }
240
241 (outg, outargs, call_exprs, altsig)
242 }
243
244 fn deanonymize_lifetime(lt: &mut Lifetime) {
245 if lt.ident == "_" {
246 lt.ident = format_ident!("static");
247 }
248 }
249
250 fn deanonymize_path(path: &mut Path) {
251 for seg in path.segments.iter_mut() {
252 match &mut seg.arguments {
253 PathArguments::None => (),
254 PathArguments::AngleBracketed(abga) => {
255 for ga in abga.args.iter_mut() {
256 if let GenericArgument::Lifetime(lt) = ga {
257 deanonymize_lifetime(lt)
258 }
259 }
260 },
261 _ => compile_error(seg.arguments.span(),
262 "Methods returning functions are TODO"),
263 }
264 }
265 }
266
267 /// Replace any references to the anonymous lifetime `'_` with `'static`.
268 fn deanonymize(literal_type: &mut Type) {
269 match literal_type {
270 Type::Array(ta) => deanonymize(ta.elem.as_mut()),
271 Type::BareFn(tbf) => {
272 if let ReturnType::Type(_, ref mut bt) = tbf.output {
273 deanonymize(bt.as_mut());
274 }
275 for input in tbf.inputs.iter_mut() {
276 deanonymize(&mut input.ty);
277 }
278 },
279 Type::Group(tg) => deanonymize(tg.elem.as_mut()),
280 Type::Infer(_) => (),
281 Type::Never(_) => (),
282 Type::Paren(tp) => deanonymize(tp.elem.as_mut()),
283 Type::Path(tp) => {
284 if let Some(ref mut qself) = tp.qself {
285 deanonymize(qself.ty.as_mut());
286 }
287 deanonymize_path(&mut tp.path);
288 },
289 Type::Ptr(tptr) => deanonymize(tptr.elem.as_mut()),
290 Type::Reference(tr) => {
291 if let Some(lt) = tr.lifetime.as_mut() {
292 deanonymize_lifetime(lt)
293 }
294 deanonymize(tr.elem.as_mut());
295 },
296 Type::Slice(s) => deanonymize(s.elem.as_mut()),
297 Type::TraitObject(tto) => {
298 for tpb in tto.bounds.iter_mut() {
299 match tpb {
300 TypeParamBound::Trait(tb) => deanonymize_path(&mut tb.path),
301 TypeParamBound::Lifetime(lt) => deanonymize_lifetime(lt),
302 _ => ()
303 }
304 }
305 },
306 Type::Tuple(tt) => {
307 for ty in tt.elems.iter_mut() {
308 deanonymize(ty)
309 }
310 }
311 x => compile_error(x.span(), "Unimplemented type for deanonymize")
312 }
313 }
314
315 // If there are any closures in the argument list, turn them into boxed
316 // functions
317 fn declosurefy(gen: &Generics, args: &Punctuated<FnArg, Token![,]>) ->
318 (Generics, Punctuated<FnArg, Token![,]>, Vec<TokenStream>)
319 {
320 let mut hm = HashMap::default();
321
322 let mut save_fn_types = |ident: &Ident, tpb: &TypeParamBound| {
323 if let TypeParamBound::Trait(tb) = tpb {
324 let fident = &tb.path.segments.last().unwrap().ident;
325 if ["Fn", "FnMut", "FnOnce"].iter().any(|s| fident == *s) {
326 let newty: Type = parse2(quote!(Box<dyn #tb>)).unwrap();
327 let subst_ty: Type = parse2(quote!(#ident)).unwrap();
328 assert!(hm.insert(subst_ty, newty).is_none(),
329 "A generic parameter had two Fn bounds?");
330 }
331 }
332 };
333
334 // First, build a HashMap of all Fn generic types
335 for g in gen.params.iter() {
336 if let GenericParam::Type(tp) = g {
337 for tpb in tp.bounds.iter() {
338 save_fn_types(&tp.ident, tpb);
339 }
340 }
341 }
342 if let Some(wc) = &gen.where_clause {
343 for pred in wc.predicates.iter() {
344 if let WherePredicate::Type(pt) = pred {
345 let bounded_ty = &pt.bounded_ty;
346 if let Ok(ident) = parse2::<Ident>(quote!(#bounded_ty)) {
347 for tpb in pt.bounds.iter() {
348 save_fn_types(&ident, tpb);
349 }
350 } else {
351 // We can't yet handle where clauses this complicated
352 }
353 }
354 }
355 }
356
357 // Then remove those types from both the Generics' params and where clause
358 let should_remove = |ident: &Ident| {
359 let ty: Type = parse2(quote!(#ident)).unwrap();
360 hm.contains_key(&ty)
361 };
362 let params = gen.params.iter()
363 .filter(|g| {
364 if let GenericParam::Type(tp) = g {
365 !should_remove(&tp.ident)
366 } else {
367 true
368 }
369 }).cloned()
370 .collect::<Punctuated<_, _>>();
371 let mut wc2 = gen.where_clause.clone();
372 if let Some(wc) = &mut wc2 {
373 wc.predicates = wc.predicates.iter()
374 .filter(|wp| {
375 if let WherePredicate::Type(pt) = wp {
376 let bounded_ty = &pt.bounded_ty;
377 if let Ok(ident) = parse2::<Ident>(quote!(#bounded_ty)) {
378 !should_remove(&ident)
379 } else {
380 // We can't yet handle where clauses this complicated
381 true
382 }
383 } else {
384 true
385 }
386 }).cloned()
387 .collect::<Punctuated<_, _>>();
388 if wc.predicates.is_empty() {
389 wc2 = None;
390 }
391 }
392 let outg = Generics {
393 lt_token: if params.is_empty() { None } else { gen.lt_token },
394 gt_token: if params.is_empty() { None } else { gen.gt_token },
395 params,
396 where_clause: wc2
397 };
398
399 // Next substitute Box<Fn> into the arguments
400 let outargs = args.iter().map(|arg| {
401 if let FnArg::Typed(pt) = arg {
402 let mut immutable_pt = pt.clone();
403 demutify_arg(&mut immutable_pt);
404 if let Some(newty) = hm.get(&pt.ty) {
405 FnArg::Typed(PatType {
406 attrs: Vec::default(),
407 pat: immutable_pt.pat,
408 colon_token: pt.colon_token,
409 ty: Box::new(newty.clone())
410 })
411 } else {
412 FnArg::Typed(PatType {
413 attrs: Vec::default(),
414 pat: immutable_pt.pat,
415 colon_token: pt.colon_token,
416 ty: pt.ty.clone()
417 })
418 }
419 } else {
420 arg.clone()
421 }
422 }).collect();
423
424 // Finally, Box any closure arguments
425 // use filter_map to remove the &self argument
426 let callargs = args.iter().filter_map(|arg| {
427 match arg {
428 FnArg::Typed(pt) => {
429 let mut pt2 = pt.clone();
430 demutify_arg(&mut pt2);
431 let pat = &pt2.pat;
432 if pat_is_self(pat) {
433 None
434 } else if hm.contains_key(&pt.ty) {
435 Some(quote!(Box::new(#pat)))
436 } else {
437 Some(quote!(#pat))
438 }
439 },
440 FnArg::Receiver(_) => None,
441 }
442 }).collect();
443 (outg, outargs, callargs)
444 }
445
446 /// Replace any "impl trait" types with "Box<dyn trait>" or equivalent.
447 fn deimplify(rt: &mut ReturnType) {
448 if let ReturnType::Type(_, ty) = rt {
449 if let Type::ImplTrait(ref tit) = &**ty {
450 let needs_pin = tit.bounds
451 .iter()
452 .any(|tpb| {
453 if let TypeParamBound::Trait(tb) = tpb {
454 if let Some(seg) = tb.path.segments.last() {
455 seg.ident == "Future" || seg.ident == "Stream"
456 } else {
457 // It might still be a Future, but we can't guess
458 // what names it might be imported under. Too bad.
459 false
460 }
461 } else {
462 false
463 }
464 });
465 let bounds = &tit.bounds;
466 if needs_pin {
467 *ty = parse2(quote!(::std::pin::Pin<Box<dyn #bounds>>)).unwrap();
468 } else {
469 *ty = parse2(quote!(Box<dyn #bounds>)).unwrap();
470 }
471 }
472 }
473 }
474
475 /// Remove any generics that place constraints on Self.
476 fn dewhereselfify(generics: &mut Generics) {
477 if let Some(ref mut wc) = &mut generics.where_clause {
478 let new_predicates = wc.predicates.iter()
479 .filter(|wp| match wp {
480 WherePredicate::Type(pt) => {
481 pt.bounded_ty != parse2(quote!(Self)).unwrap()
482 },
483 _ => true
484 }).cloned()
485 .collect::<Punctuated<WherePredicate, Token![,]>>();
486 wc.predicates = new_predicates;
487 }
488 if generics.where_clause.as_ref()
489 .map(|wc| wc.predicates.is_empty())
490 .unwrap_or(false)
491 {
492 generics.where_clause = None;
493 }
494 }
495
496 /// Remove any mutability qualifiers from a method's argument list
497 fn demutify(inputs: &mut Punctuated<FnArg, token::Comma>) {
498 for arg in inputs.iter_mut() {
499 match arg {
500 FnArg::Receiver(r) => if r.reference.is_none() {
501 r.mutability = None
502 },
503 FnArg::Typed(pt) => demutify_arg(pt),
504 }
505 }
506 }
507
508 /// Remove any "mut" from a method argument's binding.
509 fn demutify_arg(arg: &mut PatType) {
510 match *arg.pat {
511 Pat::Wild(_) => {
512 compile_error(arg.span(),
513 "Mocked methods must have named arguments");
514 },
515 Pat::Ident(ref mut pat_ident) => {
516 if let Some(r) = &pat_ident.by_ref {
517 compile_error(r.span(),
518 "Mockall does not support by-reference argument bindings");
519 }
520 if let Some((_at, subpat)) = &pat_ident.subpat {
521 compile_error(subpat.span(),
522 "Mockall does not support subpattern bindings");
523 }
524 pat_ident.mutability = None;
525 },
526 _ => {
527 compile_error(arg.span(), "Unsupported argument type");
528 }
529 };
530 }
531
532 fn deselfify_path(path: &mut Path, actual: &Ident, generics: &Generics) {
533 for seg in path.segments.iter_mut() {
534 if seg.ident == "Self" {
535 seg.ident = actual.clone();
536 if let PathArguments::None = seg.arguments {
537 if !generics.params.is_empty() {
538 let args = generics.params.iter()
539 .map(|gp| {
540 match gp {
541 GenericParam::Type(tp) => {
542 let ident = tp.ident.clone();
543 GenericArgument::Type(
544 Type::Path(
545 TypePath {
546 qself: None,
547 path: Path::from(ident)
548 }
549 )
550 )
551 },
552 GenericParam::Lifetime(ld) =>{
553 GenericArgument::Lifetime(
554 ld.lifetime.clone()
555 )
556 }
557 _ => unimplemented!(),
558 }
559 }).collect::<Punctuated<_, _>>();
560 seg.arguments = PathArguments::AngleBracketed(
561 AngleBracketedGenericArguments {
562 colon2_token: None,
563 lt_token: generics.lt_token.unwrap(),
564 args,
565 gt_token: generics.gt_token.unwrap(),
566 }
567 );
568 }
569 } else {
570 compile_error(seg.arguments.span(),
571 "Type arguments after Self are unexpected");
572 }
573 }
574 if let PathArguments::AngleBracketed(abga) = &mut seg.arguments
575 {
576 for arg in abga.args.iter_mut() {
577 match arg {
578 GenericArgument::Type(ty) =>
579 deselfify(ty, actual, generics),
580 GenericArgument::AssocType(at) =>
581 deselfify(&mut at.ty, actual, generics),
582 _ => /* Nothing to do */(),
583 }
584 }
585 }
586 }
587 }
588
589 /// Replace any references to `Self` in `literal_type` with `actual`.
590 /// `generics` is the Generics field of the parent struct. Useful for
591 /// constructor methods.
592 fn deselfify(literal_type: &mut Type, actual: &Ident, generics: &Generics) {
593 match literal_type {
594 Type::Slice(s) => {
595 deselfify(s.elem.as_mut(), actual, generics);
596 },
597 Type::Array(a) => {
598 deselfify(a.elem.as_mut(), actual, generics);
599 },
600 Type::Ptr(p) => {
601 deselfify(p.elem.as_mut(), actual, generics);
602 },
603 Type::Reference(r) => {
604 deselfify(r.elem.as_mut(), actual, generics);
605 },
606 Type::Tuple(tuple) => {
607 for elem in tuple.elems.iter_mut() {
608 deselfify(elem, actual, generics);
609 }
610 }
611 Type::Path(type_path) => {
612 if let Some(ref mut qself) = type_path.qself {
613 deselfify(qself.ty.as_mut(), actual, generics);
614 }
615 deselfify_path(&mut type_path.path, actual, generics);
616 },
617 Type::Paren(p) => {
618 deselfify(p.elem.as_mut(), actual, generics);
619 },
620 Type::Group(g) => {
621 deselfify(g.elem.as_mut(), actual, generics);
622 },
623 Type::Macro(_) | Type::Verbatim(_) => {
624 compile_error(literal_type.span(),
625 "mockall_derive does not support this type as a return argument");
626 },
627 Type::TraitObject(tto) => {
628 // Change types like `dyn Self` into `dyn MockXXX`.
629 for bound in tto.bounds.iter_mut() {
630 if let TypeParamBound::Trait(t) = bound {
631 deselfify_path(&mut t.path, actual, generics);
632 }
633 }
634 },
635 Type::ImplTrait(_) => {
636 /* Should've already been flagged as a compile_error */
637 },
638 Type::BareFn(_) => {
639 /* Bare functions can't have Self arguments. Nothing to do */
640 },
641 Type::Infer(_) | Type::Never(_) =>
642 {
643 /* Nothing to do */
644 },
645 _ => compile_error(literal_type.span(), "Unsupported type"),
646 }
647 }
648
649 /// Change any `Self` in a method's arguments' types with `actual`.
650 /// `generics` is the Generics field of the parent struct.
651 fn deselfify_args(
652 args: &mut Punctuated<FnArg, Token![,]>,
653 actual: &Ident,
654 generics: &Generics)
655 {
656 for arg in args.iter_mut() {
657 match arg {
658 FnArg::Receiver(r) => {
659 if r.colon_token.is_some() {
660 deselfify(r.ty.as_mut(), actual, generics)
661 }
662 },
663 FnArg::Typed(pt) => deselfify(pt.ty.as_mut(), actual, generics)
664 }
665 }
666 }
667
668 fn find_ident_from_path(path: &Path) -> (Ident, PathArguments) {
669 if path.segments.len() != 1 {
670 compile_error(path.span(),
671 "mockall_derive only supports structs defined in the current module");
672 return (Ident::new("", path.span()), PathArguments::None);
673 }
674 let last_seg = path.segments.last().unwrap();
675 (last_seg.ident.clone(), last_seg.arguments.clone())
676 }
677
678 fn find_lifetimes_in_tpb(bound: &TypeParamBound) -> HashSet<Lifetime> {
679 let mut ret = HashSet::default();
680 match bound {
681 TypeParamBound::Lifetime(lt) => {
682 ret.insert(lt.clone());
683 },
684 TypeParamBound::Trait(tb) => {
685 ret.extend(find_lifetimes_in_path(&tb.path));
686 },
687 _ => ()
688 };
689 ret
690 }
691
692 fn find_lifetimes_in_path(path: &Path) -> HashSet<Lifetime> {
693 let mut ret = HashSet::default();
694 for seg in path.segments.iter() {
695 if let PathArguments::AngleBracketed(abga) = &seg.arguments {
696 for arg in abga.args.iter() {
697 match arg {
698 GenericArgument::Lifetime(lt) => {
699 ret.insert(lt.clone());
700 },
701 GenericArgument::Type(ty) => {
702 ret.extend(find_lifetimes(ty));
703 },
704 GenericArgument::AssocType(at) => {
705 ret.extend(find_lifetimes(&at.ty));
706 },
707 GenericArgument::Constraint(c) => {
708 for bound in c.bounds.iter() {
709 ret.extend(find_lifetimes_in_tpb(bound));
710 }
711 },
712 GenericArgument::Const(_) => (),
713 _ => ()
714 }
715 }
716 }
717 }
718 ret
719 }
720
721 fn find_lifetimes(ty: &Type) -> HashSet<Lifetime> {
722 match ty {
723 Type::Array(ta) => find_lifetimes(ta.elem.as_ref()),
724 Type::Group(tg) => find_lifetimes(tg.elem.as_ref()),
725 Type::Infer(_ti) => HashSet::default(),
726 Type::Never(_tn) => HashSet::default(),
727 Type::Paren(tp) => find_lifetimes(tp.elem.as_ref()),
728 Type::Path(tp) => {
729 let mut ret = find_lifetimes_in_path(&tp.path);
730 if let Some(qs) = &tp.qself {
731 ret.extend(find_lifetimes(qs.ty.as_ref()));
732 }
733 ret
734 },
735 Type::Ptr(tp) => find_lifetimes(tp.elem.as_ref()),
736 Type::Reference(tr) => {
737 let mut ret = find_lifetimes(tr.elem.as_ref());
738 if let Some(lt) = &tr.lifetime {
739 ret.insert(lt.clone());
740 }
741 ret
742 },
743 Type::Slice(ts) => find_lifetimes(ts.elem.as_ref()),
744 Type::TraitObject(tto) => {
745 let mut ret = HashSet::default();
746 for bound in tto.bounds.iter() {
747 ret.extend(find_lifetimes_in_tpb(bound));
748 }
749 ret
750 }
751 Type::Tuple(tt) => {
752 let mut ret = HashSet::default();
753 for ty in tt.elems.iter() {
754 ret.extend(find_lifetimes(ty));
755 }
756 ret
757 },
758 Type::ImplTrait(tit) => {
759 let mut ret = HashSet::default();
760 for tpb in tit.bounds.iter() {
761 ret.extend(find_lifetimes_in_tpb(tpb));
762 }
763 ret
764 },
765 _ => {
766 compile_error(ty.span(), "unsupported type in this context");
767 HashSet::default()
768 }
769 }
770 }
771
772 struct AttrFormatter<'a>{
773 attrs: &'a [Attribute],
774 async_trait: bool,
775 doc: bool,
776 must_use: bool,
777 }
778
779 impl<'a> AttrFormatter<'a> {
780 fn new(attrs: &'a [Attribute]) -> AttrFormatter<'a> {
781 Self {
782 attrs,
783 async_trait: true,
784 doc: true,
785 must_use: false,
786 }
787 }
788
789 fn async_trait(&mut self, allowed: bool) -> &mut Self {
790 self.async_trait = allowed;
791 self
792 }
793
794 fn doc(&mut self, allowed: bool) -> &mut Self {
795 self.doc = allowed;
796 self
797 }
798
799 fn must_use(&mut self, allowed: bool) -> &mut Self {
800 self.must_use = allowed;
801 self
802 }
803
804 // XXX This logic requires that attributes are imported with their
805 // standard names.
806 #[allow(clippy::needless_bool)]
807 #[allow(clippy::if_same_then_else)]
808 fn format(&mut self) -> Vec<Attribute> {
809 self.attrs.iter()
810 .filter(|attr| {
811 let i = attr.path().segments.last().map(|ps| &ps.ident);
812 if is_concretize(attr) {
813 // Internally used attribute. Never emit.
814 false
815 } else if i.is_none() {
816 false
817 } else if *i.as_ref().unwrap() == "derive" {
818 // We can't usefully derive any traits. Ignore them
819 false
820 } else if *i.as_ref().unwrap() == "doc" {
821 self.doc
822 } else if *i.as_ref().unwrap() == "async_trait" {
823 self.async_trait
824 } else if *i.as_ref().unwrap() == "inline" {
825 // No need to inline mock functions.
826 false
827 } else if *i.as_ref().unwrap() == "cold" {
828 // No need for such hints on mock functions.
829 false
830 } else if *i.as_ref().unwrap() == "instrument" {
831 // We can't usefully instrument the mock method, so just
832 // ignore this attribute.
833 // https://docs.rs/tracing/0.1.23/tracing/attr.instrument.html
834 false
835 } else if *i.as_ref().unwrap() == "link_name" {
836 // This shows up sometimes when mocking ffi functions. We
837 // must not emit it on anything that isn't an ffi definition
838 false
839 } else if *i.as_ref().unwrap() == "must_use" {
840 self.must_use
841 } else if *i.as_ref().unwrap() == "auto_enum" {
842 // Ignore auto_enum, because we transform the return value
843 // into a trait object.
844 false
845 } else {
846 true
847 }
848 }).cloned()
849 .collect()
850 }
851 }
852
853 /// Determine if this Pat is any kind of `self` binding
854 fn pat_is_self(pat: &Pat) -> bool {
855 if let Pat::Ident(pi) = pat {
856 pi.ident == "self"
857 } else {
858 false
859 }
860 }
861
862 /// Add `levels` `super::` to the path. Return the number of levels added.
863 fn supersuperfy_path(path: &mut Path, levels: usize) -> usize {
864 if let Some(t) = path.segments.last_mut() {
865 match &mut t.arguments {
866 PathArguments::None => (),
867 PathArguments::AngleBracketed(ref mut abga) => {
868 for arg in abga.args.iter_mut() {
869 match arg {
870 GenericArgument::Type(ref mut ty) => {
871 *ty = supersuperfy(ty, levels);
872 },
873 GenericArgument::AssocType(ref mut at) => {
874 at.ty = supersuperfy(&at.ty, levels);
875 },
876 GenericArgument::Constraint(ref mut constraint) => {
877 supersuperfy_bounds(&mut constraint.bounds, levels);
878 },
879 _ => (),
880 }
881 }
882 },
883 PathArguments::Parenthesized(ref mut pga) => {
884 for input in pga.inputs.iter_mut() {
885 *input = supersuperfy(input, levels);
886 }
887 if let ReturnType::Type(_, ref mut ty) = pga.output {
888 *ty = Box::new(supersuperfy(ty, levels));
889 }
890 },
891 }
892 }
893 if let Some(t) = path.segments.first() {
894 if t.ident == "super" {
895 let mut ident = format_ident!("super");
896 ident.set_span(path.segments.span());
897 let ps = PathSegment {
898 ident,
899 arguments: PathArguments::None
900 };
901 for _ in 0..levels {
902 path.segments.insert(0, ps.clone());
903 }
904 levels
905 } else {
906 0
907 }
908 } else {
909 0
910 }
911 }
912
913 /// Replace any references to `super::X` in `original` with `super::super::X`.
914 fn supersuperfy(original: &Type, levels: usize) -> Type {
915 let mut output = original.clone();
916 fn recurse(t: &mut Type, levels: usize) {
917 match t {
918 Type::Slice(s) => {
919 recurse(s.elem.as_mut(), levels);
920 },
921 Type::Array(a) => {
922 recurse(a.elem.as_mut(), levels);
923 },
924 Type::Ptr(p) => {
925 recurse(p.elem.as_mut(), levels);
926 },
927 Type::Reference(r) => {
928 recurse(r.elem.as_mut(), levels);
929 },
930 Type::BareFn(bfn) => {
931 if let ReturnType::Type(_, ref mut bt) = bfn.output {
932 recurse(bt.as_mut(), levels);
933 }
934 for input in bfn.inputs.iter_mut() {
935 recurse(&mut input.ty, levels);
936 }
937 },
938 Type::Tuple(tuple) => {
939 for elem in tuple.elems.iter_mut() {
940 recurse(elem, levels);
941 }
942 }
943 Type::Path(type_path) => {
944 let added = supersuperfy_path(&mut type_path.path, levels);
945 if let Some(ref mut qself) = type_path.qself {
946 recurse(qself.ty.as_mut(), levels);
947 qself.position += added;
948 }
949 },
950 Type::Paren(p) => {
951 recurse(p.elem.as_mut(), levels);
952 },
953 Type::Group(g) => {
954 recurse(g.elem.as_mut(), levels);
955 },
956 Type::Macro(_) | Type::Verbatim(_) => {
957 compile_error(t.span(),
958 "mockall_derive does not support this type in this position");
959 },
960 Type::TraitObject(tto) => {
961 for bound in tto.bounds.iter_mut() {
962 if let TypeParamBound::Trait(tb) = bound {
963 supersuperfy_path(&mut tb.path, levels);
964 }
965 }
966 },
967 Type::ImplTrait(_) => {
968 /* Should've already been flagged as a compile error */
969 },
970 Type::Infer(_) | Type::Never(_) =>
971 {
972 /* Nothing to do */
973 },
974 _ => compile_error(t.span(), "Unsupported type"),
975 }
976 }
977 recurse(&mut output, levels);
978 output
979 }
980
981 fn supersuperfy_generics(generics: &mut Generics, levels: usize) {
982 for param in generics.params.iter_mut() {
983 if let GenericParam::Type(tp) = param {
984 supersuperfy_bounds(&mut tp.bounds, levels);
985 if let Some(ty) = tp.default.as_mut() {
986 *ty = supersuperfy(ty, levels);
987 }
988 }
989 }
990 if let Some(wc) = generics.where_clause.as_mut() {
991 for wp in wc.predicates.iter_mut() {
992 if let WherePredicate::Type(pt) = wp {
993 pt.bounded_ty = supersuperfy(&pt.bounded_ty, levels);
994 supersuperfy_bounds(&mut pt.bounds, levels);
995 }
996 }
997 }
998 }
999
1000 fn supersuperfy_bounds(
1001 bounds: &mut Punctuated<TypeParamBound, Token![+]>,
1002 levels: usize)
1003 {
1004 for bound in bounds.iter_mut() {
1005 if let TypeParamBound::Trait(tb) = bound {
1006 supersuperfy_path(&mut tb.path, levels);
1007 }
1008 }
1009 }
1010
1011 /// Generate a suitable mockall::Key generic paramter from any Generics
1012 fn gen_keyid(g: &Generics) -> impl ToTokens {
1013 match g.params.len() {
1014 0 => quote!(<()>),
1015 1 => {
1016 let (_, tg, _) = g.split_for_impl();
1017 quote!(#tg)
1018 },
1019 _ => {
1020 // Rust doesn't support variadic Generics, so mockall::Key must
1021 // always have exactly one generic type. We need to add parentheses
1022 // around whatever type generics the caller passes.
1023 let tps = g.type_params()
1024 .map(|tp| tp.ident.clone())
1025 .collect::<Punctuated::<Ident, Token![,]>>();
1026 quote!(<(#tps)>)
1027 }
1028 }
1029 }
1030
1031 /// Generate a mock identifier from the regular one: eg "Foo" => "MockFoo"
1032 fn gen_mock_ident(ident: &Ident) -> Ident {
1033 format_ident!("Mock{}", ident)
1034 }
1035
1036 /// Generate an identifier for the mock struct's private module: eg "Foo" =>
1037 /// "__mock_Foo"
1038 fn gen_mod_ident(struct_: &Ident, trait_: Option<&Ident>) -> Ident {
1039 if let Some(t) = trait_ {
1040 format_ident!("__mock_{struct_}_{}", t)
1041 } else {
1042 format_ident!("__mock_{struct_}")
1043 }
1044 }
1045
1046 /// Combine two Generics structs, producing a new one that has the union of
1047 /// their parameters.
1048 fn merge_generics(x: &Generics, y: &Generics) -> Generics {
1049 /// Compare only the identifiers of two GenericParams
1050 fn cmp_gp_idents(x: &GenericParam, y: &GenericParam) -> bool {
1051 use GenericParam::*;
1052
1053 match (x, y) {
1054 (Type(xtp), Type(ytp)) => xtp.ident == ytp.ident,
1055 (Lifetime(xld), Lifetime(yld)) => xld.lifetime == yld.lifetime,
1056 (Const(xc), Const(yc)) => xc.ident == yc.ident,
1057 _ => false
1058 }
1059 }
1060
1061 /// Compare only the identifiers of two WherePredicates
1062 fn cmp_wp_idents(x: &WherePredicate, y: &WherePredicate) -> bool {
1063 use WherePredicate::*;
1064
1065 match (x, y) {
1066 (Type(xpt), Type(ypt)) => xpt.bounded_ty == ypt.bounded_ty,
1067 (Lifetime(xpl), Lifetime(ypl)) => xpl.lifetime == ypl.lifetime,
1068 _ => false
1069 }
1070 }
1071
1072 let mut out = if x.lt_token.is_none() && x.where_clause.is_none() {
1073 y.clone()
1074 } else if y.lt_token.is_none() && y.where_clause.is_none() {
1075 x.clone()
1076 } else {
1077 let mut out = x.clone();
1078 // First merge the params
1079 'outer_param: for yparam in y.params.iter() {
1080 // XXX: O(n^2) loop
1081 for outparam in out.params.iter_mut() {
1082 if cmp_gp_idents(outparam, yparam) {
1083 if let (GenericParam::Type(ref mut ot),
1084 GenericParam::Type(yt)) = (outparam, yparam)
1085 {
1086 ot.attrs.extend(yt.attrs.iter().cloned());
1087 ot.colon_token = ot.colon_token.or(yt.colon_token);
1088 ot.eq_token = ot.eq_token.or(yt.eq_token);
1089 if ot.default.is_none() {
1090 ot.default.clone_from(&yt.default);
1091 }
1092 // XXX this might result in duplicate bounds
1093 if ot.bounds != yt.bounds {
1094 ot.bounds.extend(yt.bounds.iter().cloned());
1095 }
1096 }
1097 continue 'outer_param;
1098 }
1099 }
1100 out.params.push(yparam.clone());
1101 }
1102 out
1103 };
1104 // Then merge the where clauses
1105 match (&mut out.where_clause, &y.where_clause) {
1106 (_, None) => (),
1107 (None, Some(wc)) => out.where_clause = Some(wc.clone()),
1108 (Some(out_wc), Some(y_wc)) => {
1109 'outer_wc: for ypred in y_wc.predicates.iter() {
1110 // XXX: O(n^2) loop
1111 for outpred in out_wc.predicates.iter_mut() {
1112 if cmp_wp_idents(outpred, ypred) {
1113 if let (WherePredicate::Type(ref mut ot),
1114 WherePredicate::Type(yt)) = (outpred, ypred)
1115 {
1116 match (&mut ot.lifetimes, &yt.lifetimes) {
1117 (_, None) => (),
1118 (None, Some(bl)) =>
1119 ot.lifetimes = Some(bl.clone()),
1120 (Some(obl), Some(ybl)) =>
1121 // XXX: might result in duplicates
1122 obl.lifetimes.extend(
1123 ybl.lifetimes.iter().cloned()),
1124 };
1125 // XXX: might result in duplicate bounds
1126 if ot.bounds != yt.bounds {
1127 ot.bounds.extend(yt.bounds.iter().cloned())
1128 }
1129 }
1130 continue 'outer_wc;
1131 }
1132 }
1133 out_wc.predicates.push(ypred.clone());
1134 }
1135 }
1136 }
1137 out
1138 }
1139
1140 fn lifetimes_to_generic_params(lv: &Punctuated<LifetimeParam, Token![,]>)
1141 -> Punctuated<GenericParam, Token![,]>
1142 {
1143 lv.iter()
1144 .map(|lt| GenericParam::Lifetime(lt.clone()))
1145 .collect()
1146 }
1147
1148 /// Transform a Vec of lifetimes into a Generics
1149 fn lifetimes_to_generics(lv: &Punctuated<LifetimeParam, Token![,]>)-> Generics {
1150 if lv.is_empty() {
1151 Generics::default()
1152 } else {
1153 let params = lifetimes_to_generic_params(lv);
1154 Generics {
1155 lt_token: Some(Token![<](lv[0].span())),
1156 gt_token: Some(Token![>](lv[0].span())),
1157 params,
1158 where_clause: None
1159 }
1160 }
1161 }
1162
1163 /// Split a generics list into three: one for type generics and where predicates
1164 /// that relate to the signature, one for lifetimes that relate to the arguments
1165 /// only, and one for lifetimes that relate to the return type only.
1166 fn split_lifetimes(
1167 generics: Generics,
1168 args: &Punctuated<FnArg, Token![,]>,
1169 rt: &ReturnType)
1170 -> (Generics,
1171 Punctuated<LifetimeParam, token::Comma>,
1172 Punctuated<LifetimeParam, token::Comma>)
1173 {
1174 if generics.lt_token.is_none() {
1175 return (generics, Default::default(), Default::default());
1176 }
1177
1178 // Check which types and lifetimes are referenced by the arguments
1179 let mut alts = HashSet::<Lifetime>::default();
1180 let mut rlts = HashSet::<Lifetime>::default();
1181 for arg in args {
1182 match arg {
1183 FnArg::Receiver(r) => {
1184 if let Some((_, Some(lt))) = &r.reference {
1185 alts.insert(lt.clone());
1186 }
1187 },
1188 FnArg::Typed(pt) => {
1189 alts.extend(find_lifetimes(pt.ty.as_ref()));
1190 },
1191 };
1192 };
1193
1194 if let ReturnType::Type(_, ty) = rt {
1195 rlts.extend(find_lifetimes(ty));
1196 }
1197
1198 let mut tv = Punctuated::new();
1199 let mut alv = Punctuated::new();
1200 let mut rlv = Punctuated::new();
1201 for p in generics.params.into_iter() {
1202 match p {
1203 GenericParam::Lifetime(ltd) if rlts.contains(&ltd.lifetime) =>
1204 rlv.push(ltd),
1205 GenericParam::Lifetime(ltd) if alts.contains(&ltd.lifetime) =>
1206 alv.push(ltd),
1207 GenericParam::Lifetime(_) => {
1208 // Probably a lifetime parameter from the impl block that isn't
1209 // used by this particular method
1210 },
1211 GenericParam::Type(_) => tv.push(p),
1212 _ => (),
1213 }
1214 }
1215
1216 let tg = if tv.is_empty() {
1217 Generics::default()
1218 } else {
1219 Generics {
1220 lt_token: generics.lt_token,
1221 gt_token: generics.gt_token,
1222 params: tv,
1223 where_clause: generics.where_clause
1224 }
1225 };
1226
1227 (tg, alv, rlv)
1228 }
1229
1230 /// Return the visibility that should be used for expectation!, given the
1231 /// original method's visibility.
1232 ///
1233 /// # Arguments
1234 /// - `vis`: Original visibility of the item
1235 /// - `levels`: How many modules will the mock item be nested in?
1236 fn expectation_visibility(vis: &Visibility, levels: usize)
1237 -> Visibility
1238 {
1239 if levels == 0 {
1240 return vis.clone();
1241 }
1242
1243 let in_token = Token![in](vis.span());
1244 let super_token = Token![super](vis.span());
1245 match vis {
1246 Visibility::Inherited => {
1247 // Private items need pub(in super::[...]) for each level
1248 let mut path = Path::from(super_token);
1249 for _ in 1..levels {
1250 path.segments.push(super_token.into());
1251 }
1252 Visibility::Restricted(VisRestricted{
1253 pub_token: Token![pub](vis.span()),
1254 paren_token: token::Paren::default(),
1255 in_token: Some(in_token),
1256 path: Box::new(path)
1257 })
1258 },
1259 Visibility::Restricted(vr) => {
1260 // crate => don't change
1261 // in crate::* => don't change
1262 // super => in super::super::super
1263 // self => in super::super
1264 // in anything_else => super::super::anything_else
1265 if vr.path.segments.first().unwrap().ident == "crate" {
1266 Visibility::Restricted(vr.clone())
1267 } else {
1268 let mut out = vr.clone();
1269 out.in_token = Some(in_token);
1270 for _ in 0..levels {
1271 out.path.segments.insert(0, super_token.into());
1272 }
1273 Visibility::Restricted(out)
1274 }
1275 },
1276 _ => vis.clone()
1277 }
1278 }
1279
1280 fn staticize(generics: &Generics) -> Generics {
1281 let mut ret = generics.clone();
1282 for lt in ret.lifetimes_mut() {
1283 lt.lifetime = Lifetime::new("'static", Span::call_site());
1284 };
1285 ret
1286 }
1287
1288 fn mock_it<M: Into<MockableItem>>(inputs: M) -> TokenStream
1289 {
1290 let mockable: MockableItem = inputs.into();
1291 let mock = MockItem::from(mockable);
1292 let ts = mock.into_token_stream();
1293 if env::var("MOCKALL_DEBUG").is_ok() {
1294 println!("{ts}");
1295 }
1296 ts
1297 }
1298
1299 fn do_mock_once(input: TokenStream) -> TokenStream
1300 {
1301 let item: MockableStruct = match syn::parse2(input) {
1302 Ok(mock) => mock,
1303 Err(err) => {
1304 return err.to_compile_error();
1305 }
1306 };
1307 mock_it(item)
1308 }
1309
1310 fn do_mock(input: TokenStream) -> TokenStream
1311 {
1312 cfg_if! {
1313 if #[cfg(reprocheck)] {
1314 let ts_a = do_mock_once(input.clone());
1315 let ts_b = do_mock_once(input.clone());
1316 assert_eq!(ts_a.to_string(), ts_b.to_string());
1317 }
1318 }
1319 do_mock_once(input)
1320 }
1321
1322 #[proc_macro_attribute]
1323 pub fn concretize(
1324 _attrs: proc_macro::TokenStream,
1325 input: proc_macro::TokenStream) -> proc_macro::TokenStream
1326 {
1327 // Do nothing. This "attribute" is processed as text by the real proc
1328 // macros.
1329 input
1330 }
1331
1332 #[proc_macro]
1333 pub fn mock(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
1334 do_mock(input.into()).into()
1335 }
1336
1337 #[proc_macro_attribute]
1338 pub fn automock(attrs: proc_macro::TokenStream, input: proc_macro::TokenStream)
1339 -> proc_macro::TokenStream
1340 {
1341 let attrs: proc_macro2::TokenStream = attrs.into();
1342 let input: proc_macro2::TokenStream = input.into();
1343 do_automock(attrs, input).into()
1344 }
1345
1346 fn do_automock_once(attrs: TokenStream, input: TokenStream) -> TokenStream {
1347 let mut output = input.clone();
1348 let attrs: Attrs = match parse2(attrs) {
1349 Ok(a) => a,
1350 Err(err) => {
1351 return err.to_compile_error();
1352 }
1353 };
1354 let item: Item = match parse2(input) {
1355 Ok(item) => item,
1356 Err(err) => {
1357 return err.to_compile_error();
1358 }
1359 };
1360 output.extend(mock_it((attrs, item)));
1361 output
1362 }
1363
1364 fn do_automock(attrs: TokenStream, input: TokenStream) -> TokenStream {
1365 cfg_if! {
1366 if #[cfg(reprocheck)] {
1367 let ts_a = do_automock_once(attrs.clone(), input.clone());
1368 let ts_b = do_automock_once(attrs.clone(), input.clone());
1369 assert_eq!(ts_a.to_string(), ts_b.to_string());
1370 }
1371 }
1372 do_automock_once(attrs, input)
1373 }
1374
1375 #[cfg(test)]
1376 mod t {
1377 use super::*;
1378
1379 fn assert_contains(output: &str, tokens: TokenStream) {
1380 let s = tokens.to_string();
1381 assert!(output.contains(&s), "output does not contain {:?}", &s);
1382 }
1383
1384 fn assert_not_contains(output: &str, tokens: TokenStream) {
1385 let s = tokens.to_string();
1386 assert!(!output.contains(&s), "output contains {:?}", &s);
1387 }
1388
1389 /// Various tests for overall code generation that are hard or impossible to
1390 /// write as integration tests
1391 mod mock {
1392 use std::str::FromStr;
1393 use super::super::*;
1394 use super::*;
1395
1396 #[test]
1397 fn inherent_method_visibility() {
1398 let code = "
1399 Foo {
1400 fn foo(&self);
1401 pub fn bar(&self);
1402 pub(crate) fn baz(&self);
1403 pub(super) fn bean(&self);
1404 pub(in crate::outer) fn boom(&self);
1405 }
1406 ";
1407 let ts = proc_macro2::TokenStream::from_str(code).unwrap();
1408 let output = do_mock(ts).to_string();
1409 assert_not_contains(&output, quote!(pub fn foo));
1410 assert!(!output.contains(") fn foo"));
1411 assert_contains(&output, quote!(pub fn bar));
1412 assert_contains(&output, quote!(pub(crate) fn baz));
1413 assert_contains(&output, quote!(pub(super) fn bean));
1414 assert_contains(&output, quote!(pub(in crate::outer) fn boom));
1415
1416 assert_not_contains(&output, quote!(pub fn expect_foo));
1417 assert!(!output.contains("pub fn expect_foo"));
1418 assert!(!output.contains(") fn expect_foo"));
1419 assert_contains(&output, quote!(pub fn expect_bar));
1420 assert_contains(&output, quote!(pub(crate) fn expect_baz));
1421 assert_contains(&output, quote!(pub(super) fn expect_bean));
1422 assert_contains(&output, quote!(pub(in crate::outer) fn expect_boom));
1423 }
1424
1425 #[test]
1426 fn must_use_struct() {
1427 let code = "
1428 #[must_use]
1429 pub Foo {}
1430 ";
1431 let ts = proc_macro2::TokenStream::from_str(code).unwrap();
1432 let output = do_mock(ts).to_string();
1433 assert_contains(&output, quote!(#[must_use] pub struct MockFoo));
1434 }
1435
1436 #[test]
1437 fn specific_impl() {
1438 let code = "
1439 pub Foo<T: 'static> {}
1440 impl Bar for Foo<u32> {
1441 fn bar(&self);
1442 }
1443 impl Bar for Foo<i32> {
1444 fn bar(&self);
1445 }
1446 ";
1447 let ts = proc_macro2::TokenStream::from_str(code).unwrap();
1448 let output = do_mock(ts).to_string();
1449 assert_contains(&output, quote!(impl Bar for MockFoo<u32>));
1450 assert_contains(&output, quote!(impl Bar for MockFoo<i32>));
1451 // Ensure we don't duplicate the checkpoint function
1452 assert_not_contains(&output, quote!(
1453 self.Bar_expectations.checkpoint();
1454 self.Bar_expectations.checkpoint();
1455 ));
1456 // The expect methods should return specific types, not generic ones
1457 assert_contains(&output, quote!(
1458 pub fn expect_bar(&mut self) -> &mut __mock_MockFoo_Bar::__bar::Expectation<u32>
1459 ));
1460 assert_contains(&output, quote!(
1461 pub fn expect_bar(&mut self) -> &mut __mock_MockFoo_Bar::__bar::Expectation<i32>
1462 ));
1463 }
1464 }
1465
1466 /// Various tests for overall code generation that are hard or impossible to
1467 /// write as integration tests
1468 mod automock {
1469 use std::str::FromStr;
1470 use super::super::*;
1471 use super::*;
1472
1473 #[test]
1474 fn doc_comments() {
1475 let code = "
1476 mod foo {
1477 /// Function docs
1478 pub fn bar() { unimplemented!() }
1479 }
1480 ";
1481 let ts = proc_macro2::TokenStream::from_str(code).unwrap();
1482 let attrs_ts = proc_macro2::TokenStream::from_str("").unwrap();
1483 let output = do_automock(attrs_ts, ts).to_string();
1484 assert_contains(&output, quote!(#[doc=" Function docs"] pub fn bar));
1485 }
1486
1487 #[test]
1488 fn method_visibility() {
1489 let code = "
1490 impl Foo {
1491 fn foo(&self) {}
1492 pub fn bar(&self) {}
1493 pub(super) fn baz(&self) {}
1494 pub(crate) fn bang(&self) {}
1495 pub(in super::x) fn bean(&self) {}
1496 }";
1497 let ts = proc_macro2::TokenStream::from_str(code).unwrap();
1498 let attrs_ts = proc_macro2::TokenStream::from_str("").unwrap();
1499 let output = do_automock(attrs_ts, ts).to_string();
1500 assert_not_contains(&output, quote!(pub fn foo));
1501 assert!(!output.contains(") fn foo"));
1502 assert_not_contains(&output, quote!(pub fn expect_foo));
1503 assert!(!output.contains(") fn expect_foo"));
1504 assert_contains(&output, quote!(pub fn bar));
1505 assert_contains(&output, quote!(pub fn expect_bar));
1506 assert_contains(&output, quote!(pub(super) fn baz));
1507 assert_contains(&output, quote!(pub(super) fn expect_baz));
1508 assert_contains(&output, quote!(pub ( crate ) fn bang));
1509 assert_contains(&output, quote!(pub ( crate ) fn expect_bang));
1510 assert_contains(&output, quote!(pub ( in super :: x ) fn bean));
1511 assert_contains(&output, quote!(pub ( in super :: x ) fn expect_bean));
1512 }
1513
1514 #[test]
1515 fn must_use_method() {
1516 let code = "
1517 impl Foo {
1518 #[must_use]
1519 fn foo(&self) -> i32 {42}
1520 }";
1521 let ts = proc_macro2::TokenStream::from_str(code).unwrap();
1522 let attrs_ts = proc_macro2::TokenStream::from_str("").unwrap();
1523 let output = do_automock(attrs_ts, ts).to_string();
1524 assert_not_contains(&output, quote!(#[must_use] fn expect_foo));
1525 assert_contains(&output, quote!(#[must_use] #[allow(dead_code)] fn foo));
1526 }
1527
1528 #[test]
1529 fn must_use_static_method() {
1530 let code = "
1531 impl Foo {
1532 #[must_use]
1533 fn foo() -> i32 {42}
1534 }";
1535 let ts = proc_macro2::TokenStream::from_str(code).unwrap();
1536 let attrs_ts = proc_macro2::TokenStream::from_str("").unwrap();
1537 let output = do_automock(attrs_ts, ts).to_string();
1538 assert_not_contains(&output, quote!(#[must_use] fn expect));
1539 assert_not_contains(&output, quote!(#[must_use] fn foo_context));
1540 assert_contains(&output, quote!(#[must_use] #[allow(dead_code)] fn foo));
1541 }
1542
1543 #[test]
1544 fn must_use_trait() {
1545 let code = "
1546 #[must_use]
1547 trait Foo {}
1548 ";
1549 let ts = proc_macro2::TokenStream::from_str(code).unwrap();
1550 let attrs_ts = proc_macro2::TokenStream::from_str("").unwrap();
1551 let output = do_automock(attrs_ts, ts).to_string();
1552 assert_not_contains(&output, quote!(#[must_use] struct MockFoo));
1553 }
1554
1555 #[test]
1556 #[should_panic(expected = "can only mock inline modules")]
1557 fn external_module() {
1558 let code = "mod foo;";
1559 let ts = proc_macro2::TokenStream::from_str(code).unwrap();
1560 let attrs_ts = proc_macro2::TokenStream::from_str("").unwrap();
1561 do_automock(attrs_ts, ts).to_string();
1562 }
1563
1564 #[test]
1565 fn trait_visibility() {
1566 let code = "
1567 pub(super) trait Foo {}
1568 ";
1569 let attrs_ts = proc_macro2::TokenStream::from_str("").unwrap();
1570 let ts = proc_macro2::TokenStream::from_str(code).unwrap();
1571 let output = do_automock(attrs_ts, ts).to_string();
1572 assert_contains(&output, quote!(pub ( super ) struct MockFoo));
1573 }
1574 }
1575
1576 mod concretize_args {
1577 use super::*;
1578
1579 #[allow(clippy::needless_range_loop)] // Clippy's suggestion is worse
1580 fn check_concretize(
1581 sig: TokenStream,
1582 expected_inputs: &[TokenStream],
1583 expected_call_exprs: &[TokenStream],
1584 expected_sig_inputs: &[TokenStream])
1585 {
1586 let f: Signature = parse2(sig).unwrap();
1587 let (generics, inputs, call_exprs, altsig) = concretize_args(&f.generics, &f);
1588 assert!(generics.params.is_empty());
1589 assert_eq!(inputs.len(), expected_inputs.len());
1590 assert_eq!(call_exprs.len(), expected_call_exprs.len());
1591 for i in 0..inputs.len() {
1592 let actual = &inputs[i];
1593 let exp = &expected_inputs[i];
1594 assert_eq!(quote!(#actual).to_string(), quote!(#exp).to_string());
1595 }
1596 for i in 0..call_exprs.len() {
1597 let actual = &call_exprs[i];
1598 let exp = &expected_call_exprs[i];
1599 assert_eq!(quote!(#actual).to_string(), quote!(#exp).to_string());
1600 }
1601 for i in 0..altsig.inputs.len() {
1602 let actual = &altsig.inputs[i];
1603 let exp = &expected_sig_inputs[i];
1604 assert_eq!(quote!(#actual).to_string(), quote!(#exp).to_string());
1605 }
1606 }
1607
1608 #[test]
1609 fn bystanders() {
1610 check_concretize(
1611 quote!(fn foo<P: AsRef<Path>>(x: i32, p: P, y: &f64)),
1612 &[quote!(x: i32), quote!(p: &(dyn AsRef<Path>)), quote!(y: &f64)],
1613 &[quote!(x), quote!(&p), quote!(y)],
1614 &[quote!(x: i32), quote!(p: P), quote!(y: &f64)]
1615 );
1616 }
1617
1618 #[test]
1619 fn function_args() {
1620 check_concretize(
1621 quote!(fn foo<F1: Fn(u32) -> u32,
1622 F2: FnMut(&mut u32) -> u32,
1623 F3: FnOnce(u32) -> u32>(f1: F1, f2: F2, f3: F3)),
1624 &[quote!(f1: &(dyn Fn(u32) -> u32)),
1625 quote!(f2: &mut(dyn FnMut(&mut u32) -> u32)),
1626 quote!(f3: &(dyn FnOnce(u32) -> u32))],
1627 &[quote!(&f1), quote!(&mut f2), quote!(&f3)],
1628 &[quote!(f1: F1), quote!(mut f2: F2), quote!(f3: F3)]
1629 );
1630 }
1631
1632 #[test]
1633 fn multi_bounds() {
1634 check_concretize(
1635 quote!(fn foo<P: AsRef<String> + AsMut<String>>(p: P)),
1636 &[quote!(p: &(dyn AsRef<String> + AsMut<String>))],
1637 &[quote!(&p)],
1638 &[quote!(p: P)],
1639 );
1640 }
1641
1642 #[test]
1643 fn mutable_reference_arg() {
1644 check_concretize(
1645 quote!(fn foo<P: AsMut<Path>>(p: &mut P)),
1646 &[quote!(p: &mut (dyn AsMut<Path>))],
1647 &[quote!(p)],
1648 &[quote!(p: &mut P)],
1649 );
1650 }
1651
1652 #[test]
1653 fn mutable_reference_multi_bounds() {
1654 check_concretize(
1655 quote!(fn foo<P: AsRef<String> + AsMut<String>>(p: &mut P)),
1656 &[quote!(p: &mut (dyn AsRef<String> + AsMut<String>))],
1657 &[quote!(p)],
1658 &[quote!(p: &mut P)]
1659 );
1660 }
1661
1662 #[test]
1663 fn reference_arg() {
1664 check_concretize(
1665 quote!(fn foo<P: AsRef<Path>>(p: &P)),
1666 &[quote!(p: &(dyn AsRef<Path>))],
1667 &[quote!(p)],
1668 &[quote!(p: &P)]
1669 );
1670 }
1671
1672 #[test]
1673 fn simple() {
1674 check_concretize(
1675 quote!(fn foo<P: AsRef<Path>>(p: P)),
1676 &[quote!(p: &(dyn AsRef<Path>))],
1677 &[quote!(&p)],
1678 &[quote!(p: P)],
1679 );
1680 }
1681
1682 #[test]
1683 fn slice() {
1684 check_concretize(
1685 quote!(fn foo<P: AsRef<Path>>(p: &[P])),
1686 &[quote!(p: &[&(dyn AsRef<Path>)])],
1687 &[quote!(&(0..p.len()).map(|__mockall_i| &p[__mockall_i] as &(dyn AsRef<Path>)).collect::<Vec<_>>())],
1688 &[quote!(p: &[P])]
1689 );
1690 }
1691
1692 #[test]
1693 fn slice_with_multi_bounds() {
1694 check_concretize(
1695 quote!(fn foo<P: AsRef<Path> + AsMut<String>>(p: &[P])),
1696 &[quote!(p: &[&(dyn AsRef<Path> + AsMut<String>)])],
1697 &[quote!(&(0..p.len()).map(|__mockall_i| &p[__mockall_i] as &(dyn AsRef<Path> + AsMut<String>)).collect::<Vec<_>>())],
1698 &[quote!(p: &[P])]
1699 );
1700 }
1701
1702 #[test]
1703 fn where_clause() {
1704 check_concretize(
1705 quote!(fn foo<P>(p: P) where P: AsRef<Path>),
1706 &[quote!(p: &(dyn AsRef<Path>))],
1707 &[quote!(&p)],
1708 &[quote!(p: P)]
1709 );
1710 }
1711 }
1712
1713 mod declosurefy {
1714 use super::*;
1715
1716 fn check_declosurefy(
1717 sig: TokenStream,
1718 expected_inputs: &[TokenStream],
1719 expected_call_exprs: &[TokenStream])
1720 {
1721 let f: Signature = parse2(sig).unwrap();
1722 let (generics, inputs, call_exprs) =
1723 declosurefy(&f.generics, &f.inputs);
1724 assert!(generics.params.is_empty());
1725 assert_eq!(inputs.len(), expected_inputs.len());
1726 assert_eq!(call_exprs.len(), expected_call_exprs.len());
1727 for i in 0..inputs.len() {
1728 let actual = &inputs[i];
1729 let exp = &expected_inputs[i];
1730 assert_eq!(quote!(#actual).to_string(), quote!(#exp).to_string());
1731 }
1732 for i in 0..call_exprs.len() {
1733 let actual = &call_exprs[i];
1734 let exp = &expected_call_exprs[i];
1735 assert_eq!(quote!(#actual).to_string(), quote!(#exp).to_string());
1736 }
1737 }
1738
1739 #[test]
1740 fn r#fn() {
1741 check_declosurefy(
1742 quote!(fn foo<F: Fn(u32) -> u32>(f: F)),
1743 &[quote!(f: Box<dyn Fn(u32) -> u32>)],
1744 &[quote!(Box::new(f))]
1745 );
1746 }
1747
1748 #[test]
1749 fn fn_mut() {
1750 check_declosurefy(
1751 quote!(fn foo<F: FnMut(u32) -> u32>(f: F)),
1752 &[quote!(f: Box<dyn FnMut(u32) -> u32>)],
1753 &[quote!(Box::new(f))]
1754 );
1755 }
1756
1757 #[test]
1758 fn fn_once() {
1759 check_declosurefy(
1760 quote!(fn foo<F: FnOnce(u32) -> u32>(f: F)),
1761 &[quote!(f: Box<dyn FnOnce(u32) -> u32>)],
1762 &[quote!(Box::new(f))]
1763 );
1764 }
1765
1766 #[test]
1767 fn mutable_pattern() {
1768 check_declosurefy(
1769 quote!(fn foo<F: FnMut(u32) -> u32>(mut f: F)),
1770 &[quote!(f: Box<dyn FnMut(u32) -> u32>)],
1771 &[quote!(Box::new(f))]
1772 );
1773 }
1774
1775 #[test]
1776 fn where_clause() {
1777 check_declosurefy(
1778 quote!(fn foo<F>(f: F) where F: Fn(u32) -> u32),
1779 &[quote!(f: Box<dyn Fn(u32) -> u32>)],
1780 &[quote!(Box::new(f))]
1781 );
1782 }
1783 }
1784
1785 mod deimplify {
1786 use super::*;
1787
1788 fn check_deimplify(orig_ts: TokenStream, expected_ts: TokenStream) {
1789 let mut orig: ReturnType = parse2(orig_ts).unwrap();
1790 let expected: ReturnType = parse2(expected_ts).unwrap();
1791 deimplify(&mut orig);
1792 assert_eq!(quote!(#orig).to_string(), quote!(#expected).to_string());
1793 }
1794
1795 // Future is a special case
1796 #[test]
1797 fn impl_future() {
1798 check_deimplify(
1799 quote!(-> impl Future<Output=i32>),
1800 quote!(-> ::std::pin::Pin<Box<dyn Future<Output=i32>>>)
1801 );
1802 }
1803
1804 // Future is a special case, wherever it appears
1805 #[test]
1806 fn impl_future_reverse() {
1807 check_deimplify(
1808 quote!(-> impl Send + Future<Output=i32>),
1809 quote!(-> ::std::pin::Pin<Box<dyn Send + Future<Output=i32>>>)
1810 );
1811 }
1812
1813 // Stream is a special case
1814 #[test]
1815 fn impl_stream() {
1816 check_deimplify(
1817 quote!(-> impl Stream<Item=i32>),
1818 quote!(-> ::std::pin::Pin<Box<dyn Stream<Item=i32>>>)
1819 );
1820 }
1821
1822 #[test]
1823 fn impl_trait() {
1824 check_deimplify(
1825 quote!(-> impl Foo),
1826 quote!(-> Box<dyn Foo>)
1827 );
1828 }
1829
1830 // With extra bounds
1831 #[test]
1832 fn impl_trait2() {
1833 check_deimplify(
1834 quote!(-> impl Foo + Send),
1835 quote!(-> Box<dyn Foo + Send>)
1836 );
1837 }
1838 }
1839
1840 mod deselfify {
1841 use super::*;
1842
1843 fn check_deselfify(
1844 orig_ts: TokenStream,
1845 actual_ts: TokenStream,
1846 generics_ts: TokenStream,
1847 expected_ts: TokenStream)
1848 {
1849 let mut ty: Type = parse2(orig_ts).unwrap();
1850 let actual: Ident = parse2(actual_ts).unwrap();
1851 let generics: Generics = parse2(generics_ts).unwrap();
1852 let expected: Type = parse2(expected_ts).unwrap();
1853 deselfify(&mut ty, &actual, &generics);
1854 assert_eq!(quote!(#ty).to_string(),
1855 quote!(#expected).to_string());
1856 }
1857
1858 #[test]
1859 fn arc() {
1860 check_deselfify(
1861 quote!(Arc<Self>),
1862 quote!(Foo),
1863 quote!(),
1864 quote!(Arc<Foo>)
1865 );
1866 }
1867 #[test]
1868 fn future() {
1869 check_deselfify(
1870 quote!(Box<dyn Future<Output=Self>>),
1871 quote!(Foo),
1872 quote!(),
1873 quote!(Box<dyn Future<Output=Foo>>)
1874 );
1875 }
1876
1877 #[test]
1878 fn qself() {
1879 check_deselfify(
1880 quote!(<Self as Self>::Self),
1881 quote!(Foo),
1882 quote!(),
1883 quote!(<Foo as Foo>::Foo)
1884 );
1885 }
1886
1887 #[test]
1888 fn trait_object() {
1889 check_deselfify(
1890 quote!(Box<dyn Self>),
1891 quote!(Foo),
1892 quote!(),
1893 quote!(Box<dyn Foo>)
1894 );
1895 }
1896
1897 // A trait object with multiple bounds
1898 #[test]
1899 fn trait_object2() {
1900 check_deselfify(
1901 quote!(Box<dyn Self + Send>),
1902 quote!(Foo),
1903 quote!(),
1904 quote!(Box<dyn Foo + Send>)
1905 );
1906 }
1907 }
1908
1909 mod dewhereselfify {
1910 use super::*;
1911
1912 #[test]
1913 fn lifetime() {
1914 let mut meth: ImplItemFn = parse2(quote!(
1915 fn foo<'a>(&self) where 'a: 'static, Self: Sized {}
1916 )).unwrap();
1917 let expected: ImplItemFn = parse2(quote!(
1918 fn foo<'a>(&self) where 'a: 'static {}
1919 )).unwrap();
1920 dewhereselfify(&mut meth.sig.generics);
1921 assert_eq!(meth, expected);
1922 }
1923
1924 #[test]
1925 fn normal_method() {
1926 let mut meth: ImplItemFn = parse2(quote!(
1927 fn foo(&self) where Self: Sized {}
1928 )).unwrap();
1929 let expected: ImplItemFn = parse2(quote!(
1930 fn foo(&self) {}
1931 )).unwrap();
1932 dewhereselfify(&mut meth.sig.generics);
1933 assert_eq!(meth, expected);
1934 }
1935
1936 #[test]
1937 fn with_real_generics() {
1938 let mut meth: ImplItemFn = parse2(quote!(
1939 fn foo<T>(&self, t: T) where Self: Sized, T: Copy {}
1940 )).unwrap();
1941 let expected: ImplItemFn = parse2(quote!(
1942 fn foo<T>(&self, t: T) where T: Copy {}
1943 )).unwrap();
1944 dewhereselfify(&mut meth.sig.generics);
1945 assert_eq!(meth, expected);
1946 }
1947 }
1948
1949 mod gen_keyid {
1950 use super::*;
1951
1952 fn check_gen_keyid(orig: TokenStream, expected: TokenStream) {
1953 let g: Generics = parse2(orig).unwrap();
1954 let keyid = gen_keyid(&g);
1955 assert_eq!(quote!(#keyid).to_string(), quote!(#expected).to_string());
1956 }
1957
1958 #[test]
1959 fn empty() {
1960 check_gen_keyid(quote!(), quote!(<()>));
1961 }
1962
1963 #[test]
1964 fn onetype() {
1965 check_gen_keyid(quote!(<T>), quote!(<T>));
1966 }
1967
1968 #[test]
1969 fn twotypes() {
1970 check_gen_keyid(quote!(<T, V>), quote!(<(T, V)>));
1971 }
1972 }
1973
1974 mod merge_generics {
1975 use super::*;
1976
1977 #[test]
1978 fn both() {
1979 let mut g1: Generics = parse2(quote!(<T: 'static, V: Copy> )).unwrap();
1980 let wc1: WhereClause = parse2(quote!(where T: Default)).unwrap();
1981 g1.where_clause = Some(wc1);
1982
1983 let mut g2: Generics = parse2(quote!(<Q: Send, V: Clone>)).unwrap();
1984 let wc2: WhereClause = parse2(quote!(where T: Sync, Q: Debug)).unwrap();
1985 g2.where_clause = Some(wc2);
1986
1987 let gm = super::merge_generics(&g1, &g2);
1988 let gm_wc = &gm.where_clause;
1989
1990 let ge: Generics = parse2(quote!(
1991 <T: 'static, V: Copy + Clone, Q: Send>
1992 )).unwrap();
1993 let wce: WhereClause = parse2(quote!(
1994 where T: Default + Sync, Q: Debug
1995 )).unwrap();
1996
1997 assert_eq!(quote!(#ge #wce).to_string(),
1998 quote!(#gm #gm_wc).to_string());
1999 }
2000
2001 #[test]
2002 fn eq() {
2003 let mut g1: Generics = parse2(quote!(<T: 'static, V: Copy> )).unwrap();
2004 let wc1: WhereClause = parse2(quote!(where T: Default)).unwrap();
2005 g1.where_clause = Some(wc1.clone());
2006
2007 let gm = super::merge_generics(&g1, &g1);
2008 let gm_wc = &gm.where_clause;
2009
2010 assert_eq!(quote!(#g1 #wc1).to_string(),
2011 quote!(#gm #gm_wc).to_string());
2012 }
2013
2014 #[test]
2015 fn lhs_only() {
2016 let mut g1: Generics = parse2(quote!(<T: 'static, V: Copy> )).unwrap();
2017 let wc1: WhereClause = parse2(quote!(where T: Default)).unwrap();
2018 g1.where_clause = Some(wc1.clone());
2019
2020 let g2 = Generics::default();
2021
2022 let gm = super::merge_generics(&g1, &g2);
2023 let gm_wc = &gm.where_clause;
2024
2025 assert_eq!(quote!(#g1 #wc1).to_string(),
2026 quote!(#gm #gm_wc).to_string());
2027 }
2028
2029 #[test]
2030 fn lhs_wc_only() {
2031 let mut g1 = Generics::default();
2032 let wc1: WhereClause = parse2(quote!(where T: Default)).unwrap();
2033 g1.where_clause = Some(wc1.clone());
2034
2035 let g2 = Generics::default();
2036
2037 let gm = super::merge_generics(&g1, &g2);
2038 let gm_wc = &gm.where_clause;
2039
2040 assert_eq!(quote!(#g1 #wc1).to_string(),
2041 quote!(#gm #gm_wc).to_string());
2042 }
2043
2044 #[test]
2045 fn rhs_only() {
2046 let g1 = Generics::default();
2047 let mut g2: Generics = parse2(quote!(<Q: Send, V: Clone>)).unwrap();
2048 let wc2: WhereClause = parse2(quote!(where T: Sync, Q: Debug)).unwrap();
2049 g2.where_clause = Some(wc2.clone());
2050
2051 let gm = super::merge_generics(&g1, &g2);
2052 let gm_wc = &gm.where_clause;
2053
2054 assert_eq!(quote!(#g2 #wc2).to_string(),
2055 quote!(#gm #gm_wc).to_string());
2056 }
2057 }
2058
2059 mod supersuperfy {
2060 use super::*;
2061
2062 fn check_supersuperfy(orig: TokenStream, expected: TokenStream) {
2063 let orig_ty: Type = parse2(orig).unwrap();
2064 let expected_ty: Type = parse2(expected).unwrap();
2065 let output = supersuperfy(&orig_ty, 1);
2066 assert_eq!(quote!(#output).to_string(),
2067 quote!(#expected_ty).to_string());
2068 }
2069
2070 #[test]
2071 fn array() {
2072 check_supersuperfy(
2073 quote!([super::X; n]),
2074 quote!([super::super::X; n])
2075 );
2076 }
2077
2078 #[test]
2079 fn barefn() {
2080 check_supersuperfy(
2081 quote!(fn(super::A) -> super::B),
2082 quote!(fn(super::super::A) -> super::super::B)
2083 );
2084 }
2085
2086 #[test]
2087 fn group() {
2088 let orig = TypeGroup {
2089 group_token: token::Group::default(),
2090 elem: Box::new(parse2(quote!(super::T)).unwrap())
2091 };
2092 let expected = TypeGroup {
2093 group_token: token::Group::default(),
2094 elem: Box::new(parse2(quote!(super::super::T)).unwrap())
2095 };
2096 let output = supersuperfy(&Type::Group(orig), 1);
2097 assert_eq!(quote!(#output).to_string(),
2098 quote!(#expected).to_string());
2099 }
2100
2101 // Just check that it doesn't panic
2102 #[test]
2103 fn infer() {
2104 check_supersuperfy( quote!(_), quote!(_));
2105 }
2106
2107 // Just check that it doesn't panic
2108 #[test]
2109 fn never() {
2110 check_supersuperfy( quote!(!), quote!(!));
2111 }
2112
2113 #[test]
2114 fn paren() {
2115 check_supersuperfy(
2116 quote!((super::X)),
2117 quote!((super::super::X))
2118 );
2119 }
2120
2121 #[test]
2122 fn path() {
2123 check_supersuperfy(
2124 quote!(::super::SuperT<u32>),
2125 quote!(::super::super::SuperT<u32>)
2126 );
2127 }
2128
2129 #[test]
2130 fn path_with_qself() {
2131 check_supersuperfy(
2132 quote!(<super::X as super::Y>::Foo<u32>),
2133 quote!(<super::super::X as super::super::Y>::Foo<u32>),
2134 );
2135 }
2136
2137 #[test]
2138 fn angle_bracketed_generic_arguments() {
2139 check_supersuperfy(
2140 quote!(mod_::T<super::X>),
2141 quote!(mod_::T<super::super::X>)
2142 );
2143 }
2144
2145 #[test]
2146 fn ptr() {
2147 check_supersuperfy(
2148 quote!(*const super::X),
2149 quote!(*const super::super::X)
2150 );
2151 }
2152
2153 #[test]
2154 fn reference() {
2155 check_supersuperfy(
2156 quote!(&'a mut super::X),
2157 quote!(&'a mut super::super::X)
2158 );
2159 }
2160
2161 #[test]
2162 fn slice() {
2163 check_supersuperfy(
2164 quote!([super::X]),
2165 quote!([super::super::X])
2166 );
2167 }
2168
2169 #[test]
2170 fn trait_object() {
2171 check_supersuperfy(
2172 quote!(dyn super::X + super::Y),
2173 quote!(dyn super::super::X + super::super::Y)
2174 );
2175 }
2176
2177 #[test]
2178 fn tuple() {
2179 check_supersuperfy(
2180 quote!((super::A, super::B)),
2181 quote!((super::super::A, super::super::B))
2182 );
2183 }
2184 }
2185
2186 mod supersuperfy_generics {
2187 use super::*;
2188
2189 fn check_supersuperfy_generics(
2190 orig: TokenStream,
2191 orig_wc: TokenStream,
2192 expected: TokenStream,
2193 expected_wc: TokenStream)
2194 {
2195 let mut orig_g: Generics = parse2(orig).unwrap();
2196 orig_g.where_clause = parse2(orig_wc).unwrap();
2197 let mut expected_g: Generics = parse2(expected).unwrap();
2198 expected_g.where_clause = parse2(expected_wc).unwrap();
2199 let mut output: Generics = orig_g;
2200 supersuperfy_generics(&mut output, 1);
2201 let (o_ig, o_tg, o_wc) = output.split_for_impl();
2202 let (e_ig, e_tg, e_wc) = expected_g.split_for_impl();
2203 assert_eq!(quote!(#o_ig).to_string(), quote!(#e_ig).to_string());
2204 assert_eq!(quote!(#o_tg).to_string(), quote!(#e_tg).to_string());
2205 assert_eq!(quote!(#o_wc).to_string(), quote!(#e_wc).to_string());
2206 }
2207
2208 #[test]
2209 fn default() {
2210 check_supersuperfy_generics(
2211 quote!(<T: X = super::Y>), quote!(),
2212 quote!(<T: X = super::super::Y>), quote!(),
2213 );
2214 }
2215
2216 #[test]
2217 fn empty() {
2218 check_supersuperfy_generics(quote!(), quote!(), quote!(), quote!());
2219 }
2220
2221 #[test]
2222 fn everything() {
2223 check_supersuperfy_generics(
2224 quote!(<T: super::A = super::B>),
2225 quote!(where super::C: super::D),
2226 quote!(<T: super::super::A = super::super::B>),
2227 quote!(where super::super::C: super::super::D),
2228 );
2229 }
2230
2231 #[test]
2232 fn bound() {
2233 check_supersuperfy_generics(
2234 quote!(<T: super::A>), quote!(),
2235 quote!(<T: super::super::A>), quote!(),
2236 );
2237 }
2238
2239 #[test]
2240 fn closure() {
2241 check_supersuperfy_generics(
2242 quote!(<F: Fn(u32) -> super::SuperT>), quote!(),
2243 quote!(<F: Fn(u32) -> super::super::SuperT>), quote!(),
2244 );
2245 }
2246
2247 #[test]
2248 fn wc_bounded_ty() {
2249 check_supersuperfy_generics(
2250 quote!(), quote!(where super::T: X),
2251 quote!(), quote!(where super::super::T: X),
2252 );
2253 }
2254
2255 #[test]
2256 fn wc_bounds() {
2257 check_supersuperfy_generics(
2258 quote!(), quote!(where T: super::X),
2259 quote!(), quote!(where T: super::super::X),
2260 );
2261 }
2262 }
2263 }