aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/pybind/method.h
blob: 7c1f6e90e1bc5d4ddea097336c0ddee06f63cef5 (plain) (blame)
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#pragma once

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <util/generic/string.h>
#include <util/generic/map.h>
#include <util/generic/set.h>
#include <util/generic/vector.h>
#include <util/generic/ptr.h>
#include <util/generic/typetraits.h>

#include <util/generic/function.h>

#include "cast.h"

namespace NPyBind {
    template <typename TObjType>
    class TBaseMethodCaller {
    public:
        virtual ~TBaseMethodCaller() {
        }
        virtual bool CallMethod(PyObject* owner, TObjType* self, PyObject* args, PyObject* kwargs, PyObject*& res) const = 0;
        virtual bool HasMethod(PyObject*, TObjType*, const TString&, const TSet<TString>&) {
            return true;
        }
    };

    template <typename TObjType>
    class TIsACaller;

    template <typename TObjType>
    class TMethodCallers {
    private:
        typedef TSimpleSharedPtr<TBaseMethodCaller<TObjType>> TCallerPtr;
        typedef TVector<TCallerPtr> TCallerList;
        typedef TMap<TString, TCallerList> TCallerMap;

        const TSet<TString>& HiddenAttrNames;
        TCallerMap Callers;

    public:
        TMethodCallers(const TSet<TString>& hiddenNames)
            : HiddenAttrNames(hiddenNames)
        {
        }

        void AddCaller(const TString& name, TCallerPtr caller) {
            Callers[name].push_back(caller);
        }

        bool HasCaller(const TString& name) const {
            return Callers.has(name);
        }

        PyObject* CallMethod(PyObject* owner, TObjType* self, PyObject* args, PyObject* kwargs, const TString& name) const {
            const TCallerList* lst = Callers.FindPtr(name);
            if (!lst)
                return nullptr;
            for (const auto& caller : *lst) {
                PyObject* res = nullptr;
                PyErr_Clear();
                if (caller->CallMethod(owner, self, args, kwargs, res))
                    return res;
            }
            return nullptr;
        }

        bool HasMethod(PyObject* owner, TObjType* self, const TString& name) const {
            const TCallerList* lst = Callers.FindPtr(name);
            if (!lst)
                return false;
            for (const auto& caller : *lst) {
                if (caller->HasMethod(owner, self, name, HiddenAttrNames))
                    return true;
            }
            return false;
        }

        void GetMethodsNames(PyObject* owner, TObjType* self, TVector<TString>& resultNames) const {
            for (const auto& it : Callers) {
                if (HasMethod(owner, self, it.first) && !HiddenAttrNames.contains(it.first))
                    resultNames.push_back(it.first);
            }
        }

        void GetAllMethodsNames(TVector<TString>& resultNames) const {
            for (const auto& it : Callers) {
                resultNames.push_back(it.first);
            }
        }

        void GetPropertiesNames(PyObject*, TObjType* self, TVector<TString>& resultNames) const {
            const TCallerList* lst = Callers.FindPtr("IsA");
            if (!lst)
                return;
            for (const auto& caller : *lst) {
                TIsACaller<TObjType>* isACaller = dynamic_cast<TIsACaller<TObjType>*>(caller.Get());
                if (isACaller) {
                    resultNames = isACaller->GetPropertiesNames(self);
                    return;
                }
            }
        }
    };

    template <typename TObjType>
    class TIsACaller: public TBaseMethodCaller<TObjType> {
    private:
        class TIsAChecker {
        public:
            virtual ~TIsAChecker() {
            }
            virtual bool Check(const TObjType* obj) const = 0;
        };

        template <typename TConcrete>
        class TIsAConcreteChecker: public TIsAChecker {
        public:
            bool Check(const TObjType* obj) const override {
                return dynamic_cast<const TConcrete*>(obj) != nullptr;
            }
        };

        typedef TSimpleSharedPtr<TIsAChecker> TCheckerPtr;
        typedef TMap<TString, TCheckerPtr> TCheckersMap;

        TCheckersMap Checkers;

