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
// Copyright (c) 2017-present PyO3 Project and Contributors

use syn;

use args::{parse_arguments, Argument};
use proc_macro2::TokenStream;
use quote::ToTokens;

#[derive(Clone, PartialEq, Debug)]
pub struct FnArg<'a> {
    pub name: &'a syn::Ident,
    pub by_ref: &'a Option<syn::token::Ref>,
    pub mutability: &'a Option<syn::token::Mut>,
    pub ty: &'a syn::Type,
    pub optional: Option<&'a syn::Type>,
    pub py: bool,
    pub reference: bool,
}

#[derive(Clone, PartialEq, Debug)]
pub enum FnType {
    Getter(Option<String>),
    Setter(Option<String>),
    Fn,
    FnNew,
    FnInit,
    FnCall,
    FnClass,
    FnStatic,
}

#[derive(Clone, PartialEq, Debug)]
pub struct FnSpec<'a> {
    pub tp: FnType,
    pub attrs: Vec<Argument>,
    pub args: Vec<FnArg<'a>>,
    pub output: syn::Type,
}

pub fn get_return_info(output: &syn::ReturnType) -> syn::Type {
    match output {
        syn::ReturnType::Default => syn::Type::Infer(parse_quote!{_}),
        syn::ReturnType::Type(_, ref ty) => *ty.clone(),
    }
}

impl<'a> FnSpec<'a> {
    /// Parser function signature and function attributes
    pub fn parse(
        name: &'a syn::Ident,
        sig: &'a syn::MethodSig,
        meth_attrs: &'a mut Vec<syn::Attribute>,
    ) -> FnSpec<'a> {
        let (fn_type, fn_attrs) = parse_attributes(meth_attrs);

        let mut has_self = false;
        let mut arguments = Vec::new();

        for input in sig.decl.inputs.iter() {
            match input {
                &syn::FnArg::SelfRef(_) => {
                    has_self = true;
                }
                &syn::FnArg::SelfValue(_) => {
                    has_self = true;
                }
                &syn::FnArg::Captured(syn::ArgCaptured {
                    ref pat, ref ty, ..
                }) => {
                    // skip first argument (cls)
                    if (fn_type == FnType::FnClass || fn_type == FnType::FnNew) && !has_self {
                        has_self = true;
                        continue;
                    }

                    let (ident, by_ref, mutability) = match pat {
                        &syn::Pat::Ident(syn::PatIdent {
                            ref ident,
                            ref by_ref,
                            ref mutability,
                            ..
                        }) => (ident, by_ref, mutability),
                        _ => panic!("unsupported argument: {:?}", pat),
                    };

                    let py = match ty {
                        &syn::Type::Path(syn::TypePath { ref path, .. }) => {
                            if let Some(segment) = path.segments.last() {
                                segment.value().ident == "Python"
                            } else {
                                false
                            }
                        }
                        _ => false,
                    };

                    let opt = check_arg_ty_and_optional(name, ty);
                    arguments.push(FnArg {
                        name: ident,
                        by_ref,
                        mutability,
                        // mode: mode,
                        ty: ty,
                        optional: opt,
                        py: py,
                        reference: is_ref(name, ty),
                    });
                }
                &syn::FnArg::Ignored(_) => panic!("ignored argument: {:?}", name),
                &syn::FnArg::Inferred(_) => panic!("ingerred argument: {:?}", name),
            }
        }

        let ty = get_return_info(&sig.decl.output);

        FnSpec {
            tp: fn_type,
            attrs: fn_attrs,
            args: arguments,
            output: ty,
        }
    }

    pub fn is_args(&self, name: &syn::Ident) -> bool {
        for s in self.attrs.iter() {
            match *s {
                Argument::VarArgs(ref ident) => return name == ident,
                _ => (),
            }
        }
        false
    }

    pub fn accept_args(&self) -> bool {
        for s in self.attrs.iter() {
            match *s {
                Argument::VarArgs(_) => return true,
                Argument::VarArgsSeparator => return true,
                _ => (),
            }
        }
        false
    }

    pub fn is_kwargs(&self, name: &syn::Ident) -> bool {
        for s in self.attrs.iter() {
            match *s {
                Argument::KeywordArgs(ref ident) => return name == ident,
                _ => (),
            }
        }
        false
    }

    pub fn accept_kwargs(&self) -> bool {
        for s in self.attrs.iter() {
            match *s {
                Argument::KeywordArgs(_) => return true,
                _ => (),
            }
        }
        false
    }

    pub fn default_value(&self, name: &syn::Ident) -> Option<TokenStream> {
        for s in self.attrs.iter() {
            match *s {
                Argument::Arg(ref ident, ref opt) => {
                    if ident == name {
                        if let &Some(ref val) = opt {
                            let i: syn::Expr = syn::parse_str(&val).unwrap();
                            return Some(i.into_token_stream());
                        }
                    }
                }
                Argument::Kwarg(ref ident, ref opt) => {
                    if ident == name {
                        let i: syn::Expr = syn::parse_str(&opt).unwrap();
                        return Some(quote!(#i));
                    }
                }
                _ => (),
            }
        }
        None
    }

    pub fn is_kw_only(&self, name: &syn::Ident) -> bool {
        for s in self.attrs.iter() {
            match *s {
                Argument::Kwarg(ref ident, _) => {
                    if ident == name {
                        return true;
                    }
                }
                _ => (),
            }
        }
        false
    }
}

pub fn is_ref<'a>(name: &'a syn::Ident, ty: &'a syn::Type) -> bool {
    match ty {
        &syn::Type::Reference(_) => return true,
        &syn::Type::Path(syn::TypePath { ref path, .. }) => {
            if let Some(segment) = path.segments.last() {
                match segment.value().ident.to_string().as_str() {
                    "Option" => match segment.value().arguments {
                        syn::PathArguments::AngleBracketed(ref params) => {
                            if params.args.len() != 1 {
                                panic!("argument type is not supported by python method: {:?} ({:?}) {:?}",
                                           name,
                                           ty,
                                           path);
                            }
                            match &params.args[params.args.len() - 1] {
                                &syn::GenericArgument::Type(syn::Type::Reference(_)) => return true,
                                _ => (),
                            }
                        }
                        _ => {
                            panic!(
                                "argument type is not supported by python method: {:?} ({:?}) {:?}",
                                name, ty, path
                            );
                        }
                    },
                    _ => (),
                }
            }
        }
        _ => (),
    }
    false
}

