pybind11.h 91.6 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
14
15
16
17
18
19
20
21
22
23
#if defined(__INTEL_COMPILER)
#  pragma warning push
#  pragma warning disable 68    // integer conversion resulted in a change of sign
#  pragma warning disable 186   // pointless comparison of unsigned integer with zero
#  pragma warning disable 878   // incompatible exception specifications
#  pragma warning disable 1334  // the "template" keyword used for syntactic disambiguation may only be used within a template
#  pragma warning disable 1682  // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem)
#  pragma warning disable 1786  // function "strdup" was declared deprecated
#  pragma warning disable 1875  // offsetof applied to non-POD (Plain Old Data) types is nonstandard
#  pragma warning disable 2196  // warning #2196: routine is both "inline" and "noinline"
#elif defined(_MSC_VER)
Wenzel Jakob's avatar
Wenzel Jakob committed
24
#  pragma warning(push)
25
#  pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
Wenzel Jakob's avatar
Wenzel Jakob committed
26
#  pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
27
#  pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
Wenzel Jakob's avatar
Wenzel Jakob committed
28
29
#  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
Wenzel Jakob's avatar
Wenzel Jakob committed
30
#  pragma warning(disable: 4702) // warning C4702: unreachable code
31
#  pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
32
#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob's avatar
Wenzel Jakob committed
33
34
35
36
#  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
37
38
#  pragma GCC diagnostic ignored "-Wstrict-aliasing"
#  pragma GCC diagnostic ignored "-Wattributes"
39
40
41
#  if __GNUC__ >= 7
#    pragma GCC diagnostic ignored "-Wnoexcept-type"
#  endif
Wenzel Jakob's avatar
Wenzel Jakob committed
42
43
#endif

44
45
46
47
48
#if defined(__GNUG__) && !defined(__clang__)
 #include <cxxabi.h>
#endif


Wenzel Jakob's avatar
Wenzel Jakob committed
49
#include "attr.h"
50
#include "options.h"
51
#include "detail/class.h"
52
#include "detail/init.h"
Wenzel Jakob's avatar
Wenzel Jakob committed
53

54
NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
Wenzel Jakob's avatar
Wenzel Jakob committed
55

Wenzel Jakob's avatar
Wenzel Jakob committed
56
/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
57
class cpp_function : public function {
Wenzel Jakob's avatar
Wenzel Jakob committed
58
public:
59
    cpp_function() { }
60
    cpp_function(std::nullptr_t) { }
Wenzel Jakob's avatar
Wenzel Jakob committed
61

62
    /// Construct a cpp_function from a vanilla function pointer
63
64
    template <typename Return, typename... Args, typename... Extra>
    cpp_function(Return (*f)(Args...), const Extra&... extra) {
65
        initialize(f, f, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
66
67
    }

68
    /// Construct a cpp_function from a lambda function (possibly with internal state)
69
70
    template <typename Func, typename... Extra,
              typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
71
    cpp_function(Func &&f, const Extra&... extra) {
72
        initialize(std::forward<Func>(f),
73
                   (detail::function_signature_t<Func> *) nullptr, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
74
75
    }

76
    /// Construct a cpp_function from a class method (non-const)
77
78
    template <typename Return, typename Class, typename... Arg, typename... Extra>
    cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
79
        initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
80
                   (Return (*) (Class *, Arg...)) nullptr, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
81
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
82

83
    /// Construct a cpp_function from a class method (const)
84
85
    template <typename Return, typename Class, typename... Arg, typename... Extra>
    cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
86
        initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
87
                   (Return (*)(const Class *, Arg ...)) nullptr, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
88
89
    }

90
    /// Return the function name
Wenzel Jakob's avatar
Wenzel Jakob committed
91
    object name() const { return attr("__name__"); }
92

93
protected:
94
95
96
97
98
    /// Space optimization: don't inline this frequently instantiated fragment
    PYBIND11_NOINLINE detail::function_record *make_function_record() {
        return new detail::function_record();
    }

99
    /// Special internal constructor for functors, lambda functions, etc.
100
101
    template <typename Func, typename Return, typename... Args, typename... Extra>
    void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
102
        using namespace detail;
103
        struct capture { remove_reference_t<Func> f; };
Wenzel Jakob's avatar
Wenzel Jakob committed
104

105
        /* Store the function including any extra state it might have (e.g. a lambda capture object) */
106
        auto rec = make_function_record();
107

108
109
        /* Store the capture object directly in the function record if there is enough space */
        if (sizeof(capture) <= sizeof(rec->data)) {
110
111
112
            /* 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. */
113
#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
114
115
116
#  pragma GCC diagnostic push
#  pragma GCC diagnostic ignored "-Wplacement-new"
#endif
117
            new ((capture *) &rec->data) capture { std::forward<Func>(f) };
118
#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
119
120
#  pragma GCC diagnostic pop
#endif
121
            if (!std::is_trivially_destructible<Func>::value)
122
                rec->free_data = [](function_record *r) { ((capture *) &r->data)->~capture(); };
123
124
        } else {
            rec->data[0] = new capture { std::forward<Func>(f) };
125
            rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
126
        }
127

128
        /* Type casters for the function arguments and return value */
129
130
131
        using cast_in = argument_loader<Args...>;
        using cast_out = make_caster<
            conditional_t<std::is_void<Return>::value, void_type, Return>
132
        >;
Wenzel Jakob's avatar
Wenzel Jakob committed
133

134
        static_assert(expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
135
                      "The number of argument annotations does not match the number of function arguments");
136

137
        /* Dispatch code which converts function arguments and performs the actual function call */
138
        rec->impl = [](function_call &call) -> handle {
139
            cast_in args_converter;
140
141

            /* Try to cast the function arguments into the C++ domain */
142
            if (!args_converter.load_args(call))
143
144
                return PYBIND11_TRY_NEXT_OVERLOAD;

Wenzel Jakob's avatar
Wenzel Jakob committed
145
            /* Invoke call policy pre-call hook */
146
            process_attributes<Extra...>::precall(call);
147
148

            /* Get a pointer to the capture object */
149
150
151
            auto data = (sizeof(capture) <= sizeof(call.func.data)
                         ? &call.func.data : call.func.data[0]);
            capture *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
152

153
            /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
154
            return_value_policy policy = return_value_policy_override<Return>::policy(call.func.policy);
155

Dean Moldovan's avatar
Dean Moldovan committed
156
            /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
157
            using Guard = extract_guard_t<Extra...>;
Dean Moldovan's avatar
Dean Moldovan committed
158

159
            /* Perform the function call */
160
161
            handle result = cast_out::cast(
                std::move(args_converter).template call<Return, Guard>(cap->f), policy, call.parent);
Wenzel Jakob's avatar
Wenzel Jakob committed
162
163

            /* Invoke call policy post-call hook */
164
            process_attributes<Extra...>::postcall(call, result);
165

166
            return result;
Wenzel Jakob's avatar
Wenzel Jakob committed
167
168
        };

Wenzel Jakob's avatar
Wenzel Jakob committed
169
        /* Process any user-provided function attributes */
170
        process_attributes<Extra...>::init(extra..., rec);
171
172

        /* Generate a readable signature describing the function's arguments and return value types */
173
174
        static constexpr auto signature = _("(") + cast_in::arg_names + _(") -> ") + cast_out::name;
        PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
175
176

        /* Register the function with Python from generic (non-templated) code */
177
        initialize_generic(rec, signature.text, types.data(), sizeof...(Args));
178
179
180

        if (cast_in::has_args) rec->has_args = true;
        if (cast_in::has_kwargs) rec->has_kwargs = true;
181
182

        /* Stash some additional information used by an important optimization in 'functional.h' */
183
        using FunctionType = Return (*)(Args...);
184
185
186
187
188
        constexpr bool is_function_ptr =
            std::is_convertible<Func, FunctionType>::value &&
            sizeof(capture) == sizeof(void *);
        if (is_function_ptr) {
            rec->is_stateless = true;
189
            rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
190
        }
191
192
    }

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

197
        /* Create copies of all referenced C-style strings */
Wenzel Jakob's avatar
Wenzel Jakob committed
198
199
200
        rec->name = strdup(rec->name ? rec->name : "");
        if (rec->doc) rec->doc = strdup(rec->doc);
        for (auto &a: rec->args) {
201
202
203
204
205
            if (a.name)
                a.name = strdup(a.name);
            if (a.descr)
                a.descr = strdup(a.descr);
            else if (a.value)
206
                a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
207
        }
208

209
210
        rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");

211
212
213
214
215
216
217
218
219
220
221
222
223
224
#if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
        if (rec->is_constructor && !rec->is_new_style_constructor) {
            const auto class_name = std::string(((PyTypeObject *) rec->scope.ptr())->tp_name);
            const auto func_name = std::string(rec->name);
            PyErr_WarnEx(
                PyExc_FutureWarning,
                ("pybind11-bound class '" + class_name + "' is using an old-style "
                 "placement-new '" + func_name + "' which has been deprecated. See "
                 "the upgrade guide in pybind11's docs. This message is only visible "
                 "when compiled in debug mode.").c_str(), 0
            );
        }
#endif

225
226
        /* Generate a proper function signature */
        std::string signature;
227
228
229
        size_t type_index = 0, arg_index = 0;
        for (auto *pc = text; *pc != '\0'; ++pc) {
            const auto c = *pc;
230
231

            if (c == '{') {
232
233
234
235
236
237
238
239
240
241
                // Write arg name for everything except *args and **kwargs.
                if (*(pc + 1) == '*')
                    continue;

                if (arg_index < rec->args.size() && rec->args[arg_index].name) {
                    signature += rec->args[arg_index].name;
                } else if (arg_index == 0 && rec->is_method) {
                    signature += "self";
                } else {
                    signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
242
                }
243
                signature += ": ";
244
            } else if (c == '}') {
245
246
                // Write default value if available.
                if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
247
                    signature += " = ";
248
                    signature += rec->args[arg_index].descr;
249
                }
250
                arg_index++;
251
252
            } else if (c == '%') {
                const std::type_info *t = types[type_index++];
253
                if (!t)
254
                    pybind11_fail("Internal error while parsing type signature (1)");
255
                if (auto tinfo = detail::get_type_info(*t)) {
256
257
258
259
                    handle th((PyObject *) tinfo->type);
                    signature +=
                        th.attr("__module__").cast<std::string>() + "." +
                        th.attr("__qualname__").cast<std::string>(); // Python 3.3+, but we backport it to earlier versions
260
261
262
                } else if (rec->is_new_style_constructor && arg_index == 0) {
                    // A new-style `__init__` takes `self` as `value_and_holder`.
                    // Rewrite it to the proper class type.
263
264
265
                    signature +=
                        rec->scope.attr("__module__").cast<std::string>() + "." +
                        rec->scope.attr("__qualname__").cast<std::string>();
266
267
268
269
270
271
272
273
274
                } else {
                    std::string tname(t->name());
                    detail::clean_type_id(tname);
                    signature += tname;
                }
            } else {
                signature += c;
            }
        }
