double-derive 0.2.7

Implementations of macros for crate double-trait
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use quote::{quote, quote_spanned};
use syn::{
    AngleBracketedGenericArguments, Block, FnArg, GenericArgument, Ident, ItemTrait, Pat, PatWild,
    PathArguments, ReturnType, Token, TraitItem, TraitItemFn, Type, TypeParamBound, parse2,
    punctuated::Punctuated, spanned::Spanned, token::Comma,
};

/// Generate a double trait which mirrors the original trait's methods and provides default
/// implementations using `unimplemented!()`.
pub fn double_trait(org_trait: ItemTrait) -> syn::Result<ItemTrait> {
    let items = org_trait
        .items
        .into_iter()
        .map(|item| transform_trait_item(item, org_trait.ident.clone()))
        .collect::<syn::Result<_>>()?;
    Ok(ItemTrait { items, ..org_trait })
}

fn transform_trait_item(trait_item: TraitItem, double_trait_name: Ident) -> syn::Result<TraitItem> {
    // We are only interessted in transforming functions
    let transformed_trait_item = match trait_item {
        TraitItem::Fn(fn_item) => TraitItem::Fn(transform_function(fn_item, double_trait_name)?),
        _ => {
            // If it is not a function, we forward the original Item
            trait_item
        }
    };
    Ok(transformed_trait_item)
}

// Give methods a default implementation, if they do not have one already.
fn transform_function(
    mut fn_item: TraitItemFn,
    double_trait_name: Ident,
) -> syn::Result<TraitItemFn> {
    if fn_item.default.is_some() {
        return Ok(fn_item);
    }

    // We are stripping parameter names in order to avoid warnings regarding unused variables, since
    // our default implementation is not making use of any arguments.
    strip_parameter_names(&mut fn_item.sig.inputs);

    let return_type_info = return_type_info(&fn_item.sig.output);
    let fn_name = fn_item.sig.ident.clone();

    let default_impl = default_impl(&fn_item, double_trait_name, &return_type_info, fn_name);

    fn_item.default = Some(default_impl);

    Ok(fn_item)
}

