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

5
    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakob's avatar
Wenzel Jakob committed
6
7
8
9
10

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

11
#pragma once
Wenzel Jakob's avatar
Wenzel Jakob committed
12
13

#if defined(_MSC_VER)
Wenzel Jakob's avatar
Wenzel Jakob committed
14
15
16
17
18
19
#  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
20
#elif defined(__ICC) || defined(__INTEL_COMPILER)
Ben Pritchard's avatar
Ben Pritchard committed
21
#  pragma warning(push)
22
#  pragma warning(disable:2196)  // warning #2196: routine is both "inline" and "noinline"
23
#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob's avatar
Wenzel Jakob committed
24
25
26
27
#  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
28
29
#  pragma GCC diagnostic ignored "-Wstrict-aliasing"
#  pragma GCC diagnostic ignored "-Wattributes"
Wenzel Jakob's avatar
Wenzel Jakob committed
30
31
#endif

Wenzel Jakob's avatar
Wenzel Jakob committed
32
#include "attr.h"
Wenzel Jakob's avatar
Wenzel Jakob committed
33

34
NAMESPACE_BEGIN(pybind11)
Wenzel Jakob's avatar
Wenzel Jakob committed
35

Wenzel Jakob's avatar
Wenzel Jakob committed
36
/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
37
class cpp_function : public function {
Wenzel Jakob's avatar
Wenzel Jakob committed
38
public:
39
    cpp_function() { }
Wenzel Jakob's avatar
Wenzel Jakob committed
40

41
    /// Construct a cpp_function from a vanilla function pointer
42
    template <typename Return, typename... Args, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
43
    cpp_function(Return (*f)(Args...), const Extra&... extra) {
44
        initialize(f, f, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
45
46
    }

47
    /// Construct a cpp_function from a lambda function (possibly with internal state)
Wenzel Jakob's avatar
Wenzel Jakob committed
48
    template <typename Func, typename... Extra> cpp_function(Func &&f, const Extra&... extra) {
49
        initialize(std::forward<Func>(f),
Wenzel Jakob's avatar
Wenzel Jakob committed
50
                   (typename detail::remove_class<decltype(
Wenzel Jakob's avatar
Wenzel Jakob committed
51
                       &std::remove_reference<Func>::type::operator())>::type *) nullptr, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
52
53
    }

54
55
56
    /// Construct a cpp_function from a class method (non-const)
    template <typename Return, typename Class, typename... Arg, typename... Extra>
            cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
57
        initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Wenzel Jakob's avatar
Wenzel Jakob committed
58
                   (Return (*) (Class *, Arg...)) nullptr, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
59
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
60

61
62
63
    /// Construct a cpp_function from a class method (const)
    template <typename Return, typename Class, typename... Arg, typename... Extra>
            cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
64
        initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Wenzel Jakob's avatar
Wenzel Jakob committed
65
                   (Return (*)(const Class *, Arg ...)) nullptr, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
66
67
    }

68
    /// Return the function name
Wenzel Jakob's avatar
Wenzel Jakob committed
69
    object name() const { return attr("__name__"); }
70

71
72
protected:
    /// Special internal constructor for functors, lambda functions, etc.
73
    template <typename Func, typename Return, typename... Args, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
74
    void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
75
76
77
        static_assert(detail::expected_num_args<Extra...>(sizeof...(Args)),
                      "The number of named arguments does not match the function signature");

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

80
        /* Store the function including any extra state it might have (e.g. a lambda capture object) */
Wenzel Jakob's avatar
Wenzel Jakob committed
81
        auto rec = new detail::function_record();
82

83
84
        /* Store the capture object directly in the function record if there is enough space */
        if (sizeof(capture) <= sizeof(rec->data)) {
85
86
87
            /* Without these pragmas, GCC warns that there might not be
               enough space to use the placement new operator. However, the
               'if' statement above ensures that this is the case. */
88
#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
89
90
91
#  pragma GCC diagnostic push
#  pragma GCC diagnostic ignored "-Wplacement-new"
#endif
92
            new ((capture *) &rec->data) capture { std::forward<Func>(f) };
93
#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
94
95
#  pragma GCC diagnostic pop
#endif
96
97
98
99
100
101
            if (!std::is_trivially_destructible<Func>::value)
                rec->free_data = [](detail::function_record *r) { ((capture *) &r->data)->~capture(); };
        } else {
            rec->data[0] = new capture { std::forward<Func>(f) };
            rec->free_data = [](detail::function_record *r) { delete ((capture *) r->data[0]); };
        }
102

103
104
105
106
107
        /* Type casters for the function arguments and return value */
        typedef detail::type_caster<typename std::tuple<Args...>> cast_in;
        typedef detail::type_caster<typename std::conditional<
            std::is_void<Return>::value, detail::void_type,
            typename detail::intrinsic_type<Return>::type>::type> cast_out;
Wenzel Jakob's avatar
Wenzel Jakob committed
108

109
        /* Dispatch code which converts function arguments and performs the actual function call */
110
        rec->impl = [](detail::function_record *rec, handle args, handle kwargs, handle parent) -> handle {
111
            cast_in args_converter;
112
113

            /* Try to cast the function arguments into the C++ domain */
114
            if (!args_converter.load_args(args, kwargs, true))
115
116
                return PYBIND11_TRY_NEXT_OVERLOAD;

Wenzel Jakob's avatar
Wenzel Jakob committed
117
            /* Invoke call policy pre-call hook */
118
119
120
121
122
            detail::process_attributes<Extra...>::precall(args);

            /* Get a pointer to the capture object */
            capture *cap = (capture *) (sizeof(capture) <= sizeof(rec->data)
                                        ? &rec->data : rec->data[0]);
123

124
            /* Perform the function call */
125
126
            handle result = cast_out::cast(args_converter.template call<Return>(cap->f),
                                           rec->policy, parent);
Wenzel Jakob's avatar
Wenzel Jakob committed
127
128

            /* Invoke call policy post-call hook */
129
            detail::process_attributes<Extra...>::postcall(args, result);
130

131
            return result;
Wenzel Jakob's avatar
Wenzel Jakob committed
132
133
        };

Wenzel Jakob's avatar
Wenzel Jakob committed
134
135
        /* Process any user-provided function attributes */
        detail::process_attributes<Extra...>::init(extra..., rec);
136
137

        /* Generate a readable signature describing the function's arguments and return value types */
Wenzel Jakob's avatar
Wenzel Jakob committed
138
        using detail::descr;
Sylvain Corlay's avatar
Sylvain Corlay committed
139
        PYBIND11_DESCR signature = cast_in::name() + detail::_(" -> ") + cast_out::name();
140
141

        /* Register the function with Python from generic (non-templated) code */
142
        initialize_generic(rec, signature.text(), signature.types(), sizeof...(Args));
143
144
145

        if (cast_in::has_args) rec->has_args = true;
        if (cast_in::has_kwargs) rec->has_kwargs = true;
146
147
148
149
150
151
152
153
154
155

        /* Stash some additional information used by an important optimization in 'functional.h' */
        using FunctionType = Return (*)(Args...);
        constexpr bool is_function_ptr =
            std::is_convertible<Func, FunctionType>::value &&
            sizeof(capture) == sizeof(void *);
        if (is_function_ptr) {
            rec->is_stateless = true;
            rec->data[1] = (void *) &typeid(FunctionType);
        }
156
157
    }

158
    /// Register a function call with Python (generic non-templated code goes here)
159
    void initialize_generic(detail::function_record *rec, const char *text,
160
                            const std::type_info *const *types, size_t args) {
Wenzel Jakob's avatar
Wenzel Jakob committed
161

162
        /* Create copies of all referenced C-style strings */
Wenzel Jakob's avatar
Wenzel Jakob committed
163
164
165
        rec->name = strdup(rec->name ? rec->name : "");
        if (rec->doc) rec->doc = strdup(rec->doc);
        for (auto &a: rec->args) {
166
167
168
169
170
            if (a.name)
                a.name = strdup(a.name);
            if (a.descr)
                a.descr = strdup(a.descr);
            else if (a.value)
171
                a.descr = strdup(((std::string) ((object) handle(a.value).attr("__repr__"))().str()).c_str());
172
        }
173

174
        auto const &registered_types = detail::get_internals().registered_types_cpp;
175
176
177
178
179
180
181
182
183
184

        /* 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 == '{') {
185
186
187
188
189
190
191
192
193
194
                // Write arg name for everything except *args, **kwargs and return type.
                if (type_depth == 1 && text[char_index] != '*' && arg_index < args) {
                    if (!rec->args.empty()) {
                        signature += rec->args[arg_index].name;
                    } else if (arg_index == 0 && rec->class_) {
                        signature += "self";
                    } else {
                        signature += "arg" + std::to_string(arg_index - (rec->class_ ? 1 : 0));
                    }
                    signature += ": ";
195
196
197
198
                }
                ++type_depth;
            } else if (c == '}') {
                --type_depth;
199
200
201
                if (type_depth == 1) {
                    if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
                        signature += "=";
Wenzel Jakob's avatar
Wenzel Jakob committed
202
                        signature += rec->args[arg_index].descr;
203
204
205
206
207
                    }
                    arg_index++;
                }
            } else if (c == '%') {
                const std::type_info *t = types[type_index++];
208
                if (!t)
209
                    pybind11_fail("Internal error while parsing type signature (1)");
210
                auto it = registered_types.find(std::type_index(*t));
211
                if (it != registered_types.end()) {
212
                    signature += ((const detail::type_info *) it->second)->type->tp_name;
213
214
215
216
217
218
219
220
221
                } else {
                    std::string tname(t->name());
                    detail::clean_type_id(tname);
                    signature += tname;
                }
            } else {
                signature += c;
            }
        }
222
        if (type_depth != 0 || types[type_index] != nullptr)
223
            pybind11_fail("Internal error while parsing type signature (2)");
224
225
226
227
228

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

230
#if PY_MAJOR_VERSION < 3
Wenzel Jakob's avatar
Wenzel Jakob committed
231
232
233
        if (strcmp(rec->name, "__next__") == 0) {
            std::free(rec->name);
            rec->name = strdup("next");
234
235
236
        } else if (strcmp(rec->name, "__bool__") == 0) {
            std::free(rec->name);
            rec->name = strdup("__nonzero__");
237
        }
238
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
239
240
        rec->signature = strdup(signature.c_str());
        rec->args.shrink_to_fit();
241
        rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
242
        rec->is_stateless = false;
243
244
        rec->has_args = false;
        rec->has_kwargs = false;
245
        rec->nargs = (uint16_t) args;
246
247

#if PY_MAJOR_VERSION < 3
Wenzel Jakob's avatar
Wenzel Jakob committed
248
249
        if (rec->sibling && PyMethod_Check(rec->sibling.ptr()))
            rec->sibling = PyMethod_GET_FUNCTION(rec->sibling.ptr());
250
#endif
251

Wenzel Jakob's avatar
Wenzel Jakob committed
252
253
254
255
        detail::function_record *chain = nullptr, *chain_start = rec;
        if (rec->sibling && PyCFunction_Check(rec->sibling.ptr())) {
            capsule rec_capsule(PyCFunction_GetSelf(rec->sibling.ptr()), true);
            chain = (detail::function_record *) rec_capsule;
256
257
            /* Never append a method to an overload chain of a parent class;
               instead, hide the parent's overloads in this case */
Wenzel Jakob's avatar
Wenzel Jakob committed
258
259
            if (chain->class_ != rec->class_)
                chain = nullptr;
260
261
        }

Wenzel Jakob's avatar
Wenzel Jakob committed
262
        if (!chain) {
263
            /* No existing overload was found, create a new function object */
Wenzel Jakob's avatar
Wenzel Jakob committed
264
265
266
267
268
            rec->def = new PyMethodDef();
            memset(rec->def, 0, sizeof(PyMethodDef));
            rec->def->ml_name = rec->name;
            rec->def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
            rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
269

Wenzel Jakob's avatar
Wenzel Jakob committed
270
271
            capsule rec_capsule(rec, [](PyObject *o) {
                destruct((detail::function_record *) PyCapsule_GetPointer(o, nullptr));
272
            });
273
274
275
276
277
278
279
280
281

            object scope_module;
            if (rec->scope) {
                scope_module = (object) rec->scope.attr("__module__");
                if (!scope_module)
                    scope_module = (object) rec->scope.attr("__name__");
            }

            m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
Wenzel Jakob's avatar
Wenzel Jakob committed
282
            if (!m_ptr)
283
                pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob's avatar
Wenzel Jakob committed
284
        } else {
285
            /* Append at the end of the overload chain */
Wenzel Jakob's avatar
Wenzel Jakob committed
286
            m_ptr = rec->sibling.ptr();
Wenzel Jakob's avatar
Wenzel Jakob committed
287
            inc_ref();
Wenzel Jakob's avatar
Wenzel Jakob committed
288
289
290
291
            chain_start = chain;
            while (chain->next)
                chain = chain->next;
            chain->next = rec;
Wenzel Jakob's avatar
Wenzel Jakob committed
292
        }
293

Wenzel Jakob's avatar
Wenzel Jakob committed
294
        std::string signatures;
295
        int index = 0;
Wenzel Jakob's avatar
Wenzel Jakob committed
296
        /* Create a nice pydoc rec including all signatures and
297
           docstrings of the functions in the overload chain */
298
299
300
301
302
303
304
        if (chain) {
            // First a generic signature
            signatures += rec->name;
            signatures += "(*args, **kwargs)\n";
            signatures += "Overloaded function.\n\n";
        }
        // Then specific overload signatures
Wenzel Jakob's avatar
Wenzel Jakob committed
305
306
        for (auto it = chain_start; it != nullptr; it = it->next) {
            if (chain)
307
                signatures += std::to_string(++index) + ". ";
308
            signatures += rec->name;
309
310
311
312
            signatures += it->signature;
            signatures += "\n";
            if (it->doc && strlen(it->doc) > 0) {
                signatures += "\n";
313
                signatures += it->doc;
314
315
                signatures += "\n";
            }
316
            if (it->next)
Wenzel Jakob's avatar
Wenzel Jakob committed
317
318
                signatures += "\n";
        }
Wenzel Jakob's avatar
Wenzel Jakob committed
319
320