        bool Check(const TString& name, const TObjType* obj) const {
            const TCheckerPtr* checker = Checkers.FindPtr(name);
            if (!checker) {
                PyErr_Format(PyExc_KeyError, "unknown class name: %s", name.data());
                return false;
            }
            return (*checker)->Check(obj);
        }

    protected:
        TIsACaller() {
        }

        template <typename TConcrete>
        void AddChecker(const TString& name) {
            Checkers[name] = new TIsAConcreteChecker<TConcrete>;
        }

    public:
        bool CallMethod(PyObject*, TObjType* self, PyObject* args, PyObject*, PyObject*& res) const override {
            if (args == nullptr || !PyTuple_Check(args))
                return false;
            size_t cnt = PyTuple_Size(args);
            bool result = true;
            for (size_t i = 0; i < cnt; ++i) {
                result = result && Check(
#if PY_MAJOR_VERSION >= 3
                        PyUnicode_AsUTF8(
#else
                        PyString_AsString(
#endif
                            PyTuple_GetItem(args, i)), self);
            }
            if (PyErr_Occurred()) {
                return false;
            }
            res = BuildPyObject(result);
            return true;
        }

        TVector<TString> GetPropertiesNames(const TObjType* obj) const {
            TVector<TString> names;

            for (const auto& it : Checkers) {
                if (it.second->Check(obj)) {
                    names.push_back(it.first);
                }
            }

            return names;
        }
    };

    template <typename TObjType>
    class TGenericMethodCaller: public TBaseMethodCaller<TObjType> {
    private:
        TString AttrName;

    public:
        TGenericMethodCaller(const TString& attrName)
            : AttrName(attrName)
        {
        }

        bool CallMethod(PyObject* obj, TObjType*, PyObject* args, PyObject*, PyObject*& res) const override {
            auto str = NameFromString(AttrName);
            PyObject* attr = PyObject_GenericGetAttr(obj, str.Get());
            if (!attr)
                ythrow yexception() << "Can't get generic attribute '" << AttrName << "'";
            res = PyObject_CallObject(attr, args);
            return res != nullptr;
        }
    };


    template <typename TObjType, typename TSubObject>
    class TSubObjectChecker: public TBaseMethodCaller<TObjType> {
    public:
        ~TSubObjectChecker() override {
        }

        bool HasMethod(PyObject*, TObjType* self, const TString&, const TSet<TString>&) override {
            return dynamic_cast<const TSubObject*>(self) != nullptr;
        }
    };

    template <typename TFunctor, typename Tuple, typename ResType, typename=std::enable_if_t<!std::is_same_v<ResType, void>>>
    void ApplyFunctor(TFunctor functor, Tuple resultArgs, PyObject*& res) {
        res = BuildPyObject(std::move(Apply(functor, resultArgs)));
    }

    template <typename TFunctor, typename Tuple, typename ResType, typename=std::enable_if_t<std::is_same_v<ResType, void>>, typename=void>
    void ApplyFunctor(TFunctor functor, Tuple resultArgs, PyObject*& res) {
        Py_INCREF(Py_None);
        res = Py_None;
        Apply(functor, resultArgs);
    }

    template <typename TObjType, typename TResType, typename... Args>
    class TFunctorCaller: public TBaseMethodCaller<TObjType> {
        using TFunctor = std::function<TResType(TObjType&,Args...)>;
        TFunctor Functor;
    public:
        explicit TFunctorCaller(TFunctor functor):
            Functor(functor){}

        bool CallMethod(PyObject*, TObjType* self, PyObject* args, PyObject*, PyObject*& res) const {
            auto methodArgsTuple = GetArguments<Args...>(args);
            auto resultArgs = std::tuple_cat(std::tie(*self), methodArgsTuple);
            ApplyFunctor<TFunctor, decltype(resultArgs), TResType>(Functor, resultArgs, res);
            return true;
        }
    };

