pybind11.h 109 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

Wenzel Jakob's avatar
Wenzel Jakob committed
13
#include "attr.h"
14
#include "gil.h"
15
#include "options.h"
16
#include "detail/class.h"
17
#include "detail/init.h"
Wenzel Jakob's avatar
Wenzel Jakob committed
18

19
#include <memory>
20
#include <new>
21
22
23
24
#include <vector>
#include <string>
#include <utility>

25
26
#include <string.h>

27
28
29
30
31
32
33
#if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914))
#  define PYBIND11_STD_LAUNDER std::launder
#  define PYBIND11_HAS_STD_LAUNDER 1
#else
#  define PYBIND11_STD_LAUNDER
#  define PYBIND11_HAS_STD_LAUNDER 0
#endif
34
35
36
37
#if defined(__GNUG__) && !defined(__clang__)
#  include <cxxabi.h>
#endif

38
39
40
41
42
43
44
45
46
47
48
49
/* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning
   This warning is about ABI compatibility, not code health.
   It is only actually needed in a couple places, but apparently GCC 7 "generates this warning if
   and only if the first template instantiation ... involves noexcept" [stackoverflow], therefore
   it could get triggered from seemingly random places, depending on user code.
   No other GCC version generates this warning.
 */
#if defined(__GNUC__) && __GNUC__ == 7
#    pragma GCC diagnostic push
#    pragma GCC diagnostic ignored "-Wnoexcept-type"
#endif

50
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
Wenzel Jakob's avatar
Wenzel Jakob committed
51

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
PYBIND11_NAMESPACE_BEGIN(detail)

// Apply all the extensions translators from a list
// Return true if one of the translators completed without raising an exception
// itself. Return of false indicates that if there are other translators
// available, they should be tried.
inline bool apply_exception_translators(std::forward_list<ExceptionTranslator>& translators) {
    auto last_exception = std::current_exception();

    for (auto &translator : translators) {
        try {
            translator(last_exception);
            return true;
        } catch (...) {
            last_exception = std::current_exception();
        }
    }
    return false;
}

72
73
74
75
76
#if defined(_MSC_VER)
#    define PYBIND11_COMPAT_STRDUP _strdup
#else
#    define PYBIND11_COMPAT_STRDUP strdup
#endif
77

78
PYBIND11_NAMESPACE_END(detail)
79

Wenzel Jakob's avatar
Wenzel Jakob committed
80
/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
81
class cpp_function : public function {
Wenzel Jakob's avatar
Wenzel Jakob committed
82
public:
83
    cpp_function() = default;
84
    // NOLINTNEXTLINE(google-explicit-constructor)
85
    cpp_function(std::nullptr_t) { }
Wenzel Jakob's avatar
Wenzel Jakob committed
86

87
    /// Construct a cpp_function from a vanilla function pointer
88
    template <typename Return, typename... Args, typename... Extra>
89
    // NOLINTNEXTLINE(google-explicit-constructor)
90
    cpp_function(Return (*f)(Args...), const Extra&... extra) {
91
        initialize(f, f, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
92
93
    }

94
    /// Construct a cpp_function from a lambda function (possibly with internal state)
95
96
    template <typename Func, typename... Extra,
              typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
97
    // NOLINTNEXTLINE(google-explicit-constructor)
98
    cpp_function(Func &&f, const Extra&... extra) {
99
        initialize(std::forward<Func>(f),
100
                   (detail::function_signature_t<Func> *) nullptr, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
101
102
    }

103
    /// Construct a cpp_function from a class method (non-const, no ref-qualifier)
104
    template <typename Return, typename Class, typename... Arg, typename... Extra>
105
    // NOLINTNEXTLINE(google-explicit-constructor)
106
    cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
107
        initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
108
                   (Return (*) (Class *, Arg...)) nullptr, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
109
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
110

111
112
113
114
    /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier)
    /// A copy of the overload for non-const functions without explicit ref-qualifier
    /// but with an added `&`.
    template <typename Return, typename Class, typename... Arg, typename... Extra>
115
    // NOLINTNEXTLINE(google-explicit-constructor)
116
117
118
119
120
121
    cpp_function(Return (Class::*f)(Arg...)&, const Extra&... extra) {
        initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
                   (Return (*) (Class *, Arg...)) nullptr, extra...);
    }

    /// Construct a cpp_function from a class method (const, no ref-qualifier)
122
    template <typename Return, typename Class, typename... Arg, typename... Extra>
123
    // NOLINTNEXTLINE(google-explicit-constructor)
124
    cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
125
        initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
126
                   (Return (*)(const Class *, Arg ...)) nullptr, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
127
128
    }

129
130
131
132
    /// Construct a cpp_function from a class method (const, lvalue ref-qualifier)
    /// A copy of the overload for const functions without explicit ref-qualifier
    /// but with an added `&`.
    template <typename Return, typename Class, typename... Arg, typename... Extra>
133
    // NOLINTNEXTLINE(google-explicit-constructor)
134
135
136
137
138
    cpp_function(Return (Class::*f)(Arg...) const&, const Extra&... extra) {
        initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
                   (Return (*)(const Class *, Arg ...)) nullptr, extra...);
    }

139
    /// Return the function name
Wenzel Jakob's avatar
Wenzel Jakob committed
140
    object name() const { return attr("__name__"); }
141

142
protected:
143
144
145
146
147
148
149
    struct InitializingFunctionRecordDeleter {
        // `destruct(function_record, false)`: `initialize_generic` copies strings and
        // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`.
        void operator()(detail::function_record * rec) { destruct(rec, false); }
    };
    using unique_function_record = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;

150
    /// Space optimization: don't inline this frequently instantiated fragment
151
152
    PYBIND11_NOINLINE unique_function_record make_function_record() {
        return unique_function_record(new detail::function_record());
153
154
    }

155
    /// Special internal constructor for functors, lambda functions, etc.
156
157
    template <typename Func, typename Return, typename... Args, typename... Extra>
    void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
158
        using namespace detail;
159
        struct capture { remove_reference_t<Func> f; };
Wenzel Jakob's avatar
Wenzel Jakob committed
160

161
        /* Store the function including any extra state it might have (e.g. a lambda capture object) */
162
163
164
        // The unique_ptr makes sure nothing is leaked in case of an exception.
        auto unique_rec = make_function_record();
        auto rec = unique_rec.get();
165

166
        /* Store the capture object directly in the function record if there is enough space */
167
        if (PYBIND11_SILENCE_MSVC_C4127(sizeof(capture) <= sizeof(rec->data))) {
168
169
170
            /* 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. */
171
#if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER)
172
173
174
#  pragma GCC diagnostic push
#  pragma GCC diagnostic ignored "-Wplacement-new"
#endif
175
            new ((capture *) &rec->data) capture { std::forward<Func>(f) };
176
#if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER)
177
178
#  pragma GCC diagnostic pop
#endif
179
180
181
182
183
184
#if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER)
#  pragma GCC diagnostic push
#  pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
            // UB without std::launder, but without breaking ABI and/or
            // a significant refactoring it's "impossible" to solve.
185
            if (!std::is_trivially_destructible<capture>::value)
186
187
188
189
190
191
192
193
                rec->free_data = [](function_record *r) {
                    auto data = PYBIND11_STD_LAUNDER((capture *) &r->data);
                    (void) data;
                    data->~capture();
                };
#if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER)
#  pragma GCC diagnostic pop
#endif
194
195
        } else {
            rec->data[0] = new capture { std::forward<Func>(f) };
196
            rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
197
        }
198

199
        /* Type casters for the function arguments and return value */
200
201
202
        using cast_in = argument_loader<Args...>;
        using cast_out = make_caster<
            conditional_t<std::is_void<Return>::value, void_type, Return>
203
        >;
Wenzel Jakob's avatar
Wenzel Jakob committed
204

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

208
        /* Dispatch code which converts function arguments and performs the actual function call */
209
        rec->impl = [](function_call &call) -> handle {
210
            cast_in args_converter;
211
212

            /* Try to cast the function arguments into the C++ domain */
213
            if (!args_converter.load_args(call))
214
215
                return PYBIND11_TRY_NEXT_OVERLOAD;

Wenzel Jakob's avatar
Wenzel Jakob committed
216
            /* Invoke call policy pre-call hook */
217
            process_attributes<Extra...>::precall(call);
218
219

            /* Get a pointer to the capture object */
220
221
            auto data = (sizeof(capture) <= sizeof(call.func.data)
                         ? &call.func.data : call.func.data[0]);
222
            auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
223

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

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

230
            /* Perform the function call */
231
232
            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
233
234

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

237
            return result;
Wenzel Jakob's avatar
Wenzel Jakob committed
238
239
        };

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

243
        {
Henry Schreiner's avatar
Henry Schreiner committed
244
245
            constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
                           has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
246
247
                           has_args = any_of<std::is_same<args, Args>...>::value,
                           has_arg_annotations = any_of<is_keyword<Extra>...>::value;
Henry Schreiner's avatar
Henry Schreiner committed
248
249
250
            static_assert(has_arg_annotations || !has_kw_only_args, "py::kw_only requires the use of argument annotations");
            static_assert(has_arg_annotations || !has_pos_only_args, "py::pos_only requires the use of argument annotations (for docstrings and aligning the annotations to the argument)");
            static_assert(!(has_args && has_kw_only_args), "py::kw_only cannot be combined with a py::args argument");
251
252
        }

253
        /* Generate a readable signature describing the function's arguments and return value types */
254
255
        static constexpr auto signature = _("(") + cast_in::arg_names + _(") -> ") + cast_out::name;
        PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
256
257

        /* Register the function with Python from generic (non-templated) code */
258
259
        // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid.
        initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));
260
261
262

        if (cast_in::has_args) rec->has_args = true;
        if (cast_in::has_kwargs) rec->has_kwargs = true;
263
264

        /* Stash some additional information used by an important optimization in 'functional.h' */