pub fn check_arg_ty_and_optional<'a>(
    name: &'a syn::Ident,
    ty: &'a syn::Type,
) -> Option<&'a syn::Type> {
    match ty {
        &syn::Type::Path(syn::TypePath { ref path, .. }) => {
            //if let &Some(ref qs) = qs {
            //    panic!("explicit Self type in a 'qualified path' is not supported: {:?} - {:?}",
            //           name, qs);
            //}

            if let Some(segment) = path.segments.last() {
                match segment.value().ident.to_string().as_str() {
                    "Option" => match segment.value().arguments {
                        syn::PathArguments::AngleBracketed(ref params) => {
                            if params.args.len() != 1 {
                                panic!("argument type is not supported by python method: {:?} ({:?}) {:?}",
                                           name,
                                           ty,
                                           path);
                            }

                            match &params.args[0] {
                                    &syn::GenericArgument::Type(ref ty) => Some(ty),
                                    _ => panic!("argument type is not supported by python method: {:?} ({:?}) {:?}",
                                                    name,
                                                    ty,
                                                    path),
                                }
                        }
                        _ => {
                            panic!(
                                "argument type is not supported by python method: {:?} ({:?}) {:?}",
                                name, ty, path
                            );
                        }
                    },
                    _ => None,
                }
            } else {
                None
            }
        }
        _ => {
            None
            //panic!("argument type is not supported by python method: {:?} ({:?})",
            //name,
            //ty);
        }
    }
}

fn parse_attributes(attrs: &mut Vec<syn::Attribute>) -> (FnType, Vec<Argument>) {
    let mut new_attrs = Vec::new();
    let mut spec = Vec::new();
    let mut res: Option<FnType> = None;

    for attr in attrs.iter() {
        match attr.interpret_meta().unwrap() {
            syn::Meta::Word(ref name) => match name.to_string().as_ref() {
                "new" | "__new__" => res = Some(FnType::FnNew),
                "init" | "__init__" => res = Some(FnType::FnInit),
                "call" | "__call__" => res = Some(FnType::FnCall),
                "classmethod" => res = Some(FnType::FnClass),
                "staticmethod" => res = Some(FnType::FnStatic),
                "setter" | "getter" => {
                    if let syn::AttrStyle::Inner(_) = attr.style {
                        panic!(
                            "Inner style attribute is not
                                    supported for setter and getter"
                        );
                    }
                    if res != None {
                        panic!("setter/getter attribute can not be used mutiple times");
                    }
                    if name == "setter" {
                        res = Some(FnType::Setter(None))
                    } else {
                        res = Some(FnType::Getter(None))
                    }
                }
                _ => new_attrs.push(attr.clone()),
            },
            syn::Meta::List(syn::MetaList {
                ref ident,
                ref nested,
                ..
            }) => match ident.to_string().as_str() {
                "new" => res = Some(FnType::FnNew),
                "init" => res = Some(FnType::FnInit),
                "call" => res = Some(FnType::FnCall),
                "setter" | "getter" => {
                    if let syn::AttrStyle::Inner(_) = attr.style {
                        panic!(
                            "Inner style attribute is not
                                    supported for setter and getter"
                        );
                    }
                    if res != None {
                        panic!("setter/getter attribute can not be used mutiple times");
                    }
                    if nested.len() != 1 {
                        panic!("setter/getter requires one value");
                    }
                    match nested.first().unwrap().value() {
                        syn::NestedMeta::Meta(syn::Meta::Word(ref w)) => {
                            if ident == "setter" {
                                res = Some(FnType::Setter(Some(w.to_string())))
                            } else {
                                res = Some(FnType::Getter(Some(w.to_string())))
                            }
                        }
                        syn::NestedMeta::Literal(ref lit) => match *lit {
                            syn::Lit::Str(ref s) => {
                                if ident == "setter" {
                                    res = Some(FnType::Setter(Some(s.value())))
                                } else {
                                    res = Some(FnType::Getter(Some(s.value())))
                                }
                            }
                            _ => {
                                panic!("setter/getter attribute requires str value");
                            }
                        },
                        _ => {
                            println!("cannot parse {:?} attribute: {:?}", ident, nested);
                        }
                    }
                }
                "args" => {
                    let args = nested.iter().cloned().collect::<Vec<_>>();
                    spec.extend(parse_arguments(args.as_slice()))
                }
                _ => new_attrs.push(attr.clone()),
            },
            syn::Meta::NameValue(_) => new_attrs.push(attr.clone()),
        }
    }
    attrs.clear();
    attrs.extend(new_attrs);

    match res {
        Some(tp) => (tp, spec),
        None => (FnType::Fn, spec),
    }
}