double_derive/lib.rs
1use quote::quote;
2use syn::{Error, Ident, ItemTrait, parse_macro_input};
3
4mod double_trait;
5mod dummy_impl;
6mod trait_impl;
7
8use self::{double_trait::double_trait, trait_impl::trait_impl};
9
10/// Generates a trait which replicates the original trait method for method. It does implement the
11/// original trait for each of its implementations, by means of forwarding the method calls. The
12/// utility comes from the fact that the generated trait has default implementations for each method
13/// using `unimplemented!()`, which makes it useful for testing purposes.
14///
15/// If a test requires an implementation of an original trait `Org` yet would only invoke one of its
16/// methods, implementing the mirrored method on an implementation of the generated trait `OrgDummy`
17/// is sufficient. The other methods would not be inovked in the test, so their default
18/// implementation using `unimplemented!()` would not be reached.
19///
20/// The argument passed to the attribute is used as the name of the generated trait.
21///
22/// * Existing default implementations are respected and not overridden.
23/// * Visibility of the generated trait is the same as the original trait.
24/// * `async` methods are supported
25/// * Methods returning `impl` Traits are not supported, with the exception of `impl Future`.
26/// * Generated double trait is implemented for `Dummy`.
27///
28/// # Example
29///
30/// Basic usage allows creating test stubs for traits, without worrying about implementing methods
31/// not called in test code
32///
33/// ```no_run
34/// use double_trait::double;
35///
36/// #[double(MyTraitDouble)]
37/// trait MyTrait {
38/// fn answer(&self) -> i32;
39///
40/// fn some_other_method(&self);
41/// }
42///
43/// struct MyStub;
44///
45/// impl MyTraitDouble for MyStub {
46/// fn answer(&self) -> i32 {
47/// 42
48/// }
49/// }
50///
51/// assert_eq!(42, MyTrait::answer(&MyStub));
52/// ```
53///
54/// Then interacting with the `async_trait` crate, make sure to put the `#[async_trait]` attribute
55/// on top.
56///
57/// ```no_run
58/// use double_trait::double;
59/// use async_trait::async_trait;
60///
61/// #[async_trait]
62/// #[double(MyTraitDouble)]
63/// trait MyTrait {
64/// async fn answer(&self) -> i32;
65/// }
66/// ```
67#[proc_macro_attribute]
68pub fn double(
69 attr: proc_macro::TokenStream,
70 item: proc_macro::TokenStream,
71) -> proc_macro::TokenStream {
72 let double_name = parse_macro_input!(attr as Ident);
73 let item = parse_macro_input!(item as ItemTrait);
74
75 let output = expand(double_name, item).unwrap_or_else(Error::into_compile_error);
76
77 proc_macro::TokenStream::from(output)
78}
79
80/// The main implementation of [`crate::double`]. This function is not annotated with
81/// `#[proc_macro_attribute]` so it can exist in unit tests. It uses only APIs build on top of
82/// [`proc_macro2`] in order to be unit testable.
83fn expand(double_trait_name: Ident, org_trait: ItemTrait) -> syn::Result<proc_macro2::TokenStream> {
84 let double_trait = double_trait(double_trait_name.clone(), org_trait.clone())?;
85 let trait_impl = trait_impl(double_trait_name.clone(), org_trait.clone());
86 let dummy_impl = dummy_impl::dummy_impl(double_trait_name, org_trait.clone());
87
88 // We generate three items as part of our output.
89 // 1. The orginal trait, which we put in the output unaltered.
90 // 2. The double trait, we genarate, which mirrors the original traits methods and provides
91 // default implementations using `unimplemented!()`.
92 // 3. An implementation of the original trait for all types which implement the double trait.
93 // This is done by forwarding the method calls to the double trait.
94 let token_stream = quote! {
95 #org_trait
96
97 #double_trait
98
99 #trait_impl
100
101 #dummy_impl
102 };
103 Ok(token_stream)
104}
105
106#[cfg(test)]
107mod tests {
108
109 use super::{Ident, expand};
110 use quote::quote;
111 use syn::{ItemTrait, parse2};
112
113 #[test]
114 fn generate_double_trait() {
115 let (attr, item) = given(quote! { MyTraitDummy }, quote! { trait MyTrait {} });
116
117 let output = expand(attr, item).unwrap();
118
119 let expected = quote! {
120 trait MyTrait {}
121
122 trait MyTraitDummy {}
123
124 impl<T> MyTrait for T where T: MyTraitDummy {}
125
126 impl MyTraitDummy for double_trait::Dummy {}
127 };
128 assert_eq!(expected.to_string(), output.to_string());
129 }
130
131 #[test]
132 fn forward_visibility() {
133 // Given a public trait
134 let (attr, item) = given(quote! { MyTraitDummy }, quote! { pub trait MyTrait {} });
135
136 // When generating the dummy
137 let output = expand(attr, item).unwrap();
138
139 // Then the generated trait should be public, too
140 let expected = quote! {
141 pub trait MyTrait {}
142
143 pub trait MyTraitDummy {}
144
145 impl<T> MyTrait for T where T: MyTraitDummy {}
146
147 impl MyTraitDummy for double_trait::Dummy {}
148 };
149 assert_eq!(expected.to_string(), output.to_string());
150 }
151
152 #[test]
153 fn forward_method() {
154 // Given a trait with a method
155 let (attr, item) = given(
156 quote! { MyTraitDummy },
157 quote! {
158 trait MyTrait {
159 fn foobar(&self);
160 }
161 },
162 );
163
164 // When generating the dummy
165 let output = expand(attr, item).unwrap();
166
167 // Then the generated trait should contain that method, too
168 let expected = quote! {
169 trait MyTrait {
170 fn foobar(&self);
171 }
172
173 trait MyTraitDummy {
174 fn foobar (&self) {}
175 }
176
177 impl<T> MyTrait for T where T: MyTraitDummy {
178 fn foobar(&self) { <Self as MyTraitDummy>::foobar(self,) }
179 }
180
181 impl MyTraitDummy for double_trait::Dummy {}
182 };
183 assert_eq!(expected.to_string(), output.to_string());
184 }
185
186 #[test]
187 fn respect_existing_default_impl() {
188 // Given a method with a default implementation in the original trait
189 let (attr, item) = given(
190 quote! { MyTraitDummy },
191 quote! {
192 pub trait MyTrait {
193 fn foobar() { println!("Hello Default!") }
194 }
195 },
196 );
197
198 // When generating the dummy
199 let output = expand(attr, item).unwrap();
200
201 // Then the generated trait should not overide the existing default
202 let expected = quote! {
203 pub trait MyTrait {
204 fn foobar() { println!("Hello Default!") }
205 }
206
207 pub trait MyTraitDummy {
208 fn foobar() { println!("Hello Default!") }
209 }
210
211 impl<T> MyTrait for T where T: MyTraitDummy {
212 fn foobar() { <Self as MyTraitDummy>::foobar() }
213 }
214
215 impl MyTraitDummy for double_trait::Dummy {}
216 };
217 assert_eq!(expected.to_string(), output.to_string());
218 }
219
220 #[test]
221 fn forward_async_method() {
222 // Given a trait with a method
223 let (attr, item) = given(
224 quote! { MyTraitDummy },
225 quote! {
226 trait MyTrait {
227 async fn foobar(&self);
228 }
229 },
230 );
231
232 // When generating the dummy
233 let output = expand(attr, item).unwrap();
234
235 // Then the generated trait should contain that method, too
236 let expected = quote! {
237 trait MyTrait {
238 async fn foobar(&self);
239 }
240
241 trait MyTraitDummy {
242 async fn foobar (&self) {}
243 }
244
245 impl<T> MyTrait for T where T: MyTraitDummy {
246 async fn foobar(&self) { <Self as MyTraitDummy>::foobar(self,).await }
247 }
248
249 impl MyTraitDummy for double_trait::Dummy {}
250 };
251 assert_eq!(expected.to_string(), output.to_string());
252 }
253
254 fn given(attr: proc_macro2::TokenStream, item: proc_macro2::TokenStream) -> (Ident, ItemTrait) {
255 let attr: Ident = parse2(attr).unwrap();
256 let item: ItemTrait = parse2(item).unwrap();
257 (attr, item)
258 }
259}