265
        using FunctionType = Return (*)(Args...);
266
267
268
269
270
        constexpr bool is_function_ptr =
            std::is_convertible<Func, FunctionType>::value &&
            sizeof(capture) == sizeof(void *);
        if (is_function_ptr) {
            rec->is_stateless = true;
271
            rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
272
        }
273
274
    }

275
276
277
278
279
280
281
282
283
    // Utility class that keeps track of all duplicated strings, and cleans them up in its destructor,
    // unless they are released. Basically a RAII-solution to deal with exceptions along the way.
    class strdup_guard {
    public:
        ~strdup_guard() {
            for (auto s : strings)
                std::free(s);
        }
        char *operator()(const char *s) {
284
            auto t = PYBIND11_COMPAT_STRDUP(s);
285
286
287
288
289
290
291
292
293
294
            strings.push_back(t);
            return t;
        }
        void release() {
            strings.clear();
        }
    private:
        std::vector<char *> strings;
    };

295
    /// Register a function call with Python (generic non-templated code goes here)
296
    void initialize_generic(unique_function_record &&unique_rec, const char *text,
297
                            const std::type_info *const *types, size_t args) {
298
299
300
301
302
303
304
305
306
307
308
        // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr,
        // we do not want this to destuct the pointer. `initialize` (the caller) still relies on the
        // pointee being alive after this call. Only move out if a `capsule` is going to keep it alive.
        auto rec = unique_rec.get();

        // Keep track of strdup'ed strings, and clean them up as long as the function's capsule
        // has not taken ownership yet (when `unique_rec.release()` is called).
        // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the strings
        // are only referenced before strdup'ing. So only *after* the following block could `destruct`
        // safely be called, but even then, `repr` could still throw in the middle of copying all strings.
        strdup_guard guarded_strdup;
Wenzel Jakob's avatar
Wenzel Jakob committed
309

310
        /* Create copies of all referenced C-style strings */
311
312
        rec->name = guarded_strdup(rec->name ? rec->name : "");
        if (rec->doc) rec->doc = guarded_strdup(rec->doc);
Wenzel Jakob's avatar
Wenzel Jakob committed
313
        for (auto &a: rec->args) {
314
            if (a.name)
315
                a.name = guarded_strdup(a.name);
316
            if (a.descr)
317
                a.descr = guarded_strdup(a.descr);
318
            else if (a.value)
319
                a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());
320
        }
321

322
323
        rec->is_constructor
            = (strcmp(rec->name, "__init__") == 0) || (strcmp(rec->name, "__setstate__") == 0);
324

325
326
#if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
        if (rec->is_constructor && !rec->is_new_style_constructor) {
327
            const auto class_name = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
328
329
330
331
332
333
334
335
336
337
338
            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

339
340
        /* Generate a proper function signature */
        std::string signature;
341
342
343
        size_t type_index = 0, arg_index = 0;
        for (auto *pc = text; *pc != '\0'; ++pc) {
            const auto c = *pc;
344
345

            if (c == '{') {
346
347
348
                // Write arg name for everything except *args and **kwargs.
                if (*(pc + 1) == '*')
                    continue;
Henry Schreiner's avatar
Henry Schreiner committed
349
350
351
352
                // Separator for keyword-only arguments, placed before the kw
                // arguments start
                if (rec->nargs_kw_only > 0 && arg_index + rec->nargs_kw_only == args)
                    signature += "*, ";
353
354
355
356
357
358
                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));
359
                }
360
                signature += ": ";
361
            } else if (c == '}') {
362
363
                // Write default value if available.
                if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
364
                    signature += " = ";
365
                    signature += rec->args[arg_index].descr;
366
                }
Henry Schreiner's avatar
Henry Schreiner committed
367
368
369
370
                // Separator for positional-only arguments (placed after the
                // argument, rather than before like *
                if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only)
                    signature += ", /";
371
                arg_index++;
372
373
            } else if (c == '%') {
                const std::type_info *t = types[type_index++];
374
                if (!t)
375
                    pybind11_fail("Internal error while parsing type signature (1)");
376
                if (auto tinfo = detail::get_type_info(*t)) {
377
378
379
380
                    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
381
382
383
                } 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.
384
385
386
                    signature +=
                        rec->scope.attr("__module__").cast<std::string>() + "." +
                        rec->scope.attr("__qualname__").cast<std::string>();
387
388
389
390
391
392
393
394
395
                } else {
                    std::string tname(t->name());
                    detail::clean_type_id(tname);
                    signature += tname;
                }
            } else {
                signature += c;
            }
        }
Henry Schreiner's avatar
Henry Schreiner committed
396

397
        if (arg_index != args || types[type_index] != nullptr)
398
            pybind11_fail("Internal error while parsing type signature (2)");
399

400
#if PY_MAJOR_VERSION < 3
Wenzel Jakob's avatar
Wenzel Jakob committed
401
402
        if (strcmp(rec->name, "__next__") == 0) {
            std::free(rec->name);
403
            rec->name = guarded_strdup("next");
404
405
        } else if (strcmp(rec->name, "__bool__") == 0) {
            std::free(rec->name);
406
            rec->name = guarded_strdup("__nonzero__");
407
        }
408
#endif
409
        rec->signature = guarded_strdup(signature.c_str());
Wenzel Jakob's avatar
Wenzel Jakob committed
410
        rec->args.shrink_to_fit();
411
        rec->nargs = (std::uint16_t) args;
412

413
414
        if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr()))
            rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
415

Wenzel Jakob's avatar
Wenzel Jakob committed
416
        detail::function_record *chain = nullptr, *chain_start = rec;
417
418
        if (rec->sibling) {
            if (PyCFunction_Check(rec->sibling.ptr())) {
Wenzel Jakob's avatar
Wenzel Jakob committed
419
                auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
420
421
422
                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 */
423
                if (!chain->scope.is(rec->scope))
424
425
426
427
428
429
                    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");
430
431
        }

Wenzel Jakob's avatar
Wenzel Jakob committed
432
        if (!chain) {
433
            /* No existing overload was found, create a new function object */
Wenzel Jakob's avatar
Wenzel Jakob committed
434
            rec->def = new PyMethodDef();
435
            std::memset(rec->def, 0, sizeof(PyMethodDef));
Wenzel Jakob's avatar
Wenzel Jakob committed
436
            rec->def->ml_name = rec->name;
437
            rec->def->ml_meth
438
                = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher));
Wenzel Jakob's avatar
Wenzel Jakob committed
439
            rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
440

441
            capsule rec_capsule(unique_rec.release(), [](void *ptr) {
442
                destruct((detail::function_record *) ptr);
443
            });
444
            guarded_strdup.release();
445
446
447

            object scope_module;
            if (rec->scope) {
448
449
450
451
452
                if (hasattr(rec->scope, "__module__")) {
                    scope_module = rec->scope.attr("__module__");
                } else if (hasattr(rec->scope, "__name__")) {
                    scope_module = rec->scope.attr("__name__");
                }
453
454
455
            }

            m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
Wenzel Jakob's avatar
Wenzel Jakob committed
456
            if (!m_ptr)
457
                pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob's avatar
Wenzel Jakob committed
458
        } else {
459
            /* Append at the beginning or end of the overload chain */
Wenzel Jakob's avatar
Wenzel Jakob committed
460
            m_ptr = rec->sibling.ptr();
Wenzel Jakob's avatar
Wenzel Jakob committed
461
            inc_ref();
462
463
464
465
466
467
468
469
470
            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
                );
471
472
473
474
475
476
477
478

            if (rec->prepend) {
                // Beginning of chain; we need to replace the capsule's current head-of-the-chain
                // pointer with this one, then make this one point to the previous head of the
                // chain.
                chain_start = rec;
                rec->next = chain;
                auto rec_capsule = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self);
479
480
                rec_capsule.set_pointer(unique_rec.release());
                guarded_strdup.release();
481
482
483
484
485
            } else {
                // Or end of chain (normal behavior)
                chain_start = chain;
                while (chain->next)
                    chain = chain->next;
486
487
                chain->next = unique_rec.release();
                guarded_strdup.release();
488
            }
Wenzel Jakob's avatar
Wenzel Jakob committed
489
        }
490

Wenzel Jakob's avatar
Wenzel Jakob committed
491
        std::string signatures;
492
        int index = 0;
Wenzel Jakob's avatar
Wenzel Jakob committed
493
        /* Create a nice pydoc rec including all signatures and
494
           docstrings of the functions in the overload chain */
495
        if (chain && options::show_function_signatures()) {
496
497
498
499
500
501
            // First a generic signature
            signatures += rec->name;
            signatures += "(*args, **kwargs)\n";
            signatures += "Overloaded function.\n\n";
        }
        // Then specific overload signatures
502
        bool first_user_def = true;
Wenzel Jakob's avatar
Wenzel Jakob committed
503
        for (auto it = chain_start; it != nullptr; it = it->next) {
504
            if (options::show_function_signatures()) {
505
                if (index > 0) signatures += "\n";
506
507
508
509
                if (chain)
                    signatures += std::to_string(++index) + ". ";
                signatures += rec->name;
                signatures += it->signature;
510
                signatures += "\n";
511
            }
cyy's avatar
cyy committed
512
            if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) {
513
514
515
516
517
518
                // 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";
                }
519
                if (options::show_function_signatures()) signatures += "\n";
520
                signatures += it->doc;
521
                if (options::show_function_signatures()) signatures += "\n";
522
            }
Wenzel Jakob's avatar
Wenzel Jakob committed
523
        }
Wenzel Jakob's avatar
Wenzel Jakob committed
524
525

        /* Install docstring */
526
        auto *func = (PyCFunctionObject *) m_ptr;
527
528
        std::free(const_cast<char *>(func->m_ml->ml_doc));
        // Install docstring if it's non-empty (when at least one option is enabled)
529
530
        func->m_ml->ml_doc
            = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());
