pybind11.h 46.4 KB
Newer Older
Wenzel Jakob's avatar
Wenzel Jakob committed
1
/*
2
    pybind11/pybind11.h: Main header file of the C++11 python binding generator library
Wenzel Jakob's avatar
Wenzel Jakob committed
3
4
5
6
7
8
9

    Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>

    All rights reserved. Use of this source code is governed by a
    BSD-style license that can be found in the LICENSE file.
*/

10
#pragma once
Wenzel Jakob's avatar
Wenzel Jakob committed
11
12
13
14
15
16
17
18

#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
#pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
#pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
#pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
#pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
19
#elif defined(__GNUG__) and !defined(__clang__)
20
21
22
23
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
Wenzel Jakob's avatar
Wenzel Jakob committed
24
25
#endif

26
#include "cast.h"
Wenzel Jakob's avatar
Wenzel Jakob committed
27

28
NAMESPACE_BEGIN(pybind11)
Wenzel Jakob's avatar
Wenzel Jakob committed
29

30
31
32
33
34
template <typename T> struct arg_t;

/// Annotation for keyword arguments
struct arg {
    arg(const char *name) : name(name) { }
Wenzel Jakob's avatar
Wenzel Jakob committed
35
    template <typename T> arg_t<T> operator=(const T &value);
36
37
38
39
40
    const char *name;
};

/// Annotation for keyword arguments with default values
template <typename T> struct arg_t : public arg {
41
42
    arg_t(const char *name, const T &value, const char *descr = nullptr)
        : arg(name), value(value), descr(descr) { }
43
    T value;
44
    const char *descr;
45
};
46

Wenzel Jakob's avatar
Wenzel Jakob committed
47
template <typename T> arg_t<T> arg::operator=(const T &value) { return arg_t<T>(name, value); }
48
49

/// Annotation for methods
Wenzel Jakob's avatar
Wenzel Jakob committed
50
struct is_method { PyObject *class_; is_method(object *o) : class_(o->ptr()) { } };
51
52
53
54
55
56
57
58
59
60

/// Annotation for documentation
struct doc { const char *value; doc(const char *value) : value(value) { } };

/// Annotation for function names
struct name { const char *value; name(const char *value) : value(value) { } };

/// Annotation for function siblings
struct sibling { PyObject *value; sibling(handle value) : value(value.ptr()) { } };

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/// Keep patient alive while nurse lives
template <int Nurse, int Patient> struct keep_alive { };

NAMESPACE_BEGIN(detail)
template <typename... Args> struct process_dynamic;
template <typename T> struct process_dynamic<T> {
    static void precall(PyObject *) { }
    static void postcall(PyObject *, PyObject *) { }
};
template <> struct process_dynamic<> : public process_dynamic<void> { };
template <typename T, typename... Args> struct process_dynamic<T, Args...> {
    static void precall(PyObject *arg) {
        process_dynamic<T>::precall(arg);
        process_dynamic<Args...>::precall(arg);
    }
    static void postcall(PyObject *arg, PyObject *ret) {
        process_dynamic<T>::postcall(arg, ret);
        process_dynamic<Args...>::postcall(arg, ret);
    }
};
NAMESPACE_END(detail)

Wenzel Jakob's avatar
Wenzel Jakob committed
83
/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
84
class cpp_function : public function {
Wenzel Jakob's avatar
Wenzel Jakob committed
85
private:
86
    /// Linked list of function overloads
Wenzel Jakob's avatar
Wenzel Jakob committed
87
    struct function_entry {
88
        /// Function name and user-specified documentation string
89
90
91
        char *name = nullptr, *doc = nullptr; /* why no C++ strings? They generate heavier code.. */
        /// Human-readable version of the function signature
        char *signature = nullptr;
92
        /// List of registered keyword arguments
93
94
        std::vector<detail::argument_entry> args;
        /// Pointer to lambda function which converts arguments and performs the actual call
95
96
        PyObject * (*impl) (function_entry *, PyObject *, PyObject *) = nullptr;
        /// Storage for the wrapped function pointer and captured data, if any
97
        void *data = nullptr;
98
        /// Pointer to custom destructor for 'data' (if needed)
99
        void (*free_data) (void *ptr) = nullptr;
100
        /// Return value policy associated with this function
101
        return_value_policy policy = return_value_policy::automatic;
102
103
104
105
106
        /// True if name == '__init__'
        bool is_constructor = false;
        /// Python method object
        PyMethodDef *def = nullptr;
        /// Pointer to class (if this is method)
107
        PyObject *class_ = nullptr;
108
        /// Pointer to first registered function in overload chain
109
        PyObject *sibling = nullptr;
110
        /// Pointer to next overload
Wenzel Jakob's avatar
Wenzel Jakob committed
111
112
113
        function_entry *next = nullptr;
    };

114
115
    function_entry *m_entry;

Wenzel Jakob's avatar
Wenzel Jakob committed
116
117
118
    /// Picks a suitable return value converter from cast.h
    template <typename T> using return_value_caster =
        detail::type_caster<typename std::conditional<
119
            std::is_void<T>::value, detail::void_type, typename detail::intrinsic_type<T>::type>::type>;
Wenzel Jakob's avatar
Wenzel Jakob committed
120
121