        /* Install docstring */
Wenzel Jakob's avatar
Wenzel Jakob committed
321
322
        PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
        if (func->m_ml->ml_doc)
323
            std::free((char *) func->m_ml->ml_doc);
Wenzel Jakob's avatar
Wenzel Jakob committed
324
        func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob's avatar
Wenzel Jakob committed
325
326
327

        if (rec->class_) {
            m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->class_.ptr());
Wenzel Jakob's avatar
Wenzel Jakob committed
328
            if (!m_ptr)
329
                pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob's avatar
Wenzel Jakob committed
330
331
332
            Py_DECREF(func);
        }
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
333
334
335
336
337
338

    /// When a cpp_function is GCed, release any memory allocated by pybind11
    static void destruct(detail::function_record *rec) {
        while (rec) {
            detail::function_record *next = rec->next;
            if (rec->free_data)
339
                rec->free_data(rec);
Wenzel Jakob's avatar
Wenzel Jakob committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
            std::free((char *) rec->name);
            std::free((char *) rec->doc);
            std::free((char *) rec->signature);
            for (auto &arg: rec->args) {
                std::free((char *) arg.name);
                std::free((char *) arg.descr);
                arg.value.dec_ref();
            }
            if (rec->def) {
                std::free((char *) rec->def->ml_doc);
                delete rec->def;
            }
            delete rec;
            rec = next;
        }
    }

    /// Main dispatch logic for calls to functions bound using pybind11
    static PyObject *dispatcher(PyObject *self, PyObject *args, PyObject *kwargs) {
        /* Iterator over the list of potentially admissible overloads */
        detail::function_record *overloads = (detail::function_record *) PyCapsule_GetPointer(self, nullptr),
                                *it = overloads;

        /* Need to know how many arguments + keyword arguments there are to pick the right overload */
364
365
        size_t nargs = (size_t) PyTuple_GET_SIZE(args),
               nkwargs = kwargs ? (size_t) PyDict_Size(kwargs) : 0;
Wenzel Jakob's avatar
Wenzel Jakob committed
366

367
        handle parent = nargs > 0 ? PyTuple_GET_ITEM(args, 0) : nullptr,
Wenzel Jakob's avatar
Wenzel Jakob committed
368
369
370
371
               result = PYBIND11_TRY_NEXT_OVERLOAD;
        try {
            for (; it != nullptr; it = it->next) {
                tuple args_(args, true);
372
                size_t kwargs_consumed = 0;
Wenzel Jakob's avatar
Wenzel Jakob committed
373
374
375
376
377
378
379
380

                /* For each overload:
                   1. If the required list of arguments is longer than the
                      actually provided amount, create a copy of the argument
                      list and fill in any available keyword/default arguments.
                   2. Ensure that all keyword arguments were "consumed"
                   3. Call the function call dispatcher (function_record::impl)
                 */
381
382
383
384
385
                size_t nargs_ = nargs;
                if (nargs < it->args.size()) {
                    nargs_ = it->args.size();
                    args_ = tuple(nargs_);
                    for (size_t i = 0; i < nargs; ++i) {
Wenzel Jakob's avatar
Wenzel Jakob committed
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
                        handle item = PyTuple_GET_ITEM(args, i);
                        PyTuple_SET_ITEM(args_.ptr(), i, item.inc_ref().ptr());
                    }

                    int arg_ctr = 0;
                    for (auto const &it2 : it->args) {
                        int index = arg_ctr++;
                        if (PyTuple_GET_ITEM(args_.ptr(), index))
                            continue;

                        handle value;
                        if (kwargs)
                            value = PyDict_GetItemString(kwargs, it2.name);

                        if (value)
                            kwargs_consumed++;
                        else if (it2.value)
                            value = it2.value;

                        if (value) {
                            PyTuple_SET_ITEM(args_.ptr(), index, value.inc_ref().ptr());
                        } else {
408
                            kwargs_consumed = (size_t) -1; /* definite failure */
Wenzel Jakob's avatar
Wenzel Jakob committed
409
410
411
412
                            break;
                        }
                    }
                }
413
414

                try {
415
416
417
                    if ((kwargs_consumed == nkwargs || it->has_kwargs) &&
                        (nargs_ == it->nargs || it->has_args))
                        result = it->impl(it, args_, kwargs, parent);
418
                } catch (reference_cast_error &) {
419
420
                    result = PYBIND11_TRY_NEXT_OVERLOAD;
                }
Wenzel Jakob's avatar
Wenzel Jakob committed
421
422
423
424

                if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
                    break;
            }
425
426
        } catch (const error_already_set &) {
            return nullptr;
Wenzel Jakob's avatar
Wenzel Jakob committed
427
        } catch (...) {
428
429
430
            /* When an exception is caught, give each registered exception
               translator a chance to translate it to a Python exception
               in reverse order of registration.
431

432
               A translator may choose to do one of the following:
433

434
435
436
437
438
                - catch the exception and call PyErr_SetString or PyErr_SetObject
                  to set a standard (or custom) Python exception, or
                - do nothing and let the exception fall through to the next translator, or
                - delegate translation to the next translator by throwing a new type of exception. */

439
            auto last_exception = std::current_exception();
440
441
442
443
444
445
446
447
448
449
450
            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 nullptr;
            }
            PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
Wenzel Jakob's avatar
Wenzel Jakob committed
451
452
453
454
            return nullptr;
        }

        if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