Wenzel Jakob's avatar
Wenzel Jakob committed
531

532
533
        if (rec->is_method) {
            m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
Wenzel Jakob's avatar
Wenzel Jakob committed
534
            if (!m_ptr)
535
                pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob's avatar
Wenzel Jakob committed
536
537
538
            Py_DECREF(func);
        }
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
539
540

    /// When a cpp_function is GCed, release any memory allocated by pybind11
541
    static void destruct(detail::function_record *rec, bool free_strings = true) {
542
543
544
545
546
547
        // If on Python 3.9, check the interpreter "MICRO" (patch) version.
        // If this is running on 3.9.0, we have to work around a bug.
        #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
            static bool is_zero = Py_GetVersion()[4] == '0';
        #endif

Wenzel Jakob's avatar
Wenzel Jakob committed
548
549
550
        while (rec) {
            detail::function_record *next = rec->next;
            if (rec->free_data)
551
                rec->free_data(rec);
552
553
554
555
556
557
558
559
560
561
562
            // During initialization, these strings might not have been copied yet,
            // so they cannot be freed. Once the function has been created, they can.
            // Check `make_function_record` for more details.
            if (free_strings) {
                std::free((char *) rec->name);
                std::free((char *) rec->doc);
                std::free((char *) rec->signature);
                for (auto &arg: rec->args) {
                    std::free(const_cast<char *>(arg.name));
                    std::free(const_cast<char *>(arg.descr));
                }
Wenzel Jakob's avatar
Wenzel Jakob committed
563
            }
564
565
            for (auto &arg: rec->args)
                arg.value.dec_ref();
Wenzel Jakob's avatar
Wenzel Jakob committed
566
            if (rec->def) {
567
                std::free(const_cast<char *>(rec->def->ml_doc));
568
569
570
571
572
573
574
575
576
                // Python 3.9.0 decref's these in the wrong order; rec->def
                // If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)
                // See https://github.com/python/cpython/pull/22670
                #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
                    if (!is_zero)
                        delete rec->def;
                #else
                    delete rec->def;
                #endif
Wenzel Jakob's avatar
Wenzel Jakob committed
577
578
579
580
581
582
            }
            delete rec;
            rec = next;
        }
    }

583

Wenzel Jakob's avatar
Wenzel Jakob committed
584
    /// Main dispatch logic for calls to functions bound using pybind11
585
    static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
586
587
        using namespace detail;

Wenzel Jakob's avatar
Wenzel Jakob committed
588
        /* Iterator over the list of potentially admissible overloads */
589
590
        const function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
                              *it = overloads;
Wenzel Jakob's avatar
Wenzel Jakob committed
591
592

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

595
        handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
Wenzel Jakob's avatar
Wenzel Jakob committed
596
               result = PYBIND11_TRY_NEXT_OVERLOAD;
597

598
599
        auto self_value_and_holder = value_and_holder();
        if (overloads->is_constructor) {
600
601
            if (!parent || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
                PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid or missing `self` argument");
602
603
604
                return nullptr;
            }

605
606
607
608
            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, true);

609
610
611
612
613
614
            // 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
615
        try {
616
617
618
619
620
621
622
623
624
            // 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
625
            for (; it != nullptr; it = it->next) {
626

Wenzel Jakob's avatar
Wenzel Jakob committed
627
                /* For each overload:
628
629
                   1. Copy all positional arguments we were given, also checking to make sure that
                      named positional arguments weren't *also* specified via kwarg.
630
                   2. If we weren't given enough, try to make up the omitted ones by checking
631
632
633
634
635
636
637
638
639
640
641
642
643
                      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
644
645
                 */

646
                const function_record &func = *it;
647
648
649
                size_t num_args = func.nargs;    // Number of positional arguments that we need
                if (func.has_args) --num_args;   // (but don't count py::args
                if (func.has_kwargs) --num_args; //  or py::kwargs)
Henry Schreiner's avatar
Henry Schreiner committed
650
                size_t pos_args = num_args - func.nargs_kw_only;
Wenzel Jakob's avatar
Wenzel Jakob committed
651

652
                if (!func.has_args && n_args_in > pos_args)
653
                    continue; // Too many positional arguments for this overload
654

655
                if (n_args_in < pos_args && func.args.size() < pos_args)
656
                    continue; // Not enough positional arguments given, and not enough defaults to fill in the blanks
657

658
                function_call call(func, parent);
Wenzel Jakob's avatar
Wenzel Jakob committed
659

660
                size_t args_to_copy = (std::min)(pos_args, n_args_in); // Protect std::min with parentheses
661
662
                size_t args_copied = 0;

663
664
665
666
667
668
669
                // 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);

670
                    call.init_self = PyTuple_GET_ITEM(args_in, 0);
671
                    call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
672
673
674
675
                    call.args_convert.push_back(false);
                    ++args_copied;
                }

676
                // 1. Copy any position arguments given.
677
                bool bad_arg = false;
678
                for (; args_copied < args_to_copy; ++args_copied) {
679
                    const argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
680
                    if (kwargs_in && arg_rec && arg_rec->name && dict_getitemstring(kwargs_in, arg_rec->name)) {
681
                        bad_arg = true;
682
                        break;
683
684
                    }

685
686
687
688
689
690
691
                    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);
692
                }
693
                if (bad_arg)
694
                    continue; // Maybe it was meant for another overload (issue #688)
695
696
697
698

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

Henry Schreiner's avatar
Henry Schreiner committed
699
700
701
                // 1.5. Fill in any missing pos_only args from defaults if they exist
                if (args_copied < func.nargs_pos_only) {
                    for (; args_copied < func.nargs_pos_only; ++args_copied) {
702
                        const auto &arg_rec = func.args[args_copied];
Henry Schreiner's avatar
Henry Schreiner committed
703
704
                        handle value;

705
706
                        if (arg_rec.value) {
                            value = arg_rec.value;
Henry Schreiner's avatar
Henry Schreiner committed
707
708
709
                        }
                        if (value) {
                            call.args.push_back(value);
710
                            call.args_convert.push_back(arg_rec.convert);
Henry Schreiner's avatar
Henry Schreiner committed
711
712
713
714
715
716
717
718
                        } else
                            break;
                    }

                    if (args_copied < func.nargs_pos_only)
                        continue; // Not enough defaults to fill the positional arguments
                }

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

723
                    for (; args_copied < num_args; ++args_copied) {
724
                        const auto &arg_rec = func.args[args_copied];
725
726

                        handle value;
727
                        if (kwargs_in && arg_rec.name)
728
                            value = dict_getitemstring(kwargs.ptr(), arg_rec.name);
Wenzel Jakob's avatar
Wenzel Jakob committed
729
730

                        if (value) {
731
732
733
734
735
                            // Consume a kwargs value
                            if (!copied_kwargs) {
                                kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
                                copied_kwargs = true;
                            }
736
737
738
                            if (PyDict_DelItemString(kwargs.ptr(), arg_rec.name) == -1) {
                                throw error_already_set();
                            }
739
740
741
742
743
744
                        } else if (arg_rec.value) {
                            value = arg_rec.value;
                        }

                        if (!arg_rec.none && value.is_none()) {
                            break;
745
746
                        }

747
                        if (value) {
748
                            call.args.push_back(value);
749
                            call.args_convert.push_back(arg_rec.convert);
750
                        }
751
                        else
Wenzel Jakob's avatar
Wenzel Jakob committed
752
                            break;
753
754
                    }

755
                    if (args_copied < num_args)
756
757
758
759
                        continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments
                }

                // 3. Check everything was consumed (unless we have a kwargs arg)
760
                if (kwargs && !kwargs.empty() && !func.has_kwargs)
761
762
763
                    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
764
                if (func.has_args) {
765
                    tuple extra_args;
766
767
768
769
                    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);
770
                    } else if (args_copied >= n_args_in) {
771
                        extra_args = tuple(0);
772
                    } else {
773
774
775
                        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
776
                            extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i);
Wenzel Jakob's avatar
Wenzel Jakob committed
777
778
                        }
                    }
779
                    call.args.push_back(extra_args);
780
                    call.args_convert.push_back(false);
781
                    call.args_ref = std::move(extra_args);
Wenzel Jakob's avatar
Wenzel Jakob committed
782
                }
783

784
                // 4b. If we have a py::kwargs, pass on any remaining kwargs
785
                if (func.has_kwargs) {
786
787
                    if (!kwargs.ptr())
                        kwargs = dict(); // If we didn't get one, send an empty one
788
                    call.args.push_back(kwargs);
789
                    call.args_convert.push_back(false);
790
                    call.kwargs_ref = std::move(kwargs);
791
792
                }

793
794
795
                // 5. Put everything in a vector.  Not technically step 5, we've been building it
                // in `call.args` all along.
                #if !defined(NDEBUG)
796
                if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
797
798
                    pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
                #endif
799

800
801
802
803
804
805
806
807
808
                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);
                }

809
                // 6. Call the function.
810
                try {
811
                    loader_life_support guard{};
812
                    result = func.impl(call);
813
                } catch (reference_cast_error &) {
814
815
                    result = PYBIND11_TRY_NEXT_OVERLOAD;
                }
Wenzel Jakob's avatar
Wenzel Jakob committed
816
817
818

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

820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
                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 {
840
                        loader_life_support guard{};
841
842
843
844
845
                        result = call.func.impl(call);
                    } catch (reference_cast_error &) {
                        result = PYBIND11_TRY_NEXT_OVERLOAD;
                    }

846
847
848
849
850
                    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;
851
                        break;
852
                    }
853
                }
Wenzel Jakob's avatar
Wenzel Jakob committed
854
            }