    template <typename TObjType, typename TRealType>
    class TGetStateCaller: public TSubObjectChecker<TObjType, TRealType> {
    protected:
        TPyObjectPtr AddFromCaller(PyObject* obj, const TString& methodName) const {
            PyObject* res = PyObject_CallMethod(obj, const_cast<char*>(methodName.c_str()), const_cast<char*>(""));
            if (!res) {
                PyErr_Clear();
                return TPyObjectPtr(Py_None);
            }
            return TPyObjectPtr(res, true);
        }

        void GetStandartAttrsDictionary(PyObject* obj, TRealType*, TMap<TString, TPyObjectPtr>& dict) const {
            TPyObjectPtr attrsDict(PyObject_GetAttrString(obj, "__dict__"), true);
            TMap<TString, TPyObjectPtr> attrs;
            if (!FromPyObject(attrsDict.Get(), attrs))
                ythrow yexception() << "Can't get '__dict__' attribute";
            dict.insert(attrs.begin(), attrs.end());
        }

        virtual void GetAttrsDictionary(PyObject* obj, TRealType* self, TMap<TString, TPyObjectPtr>& dict) const = 0;

    public:
        bool CallMethod(PyObject* obj, TObjType* self, PyObject* args, PyObject*, PyObject*& res) const override {
            if (!ExtractArgs(args))
                ythrow yexception() << "Can't parse arguments: it should be none";
            TRealType* rself = dynamic_cast<TRealType*>(self);
            if (!rself)
                return false;
            TMap<TString, TPyObjectPtr> dict;
            GetAttrsDictionary(obj, rself, dict);
            res = BuildPyObject(dict);
            return true;
        }
    };

    template <typename TObjType, typename TRealType>
    class TSetStateCaller: public TSubObjectChecker<TObjType, TRealType> {
    protected:
        void SetStandartAttrsDictionary(PyObject* obj, TRealType*, TMap<TString, TPyObjectPtr>& dict) const {
            TPyObjectPtr value(BuildPyObject(dict), true);
            PyObject_SetAttrString(obj, "__dict__", value.Get());
        }

        virtual void SetAttrsDictionary(PyObject* obj, TRealType* self, TMap<TString, TPyObjectPtr>& dict) const = 0;

    public:
        bool CallMethod(PyObject* obj, TObjType* self, PyObject* args, PyObject*, PyObject*& res) const override {
            TMap<TString, TPyObjectPtr> dict;
            if (!ExtractArgs(args, dict))
                ythrow yexception() << "Can't parse arguments: it should be one dictionary";
            TRealType* rself = dynamic_cast<TRealType*>(self);
            if (!rself)
                return false;
            SetAttrsDictionary(obj, rself, dict);
            Py_INCREF(Py_None);
            res = Py_None;
            return true;
        }
    };

    template <typename TObjType, typename TResult, typename TSubObject, typename TMethod, typename... Args>
    class TAnyParameterMethodCaller: public TSubObjectChecker<TObjType, TSubObject> {
    private:
        TMethod Method;

    public:
        TAnyParameterMethodCaller(TMethod method)
            : Method(method)
        {
        }

    public:
        bool CallMethod(PyObject*, TObjType* self, PyObject* args, PyObject*, PyObject*& res) const override {
            TSubObject* sub = dynamic_cast<TSubObject*>(self);
            if (sub == nullptr)
                return false;
            if (args && (!PyTuple_Check(args) || PyTuple_Size(args) != TFunctionArgs<TMethod>::Length)) {
                //ythrow yexception() << "Method takes " << (size_t)(TFunctionArgs<TMethod>::Length) << " arguments, " << PyTuple_Size(args) << " provided";
                return false;
            }

            try {
                class Applicant {
                public:
                    TResult operator()(Args... theArgs) {
                        return (Sub->*Method)(theArgs...);
                    }
                    TSubObject* Sub;
                    TMethod Method;
                };
                res = BuildPyObject(std::move(Apply(Applicant{sub, Method}, GetArguments<Args...>(args))));
            } catch (cast_exception) {
                return false;
            } catch (...) {
                if (PyExc_StopIteration == PyErr_Occurred()) {
                    // NB: it's replacement for geo_boost::python::throw_error_already_set();
                    return true;
                }
                PyErr_SetString(PyExc_RuntimeError, CurrentExceptionMessage().data());
                return true;
            }

            return true;
        }
    };