    /// Picks a suitable argument value converter from cast.h
122
    template <typename... T> using arg_value_caster =
Wenzel Jakob's avatar
Wenzel Jakob committed
123
        detail::type_caster<typename std::tuple<T...>>;
124

125
126
    template <typename... T> static void process_static(const std::tuple<T...> &args, function_entry *entry) {
        process_static(args, entry, typename detail::make_index_sequence<sizeof...(T)>::type());
127
128
    }

129
    template <typename... T, size_t ... Index> static void process_static(const std::tuple<T...> &args,
130
            function_entry *entry, detail::index_sequence<Index...>) {
131
        int unused[] = { 0, (process_static(std::get<Index>(args), entry), 0)... };
132
133
134
        (void) unused;
    }

135
    template <int Nurse, int Patient>
136
137
138
139
140
141
142
143
    static void process_static(const keep_alive<Nurse, Patient> &, function_entry *) { }
    static void process_static(const char *doc, function_entry *entry) { entry->doc = (char *) doc; }
    static void process_static(const pybind11::doc &d, function_entry *entry) { entry->doc = (char *) d.value; }
    static void process_static(const pybind11::name &n, function_entry *entry) { entry->name = (char *) n.value; }
    static void process_static(const pybind11::return_value_policy p, function_entry *entry) { entry->policy = p; }
    static void process_static(const pybind11::sibling s, function_entry *entry) { entry->sibling = s.value; }
    static void process_static(const pybind11::is_method &m, function_entry *entry) { entry->class_ = m.class_; }
    static void process_static(const pybind11::arg &a, function_entry *entry) {
144
        if (entry->class_ && entry->args.empty())
145
146
            entry->args.emplace_back("self", nullptr, nullptr);
        entry->args.emplace_back(a.name, nullptr, nullptr);
147
    }
148

149
    template <typename T>
150
    static void process_static(const pybind11::arg_t<T> &a, function_entry *entry) {
151
        if (entry->class_ && entry->args.empty())
152
            entry->args.emplace_back("self", nullptr, nullptr);
153

154
        PyObject *obj = detail::type_caster<typename detail::intrinsic_type<T>::type>::cast(
155
                a.value, return_value_policy::automatic, nullptr);
156

157
158
159
160
161
162
        if (obj == nullptr)
            throw std::runtime_error("arg(): could not convert default keyword "
                                     "argument into a Python object (type not "
                                     "registered yet?)");

        entry->args.emplace_back(a.name, a.descr, obj);
163
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
164
public:
165
    cpp_function() { }
Wenzel Jakob's avatar
Wenzel Jakob committed
166
167

    /// Vanilla function pointers
168
169
170
    template <typename Return, typename... Args, typename... Extra>
    cpp_function(Return (*f)(Args...), Extra&&... extra) {
        using detail::descr;
171
        m_entry = new function_entry();
172
        m_entry->data = (void *) f;
Wenzel Jakob's avatar
Wenzel Jakob committed
173

174
        typedef arg_value_caster<Args...> cast_in;
175
176
        typedef return_value_caster<Return> cast_out;

177
        m_entry->impl = [](function_entry *entry, PyObject *pyArgs, PyObject *parent) -> PyObject * {
Wenzel Jakob's avatar
Wenzel Jakob committed
178
            cast_in args;
179
            if (!args.load(pyArgs, true))
180
                return (PyObject *) 1; /* Special return code: try next overload */
181
182
183
184
            detail::process_dynamic<Extra...>::precall(pyArgs);
            PyObject *result = cast_out::cast(args.template call<Return>((Return (*)(Args...)) entry->data), entry->policy, parent);
            detail::process_dynamic<Extra...>::postcall(pyArgs, result);
            return result;
Wenzel Jakob's avatar
Wenzel Jakob committed
185
186
        };

187
        process_static(std::make_tuple(std::forward<Extra>(extra)...), m_entry);
188
189
        PYBIND11_DESCR signature = cast_in::name() + detail::_(" -> ") + cast_out::name();
        initialize(signature.text(), signature.types(), sizeof...(Args));
Wenzel Jakob's avatar
Wenzel Jakob committed
190
191
192
    }

    /// Delegating helper constructor to deal with lambda functions
193
194
    template <typename Func, typename... Extra> cpp_function(Func &&f, Extra&&... extra) {
        initialize(std::forward<Func>(f),
Wenzel Jakob's avatar
Wenzel Jakob committed
195
                   (typename detail::remove_class<decltype(
196
197
                       &std::remove_reference<Func>::type::operator())>::type *) nullptr,
                   std::forward<Extra>(extra)...);
Wenzel Jakob's avatar
Wenzel Jakob committed
198
199
200
    }

    /// Class methods (non-const)
201
202
203
204
    template <typename Return, typename Class, typename... Arg, typename... Extra> cpp_function(
            Return (Class::*f)(Arg...), Extra&&... extra) {
        initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
                   (Return (*) (Class *, Arg...)) nullptr, std::forward<Extra>(extra)...);
Wenzel Jakob's avatar
Wenzel Jakob committed
205
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
206
207

    /// Class methods (const)
208
209
210
211
    template <typename Return, typename Class, typename... Arg, typename... Extra> cpp_function(
            Return (Class::*f)(Arg...) const, Extra&&... extra) {
        initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
                   (Return (*)(const Class *, Arg ...)) nullptr, std::forward<Extra>(extra)...);
Wenzel Jakob's avatar
Wenzel Jakob committed
212
213
    }

214
215
216
    /// Return the function name
    const char *name() const { return m_entry->name; }

Wenzel Jakob's avatar
Wenzel Jakob committed
217
private:
Wenzel Jakob's avatar
Wenzel Jakob committed
218
    /// Functors, lambda functions, etc.
219
220
221
222
223
    template <typename Func, typename Return, typename... Args, typename... Extra>
    void initialize(Func &&f, Return (*)(Args...), Extra&&... extra) {
        using detail::descr;

        struct capture { typename std::remove_reference<Func>::type f; };
Wenzel Jakob's avatar
Wenzel Jakob committed
224

225
        m_entry = new function_entry();
226
        m_entry->data = new capture { std::forward<Func>(f) };
227

228
        if (!std::is_trivially_destructible<Func>::value)
229
            m_entry->free_data = [](void *ptr) { delete (capture *) ptr; };
230
        else
231
            m_entry->free_data = operator delete;
232

233
        typedef arg_value_caster<Args...> cast_in;
234
        typedef return_value_caster<Return> cast_out;
Wenzel Jakob's avatar
Wenzel Jakob committed
235

236
        m_entry->impl = [](function_entry *entry, PyObject *pyArgs, PyObject *parent) -> PyObject *{
Wenzel Jakob's avatar
Wenzel Jakob committed
237
            cast_in args;
238
            if (!args.load(pyArgs, true))
239
                return (PyObject *) 1; /* Special return code: try next overload */
240
241
242
243
            detail::process_dynamic<Extra...>::precall(pyArgs);
            PyObject *result = cast_out::cast(args.template call<Return>(((capture *) entry->data)->f), entry->policy, parent);
            detail::process_dynamic<Extra...>::postcall(pyArgs, result);
            return result;
Wenzel Jakob's avatar
Wenzel Jakob committed
244
245
        };

246
        process_static(std::make_tuple(std::forward<Extra>(extra)...), m_entry);
247
248
        PYBIND11_DESCR signature = cast_in::name() + detail::_(" -> ") + cast_out::name();
        initialize(signature.text(), signature.types(), sizeof...(Args));
Wenzel Jakob's avatar
Wenzel Jakob committed
249
250
    }

Wenzel Jakob's avatar
Wenzel Jakob committed
251
    static PyObject *dispatcher(PyObject *self, PyObject *args, PyObject *kwargs) {
252
253
254
255
256
257
        function_entry *overloads = (function_entry *) PyCapsule_GetPointer(self, nullptr),
                       *it = overloads;
        int nargs = (int) PyTuple_Size(args),
            nkwargs = kwargs ? (int) PyDict_Size(kwargs) : 0;
        PyObject *parent = nargs > 0 ? PyTuple_GetItem(args, 0) : nullptr,
                 *result = (PyObject *) 1;
Wenzel Jakob's avatar
Wenzel Jakob committed
258
        try {
259
            for (; it != nullptr; it = it->next) {
260
                object args_(args, true);
261
                int kwargs_consumed = 0;
262

263
                if (nargs < (int) it->args.size()) {
264
                    args_ = object(PyTuple_New(it->args.size()), false);
265
                    for (int i = 0; i < nargs; ++i) {
266
267
                        PyObject *item = PyTuple_GET_ITEM(args, i);
                        Py_INCREF(item);
268
                        PyTuple_SET_ITEM(args_.ptr(), i, item);
269
                    }
270
                    int arg_ctr = 0;
271
                    for (auto const &it2 : it->args) {
272
                        int index = arg_ctr++;
273
                        if (PyTuple_GET_ITEM(args_.ptr(), index))
274
275
276
                            continue;
                        PyObject *value = nullptr;
                        if (kwargs)
277
                            value = PyDict_GetItemString(kwargs, it2.name);
278
279
                        if (value)
                            kwargs_consumed++;
280
281
                        else if (it2.value)
                            value = it2.value;
282
283
                        if (value) {
                            Py_INCREF(value);
284
                            PyTuple_SET_ITEM(args_.ptr(), index, value);
285
286
287
288
289
                        } else {
                            kwargs_consumed = -1; /* definite failure */
                            break;
                        }
                    }
290
291
                }

292
                if (kwargs_consumed == nkwargs)
293
                    result = it->impl(it, args_.ptr(), parent);
294

295
                if (result != (PyObject *) 1)
Wenzel Jakob's avatar
Wenzel Jakob committed
296
297
                    break;
            }
Jonas Adler's avatar
Jonas Adler committed
298
299
300
301
302
303
304
305
306
307
        } catch (const error_already_set &)      {                                                 return nullptr;
        } catch (const index_error &e)           { PyErr_SetString(PyExc_IndexError,    e.what()); return nullptr;
        } catch (const stop_iteration &e)        { PyErr_SetString(PyExc_StopIteration, e.what()); return nullptr;
        } catch (const std::bad_alloc &e)        { PyErr_SetString(PyExc_MemoryError,   e.what()); return nullptr;
        } catch (const std::domain_error &e)     { PyErr_SetString(PyExc_ValueError,    e.what()); return nullptr;
        } catch (const std::invalid_argument &e) { PyErr_SetString(PyExc_ValueError,    e.what()); return nullptr;
        } catch (const std::length_error &e)     { PyErr_SetString(PyExc_ValueError,    e.what()); return nullptr;
        } catch (const std::out_of_range &e)     { PyErr_SetString(PyExc_IndexError,    e.what()); return nullptr;
        } catch (const std::range_error &e)      { PyErr_SetString(PyExc_ValueError,    e.what()); return nullptr;
        } catch (const std::exception &e)        { PyErr_SetString(PyExc_RuntimeError,  e.what()); return nullptr;
Wenzel Jakob's avatar
Wenzel Jakob committed
308
309
310
311
        } catch (...) {
            PyErr_SetString(PyExc_RuntimeError, "Caught an unknown exception!");
            return nullptr;
        }
312
313
314
315
        if (result == (PyObject *) 1) {
            std::string msg = "Incompatible function arguments. The "
                              "following argument types are supported:\n";
            int ctr = 0;
Wenzel Jakob's avatar
Wenzel Jakob committed
316
            for (function_entry *it2 = overloads; it2 != nullptr; it2 = it2->next) {
317
                msg += "    "+ std::to_string(++ctr) + ". ";
318
                msg += it2->signature;
319
320
321
322
323
324
325
                msg += "\n";
            }
            PyErr_SetString(PyExc_TypeError, msg.c_str());
            return nullptr;
        } else if (result == nullptr) {
            std::string msg = "Unable to convert function return value to a "
                              "Python type! The signature was\n\t";
326
            msg += it->signature;
327
328
329
            PyErr_SetString(PyExc_TypeError, msg.c_str());
            return nullptr;
        } else {
Wenzel Jakob's avatar
Wenzel Jakob committed
330
331
332
333
            if (overloads->is_constructor) {
                PyObject *inst = PyTuple_GetItem(args, 0);
                const detail::type_info *type_info =
                    capsule(PyObject_GetAttrString((PyObject *) Py_TYPE(inst),
334
                                const_cast<char *>("__pybind11__")), false);
335
                type_info->init_holder(inst, nullptr);
Wenzel Jakob's avatar
Wenzel Jakob committed
336
337
338
339
340
            }
            return result;
        }
    }

341
342
343
    static void destruct(function_entry *entry) {
        while (entry) {
            function_entry *next = entry->next;
344
345
346
347
348
349
350
351
352
353
            if (entry->free_data)
                entry->free_data(entry->data);
            std::free((char *) entry->name);
            std::free((char *) entry->doc);
            std::free((char *) entry->signature);
            for (auto &arg: entry->args) {
                std::free((char *) arg.name);
                std::free((char *) arg.descr);
                Py_XDECREF(arg.value);
            }
354
355
356
357
            if (entry->def) {
                free((char *) entry->def->ml_doc);
                delete entry->def;
            }
358
359
360
361
362
            delete entry;
            entry = next;
        }
    }

363
364
365
366
367
368
369
370
371
372
    void initialize(const char *text, const std::type_info * const * types, int args) {
        /* Create copies of all referenced C-style strings */
        m_entry->name = strdup(m_entry->name ? m_entry->name : "");
        if (m_entry->doc) m_entry->doc = strdup(m_entry->doc);
        for (auto &a: m_entry->args) {
            if (a.name)
                a.name = strdup(a.name);
            if (a.descr)
                a.descr = strdup(a.descr);
            else if (a.value)
373
                a.descr = strdup(((std::string) ((object) handle(a.value).attr("__repr__")).call().str()).c_str());
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
        }
        auto const &registered_types = detail::get_internals().registered_types;

        /* Generate a proper function signature */
        std::string signature;
        size_t type_depth = 0, char_index = 0, type_index = 0, arg_index = 0;
        while (true) {
            char c = text[char_index++];
            if (c == '\0')
                break;

            if (c == '{') {
                if (type_depth == 1 && arg_index < m_entry->args.size()) {
                    signature += m_entry->args[arg_index].name;
                    signature += " : ";
                }
                ++type_depth;
            } else if (c == '}') {
                --type_depth;
                if (type_depth == 1 && arg_index < m_entry->args.size()) {
                    if (m_entry->args[arg_index].descr) {
                        signature += " = ";
                        signature += m_entry->args[arg_index].descr;
                    }
                    arg_index++;
                }
            } else if (c == '%') {
                const std::type_info *t = types[type_index++];
402
                if (!t)
403
                    throw std::runtime_error("Internal error while parsing type signature (1)");
404
405
406
407
408
409
410
411
412
413
414
415
                auto it = registered_types.find(t);
                if (it != registered_types.end()) {
                    signature += it->second.type->tp_name;
                } else {
                    std::string tname(t->name());
                    detail::clean_type_id(tname);
                    signature += tname;
                }
            } else {
                signature += c;
            }
        }
416
        if (type_depth != 0 || types[type_index] != nullptr)
417
            throw std::runtime_error("Internal error while parsing type signature (2)");
418
419
420
421
422

        #if !defined(PYBIND11_CPP14)
            delete[] types;
            delete[] text;
        #endif
423

424
#if PY_MAJOR_VERSION < 3
425
426
427
428
        if (strcmp(m_entry->name, "__next__") == 0) {
            free(m_entry->name);
            m_entry->name = strdup("next");
        }
429
430
#endif

431
        if (!m_entry->args.empty() && (int) m_entry->args.size() != args)
432
            throw std::runtime_error(
433
                "cpp_function(): function \"" + std::string(m_entry->name) + "\" takes " +
434
                std::to_string(args) + " arguments, but " + std::to_string(m_entry->args.size()) +
435
                " pybind11::arg entries were specified!");
436

437
        m_entry->is_constructor = !strcmp(m_entry->name, "__init__");
438
439
        m_entry->signature = strdup(signature.c_str());
        m_entry->args.shrink_to_fit();
440
441
442
443
444

#if PY_MAJOR_VERSION < 3
        if (m_entry->sibling && PyMethod_Check(m_entry->sibling))
            m_entry->sibling = PyMethod_GET_FUNCTION(m_entry->sibling);
#endif
445

446
447
448
449
450
        function_entry *s_entry = nullptr, *entry = m_entry;
        if (m_entry->sibling && PyCFunction_Check(m_entry->sibling)) {
            capsule entry_capsule(PyCFunction_GetSelf(m_entry->sibling), true);
            s_entry = (function_entry *) entry_capsule;
            if (s_entry->class_ != m_entry->class_)
451
                s_entry = nullptr; /* Overridden method, don't append to parent class overloads */
452
453
        }

454
        if (!s_entry) { /* No existing overload was found, create a function object */
455
456
457
458
459
460
461
            m_entry->def = new PyMethodDef();
            memset(m_entry->def, 0, sizeof(PyMethodDef));
            m_entry->def->ml_name = m_entry->name;
            m_entry->def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
            m_entry->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
            capsule entry_capsule(m_entry, [](PyObject *o) { destruct((function_entry *) PyCapsule_GetPointer(o, nullptr)); });
            m_ptr = PyCFunction_New(m_entry->def, entry_capsule.ptr());
Wenzel Jakob's avatar
Wenzel Jakob committed
462
            if (!m_ptr)
463
                throw std::runtime_error("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob's avatar
Wenzel Jakob committed
464
        } else {
465
            m_ptr = m_entry->sibling;
Wenzel Jakob's avatar
Wenzel Jakob committed
466
            inc_ref();
467
468
469
470
            entry = s_entry;
            while (s_entry->next)
                s_entry = s_entry->next;
            s_entry->next = m_entry;
Wenzel Jakob's avatar
Wenzel Jakob committed
471
        }
472

Wenzel Jakob's avatar
Wenzel Jakob committed
473
        std::string signatures;
474
475
        int index = 0;
        function_entry *it = entry;
476
        while (it) { /* Create pydoc entry including all function signatures and docstrings of the overload chain */
477
            if (s_entry)
478
                signatures += std::to_string(++index) + ". ";
479
480
481
482
483
484
485
486
            signatures += "Signature : ";
            signatures += it->signature;
            signatures += "\n";
            if (it->doc && strlen(it->doc) > 0) {
                signatures += "\n";
                signatures += it->doc;
                signatures += "\n";
            }
487
            if (it->next)
Wenzel Jakob's avatar
Wenzel Jakob committed
488
                signatures += "\n";
489
            it = it->next;
Wenzel Jakob's avatar
Wenzel Jakob committed
490
491
492
        }
        PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
        if (func->m_ml->ml_doc)
493
            free((char *) func->m_ml->ml_doc);
Wenzel Jakob's avatar
Wenzel Jakob committed
494
        func->m_ml->ml_doc = strdup(signatures.c_str());
495
        if (entry->class_) {
496
#if PY_MAJOR_VERSION >= 3
Wenzel Jakob's avatar
Wenzel Jakob committed
497
            m_ptr = PyInstanceMethod_New(m_ptr);
498
499
500
#else
            m_ptr = PyMethod_New(m_ptr, nullptr, entry->class_);
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
501
            if (!m_ptr)
502
                throw std::runtime_error("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob's avatar
Wenzel Jakob committed
503
504
505
506
507
508
509
            Py_DECREF(func);
        }
    }
};

class module : public object {
public:
510
    PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob's avatar
Wenzel Jakob committed
511
512

    module(const char *name, const char *doc = nullptr) {
513
#if PY_MAJOR_VERSION >= 3
Wenzel Jakob's avatar
Wenzel Jakob committed
514
515
516
517
518
519
520
        PyModuleDef *def = new PyModuleDef();
        memset(def, 0, sizeof(PyModuleDef));
        def->m_name = name;
        def->m_doc = doc;
        def->m_size = -1;
        Py_INCREF(def);
        m_ptr = PyModule_Create(def);
521
522
523
#else
        m_ptr = Py_InitModule3(name, nullptr, doc);
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
524
525
526
527
528
        if (m_ptr == nullptr)
            throw std::runtime_error("Internal error in module::module()");
        inc_ref();
    }

529
530
531
532
    template <typename Func, typename... Extra>
    module &def(const char *name_, Func &&f, Extra&& ... extra) {
        cpp_function func(std::forward<Func>(f), name(name_),
                          sibling((handle) attr(name_)), std::forward<Extra>(extra)...);
Wenzel Jakob's avatar
Wenzel Jakob committed
533
        func.inc_ref(); /* The following line steals a reference to 'func' */
534
        PyModule_AddObject(ptr(), name_, func.ptr());
Wenzel Jakob's avatar
Wenzel Jakob committed
535
536
537
        return *this;
    }

538
    module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob's avatar
Wenzel Jakob committed
539
540
541
        std::string full_name = std::string(PyModule_GetName(m_ptr))
            + std::string(".") + std::string(name);
        module result(PyImport_AddModule(full_name.c_str()), true);
542
        if (doc)
543
            result.attr("__doc__") = pybind11::str(doc);
Wenzel Jakob's avatar
Wenzel Jakob committed
544
545
546
        attr(name) = result;
        return result;
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
547
548

    static module import(const char *name) {
549
550
551
552
        PyObject *obj = PyImport_ImportModule(name);
        if (!obj)
            throw std::runtime_error("Module \"" + std::string(name) + "\" not found!");
        return module(obj, false);
Wenzel Jakob's avatar
Wenzel Jakob committed
553
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
554
555
556
557
558
559
};

NAMESPACE_BEGIN(detail)
/// Basic support for creating new Python heap types
class custom_type : public object {
public:
560
    PYBIND11_OBJECT_DEFAULT(custom_type, object, PyType_Check)
Wenzel Jakob's avatar
Wenzel Jakob committed
561

562
    custom_type(object &scope, const char *name_, const std::type_info *tinfo,
Wenzel Jakob's avatar
Wenzel Jakob committed
563
                size_t type_size, size_t instance_size,
564
                void (*init_holder)(PyObject *, const void *), const destructor &dealloc,
Wenzel Jakob's avatar
Wenzel Jakob committed
565
566
                PyObject *parent, const char *doc) {
        PyHeapTypeObject *type = (PyHeapTypeObject*) PyType_Type.tp_alloc(&PyType_Type, 0);
567
#if PY_MAJOR_VERSION >= 3
Wenzel Jakob's avatar
Wenzel Jakob committed
568
        PyObject *name = PyUnicode_FromString(name_);
569
570
571
#else
        PyObject *name = PyString_FromString(name_);
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
572
573
574
575
576
        if (type == nullptr || name == nullptr)
            throw std::runtime_error("Internal error in custom_type::custom_type()");
        Py_INCREF(name);
        std::string full_name(name_);

577
        pybind11::str scope_name = (object) scope.attr("__name__"),
Wenzel Jakob's avatar
Wenzel Jakob committed
578
579
580
581
582
583
584
                    module_name = (object) scope.attr("__module__");

        if (scope_name.check())
            full_name =  std::string(scope_name) + "." + full_name;
        if (module_name.check())
            full_name =  std::string(module_name) + "." + full_name;

585
586
587
588
        type->ht_name = name;
#if PY_MAJOR_VERSION >= 3
        type->ht_qualname = name;
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
589
590
591
592
593
594
595
596
        type->ht_type.tp_name = strdup(full_name.c_str());
        type->ht_type.tp_basicsize = instance_size;
        type->ht_type.tp_init = (initproc) init;
        type->ht_type.tp_new = (newfunc) new_instance;
        type->ht_type.tp_dealloc = dealloc;
        type->ht_type.tp_flags |=
            Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
        type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
597
598
599
#if PY_MAJOR_VERSION < 3
        type->ht_type.tp_flags |= Py_TPFLAGS_CHECKTYPES;
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
600
601
602
603
        type->ht_type.tp_as_number = &type->as_number;
        type->ht_type.tp_as_sequence = &type->as_sequence;
        type->ht_type.tp_as_mapping = &type->as_mapping;
        type->ht_type.tp_base = (PyTypeObject *) parent;
604
605
        type->ht_type.tp_weaklistoffset = offsetof(instance<void>, weakrefs);

Wenzel Jakob's avatar
Wenzel Jakob committed
606
        if (doc) {
607
            size_t size = strlen(doc) + 1;
608
            type->ht_type.tp_doc = (char *) PyObject_MALLOC(size);
Wenzel Jakob's avatar
Wenzel Jakob committed
609
610
            memcpy((void *) type->ht_type.tp_doc, doc, size);
        }
Wenzel Jakob's avatar
Wenzel Jakob committed
611
612
613
614
615
616
617
        Py_XINCREF(parent);

        if (PyType_Ready(&type->ht_type) < 0)
            throw std::runtime_error("Internal error in custom_type::custom_type()");
        m_ptr = (PyObject *) type;

        /* Needed by pydoc */
618
        attr("__module__") = scope_name;
Wenzel Jakob's avatar
Wenzel Jakob committed
619

620
621
        auto &registered_types = get_internals().registered_types;
        auto &type_info = registered_types[tinfo];
Wenzel Jakob's avatar
Wenzel Jakob committed
622
623
624
        type_info.type = (PyTypeObject *) m_ptr;
        type_info.type_size = type_size;
        type_info.init_holder = init_holder;
625
        attr("__pybind11__") = capsule(&type_info);
Wenzel Jakob's avatar
Wenzel Jakob committed
626
627
628
629
630
631
632
633

        scope.attr(name) = *this;
    }

protected:
    /* Allocate a metaclass on demand (for static properties) */
    handle metaclass() {
        auto &ht_type = ((PyHeapTypeObject *) m_ptr)->ht_type;
634
#if PY_MAJOR_VERSION >= 3
Wenzel Jakob's avatar
Wenzel Jakob committed
635
        auto &ob_type = ht_type.ob_base.ob_base.ob_type;
636
637
638
639
#else
        auto &ob_type = ht_type.ob_type;
#endif

Wenzel Jakob's avatar
Wenzel Jakob committed
640
641
642
643
644
645
646
        if (ob_type == &PyType_Type) {
            std::string name_ = std::string(ht_type.tp_name) + "_meta";
            PyHeapTypeObject *type = (PyHeapTypeObject*) PyType_Type.tp_alloc(&PyType_Type, 0);
            PyObject *name = PyUnicode_FromString(name_.c_str());
            if (type == nullptr || name == nullptr)
                throw std::runtime_error("Internal error in custom_type::metaclass()");
            Py_INCREF(name);
647
648
649
650
            type->ht_name = name;
#if PY_MAJOR_VERSION >= 3
            type->ht_qualname = name;
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
            type->ht_type.tp_name = strdup(name_.c_str());
            type->ht_type.tp_base = &PyType_Type;
            type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
            type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
            if (PyType_Ready(&type->ht_type) < 0)
                throw std::runtime_error("Internal error in custom_type::metaclass()");
            ob_type = (PyTypeObject *) type;
            Py_INCREF(type);
        }
        return handle((PyObject *) ob_type);
    }

    static int init(void *self, PyObject *, PyObject *) {
        std::string msg = std::string(Py_TYPE(self)->tp_name) + ": No constructor defined!";
        PyErr_SetString(PyExc_TypeError, msg.c_str());
        return -1;
    }

    static PyObject *new_instance(PyTypeObject *type, PyObject *, PyObject *) {
        const detail::type_info *type_info = capsule(
671
            PyObject_GetAttrString((PyObject *) type, const_cast<char*>("__pybind11__")), false);
Wenzel Jakob's avatar
Wenzel Jakob committed
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
        instance<void> *self = (instance<void> *) PyType_GenericAlloc(type, 0);
        self->value = ::operator new(type_info->type_size);
        self->owned = true;
        self->parent = nullptr;
        self->constructed = false;
        detail::get_internals().registered_instances[self->value] = (PyObject *) self;
        return (PyObject *) self;
    }

    static void dealloc(instance<void> *self) {
        if (self->value) {
            bool dont_cache = self->parent && ((instance<void> *) self->parent)->value == self->value;
            if (!dont_cache) { // avoid an issue with internal references matching their parent's address
                auto &registered_instances = detail::get_internals().registered_instances;
                auto it = registered_instances.find(self->value);
                if (it == registered_instances.end())
                    throw std::runtime_error("Deallocating unregistered instance!");
                registered_instances.erase(it);
            }
            Py_XDECREF(self->parent);
692
693
            if (self->weakrefs)
                PyObject_ClearWeakRefs((PyObject *) self);
Wenzel Jakob's avatar
Wenzel Jakob committed
694
695
696
697
        }
        Py_TYPE(self)->tp_free((PyObject*) self);
    }

Wenzel Jakob's avatar
Wenzel Jakob committed
698
699
700
    void install_buffer_funcs(
            buffer_info *(*get_buffer)(PyObject *, void *),
            void *get_buffer_data) {
Wenzel Jakob's avatar
Wenzel Jakob committed
701
702
        PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
        type->ht_type.tp_as_buffer = &type->as_buffer;
703
704
705
#if PY_MAJOR_VERSION < 3
        type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
706
707
        type->as_buffer.bf_getbuffer = getbuffer;
        type->as_buffer.bf_releasebuffer = releasebuffer;
708
        auto info = ((detail::type_info *) capsule(attr("__pybind11__")));
Wenzel Jakob's avatar
Wenzel Jakob committed
709
710
        info->get_buffer = get_buffer;
        info->get_buffer_data = get_buffer_data;
Wenzel Jakob's avatar
Wenzel Jakob committed
711
712
713
    }

    static int getbuffer(PyObject *obj, Py_buffer *view, int flags) {
714
        auto const &typeinfo = ((detail::type_info *) capsule(handle(obj).attr("__pybind11__")));
Wenzel Jakob's avatar
Wenzel Jakob committed
715
716

        if (view == nullptr || obj == nullptr || !typeinfo || !typeinfo->get_buffer) {
Wenzel Jakob's avatar
Wenzel Jakob committed
717
718
719
720
            PyErr_SetString(PyExc_BufferError, "Internal error");
            return -1;
        }
        memset(view, 0, sizeof(Py_buffer));
Wenzel Jakob's avatar
Wenzel Jakob committed
721
        buffer_info *info = typeinfo->get_buffer(obj, typeinfo->get_buffer_data);
Wenzel Jakob's avatar
Wenzel Jakob committed
722
723
724
725
726
727
728
729
730
731
732
733
        view->obj = obj;
        view->ndim = 1;
        view->internal = info;
        view->buf = info->ptr;
        view->itemsize = info->itemsize;
        view->len = view->itemsize;
        for (auto s : info->shape)
            view->len *= s;
        if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
            view->format = const_cast<char *>(info->format.c_str());
        if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
            view->ndim = info->ndim;
734
735
            view->strides = (ssize_t *) &info->strides[0];
            view->shape = (ssize_t *) &info->shape[0];
Wenzel Jakob's avatar
Wenzel Jakob committed
736
737
738
739
740
741
742
        }
        Py_INCREF(view->obj);
        return 0;
    }

    static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; }
};
743
744
745
746
747
748
749

/* Forward declarations */
enum op_id : int;
enum op_type : int;
struct undefined_t;
template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_;
template <typename... Args> struct init;
Wenzel Jakob's avatar
Wenzel Jakob committed
750
751
752
753
754
755
NAMESPACE_END(detail)

template <typename type, typename holder_type = std::unique_ptr<type>> class class_ : public detail::custom_type {
public:
    typedef detail::instance<type, holder_type> instance_type;

756
    PYBIND11_OBJECT(class_, detail::custom_type, PyType_Check)
Wenzel Jakob's avatar
Wenzel Jakob committed
757
758

    class_(object &scope, const char *name, const char *doc = nullptr)
759
        : detail::custom_type(scope, name, &typeid(type), sizeof(type),
Wenzel Jakob's avatar
Wenzel Jakob committed
760
761
762
763
764
                              sizeof(instance_type), init_holder, dealloc,
                              nullptr, doc) { }

    class_(object &scope, const char *name, object &parent,
           const char *doc = nullptr)
765
        : detail::custom_type(scope, name, &typeid(type), sizeof(type),
Wenzel Jakob's avatar
Wenzel Jakob committed
766
767
768
                              sizeof(instance_type), init_holder, dealloc,
                              parent.ptr(), doc) { }

769
770
    template <typename Func, typename... Extra>
    class_ &def(const char *name_, Func&& f, Extra&&... extra) {
771
772
773
774
        cpp_function cf(std::forward<Func>(f), name(name_),
                        sibling(attr(name_)), is_method(this),
                        std::forward<Extra>(extra)...);
        attr(cf.name()) = cf;
Wenzel Jakob's avatar
Wenzel Jakob committed
775
776
777
        return *this;
    }

778
779
    template <typename Func, typename... Extra> class_ &
    def_static(const char *name_, Func f, Extra&&... extra) {
780
781
782
783
        cpp_function cf(std::forward<Func>(f), name(name_),
                        sibling(attr(name_)),
                        std::forward<Extra>(extra)...);
        attr(cf.name()) = cf;
Wenzel Jakob's avatar
Wenzel Jakob committed
784
785
786
        return *this;
    }

787
788
789
    template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
    class_ &def(const detail::op_<id, ot, L, R> &op, Extra&&... extra) {
        op.template execute<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob's avatar
Wenzel Jakob committed
790
791
792
        return *this;
    }

793
794
795
    template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
    class_ & def_cast(const detail::op_<id, ot, L, R> &op, Extra&&... extra) {
        op.template execute_cast<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob's avatar
Wenzel Jakob committed
796
797
798
        return *this;
    }

799
800
801
    template <typename... Args, typename... Extra>
    class_ &def(const detail::init<Args...> &init, Extra&&... extra) {
        init.template execute<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob's avatar
Wenzel Jakob committed
802
803
804
        return *this;
    }

805
    template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob's avatar
Wenzel Jakob committed
806
807
808
        struct capture { Func func; };
        capture *ptr = new capture { std::forward<Func>(func) };
        install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Wenzel Jakob's avatar
Wenzel Jakob committed
809
810
811
            detail::type_caster<type> caster;
            if (!caster.load(obj, false))
                return nullptr;
Wenzel Jakob's avatar
Wenzel Jakob committed
812
813
            return new buffer_info(((capture *) ptr)->func(caster));
        }, ptr);