855
856
        } catch (error_already_set &e) {
            e.restore();
857
            return nullptr;
858
#ifdef __GLIBCXX__
859
860
861
        } catch ( abi::__forced_unwind& ) {
            throw;
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
862
        } catch (...) {
863
            /* When an exception is caught, give each registered exception
864
865
866
867
868
869
               translator a chance to translate it to a Python exception. First
               all module-local translators will be tried in reverse order of
               registration. If none of the module-locale translators handle
               the exception (or there are no module-locale translators) then
               the global translators will be tried, also in reverse order of
               registration.
870

871
               A translator may choose to do one of the following:
872

873
874
875
876
877
                - 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. */

878
879
880
881
882
883
            auto &local_exception_translators = get_local_internals().registered_exception_translators;
            if (detail::apply_exception_translators(local_exception_translators)) {
                return nullptr;
            }
            auto &exception_translators = get_internals().registered_exception_translators;
            if (detail::apply_exception_translators(exception_translators)) {
884
885
                return nullptr;
            }
886

887
            PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
Wenzel Jakob's avatar
Wenzel Jakob committed
888
889
890
            return nullptr;
        }

891
892
893
894
895
896
897
898
899
900
        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
901
        if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
902
903
904
            if (overloads->is_operator)
                return handle(Py_NotImplemented).inc_ref().ptr();

905
906
907
908
            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
909
            int ctr = 0;
910
            for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
Wenzel Jakob's avatar
Wenzel Jakob committed
911
                msg += "    "+ std::to_string(++ctr) + ". ";
912
913
914

                bool wrote_sig = false;
                if (overloads->is_constructor) {
915
                    // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
916
                    std::string sig = it2->signature;
917
                    size_t start = sig.find('(') + 7; // skip "(self: "
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
                    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
934
935
                msg += "\n";
            }
936
            msg += "\nInvoked with: ";
937
            auto args_ = reinterpret_borrow<tuple>(args_in);
938
            bool some_args = false;
939
            for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
940
941
                if (!some_args) some_args = true;
                else msg += ", ";
942
943
944
945
946
                try {
                    msg += pybind11::repr(args_[ti]);
                } catch (const error_already_set&) {
                    msg += "<repr raised Error>";
                }
947
            }
948
949
            if (kwargs_in) {
                auto kwargs = reinterpret_borrow<dict>(kwargs_in);
950
                if (!kwargs.empty()) {
951
952
953
954
955
956
                    if (some_args) msg += "; ";
                    msg += "kwargs: ";
                    bool first = true;
                    for (auto kwarg : kwargs) {
                        if (first) first = false;
                        else msg += ", ";
957
958
959
960
961
962
                        msg += pybind11::str("{}=").format(kwarg.first);
                        try {
                            msg += pybind11::repr(kwarg.second);
                        } catch (const error_already_set&) {
                            msg += "<repr raised Error>";
                        }
963
964
965
966
                    }
                }
            }

967
            append_note_if_missing_header_is_suspected(msg);
Wenzel Jakob's avatar
Wenzel Jakob committed
968
969
            PyErr_SetString(PyExc_TypeError, msg.c_str());
            return nullptr;
970
971
        }
        if (!result) {
Wenzel Jakob's avatar
Wenzel Jakob committed
972
973
974
            std::string msg = "Unable to convert function return value to a "
                              "Python type! The signature was\n\t";
            msg += it->signature;
975
            append_note_if_missing_header_is_suspected(msg);
Wenzel Jakob's avatar
Wenzel Jakob committed
976
977
978
            PyErr_SetString(PyExc_TypeError, msg.c_str());
            return nullptr;
        }
979
980
981
982
983
        if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
            auto *pi = reinterpret_cast<instance *>(parent.ptr());
            self_value_and_holder.type->init_instance(pi, nullptr);
        }
        return result.ptr();
Wenzel Jakob's avatar
Wenzel Jakob committed
984
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
985
986
};

987

988
/// Wrapper for Python extension modules
989
class module_ : public object {
Wenzel Jakob's avatar
Wenzel Jakob committed
990
public:
991
    PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)
Wenzel Jakob's avatar
Wenzel Jakob committed
992

993
    /// Create a new top-level Python module with the given name and docstring
994
995
    PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead")
    explicit module_(const char *name, const char *doc = nullptr) {
996
#if PY_MAJOR_VERSION >= 3
997
        *this = create_extension_module(name, doc, new PyModuleDef());
998
#else
999
        *this = create_extension_module(name, doc, nullptr);
1000
#endif
1001
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
1002

1003
1004
1005
1006
1007
    /** \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 */
1008
    template <typename Func, typename... Extra>
1009
    module_ &def(const char *name_, Func &&f, const Extra& ... extra) {
1010
1011
        cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
                          sibling(getattr(*this, name_, none())), extra...);
1012
1013
1014
        // 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
1015
1016
1017
        return *this;
    }

1018
1019
1020
1021
1022
1023
    /** \rst
        Create and return a new Python submodule with the given name and docstring.
        This also works recursively, i.e.

        .. code-block:: cpp

1024
1025
1026
            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'");
1027
    \endrst */
1028
    module_ def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob's avatar
Wenzel Jakob committed
1029
1030
        std::string full_name = std::string(PyModule_GetName(m_ptr))
            + std::string(".") + std::string(name);
1031
        auto result = reinterpret_borrow<module_>(PyImport_AddModule(full_name.c_str()));
1032
        if (doc && options::show_user_defined_docstrings())
1033
            result.attr("__doc__") = pybind11::str(doc);
Wenzel Jakob's avatar
Wenzel Jakob committed
1034
1035
1036
        attr(name) = result;
        return result;
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
1037

1038
    /// Import and return a module or throws `error_already_set`.
1039
    static module_ import(const char *name) {
1040
1041
        PyObject *obj = PyImport_ImportModule(name);
        if (!obj)
1042
            throw error_already_set();
1043
        return reinterpret_steal<module_>(obj);
Wenzel Jakob's avatar
Wenzel Jakob committed
1044
    }
1045

1046
1047
1048
1049
1050
    /// Reload the module or throws `error_already_set`.
    void reload() {
        PyObject *obj = PyImport_ReloadModule(ptr());
        if (!obj)
            throw error_already_set();
1051
        *this = reinterpret_steal<module_>(obj);
1052
1053
    }

1054
1055
1056
1057
1058
1059
1060
    /** \rst
        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.
    \endrst */
1061
    PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
1062
1063
1064
1065
        if (!overwrite && hasattr(*this, name))
            pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
                    std::string(name) + "\"");

1066
        PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
1067
    }
1068
1069

#if PY_MAJOR_VERSION >= 3
1070
1071
1072
1073
    using module_def = PyModuleDef;
#else
    struct module_def {};
#endif
1074

1075
1076
1077
    /** \rst
        Create a new top-level module that can be used as the main module of a C extension.

1078
        For Python 3, ``def`` should point to a statically allocated module_def.
1079
1080
1081
1082
1083
        For Python 2, ``def`` can be a nullptr and is completely ignored.
    \endrst */
    static module_ create_extension_module(const char *name, const char *doc, module_def *def) {
#if PY_MAJOR_VERSION >= 3
        // module_def is PyModuleDef
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
        def = new (def) PyModuleDef {  // Placement new (not an allocation).
            /* m_base */     PyModuleDef_HEAD_INIT,
            /* m_name */     name,
            /* m_doc */      options::show_user_defined_docstrings() ? doc : nullptr,
            /* m_size */     -1,
            /* m_methods */  nullptr,
            /* m_slots */    nullptr,
            /* m_traverse */ nullptr,
            /* m_clear */    nullptr,
            /* m_free */     nullptr
        };
1095
1096
1097
1098
1099
        auto m = PyModule_Create(def);
#else
        // Ignore module_def *def; only necessary for Python 3
        (void) def;
        auto m = Py_InitModule3(name, nullptr, options::show_user_defined_docstrings() ? doc : nullptr);
1100
#endif
1101
1102
1103
1104
1105
        if (m == nullptr) {
            if (PyErr_Occurred())
                throw error_already_set();
            pybind11_fail("Internal error in module_::create_extension_module()");
        }
1106
        // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when returned from PyInit_...
1107
1108
1109
        //       For Python 2, reinterpret_borrow is correct.
        return reinterpret_borrow<module_>(m);
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
1110
1111
};

1112
1113
1114
// When inside a namespace (or anywhere as long as it's not the first item on a line),
// C++20 allows "module" to be used. This is provided for backward compatibility, and for
// simplicity, if someone wants to use py::module for example, that is perfectly safe.
1115
1116
using module = module_;

1117
/// \ingroup python_builtins
1118
1119
1120
1121
/// 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();
1122
    return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
1123
}
1124

1125
PYBIND11_NAMESPACE_BEGIN(detail)
Wenzel Jakob's avatar
Wenzel Jakob committed
1126
/// Generic support for creating new Python heap types
1127
class generic_type : public object {
Wenzel Jakob's avatar
Wenzel Jakob committed
1128
public:
1129
    PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
Wenzel Jakob's avatar
Wenzel Jakob committed
1130
protected:
1131
    void initialize(const type_record &rec) {
1132
        if (rec.scope && hasattr(rec.scope, "__dict__") && rec.scope.attr("__dict__").contains(rec.name))
1133
1134
            pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
                          "\": an object with that name is already defined");
1135

1136
1137
        if ((rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
            != nullptr)
1138
            pybind11_fail("generic_type: type \"" + std::string(rec.name) +
1139
1140
                          "\" is already registered!");

1141
        m_ptr = make_new_python_type(rec);
1142
1143

        /* Register supplemental type information in C++ dict */
1144
1145
        auto *tinfo = new detail::type_info();
        tinfo->type = (PyTypeObject *) m_ptr;
1146
        tinfo->cpptype = rec.type;
1147
        tinfo->type_size = rec.type_size;
1148
        tinfo->type_align = rec.type_align;
1149
        tinfo->operator_new = rec.operator_new;
1150
        tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
1151
        tinfo->init_instance = rec.init_instance;
1152
        tinfo->dealloc = rec.dealloc;
1153
1154
        tinfo->simple_type = true;
        tinfo->simple_ancestors = true;
1155
1156
        tinfo->default_holder = rec.default_holder;
        tinfo->module_local = rec.module_local;
1157
1158
1159

        auto &internals = get_internals();
        auto tindex = std::type_index(*rec.type);
1160
        tinfo->direct_conversions = &internals.direct_conversions[tindex];
1161
        if (rec.module_local)
1162
            get_local_internals().registered_types_cpp[tindex] = tinfo;
1163
1164
        else
            internals.registered_types_cpp[tindex] = tinfo;
1165
        internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo };
Wenzel Jakob's avatar
Wenzel Jakob committed
1166

1167
        if (rec.bases.size() > 1 || rec.multiple_inheritance) {
1168
            mark_parents_nonsimple(tinfo->type);
1169
1170
1171
1172
1173
1174
            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;
        }
1175
1176
1177
1178

        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;
1179
            setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
1180
        }