275
        if (arg_index != args || types[type_index] != nullptr)
276
            pybind11_fail("Internal error while parsing type signature (2)");
277

278
#if PY_MAJOR_VERSION < 3
Wenzel Jakob's avatar
Wenzel Jakob committed
279
280
281
        if (strcmp(rec->name, "__next__") == 0) {
            std::free(rec->name);
            rec->name = strdup("next");
282
283
284
        } else if (strcmp(rec->name, "__bool__") == 0) {
            std::free(rec->name);
            rec->name = strdup("__nonzero__");
285
        }
286
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
287
288
        rec->signature = strdup(signature.c_str());
        rec->args.shrink_to_fit();
289
        rec->nargs = (std::uint16_t) args;
290

291
292
        if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr()))
            rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
293

Wenzel Jakob's avatar
Wenzel Jakob committed
294
        detail::function_record *chain = nullptr, *chain_start = rec;
295
296
        if (rec->sibling) {
            if (PyCFunction_Check(rec->sibling.ptr())) {
Wenzel Jakob's avatar
Wenzel Jakob committed
297
                auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
298
299
300
                chain = (detail::function_record *) rec_capsule;
                /* Never append a method to an overload chain of a parent class;
                   instead, hide the parent's overloads in this case */
301
                if (!chain->scope.is(rec->scope))
302
303
304
305
306
307
                    chain = nullptr;
            }
            // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
            else if (!rec->sibling.is_none() && rec->name[0] != '_')
                pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
                        "\" with a function of the same name");
308
309
        }

Wenzel Jakob's avatar
Wenzel Jakob committed
310
        if (!chain) {
311
            /* No existing overload was found, create a new function object */
Wenzel Jakob's avatar
Wenzel Jakob committed
312
            rec->def = new PyMethodDef();
313
            std::memset(rec->def, 0, sizeof(PyMethodDef));
Wenzel Jakob's avatar
Wenzel Jakob committed
314
            rec->def->ml_name = rec->name;
315
            rec->def->ml_meth = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(*dispatcher));
Wenzel Jakob's avatar
Wenzel Jakob committed
316
            rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
317

318
319
            capsule rec_capsule(rec, [](void *ptr) {
                destruct((detail::function_record *) ptr);
320
            });
321
322
323

            object scope_module;
            if (rec->scope) {
324
325
326
327
328
                if (hasattr(rec->scope, "__module__")) {
                    scope_module = rec->scope.attr("__module__");
                } else if (hasattr(rec->scope, "__name__")) {
                    scope_module = rec->scope.attr("__name__");
                }
329
330
331
            }

            m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
Wenzel Jakob's avatar
Wenzel Jakob committed
332
            if (!m_ptr)
333
                pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob's avatar
Wenzel Jakob committed
334
        } else {
335
            /* Append at the end of the overload chain */
Wenzel Jakob's avatar
Wenzel Jakob committed
336
            m_ptr = rec->sibling.ptr();
Wenzel Jakob's avatar
Wenzel Jakob committed
337
            inc_ref();
Wenzel Jakob's avatar
Wenzel Jakob committed
338
            chain_start = chain;
339
340
341
342
343
344
345
346
347
            if (chain->is_method != rec->is_method)
                pybind11_fail("overloading a method with both static and instance methods is not supported; "
                    #if defined(NDEBUG)
                        "compile in debug mode for more details"
                    #else
                        "error while attempting to bind " + std::string(rec->is_method ? "instance" : "static") + " method " +
                        std::string(pybind11::str(rec->scope.attr("__name__"))) + "." + std::string(rec->name) + signature
                    #endif
                );
Wenzel Jakob's avatar
Wenzel Jakob committed
348
349
350
            while (chain->next)
                chain = chain->next;
            chain->next = rec;
Wenzel Jakob's avatar
Wenzel Jakob committed
351
        }
352

Wenzel Jakob's avatar
Wenzel Jakob committed
353
        std::string signatures;
354
        int index = 0;
Wenzel Jakob's avatar
Wenzel Jakob committed
355
        /* Create a nice pydoc rec including all signatures and
356
           docstrings of the functions in the overload chain */
357
        if (chain && options::show_function_signatures()) {
358
359
360
361
362
363
            // First a generic signature
            signatures += rec->name;
            signatures += "(*args, **kwargs)\n";
            signatures += "Overloaded function.\n\n";
        }
        // Then specific overload signatures
364
        bool first_user_def = true;
Wenzel Jakob's avatar
Wenzel Jakob committed
365
        for (auto it = chain_start; it != nullptr; it = it->next) {
366
            if (options::show_function_signatures()) {
367
                if (index > 0) signatures += "\n";
368
369
370
371
                if (chain)
                    signatures += std::to_string(++index) + ". ";
                signatures += rec->name;
                signatures += it->signature;
372
                signatures += "\n";
373
374
            }
            if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
375
376
377
378
379
380
                // If we're appending another docstring, and aren't printing function signatures, we
                // need to append a newline first:
                if (!options::show_function_signatures()) {
                    if (first_user_def) first_user_def = false;
                    else signatures += "\n";
                }
381
                if (options::show_function_signatures()) signatures += "\n";
382
                signatures += it->doc;
383
                if (options::show_function_signatures()) signatures += "\n";
384
            }
Wenzel Jakob's avatar
Wenzel Jakob committed
385
        }
Wenzel Jakob's avatar
Wenzel Jakob committed
386
387

        /* Install docstring */
Wenzel Jakob's avatar
Wenzel Jakob committed
388
389
        PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
        if (func->m_ml->ml_doc)
390
            std::free(const_cast<char *>(func->m_ml->ml_doc));
Wenzel Jakob's avatar
Wenzel Jakob committed
391
        func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob's avatar
Wenzel Jakob committed
392

393
394
        if (rec->is_method) {
            m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
Wenzel Jakob's avatar
Wenzel Jakob committed
395
            if (!m_ptr)
396
                pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob's avatar
Wenzel Jakob committed
397
398
399
            Py_DECREF(func);
        }
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
400
401
402
403
404
405

    /// 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)
406
                rec->free_data(rec);
Wenzel Jakob's avatar
Wenzel Jakob committed
407
408
409
410
            std::free((char *) rec->name);
            std::free((char *) rec->doc);
            std::free((char *) rec->signature);
            for (auto &arg: rec->args) {
411
412
                std::free(const_cast<char *>(arg.name));
                std::free(const_cast<char *>(arg.descr));
Wenzel Jakob's avatar
Wenzel Jakob committed
413
414
415
                arg.value.dec_ref();
            }
            if (rec->def) {
416
                std::free(const_cast<char *>(rec->def->ml_doc));
Wenzel Jakob's avatar
Wenzel Jakob committed
417
418
419
420
421
422
423
424
                delete rec->def;
            }
            delete rec;
            rec = next;
        }
    }

    /// Main dispatch logic for calls to functions bound using pybind11
425
    static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
426
427
        using namespace detail;

Wenzel Jakob's avatar
Wenzel Jakob committed
428
        /* Iterator over the list of potentially admissible overloads */
429
430
        const function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
                              *it = overloads;
Wenzel Jakob's avatar
Wenzel Jakob committed
431
432

        /* Need to know how many arguments + keyword arguments there are to pick the right overload */
433
        const size_t n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
Wenzel Jakob's avatar
Wenzel Jakob committed
434

435
        handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
Wenzel Jakob's avatar
Wenzel Jakob committed
436
               result = PYBIND11_TRY_NEXT_OVERLOAD;
437

438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
        auto self_value_and_holder = value_and_holder();
        if (overloads->is_constructor) {
            const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
            const auto pi = reinterpret_cast<instance *>(parent.ptr());
            self_value_and_holder = pi->get_value_and_holder(tinfo, false);

            if (!self_value_and_holder.type || !self_value_and_holder.inst) {
                PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid `self` argument");
                return nullptr;
            }

            // If this value is already registered it must mean __init__ is invoked multiple times;
            // we really can't support that in C++, so just ignore the second __init__.
            if (self_value_and_holder.instance_registered())
                return none().release().ptr();
        }