455
456
            std::string msg = "Incompatible " + std::string(overloads->is_constructor ? "constructor" : "function") +
                              " arguments. The following argument types are supported:\n";
Wenzel Jakob's avatar
Wenzel Jakob committed
457
458
459
            int ctr = 0;
            for (detail::function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
                msg += "    "+ std::to_string(++ctr) + ". ";
460
461
462

                bool wrote_sig = false;
                if (overloads->is_constructor) {
463
                    // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
464
                    std::string sig = it2->signature;
465
                    size_t start = sig.find('(') + 7; // skip "(self: "
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
                    if (start < sig.size()) {
                        // End at the , for the next argument
                        size_t end = sig.find(", "), next = end + 2;
                        size_t ret = sig.rfind(" -> ");
                        // Or the ), if there is no comma:
                        if (end >= sig.size()) next = end = sig.find(')');
                        if (start < end && next < sig.size()) {
                            msg.append(sig, start, end - start);
                            msg += '(';
                            msg.append(sig, next, ret - next);
                            wrote_sig = true;
                        }
                    }
                }
                if (!wrote_sig) msg += it2->signature;

Wenzel Jakob's avatar
Wenzel Jakob committed
482
483
                msg += "\n";
            }
484
485
            msg += "    Invoked with: ";
            tuple args_(args, true);
486
            for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
487
488
489
490
                msg += static_cast<std::string>(static_cast<object>(args_[ti]).str());
                if ((ti + 1) != args_.size() )
                    msg += ", ";
            }