Wenzel Jakob's avatar
Wenzel Jakob committed
1181
1182
    }

Wenzel Jakob's avatar
Wenzel Jakob committed
1183
1184
    /// Helper function which tags all parents of a type using mult. inheritance
    void mark_parents_nonsimple(PyTypeObject *value) {
1185
        auto t = reinterpret_borrow<tuple>(value->tp_bases);
Wenzel Jakob's avatar
Wenzel Jakob committed
1186
1187
1188
1189
1190
1191
1192
1193
        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
1194
1195
1196
    void install_buffer_funcs(
            buffer_info *(*get_buffer)(PyObject *, void *),
            void *get_buffer_data) {
1197
        auto *type = (PyHeapTypeObject*) m_ptr;
1198
        auto tinfo = detail::get_type_info(&type->ht_type);
Wenzel Jakob's avatar
Wenzel Jakob committed
1199
1200
1201
1202

        if (!type->ht_type.tp_as_buffer)
            pybind11_fail(
                "To be able to register buffer protocol support for the type '" +
1203
                get_fully_qualified_tp_name(tinfo->type) +
Wenzel Jakob's avatar
Wenzel Jakob committed
1204
1205
1206
                "' the associated class<>(..) invocation must "
                "include the pybind11::buffer_protocol() annotation!");

1207
1208
        tinfo->get_buffer = get_buffer;
        tinfo->get_buffer_data = get_buffer_data;
Wenzel Jakob's avatar
Wenzel Jakob committed
1209
1210
    }

1211
    // rec_func must be set for either fget or fset.
Wenzel Jakob's avatar
Wenzel Jakob committed
1212
1213
    void def_property_static_impl(const char *name,
                                  handle fget, handle fset,
1214
                                  detail::function_record *rec_func) {
1215
1216
1217
        const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);
        const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)
                             && pybind11::options::show_user_defined_docstrings();
1218
1219
1220
1221
1222
        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(),
1223
                              pybind11::str(has_doc ? rec_func->doc : ""));
Wenzel Jakob's avatar
Wenzel Jakob committed
1224
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
1225
};
1226

1227
1228
1229
1230
1231
1232
/// 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(...) { }

1233
1234
1235
1236
1237
1238
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 { };
1239
/// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
1240
template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
1241
void call_operator_delete(T *p, size_t, size_t) { T::operator delete(p); }
1242
template <typename T, enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> = 0>
1243
1244
1245
1246
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;
1247
    #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
        if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
            #ifdef __cpp_sized_deallocation
                ::operator delete(p, s, std::align_val_t(a));
            #else
                ::operator delete(p, std::align_val_t(a));
            #endif
            return;
        }
    #endif
    #ifdef __cpp_sized_deallocation
1258
        ::operator delete(p, s);
1259
1260
1261
    #else
        ::operator delete(p);
    #endif
1262
}
1263

1264
1265
1266
1267
1268
1269
1270
inline void add_class_method(object& cls, const char *name_, const cpp_function &cf) {
    cls.attr(cf.name()) = cf;
    if (strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) {
      cls.attr("__hash__") = none();
    }
}

1271
PYBIND11_NAMESPACE_END(detail)
Wenzel Jakob's avatar
Wenzel Jakob committed
1272

1273
1274
1275
1276
1277
1278
/// 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>
1279
1280
1281
1282
1283
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;
}
1284
1285

template <typename Derived, typename Return, typename Class, typename... Args>
1286
1287
1288
1289
1290
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;
}
1291

1292
template <typename type_, typename... options>
Wenzel Jakob's avatar
Wenzel Jakob committed
1293
class class_ : public detail::generic_type {
1294
    template <typename T> using is_holder = detail::is_holder_type<type_, T>;
1295
1296
    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_>;
1297
1298
1299
    // 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>> {};
1300

Wenzel Jakob's avatar
Wenzel Jakob committed
1301
public:
1302
    using type = type_;
1303
    using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
1304
    constexpr static bool has_alias = !std::is_void<type_alias>::value;
1305
    using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
1306

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

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

1313
    PYBIND11_OBJECT(class_, generic_type, PyType_Check)
Wenzel Jakob's avatar
Wenzel Jakob committed
1314

Wenzel Jakob's avatar
Wenzel Jakob committed
1315
1316
    template <typename... Extra>
    class_(handle scope, const char *name, const Extra &... extra) {
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
        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
1328
1329
1330
        record.scope = scope;
        record.name = name;
        record.type = &typeid(type);
1331
        record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
1332
        record.type_align = alignof(conditional_t<has_alias, type_alias, type>&);
1333
        record.holder_size = sizeof(holder_type);
1334
        record.init_instance = init_instance;
Wenzel Jakob's avatar
Wenzel Jakob committed
1335
        record.dealloc = dealloc;
1336
        record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
Wenzel Jakob's avatar
Wenzel Jakob committed
1337

1338
1339
        set_operator_new<type>(&record);

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

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

1346
        generic_type::initialize(record);
1347

1348
        if (has_alias) {
1349
            auto &instances = record.module_local ? get_local_internals().registered_types_cpp : get_internals().registered_types_cpp;
1350
1351
            instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
        }
Wenzel Jakob's avatar
Wenzel Jakob committed
1352
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
1353

1354
    template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
Wenzel Jakob's avatar
Wenzel Jakob committed
1355
    static void add_base(detail::type_record &rec) {
1356
        rec.add_base(typeid(Base), [](void *src) -> void * {
Wenzel Jakob's avatar
Wenzel Jakob committed
1357
1358
1359
1360
            return static_cast<Base *>(reinterpret_cast<type *>(src));
        });
    }

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

1364
    template <typename Func, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1365
    class_ &def(const char *name_, Func&& f, const Extra&... extra) {
1366
        cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), name(name_), is_method(*this),
1367
                        sibling(getattr(*this, name_, none())), extra...);
1368
        add_class_method(*this, name_, cf);
Wenzel Jakob's avatar
Wenzel Jakob committed
1369
1370
1371
        return *this;
    }

1372
    template <typename Func, typename... Extra> class_ &
1373
1374
1375
    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");
1376
1377
        cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
                        sibling(getattr(*this, name_, none())), extra...);
1378
        attr(cf.name()) = staticmethod(cf);
Wenzel Jakob's avatar
Wenzel Jakob committed
1379
1380
1381
        return *this;
    }

1382
    template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1383
    class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
1384
        op.execute(*this, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1385
1386
1387
        return *this;
    }

1388
    template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1389
    class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
1390
        op.execute_cast(*this, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1391
1392
1393
        return *this;
    }

1394
    template <typename... Args, typename... Extra>
1395
    class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra&... extra) {
1396
        PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
1397
        init.execute(*this, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1398
1399
1400
        return *this;
    }

1401
    template <typename... Args, typename... Extra>
1402
    class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra&... extra) {
1403
        PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
1404
        init.execute(*this, extra...);
1405
1406
1407
        return *this;
    }

1408
1409
1410
1411
1412
1413
    template <typename... Args, typename... Extra>
    class_ &def(detail::initimpl::factory<Args...> &&init, const Extra&... extra) {
        std::move(init).execute(*this, extra...);
        return *this;
    }

1414
1415
1416
1417
1418
1419
    template <typename... Args, typename... Extra>
    class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
        std::move(pf).execute(*this, extra...);
        return *this;
    }

1420
1421
    template <typename Func>
    class_& def_buffer(Func &&func) {
Wenzel Jakob's avatar
Wenzel Jakob committed
1422
        struct capture { Func func; };
1423
        auto *ptr = new capture { std::forward<Func>(func) };
Wenzel Jakob's avatar
Wenzel Jakob committed
1424
        install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
1425
            detail::make_caster<type> caster;
Wenzel Jakob's avatar
Wenzel Jakob committed
1426
1427
            if (!caster.load(obj, false))
                return nullptr;
Wenzel Jakob's avatar
Wenzel Jakob committed
1428
1429
            return new buffer_info(((capture *) ptr)->func(caster));
        }, ptr);
1430
1431
1432
1433
        weakref(m_ptr, cpp_function([ptr](handle wr) {
            delete ptr;
            wr.dec_ref();
        })).release();
Wenzel Jakob's avatar
Wenzel Jakob committed
1434
1435
1436
        return *this;
    }

1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
    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)(); });
    }

1447
    template <typename C, typename D, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1448
    class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
1449
        static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value, "def_readwrite() requires a class member (or base class member)");
1450
1451
        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));
1452
        def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1453
1454
1455
        return *this;
    }

1456
    template <typename C, typename D, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1457
    class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
1458
        static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value, "def_readonly() requires a class member (or base class member)");
1459
        cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this));
1460
        def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1461
1462
1463
        return *this;
    }

1464
    template <typename D, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1465
    class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
1466
1467
        cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)),
            fset([pm](const object &, const D &value) { *pm = value; }, scope(*this));
1468
        def_property_static(name, fget, fset, return_value_policy::reference, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1469
1470
1471
        return *this;
    }

1472
    template <typename D, typename... Extra>