Wenzel Jakob's avatar
Wenzel Jakob committed
455
        try {
456
457
458
459
460
461
462
463
464
            // We do this in two passes: in the first pass, we load arguments with `convert=false`;
            // in the second, we allow conversion (except for arguments with an explicit
            // py::arg().noconvert()).  This lets us prefer calls without conversion, with
            // conversion as a fallback.
            std::vector<function_call> second_pass;

            // However, if there are no overloads, we can just skip the no-convert pass entirely
            const bool overloaded = it != nullptr && it->next != nullptr;

Wenzel Jakob's avatar
Wenzel Jakob committed
465
            for (; it != nullptr; it = it->next) {
466

Wenzel Jakob's avatar
Wenzel Jakob committed
467
                /* For each overload:
468
469
                   1. Copy all positional arguments we were given, also checking to make sure that
                      named positional arguments weren't *also* specified via kwarg.
470
                   2. If we weren't given enough, try to make up the omitted ones by checking
471
472
473
474
475
476
477
478
479
480
481
482
483
                      whether they were provided by a kwarg matching the `py::arg("name")` name.  If
                      so, use it (and remove it from kwargs; if not, see if the function binding
                      provided a default that we can use.
                   3. Ensure that either all keyword arguments were "consumed", or that the function
                      takes a kwargs argument to accept unconsumed kwargs.
                   4. Any positional arguments still left get put into a tuple (for args), and any
                      leftover kwargs get put into a dict.
                   5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
                      extra tuple or dict at the end of the positional arguments.
                   6. Call the function call dispatcher (function_record::impl)

                   If one of these fail, move on to the next overload and keep trying until we get a
                   result other than PYBIND11_TRY_NEXT_OVERLOAD.
Wenzel Jakob's avatar
Wenzel Jakob committed
484
485
                 */

486
                const function_record &func = *it;
487
488
489
                size_t pos_args = func.nargs;    // Number of positional arguments that we need
                if (func.has_args) --pos_args;   // (but don't count py::args
                if (func.has_kwargs) --pos_args; //  or py::kwargs)
Wenzel Jakob's avatar
Wenzel Jakob committed
490

491
                if (!func.has_args && n_args_in > pos_args)
492
493
                    continue; // Too many arguments for this overload

494
                if (n_args_in < pos_args && func.args.size() < pos_args)
495
496
                    continue; // Not enough arguments given, and not enough defaults to fill in the blanks

497
                function_call call(func, parent);
Wenzel Jakob's avatar
Wenzel Jakob committed
498

499
500
501
                size_t args_to_copy = std::min(pos_args, n_args_in);
                size_t args_copied = 0;

502
503
504
505
506
507
508
                // 0. Inject new-style `self` argument
                if (func.is_new_style_constructor) {
                    // The `value` may have been preallocated by an old-style `__init__`
                    // if it was a preceding candidate for overload resolution.
                    if (self_value_and_holder)
                        self_value_and_holder.type->dealloc(self_value_and_holder);

509
                    call.init_self = PyTuple_GET_ITEM(args_in, 0);
510
511
512
513
514
                    call.args.push_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
                    call.args_convert.push_back(false);
                    ++args_copied;
                }

515
                // 1. Copy any position arguments given.
516
                bool bad_arg = false;
517
                for (; args_copied < args_to_copy; ++args_copied) {
518
                    const argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
519
520
                    if (kwargs_in && arg_rec && arg_rec->name && PyDict_GetItemString(kwargs_in, arg_rec->name)) {
                        bad_arg = true;
521
                        break;
522
523
                    }

524
525
526
527
528
529
530
                    handle arg(PyTuple_GET_ITEM(args_in, args_copied));
                    if (arg_rec && !arg_rec->none && arg.is_none()) {
                        bad_arg = true;
                        break;
                    }
                    call.args.push_back(arg);
                    call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
531
                }
532
                if (bad_arg)
533
                    continue; // Maybe it was meant for another overload (issue #688)
534
535
536
537
538
539
540
541
542

                // We'll need to copy this if we steal some kwargs for defaults
                dict kwargs = reinterpret_borrow<dict>(kwargs_in);

                // 2. Check kwargs and, failing that, defaults that may help complete the list
                if (args_copied < pos_args) {
                    bool copied_kwargs = false;

                    for (; args_copied < pos_args; ++args_copied) {
543
                        const auto &arg = func.args[args_copied];
544
545

                        handle value;
546
                        if (kwargs_in && arg.name)
547
                            value = PyDict_GetItemString(kwargs.ptr(), arg.name);
Wenzel Jakob's avatar
Wenzel Jakob committed
548
549

                        if (value) {
550
551
552
553
554
555
                            // Consume a kwargs value
                            if (!copied_kwargs) {
                                kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
                                copied_kwargs = true;
                            }
                            PyDict_DelItemString(kwargs.ptr(), arg.name);
556
                        } else if (arg.value) {
557
558
559
                            value = arg.value;
                        }

560
                        if (value) {
561
                            call.args.push_back(value);
562
563
                            call.args_convert.push_back(arg.convert);
                        }
564
                        else
Wenzel Jakob's avatar
Wenzel Jakob committed
565
                            break;
566
567
568
569
570
571
572
                    }

                    if (args_copied < pos_args)
                        continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments
                }

                // 3. Check everything was consumed (unless we have a kwargs arg)
573
                if (kwargs && kwargs.size() > 0 && !func.has_kwargs)
574
575
576
                    continue; // Unconsumed kwargs, but no py::kwargs argument to accept them

                // 4a. If we have a py::args argument, create a new tuple with leftovers
577
                if (func.has_args) {
578
                    tuple extra_args;
579
580
581
582
                    if (args_to_copy == 0) {
                        // We didn't copy out any position arguments from the args_in tuple, so we
                        // can reuse it directly without copying:
                        extra_args = reinterpret_borrow<tuple>(args_in);
583
                    } else if (args_copied >= n_args_in) {
584
                        extra_args = tuple(0);
585
                    } else {
586
587
588
                        size_t args_size = n_args_in - args_copied;
                        extra_args = tuple(args_size);
                        for (size_t i = 0; i < args_size; ++i) {
Jason Rhinelander's avatar
Jason Rhinelander committed
589
                            extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i);
Wenzel Jakob's avatar
Wenzel Jakob committed
590
591
                        }
                    }
592
                    call.args.push_back(extra_args);
593
                    call.args_convert.push_back(false);
594
                    call.args_ref = std::move(extra_args);
Wenzel Jakob's avatar
Wenzel Jakob committed
595
                }
596

597
                // 4b. If we have a py::kwargs, pass on any remaining kwargs
598
                if (func.has_kwargs) {
599
600
                    if (!kwargs.ptr())
                        kwargs = dict(); // If we didn't get one, send an empty one
601
                    call.args.push_back(kwargs);
602
                    call.args_convert.push_back(false);
603
                    call.kwargs_ref = std::move(kwargs);
604
605
                }

606
607
608
                // 5. Put everything in a vector.  Not technically step 5, we've been building it
                // in `call.args` all along.
                #if !defined(NDEBUG)
609
                if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
610
611
                    pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
                #endif
612

613
614
615
616
617
618
619
620
621
                std::vector<bool> second_pass_convert;
                if (overloaded) {
                    // We're in the first no-convert pass, so swap out the conversion flags for a
                    // set of all-false flags.  If the call fails, we'll swap the flags back in for
                    // the conversion-allowed call below.
                    second_pass_convert.resize(func.nargs, false);
                    call.args_convert.swap(second_pass_convert);
                }

622
                // 6. Call the function.
623
                try {
624
                    loader_life_support guard{};
625
                    result = func.impl(call);
626
                } catch (reference_cast_error &) {
627
628
                    result = PYBIND11_TRY_NEXT_OVERLOAD;
                }
Wenzel Jakob's avatar
Wenzel Jakob committed
629
630
631

                if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
                    break;
632

633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
                if (overloaded) {
                    // The (overloaded) call failed; if the call has at least one argument that
                    // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
                    // then add this call to the list of second pass overloads to try.
                    for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
                        if (second_pass_convert[i]) {
                            // Found one: swap the converting flags back in and store the call for
                            // the second pass.
                            call.args_convert.swap(second_pass_convert);
                            second_pass.push_back(std::move(call));
                            break;
                        }
                    }
                }
            }

            if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
                // The no-conversion pass finished without success, try again with conversion allowed
                for (auto &call : second_pass) {
                    try {
653
                        loader_life_support guard{};
654
655
656
657
658
                        result = call.func.impl(call);
                    } catch (reference_cast_error &) {
                        result = PYBIND11_TRY_NEXT_OVERLOAD;
                    }

659
660
661
662
663
                    if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
                        // The error reporting logic below expects 'it' to be valid, as it would be
                        // if we'd encountered this failure in the first-pass loop.
                        if (!result)
                            it = &call.func;
664
                        break;
665
                    }
666
                }
Wenzel Jakob's avatar
Wenzel Jakob committed
667
            }
668
669
        } catch (error_already_set &e) {
            e.restore();
670
            return nullptr;
671
672
673
674
#if defined(__GNUG__) && !defined(__clang__)
        } catch ( abi::__forced_unwind& ) {
            throw;
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
675
        } catch (...) {
676
677
678
            /* When an exception is caught, give each registered exception
               translator a chance to translate it to a Python exception
               in reverse order of registration.
679

680
               A translator may choose to do one of the following:
681

682
683
684
685
686
                - 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. */

687
            auto last_exception = std::current_exception();
688
            auto &registered_exception_translators = get_internals().registered_exception_translators;
689
690
691
692
693
694
695
696
697
698
            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
699
700
701
            return nullptr;
        }

702
703
704
705
706
707
708
709
710
711
        auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
            if (msg.find("std::") != std::string::npos) {
                msg += "\n\n"
                       "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
                       "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
                       "conversions are optional and require extra headers to be included\n"
                       "when compiling your pybind11 module.";
            }
        };

Wenzel Jakob's avatar
Wenzel Jakob committed
712
        if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
713
714
715
            if (overloads->is_operator)
                return handle(Py_NotImplemented).inc_ref().ptr();

716
717
718
719
            std::string msg = std::string(overloads->name) + "(): incompatible " +
                std::string(overloads->is_constructor ? "constructor" : "function") +
                " arguments. The following argument types are supported:\n";

Wenzel Jakob's avatar
Wenzel Jakob committed
720
            int ctr = 0;
721
            for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
Wenzel Jakob's avatar
Wenzel Jakob committed
722
                msg += "    "+ std::to_string(++ctr) + ". ";
723
724
725

                bool wrote_sig = false;
                if (overloads->is_constructor) {
726
                    // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
727
                    std::string sig = it2->signature;
728
                    size_t start = sig.find('(') + 7; // skip "(self: "
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
                    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
745
746
                msg += "\n";
            }
747
            msg += "\nInvoked with: ";
748
            auto args_ = reinterpret_borrow<tuple>(args_in);
749
            bool some_args = false;
750
            for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
751
752
                if (!some_args) some_args = true;
                else msg += ", ";
753
                msg += pybind11::repr(args_[ti]);
754
            }
755
756
757
758
759
760
761
762
763
764
765
766
767
768
            if (kwargs_in) {
                auto kwargs = reinterpret_borrow<dict>(kwargs_in);
                if (kwargs.size() > 0) {
                    if (some_args) msg += "; ";
                    msg += "kwargs: ";
                    bool first = true;
                    for (auto kwarg : kwargs) {
                        if (first) first = false;
                        else msg += ", ";
                        msg += pybind11::str("{}={!r}").format(kwarg.first, kwarg.second);
                    }
                }
            }

