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
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{self, Data, Fields};
#[proc_macro_derive(Typemap)]
pub fn typemap_macro_derive(input: TokenStream) -> TokenStream {
let ast = syn::parse(input).unwrap();
impl_typemap_macro(&ast)
}
fn impl_typemap_macro(ast: &syn::DeriveInput) -> TokenStream {
let struct_data = if let Data::Struct(s) = &ast.data {
s
} else {
panic!("Typemap only applies to tuple struct, but used on a non-struct!")
};
let tuple_fields = if let Fields::Unnamed(f) = &struct_data.fields {
f
} else {
panic!("Typemap only applies to tuple struct, but used on a non-tuple struct!")
};
let types = tuple_fields.unnamed.iter().map(|e| e.ty.to_token_stream());
let indices = (0..types.len()).map(syn::Index::from);
let name = &ast.ident;
let generics = &ast.generics;
let gen = quote! {
#(impl #generics Get<#types> for #name #generics {
fn get(&self) -> &#types {
&self.#indices
}
})*
};
gen.into()
}