Wenzel Jakob's avatar
Wenzel Jakob committed
1473
    class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
1474
        cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this));
1475
        def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1476
1477
1478
        return *this;
    }

1479
1480
1481
    /// 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) {
1482
1483
        return def_property_readonly(name, cpp_function(method_adaptor<type>(fget)),
                                     return_value_policy::reference_internal, extra...);
1484
1485
1486
    }

    /// Uses cpp_function's return_value_policy by default
1487
1488
    template <typename... Extra>
    class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
1489
        return def_property(name, fget, nullptr, extra...);
1490
1491
1492
1493
1494
1495
    }

    /// 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
1496
1497
    }

1498
    /// Uses cpp_function's return_value_policy by default
1499
1500
    template <typename... Extra>
    class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
1501
        return def_property_static(name, fget, nullptr, extra...);
1502
1503
1504
    }

    /// Uses return_value_policy::reference_internal by default
1505
1506
1507
1508
    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...);
    }
1509
1510
    template <typename Getter, typename... Extra>
    class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1511
1512
        return def_property(name, cpp_function(method_adaptor<type>(fget)), fset,
                            return_value_policy::reference_internal, extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1513
1514
    }

1515
    /// Uses cpp_function's return_value_policy by default
1516
1517
    template <typename... Extra>
    class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1518
        return def_property_static(name, fget, fset, is_method(*this), extra...);
Wenzel Jakob's avatar
Wenzel Jakob committed
1519
1520
    }

1521
1522
1523
1524
1525
1526
1527
    /// 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
1528
1529
    template <typename... Extra>
    class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1530
1531
        static_assert( 0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
                      "Argument annotations are not allowed for properties");
1532
        auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1533
1534
1535
1536
1537
1538
        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);
1539
              rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc);
1540
           }
1541
1542
        }
        if (rec_fset) {
1543
            char *doc_prev = rec_fset->doc;
1544
            detail::process_attributes<Extra...>::init(extra..., rec_fset);
1545
1546
            if (rec_fset->doc && rec_fset->doc != doc_prev) {
                free(doc_prev);
1547
                rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc);
1548
            }
1549
            if (! rec_active) rec_active = rec_fset;
1550
        }
1551
        def_property_static_impl(name, fget, fset, rec_active);
Wenzel Jakob's avatar
Wenzel Jakob committed
1552
1553
        return *this;
    }
1554

Wenzel Jakob's avatar
Wenzel Jakob committed
1555
private:
1556
1557
    /// Initialize holder object, variant 1: object derives from enable_shared_from_this
    template <typename T>
1558
    static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1559
            const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
1560
1561
1562
1563
1564
1565
1566

        auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
                detail::try_get_shared_from_this(v_h.value_ptr<type>()));
        if (sh) {
            new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
            v_h.set_holder_constructed();
        }
1567
1568

        if (!v_h.holder_constructed() && inst->owned) {
1569
            new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1570
            v_h.set_holder_constructed();
1571
        }
1572
1573
    }

1574
1575
    static void init_holder_from_existing(const detail::value_and_holder &v_h,
            const holder_type *holder_ptr, std::true_type /*is_copy_constructible*/) {
1576
        new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1577
1578
    }

1579
1580
    static void init_holder_from_existing(const detail::value_and_holder &v_h,
            const holder_type *holder_ptr, std::false_type /*is_copy_constructible*/) {
1581
        new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1582
1583
    }

1584
    /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
1585
    static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1586
            const holder_type *holder_ptr, const void * /* dummy -- not enable_shared_from_this<T>) */) {
1587
        if (holder_ptr) {
1588
1589
            init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
            v_h.set_holder_constructed();
1590
        } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
1591
            new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1592
            v_h.set_holder_constructed();
1593
        }
1594
1595
    }

1596
1597
1598
1599
1600
    /// 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) {
1601
        auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
1602
1603
1604
1605
        if (!v_h.instance_registered()) {
            register_instance(inst, v_h.value_ptr(), v_h.type);
            v_h.set_instance_registered();
        }
1606
        init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
1607
1608
    }

1609
    /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
1610
    static void dealloc(detail::value_and_holder &v_h) {
1611
1612
1613
1614
1615
1616
1617
        // We could be deallocating because we are cleaning up after a Python exception.
        // If so, the Python error indicator will be set. We need to clear that before
        // running the destructor, in case the destructor code calls more Python.
        // If we don't, the Python API will exit with an exception, and pybind11 will
        // throw error_already_set from the C++ destructor which is forbidden and triggers
        // std::terminate().
        error_scope scope;
1618
        if (v_h.holder_constructed()) {
1619
            v_h.holder<holder_type>().~holder_type();
1620
1621
1622
            v_h.set_holder_constructed(false);
        }
        else {
1623
1624
1625
1626
            detail::call_operator_delete(v_h.value_ptr<type>(),
                v_h.type->type_size,
                v_h.type->type_align
            );
1627
1628
        }
        v_h.value_ptr() = nullptr;
Wenzel Jakob's avatar
Wenzel Jakob committed
1629
    }
1630
1631
1632

    static detail::function_record *get_function_record(handle h) {
        h = detail::get_function(h);
Wenzel Jakob's avatar
Wenzel Jakob committed
1633
        return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
1634
                 : nullptr;
1635
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
1636
1637
};

1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
/// 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
1660
}
1661

1662
PYBIND11_NAMESPACE_BEGIN(detail)
David Vo's avatar
David Vo committed
1663
1664
1665

inline str enum_name(handle arg) {
    dict entries = arg.get_type().attr("__entries");
1666
    for (auto kv : entries) {
David Vo's avatar
David Vo committed
1667
1668
1669
1670
1671
1672
        if (handle(kv.second[int_(0)]).equal(arg))
            return pybind11::str(kv.first);
    }
    return "???";
}

1673
struct enum_base {
1674
    enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) { }
1675
1676
1677
1678
1679
1680
1681

    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(
1682
            [](const object &arg) -> str {
1683
                handle type = type::handle_of(arg);
1684
                object type_name = type.attr("__name__");
David Vo's avatar
David Vo committed
1685
                return pybind11::str("<{}.{}: {}>").format(type_name, enum_name(arg), int_(arg));
1686
1687
1688
            },
            name("__repr__"),
            is_method(m_base));
1689

David Vo's avatar
David Vo committed
1690
1691
1692
        m_base.attr("name") = property(cpp_function(&enum_name, name("name"), is_method(m_base)));

        m_base.attr("__str__") = cpp_function(
1693
            [](handle arg) -> str {
David Vo's avatar
David Vo committed
1694
1695
                object type_name = type::handle_of(arg).attr("__name__");
                return pybind11::str("{}.{}").format(type_name, enum_name(arg));
1696
            }, name("name"), is_method(m_base)
David Vo's avatar
David Vo committed
1697
        );
1698
1699
1700
1701
1702
1703
1704
1705

        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:";
1706
                for (auto kv : entries) {
1707
1708
1709
1710
1711
1712
1713
                    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;
1714
            }, name("__doc__")
1715
1716
1717
1718
1719
        ), none(), none(), "");

        m_base.attr("__members__") = static_property(cpp_function(
            [](handle arg) -> dict {
                dict entries = arg.attr("__entries"), m;
1720
                for (auto kv : entries)
1721
1722
                    m[kv.first] = kv.second[int_(0)];
                return m;
1723
            }, name("__members__")), none(), none(), ""
1724
1725
        );

1726
1727
1728
1729
#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)                                        \
    m_base.attr(op) = cpp_function(                                                               \
        [](const object &a, const object &b) {                                                    \
            if (!type::handle_of(a).is(type::handle_of(b)))                                       \
1730
                strict_behavior; /* NOLINT(bugprone-macro-parentheses) */                         \
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
            return expr;                                                                          \
        },                                                                                        \
        name(op),                                                                                 \
        is_method(m_base),                                                                        \
        arg("other"))

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

#define PYBIND11_ENUM_OP_CONV_LHS(op, expr)                                                       \
    m_base.attr(op) = cpp_function(                                                               \
        [](const object &a_, const object &b) {                                                   \
            int_ a(a_);                                                                           \
            return expr;                                                                          \
        },                                                                                        \
        name(op),                                                                                 \
        is_method(m_base),                                                                        \
        arg("other"))
1756

1757
        if (is_convertible) {
1758
1759
            PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() &&  a.equal(b));
            PYBIND11_ENUM_OP_CONV_LHS("__ne__",  b.is_none() || !a.equal(b));
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771

            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);
1772
1773
1774
1775
                m_base.attr("__invert__")
                    = cpp_function([](const object &arg) { return ~(int_(arg)); },
                                   name("__invert__"),
                                   is_method(m_base));
1776
1777
            }
        } else {
1778
1779
            PYBIND11_ENUM_OP_STRICT("__eq__",  int_(a).equal(int_(b)), return false);
            PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
1780
1781

            if (is_arithmetic) {
1782
1783
1784
1785
1786
1787
                #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
1788
1789
1790
            }
        }

1791
        #undef PYBIND11_ENUM_OP_CONV_LHS
1792
1793
1794
        #undef PYBIND11_ENUM_OP_CONV
        #undef PYBIND11_ENUM_OP_STRICT

1795
        m_base.attr("__getstate__") = cpp_function(
1796
            [](const object &arg) { return int_(arg); }, name("__getstate__"), is_method(m_base));
1797

1798
        m_base.attr("__hash__") = cpp_function(
1799
            [](const object &arg) { return int_(arg); }, name("__hash__"), is_method(m_base));
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
    }

    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");
1816
        for (auto kv : entries)
1817
1818
1819
1820
1821
1822
1823
            m_parent.attr(kv.first) = kv.second[int_(0)];
    }

    handle m_base;
    handle m_parent;
};