769
            append_note_if_missing_header_is_suspected(msg);
Wenzel Jakob's avatar
Wenzel Jakob committed
770
771
772
773
774
775
            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;
776
            append_note_if_missing_header_is_suspected(msg);
Wenzel Jakob's avatar
Wenzel Jakob committed
777
778
779
            PyErr_SetString(PyExc_TypeError, msg.c_str());
            return nullptr;
        } else {
780
            if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
781
                auto *pi = reinterpret_cast<instance *>(parent.ptr());
782
                self_value_and_holder.type->init_instance(pi, nullptr);
Wenzel Jakob's avatar
Wenzel Jakob committed
783
784
785
786
            }
            return result.ptr();
        }
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
787
788
};

789
/// Wrapper for Python extension modules
Wenzel Jakob's avatar
Wenzel Jakob committed
790
791
class module : public object {
public:
792
    PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob's avatar
Wenzel Jakob committed
793

794
    /// Create a new top-level Python module with the given name and docstring
795
    explicit module(const char *name, const char *doc = nullptr) {
796
        if (!options::show_user_defined_docstrings()) doc = nullptr;
797
#if PY_MAJOR_VERSION >= 3
Wenzel Jakob's avatar
Wenzel Jakob committed
798
        PyModuleDef *def = new PyModuleDef();
799
        std::memset(def, 0, sizeof(PyModuleDef));
Wenzel Jakob's avatar
Wenzel Jakob committed
800
801
802
803
804
        def->m_name = name;
        def->m_doc = doc;
        def->m_size = -1;
        Py_INCREF(def);
        m_ptr = PyModule_Create(def);
805
806
807
#else
        m_ptr = Py_InitModule3(name, nullptr, doc);
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
808
        if (m_ptr == nullptr)
809
            pybind11_fail("Internal error in module::module()");
Wenzel Jakob's avatar
Wenzel Jakob committed
810
811
812
        inc_ref();
    }

813
814
815
816
817
    /** \rst
        Create Python binding for a new function within the module scope. ``Func``
        can be a plain C++ function, a function pointer, or a lambda function. For
        details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
    \endrst */
818
    template <typename Func, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
819
    module &def(const char *name_, Func &&f, const Extra& ... extra) {
820
821
        cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
                          sibling(getattr(*this, name_, none())), extra...);
822
823
824
        // NB: allow overwriting here because cpp_function sets up a chain with the intention of
        // overwriting (and has already checked internally that it isn't overwriting non-functions).
        add_object(name_, func, true /* overwrite */);
Wenzel Jakob's avatar
Wenzel Jakob committed
825
826
827
        return *this;
    }

828
829
830
831
832
833
834
835
836
837
    /** \rst
        Create and return a new Python submodule with the given name and docstring.
        This also works recursively, i.e.

        .. code-block:: cpp

            py::module m("example", "pybind11 example plugin");
            py::module m2 = m.def_submodule("sub", "A submodule of 'example'");
            py::module m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
    \endrst */
838
    module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob's avatar
Wenzel Jakob committed
839
840
        std::string full_name = std::string(PyModule_GetName(m_ptr))
            + std::string(".") + std::string(name);
841
        auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
842
        if (doc && options::show_user_defined_docstrings())
843
            result.attr("__doc__") = pybind11::str(doc);
Wenzel Jakob's avatar
Wenzel Jakob committed
844
845
846
        attr(name) = result;
        return result;
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
847

848
    /// Import and return a module or throws `error_already_set`.
Wenzel Jakob's avatar
Wenzel Jakob committed
849
    static module import(const char *name) {
850
851
        PyObject *obj = PyImport_ImportModule(name);
        if (!obj)
852
            throw error_already_set();
853
        return reinterpret_steal<module>(obj);
Wenzel Jakob's avatar
Wenzel Jakob committed
854
    }
855

856
857
858
859
860
861
862
863
    /// Reload the module or throws `error_already_set`.
    void reload() {
        PyObject *obj = PyImport_ReloadModule(ptr());
        if (!obj)
            throw error_already_set();
        *this = reinterpret_steal<module>(obj);
    }

864
865
866
867
868
    // Adds an object to the module using the given name.  Throws if an object with the given name
    // already exists.
    //
    // overwrite should almost always be false: attempting to overwrite objects that pybind11 has
    // established will, in most cases, break things.
869
    PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
870
871
872
873
        if (!overwrite && hasattr(*this, name))
            pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
                    std::string(name) + "\"");

874
        PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
875
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
876
877
};

878
/// \ingroup python_builtins
879
880
881
882
883
884
/// Return a dictionary representing the global variables in the current execution frame,
/// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
inline dict globals() {
    PyObject *p = PyEval_GetGlobals();
    return reinterpret_borrow<dict>(p ? p : module::import("__main__").attr("__dict__").ptr());
}
885

Wenzel Jakob's avatar
Wenzel Jakob committed
886
NAMESPACE_BEGIN(detail)
Wenzel Jakob's avatar
Wenzel Jakob committed
887
/// Generic support for creating new Python heap types
888
class generic_type : public object {
889
    template <typename...> friend class class_;
Wenzel Jakob's avatar
Wenzel Jakob committed
890
public:
891
    PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
Wenzel Jakob's avatar
Wenzel Jakob committed
892
protected:
893
894
895
896
    void initialize(const type_record &rec) {
        if (rec.scope && hasattr(rec.scope, rec.name))
            pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
                          "\": an object with that name is already defined");
897

898
        if (rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
899
            pybind11_fail("generic_type: type \"" + std::string(rec.name) +
900
901
                          "\" is already registered!");

902
        m_ptr = make_new_python_type(rec);
903
904

        /* Register supplemental type information in C++ dict */
905
906
        auto *tinfo = new detail::type_info();
        tinfo->type = (PyTypeObject *) m_ptr;
907
        tinfo->cpptype = rec.type;
908
        tinfo->type_size = rec.type_size;
909
        tinfo->type_align = rec.type_align;
910
        tinfo->operator_new = rec.operator_new;
911
        tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
912
        tinfo->init_instance = rec.init_instance;
913
        tinfo->dealloc = rec.dealloc;
914
915
        tinfo->simple_type = true;
        tinfo->simple_ancestors = true;
916
917
        tinfo->default_holder = rec.default_holder;
        tinfo->module_local = rec.module_local;
918
919
920

        auto &internals = get_internals();
        auto tindex = std::type_index(*rec.type);
921
        tinfo->direct_conversions = &internals.direct_conversions[tindex];
922
923
924
925
        if (rec.module_local)
            registered_local_types_cpp()[tindex] = tinfo;
        else
            internals.registered_types_cpp[tindex] = tinfo;
926
        internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo };
Wenzel Jakob's avatar
Wenzel Jakob committed
927

928
        if (rec.bases.size() > 1 || rec.multiple_inheritance) {
929
            mark_parents_nonsimple(tinfo->type);
930
931
932
933
934
935
            tinfo->simple_ancestors = false;
        }
        else if (rec.bases.size() == 1) {
            auto parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
            tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
        }
936
937
938
939

        if (rec.module_local) {
            // Stash the local typeinfo and loader so that external modules can access it.
            tinfo->module_local_load = &type_caster_generic::local_load;
940
            setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
941
        }
Wenzel Jakob's avatar
Wenzel Jakob committed
942
943
    }

Wenzel Jakob's avatar
Wenzel Jakob committed
944
945
    /// Helper function which tags all parents of a type using mult. inheritance
    void mark_parents_nonsimple(PyTypeObject *value) {
946
        auto t = reinterpret_borrow<tuple>(value->tp_bases);
Wenzel Jakob's avatar
Wenzel Jakob committed
947
948
949
950
951
952
953
954
        for (handle h : t) {
            auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
            if (tinfo2)
                tinfo2->simple_type = false;
            mark_parents_nonsimple((PyTypeObject *) h.ptr());
        }
    }

Wenzel Jakob's avatar
Wenzel Jakob committed
955
956
957
    void install_buffer_funcs(
            buffer_info *(*get_buffer)(PyObject *, void *),
            void *get_buffer_data) {
Wenzel Jakob's avatar
Wenzel Jakob committed
958
        PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
959
        auto tinfo = detail::get_type_info(&type->ht_type);
Wenzel Jakob's avatar
Wenzel Jakob committed
960
961
962
963
964
965
966
967

        if (!type->ht_type.tp_as_buffer)
            pybind11_fail(
                "To be able to register buffer protocol support for the type '" +
                std::string(tinfo->type->tp_name) +
                "' the associated class<>(..) invocation must "
                "include the pybind11::buffer_protocol() annotation!");

968
969
        tinfo->get_buffer = get_buffer;
        tinfo->get_buffer_data = get_buffer_data;
Wenzel Jakob's avatar
Wenzel Jakob committed
970
971
    }

972
    // rec_func must be set for either fget or fset.
Wenzel Jakob's avatar
Wenzel Jakob committed
973
974
    void def_property_static_impl(const char *name,
                                  handle fget, handle fset,
975
976
977
                                  detail::function_record *rec_func) {
        const auto is_static = rec_func && !(rec_func->is_method && rec_func->scope);
        const auto has_doc = rec_func && rec_func->doc && pybind11::options::show_user_defined_docstrings();
978
979
980
981
982
        auto property = handle((PyObject *) (is_static ? get_internals().static_property_type
                                                       : &PyProperty_Type));
        attr(name) = property(fget.ptr() ? fget : none(),
                              fset.ptr() ? fset : none(),
                              /*deleter*/none(),
983
                              pybind11::str(has_doc ? rec_func->doc : ""));
Wenzel Jakob's avatar
Wenzel Jakob committed
984
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
985
};
986

987
988
989
990
991
992
/// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator new))>>
void set_operator_new(type_record *r) { r->operator_new = &T::operator new; }

template <typename> void set_operator_new(...) { }

993
994
995
996
997
998
template <typename T, typename SFINAE = void> struct has_operator_delete : std::false_type { };
template <typename T> struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
    : std::true_type { };
