Debian Codegraph @

src/lib.rs

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