Wenzel Jakob's avatar
Wenzel Jakob committed
491
492
493
494
495
496
497
498
499
500
            PyErr_SetString(PyExc_TypeError, msg.c_str());
            return nullptr;
        } else if (!result) {
            std::string msg = "Unable to convert function return value to a "
                              "Python type! The signature was\n\t";
            msg += it->signature;
            PyErr_SetString(PyExc_TypeError, msg.c_str());
            return nullptr;
        } else {
            if (overloads->is_constructor) {
501
                /* When a constructor ran successfully, the corresponding
Wenzel Jakob's avatar
Wenzel Jakob committed
502
                   holder type (e.g. std::unique_ptr) must still be initialized. */
503
                PyObject *inst = PyTuple_GET_ITEM(args, 0);
Wenzel Jakob's avatar
Wenzel Jakob committed
504
505
506
507
508
509
                auto tinfo = detail::get_type_info(Py_TYPE(inst));
                tinfo->init_holder(inst, nullptr);
            }
            return result.ptr();
        }
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
510
511
};

512
/// Wrapper for Python extension modules
Wenzel Jakob's avatar
Wenzel Jakob committed
513
514
class module : public object {
public:
515
    PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob's avatar
Wenzel Jakob committed
516
517

    module(const char *name, const char *doc = nullptr) {
518
#if PY_MAJOR_VERSION >= 3
Wenzel Jakob's avatar
Wenzel Jakob committed
519
520
521
522
523
524
525
        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);
526
527
528
#else
        m_ptr = Py_InitModule3(name, nullptr, doc);
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
529
        if (m_ptr == nullptr)
530
            pybind11_fail("Internal error in module::module()");
Wenzel Jakob's avatar
Wenzel Jakob committed
531
532
533
        inc_ref();
    }

534
    template <typename Func, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
535
    module &def(const char *name_, Func &&f, const Extra& ... extra) {
536
        cpp_function func(std::forward<Func>(f), name(name_),
537
                          sibling((handle) attr(name_)), scope(*this), extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
538
539
        /* PyModule_AddObject steals a reference to 'func' */
        PyModule_AddObject(ptr(), name_, func.inc_ref().ptr());
Wenzel Jakob's avatar
Wenzel Jakob committed
540
541
542
        return *this;
    }

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

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

NAMESPACE_BEGIN(detail)
Wenzel Jakob's avatar
Wenzel Jakob committed
562
/// Generic support for creating new Python heap types
563
class generic_type : public object {
564
    template <typename type, typename holder_type, typename type_alias> friend class class_;
Wenzel Jakob's avatar
Wenzel Jakob committed
565
public:
566
    PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
Wenzel Jakob's avatar
Wenzel Jakob committed
567
568
569
570
571
572
573
574
575
576
577
578
579
protected:
    void initialize(type_record *rec) {
        if (rec->base_type) {
            if (rec->base_handle)
                pybind11_fail("generic_type: specified base type multiple times!");
            rec->base_handle = detail::get_type_handle(*(rec->base_type));
            if (!rec->base_handle) {
                std::string tname(rec->base_type->name());
                detail::clean_type_id(tname);
                pybind11_fail("generic_type: type \"" + std::string(rec->name) +
                              "\" referenced unknown base type \"" + tname + "\"");
            }
        }
580

581
582
583
584
585
586
587
588
        auto &internals = get_internals();
        auto tindex = std::type_index(*(rec->type));

        if (internals.registered_types_cpp.find(tindex) !=
            internals.registered_types_cpp.end())
            pybind11_fail("generic_type: type \"" + std::string(rec->name) +
                          "\" is already registered!");

Wenzel Jakob's avatar
Wenzel Jakob committed
589
        object name(PYBIND11_FROM_STRING(rec->name), false);
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
        object scope_module;
        if (rec->scope) {
            scope_module = (object) rec->scope.attr("__module__");
            if (!scope_module)
                scope_module = (object) rec->scope.attr("__name__");
        }

#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
        /* Qualified names for Python >= 3.3 */
        object scope_qualname;
        if (rec->scope)
            scope_qualname = (object) rec->scope.attr("__qualname__");
        object ht_qualname;
        if (scope_qualname) {
            ht_qualname = object(PyUnicode_FromFormat(
                "%U.%U", scope_qualname.ptr(), name.ptr()), false);
        } else {
            ht_qualname = name;
        }
#endif
        std::string full_name = (scope_module ? ((std::string) scope_module.str() + "." + rec->name)
                                              : std::string(rec->name));

        char *tp_doc = nullptr;
        if (rec->doc) {
            /* Allocate memory for docstring (using PyObject_MALLOC, since
               Python will free this later on) */
            size_t size = strlen(rec->doc) + 1;
            tp_doc = (char *) PyObject_MALLOC(size);
            memcpy((void *) tp_doc, rec->doc, size);
        }

        object type_holder(PyType_Type.tp_alloc(&PyType_Type, 0), false);
623
624
625
        auto type = (PyHeapTypeObject*) type_holder.ptr();

        if (!type_holder || !name)
626
            pybind11_fail("generic_type: unable to create type object!");
627
628
629
630

        /* Register supplemental type information in C++ dict */
        detail::type_info *tinfo = new detail::type_info();
        tinfo->type = (PyTypeObject *) type;
Wenzel Jakob's avatar
Wenzel Jakob committed
631
632
        tinfo->type_size = rec->type_size;
        tinfo->init_holder = rec->init_holder;
633
        internals.registered_types_cpp[tindex] = tinfo;
634
635
636
637
        internals.registered_types_py[type] = tinfo;

        /* Basic type attributes */
        type->ht_type.tp_name = strdup(full_name.c_str());
638
        type->ht_type.tp_basicsize = (ssize_t) rec->instance_size;
Wenzel Jakob's avatar
Wenzel Jakob committed
639
640
        type->ht_type.tp_base = (PyTypeObject *) rec->base_handle.ptr();
        rec->base_handle.inc_ref();
641

642
643
        type->ht_name = name.release().ptr();

644
#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
645
        type->ht_qualname = ht_qualname.release().ptr();
646
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
647

648
649
650
651
        /* Supported protocols */
        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;
Wenzel Jakob's avatar
Wenzel Jakob committed
652

653
        /* Supported elementary operations */
Wenzel Jakob's avatar
Wenzel Jakob committed
654
655
        type->ht_type.tp_init = (initproc) init;
        type->ht_type.tp_new = (newfunc) new_instance;
Wenzel Jakob's avatar
Wenzel Jakob committed
656
        type->ht_type.tp_dealloc = rec->dealloc;
657
658

        /* Support weak references (needed for the keep_alive feature) */
659
        type->ht_type.tp_weaklistoffset = offsetof(instance_essentials<void>, weakrefs);
660
661
662

        /* Flags */
        type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
663
664
665
#if PY_MAJOR_VERSION < 3
        type->ht_type.tp_flags |= Py_TPFLAGS_CHECKTYPES;
#endif
666
        type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
667

668
        type->ht_type.tp_doc = tp_doc;
Wenzel Jakob's avatar
Wenzel Jakob committed
669
670

        if (PyType_Ready(&type->ht_type) < 0)
671
            pybind11_fail("generic_type: PyType_Ready failed!");
672
673

        m_ptr = type_holder.ptr();
Wenzel Jakob's avatar
Wenzel Jakob committed
674

675
        if (scope_module) // Needed by pydoc
Wenzel Jakob's avatar
Wenzel Jakob committed
676
            attr("__module__") = scope_module;
Wenzel Jakob's avatar
Wenzel Jakob committed
677

678
        /* Register type with the parent scope */
679
680
        if (rec->scope)
            rec->scope.attr(handle(type->ht_name)) = *this;
Wenzel Jakob's avatar
Wenzel Jakob committed
681

682
        type_holder.release();
Wenzel Jakob's avatar
Wenzel Jakob committed
683
684
    }

685
    /// Allocate a metaclass on demand (for static properties)
Wenzel Jakob's avatar
Wenzel Jakob committed
686
687
    handle metaclass() {
        auto &ht_type = ((PyHeapTypeObject *) m_ptr)->ht_type;
688
        auto &ob_type = PYBIND11_OB_TYPE(ht_type);
689

Wenzel Jakob's avatar
Wenzel Jakob committed
690
        if (ob_type == &PyType_Type) {
691
            std::string name_ = std::string(ht_type.tp_name) + "__Meta";
692
693
694
695
#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
            object ht_qualname(PyUnicode_FromFormat(
                "%U__Meta", ((object) attr("__qualname__")).ptr()), false);
#endif
696
            object name(PYBIND11_FROM_STRING(name_.c_str()), false);
697
            object type_holder(PyType_Type.tp_alloc(&PyType_Type, 0), false);
698
            if (!type_holder || !name)
699
                pybind11_fail("generic_type::metaclass(): unable to create type object!");
700
701

            auto type = (PyHeapTypeObject*) type_holder.ptr();
Wenzel Jakob's avatar
Wenzel Jakob committed
702
            type->ht_name = name.release().ptr();
703

Wenzel Jakob's avatar
Wenzel Jakob committed
704
705
#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
            /* Qualified names for Python >= 3.3 */
706
            type->ht_qualname = ht_qualname.release().ptr();
Wenzel Jakob's avatar
Wenzel Jakob committed
707
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
708
            type->ht_type.tp_name = strdup(name_.c_str());
Wenzel Jakob's avatar
Wenzel Jakob committed
709
            type->ht_type.tp_base = ob_type;
710
711
712
            type->ht_type.tp_flags |= (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE) &
                                      ~Py_TPFLAGS_HAVE_GC;

Wenzel Jakob's avatar
Wenzel Jakob committed
713
            if (PyType_Ready(&type->ht_type) < 0)
714
                pybind11_fail("generic_type::metaclass(): PyType_Ready failed!");
715

Wenzel Jakob's avatar
Wenzel Jakob committed
716
            ob_type = (PyTypeObject *) type_holder.release().ptr();
Wenzel Jakob's avatar
Wenzel Jakob committed
717
718
719
720
721
722
723
724
725
726
727
        }
        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 *) {
728
729
730
        instance<void> *self = (instance<void> *) PyType_GenericAlloc((PyTypeObject *) type, 0);
        auto tinfo = detail::get_type_info(type);
        self->value = ::operator new(tinfo->type_size);
Wenzel Jakob's avatar
Wenzel Jakob committed
731
732
733
734
735
736
737
738
739
740
741
742
743
744
        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())
745
                    pybind11_fail("generic_type::dealloc(): Tried to deallocate unregistered instance!");
Wenzel Jakob's avatar
Wenzel Jakob committed
746
747
748
                registered_instances.erase(it);
            }
            Py_XDECREF(self->parent);
749
750
            if (self->weakrefs)
                PyObject_ClearWeakRefs((PyObject *) self);
Wenzel Jakob's avatar
Wenzel Jakob committed
751
752
753
754
        }
        Py_TYPE(self)->tp_free((PyObject*) self);
    }