template <typename T, typename SFINAE = void> struct has_operator_delete_size : std::false_type { };
template <typename T> struct has_operator_delete_size<T, void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>>
    : std::true_type { };
999
/// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
1000
template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
1001
void call_operator_delete(T *p, size_t, size_t) { T::operator delete(p); }
1002
template <typename T, enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> = 0>
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
void call_operator_delete(T *p, size_t s, size_t) { T::operator delete(p, s); }

inline void call_operator_delete(void *p, size_t s, size_t a) {
    (void)s; (void)a;
#if defined(PYBIND11_CPP17)
    if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
        ::operator delete(p, s, std::align_val_t(a));
    else
        ::operator delete(p, s);
#else
    ::operator delete(p);
#endif
}
1016

Wenzel Jakob's avatar
Wenzel Jakob committed
1017
1018
NAMESPACE_END(detail)

1019
1020
1021
1022
1023
1024
/// Given a pointer to a member function, cast it to its `Derived` version.
/// Forward everything else unchanged.
template <typename /*Derived*/, typename F>
auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) { return std::forward<F>(f); }

template <typename Derived, typename Return, typename Class, typename... Args>
1025
1026
1027
1028
1029
auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
    static_assert(detail::is_accessible_base_of<Class, Derived>::value,
        "Cannot bind an inaccessible base class method; use a lambda definition instead");
    return pmf;
}
1030
1031

template <typename Derived, typename Return, typename Class, typename... Args>
1032
1033
1034
1035
1036
auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
    static_assert(detail::is_accessible_base_of<Class, Derived>::value,
        "Cannot bind an inaccessible base class method; use a lambda definition instead");
    return pmf;
}
1037

1038
template <typename type_, typename... options>
Wenzel Jakob's avatar
Wenzel Jakob committed
1039
class class_ : public detail::generic_type {
1040
    template <typename T> using is_holder = detail::is_holder_type<type_, T>;
1041
1042
    template <typename T> using is_subtype = detail::is_strict_base_of<type_, T>;
    template <typename T> using is_base = detail::is_strict_base_of<T, type_>;
1043
1044
1045
    // struct instead of using here to help MSVC:
    template <typename T> struct is_valid_class_option :
        detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
1046

Wenzel Jakob's avatar
Wenzel Jakob committed
1047
public:
1048
    using type = type_;
1049
    using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
1050
    constexpr static bool has_alias = !std::is_void<type_alias>::value;
1051
    using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
1052

1053
    static_assert(detail::all_of<is_valid_class_option<options>...>::value,
1054
            "Unknown/invalid class_ template parameters provided");
Wenzel Jakob's avatar
Wenzel Jakob committed
1055

1056
1057
1058
    static_assert(!has_alias || std::is_polymorphic<type>::value,
            "Cannot use an alias class with a non-polymorphic type");

1059
    PYBIND11_OBJECT(class_, generic_type, PyType_Check)
Wenzel Jakob's avatar
Wenzel Jakob committed
1060

Wenzel Jakob's avatar
Wenzel Jakob committed
1061
1062
    template <typename... Extra>
    class_(handle scope, const char *name, const Extra &... extra) {
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
        using namespace detail;

        // MI can only be specified via class_ template options, not constructor parameters
        static_assert(
            none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
            (   constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
                constexpr_sum(is_base<options>::value...)   == 0 && // no template option bases
                none_of<std::is_same<multiple_inheritance, Extra>...>::value), // no multiple_inheritance attr
            "Error: multiple inheritance bases must be specified via class_ template options");

        type_record record;
Wenzel Jakob's avatar
Wenzel Jakob committed
1074
1075
1076
        record.scope = scope;
        record.name = name;
        record.type = &typeid(type);
1077
        record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
1078
        record.type_align = alignof(conditional_t<has_alias, type_alias, type>&);
1079
        record.holder_size = sizeof(holder_type);
1080
        record.init_instance = init_instance;
Wenzel Jakob's avatar
Wenzel Jakob committed
1081
        record.dealloc = dealloc;
1082
        record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
Wenzel Jakob's avatar
Wenzel Jakob committed
1083

1084
1085
        set_operator_new<type>(&record);

Wenzel Jakob's avatar
Wenzel Jakob committed
1086
        /* Register base classes specified via template arguments to class_, if any */
1087
        PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
1088

Wenzel Jakob's avatar
Wenzel Jakob committed
1089
        /* Process optional arguments, if any */
1090
        process_attributes<Extra...>::init(extra..., &record);
Wenzel Jakob's avatar
Wenzel Jakob committed
1091

1092
        generic_type::initialize(record);
1093

1094
        if (has_alias) {
1095
            auto &instances = record.module_local ? registered_local_types_cpp() : get_internals().registered_types_cpp;
1096
1097
            instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
        }
Wenzel Jakob's avatar
Wenzel Jakob committed
1098
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
1099

1100
    template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
Wenzel Jakob's avatar
Wenzel Jakob committed
1101
    static void add_base(detail::type_record &rec) {
1102
        rec.add_base(typeid(Base), [](void *src) -> void * {
Wenzel Jakob's avatar
Wenzel Jakob committed
1103
1104
1105
1106
            return static_cast<Base *>(reinterpret_cast<type *>(src));
        });
    }

1107
    template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
Wenzel Jakob's avatar
Wenzel Jakob committed
1108
1109
    static void add_base(detail::type_record &) { }

1110
    template <typename Func, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1111
    class_ &def(const char *name_, Func&& f, const Extra&... extra) {
1112
        cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), name(name_), is_method(*this),
1113
                        sibling(getattr(*this, name_, none())), extra...);
1114
        attr(cf.name()) = cf;
Wenzel Jakob's avatar
Wenzel Jakob committed
1115
1116
1117
        return *this;
    }

1118
    template <typename Func, typename... Extra> class_ &
1119
1120
1121
    def_static(const char *name_, Func &&f, const Extra&... extra) {
        static_assert(!std::is_member_function_pointer<Func>::value,
                "def_static(...) called with a non-static member function pointer");
1122
1123
        cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
                        sibling(getattr(*this, name_, none())), extra...);
1124
        attr(cf.name()) = cf;
Wenzel Jakob's avatar
Wenzel Jakob committed
1125
1126
1127
        return *this;
    }

1128
    template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1129
    class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
1130
        op.execute(*this, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1131
1132
1133
        return *this;
    }

1134
    template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1135
    class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
1136
        op.execute_cast(*this, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1137
1138
1139
        return *this;
    }

1140
    template <typename... Args, typename... Extra>
1141
    class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra&... extra) {
1142
        init.execute(*this, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1143
1144
1145
        return *this;
    }

1146
    template <typename... Args, typename... Extra>
1147
    class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra&... extra) {
1148
        init.execute(*this, extra...);
1149
1150
1151
        return *this;
    }

1152
1153
1154
1155
1156
1157
    template <typename... Args, typename... Extra>
    class_ &def(detail::initimpl::factory<Args...> &&init, const Extra&... extra) {
        std::move(init).execute(*this, extra...);
        return *this;
    }

1158
1159
1160
1161
1162
1163
    template <typename... Args, typename... Extra>
    class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
        std::move(pf).execute(*this, extra...);
        return *this;
    }

1164
    template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob's avatar
Wenzel Jakob committed
1165
1166
1167
        struct capture { Func func; };
        capture *ptr = new capture { std::forward<Func>(func) };
        install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
1168
            detail::make_caster<type> caster;
Wenzel Jakob's avatar
Wenzel Jakob committed
1169
1170
            if (!caster.load(obj, false))
                return nullptr;
Wenzel Jakob's avatar
Wenzel Jakob committed
1171
1172
            return new buffer_info(((capture *) ptr)->func(caster));
        }, ptr);
Wenzel Jakob's avatar
Wenzel Jakob committed
1173
1174
1175
        return *this;
    }

1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
    template <typename Return, typename Class, typename... Args>
    class_ &def_buffer(Return (Class::*func)(Args...)) {
        return def_buffer([func] (type &obj) { return (obj.*func)(); });
    }

    template <typename Return, typename Class, typename... Args>
    class_ &def_buffer(Return (Class::*func)(Args...) const) {
        return def_buffer([func] (const type &obj) { return (obj.*func)(); });
    }

1186
    template <typename C, typename D, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1187
    class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
1188
1189
1190
        static_assert(std::is_base_of<C, type>::value, "def_readwrite() requires a class member (or base class member)");
        cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this)),
                     fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
1191
        def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1192
1193
1194
        return *this;
    }

1195
    template <typename C, typename D, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1196
    class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
1197
1198
        static_assert(std::is_base_of<C, type>::value, "def_readonly() requires a class member (or base class member)");
        cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this));
1199
        def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1200
1201
1202
        return *this;
    }

1203
    template <typename D, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1204
    class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
1205
1206
1207
        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
1208
1209
1210
        return *this;
    }

1211
    template <typename D, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1212
    class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
1213
1214
        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
1215
1216
1217
        return *this;
    }

1218
1219
1220
    /// Uses return_value_policy::reference_internal by default
    template <typename Getter, typename... Extra>
    class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
1221
1222
        return def_property_readonly(name, cpp_function(method_adaptor<type>(fget)),
                                     return_value_policy::reference_internal, extra...);
1223
1224
1225
    }

    /// Uses cpp_function's return_value_policy by default
1226
1227
    template <typename... Extra>
    class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
1228
        return def_property(name, fget, nullptr, extra...);
1229
1230
1231
1232
1233
1234
    }

    /// Uses return_value_policy::reference by default
    template <typename Getter, typename... Extra>
    class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
        return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1235
1236
    }

1237
    /// Uses cpp_function's return_value_policy by default
1238
1239
    template <typename... Extra>
    class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
1240
        return def_property_static(name, fget, nullptr, extra...);
1241
1242
1243
    }

    /// Uses return_value_policy::reference_internal by default
1244
1245
1246
1247
    template <typename Getter, typename Setter, typename... Extra>
    class_ &def_property(const char *name, const Getter &fget, const Setter &fset, const Extra& ...extra) {
        return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
    }
1248
1249
    template <typename Getter, typename... Extra>
    class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1250
1251
        return def_property(name, cpp_function(method_adaptor<type>(fget)), fset,
                            return_value_policy::reference_internal, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1252
1253
    }