    template <typename TObjType, typename TSubObject, typename TMethod, typename... Args>
    class TAnyParameterMethodCaller<TObjType, void, TSubObject, TMethod, Args...>: public TSubObjectChecker<TObjType, TSubObject> {
    private:
        TMethod Method;

    public:
        TAnyParameterMethodCaller(TMethod method)
            : Method(method)
        {
        }

    public:
        bool CallMethod(PyObject*, TObjType* self, PyObject* args, PyObject*, PyObject*& res) const override {
            TSubObject* sub = dynamic_cast<TSubObject*>(self);
            if (sub == nullptr) {
                return false;
            }
            if (args && (!PyTuple_Check(args) || PyTuple_Size(args) != TFunctionArgs<TMethod>::Length)) {
                return false;
            }

            try {
                class Applicant {
                public:
                    void operator()(Args... theArgs) {
                        (Sub->*Method)(theArgs...);
                    }
                    TSubObject* Sub;
                    TMethod Method;
                };

                Apply(Applicant{sub, Method}, GetArguments<Args...>(args));

                Py_INCREF(Py_None);
                res = Py_None;
            } catch (cast_exception) {
                return false;
            } catch (...) {
                PyErr_SetString(PyExc_RuntimeError, CurrentExceptionMessage().data());
                return true;
            }

            return true;
        }
    };

    template <typename TResult, typename TSubObject, typename... Args>
    struct TConstTraits {
        typedef TResult (TSubObject::*TMethod)(Args... args) const;
    };

    template <typename TResult, typename TSubObject, typename... Args>
    struct TNonConstTraits {
        typedef TResult (TSubObject::*TMethod)(Args... args);
    };

    template <typename TObjType, typename TResult, typename TSubObject, typename TMethod, typename... Args>
    class TConstMethodCaller: public TAnyParameterMethodCaller<TObjType, TResult, const TSubObject, typename TConstTraits<TResult, TSubObject, Args...>::TMethod, Args...> {
    public:
        TConstMethodCaller(typename TConstTraits<TResult, TSubObject, Args...>::TMethod method)
            : TAnyParameterMethodCaller<TObjType, TResult, const TSubObject, typename TConstTraits<TResult, TSubObject, Args...>::TMethod, Args...>(method)
        {
        }
    };

    template <typename TObjType, typename TResult, typename TSubObject, typename... Args>
    TSimpleSharedPtr<TBaseMethodCaller<TObjType>> CreateConstMethodCaller(TResult (TSubObject::*method)(Args...) const) {
        return new TConstMethodCaller<TObjType, TResult, TSubObject, TResult (TSubObject::*)(Args...) const, Args...>(method);
    }

    template <typename TObjType, typename TResType, typename... Args>
    TSimpleSharedPtr<TBaseMethodCaller<TObjType>> CreateFunctorCaller(std::function<TResType(TObjType&, Args...)> functor) {
        return new TFunctorCaller<TObjType, TResType, Args...>(functor);
    }

    template <typename TObjType, typename TResult, typename TSubObject, typename TMethod, typename... Args>
    class TMethodCaller: public TAnyParameterMethodCaller<TObjType, TResult, TSubObject, typename TNonConstTraits<TResult, TSubObject, Args...>::TMethod, Args...> {
    public:
        TMethodCaller(typename TNonConstTraits<TResult, TSubObject, Args...>::TMethod method)
            : TAnyParameterMethodCaller<TObjType, TResult, TSubObject, typename TNonConstTraits<TResult, TSubObject, Args...>::TMethod, Args...>(method)
        {
        }
    };

    template <typename TObjType, typename TResult, typename TSubObject, typename... Args>
    TSimpleSharedPtr<TBaseMethodCaller<TObjType>> CreateMethodCaller(TResult (TSubObject::*method)(Args...)) {
        return new TMethodCaller<TObjType, TResult, TSubObject, TResult (TSubObject::*)(Args...), Args...>(method);
    }

}