Wenzel Jakob's avatar
Wenzel Jakob committed
814
815
816
        return *this;
    }

817
818
819
820
    template <typename C, typename D, typename... Extra>
    class_ &def_readwrite(const char *name, D C::*pm, Extra&&... extra) {
        cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; },
                          return_value_policy::reference_internal,
821
                          is_method(this), extra...),
822
                     fset([pm](C &c, const D &value) { c.*pm = value; },
823
                          is_method(this), extra...);
824
        def_property(name, fget, fset);
Wenzel Jakob's avatar
Wenzel Jakob committed
825
826
827
        return *this;
    }

828
829
830
831
    template <typename C, typename D, typename... Extra>
    class_ &def_readonly(const char *name, const D C::*pm, Extra&& ...extra) {
        cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; },
                          return_value_policy::reference_internal,
832
                          is_method(this), std::forward<Extra>(extra)...);
833
        def_property_readonly(name, fget);
Wenzel Jakob's avatar
Wenzel Jakob committed
834
835
836
        return *this;
    }

837
838
    template <typename D, typename... Extra>
    class_ &def_readwrite_static(const char *name, D *pm, Extra&& ...extra) {
839
        cpp_function fget([pm](object) -> const D &{ return *pm; }, nullptr,
840
841
842
                          return_value_policy::reference_internal, extra...),
                     fset([pm](object, const D &value) { *pm = value; }, extra...);
        def_property_static(name, fget, fset);
Wenzel Jakob's avatar
Wenzel Jakob committed
843
844
845
        return *this;
    }