1254
    /// Uses cpp_function's return_value_policy by default
1255
1256
    template <typename... Extra>
    class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1257
        return def_property_static(name, fget, fset, is_method(*this), extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1258
1259
    }

1260
1261
1262
1263
1264
1265
1266
    /// Uses return_value_policy::reference by default
    template <typename Getter, typename... Extra>
    class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
        return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
    }

    /// Uses cpp_function's return_value_policy by default
1267
1268
1269
    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);
1270
1271
1272
1273
1274
1275
1276
1277
        auto *rec_active = rec_fget;
        if (rec_fget) {
           char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
           detail::process_attributes<Extra...>::init(extra..., rec_fget);
           if (rec_fget->doc && rec_fget->doc != doc_prev) {
              free(doc_prev);
              rec_fget->doc = strdup(rec_fget->doc);
           }
1278
1279
        }
        if (rec_fset) {
1280
            char *doc_prev = rec_fset->doc;
1281
            detail::process_attributes<Extra...>::init(extra..., rec_fset);
1282
1283
1284
1285
            if (rec_fset->doc && rec_fset->doc != doc_prev) {
                free(doc_prev);
                rec_fset->doc = strdup(rec_fset->doc);
            }
1286
            if (! rec_active) rec_active = rec_fset;
1287
        }
1288
        def_property_static_impl(name, fget, fset, rec_active);
Wenzel Jakob's avatar
Wenzel Jakob committed
1289
1290
        return *this;
    }
1291

Wenzel Jakob's avatar
Wenzel Jakob committed
1292
private:
1293
1294
    /// Initialize holder object, variant 1: object derives from enable_shared_from_this
    template <typename T>
1295
    static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1296
            const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
1297
        try {
1298
1299
            auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
                    v_h.value_ptr<type>()->shared_from_this());
1300
            if (sh) {
1301
                new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
1302
                v_h.set_holder_constructed();
1303
            }
1304
        } catch (const std::bad_weak_ptr &) {}
1305
1306

        if (!v_h.holder_constructed() && inst->owned) {
1307
            new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1308
            v_h.set_holder_constructed();
1309
        }
1310
1311
    }

1312
1313
    static void init_holder_from_existing(const detail::value_and_holder &v_h,
            const holder_type *holder_ptr, std::true_type /*is_copy_constructible*/) {
1314
        new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1315
1316
    }

1317
1318
    static void init_holder_from_existing(const detail::value_and_holder &v_h,
            const holder_type *holder_ptr, std::false_type /*is_copy_constructible*/) {
1319
        new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1320
1321
    }

1322
    /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
1323
    static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1324
            const holder_type *holder_ptr, const void * /* dummy -- not enable_shared_from_this<T>) */) {
1325
        if (holder_ptr) {
1326
1327
            init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
            v_h.set_holder_constructed();
1328
        } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
1329
            new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1330
            v_h.set_holder_constructed();
1331
        }
1332
1333
    }

1334
1335
1336
1337
1338
    /// Performs instance initialization including constructing a holder and registering the known
    /// instance.  Should be called as soon as the `type` value_ptr is set for an instance.  Takes an
    /// optional pointer to an existing holder to use; if not specified and the instance is
    /// `.owned`, a new holder will be constructed to manage the value pointer.
    static void init_instance(detail::instance *inst, const void *holder_ptr) {
1339
        auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
1340
1341
1342
1343
        if (!v_h.instance_registered()) {
            register_instance(inst, v_h.value_ptr(), v_h.type);
            v_h.set_instance_registered();
        }
1344
        init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
1345
1346
    }

1347
    /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
1348
1349
    static void dealloc(detail::value_and_holder &v_h) {
        if (v_h.holder_constructed()) {
1350
            v_h.holder<holder_type>().~holder_type();
1351
1352
1353
            v_h.set_holder_constructed(false);
        }
        else {
1354
1355
1356
1357
            detail::call_operator_delete(v_h.value_ptr<type>(),
                v_h.type->type_size,
                v_h.type->type_align
            );
1358
1359
        }
        v_h.value_ptr() = nullptr;
Wenzel Jakob's avatar
Wenzel Jakob committed
1360
    }
1361
1362
1363

    static detail::function_record *get_function_record(handle h) {
        h = detail::get_function(h);
Wenzel Jakob's avatar
Wenzel Jakob committed
1364
        return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
1365
                 : nullptr;
1366
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
1367
1368
};

1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
/// Binds an existing constructor taking arguments Args...
template <typename... Args> detail::initimpl::constructor<Args...> init() { return {}; }
/// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
/// when not inheriting on the Python side).
template <typename... Args> detail::initimpl::alias_constructor<Args...> init_alias() { return {}; }

/// Binds a factory function as a constructor
template <typename Func, typename Ret = detail::initimpl::factory<Func>>
Ret init(Func &&f) { return {std::forward<Func>(f)}; }

/// Dual-argument factory function: the first function is called when no alias is needed, the second
/// when an alias is needed (i.e. due to python-side inheritance).  Arguments must be identical.
template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
Ret init(CFunc &&c, AFunc &&a) {
    return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
}

/// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
/// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
template <typename GetState, typename SetState>
detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
    return {std::forward<GetState>(g), std::forward<SetState>(s)};
Marcin Wojdyr's avatar
Marcin Wojdyr committed
1391
}
1392

1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
NAMESPACE_BEGIN(detail)
struct enum_base {
    enum_base(handle base, handle parent) : m_base(base), m_parent(parent) { }

    PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
        m_base.attr("__entries") = dict();
        auto property = handle((PyObject *) &PyProperty_Type);
        auto static_property = handle((PyObject *) get_internals().static_property_type);

        m_base.attr("__repr__") = cpp_function(
            [](handle arg) -> str {
                handle type = arg.get_type();
                object type_name = type.attr("__name__");
                dict entries = type.attr("__entries");
                for (const auto &kv : entries) {
                    object other = kv.second[int_(0)];
                    if (other.equal(arg))
                        return pybind11::str("{}.{}").format(type_name, kv.first);
                }
                return pybind11::str("{}.???").format(type_name);
            }, is_method(m_base)
        );

        m_base.attr("name") = property(cpp_function(
            [](handle arg) -> str {
                dict entries = arg.get_type().attr("__entries");
                for (const auto &kv : entries) {
                    if (handle(kv.second[int_(0)]).equal(arg))
                        return pybind11::str(kv.first);
                }
                return "???";
            }, is_method(m_base)
        ));

        m_base.attr("__doc__") = static_property(cpp_function(
            [](handle arg) -> std::string {
                std::string docstring;
                dict entries = arg.attr("__entries");
                if (((PyTypeObject *) arg.ptr())->tp_doc)
                    docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) + "\n\n";
                docstring += "Members:";
                for (const auto &kv : entries) {
                    auto key = std::string(pybind11::str(kv.first));
                    auto comment = kv.second[int_(1)];
                    docstring += "\n\n  " + key;
                    if (!comment.is_none())
                        docstring += " : " + (std::string) pybind11::str(comment);
                }
                return docstring;
            }
        ), none(), none(), "");

        m_base.attr("__members__") = static_property(cpp_function(
            [](handle arg) -> dict {
                dict entries = arg.attr("__entries"), m;
                for (const auto &kv : entries)
                    m[kv.first] = kv.second[int_(0)];
                return m;
            }), none(), none(), ""
        );

1454
        #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)                     \
1455
1456
1457
            m_base.attr(op) = cpp_function(                                            \
                [](object a, object b) {                                               \
                    if (!a.get_type().is(b.get_type()))                                \
1458
                        strict_behavior;                                               \
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
                    return expr;                                                       \
                },                                                                     \
                is_method(m_base))

        #define PYBIND11_ENUM_OP_CONV(op, expr)                                        \
            m_base.attr(op) = cpp_function(                                            \
                [](object a_, object b_) {                                             \
                    int_ a(a_), b(b_);                                                 \
                    return expr;                                                       \
                },                                                                     \
                is_method(m_base))

        if (is_convertible) {
            PYBIND11_ENUM_OP_CONV("__eq__", !b.is_none() &&  a.equal(b));
            PYBIND11_ENUM_OP_CONV("__ne__",  b.is_none() || !a.equal(b));

            if (is_arithmetic) {
                PYBIND11_ENUM_OP_CONV("__lt__",   a <  b);
                PYBIND11_ENUM_OP_CONV("__gt__",   a >  b);
                PYBIND11_ENUM_OP_CONV("__le__",   a <= b);
                PYBIND11_ENUM_OP_CONV("__ge__",   a >= b);
                PYBIND11_ENUM_OP_CONV("__and__",  a &  b);
                PYBIND11_ENUM_OP_CONV("__rand__", a &  b);
                PYBIND11_ENUM_OP_CONV("__or__",   a |  b);
                PYBIND11_ENUM_OP_CONV("__ror__",  a |  b);
                PYBIND11_ENUM_OP_CONV("__xor__",  a ^  b);
                PYBIND11_ENUM_OP_CONV("__rxor__", a ^  b);
            }
        } else {
1488
1489
            PYBIND11_ENUM_OP_STRICT("__eq__",  int_(a).equal(int_(b)), return false);
            PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
1490
1491

            if (is_arithmetic) {
1492
1493
1494
1495
1496
1497
                #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
                PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) <  int_(b), PYBIND11_THROW);
                PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) >  int_(b), PYBIND11_THROW);
                PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
                PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
                #undef PYBIND11_THROW
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
            }
        }

        #undef PYBIND11_ENUM_OP_CONV
        #undef PYBIND11_ENUM_OP_STRICT

        object getstate = cpp_function(
            [](object arg) { return int_(arg); }, is_method(m_base));

        m_base.attr("__getstate__") = getstate;
        m_base.attr("__hash__") = getstate;
    }

    PYBIND11_NOINLINE void value(char const* name_, object value, const char *doc = nullptr) {
        dict entries = m_base.attr("__entries");
        str name(name_);
        if (entries.contains(name)) {
            std::string type_name = (std::string) str(m_base.attr("__name__"));
            throw value_error(type_name + ": element \"" + std::string(name_) + "\" already exists!");
        }

        entries[name] = std::make_pair(value, doc);
        m_base.attr(name) = value;
    }

    PYBIND11_NOINLINE void export_values() {
        dict entries = m_base.attr("__entries");
        for (const auto &kv : entries)
            m_parent.attr(kv.first) = kv.second[int_(0)];
    }

    handle m_base;
    handle m_parent;
};