1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
template <bool is_signed, size_t length> struct equivalent_integer {};
template <> struct equivalent_integer<true,  1> { using type = int8_t;   };
template <> struct equivalent_integer<false, 1> { using type = uint8_t;  };
template <> struct equivalent_integer<true,  2> { using type = int16_t;  };
template <> struct equivalent_integer<false, 2> { using type = uint16_t; };
template <> struct equivalent_integer<true,  4> { using type = int32_t;  };
template <> struct equivalent_integer<false, 4> { using type = uint32_t; };
template <> struct equivalent_integer<true,  8> { using type = int64_t;  };
template <> struct equivalent_integer<false, 8> { using type = uint64_t; };

template <typename IntLike>
using equivalent_integer_t = typename equivalent_integer<std::is_signed<IntLike>::value, sizeof(IntLike)>::type;

1837
PYBIND11_NAMESPACE_END(detail)
1838

Wenzel Jakob's avatar
Wenzel Jakob committed
1839
1840
1841
/// Binds C++ enumerations and enumeration classes to Python
template <typename Type> class enum_ : public class_<Type> {
public:
1842
1843
1844
1845
1846
    using Base = class_<Type>;
    using Base::def;
    using Base::attr;
    using Base::def_property_readonly;
    using Base::def_property_readonly_static;
1847
1848
1849
1850
1851
    using Underlying = typename std::underlying_type<Type>::type;
    // Scalar is the integer representation of underlying type
    using Scalar = detail::conditional_t<detail::any_of<
        detail::is_std_char_type<Underlying>, std::is_same<Underlying, bool>
    >::value, detail::equivalent_integer_t<Underlying>, Underlying>;
1852

Wenzel Jakob's avatar
Wenzel Jakob committed
1853
1854
    template <typename... Extra>
    enum_(const handle &scope, const char *name, const Extra&... extra)
1855
      : class_<Type>(scope, name, extra...), m_base(*this, scope) {
1856
        constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
1857
        constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
1858
        m_base.init(is_arithmetic, is_convertible);
1859

1860
        def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
1861
        def_property_readonly("value", [](Type value) { return (Scalar) value; });
1862
        def("__int__", [](Type value) { return (Scalar) value; });
1863
1864
1865
        #if PY_MAJOR_VERSION < 3
            def("__long__", [](Type value) { return (Scalar) value; });
        #endif
1866
        #if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 8)
1867
1868
1869
            def("__index__", [](Type value) { return (Scalar) value; });
        #endif

1870
1871
1872
1873
1874
        attr("__setstate__") = cpp_function(
            [](detail::value_and_holder &v_h, Scalar arg) {
                detail::initimpl::setstate<Base>(v_h, static_cast<Type>(arg),
                        Py_TYPE(v_h.inst) != v_h.type->type); },
            detail::is_new_style_constructor(),
1875
            pybind11::name("__setstate__"), is_method(*this), arg("state"));
Wenzel Jakob's avatar
Wenzel Jakob committed
1876
1877
1878
    }

    /// Export enumeration entries into the parent scope
1879
    enum_& export_values() {
1880
        m_base.export_values();
1881
        return *this;
Wenzel Jakob's avatar
Wenzel Jakob committed
1882
1883
1884
    }

    /// Add an enumeration entry
1885
    enum_& value(char const* name, Type value, const char *doc = nullptr) {
1886
        m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
Wenzel Jakob's avatar
Wenzel Jakob committed
1887
1888
        return *this;
    }
1889

Wenzel Jakob's avatar
Wenzel Jakob committed
1890
private:
1891
    detail::enum_base m_base;
Wenzel Jakob's avatar
Wenzel Jakob committed
1892
1893
};

1894
PYBIND11_NAMESPACE_BEGIN(detail)
1895

1896

1897
PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient) {
1898
    if (!nurse || !patient)
1899
        pybind11_fail("Could not activate keep_alive!");
1900

1901
    if (patient.is_none() || nurse.is_none())
1902
        return; /* Nothing to keep alive or nothing to be kept alive by */
1903

1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
    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(); });
1916

1917
        weakref wr(nurse, disable_lifesupport);
1918

1919
1920
1921
        patient.inc_ref(); /* reference patient and leak the weak reference */
        (void) wr.release();
    }
1922
1923
}

1924
PYBIND11_NOINLINE void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
1925
1926
1927
    auto get_arg = [&](size_t n) {
        if (n == 0)
            return ret;
1928
        if (n == 1 && call.init_self)
1929
            return call.init_self;
1930
        if (n <= call.args.size())
1931
1932
1933
1934
1935
            return call.args[n - 1];
        return handle();
    };

    keep_alive_impl(get_arg(Nurse), get_arg(Patient));
1936
1937
}

1938
1939
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
1940
#ifdef __cpp_lib_unordered_map_try_emplace
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
        .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;
}

1957
template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
1958
1959
1960
struct iterator_state {
    Iterator it;
    Sentinel end;
1961
    bool first_or_done;
1962
};
1963

1964
PYBIND11_NAMESPACE_END(detail)
Wenzel Jakob's avatar
Wenzel Jakob committed
1965

1966
/// Makes a python iterator from a first and past-the-end C++ InputIterator.
1967
1968
template <return_value_policy Policy = return_value_policy::reference_internal,
          typename Iterator,
1969
          typename Sentinel,
1970
#ifndef DOXYGEN_SHOULD_SKIP_THIS  // Issue in breathe 4.26.1
1971
          typename ValueType = decltype(*std::declval<Iterator>()),
1972
#endif
1973
          typename... Extra>
1974
iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1975
    using state = detail::iterator_state<Iterator, Sentinel, false, Policy>;
1976

Wenzel Jakob's avatar
Wenzel Jakob committed
1977
    if (!detail::get_type_info(typeid(state), false)) {
1978
        class_<state>(handle(), "iterator", pybind11::module_local())
1979
            .def("__iter__", [](state &s) -> state& { return s; })
1980
            .def("__next__", [](state &s) -> ValueType {
1981
                if (!s.first_or_done)
1982
1983
                    ++s.it;
                else
1984
1985
1986
                    s.first_or_done = false;
                if (s.it == s.end) {
                    s.first_or_done = true;
1987
                    throw stop_iteration();
1988
                }
1989
                return *s.it;
1990
            }, std::forward<Extra>(extra)..., Policy);
1991
1992
    }

1993
    return cast(state{first, last, true});
1994
}
1995

1996
1997
/// Makes an python iterator over the keys (`.first`) of a iterator over pairs from a
/// first and past-the-end InputIterator.
1998
1999
template <return_value_policy Policy = return_value_policy::reference_internal,
          typename Iterator,
2000
          typename Sentinel,
2001
#ifndef DOXYGEN_SHOULD_SKIP_THIS  // Issue in breathe 4.26.1
2002
          typename KeyType = decltype((*std::declval<Iterator>()).first),
2003
#endif
2004
          typename... Extra>
2005
iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2006
    using state = detail::iterator_state<Iterator, Sentinel, true, Policy>;
2007

Wenzel Jakob's avatar
Wenzel Jakob committed
2008
    if (!detail::get_type_info(typeid(state), false)) {
2009
        class_<state>(handle(), "iterator", pybind11::module_local())
2010
            .def("__iter__", [](state &s) -> state& { return s; })
2011
            .def("__next__", [](state &s) -> detail::remove_cv_t<KeyType> {
2012
                if (!s.first_or_done)
2013
2014
                    ++s.it;
                else
2015
2016
2017
                    s.first_or_done = false;
                if (s.it == s.end) {
                    s.first_or_done = true;
2018
                    throw stop_iteration();
2019
                }
2020
                return (*s.it).first;
2021
            }, std::forward<Extra>(extra)..., Policy);
2022
2023
    }

2024
    return cast(state{first, last, true});
2025
}
2026

2027
2028
/// Makes an iterator over values of an stl container or other container supporting
/// `std::begin()`/`std::end()`
2029
2030
2031
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...);
2032
2033
}

2034
2035
/// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
/// `std::begin()`/`std::end()`
2036
2037
2038
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...);
2039
2040
}

Wenzel Jakob's avatar
Wenzel Jakob committed
2041
template <typename InputType, typename OutputType> void implicitly_convertible() {
2042
2043
    struct set_flag {
        bool &flag;
2044
        explicit set_flag(bool &flag_) : flag(flag_) { flag_ = true; }
2045
2046
        ~set_flag() { flag = false; }
    };
2047
    auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
2048
2049
2050
2051
        static bool currently_used = false;
        if (currently_used) // implicit conversions are non-reentrant
            return nullptr;
        set_flag flag_helper(currently_used);
2052
        if (!detail::make_caster<InputType>().load(obj, false))
Wenzel Jakob's avatar
Wenzel Jakob committed
2053
2054
2055
2056
2057
2058
2059
2060
            return nullptr;
        tuple args(1);
        args[0] = obj;
        PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
        if (result == nullptr)
            PyErr_Clear();
        return result;
    };
2061
2062
2063
2064

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

2068
2069

inline void register_exception_translator(ExceptionTranslator &&translator) {
2070
2071
2072
2073
    detail::get_internals().registered_exception_translators.push_front(
        std::forward<ExceptionTranslator>(translator));
}

2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085

/**
  * Add a new module-local exception translator. Locally registered functions
  * will be tried before any globally registered exception translators, which
  * will only be invoked if the module-local handlers do not deal with
  * the exception.
  */
inline void register_local_exception_translator(ExceptionTranslator &&translator) {
    detail::get_local_internals().registered_exception_translators.push_front(
        std::forward<ExceptionTranslator>(translator));
}