846
847
    template <typename D, typename... Extra>
    class_ &def_readonly_static(const char *name, const D *pm, Extra&& ...extra) {
848
        cpp_function fget([pm](object) -> const D &{ return *pm; }, nullptr,
849
850
                          return_value_policy::reference_internal, std::forward<Extra>(extra)...);
        def_property_readonly_static(name, fget);
Wenzel Jakob's avatar
Wenzel Jakob committed
851
852
853
        return *this;
    }

854
855
    class_ &def_property_readonly(const char *name, const cpp_function &fget, const char *doc = nullptr) {
        def_property(name, fget, cpp_function(), doc);
Wenzel Jakob's avatar
Wenzel Jakob committed
856
857
858
        return *this;
    }

859
860
    class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const char *doc = nullptr) {
        def_property_static(name, fget, cpp_function(), doc);
Wenzel Jakob's avatar
Wenzel Jakob committed
861
862
863
        return *this;
    }

864
    class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const char *doc = nullptr) {
865
        object doc_obj = doc ? pybind11::str(doc) : (object) const_cast<cpp_function&>(fget).attr("__doc__");
Wenzel Jakob's avatar
Wenzel Jakob committed
866
867
        object property(
            PyObject_CallFunction((PyObject *)&PyProperty_Type,
868
                                  const_cast<char *>("OOOO"), fget.ptr() ? fget.ptr() : Py_None,
869
                                  fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr()), false);
Wenzel Jakob's avatar
Wenzel Jakob committed
870
871
872
873
        attr(name) = property;
        return *this;
    }

