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
use proc_macro::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use syn;
use syn::punctuated::Pair;
use syn::Path;
use syn::{Data, DataStruct, DeriveInput, Fields, FieldsNamed, Ident, Lit, Meta, NestedMeta};

#[proc_macro_derive(Inter, attributes(from))]
pub fn derive_inter(input: TokenStream) -> TokenStream {
    let ast: DeriveInput = syn::parse(input).expect("Failed to parse macro input");
    let from_path = inter_attr_from_path(&ast);
    let name = ast.ident;
    if let Data::Struct(data) = ast.data {
        impl_struct_from(name, from_path, data)
    } else {
        panic!("Derivation only supports structs")
    }
}

fn find_meta_attr_single_path(ast: &DeriveInput, name: &str) -> Path {
    match find_meta_attr(ast, name) {
        Meta::List(meta_list) => {
            if meta_list.nested.len() != 1 {
                panic!(
                    "Meta attribute `{}` is expected to have a single path",
                    &name
                );
            };
            let nested = meta_list.nested.first().unwrap();
            match nested {
                NestedMeta::Meta(Meta::Path(path)) => path.clone(),
                NestedMeta::Lit(Lit::Str(lit)) => lit.parse::<Path>().expect(&format!(
                    "Meta attr `{}` does not include a valid path",
                    &name
                )),
                _ => panic!("Unexpected meta `{}` attrribute", &name),
            }
        }
        _ => panic!("Unexpected type of meta attribute for `{}`", &name),
    }
}

fn find_meta_attr(ast: &DeriveInput, name: &str) -> Meta {
    let attr = ast
        .attrs
        .iter()
        .find(|attr| attr.path.is_ident(name))
        .expect(&format!("Could not find the {} attribute", &name));
    attr.parse_meta()
        .expect(&format!("Expected `{}` attribute is malformed", &name))
}

fn inter_attr_from_path(ast: &DeriveInput) -> Path {
    find_meta_attr_single_path(ast, "from")
}

/// Derive an `impl From<$from_path> for $name`
fn impl_struct_from(name: Ident, from_path: Path, data: DataStruct) -> TokenStream {
    let fields = struct_fields_mappings(data.fields);
    let gen = quote! {
        impl From<#from_path> for #name {
            fn from(s: #from_path) -> #name {
                #name {
                  #fields
                }
            }
        }
    };
    gen.into()
}

fn struct_fields_mappings(fields: Fields) -> impl ToTokens {
    match fields {
        Fields::Named(fields_named) => struct_fields_named_mappings(fields_named),
        _ => panic!("Structs with unnamed fields are not supported"),
    }
}

fn struct_fields_named_mappings(fields_named: FieldsNamed) -> impl ToTokens {
    let mappings = fields_named.named.into_pairs().map(|pair| match pair {
        Pair::Punctuated(field, _) => {
            let name = field.ident;
            quote! { #name: s.#name.into(), }
        }
        _ => panic!("Encountered a struct field that wasn't expected"),
    });
    combine_tokens(mappings)
}

fn combine_tokens<T: ToTokens, I: IntoIterator<Item = T>>(token_streams: I) -> impl ToTokens {
    let mut tokens = quote! {};
    tokens.append_all(token_streams);
    tokens
}