NAMESPACE_END(detail)

Wenzel Jakob's avatar
Wenzel Jakob committed
1535
1536
1537
/// Binds C++ enumerations and enumeration classes to Python
template <typename Type> class enum_ : public class_<Type> {
public:
1538
1539
1540
1541
1542
    using Base = class_<Type>;
    using Base::def;
    using Base::attr;
    using Base::def_property_readonly;
    using Base::def_property_readonly_static;
1543
1544
    using Scalar = typename std::underlying_type<Type>::type;

Wenzel Jakob's avatar
Wenzel Jakob committed
1545
1546
    template <typename... Extra>
    enum_(const handle &scope, const char *name, const Extra&... extra)
1547
      : class_<Type>(scope, name, extra...), m_base(*this, scope) {
1548
        constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
1549
1550
        constexpr bool is_convertible = std::is_convertible<Type, Scalar>::value;
        m_base.init(is_arithmetic, is_convertible);
1551

1552
        def(init([](Scalar i) { return static_cast<Type>(i); }));
1553
        def("__int__", [](Type value) { return (Scalar) value; });
1554
1555
1556
        #if PY_MAJOR_VERSION < 3
            def("__long__", [](Type value) { return (Scalar) value; });
        #endif
1557
1558
1559
1560
        cpp_function setstate(
            [](Type &value, Scalar arg) { value = static_cast<Type>(arg); },
            is_method(*this));
        attr("__setstate__") = setstate;
Wenzel Jakob's avatar
Wenzel Jakob committed
1561
1562
1563
    }

    /// Export enumeration entries into the parent scope
1564
    enum_& export_values() {
1565
        m_base.export_values();
1566
        return *this;
Wenzel Jakob's avatar
Wenzel Jakob committed
1567
1568
1569
    }

    /// Add an enumeration entry
1570
    enum_& value(char const* name, Type value, const char *doc = nullptr) {
1571
        m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
Wenzel Jakob's avatar
Wenzel Jakob committed
1572
1573
        return *this;
    }
1574

Wenzel Jakob's avatar
Wenzel Jakob committed
1575
private:
1576
    detail::enum_base m_base;
Wenzel Jakob's avatar
Wenzel Jakob committed
1577
1578
1579
};

NAMESPACE_BEGIN(detail)
1580

1581

1582
inline void keep_alive_impl(handle nurse, handle patient) {
1583
    if (!nurse || !patient)
1584
        pybind11_fail("Could not activate keep_alive!");
1585

1586
    if (patient.is_none() || nurse.is_none())
1587
        return; /* Nothing to keep alive or nothing to be kept alive by */
1588

1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
    auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
    if (!tinfo.empty()) {
        /* It's a pybind-registered type, so we can store the patient in the
         * internal list. */
        add_patient(nurse.ptr(), patient.ptr());
    }
    else {
        /* Fall back to clever approach based on weak references taken from
         * Boost.Python. This is not used for pybind-registered types because
         * the objects can be destroyed out-of-order in a GC pass. */
        cpp_function disable_lifesupport(
            [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
1601

1602
        weakref wr(nurse, disable_lifesupport);
1603

1604
1605
1606
        patient.inc_ref(); /* reference patient and leak the weak reference */
        (void) wr.release();
    }
1607
1608
}

1609
PYBIND11_NOINLINE inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
    auto get_arg = [&](size_t n) {
        if (n == 0)
            return ret;
        else if (n == 1 && call.init_self)
            return call.init_self;
        else if (n <= call.args.size())
            return call.args[n - 1];
        return handle();
    };

    keep_alive_impl(get_arg(Nurse), get_arg(Patient));
1621
1622
}

1623
1624
inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type) {
    auto res = get_internals().registered_types_py
Jason Rhinelander's avatar
Jason Rhinelander committed
1625
#ifdef __cpp_lib_unordered_map_try_emplace
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
        .try_emplace(type);
#else
        .emplace(type, std::vector<detail::type_info *>());
#endif
    if (res.second) {
        // New cache entry created; set up a weak reference to automatically remove it if the type
        // gets destroyed:
        weakref((PyObject *) type, cpp_function([type](handle wr) {
            get_internals().registered_types_py.erase(type);
            wr.dec_ref();
        })).release();
    }

    return res;
}

1642
template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
1643
1644
1645
struct iterator_state {
    Iterator it;
    Sentinel end;
1646
    bool first_or_done;
1647
};
1648

Wenzel Jakob's avatar
Wenzel Jakob committed
1649
1650
NAMESPACE_END(detail)

1651
/// Makes a python iterator from a first and past-the-end C++ InputIterator.
1652
1653
template <return_value_policy Policy = return_value_policy::reference_internal,
          typename Iterator,
1654
          typename Sentinel,
1655
1656
          typename ValueType = decltype(*std::declval<Iterator>()),
          typename... Extra>
1657
iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1658
    typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
1659

Wenzel Jakob's avatar
Wenzel Jakob committed
1660
    if (!detail::get_type_info(typeid(state), false)) {
1661
        class_<state>(handle(), "iterator", pybind11::module_local())
1662
            .def("__iter__", [](state &s) -> state& { return s; })
1663
            .def("__next__", [](state &s) -> ValueType {
1664
                if (!s.first_or_done)
1665
1666
                    ++s.it;
                else
1667
1668
1669
                    s.first_or_done = false;
                if (s.it == s.end) {
                    s.first_or_done = true;
1670
                    throw stop_iteration();
1671
                }
1672
                return *s.it;
1673
            }, std::forward<Extra>(extra)..., Policy);
1674
1675
    }

1676
    return cast(state{first, last, true});
1677
}
1678

1679
1680
/// Makes an python iterator over the keys (`.first`) of a iterator over pairs from a
/// first and past-the-end InputIterator.
1681
1682
template <return_value_policy Policy = return_value_policy::reference_internal,
          typename Iterator,
1683
          typename Sentinel,
1684
          typename KeyType = decltype((*std::declval<Iterator>()).first),
1685
          typename... Extra>
1686
iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1687
    typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
1688

Wenzel Jakob's avatar
Wenzel Jakob committed
1689
    if (!detail::get_type_info(typeid(state), false)) {
1690
        class_<state>(handle(), "iterator", pybind11::module_local())
1691
1692
            .def("__iter__", [](state &s) -> state& { return s; })
            .def("__next__", [](state &s) -> KeyType {
1693
                if (!s.first_or_done)
1694
1695
                    ++s.it;
                else
1696
1697
1698
                    s.first_or_done = false;
                if (s.it == s.end) {
                    s.first_or_done = true;
1699
                    throw stop_iteration();
1700
                }
1701
                return (*s.it).first;
1702
            }, std::forward<Extra>(extra)..., Policy);
1703
1704
    }

1705
    return cast(state{first, last, true});
1706
}
1707

1708
1709
/// Makes an iterator over values of an stl container or other container supporting
/// `std::begin()`/`std::end()`
1710
1711
1712
template <return_value_policy Policy = return_value_policy::reference_internal,
          typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
    return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
1713
1714
}

1715
1716
/// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
/// `std::begin()`/`std::end()`
1717
1718
1719
template <return_value_policy Policy = return_value_policy::reference_internal,
          typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
    return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
1720
1721
}

Wenzel Jakob's avatar
Wenzel Jakob committed
1722
template <typename InputType, typename OutputType> void implicitly_convertible() {
1723
1724
1725
1726
1727
    struct set_flag {
        bool &flag;
        set_flag(bool &flag) : flag(flag) { flag = true; }
        ~set_flag() { flag = false; }
    };
1728
    auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
1729
1730
1731
1732
        static bool currently_used = false;
        if (currently_used) // implicit conversions are non-reentrant
            return nullptr;
        set_flag flag_helper(currently_used);
1733
        if (!detail::make_caster<InputType>().load(obj, false))
Wenzel Jakob's avatar
Wenzel Jakob committed
1734
1735
1736
1737
1738
1739
1740
1741
            return nullptr;
        tuple args(1);
        args[0] = obj;
        PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
        if (result == nullptr)
            PyErr_Clear();
        return result;
    };
1742
1743
1744
1745

    if (auto tinfo = detail::get_type_info(typeid(OutputType)))
        tinfo->implicit_conversions.push_back(implicit_caster);
    else
1746
        pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
Wenzel Jakob's avatar
Wenzel Jakob committed
1747
1748
}

1749
1750
1751
1752
1753
1754
template <typename ExceptionTranslator>
void register_exception_translator(ExceptionTranslator&& translator) {
    detail::get_internals().registered_exception_translators.push_front(
        std::forward<ExceptionTranslator>(translator));
}

1755
1756
/**
 * Wrapper to generate a new Python exception type.
1757
1758
1759
1760
1761
1762
1763
1764
 *
 * 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:
1765
    exception() = default;
1766
1767
1768
    exception(handle scope, const char *name, PyObject *base = PyExc_Exception) {
        std::string full_name = scope.attr("__name__").cast<std::string>() +
                                std::string(".") + name;
1769
        m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base, NULL);
1770
1771
1772
1773
        if (hasattr(scope, name))
            pybind11_fail("Error during initialization: multiple incompatible "
                          "definitions with name \"" + std::string(name) + "\"");
        scope.attr(name) = *this;
1774
    }
1775
1776
1777
1778
1779

    // Sets the current python exception to this exception object with the given message
    void operator()(const char *message) {
        PyErr_SetString(m_ptr, message);
    }
1780
1781
};

1782
1783
1784
1785
1786
1787
1788
1789
NAMESPACE_BEGIN(detail)
// Returns a reference to a function-local static exception object used in the simple
// register_exception approach below.  (It would be simpler to have the static local variable
// directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
template <typename CppException>
exception<CppException> &get_exception_object() { static exception<CppException> ex; return ex; }
NAMESPACE_END(detail)

1790
1791
/**
 * Registers a Python exception in `m` of the given `name` and installs an exception translator to
1792
1793
1794
1795
 * translate the C++ exception to the created Python exception using the exceptions what() method.
 * This is intended for simple exception translations; for more complex translation, register the
 * exception object and translator directly.
 */