874
    class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const char *doc = nullptr) {
875
        object doc_obj = doc ? pybind11::str(doc) : (object) const_cast<cpp_function&>(fget).attr("__doc__");
Wenzel Jakob's avatar
Wenzel Jakob committed
876
877
        object property(
            PyObject_CallFunction((PyObject *)&PyProperty_Type,
878
879
                                  const_cast<char *>("OOOs"), fget.ptr() ? fget.ptr() : Py_None,
                                  fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr()), false);
Wenzel Jakob's avatar
Wenzel Jakob committed
880
881
882
        metaclass().attr(name) = property;
        return *this;
    }
883
884

    template <typename target> class_ alias() {
885
        auto &instances = pybind11::detail::get_internals().registered_types;
886
887
888
        instances[&typeid(target)] = instances[&typeid(type)];
        return *this;
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
889
private:
890
891
892
    /// Initialize holder object, variant 1: object derives from enable_shared_from_this
    template <typename T>
    static void init_holder_helper(instance_type *inst, const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
893
        try {
894
            new (&inst->holder) holder_type(inst->value->shared_from_this());
895
896
897
        } catch (const std::bad_weak_ptr &) {
            new (&inst->holder) holder_type(inst->value);
        }
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
    }

    /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
    template <typename T = holder_type,
              typename std::enable_if<std::is_copy_constructible<T>::value, int>::type = 0>
    static void init_holder_helper(instance_type *inst, const holder_type *holder_ptr, const void * /* dummy */) {
        if (holder_ptr)
            new (&inst->holder) holder_type(*holder_ptr);
        else
            new (&inst->holder) holder_type(inst->value);
    }

    /// Initialize holder object, variant 3: holder is not copy constructible (e.g. unique_ptr), always initialize from raw pointer
    template <typename T = holder_type,
              typename std::enable_if<!std::is_copy_constructible<T>::value, int>::type = 0>
    static void init_holder_helper(instance_type *inst, const holder_type * /* unused */, const void * /* dummy */) {
        new (&inst->holder) holder_type(inst->value);
    }

    /// Initialize holder object of an instance, possibly given a pointer to an existing holder
    static void init_holder(PyObject *inst_, const void *holder_ptr) {
        auto inst = (instance_type *) inst_;
        init_holder_helper(inst, (const holder_type *) holder_ptr, inst->value);
921
922
923
        inst->constructed = true;
    }

Wenzel Jakob's avatar
Wenzel Jakob committed
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
    static void dealloc(PyObject *inst_) {
        instance_type *inst = (instance_type *) inst_;
        if (inst->owned) {
            if (inst->constructed)
                inst->holder.~holder_type();
            else
                ::operator delete(inst->value);
        }
        custom_type::dealloc((detail::instance<void> *) inst);
    }
};