Wenzel Jakob's avatar
Wenzel Jakob committed
755
756
757
    void install_buffer_funcs(
            buffer_info *(*get_buffer)(PyObject *, void *),
            void *get_buffer_data) {
Wenzel Jakob's avatar
Wenzel Jakob committed
758
759
        PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
        type->ht_type.tp_as_buffer = &type->as_buffer;
760
761
762
#if PY_MAJOR_VERSION < 3
        type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
763
764
        type->as_buffer.bf_getbuffer = getbuffer;
        type->as_buffer.bf_releasebuffer = releasebuffer;
765
766
767
        auto tinfo = detail::get_type_info(&type->ht_type);
        tinfo->get_buffer = get_buffer;
        tinfo->get_buffer_data = get_buffer_data;
Wenzel Jakob's avatar
Wenzel Jakob committed
768
769
770
    }

    static int getbuffer(PyObject *obj, Py_buffer *view, int flags) {
771
772
773
        auto tinfo = detail::get_type_info(Py_TYPE(obj));
        if (view == nullptr || obj == nullptr || !tinfo || !tinfo->get_buffer) {
            PyErr_SetString(PyExc_BufferError, "generic_type::getbuffer(): Internal error");
Wenzel Jakob's avatar
Wenzel Jakob committed
774
775
776
            return -1;
        }
        memset(view, 0, sizeof(Py_buffer));
777
        buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
Wenzel Jakob's avatar
Wenzel Jakob committed
778
779
780
781
        view->obj = obj;
        view->ndim = 1;
        view->internal = info;
        view->buf = info->ptr;
782
        view->itemsize = (ssize_t) info->itemsize;
Wenzel Jakob's avatar
Wenzel Jakob committed
783
784
785
786
787
788
        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) {
789
            view->ndim = (int) info->ndim;
790
791
            view->strides = (ssize_t *) &info->strides[0];
            view->shape = (ssize_t *) &info->shape[0];
Wenzel Jakob's avatar
Wenzel Jakob committed
792
793
794
795
796
797
798
799
800
        }
        Py_INCREF(view->obj);
        return 0;
    }

    static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; }
};
NAMESPACE_END(detail)

