aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/pybind/attr.h
blob: 5f25a6d73d15ecaf11dcfc0c27824596d7e7ca64 (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
#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 "cast.h"
#include "exceptions.h"

namespace NPyBind {
    // TBaseAttrGetter
    template <typename TObjType>
    class TBaseAttrGetter {
    public:
        virtual ~TBaseAttrGetter() {
        }
        virtual bool GetAttr(PyObject* owner, const TObjType& self, const TString& attr, PyObject*& res) const = 0;

        virtual bool HasAttr(PyObject* owner, const TObjType& self, const TString& attr, const TSet<TString>& hiddenNames) const {
            if (hiddenNames.find(attr) != hiddenNames.end())
                return false;
            PyObject* res = nullptr;
            if (!GetAttr(owner, self, attr, res))
                return false;
            Py_XDECREF(res);
            return true;
        }
    };

    template <typename TObjType>
    class TBaseAttrSetter {
    public:
        virtual ~TBaseAttrSetter() {
        }

        virtual bool SetAttr(PyObject* owner, TObjType& self, const TString& attr, PyObject* val) = 0;
    };

    template <typename TObjType>
    class TAttrGetters {
    public:
        typedef TSimpleSharedPtr<TBaseAttrGetter<TObjType>> TGetterPtr;

    private:
        typedef TVector<TGetterPtr> TGetterList;
        typedef TMap<TString, TGetterList> TGetterMap;

        const TSet<TString>& HiddenAttrNames;
        TGetterMap Getters;

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

        void AddGetter(const TString& attr, TGetterPtr getter) {
            Getters[attr].push_back(getter);
        }

        PyObject* GetAttr(PyObject* owner, const TObjType& self, const TString& attr) const {
            typename TGetterMap::const_iterator it1 = Getters.find(attr);
            if (it1 == Getters.end())
                it1 = Getters.find("");
            if (it1 == Getters.end())
                return nullptr;
            const TGetterList& lst = it1->second;
            for (typename TGetterList::const_iterator it2 = lst.begin(), end = lst.end(); it2 != end; ++it2) {
                PyObject* res = nullptr;
                if ((*it2)->GetAttr(owner, self, attr, res))
                    return res;
                // IMPORTANT!
                // we have to fail GetAttr right there  because we've failed because of internal python error/exception and can't continue iterating because
                // it cause subsequent exceptions during call to Py_BuildValue
                // moreover we have to preserve original exception right there
                if (PyErr_Occurred()) {
                    break;
                }
            }
            return nullptr;
        }

        bool HasAttr(PyObject* owner, const TObjType& self, const TString& attr) const {
            typename TGetterMap::const_iterator it1 = Getters.find(attr);
            if (it1 == Getters.end())
                return false;
            const TGetterList& lst = it1->second;
            for (typename TGetterList::const_iterator it2 = lst.begin(), end = lst.end(); it2 != end; ++it2) {
                if ((*it2)->HasAttr(owner, self, attr, HiddenAttrNames))
                    return true;
            }
            return false;
        }

        void GetAttrsDictionary(PyObject* owner, const TObjType& self, TMap<TString, PyObject*>& res) const {
            for (typename TGetterMap::const_iterator it = Getters.begin(), end = Getters.end(); it != end; ++it) {
                try {
                    if (HasAttr(owner, self, it->first)) {
                        auto attrPtr = GetAttr(owner, self, it->first);
                        if (attrPtr) {
                            res[it->first] = attrPtr;
                        }
                        if (PyErr_Occurred()) {
                            PyErr_Clear(); // Skip python errors as well
                        }
                    }
                } catch (const std::exception&) {
                    // ignore this field
                }
            }
        }

        void GetAttrsNames(PyObject* owner, const TObjType& self, TVector<TString>& resultNames) const {
            for (typename TGetterMap::const_iterator it = Getters.begin(), end = Getters.end(); it != end; ++it) {
                if (HasAttr(owner, self, it->first))
                    resultNames.push_back(it->first);
            }
        }
    };

    template <typename TObjType>
    class TGenericAttrGetter: public TBaseAttrGetter<TObjType> {
    private:
        TString AttrName;

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

        bool GetAttr(PyObject* obj, const TObjType&, const TString&, PyObject*& res) const override {
            auto str = NameFromString(AttrName);
            res = PyObject_GenericGetAttr(obj, str.Get());
            if (!res && !PyErr_Occurred())
                ythrow TPyErr(PyExc_AttributeError) << "Can't get generic attribute '" << AttrName << "'";
            return res;
        }
    };

    template <typename TObjType>
    class TAttrSetters {
    private:
        typedef TSimpleSharedPtr<TBaseAttrSetter<TObjType>> TSetterPtr;
        typedef TVector<TSetterPtr> TSetterList;
        typedef TMap<TString, TSetterList> TSetterMap;

        TSetterMap Setters;

    public:
        void AddSetter(const TString& attr, TSetterPtr setter) {
            Setters[attr].push_back(setter);
        }

        bool SetAttr(PyObject* owner, TObjType& self, const TString& attr, PyObject* val) {
            typename TSetterMap::const_iterator it1 = Setters.find(attr);
            if (it1 == Setters.end())
                it1 = Setters.find("");
            if (it1 == Setters.end())
                return false;
            const TSetterList& lst = it1->second;
            for (typename TSetterList::const_iterator it2 = lst.begin(), end = lst.end(); it2 != end; ++it2) {
                if ((*it2)->SetAttr(owner, self, attr, val))
                    return true;
            }
            return false;
        }

        bool SetAttrDictionary(PyObject* owner, TObjType& self, TMap<TString, PyObject*>& dict) {
            for (TMap<TString, PyObject*>::const_iterator it = dict.begin(), end = dict.end(); it != end; ++it) {
                try {
                    SetAttr(owner, self, it->first, it->second);
                } catch (std::exception&) {
                    // ignore this field
                }
            }

            return true;
        }
    };

    /**
      * TMethodAttrGetter - this class maps Python attribute read to C++ method call
      */
    template <typename TObjType, typename TResult, typename TSubObject>
    class TMethodAttrGetter: public TBaseAttrGetter<TObjType> {
    private:
        typedef TResult (TSubObject::*TMethod)() const;
        TMethod Method;

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

        bool GetAttr(PyObject*, const TObjType& self, const TString&, PyObject*& res) const override {
            const TSubObject* sub = dynamic_cast<const TSubObject*>(&self);
            if (sub == nullptr)
                return false;
            res = BuildPyObject((sub->*Method)());
            return (res != nullptr);
        }
    };

    template <typename TObjType, typename TFunctor>
    class TFunctorAttrGetter: public TBaseAttrGetter<TObjType> {
        TFunctor Functor;
    public:
        explicit TFunctorAttrGetter(TFunctor functor)
            : Functor(functor)
        {
        }

        bool GetAttr(PyObject*, const TObjType& self, const TString&, PyObject*& res) const override {
            res = BuildPyObject(Functor(self));
            return (res != nullptr);
        }
    };


    /**
      * TMethodAttrGetterWithCheck - this class maps Python attribute read to C++ HasAttr/GetAttr call
      *     If HasAttr returns false, None is returned.
      *     Otherwise GetAttr is called.
      */
    template <typename TObjType, typename TResult, typename TSubObject>
    class TMethodAttrGetterWithCheck: public TBaseAttrGetter<TObjType> {
    private:
        typedef TResult (TSubObject::*TMethod)() const;
        typedef bool (TSubObject::*TCheckerMethod)() const;
        TMethod Method;
        TCheckerMethod CheckerMethod;

    public:
        TMethodAttrGetterWithCheck(TMethod method, TCheckerMethod checkerMethod)
            : Method(method)
            , CheckerMethod(checkerMethod)
        {
        }

        bool GetAttr(PyObject*, const TObjType& self, const TString&, PyObject*& res) const override {
            const TSubObject* sub = dynamic_cast<const TSubObject*>(&self);
            if (sub == nullptr)
                return false;
            if ((sub->*CheckerMethod)())
                res = BuildPyObject((sub->*Method)());
            else {
                Py_INCREF(Py_None);
                res = Py_None;
            }
            return (res != nullptr);
        }
    };

    template <typename TObjType, typename TResult, typename TSubObject, typename TMapper>
    class TMethodAttrMappingGetter: public TBaseAttrGetter<TObjType> {
    private:
        typedef TResult (TSubObject::*TMethod)() const;

        TMethod Method;
        TMapper Mapper;

    public:
        TMethodAttrMappingGetter(TMethod method, TMapper mapper)
            : Method(method)
            , Mapper(mapper)
        {
        }

        bool GetAttr(PyObject*, const TObjType& self, const TString&, PyObject*& res) const override {
            const TSubObject* sub = dynamic_cast<const TSubObject*>(&self);
            if (sub == nullptr)
                return false;
            res = BuildPyObject(Mapper((sub->*Method)()));
            return (res != nullptr);
        }
    };

    template <typename TObjType, typename TResult, typename TSubObject, typename TMapper>
    TSimpleSharedPtr<TBaseAttrGetter<TObjType>>
    CreateMethodAttrMappingGetter(TResult (TSubObject::*method)() const,
                                  TMapper mapper) {
        return new TMethodAttrMappingGetter<TObjType, TResult, TSubObject, TMapper>(method,
                                                                                    mapper);
    }

    template <typename TObjType, typename TResult, typename TValue, typename TSubObject>
    class TMethodAttrSetter: public TBaseAttrSetter<TObjType> {
    private:
        typedef TResult (TSubObject::*TMethod)(TValue&);
        TMethod Method;

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

        virtual bool SetAttr(PyObject*, TObjType& self, const TString&, PyObject* val) {
            TSubObject* sub = dynamic_cast<TSubObject*>(&self);
            if (sub == nullptr)
                return false;
            TValue value;
            if (!FromPyObject(val, value))
                return false;
            (sub->*Method)(value);
            return true;
        }
    };

    template <typename TObjType, typename TValue, typename TFunctor>
    class TFunctorAttrSetter: public TBaseAttrSetter<TObjType> {
        TFunctor Functor;
    public:
        explicit TFunctorAttrSetter(TFunctor functor)
            : Functor(functor)
        {
        }

        bool SetAttr(PyObject*, TObjType& self, const TString&, PyObject* val) const override {
            TValue value;
            if (!FromPyObject(val, value))
                return false;
            auto res = BuildPyObject(Functor(self, value));
            return (res != nullptr);
        }
    };
    template <typename TObjType, typename TResult, typename TSubObject>
    TSimpleSharedPtr<TBaseAttrGetter<TObjType>> CreateMethodAttrGetter(TResult (TSubObject::*method)() const) {
        return new TMethodAttrGetter<TObjType, TResult, TSubObject>(method);
    }

    template <typename TObjType, typename TFunctor>
    TSimpleSharedPtr<TFunctorAttrGetter<TObjType, TFunctor>> CreateFunctorAttrGetter(TFunctor functor) {
        return MakeSimpleShared<TFunctorAttrGetter<TObjType, TFunctor>>(functor);
    }

    template <typename TObjType, typename TResult, typename TSubObject>
    TSimpleSharedPtr<TBaseAttrGetter<TObjType>> CreateMethodAttrGetterWithCheck(
        TResult (TSubObject::*method)() const,
        bool (TSubObject::*checkerMethod)() const) {
        return new TMethodAttrGetterWithCheck<TObjType, TResult, TSubObject>(method, checkerMethod);
    }

    template <typename TObjType, typename TResult, typename TValue, typename TSubObject>
    TSimpleSharedPtr<TBaseAttrSetter<TObjType>> CreateMethodAttrSetter(TResult (TSubObject::*method)(TValue&)) {
        return new TMethodAttrSetter<TObjType, TResult, TValue, TSubObject>(method);
    }

    template <typename TObjType, typename TFunctor, typename TValue>
    TSimpleSharedPtr<TFunctorAttrSetter<TObjType, TValue, TFunctor>> CreateFunctorAttrSetter(TFunctor functor) {
        return MakeSimpleShared<TFunctorAttrSetter<TObjType, TValue, TFunctor>>(functor);
    }

    template <typename TObjType, typename TValue, typename TSubObject>
    class TDirectAttrSetter: public TBaseAttrSetter<TObjType> {
    private:
        typedef TValue TSubObject::*TValueType;
        TValueType Value;

    public:
        TDirectAttrSetter(TValueType value)
            : Value(value)
        {
        }

        bool SetAttr(PyObject*, TObjType& self, const TString&, PyObject* val) override {
            TSubObject* sub = dynamic_cast<TSubObject*>(&self);
            if (sub == NULL)
                return false;
            if (!FromPyObject(val, sub->*Value))
                return false;
            return true;
        }
    };

    template <typename TObjType, typename TValue, typename TSubObject>
    TSimpleSharedPtr<TBaseAttrSetter<TObjType>> CreateAttrSetter(TValue TSubObject::*value) {
        return new TDirectAttrSetter<TObjType, TValue, TSubObject>(value);
    }

    template <typename TObjType, typename TValue, typename TSubObject>
    class TDirectAttrGetter: public TBaseAttrGetter<TObjType> {
    private:
        typedef TValue TSubObject::*TValueType;
        TValueType Value;

    public:
        TDirectAttrGetter(TValueType value)
            : Value(value)
        {
        }

        bool GetAttr(PyObject*, const TObjType& self, const TString&, PyObject*& res) const override {
            const TSubObject* sub = dynamic_cast<const TSubObject*>(&self);
            if (sub == nullptr)
                return false;
            res = BuildPyObject(sub->*Value);
            return (res != nullptr);
        }
    };

    template <typename TObjType, typename TValue, typename TSubObject>
    TSimpleSharedPtr<TBaseAttrGetter<TObjType>> CreateAttrGetter(TValue TSubObject::*value) {
        return new TDirectAttrGetter<TObjType, TValue, TSubObject>(value);
    }
}