/// Binds C++ enumerations and enumeration classes to Python
template <typename Type> class enum_ : public class_<Type> {
public:
    enum_(object &scope, const char *name, const char *doc = nullptr)
      : class_<Type>(scope, name, doc), m_parent(scope) {
        auto entries = new std::unordered_map<int, const char *>();
942
        this->def("__repr__", [name, entries](Type value) -> std::string {
Wenzel Jakob's avatar
Wenzel Jakob committed
943
            auto it = entries->find((int) value);
Wenzel Jakob's avatar
Wenzel Jakob committed
944
945
946
947
            return std::string(name) + "." +
                ((it == entries->end()) ? std::string("???")
                                        : std::string(it->second));
        });
948
        this->def("__int__", [](Type value) { return (int) value; });
Wenzel Jakob's avatar
Wenzel Jakob committed
949
950
951
952
953
954
955
        m_entries = entries;
    }

    /// Export enumeration entries into the parent scope
    void export_values() {
        PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict;
        PyObject *key, *value;
956
        ssize_t pos = 0;
Wenzel Jakob's avatar
Wenzel Jakob committed
957
958
959
960
961
962
963
        while (PyDict_Next(dict, &pos, &key, &value))
            if (PyObject_IsInstance(value, this->m_ptr))
                m_parent.attr(key) = value;
    }

    /// Add an enumeration entry
    enum_& value(char const* name, Type value) {
964
        this->attr(name) = pybind11::cast(value, return_value_policy::copy);
Wenzel Jakob's avatar
Wenzel Jakob committed
965
966
967
968
969
970
971
972
973
        (*m_entries)[(int) value] = name;
        return *this;
    }
private:
    std::unordered_map<int, const char *> *m_entries;
    object &m_parent;
};

