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
#![feature(proc_macro, proc_macro_lib)]
#![recursion_limit="150"]

#[macro_use]
extern crate log;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate syn;

use proc_macro::TokenStream;
use std::collections::BTreeMap;

#[proc_macro_derive(TelegramFunction)]
pub fn derive_TelegramFunction(input: TokenStream) -> TokenStream {
    let ast = syn::parse_macro_input(&input.to_string()).unwrap();
    let expanded = expand(ast);
    expanded.to_string().parse().unwrap()
}

fn expand(mut ast: syn::MacroInput) -> quote::Tokens {
    let config = config_from(&ast.attrs);

    let function = config.get("function").unwrap();
    let function = syn::Lit::Str((*function).clone(), syn::StrStyle::Cooked);
    let bot_function = syn::Ident::from(config.get("bot_function").unwrap().as_str());
    let answer = syn::Ident::from(config.get("answer").unwrap().as_str());

    let fields: Vec<_> = match ast.body {
        syn::Body::Struct(syn::VariantData::Struct(ref fields)) => {
            fields.iter().map(|f| (f.ident.as_ref().unwrap(), &f.ty)).collect()
        },
        syn::Body::Struct(syn::VariantData::Unit) => {
            vec![]
        },
        _ => panic!("#[derive(getters)] can only be used with braced structs"),
    };

    
    /*for field in &fields {
        println!("{:?}", field.1);
    }*/
    
    let name = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics
        .split_for_impl();
    //let getter: Vec<_> = fields.iter().map(|f| f.0).collect();
    
    let is_option_ident = |ref f: &(&syn::Ident, &syn::Ty)| -> bool {
        match *f.1 {
            syn::Ty::Path(_, ref path) => {
                match path.segments.first().unwrap().ident.as_ref() {
                    "Option" => true,
                    _ => false
                }
            },
            _ => false
        }
    };

    let field_compulsory: Vec<_> = fields.iter().filter(|f| !is_option_ident(&f))
    .map(|f| syn::Ident::from(format!("_{}", f.0.as_ref()))).collect();
    
    let field_optional: Vec<_> = fields.iter().filter(|f| is_option_ident(&f)).map(|f| f.0).collect();
    let field_optional2 = field_optional.clone();

    let field_compulsory2: Vec<_> = fields.iter().map(|f| f.0).collect();
    let field_compulsory3 = field_compulsory.clone();
    let values: Vec<_> = fields.iter().map(|f| {
        match *f.1 {
            syn::Ty::Path(_, ref path) => {
                match path.segments.first().unwrap().ident.as_ref() {
                    "Option" => return syn::Ident::from("None"),
                    _ => return syn::Ident::from(format!("_{}", f.0.as_ref()))
                }
            },
            _ => return syn::Ident::from("None")
        }

        return "".into();
    }).collect();
    
    let ty_compulsory: Vec<_> = fields.iter().map(|f| f.1).collect();
    let ty_compulsory2 = ty_compulsory.clone();
    let ty_optional: Vec<_> = fields.iter().filter(|f| is_option_ident(&f)).map(|f| {
        if let syn::Ty::Path(_, ref path) = *f.1 {
            if let syn::PathParameters::AngleBracketed(ref param) = path.segments.first().unwrap().parameters {
                if let &syn::Ty::Path(_, ref path) = param.types.first().unwrap() {
                    return (*path).clone();
                }
            }
        }

        panic!("no sane type!");
    }).collect();

    //println!("{:?}", ty_optional.first());

    let trait_name = syn::Ident::from(format!("Function{}",  name.as_ref()));
    let wrapper_name = syn::Ident::from(format!("Wrapper{}", name.as_ref()));
    let bot_function_name = syn::Lit::Str(format!("{}", bot_function), syn::StrStyle::Cooked);

    quote! {
        pub struct #wrapper_name {
            bot: Rc<Bot>,
            inner: #name
        }

        
        impl #wrapper_name {
            pub fn send<'a>(self) -> impl Future<Item=(RcBot, objects::#answer), Error=Error> + 'a {
                let msg = serde_json::to_string(&self.inner).unwrap();
                self.bot.fetch_json(#function, &msg)
                    .map(move |x| (RcBot { inner: self.bot.clone() }, serde_json::from_str::<objects::#answer>(&x).unwrap()))
            }
           
            pub fn send_with<'b,T: io::Read + 'b>(self, file_name: &str, file: T) -> impl Future<Item=(RcBot, objects::#answer), Error=Error> + 'b{
                let msg = serde_json::to_value(&self.inner);
                self.bot.fetch_formdata(#function, msg, file, #bot_function_name, file_name)
                    .map(move |x| (RcBot { inner: self.bot.clone() }, serde_json::from_str::<objects::#answer>(&x).unwrap()))
            }
            
            #(
                pub fn #field_optional<S>(mut self, val: S) -> Self where S: Into<#ty_optional> {
                    self.inner.#field_optional2 = Some(val.into());

                    self
                }
            )*
        }

        pub trait #trait_name {
             fn #bot_function(&self, #( #field_compulsory: #ty_compulsory, )*) -> #wrapper_name;
        }

        impl #trait_name for RcBot{
            fn #bot_function(&self, #( #field_compulsory3: #ty_compulsory2, )*) -> #wrapper_name {
                #wrapper_name { inner: #name { #( #field_compulsory2: #values, )* }, bot: self.inner.clone() }
            }
        }
    }
}

fn config_from(attrs: &[syn::Attribute]) -> BTreeMap<String, String> {
    let mut result = BTreeMap::new();
    for attr in attrs {
        if let syn::MetaItem::NameValue(ref name, ref value) = attr.value {
            let name = format!("{}", name);
            let value = match value.clone() {
                syn::Lit::Str(value, _) => value,
                _ => panic!("bla")
            };
            result.insert(name, value);
        }
    }
    result
}