801
template <typename type, typename holder_type = std::unique_ptr<type>, typename type_alias = type>
Wenzel Jakob's avatar
Wenzel Jakob committed
802
class class_ : public detail::generic_type {
Wenzel Jakob's avatar
Wenzel Jakob committed
803
804
805
public:
    typedef detail::instance<type, holder_type> instance_type;

806
    PYBIND11_OBJECT(class_, detail::generic_type, PyType_Check)
Wenzel Jakob's avatar
Wenzel Jakob committed
807

Wenzel Jakob's avatar
Wenzel Jakob committed
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
    template <typename... Extra>
    class_(handle scope, const char *name, const Extra &... extra) {
        detail::type_record record;
        record.scope = scope;
        record.name = name;
        record.type = &typeid(type);
        record.type_size = sizeof(type);
        record.instance_size = sizeof(instance_type);
        record.init_holder = init_holder;
        record.dealloc = dealloc;

        /* Process optional arguments, if any */
        detail::process_attributes<Extra...>::init(extra..., &record);

        detail::generic_type::initialize(&record);
823
824
825
826
827

        if (!std::is_same<type, type_alias>::value) {
            auto &instances = pybind11::detail::get_internals().registered_types_cpp;
            instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
        }
Wenzel Jakob's avatar
Wenzel Jakob committed
828
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
829

830
    template <typename Func, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
831
    class_ &def(const char *name_, Func&& f, const Extra&... extra) {
832
        cpp_function cf(std::forward<Func>(f), name(name_),
Wenzel Jakob's avatar
Wenzel Jakob committed
833
834
                        sibling(attr(name_)), is_method(*this),
                        extra...);
835
        attr(cf.name()) = cf;
Wenzel Jakob's avatar
Wenzel Jakob committed
836
837
838
        return *this;
    }

839
    template <typename Func, typename... Extra> class_ &
Wenzel Jakob's avatar
Wenzel Jakob committed
840
    def_static(const char *name_, Func f, const Extra&... extra) {
841
        cpp_function cf(std::forward<Func>(f), name(name_),
842
                        sibling(attr(name_)), scope(*this), extra...);
843
        attr(cf.name()) = cf;
Wenzel Jakob's avatar
Wenzel Jakob committed
844
845
846
        return *this;
    }

847
    template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
848
    class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Wenzel Jakob's avatar
Wenzel Jakob committed
849
        op.template execute<type>(*this, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
850
851
852
        return *this;
    }

853
    template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
854
    class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Wenzel Jakob's avatar
Wenzel Jakob committed
855
        op.template execute_cast<type>(*this, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
856
857
858
        return *this;
    }

859
    template <typename... Args, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
860
    class_ &def(const detail::init<Args...> &init, const Extra&... extra) {
Wenzel Jakob's avatar
Wenzel Jakob committed
861
        init.template execute<type>(*this, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
862
863
864
        return *this;
    }

865
866
867
868
869
870
    template <typename... Args, typename... Extra>
    class_ &def(const detail::init_alias<Args...> &init, const Extra&... extra) {
        init.template execute<type>(*this, extra...);
        return *this;
    }

871
    template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob's avatar
Wenzel Jakob committed
872
873
874
        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
875
876
877
            detail::type_caster<type> caster;
            if (!caster.load(obj, false))
                return nullptr;
Wenzel Jakob's avatar
Wenzel Jakob committed
878
879
            return new buffer_info(((capture *) ptr)->func(caster));
        }, ptr);
Wenzel Jakob's avatar
Wenzel Jakob committed
880
881
882
        return *this;
    }

883
    template <typename C, typename D, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
884
    class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
885
886
887
        cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this)),
                     fset([pm](C &c, const D &value) { c.*pm = value; }, is_method(*this));
        def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
888
889
890
        return *this;
    }

891
    template <typename C, typename D, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
892
    class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
893
894
        cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this));
        def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
895
896
897
        return *this;
    }

898
    template <typename D, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
899
    class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
900
901
902
        cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
                     fset([pm](object, const D &value) { *pm = value; }, scope(*this));
        def_property_static(name, fget, fset, return_value_policy::reference, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
903
904
905
        return *this;
    }

906
    template <typename D, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
907
    class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
908
909
        cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
        def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
910
911
912
        return *this;
    }

913
914
915
    template <typename... Extra>
    class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
        def_property(name, fget, cpp_function(), extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
916
917
918
        return *this;
    }

919
920
921
    template <typename... Extra>
    class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
        def_property_static(name, fget, cpp_function(), extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
922
923
924
        return *this;
    }

925
926
    template <typename... Extra>
    class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
927
        return def_property_static(name, fget, fset, is_method(*this), extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
928
929
    }

930
931
932
    template <typename... Extra>
    class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
        auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
933
        char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
934
        detail::process_attributes<Extra...>::init(extra..., rec_fget);
935
936
937
938
939
940
        if (rec_fget->doc && rec_fget->doc != doc_prev) {
            free(doc_prev);
            rec_fget->doc = strdup(rec_fget->doc);
        }
        if (rec_fset) {
            doc_prev = rec_fset->doc;
941
            detail::process_attributes<Extra...>::init(extra..., rec_fset);
942
943
944
945
946
            if (rec_fset->doc && rec_fset->doc != doc_prev) {
                free(doc_prev);
                rec_fset->doc = strdup(rec_fset->doc);
            }
        }
947
        pybind11::str doc_obj = pybind11::str(rec_fget->doc ? rec_fget->doc : "");
Wenzel Jakob's avatar
Wenzel Jakob committed
948
        object property(
Wenzel Jakob's avatar
Wenzel Jakob committed
949
950
            PyObject_CallFunctionObjArgs((PyObject *) &PyProperty_Type, fget.ptr() ? fget.ptr() : Py_None,
                                         fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr(), nullptr), false);
951
952
953
954
        if (rec_fget->class_)
            attr(name) = property;
        else
            metaclass().attr(name) = property;
Wenzel Jakob's avatar
Wenzel Jakob committed
955
956
        return *this;
    }
957

Wenzel Jakob's avatar
Wenzel Jakob committed
958
private:
959
960
961
    /// 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 */) {
962
        try {
963
            new (&inst->holder) holder_type(std::static_pointer_cast<typename holder_type::element_type>(inst->value->shared_from_this()));
964
965
966
        } catch (const std::bad_weak_ptr &) {
            new (&inst->holder) holder_type(inst->value);
        }
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
    }

    /// 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);
990
991
992
        inst->constructed = true;
    }

Wenzel Jakob's avatar
Wenzel Jakob committed
993
994
995
996
997
998
999
1000
    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);
        }
1001
        generic_type::dealloc((detail::instance<void> *) inst);
Wenzel Jakob's avatar
Wenzel Jakob committed
1002
    }
1003
1004
1005
1006
1007
1008

    static detail::function_record *get_function_record(handle h) {
        h = detail::get_function(h);
        return h ? (detail::function_record *) capsule(
               PyCFunction_GetSelf(h.ptr()), true) : nullptr;
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
1009
1010
1011
1012
1013
};

/// Binds C++ enumerations and enumeration classes to Python
template <typename Type> class enum_ : public class_<Type> {
public:
1014
    using UnderlyingType = typename std::underlying_type<Type>::type;
Wenzel Jakob's avatar
Wenzel Jakob committed
1015
1016
1017
    template <typename... Extra>
    enum_(const handle &scope, const char *name, const Extra&... extra)
      : class_<Type>(scope, name, extra...), m_parent(scope) {
1018
        auto entries = new std::unordered_map<UnderlyingType, const char *>();
1019
        this->def("__repr__", [name, entries](Type value) -> std::string {
1020
            auto it = entries->find((UnderlyingType) value);
Wenzel Jakob's avatar
Wenzel Jakob committed
1021
1022
1023
1024
            return std::string(name) + "." +
                ((it == entries->end()) ? std::string("???")
                                        : std::string(it->second));
        });
1025
1026
1027
        this->def("__init__", [](Type& value, UnderlyingType i) { value = (Type)i; });
        this->def("__init__", [](Type& value, UnderlyingType i) { new (&value) Type((Type) i); });
        this->def("__int__", [](Type value) { return (UnderlyingType) value; });
1028
1029
        this->def("__eq__", [](const Type &value, Type *value2) { return value2 && value == *value2; });
        this->def("__ne__", [](const Type &value, Type *value2) { return !value2 || value != *value2; });
1030
1031
1032
1033
1034
1035
1036
        if (std::is_convertible<Type, UnderlyingType>::value) {
            // Don't provide comparison with the underlying type if the enum isn't convertible,
            // i.e. if Type is a scoped enum, mirroring the C++ behaviour.  (NB: we explicitly
            // convert Type to UnderlyingType below anyway because this needs to compile).
            this->def("__eq__", [](const Type &value, UnderlyingType value2) { return (UnderlyingType) value == value2; });
            this->def("__ne__", [](const Type &value, UnderlyingType value2) { return (UnderlyingType) value != value2; });
        }
1037
        this->def("__hash__", [](const Type &value) { return (UnderlyingType) value; });
Wenzel Jakob's avatar
Wenzel Jakob committed
1038
1039
1040
1041
1042
1043
1044
        m_entries = entries;
    }

    /// Export enumeration entries into the parent scope
    void export_values() {
        PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict;
        PyObject *key, *value;
1045
        ssize_t pos = 0;
Wenzel Jakob's avatar
Wenzel Jakob committed
1046
1047
1048
1049
1050
1051
1052
        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) {
1053
        this->attr(name) = pybind11::cast(value, return_value_policy::copy);
1054
        (*m_entries)[(UnderlyingType) value] = name;
Wenzel Jakob's avatar
Wenzel Jakob committed
1055
1056
1057
        return *this;
    }
private:
1058
    std::unordered_map<UnderlyingType, const char *> *m_entries;
Wenzel Jakob's avatar
Wenzel Jakob committed
1059
    handle m_parent;
Wenzel Jakob's avatar
Wenzel Jakob committed
1060
1061
1062
};

