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
extern crate proc_macro;
extern crate syn;
#[macro_use]
extern crate quote;

use proc_macro::TokenStream;
use syn::DeriveInput;

#[proc_macro_derive(FailingTryFrom, attributes(FailingTryFrom))]
pub fn my_macro(input: TokenStream) -> TokenStream {
    // Parse the input tokens into a syntax tree.
    let input: DeriveInput = syn::parse(input).unwrap();

    let name = input.ident;
    let generics = input.generics;
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    let targets: Vec<syn::Ident> = input
        .attrs
        .iter()
        .filter_map(|attr| {
            // Find a list attribute named FailingTryFrom.
            match attr.interpret_meta()
                .filter(|meta| meta.name() == "FailingTryFrom")
            {
                Some(syn::Meta::List(list)) => Some(list.nested),
                _ => None,
            }
        })
        .next()
        .expect("No FailingTryFrom attribute found.")
        .into_iter()
        // Retrieve the list of target types from the attribute.
        .filter_map(|target_meta| match target_meta {
            syn::NestedMeta::Meta(syn::Meta::Word(target)) => Some(target),
            _ => None,
        })
        .collect();

    let expanded = targets
        .iter()
        .map(|target| {
            quote!{
                impl #impl_generics ::std::convert::TryFrom<#target> for #name #ty_generics #where_clause {
                    type Error = #target;

                    fn try_from(value: #target) -> Result<#name, #target> {
                        Err(value)
                    }
                }
            }
        })
        .fold(quote::Tokens::new(), |tokens, target| {
            quote!{
                #tokens
                #target
            }
        });

    expanded.into()
}