2086
2087
/**
 * Wrapper to generate a new Python exception type.
2088
2089
2090
2091
2092
2093
2094
2095
 *
 * 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:
2096
    exception() = default;
2097
    exception(handle scope, const char *name, handle base = PyExc_Exception) {
2098
2099
        std::string full_name = scope.attr("__name__").cast<std::string>() +
                                std::string(".") + name;
2100
        m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), NULL);
2101
        if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name))
2102
2103
2104
            pybind11_fail("Error during initialization: multiple incompatible "
                          "definitions with name \"" + std::string(name) + "\"");
        scope.attr(name) = *this;
2105
    }
2106
2107
2108
2109
2110

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

2113
PYBIND11_NAMESPACE_BEGIN(detail)
2114
2115
2116
2117
2118
2119
// 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; }

2120
// Helper function for register_exception and register_local_exception
2121
template <typename CppException>
2122
2123
2124
2125
exception<CppException> &register_exception_impl(handle scope,
                                                const char *name,
                                                handle base,
                                                bool isLocal) {
2126
2127
2128
    auto &ex = detail::get_exception_object<CppException>();
    if (!ex) ex = exception<CppException>(scope, name, base);

2129
2130
2131
2132
    auto register_func = isLocal ? &register_local_exception_translator
                                 : &register_exception_translator;

    register_func([](std::exception_ptr p) {
2133
2134
2135
        if (!p) return;
        try {
            std::rethrow_exception(p);
2136
        } catch (const CppException &e) {
2137
            detail::get_exception_object<CppException>()(e.what());
2138
2139
2140
2141
2142
        }
    });
    return ex;
}

2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
PYBIND11_NAMESPACE_END(detail)

/**
 * Registers a Python exception in `m` of the given `name` and installs a translator to
 * translate the C++ exception to the created Python exception using the what() method.
 * This is intended for simple exception translations; for more complex translation, register the
 * exception object and translator directly.
 */
template <typename CppException>
exception<CppException> &register_exception(handle scope,
                                            const char *name,
                                            handle base = PyExc_Exception) {
    return detail::register_exception_impl<CppException>(scope, name, base, false /* isLocal */);
}

/**
 * Registers a Python exception in `m` of the given `name` and installs a translator to
 * translate the C++ exception to the created Python exception using the what() method.
 * This translator will only be used for exceptions that are thrown in this module and will be
 * tried before global exception translators, including those registered with register_exception.
 * This is intended for simple exception translations; for more complex translation, register the
 * exception object and translator directly.
 */
template <typename CppException>
exception<CppException> &register_local_exception(handle scope,
                                                  const char *name,
                                                  handle base = PyExc_Exception) {
    return detail::register_exception_impl<CppException>(scope, name, base, true /* isLocal */);
}

2173
PYBIND11_NAMESPACE_BEGIN(detail)
2174
PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) {
Dean Moldovan's avatar
Dean Moldovan committed
2175
2176
    auto strings = tuple(args.size());
    for (size_t i = 0; i < args.size(); ++i) {
2177
        strings[i] = str(args[i]);
Dean Moldovan's avatar
Dean Moldovan committed
2178
    }
2179
    auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
2180
    auto line = sep.attr("join")(strings);
Dean Moldovan's avatar
Dean Moldovan committed
2181

2182
2183
2184
2185
2186
    object file;
    if (kwargs.contains("file")) {
        file = kwargs["file"].cast<object>();
    } else {
        try {
2187
            file = module_::import("sys").attr("stdout");
2188
        } catch (const error_already_set &) {
2189
2190
2191
2192
2193
2194
2195
2196
            /* 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;
        }
    }

2197
    auto write = file.attr("write");
Dean Moldovan's avatar
Dean Moldovan committed
2198
    write(line);
2199
    write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
Dean Moldovan's avatar
Dean Moldovan committed
2200

2201
    if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
2202
        file.attr("flush")();
Dean Moldovan's avatar
Dean Moldovan committed
2203
}
2204
PYBIND11_NAMESPACE_END(detail)
Dean Moldovan's avatar
Dean Moldovan committed
2205
2206
2207
2208
2209
2210
2211

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());
}

2212
error_already_set::~error_already_set() {
2213
    if (m_type) {
2214
        gil_scoped_acquire gil;
2215
        error_scope scope;
2216
2217
2218
        m_type.release().dec_ref();
        m_value.release().dec_ref();
        m_trace.release().dec_ref();
2219
2220
2221
    }
}

2222
2223
2224
PYBIND11_NAMESPACE_BEGIN(detail)
inline function get_type_override(const void *this_ptr, const type_info *this_type, const char *name)  {
    handle self = get_object_handle(this_ptr, this_type);
Wenzel Jakob's avatar
Wenzel Jakob committed
2225
    if (!self)
2226
        return function();
2227
    handle type = type::handle_of(self);
2228
2229
    auto key = std::make_pair(type.ptr(), name);

2230
    /* Cache functions that aren't overridden in Python to avoid
2231
       many costly Python dictionary lookups below */
2232
    auto &cache = get_internals().inactive_override_cache;
2233
2234
2235
    if (cache.find(key) != cache.end())
        return function();

2236
2237
    function override = getattr(self, name, function());
    if (override.is_cpp_function()) {
2238
2239
2240
        cache.insert(key);
        return function();
    }
2241

Wenzel Jakob's avatar
Wenzel Jakob committed
2242
2243
2244
    /* Don't call dispatch code if invoked from overridden function.
       Unfortunately this doesn't work on PyPy. */
#if !defined(PYPY_VERSION)
2245
    PyFrameObject *frame = PyThreadState_Get()->frame;
2246
2247
    if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name
        && frame->f_code->co_argcount > 0) {
2248
        PyFrame_FastToLocals(frame);
2249
        PyObject *self_caller = dict_getitem(
2250
            frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
Wenzel Jakob's avatar
Wenzel Jakob committed
2251
        if (self_caller == self.ptr())
2252
2253
            return function();
    }
Wenzel Jakob's avatar
Wenzel Jakob committed
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
#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();
2272
    if (d["self"].is_none())
Wenzel Jakob's avatar
Wenzel Jakob committed
2273
2274
2275
2276
        return function();
    Py_DECREF(result);
#endif

2277
    return override;
2278
}
2279
PYBIND11_NAMESPACE_END(detail)
2280

2281
2282
2283
/** \rst
  Try to retrieve a python method by the provided name from the instance pointed to by the this_ptr.

2284
  :this_ptr: The pointer to the object the overridden method should be retrieved for. This should be
2285
2286
             the first non-trampoline class encountered in the inheritance chain.
  :name: The name of the overridden Python method to retrieve.
2287
2288
  :return: The Python method by this name from the object or an empty function wrapper.
 \endrst */
2289
template <class T> function get_override(const T *this_ptr, const char *name) {
2290
    auto tinfo = detail::get_type_info(typeid(T));
2291
    return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
2292
2293
}

2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
#define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...)                                        \
    do {                                                                                          \
        pybind11::gil_scoped_acquire gil;                                                         \
        pybind11::function override                                                               \
            = pybind11::get_override(static_cast<const cname *>(this), name);                     \
        if (override) {                                                                           \
            auto o = override(__VA_ARGS__);                                                       \
            if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) {           \
                static pybind11::detail::override_caster_t<ret_type> caster;                      \
                return pybind11::detail::cast_ref<ret_type>(std::move(o), caster);                \
            }                                                                                     \
            return pybind11::detail::cast_safe<ret_type>(std::move(o));                           \
        }                                                                                         \
2307
    } while (false)
2308

2309
2310
2311
2312
2313
2314
2315
2316
2317
/** \rst
    Macro to populate the virtual method in the trampoline class. This macro tries to look up a method named 'fn'
    from the Python side, deals with the :ref:`gil` and necessary argument conversions to call this method and return
    the appropriate type. See :ref:`overriding_virtuals` for more information. This macro should be used when the method
    name in C is not the same as the method name in Python. For example with `__str__`.

    .. code-block:: cpp

      std::string toString() override {
2318
        PYBIND11_OVERRIDE_NAME(
2319
2320
            std::string, // Return type (ret_type)
            Animal,      // Parent class (cname)
methylDragon's avatar
methylDragon committed
2321
2322
            "__str__",   // Name of method in Python (name)
            toString,    // Name of function in C++ (fn)
2323
2324
2325
        );
      }
\endrst */
2326
2327
2328
2329
2330
#define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
    do { \
        PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
        return cname::fn(__VA_ARGS__); \
    } while (false)
2331

2332
/** \rst
2333
2334
    Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it
    throws if no override can be found.
2335
\endrst */
2336
2337
2338
2339
2340
#define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
    do { \
        PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
        pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
    } while (false)
2341

2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
/** \rst
    Macro to populate the virtual method in the trampoline class. This macro tries to look up the method
    from the Python side, deals with the :ref:`gil` and necessary argument conversions to call this method and return
    the appropriate type. This macro should be used if the method name in C and in Python are identical.
    See :ref:`overriding_virtuals` for more information.

    .. code-block:: cpp

      class PyAnimal : public Animal {
      public:
          // Inherit the constructors
          using Animal::Animal;

          // Trampoline (need one for each virtual function)
          std::string go(int n_times) override {
2357
              PYBIND11_OVERRIDE_PURE(
2358
2359
2360
2361
2362
2363
2364
2365
                  std::string, // Return type (ret_type)
                  Animal,      // Parent class (cname)
                  go,          // Name of function in C++ (must match Python name) (fn)
                  n_times      // Argument(s) (...)
              );
          }
      };
\endrst */
2366
2367
#define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
    PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2368

2369
/** \rst
2370
2371
    Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`, except that it throws
    if no override can be found.
2372
\endrst */
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
#define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
    PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)


// Deprecated versions

PYBIND11_DEPRECATED("get_type_overload has been deprecated")
inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
    return detail::get_type_override(this_ptr, this_type, name);
}

template <class T>
inline function get_overload(const T *this_ptr, const char *name) {
    return get_override(this_ptr, name);
}

#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
    PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
    PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
    PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
    PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
2397
#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2398
    PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
2399

2400
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
Wenzel Jakob's avatar
Wenzel Jakob committed
2401

2402
2403
2404
#if defined(__GNUC__) && __GNUC__ == 7
#    pragma GCC diagnostic pop // -Wnoexcept-type
#endif