NAMESPACE_BEGIN(detail)
974
template <typename... Args> struct init {
975
    template <typename Base, typename Holder, typename... Extra> void execute(pybind11::class_<Base, Holder> &class_, Extra&&... extra) const {
Wenzel Jakob's avatar
Wenzel Jakob committed
976
        /// Function which calls a specific C++ in-place constructor
977
        class_.def("__init__", [](Base *instance, Args... args) { new (instance) Base(args...); }, std::forward<Extra>(extra)...);
Wenzel Jakob's avatar
Wenzel Jakob committed
978
979
    }
};
980
981
982

PYBIND11_NOINLINE inline void keep_alive_impl(int Nurse, int Patient, PyObject *arg, PyObject *ret) {
    /* Clever approach based on weak references taken from Boost.Python */
983
984
    handle nurse  (Nurse   > 0 ? PyTuple_GetItem(arg, Nurse   - 1) : ret);
    handle patient(Patient > 0 ? PyTuple_GetItem(arg, Patient - 1) : ret);
985

986
987
    if (!nurse || !patient)
        throw std::runtime_error("Could not activate keep_alive!");
988
989

    cpp_function disable_lifesupport(
990
        [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
991

992
993
    weakref wr(nurse, disable_lifesupport);
    if (!wr)
994
995
        throw std::runtime_error("Could not allocate weak reference!");

996
997
    patient.inc_ref(); /* reference patient and leak the weak reference */
    (void) wr.release();
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
}

template <int Nurse, int Patient> struct process_dynamic<keep_alive<Nurse, Patient>> : public process_dynamic<void> {
    template <int N = Nurse, int P = Patient, typename std::enable_if<N != 0 && P != 0, int>::type = 0>
    static void precall(PyObject *arg) { keep_alive_impl(Nurse, Patient, arg, nullptr); }
    template <int N = Nurse, int P = Patient, typename std::enable_if<N != 0 && P != 0, int>::type = 0>
    static void postcall(PyObject *, PyObject *) { }
    template <int N = Nurse, int P = Patient, typename std::enable_if<N == 0 || P == 0, int>::type = 0>
    static void precall(PyObject *) { }
    template <int N = Nurse, int P = Patient, typename std::enable_if<N == 0 || P == 0, int>::type = 0>
    static void postcall(PyObject *arg, PyObject *ret) { keep_alive_impl(Nurse, Patient, arg, ret); }
};

Wenzel Jakob's avatar
Wenzel Jakob committed
1011
1012
1013
1014
1015
NAMESPACE_END(detail)

template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); };

