megenginelite-sys 1.8.2

A safe megenginelite wrapper in Rust
Documentation
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/**
 * \file imperative/python/src/pyext17.h
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

#pragma once

#include <Python.h>
#include <pybind11/pybind11.h>
#include <exception>
#include <stdexcept>
#include <utility>
#include <vector>

namespace pyext17 {

#ifdef METH_FASTCALL
constexpr bool has_fastcall = true;
#else
constexpr bool has_fastcall = false;
#endif

#ifdef _Py_TPFLAGS_HAVE_VECTORCALL
constexpr bool has_vectorcall = true;
#else
constexpr bool has_vectorcall = false;
#endif

template <typename... Args>
struct invocable_with {
    template <typename T>
    constexpr bool operator()(T&& lmb) {
        return std::is_invocable_v<T, Args...>;
    }
};

#define HAS_MEMBER_TYPE(T, U) \
    invocable_with<T>{}([](auto&& x) -> typename std::decay_t<decltype(x)>::U {})
#define HAS_MEMBER(T, m) \
    invocable_with<T>{}([](auto&& x) -> decltype(&std::decay_t<decltype(x)>::m) {})

inline PyObject* cvt_retval(PyObject* rv) {
    return rv;
}

#define CVT_RET_PYOBJ(...)                                       \
    if constexpr (std::is_same_v<decltype(__VA_ARGS__), void>) { \
        __VA_ARGS__;                                             \
        Py_RETURN_NONE;                                          \
    } else {                                                     \
        return cvt_retval(__VA_ARGS__);                          \
    }

inline int cvt_retint(int ret) {
    return ret;
}

#define CVT_RET_INT(...)                                         \
    if constexpr (std::is_same_v<decltype(__VA_ARGS__), void>) { \
        __VA_ARGS__;                                             \
        return 0;                                                \
    } else {                                                     \
        return cvt_retint(__VA_ARGS__);                          \
    }

struct py_err_set : std::exception {};

// refer to pybind11 for the following exception handling helper

inline void pybind11_translate_exception(std::exception_ptr last_exception) {
    auto& registered_exception_translators =
            pybind11::detail::get_internals().registered_exception_translators;
    for (auto& translator : registered_exception_translators) {
        try {
            translator(last_exception);
        } catch (...) {
            last_exception = std::current_exception();
            continue;
        }
        return;
    }
    PyErr_SetString(
            PyExc_SystemError, "Exception escaped from default exception translator!");
}

inline void pybind11_translate_exception() {
    pybind11_translate_exception(std::current_exception());
}

#if defined(__GNUG__) && !defined(__clang__)
#define PYEXT17_TRANSLATE_EXC_CATCH_FORCED_UNWIND \
    catch (::abi::__forced_unwind&) {             \
        throw;                                    \
    }
#else
#define PYEXT17_TRANSLATE_EXC_CATCH_FORCED_UNWIND
#endif

#define PYEXT17_TRANSLATE_EXC                      \
    catch (::pyext17::py_err_set&) {               \
    }                                              \
    catch (::pybind11::error_already_set & e) {    \
        e.restore();                               \
    }                                              \
    PYEXT17_TRANSLATE_EXC_CATCH_FORCED_UNWIND      \
    catch (...) {                                  \
        ::pyext17::pybind11_translate_exception(); \
    }

#define PYEXT17_TRANSLATE_EXC_RET(RET)             \
    catch (::pyext17::py_err_set&) {               \
        return RET;                                \
    }                                              \
    catch (::pybind11::error_already_set & e) {    \
        e.restore();                               \
        return RET;                                \
    }                                              \
    PYEXT17_TRANSLATE_EXC_CATCH_FORCED_UNWIND      \
    catch (...) {                                  \
        ::pyext17::pybind11_translate_exception(); \
        return RET;                                \
    };

template <typename T>
struct wrap {
private:
    typedef wrap<T> wrap_t;

public:
    PyObject_HEAD std::aligned_storage_t<sizeof(T), alignof(T)> storage;
#ifdef _Py_TPFLAGS_HAVE_VECTORCALL
    PyObject* (*vectorcall_slot)(PyObject*, PyObject* const*, size_t, PyObject*);
#endif

    inline T* inst() { return reinterpret_cast<T*>(&storage); }

    inline static PyObject* pycast(T* ptr) {
        return (PyObject*)((char*)ptr - offsetof(wrap_t, storage));
    }

private:
    // method wrapper

    enum struct meth_type { noarg, varkw, fastcall, singarg };

    template <auto f>
    struct detect_meth_type {
        static constexpr meth_type value = []() {
            using F = decltype(f);
            static_assert(std::is_member_function_pointer_v<F>);
            if constexpr (std::is_invocable_v<F, T>) {
                return meth_type::noarg;
            } else if constexpr (std::is_invocable_v<F, T, PyObject*, PyObject*>) {
                return meth_type::varkw;
            } else if constexpr (std::is_invocable_v<
                                         F, T, PyObject* const*, Py_ssize_t>) {
                return meth_type::fastcall;
            } else if constexpr (std::is_invocable_v<F, T, PyObject*>) {
                return meth_type::singarg;
            } else {
                static_assert(!std::is_same_v<F, F>);
            }
        }();
    };

    template <meth_type, auto f>
    struct meth {};

    template <auto f>
    struct meth<meth_type::noarg, f> {
        static constexpr int flags = METH_NOARGS;

        static PyObject* impl(PyObject* self, PyObject*) {
            auto* inst = reinterpret_cast<wrap_t*>(self)->inst();
            try {
                CVT_RET_PYOBJ((inst->*f)());
            }
            PYEXT17_TRANSLATE_EXC_RET(nullptr)
        }
    };

    template <auto f>
    struct meth<meth_type::varkw, f> {
        static constexpr int flags = METH_VARARGS | METH_KEYWORDS;

        static PyObject* impl(PyObject* self, PyObject* args, PyObject* kwargs) {
            auto* inst = reinterpret_cast<wrap_t*>(self)->inst();
            try {
                CVT_RET_PYOBJ((inst->*f)(args, kwargs));
            }
            PYEXT17_TRANSLATE_EXC_RET(nullptr)
        }
    };

    template <auto f>
    struct meth<meth_type::fastcall, f> {
#ifdef METH_FASTCALL
        static constexpr int flags = METH_FASTCALL;

        static PyObject* impl(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
            auto* inst = reinterpret_cast<wrap_t*>(self)->inst();
            try {
                CVT_RET_PYOBJ((inst->*f)(args, nargs));
            }
            PYEXT17_TRANSLATE_EXC_RET(nullptr)
        }
#else
        static constexpr int flags = METH_VARARGS;

        static PyObject* impl(PyObject* self, PyObject* args) {
            auto* inst = reinterpret_cast<wrap_t*>(self)->inst();
            auto* arr = &PyTuple_GET_ITEM(args, 0);
            auto size = PyTuple_GET_SIZE(args);
            try {
                CVT_RET_PYOBJ((inst->*f)(arr, size));
            }
            PYEXT17_TRANSLATE_EXC_RET(nullptr)
        }
#endif
    };

    template <auto f>
    struct meth<meth_type::singarg, f> {
        static constexpr int flags = METH_O;

        static PyObject* impl(PyObject* self, PyObject* obj) {
            auto* inst = reinterpret_cast<wrap_t*>(self)->inst();
            try {
                CVT_RET_PYOBJ((inst->*f)(obj));
            }
            PYEXT17_TRANSLATE_EXC_RET(nullptr)
        }
    };

    template <auto f>
    static constexpr PyMethodDef make_meth_def(
            const char* name, const char* doc = nullptr) {
        using M = meth<detect_meth_type<f>::value, f>;
        return {name, (PyCFunction)M::impl, M::flags, doc};
    }

    template <auto f>
    struct getter {
        using F = decltype(f);

        static PyObject* impl(PyObject* self, void* closure) {
            auto* inst = reinterpret_cast<wrap_t*>(self)->inst();
            try {
                if constexpr (std::is_invocable_v<F, PyObject*, void*>) {
                    CVT_RET_PYOBJ(f(self, closure));
                } else if constexpr (std::is_invocable_v<F, T, void*>) {
                    CVT_RET_PYOBJ((inst->*f)(closure));
                } else if constexpr (std::is_invocable_v<F, T>) {
                    CVT_RET_PYOBJ((inst->*f)());
                } else {
                    static_assert(!std::is_same_v<F, F>);
                }
            }
            PYEXT17_TRANSLATE_EXC_RET(nullptr)
        }
    };

    template <auto f>
    struct setter {
        using F = decltype(f);

        template <typename = void>
        static int impl_(PyObject* self, PyObject* val, void* closure) {
            auto* inst = reinterpret_cast<wrap_t*>(self)->inst();
            try {
                if constexpr (std::is_invocable_v<F, PyObject*, PyObject*, void*>) {
                    CVT_RET_INT(f(self, val, closure));
                } else if constexpr (std::is_invocable_v<F, T, PyObject*, void*>) {
                    CVT_RET_INT((inst->*f)(val, closure));
                } else if constexpr (std::is_invocable_v<F, T, PyObject*>) {
                    CVT_RET_INT((inst->*f)(val));
                } else {
                    static_assert(!std::is_same_v<F, F>);
                }
            }
            PYEXT17_TRANSLATE_EXC_RET(-1)
        }

        static constexpr auto impl = []() {
            if constexpr (std::is_same_v<F, std::nullptr_t>)
                return nullptr;
            else
                return impl_<>;
        }();
    };

    template <auto get, auto set = nullptr>
    static constexpr PyGetSetDef make_getset_def(
            const char* name, const char* doc = nullptr, void* closure = nullptr) {
        return {const_cast<char*>(name), getter<get>::impl, setter<set>::impl,
                const_cast<char*>(doc), closure};
    }

    // polyfills

    struct tp_vectorcall {
        static constexpr bool valid = HAS_MEMBER(T, tp_vectorcall);
        static constexpr bool haskw = []() {
            if constexpr (valid)
                if constexpr (std::is_invocable_v<
                                      decltype(&T::tp_vectorcall), T, PyObject* const*,
                                      size_t, PyObject*>)
                    return true;
            return false;
        }();

        template <typename = void>
        static PyObject* impl(
                PyObject* self, PyObject* const* args, size_t nargsf,
                PyObject* kwnames) {
            auto* inst = reinterpret_cast<wrap_t*>(self)->inst();
            if constexpr (haskw) {
                CVT_RET_PYOBJ(inst->tp_vectorcall(args, nargsf, kwnames));
            } else {
                if (kwnames && PyTuple_GET_SIZE(kwnames)) {
                    PyErr_SetString(PyExc_TypeError, "expect no keyword argument");
                    return nullptr;
                }
                CVT_RET_PYOBJ(inst->tp_vectorcall(args, nargsf));
            }
        }

        static constexpr Py_ssize_t offset = []() {
            if constexpr (valid)
                return offsetof(wrap_t, vectorcall_slot);
            else
                return 0;
        }();
    };

    struct tp_call {
        static constexpr bool provided = HAS_MEMBER(T, tp_call);
        static constexpr bool static_form =
                invocable_with<T, PyObject*, PyObject*, PyObject*>{}(
                        [](auto&& t, auto... args)
                                -> decltype(std::decay_t<decltype(t)>::tp_call(
                                        args...)) {});
        static constexpr bool valid = provided || tp_vectorcall::valid;

        template <typename = void>
        static PyObject* impl(PyObject* self, PyObject* args, PyObject* kwargs) {
            auto* inst = reinterpret_cast<wrap_t*>(self)->inst();
            CVT_RET_PYOBJ(inst->tp_call(args, kwargs));
        }

        static constexpr ternaryfunc value = []() {
            if constexpr (static_form)
                return T::tp_call;
            else if constexpr (provided)
                return impl<>;
#ifdef _Py_TPFLAGS_HAVE_VECTORCALL
            else if constexpr (valid)
                return PyVectorcall_Call;
#endif
            else
                return nullptr;
        }();
    };

    struct tp_new {
        static constexpr bool provided = HAS_MEMBER(T, tp_new);
        static constexpr bool varkw = std::is_constructible_v<T, PyObject*, PyObject*>;
        static constexpr bool noarg = std::is_default_constructible_v<T>;

        template <typename = void>
        static PyObject* impl(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
            struct FreeGuard {
                PyObject* self;
                PyTypeObject* type;
                ~FreeGuard() {
                    if (self)
                        type->tp_free(self);
                }
            };

            auto* self = type->tp_alloc(type, 0);
            FreeGuard free_guard{self, type};
            auto* inst = reinterpret_cast<wrap_t*>(self)->inst();
            if constexpr (has_vectorcall && tp_vectorcall::valid) {
                reinterpret_cast<wrap_t*>(self)->vectorcall_slot =
                        &tp_vectorcall::template impl<>;
            }
            try {
                if constexpr (varkw) {
                    new (inst) T(args, kwargs);
                } else {
                    new (inst) T();
                }
            }
            PYEXT17_TRANSLATE_EXC_RET(nullptr)
            free_guard.self = nullptr;
            return self;
        }

        static constexpr newfunc value = []() {
            if constexpr (provided)
                return T::tp_new;
            else if constexpr (varkw || noarg)
                return impl<>;
            else
                return nullptr;
        }();
    };

    struct tp_dealloc {
        static constexpr bool provided = HAS_MEMBER(T, tp_dealloc);

        template <typename = void>
        static void impl(PyObject* self) {
            reinterpret_cast<wrap_t*>(self)->inst()->~T();
            Py_TYPE(self)->tp_free(self);
        }

        static constexpr destructor value = []() {
            if constexpr (provided)
                return T::tp_dealloc;
            else
                return impl<>;
        }();
    };

public:
    class TypeBuilder {
        std::vector<PyMethodDef> m_methods;
        std::vector<PyGetSetDef> m_getsets;
        PyTypeObject m_type;
        bool m_finalized = false;
        bool m_ready = false;

        void check_finalized() {
            if (m_finalized) {
                throw std::runtime_error("type is already finalized");
            }
        }

        static const char* to_c_str(const char* s) { return s; }

        template <size_t N, typename... Ts>
        static const char* to_c_str(const pybind11::detail::descr<N, Ts...>& desc) {
            return desc.text;
        }

    public:
        TypeBuilder(const TypeBuilder&) = delete;
        TypeBuilder& operator=(const TypeBuilder&) = delete;

        TypeBuilder() : m_type{PyVarObject_HEAD_INIT(nullptr, 0)} {
            constexpr auto has_tp_name = HAS_MEMBER(T, tp_name);
            if constexpr (has_tp_name) {
                m_type.tp_name = to_c_str(T::tp_name);
            }
            m_type.tp_dealloc = tp_dealloc::value;
#ifdef _Py_TPFLAGS_HAVE_VECTORCALL
            m_type.tp_vectorcall_offset = tp_vectorcall::offset;
#endif
            m_type.tp_call = tp_call::value;
            m_type.tp_basicsize = sizeof(wrap_t);
            m_type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
#ifdef _Py_TPFLAGS_HAVE_VECTORCALL
            if constexpr (tp_vectorcall::valid) {
                m_type.tp_flags |= _Py_TPFLAGS_HAVE_VECTORCALL;
            }
#endif
            m_type.tp_new = tp_new::value;
        }

        PyTypeObject* operator->() { return &m_type; }

        bool ready() const { return m_ready; }

        bool isinstance(PyObject* op) { return PyObject_TypeCheck(op, &m_type); }

        bool isexact(PyObject* op) { return Py_TYPE(op) == &m_type; }

        bool same_pytype(PyTypeObject* pt) { return pt == &m_type; }

        PyObject* finalize() {
            if (!m_finalized) {
                m_finalized = true;
                if (m_methods.size()) {
                    m_methods.push_back({0});
                    if (m_type.tp_methods) {
                        PyErr_SetString(PyExc_SystemError, "tp_method is already set");
                        return nullptr;
                    }
                    m_type.tp_methods = &m_methods[0];
                }
                if (m_getsets.size()) {
                    m_getsets.push_back({0});
                    if (m_type.tp_getset) {
                        PyErr_SetString(PyExc_SystemError, "tp_getset is already set");
                        return nullptr;
                    }
                    m_type.tp_getset = &m_getsets[0];
                }
                if (PyType_Ready(&m_type)) {
                    return nullptr;
                }
                m_ready = true;
            }
            return (PyObject*)&m_type;
        }

        template <auto f>
        TypeBuilder& def(const char* name, const char* doc = nullptr) {
            check_finalized();
            m_methods.push_back(make_meth_def<f>(name, doc));
            return *this;
        }

        template <auto get, auto set = nullptr>
        TypeBuilder& def_getset(
                const char* name, const char* doc = nullptr, void* closure = nullptr) {
            check_finalized();
            m_getsets.push_back(make_getset_def<get, set>(name, doc, closure));
            return *this;
        }
    };

    static TypeBuilder& type() {
        static TypeBuilder type_helper;
        return type_helper;
    }

    template <typename... Args>
    static PyObject* cnew(Args&&... args) {
        auto* pytype = type().operator->();
        return cnew_with_type(pytype, std::forward<Args>(args)...);
    }

    template <typename... Args>
    static PyObject* cnew_with_type(PyTypeObject* pytype, Args&&... args) {
        auto* self = pytype->tp_alloc(pytype, 0);
        auto* inst = reinterpret_cast<wrap_t*>(self)->inst();
        if constexpr (has_vectorcall && tp_vectorcall::valid) {
            reinterpret_cast<wrap_t*>(self)->vectorcall_slot =
                    &tp_vectorcall::template impl<>;
        }
        new (inst) T(std::forward<Args>(args)...);
        return self;
    }

    struct caster {
        static constexpr auto name = T::tp_name;

        T* value;

        bool load(pybind11::handle src, bool convert) {
            if (wrap_t::type().isinstance(src.ptr())) {
                value = reinterpret_cast<wrap_t*>(src.ptr())->inst();
                return true;
            }
            return false;
        }

        template <typename U>
        using cast_op_type = pybind11::detail::cast_op_type<U>;
        operator T*() { return value; }
        operator T&() { return *value; }
    };
};

}  // namespace pyext17

#undef HAS_MEMBER_TYPE
#undef HAS_MEMBER
#undef CVT_RET_PYOBJ
#undef CVT_RET_INT