1796
1797
1798
1799
template <typename CppException>
exception<CppException> &register_exception(handle scope,
                                            const char *name,
                                            PyObject *base = PyExc_Exception) {
1800
1801
1802
    auto &ex = detail::get_exception_object<CppException>();
    if (!ex) ex = exception<CppException>(scope, name, base);

1803
1804
1805
1806
    register_exception_translator([](std::exception_ptr p) {
        if (!p) return;
        try {
            std::rethrow_exception(p);
1807
        } catch (const CppException &e) {
1808
            detail::get_exception_object<CppException>()(e.what());
1809
1810
1811
1812
1813
        }
    });
    return ex;
}

Dean Moldovan's avatar
Dean Moldovan committed
1814
1815
1816
1817
NAMESPACE_BEGIN(detail)
PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
    auto strings = tuple(args.size());
    for (size_t i = 0; i < args.size(); ++i) {
1818
        strings[i] = str(args[i]);
Dean Moldovan's avatar
Dean Moldovan committed
1819
    }
1820
    auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
1821
    auto line = sep.attr("join")(strings);
Dean Moldovan's avatar
Dean Moldovan committed
1822

1823
1824
1825
1826
1827
1828
    object file;
    if (kwargs.contains("file")) {
        file = kwargs["file"].cast<object>();
    } else {
        try {
            file = module::import("sys").attr("stdout");
1829
        } catch (const error_already_set &) {
1830
1831
1832
1833
1834
1835
1836
1837
            /* If print() is called from code that is executed as
               part of garbage collection during interpreter shutdown,
               importing 'sys' can fail. Give up rather than crashing the
               interpreter in this case. */
            return;
        }
    }

1838
    auto write = file.attr("write");
Dean Moldovan's avatar
Dean Moldovan committed
1839
    write(line);
1840
    write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
Dean Moldovan's avatar
Dean Moldovan committed
1841

1842
    if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
1843
        file.attr("flush")();
Dean Moldovan's avatar
Dean Moldovan committed
1844
1845
1846
1847
1848
1849
1850
1851
1852
}
NAMESPACE_END(detail)

template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
void print(Args &&...args) {
    auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
    detail::print(c.args(), c.kwargs());
}

Wenzel Jakob's avatar
Wenzel Jakob committed
1853
#if defined(WITH_THREAD) && !defined(PYPY_VERSION)
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867

/* 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
1868
1869
 *    thread would otherwise constantly construct and destroy thread state data
 *    structures.
1870
1871
1872
1873
1874
 *
 * 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).
1875
 */
Wenzel Jakob's avatar
Wenzel Jakob committed
1876
1877
1878

class gil_scoped_acquire {
public:
1879
    PYBIND11_NOINLINE gil_scoped_acquire() {
1880
        auto const &internals = detail::get_internals();
1881
        tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
1882

1883
1884
1885
1886
1887
1888
1889
1890
1891
        if (!tstate) {
            /* Check if the GIL was acquired using the PyGILState_* API instead (e.g. if
               calling from a Python thread). Since we use a different key, this ensures
               we don't create a new thread state and deadlock in PyEval_AcquireThread
               below. Note we don't save this state with internals.tstate, since we don't
               create it we would fail to clear it (its reference count should be > 0). */
            tstate = PyGILState_GetThisThreadState();
        }

1892
1893
1894
1895
1896
1897
1898
        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;
1899
            PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
1900
        } else {
1901
            release = detail::get_thread_state_unchecked() != tstate;
1902
1903
1904
1905
        }

        if (release) {
            /* Work around an annoying assertion in PyThreadState_Swap */
1906
1907
1908
1909
            #if defined(Py_DEBUG)
                PyInterpreterState *interp = tstate->interp;
                tstate->interp = nullptr;
            #endif
1910
            PyEval_AcquireThread(tstate);
1911
1912
1913
            #if defined(Py_DEBUG)
                tstate->interp = interp;
            #endif
1914
1915
1916
1917
1918
1919
1920
1921
1922
        }

        inc_ref();
    }

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

1923
    PYBIND11_NOINLINE void dec_ref() {
1924
1925
        --tstate->gilstate_counter;
        #if !defined(NDEBUG)
1926
            if (detail::get_thread_state_unchecked() != tstate)
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
                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();
1938
            PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
1939
1940
1941
1942
            release = false;
        }
    }

1943
    PYBIND11_NOINLINE ~gil_scoped_acquire() {
1944
1945
1946
1947
1948
1949
1950
        dec_ref();
        if (release)
           PyEval_SaveThread();
    }
private:
    PyThreadState *tstate = nullptr;
    bool release = true;
Wenzel Jakob's avatar
Wenzel Jakob committed
1951
1952
1953
1954
};

class gil_scoped_release {
public:
1955
    explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
1956
1957
1958
1959
        // `get_internals()` must be called here unconditionally in order to initialize
        // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
        // initialization race could occur as multiple threads try `gil_scoped_acquire`.
        const auto &internals = detail::get_internals();
1960
        tstate = PyEval_SaveThread();
1961
        if (disassoc) {
1962
            auto key = internals.tstate;
1963
            PYBIND11_TLS_DELETE_VALUE(key);
1964
        }
1965
1966
1967
1968
1969
    }
    ~gil_scoped_release() {
        if (!tstate)
            return;
        PyEval_RestoreThread(tstate);
1970
        if (disassoc) {
1971
            auto key = detail::get_internals().tstate;
1972
            PYBIND11_TLS_REPLACE_VALUE(key, tstate);
1973
        }
1974
1975
1976
1977
    }
private:
    PyThreadState *tstate;
    bool disassoc;
Wenzel Jakob's avatar
Wenzel Jakob committed
1978
};
Wenzel Jakob's avatar
Wenzel Jakob committed
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
#elif defined(PYPY_VERSION)
class gil_scoped_acquire {
    PyGILState_STATE state;
public:
    gil_scoped_acquire() { state = PyGILState_Ensure(); }
    ~gil_scoped_acquire() { PyGILState_Release(state); }
};

class gil_scoped_release {
    PyThreadState *state;
public:
    gil_scoped_release() { state = PyEval_SaveThread(); }
    ~gil_scoped_release() { PyEval_RestoreThread(state); }
};
1993
1994
1995
#else
class gil_scoped_acquire { };
class gil_scoped_release { };
1996
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
1997

1998
error_already_set::~error_already_set() {
1999
    if (m_type) {
2000
        error_scope scope;
2001
        gil_scoped_acquire gil;
2002
2003
2004
        m_type.release().dec_ref();
        m_value.release().dec_ref();
        m_trace.release().dec_ref();
2005
2006
2007
    }
}

2008
inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name)  {
Wenzel Jakob's avatar
Wenzel Jakob committed
2009
2010
    handle self = detail::get_object_handle(this_ptr, this_type);
    if (!self)
2011
        return function();
Wenzel Jakob's avatar
Wenzel Jakob committed
2012
    handle type = self.get_type();
2013
2014
    auto key = std::make_pair(type.ptr(), name);

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

Wenzel Jakob's avatar
Wenzel Jakob committed
2021
    function overload = getattr(self, name, function());
2022
2023
2024
2025
    if (overload.is_cpp_function()) {
        cache.insert(key);
        return function();
    }
2026

Wenzel Jakob's avatar
Wenzel Jakob committed
2027
2028
2029
    /* Don't call dispatch code if invoked from overridden function.
       Unfortunately this doesn't work on PyPy. */
#if !defined(PYPY_VERSION)
2030
    PyFrameObject *frame = PyThreadState_Get()->frame;
2031
    if (frame && (std::string) str(frame->f_code->co_name) == name &&
2032
2033
2034
2035
        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));
Wenzel Jakob's avatar
Wenzel Jakob committed
2036
        if (self_caller == self.ptr())
2037
2038
            return function();
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
#else
    /* PyPy currently doesn't provide a detailed cpyext emulation of
       frame objects, so we have to emulate this using Python. This
       is going to be slow..*/
    dict d; d["self"] = self; d["name"] = pybind11::str(name);
    PyObject *result = PyRun_String(
        "import inspect\n"
        "frame = inspect.currentframe()\n"
        "if frame is not None:\n"
        "    frame = frame.f_back\n"
        "    if frame is not None and str(frame.f_code.co_name) == name and "
        "frame.f_code.co_argcount > 0:\n"
        "        self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
        "        if self_caller == self:\n"
        "            self = None\n",
        Py_file_input, d.ptr(), d.ptr());
    if (result == nullptr)
        throw error_already_set();
2057
    if (d["self"].is_none())
Wenzel Jakob's avatar
Wenzel Jakob committed
2058
2059
2060
2061
        return function();
    Py_DECREF(result);
#endif

2062
2063
2064
    return overload;
}

2065
template <class T> function get_overload(const T *this_ptr, const char *name) {
2066
2067
    auto tinfo = detail::get_type_info(typeid(T));
    return tinfo ? get_type_overload(this_ptr, tinfo, name) : function();
2068
2069
}

2070
#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
2071
        pybind11::gil_scoped_acquire gil; \
2072
        pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
2073
        if (overload) { \
2074
            auto o = overload(__VA_ARGS__); \
2075
            if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
2076
2077
                static pybind11::detail::overload_caster_t<ret_type> caster; \
                return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
2078
2079
2080
2081
            } \
            else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
        } \
    }
2082

2083
#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
2084
    PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
2085
    return cname::fn(__VA_ARGS__)
2086

2087
#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
2088
    PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
2089
    pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\"");
2090
2091

#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
2092
    PYBIND11_OVERLOAD_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2093
2094

#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2095
    PYBIND11_OVERLOAD_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2096

2097
NAMESPACE_END(PYBIND11_NAMESPACE)
Wenzel Jakob's avatar
Wenzel Jakob committed
2098

2099
#if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
Wenzel Jakob's avatar
Wenzel Jakob committed
2100
#  pragma warning(pop)
2101
#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob's avatar
Wenzel Jakob committed
2102
#  pragma GCC diagnostic pop
Wenzel Jakob's avatar
Wenzel Jakob committed
2103
#endif