template <typename InputType, typename OutputType> void implicitly_convertible() {
1016
    auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
Wenzel Jakob's avatar
Wenzel Jakob committed
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
        if (!detail::type_caster<InputType>().load(obj, false))
            return nullptr;
        tuple args(1);
        args[0] = obj;
        PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
        if (result == nullptr)
            PyErr_Clear();
        return result;
    };
    auto & registered_types = detail::get_internals().registered_types;
1027
    auto it = registered_types.find(&typeid(OutputType));
Wenzel Jakob's avatar
Wenzel Jakob committed
1028
    if (it == registered_types.end())
1029
        throw std::runtime_error("implicitly_convertible: Unable to find type " + type_id<OutputType>());
Wenzel Jakob's avatar
Wenzel Jakob committed
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
    it->second.implicit_conversions.push_back(implicit_caster);
}

inline void init_threading() { PyEval_InitThreads(); }

class gil_scoped_acquire {
    PyGILState_STATE state;
public:
    inline gil_scoped_acquire() { state = PyGILState_Ensure(); }
    inline ~gil_scoped_acquire() { PyGILState_Release(state); }
};

class gil_scoped_release {
    PyThreadState *state;
public:
    inline gil_scoped_release() { state = PyEval_SaveThread(); }
    inline ~gil_scoped_release() { PyEval_RestoreThread(state); }
};

1049
1050
inline function get_overload(const void *this_ptr, const char *name)  {
    handle py_object = detail::get_object_handle(this_ptr);
1051
1052
    if (!py_object)
        return function();
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
    handle type = py_object.get_type();
    auto key = std::make_pair(type.ptr(), name);

    /* Cache functions that aren't overloaded in python to avoid
       many costly dictionary lookups in Python */
    auto &cache = detail::get_internals().inactive_overload_cache;
    if (cache.find(key) != cache.end())
        return function();

    function overload = (function) py_object.attr(name);
    if (overload.is_cpp_function()) {
        cache.insert(key);
        return function();
    }
1067

1068
    PyFrameObject *frame = PyThreadState_Get()->frame;
1069
    pybind11::str caller = pybind11::handle(frame->f_code->co_name).str();
1070
    if ((std::string) caller == name)
1071
1072
1073
1074
        return function();
    return overload;
}

1075
#define PYBIND11_OVERLOAD_INT(ret_type, class_name, name, ...) { \
1076
1077
        pybind11::gil_scoped_acquire gil; \
        pybind11::function overload = pybind11::get_overload(this, #name); \
1078
1079
1080
        if (overload) \
            return overload.call(__VA_ARGS__).cast<ret_type>();  }

1081
1082
#define PYBIND11_OVERLOAD(ret_type, class_name, name, ...) \
    PYBIND11_OVERLOAD_INT(ret_type, class_name, name, __VA_ARGS__) \
1083
1084
    return class_name::name(__VA_ARGS__)

1085
1086
#define PYBIND11_OVERLOAD_PURE(ret_type, class_name, name, ...) \
    PYBIND11_OVERLOAD_INT(ret_type, class_name, name, __VA_ARGS__) \
1087
1088
    throw std::runtime_error("Tried to call pure virtual function \"" #name "\"");

1089
NAMESPACE_END(pybind11)
Wenzel Jakob's avatar
Wenzel Jakob committed
1090
1091
1092

#if defined(_MSC_VER)
#pragma warning(pop)
1093
#elif defined(__GNUG__) and !defined(__clang__)
1094
#pragma GCC diagnostic pop
Wenzel Jakob's avatar
Wenzel Jakob committed
1095
#endif
1096