fn default_impl(
    fn_item: &TraitItemFn,
    double_trait_name: Ident,
    return_type_info: &ReturnTypeInfo,
    fn_name: Ident,
) -> Block {
    match return_type_info {
        ReturnTypeInfo::ImplFuture { output } => {
            // Treat missing Output type like other, i.e. use unimplemented!() in the async block
            let output = output.as_deref().unwrap_or(&ReturnTypeInfo::Other);
            let inner = default_impl(fn_item, double_trait_name, output, fn_name);
            // If the method returns an impl Future, we provide a default implementation using an
            // async block, so that the compiler won't complain about not being able to infer the
            // type of `impl Future`.
            parse2(quote! {{ async #inner }}).unwrap()
        }
        ReturnTypeInfo::ImplIterator => {
            // If the method returns an impl Iterator, we provide a default implementation using an
            // empty array, so that the compiler won't complain about not being able to infer the
            // type of `impl Iterator`.
            parse2(quote! {{ [].into_iter() }}).unwrap()
        }
        ReturnTypeInfo::Other => {
            // Otherwise, we provide a default implementation using unimplemented!
            // We can unwrap here, this body should always compile
            parse2(quote! {{
                let double_trait_name = stringify!(#double_trait_name);
                let fn_name = stringify!(#fn_name);
                unimplemented!("{double_trait_name}::{fn_name}")
            }})
            .unwrap()
        }
        ReturnTypeInfo::Empty => {
            // If the function does not return anything, we provide an empty default implementation
            // to avoid using `unimplemented!()`.
            parse2(quote! { { } }).unwrap()
        }
        ReturnTypeInfo::UnknownImpl => parse2(quote_spanned! {
            fn_item.sig.output.span() => {
                compile_error!(
                    "impl Trait is currently not supported by double-trait. Apart from the \
                    special case of impl Future."
            )}
        })
        .unwrap(),
    }
}

fn strip_parameter_names(input: &mut Punctuated<FnArg, Comma>) {
    for arg in input {
        // We are only interested in pattern type. No need to transform `self`
        if let FnArg::Typed(pat_type) = arg {
            *pat_type.pat = Pat::Wild(PatWild {
                attrs: Vec::new(),
                underscore_token: Token![_](pat_type.span()),
            })
        }
    }
}

fn return_type_info(output: &ReturnType) -> ReturnTypeInfo {
    if let ReturnType::Type(_rarrow, ty) = output {
        type_info(ty)
    } else {
        ReturnTypeInfo::Empty
    }
}

fn type_info(ty: &Type) -> ReturnTypeInfo {
    match *ty {
        Type::ImplTrait(ref impl_trait) => {
            let mut trait_bounds = impl_trait.bounds.iter().filter_map(|b| match b {
                TypeParamBound::Trait(trait_bound) => Some(trait_bound),
                TypeParamBound::Lifetime(_)
                | TypeParamBound::PreciseCapture(_)
                | TypeParamBound::Verbatim(_)
                | _ => None,
            });
            let first_trait_bound = trait_bounds
                .next()
                .expect("At least one trait bound expected in impl trait.");
            let first_path_segment = first_trait_bound
                .path
                .segments
                .first()
                .expect("There must be at least one path segment in trait bound");
            let identifier = &first_path_segment.ident.to_string();
            match identifier.as_str() {
                "Future" => {
                    let output = associated_output_type(&first_path_segment.arguments);
                    // If the first trait bound is Future, we assume that this is an impl Future.
                    ReturnTypeInfo::ImplFuture {
                        output: output.map(|ty| Box::new(type_info(ty))),
                    }
                }
                "Iterator" => ReturnTypeInfo::ImplIterator,
                _ => ReturnTypeInfo::UnknownImpl,
            }
        }
        Type::Tuple(ref tuple_type) => {
            if tuple_type.elems.is_empty() {
                ReturnTypeInfo::Empty
            } else {
                ReturnTypeInfo::Other
            }
        }
        _ => ReturnTypeInfo::Other,
    }
}

/// Find the associated output type of an impl Future trait. E.g. the `i64` in impl Future<Output=i64>.
fn associated_output_type(future_trait_args: &PathArguments) -> Option<&Type> {
    let PathArguments::AngleBracketed(AngleBracketedGenericArguments { args, .. }) =
        future_trait_args
    else {
        return None;
    };
    args.iter()
        // Only look at associated types
        .filter_map(|arg| {
            let GenericArgument::AssocType(at) = arg else {
                return None;
            };
            Some(at)
        })
        // Find the associated type named "Output"
        .find(|at| at.ident == "Output")
        // Return the type of the associated type
        .map(|at| &at.ty)
}

#[derive(Debug)]
enum ReturnTypeInfo {
    /// If the function does not return, we want the default implementation to be empty, rather than
    /// using `unimplemented!()`.
    Empty,
    /// Indicates that the return type is an impl Future. We want to know this, so we can wrap
    /// `unimplemented!()` in an async block.
    ImplFuture {
        output: Option<Box<ReturnTypeInfo>>,
    },
    ImplIterator,
    UnknownImpl,
    Other,
}

#[cfg(test)]
mod tests {
    use super::{ReturnTypeInfo, double_trait, return_type_info};
    use quote::quote;
    use syn::{ItemTrait, ReturnType, parse2};

    #[test]
    fn return_type_info_unit() {
        let rt: ReturnType = parse2(quote! {-> () }).unwrap();
        assert!(matches!(return_type_info(&rt), ReturnTypeInfo::Empty));
    }

    #[test]
    fn return_type_info_i34() {
        let rt: ReturnType = parse2(quote! {-> i32 }).unwrap();
        assert!(matches!(return_type_info(&rt), ReturnTypeInfo::Other));
    }

    #[test]
    fn return_type_info_impl_future_i32() {
        let rt: ReturnType = parse2(quote! {-> impl Future<Output = i32> }).unwrap();
        let ReturnTypeInfo::ImplFuture {
            output: Some(output),
        } = return_type_info(&rt)
        else {
            panic!("Expected ReturnTypeInfo::ImplFuture with Some output");
        };
        assert!(matches!(*output, ReturnTypeInfo::Other));
    }

    #[test]
    fn return_type_info_impl_future_unit() {
        let rt: ReturnType = parse2(quote! {-> impl Future<Output = ()> }).unwrap();
        let ReturnTypeInfo::ImplFuture {
            output: Some(output),
        } = return_type_info(&rt)
        else {
            panic!("Expected ReturnTypeInfo::ImplFuture with Some output");
        };
        assert!(matches!(*output, ReturnTypeInfo::Empty));
    }

    #[test]
    fn return_type_info_impl_future_impl_iterator_i32() {
        let rt: ReturnType =
            parse2(quote! {-> impl Future<Output = impl Iterator<Item=i32>> }).unwrap();
        let ReturnTypeInfo::ImplFuture {
            output: Some(output),
        } = return_type_info(&rt)
        else {
            panic!("Expected ReturnTypeInfo::ImplFuture with Some output");
        };
        assert!(matches!(*output, ReturnTypeInfo::ImplIterator));
    }

    #[test]
    fn default_impl_for_method_with_impl_future_output_unit() {
        // Given an original trait with a method returning an impl Future
        let org_trait = given(quote! {
            trait MyTrait {
                fn method(&self) -> impl Future<Output = ()>;
            }
        });

        // When generating the double trait
        let double_trait = double_trait(org_trait).unwrap();

        // Then the double trait should have a default implementation for the method which uses
        // an async block
        let actual = quote! { #double_trait };
        let expected = quote! {
            trait MyTrait {
                fn method(&self) -> impl Future<Output = ()> {
                    async { }
                }
            }
        };
        assert_eq!(actual.to_string(), expected.to_string());
    }

    #[test]
    fn default_impl_for_method_with_impl_future_output_i32() {
        // Given an original trait with a method returning an impl Future
        let org_trait = given(quote! {
            trait MyTrait {
                fn method(&self) -> impl Future<Output = i32>;
            }
        });

        // When generating the double trait
        let double_trait = double_trait(org_trait).unwrap();

        // Then the double trait should have a default implementation for the method which uses
        // an async block
        let actual = quote! { #double_trait };
        let expected = quote! {
            trait MyTrait {
                fn method(&self) -> impl Future<Output = i32> {
                    async {
                        let double_trait_name = stringify!(MyTrait);
                        let fn_name = stringify!(method);
                        unimplemented!("{double_trait_name}::{fn_name}")
                    }
                }
            }
        };
        assert_eq!(expected.to_string(), actual.to_string());
    }

    #[test]
    fn default_impl_for_method_with_impl_iterator_return() {
        // Given an original trait with a method returning an impl Iterator
        let org_trait = given(quote! {
            trait MyTrait {
                fn method(&self) -> impl Iterator<Item = String>;
            }
        });

        // When generating the double trait
        let double_trait = double_trait(org_trait).unwrap();

        // Then the double trait should have a default implementation for the method which uses
        // an empty array iterator
        let actual = quote! { #double_trait };
        let expected = quote! {
            trait MyTrait {
                fn method(&self) -> impl Iterator<Item = String> {
                    [].into_iter()
                }
            }
        };
        assert_eq!(actual.to_string(), expected.to_string());
    }

    #[test]
    fn empty_default_implementation_if_function_does_not_return_anything() {
        // Given
        let org_trait = given(quote! {
            trait MyTrait {
                fn method(x: i32);
            }
        });

        // When
        let double_trait = double_trait(org_trait).unwrap();

        // Then
        let actual = quote! { #double_trait };
        let expected = quote! {
            trait MyTrait {
                fn method(_: i32) {}
            }
        };
        assert_eq!(actual.to_string(), expected.to_string());
    }

    #[test]
    fn default_implementation_for_function_with_i32_result() {
        // Given an original trait with a method returning an i32
        let org_trait = given(quote! {
            trait MyTrait {
                fn method(x: i32) -> i32;
            }
        });

        // When generating the double trait
        let double_trait = double_trait(org_trait).unwrap();

        // Then the double trait should have a default implementation with unimplemented!() which
        // uses the trait and function name in the error message.
        let actual = quote! { #double_trait };
        let expected = quote! {
            trait MyTrait {
                fn method(_: i32) -> i32 {
                    let double_trait_name = stringify!(MyTrait);
                    let fn_name = stringify!(method);
                    unimplemented!("{double_trait_name}::{fn_name}")
                }
            }
        };
        assert_eq!(actual.to_string(), expected.to_string());
    }

    #[test]
    fn compiler_error_for_unknown_return_impl() {
        // Given an original trait with a method returning an impl to an unsupported trait
        let org_trait = given(quote! {
            trait MyTrait {
                fn method() -> impl UnsupportedTrait;
            }
        });

        // When generating the double trait
        let double_trait = double_trait(org_trait).unwrap();

        // Then the double trait should have a default implementation which generates a nice compile
        // error.
        let actual = quote! { #double_trait };
        let expected = quote! {
            trait MyTrait {
                fn method() -> impl UnsupportedTrait {
                    compile_error!(
                        "impl Trait is currently not supported by double-trait. Apart from the \
                    special case of impl Future."
                    )
                }
            }
        };
        assert_eq!(actual.to_string(), expected.to_string());
    }

    #[test]
    fn strip_parameter_names_from_default_implementation() {
        // Given an original trait with a method returning an impl Future
        let org_trait = given(quote! {
            trait MyTrait {
                fn method(x: i32) -> i32;
            }
        });

        // When generating the double trait
        let double_trait = double_trait(org_trait).unwrap();

        // Then the double trait should have a default implementation for the method which uses
        // an async block
        let actual = quote! { #double_trait };
        let expected = quote! {
            trait MyTrait {
                fn method(_: i32) -> i32{
                    let double_trait_name = stringify!(MyTrait);
                    let fn_name = stringify!(method);
                    unimplemented!("{double_trait_name}::{fn_name}")
                }
            }
        };
        assert_eq!(actual.to_string(), expected.to_string());
    }

    fn given(item: proc_macro2::TokenStream) -> ItemTrait {
        parse2(item).unwrap()
    }
}