NAMESPACE_BEGIN(detail)
1063
template <typename... Args> struct init {
1064
1065
1066
    template <typename Base, typename Holder, typename Alias, typename... Extra,
              typename std::enable_if<std::is_same<Base, Alias>::value, int>::type = 0>
    void execute(pybind11::class_<Base, Holder, Alias> &class_, const Extra&... extra) const {
Wenzel Jakob's avatar
Wenzel Jakob committed
1067
        /// Function which calls a specific C++ in-place constructor
1068
        class_.def("__init__", [](Base *self_, Args... args) { new (self_) Base(args...); }, extra...);
1069
1070
1071
1072
1073
1074
1075
    }

    template <typename Base, typename Holder, typename Alias, typename... Extra,
              typename std::enable_if<!std::is_same<Base, Alias>::value &&
                                       std::is_constructible<Base, Args...>::value, int>::type = 0>
    void execute(pybind11::class_<Base, Holder, Alias> &class_, const Extra&... extra) const {
        handle cl_type = class_;
1076
1077
1078
        class_.def("__init__", [cl_type](handle self_, Args... args) {
                if (self_.get_type() == cl_type)
                    new (self_.cast<Base *>()) Base(args...);
1079
                else
1080
                    new (self_.cast<Alias *>()) Alias(args...);
1081
1082
1083
1084
1085
1086
1087
            }, extra...);
    }

    template <typename Base, typename Holder, typename Alias, typename... Extra,
              typename std::enable_if<!std::is_same<Base, Alias>::value &&
                                      !std::is_constructible<Base, Args...>::value, int>::type = 0>
    void execute(pybind11::class_<Base, Holder, Alias> &class_, const Extra&... extra) const {
1088
        class_.def("__init__", [](Alias *self_, Args... args) { new (self_) Alias(args...); }, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1089
1090
    }
};
1091

Wenzel Jakob's avatar
Wenzel Jakob committed
1092
PYBIND11_NOINLINE inline void keep_alive_impl(int Nurse, int Patient, handle args, handle ret) {
1093
    /* Clever approach based on weak references taken from Boost.Python */
Wenzel Jakob's avatar
Wenzel Jakob committed
1094
1095
    handle nurse  (Nurse   > 0 ? PyTuple_GetItem(args.ptr(), Nurse   - 1) : ret.ptr());
    handle patient(Patient > 0 ? PyTuple_GetItem(args.ptr(), Patient - 1) : ret.ptr());
1096

1097
    if (!nurse || !patient)
1098
        pybind11_fail("Could not activate keep_alive!");
1099

1100
1101
1102
    if (patient.ptr() == Py_None)
        return; /* Nothing to keep alive */

1103
    cpp_function disable_lifesupport(
1104
        [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
1105

1106
    weakref wr(nurse, disable_lifesupport);
1107

1108
1109
    patient.inc_ref(); /* reference patient and leak the weak reference */
    (void) wr.release();
1110
1111
}

1112
1113
1114
1115
template <typename Iterator> struct iterator_state {
    Iterator it, end;
    bool first;
};
1116

Wenzel Jakob's avatar
Wenzel Jakob committed
1117
1118
NAMESPACE_END(detail)

1119
template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); }
Wenzel Jakob's avatar
Wenzel Jakob committed
1120

1121
1122
1123
1124
template <typename Iterator,
          typename ValueType = decltype(*std::declval<Iterator>()),
          typename... Extra>
iterator make_iterator(Iterator first, Iterator last, Extra &&... extra) {
1125
1126
1127
1128
1129
    typedef detail::iterator_state<Iterator> state;

    if (!detail::get_type_info(typeid(state))) {
        class_<state>(handle(), "")
            .def("__iter__", [](state &s) -> state& { return s; })
1130
            .def("__next__", [](state &s) -> ValueType {
1131
1132
1133
1134
                if (!s.first)
                    ++s.it;
                else
                    s.first = false;
1135
1136
                if (s.it == s.end)
                    throw stop_iteration();
1137
                return *s.it;
1138
1139
1140
            }, return_value_policy::reference_internal, std::forward<Extra>(extra)...);
    }

1141
    return (iterator) cast(state { first, last, true });
1142
1143
}

1144
1145
1146
1147
template <typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
    return make_iterator(std::begin(value), std::end(value), extra...);
}

Wenzel Jakob's avatar
Wenzel Jakob committed
1148
template <typename InputType, typename OutputType> void implicitly_convertible() {
1149
    auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
Wenzel Jakob's avatar
Wenzel Jakob committed
1150
1151
1152
1153
1154
1155
1156
1157
1158
        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;
    };
1159
1160
    auto &registered_types = detail::get_internals().registered_types_cpp;
    auto it = registered_types.find(std::type_index(typeid(OutputType)));
Wenzel Jakob's avatar
Wenzel Jakob committed
1161
    if (it == registered_types.end())
1162
        pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
1163
    ((detail::type_info *) it->second)->implicit_conversions.push_back(implicit_caster);
Wenzel Jakob's avatar
Wenzel Jakob committed
1164
1165
}

1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
template <typename ExceptionTranslator>
void register_exception_translator(ExceptionTranslator&& translator) {
    detail::get_internals().registered_exception_translators.push_front(
        std::forward<ExceptionTranslator>(translator));
}

/* Wrapper to generate a new Python exception type.
 *
 * This should only be used with PyErr_SetString for now.
 * It is not (yet) possible to use as a py::base.
 * Template type argument is reserved for future use.
 */
template <typename type>
class exception : public object {
public:
    exception(module &m, const std::string name, PyObject* base=PyExc_Exception) {
        std::string full_name = std::string(PyModule_GetName(m.ptr()))
                + std::string(".") + name;
        char* exception_name = const_cast<char*>(full_name.c_str());
        m_ptr = PyErr_NewException(exception_name, base, NULL);
        inc_ref(); // PyModule_AddObject() steals a reference
        PyModule_AddObject(m.ptr(), name.c_str(), m_ptr);
    }
};

1191
#if defined(WITH_THREAD)
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205

/* The functions below essentially reproduce the PyGILState_* API using a RAII
 * pattern, but there are a few important differences:
 *
 * 1. When acquiring the GIL from an non-main thread during the finalization
 *    phase, the GILState API blindly terminates the calling thread, which
 *    is often not what is wanted. This API does not do this.
 *
 * 2. The gil_scoped_release function can optionally cut the relationship
 *    of a PyThreadState and its associated thread, which allows moving it to
 *    another thread (this is a fairly rare/advanced use case).
 *
 * 3. The reference count of an acquired thread state can be controlled. This
 *    can be handy to prevent cases where callbacks issued from an external
1206
1207
 *    thread would otherwise constantly construct and destroy thread state data
 *    structures.
1208
1209
1210
1211
1212
 *
 * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
 * example which uses features 2 and 3 to migrate the Python thread of
 * execution to another thread (to run the event loop on the original thread,
 * in this case).
1213
 */
Wenzel Jakob's avatar
Wenzel Jakob committed
1214
1215
1216

class gil_scoped_acquire {
public:
1217
    PYBIND11_NOINLINE gil_scoped_acquire() {
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
        auto const &internals = detail::get_internals();
        tstate = (PyThreadState *) PyThread_get_key_value(internals.tstate);

        if (!tstate) {
            tstate = PyThreadState_New(internals.istate);
            #if !defined(NDEBUG)
                if (!tstate)
                    pybind11_fail("scoped_acquire: could not create thread state!");
            #endif
            tstate->gilstate_counter = 0;
1228
1229
1230
            #if PY_MAJOR_VERSION < 3
                PyThread_delete_key_value(internals.tstate);
            #endif
1231
1232
            PyThread_set_key_value(internals.tstate, tstate);
        } else {
1233
            release = detail::get_thread_state_unchecked() != tstate;
1234
1235
1236
1237
        }

        if (release) {
            /* Work around an annoying assertion in PyThreadState_Swap */
1238
1239
1240
1241
            #if defined(Py_DEBUG)
                PyInterpreterState *interp = tstate->interp;
                tstate->interp = nullptr;
            #endif
1242
            PyEval_AcquireThread(tstate);
1243
1244
1245
            #if defined(Py_DEBUG)
                tstate->interp = interp;
            #endif
1246
1247
1248
1249
1250
1251
1252
1253
1254
        }

        inc_ref();
    }

    void inc_ref() {
        ++tstate->gilstate_counter;
    }

1255
    PYBIND11_NOINLINE void dec_ref() {
1256
1257
        --tstate->gilstate_counter;
        #if !defined(NDEBUG)
1258
            if (detail::get_thread_state_unchecked() != tstate)
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
                pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
            if (tstate->gilstate_counter < 0)
                pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
        #endif
        if (tstate->gilstate_counter == 0) {
            #if !defined(NDEBUG)
                if (!release)
                    pybind11_fail("scoped_acquire::dec_ref(): internal error!");
            #endif
            PyThreadState_Clear(tstate);
            PyThreadState_DeleteCurrent();
1270
            PyThread_delete_key_value(detail::get_internals().tstate);
1271
1272
1273
1274
            release = false;
        }
    }

1275
    PYBIND11_NOINLINE ~gil_scoped_acquire() {
1276
1277
1278
1279
1280
1281
1282
        dec_ref();
        if (release)
           PyEval_SaveThread();
    }
private:
    PyThreadState *tstate = nullptr;
    bool release = true;
Wenzel Jakob's avatar
Wenzel Jakob committed
1283
1284
1285
1286
};

class gil_scoped_release {
public:
1287
1288
    gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
        tstate = PyEval_SaveThread();
1289
        if (disassoc) {
1290
            auto key = detail::get_internals().tstate;
1291
1292
1293
1294
1295
1296
            #if PY_MAJOR_VERSION < 3
                PyThread_delete_key_value(key);
            #else
                PyThread_set_key_value(key, nullptr);
            #endif
        }
1297
1298
1299
1300
1301
    }
    ~gil_scoped_release() {
        if (!tstate)
            return;
        PyEval_RestoreThread(tstate);
1302
        if (disassoc) {
1303
            auto key = detail::get_internals().tstate;
1304
1305
1306
1307
1308
            #if PY_MAJOR_VERSION < 3
                PyThread_delete_key_value(key);
            #endif
            PyThread_set_key_value(key, tstate);
        }
1309
1310
1311
1312
    }
private:
    PyThreadState *tstate;
    bool disassoc;
Wenzel Jakob's avatar
Wenzel Jakob committed
1313
};
1314
1315
1316
#else
class gil_scoped_acquire { };
class gil_scoped_release { };
1317
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
1318

1319
1320
inline function get_overload(const void *this_ptr, const char *name)  {
    handle py_object = detail::get_object_handle(this_ptr);
1321
1322
    if (!py_object)
        return function();
1323
1324
1325
    handle type = py_object.get_type();
    auto key = std::make_pair(type.ptr(), name);

1326
1327
    /* Cache functions that aren't overloaded in Python to avoid
       many costly Python dictionary lookups below */
1328
1329
1330
1331
1332
1333
1334
1335
1336
    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();
    }
1337

1338
    /* Don't call dispatch code if invoked from overridden function */
1339
    PyFrameObject *frame = PyThreadState_Get()->frame;
1340
    if (frame && (std::string) pybind11::handle(frame->f_code->co_name).str() == name &&
1341
1342
1343
1344
1345
1346
1347
        frame->f_code->co_argcount > 0) {
        PyFrame_FastToLocals(frame);
        PyObject *self_caller = PyDict_GetItem(
            frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
        if (self_caller == py_object.ptr())
            return function();
    }
1348
1349
1350
    return overload;
}

1351
#define PYBIND11_OVERLOAD_INT(ret_type, name, ...) { \
1352
        pybind11::gil_scoped_acquire gil; \
1353
        pybind11::function overload = pybind11::get_overload(this, name); \
1354
        if (overload) \
1355
            return overload(__VA_ARGS__).template cast<ret_type>();  }
1356

1357
1358
1359
#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
    PYBIND11_OVERLOAD_INT(ret_type, name, __VA_ARGS__) \
    return cname::fn(__VA_ARGS__)
1360

1361
1362
1363
1364
1365
1366
1367
1368
1369
#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
    PYBIND11_OVERLOAD_INT(ret_type, name, __VA_ARGS__) \
    pybind11::pybind11_fail("Tried to call pure virtual function \"" #cname "::" name "\"");

#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
    PYBIND11_OVERLOAD_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)

#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
    PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
1370

1371
NAMESPACE_END(pybind11)
Wenzel Jakob's avatar
Wenzel Jakob committed
1372
1373

#if defined(_MSC_VER)
Wenzel Jakob's avatar
Wenzel Jakob committed
1374
#  pragma warning(pop)
Ben Pritchard's avatar
Ben Pritchard committed
1375
1376
#elif defined(__ICC) || defined(__INTEL_COMPILER)
#  pragma warning(pop)
1377
#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob's avatar
Wenzel Jakob committed
1378
#  pragma GCC diagnostic pop
Wenzel Jakob's avatar
Wenzel Jakob committed
1379
#endif