Back to home page

EIC code displayed by LXR

 
 

    


Warning, file /include/pybind11/pybind11.h was not indexed or was modified since last indexation (in which case cross-reference links may be missing, inaccurate or erroneous).

0001 /*
0002     pybind11/pybind11.h: Main header file of the C++11 python
0003     binding generator library
0004 
0005     Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
0006 
0007     All rights reserved. Use of this source code is governed by a
0008     BSD-style license that can be found in the LICENSE file.
0009 */
0010 
0011 #pragma once
0012 
0013 #include "detail/class.h"
0014 #include "detail/init.h"
0015 #include "attr.h"
0016 #include "gil.h"
0017 #include "gil_safe_call_once.h"
0018 #include "options.h"
0019 #include "typing.h"
0020 
0021 #include <cstdlib>
0022 #include <cstring>
0023 #include <memory>
0024 #include <new>
0025 #include <string>
0026 #include <utility>
0027 #include <vector>
0028 
0029 #if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914))
0030 #    define PYBIND11_STD_LAUNDER std::launder
0031 #    define PYBIND11_HAS_STD_LAUNDER 1
0032 #else
0033 #    define PYBIND11_STD_LAUNDER
0034 #    define PYBIND11_HAS_STD_LAUNDER 0
0035 #endif
0036 #if defined(__GNUG__) && !defined(__clang__)
0037 #    include <cxxabi.h>
0038 #endif
0039 
0040 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0041 
0042 /* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning
0043    This warning is about ABI compatibility, not code health.
0044    It is only actually needed in a couple places, but apparently GCC 7 "generates this warning if
0045    and only if the first template instantiation ... involves noexcept" [stackoverflow], therefore
0046    it could get triggered from seemingly random places, depending on user code.
0047    No other GCC version generates this warning.
0048  */
0049 #if defined(__GNUC__) && __GNUC__ == 7
0050 PYBIND11_WARNING_DISABLE_GCC("-Wnoexcept-type")
0051 #endif
0052 
0053 PYBIND11_WARNING_DISABLE_MSVC(4127)
0054 
0055 PYBIND11_NAMESPACE_BEGIN(detail)
0056 
0057 inline std::string replace_newlines_and_squash(const char *text) {
0058     const char *whitespaces = " \t\n\r\f\v";
0059     std::string result(text);
0060     bool previous_is_whitespace = false;
0061 
0062     if (result.size() >= 2) {
0063         // Do not modify string representations
0064         char first_char = result[0];
0065         char last_char = result[result.size() - 1];
0066         if (first_char == last_char && first_char == '\'') {
0067             return result;
0068         }
0069     }
0070     result.clear();
0071 
0072     // Replace characters in whitespaces array with spaces and squash consecutive spaces
0073     while (*text != '\0') {
0074         if (std::strchr(whitespaces, *text)) {
0075             if (!previous_is_whitespace) {
0076                 result += ' ';
0077                 previous_is_whitespace = true;
0078             }
0079         } else {
0080             result += *text;
0081             previous_is_whitespace = false;
0082         }
0083         ++text;
0084     }
0085 
0086     // Strip leading and trailing whitespaces
0087     const size_t str_begin = result.find_first_not_of(whitespaces);
0088     if (str_begin == std::string::npos) {
0089         return "";
0090     }
0091 
0092     const size_t str_end = result.find_last_not_of(whitespaces);
0093     const size_t str_range = str_end - str_begin + 1;
0094 
0095     return result.substr(str_begin, str_range);
0096 }
0097 
0098 // Apply all the extensions translators from a list
0099 // Return true if one of the translators completed without raising an exception
0100 // itself. Return of false indicates that if there are other translators
0101 // available, they should be tried.
0102 inline bool apply_exception_translators(std::forward_list<ExceptionTranslator> &translators) {
0103     auto last_exception = std::current_exception();
0104 
0105     for (auto &translator : translators) {
0106         try {
0107             translator(last_exception);
0108             return true;
0109         } catch (...) {
0110             last_exception = std::current_exception();
0111         }
0112     }
0113     return false;
0114 }
0115 
0116 #if defined(_MSC_VER)
0117 #    define PYBIND11_COMPAT_STRDUP _strdup
0118 #else
0119 #    define PYBIND11_COMPAT_STRDUP strdup
0120 #endif
0121 
0122 PYBIND11_NAMESPACE_END(detail)
0123 
0124 /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
0125 class cpp_function : public function {
0126 public:
0127     cpp_function() = default;
0128     // NOLINTNEXTLINE(google-explicit-constructor)
0129     cpp_function(std::nullptr_t) {}
0130     cpp_function(std::nullptr_t, const is_setter &) {}
0131 
0132     /// Construct a cpp_function from a vanilla function pointer
0133     template <typename Return, typename... Args, typename... Extra>
0134     // NOLINTNEXTLINE(google-explicit-constructor)
0135     cpp_function(Return (*f)(Args...), const Extra &...extra) {
0136         initialize(f, f, extra...);
0137     }
0138 
0139     /// Construct a cpp_function from a lambda function (possibly with internal state)
0140     template <typename Func,
0141               typename... Extra,
0142               typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
0143     // NOLINTNEXTLINE(google-explicit-constructor)
0144     cpp_function(Func &&f, const Extra &...extra) {
0145         initialize(
0146             std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...);
0147     }
0148 
0149     /// Construct a cpp_function from a class method (non-const, no ref-qualifier)
0150     template <typename Return, typename Class, typename... Arg, typename... Extra>
0151     // NOLINTNEXTLINE(google-explicit-constructor)
0152     cpp_function(Return (Class::*f)(Arg...), const Extra &...extra) {
0153         initialize(
0154             [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0155             (Return(*)(Class *, Arg...)) nullptr,
0156             extra...);
0157     }
0158 
0159     /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier)
0160     /// A copy of the overload for non-const functions without explicit ref-qualifier
0161     /// but with an added `&`.
0162     template <typename Return, typename Class, typename... Arg, typename... Extra>
0163     // NOLINTNEXTLINE(google-explicit-constructor)
0164     cpp_function(Return (Class::*f)(Arg...) &, const Extra &...extra) {
0165         initialize(
0166             [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0167             (Return(*)(Class *, Arg...)) nullptr,
0168             extra...);
0169     }
0170 
0171     /// Construct a cpp_function from a class method (const, no ref-qualifier)
0172     template <typename Return, typename Class, typename... Arg, typename... Extra>
0173     // NOLINTNEXTLINE(google-explicit-constructor)
0174     cpp_function(Return (Class::*f)(Arg...) const, const Extra &...extra) {
0175         initialize([f](const Class *c,
0176                        Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0177                    (Return(*)(const Class *, Arg...)) nullptr,
0178                    extra...);
0179     }
0180 
0181     /// Construct a cpp_function from a class method (const, lvalue ref-qualifier)
0182     /// A copy of the overload for const functions without explicit ref-qualifier
0183     /// but with an added `&`.
0184     template <typename Return, typename Class, typename... Arg, typename... Extra>
0185     // NOLINTNEXTLINE(google-explicit-constructor)
0186     cpp_function(Return (Class::*f)(Arg...) const &, const Extra &...extra) {
0187         initialize([f](const Class *c,
0188                        Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0189                    (Return(*)(const Class *, Arg...)) nullptr,
0190                    extra...);
0191     }
0192 
0193     /// Return the function name
0194     object name() const { return attr("__name__"); }
0195 
0196 protected:
0197     struct InitializingFunctionRecordDeleter {
0198         // `destruct(function_record, false)`: `initialize_generic` copies strings and
0199         // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`.
0200         void operator()(detail::function_record *rec) { destruct(rec, false); }
0201     };
0202     using unique_function_record
0203         = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
0204 
0205     /// Space optimization: don't inline this frequently instantiated fragment
0206     PYBIND11_NOINLINE unique_function_record make_function_record() {
0207         return unique_function_record(new detail::function_record());
0208     }
0209 
0210     /// Special internal constructor for functors, lambda functions, etc.
0211     template <typename Func, typename Return, typename... Args, typename... Extra>
0212     void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) {
0213         using namespace detail;
0214         struct capture {
0215             remove_reference_t<Func> f;
0216         };
0217 
0218         /* Store the function including any extra state it might have (e.g. a lambda capture
0219          * object) */
0220         // The unique_ptr makes sure nothing is leaked in case of an exception.
0221         auto unique_rec = make_function_record();
0222         auto *rec = unique_rec.get();
0223 
0224         /* Store the capture object directly in the function record if there is enough space */
0225         if (sizeof(capture) <= sizeof(rec->data)) {
0226             /* Without these pragmas, GCC warns that there might not be
0227                enough space to use the placement new operator. However, the
0228                'if' statement above ensures that this is the case. */
0229             PYBIND11_WARNING_PUSH
0230 
0231 #if defined(__GNUG__) && __GNUC__ >= 6
0232             PYBIND11_WARNING_DISABLE_GCC("-Wplacement-new")
0233 #endif
0234 
0235             new ((capture *) &rec->data) capture{std::forward<Func>(f)};
0236 
0237 #if !PYBIND11_HAS_STD_LAUNDER
0238             PYBIND11_WARNING_DISABLE_GCC("-Wstrict-aliasing")
0239 #endif
0240 
0241             // UB without std::launder, but without breaking ABI and/or
0242             // a significant refactoring it's "impossible" to solve.
0243             if (!std::is_trivially_destructible<capture>::value) {
0244                 rec->free_data = [](function_record *r) {
0245                     auto data = PYBIND11_STD_LAUNDER((capture *) &r->data);
0246                     (void) data;
0247                     data->~capture();
0248                 };
0249             }
0250             PYBIND11_WARNING_POP
0251         } else {
0252             rec->data[0] = new capture{std::forward<Func>(f)};
0253             rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
0254         }
0255 
0256         /* Type casters for the function arguments and return value */
0257         using cast_in = argument_loader<Args...>;
0258         using cast_out
0259             = make_caster<conditional_t<std::is_void<Return>::value, void_type, Return>>;
0260 
0261         static_assert(
0262             expected_num_args<Extra...>(
0263                 sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
0264             "The number of argument annotations does not match the number of function arguments");
0265 
0266         /* Dispatch code which converts function arguments and performs the actual function call */
0267         rec->impl = [](function_call &call) -> handle {
0268             cast_in args_converter;
0269 
0270             /* Try to cast the function arguments into the C++ domain */
0271             if (!args_converter.load_args(call)) {
0272                 return PYBIND11_TRY_NEXT_OVERLOAD;
0273             }
0274 
0275             /* Invoke call policy pre-call hook */
0276             process_attributes<Extra...>::precall(call);
0277 
0278             /* Get a pointer to the capture object */
0279             const auto *data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data
0280                                                                           : call.func.data[0]);
0281             auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
0282 
0283             /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
0284             return_value_policy policy
0285                 = return_value_policy_override<Return>::policy(call.func.policy);
0286 
0287             /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
0288             using Guard = extract_guard_t<Extra...>;
0289 
0290             /* Perform the function call */
0291             handle result;
0292             if (call.func.is_setter) {
0293                 (void) std::move(args_converter).template call<Return, Guard>(cap->f);
0294                 result = none().release();
0295             } else {
0296                 result = cast_out::cast(
0297                     std::move(args_converter).template call<Return, Guard>(cap->f),
0298                     policy,
0299                     call.parent);
0300             }
0301 
0302             /* Invoke call policy post-call hook */
0303             process_attributes<Extra...>::postcall(call, result);
0304 
0305             return result;
0306         };
0307 
0308         rec->nargs_pos = cast_in::args_pos >= 0
0309                              ? static_cast<std::uint16_t>(cast_in::args_pos)
0310                              : sizeof...(Args) - cast_in::has_kwargs; // Will get reduced more if
0311                                                                       // we have a kw_only
0312         rec->has_args = cast_in::args_pos >= 0;
0313         rec->has_kwargs = cast_in::has_kwargs;
0314 
0315         /* Process any user-provided function attributes */
0316         process_attributes<Extra...>::init(extra..., rec);
0317 
0318         {
0319             constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
0320                            has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
0321                            has_arg_annotations = any_of<is_keyword<Extra>...>::value;
0322             static_assert(has_arg_annotations || !has_kw_only_args,
0323                           "py::kw_only requires the use of argument annotations");
0324             static_assert(has_arg_annotations || !has_pos_only_args,
0325                           "py::pos_only requires the use of argument annotations (for docstrings "
0326                           "and aligning the annotations to the argument)");
0327 
0328             static_assert(constexpr_sum(is_kw_only<Extra>::value...) <= 1,
0329                           "py::kw_only may be specified only once");
0330             static_assert(constexpr_sum(is_pos_only<Extra>::value...) <= 1,
0331                           "py::pos_only may be specified only once");
0332             constexpr auto kw_only_pos = constexpr_first<is_kw_only, Extra...>();
0333             constexpr auto pos_only_pos = constexpr_first<is_pos_only, Extra...>();
0334             static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
0335                           "py::pos_only must come before py::kw_only");
0336         }
0337 
0338         /* Generate a readable signature describing the function's arguments and return
0339            value types */
0340         static constexpr auto signature
0341             = const_name("(") + cast_in::arg_names + const_name(") -> ") + cast_out::name;
0342         PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
0343 
0344         /* Register the function with Python from generic (non-templated) code */
0345         // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid.
0346         initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));
0347 
0348         /* Stash some additional information used by an important optimization in 'functional.h' */
0349         using FunctionType = Return (*)(Args...);
0350         constexpr bool is_function_ptr
0351             = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *);
0352         if (is_function_ptr) {
0353             rec->is_stateless = true;
0354             rec->data[1]
0355                 = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
0356         }
0357     }
0358 
0359     // Utility class that keeps track of all duplicated strings, and cleans them up in its
0360     // destructor, unless they are released. Basically a RAII-solution to deal with exceptions
0361     // along the way.
0362     class strdup_guard {
0363     public:
0364         strdup_guard() = default;
0365         strdup_guard(const strdup_guard &) = delete;
0366         strdup_guard &operator=(const strdup_guard &) = delete;
0367 
0368         ~strdup_guard() {
0369             for (auto *s : strings) {
0370                 std::free(s);
0371             }
0372         }
0373         char *operator()(const char *s) {
0374             auto *t = PYBIND11_COMPAT_STRDUP(s);
0375             strings.push_back(t);
0376             return t;
0377         }
0378         void release() { strings.clear(); }
0379 
0380     private:
0381         std::vector<char *> strings;
0382     };
0383 
0384     /// Register a function call with Python (generic non-templated code goes here)
0385     void initialize_generic(unique_function_record &&unique_rec,
0386                             const char *text,
0387                             const std::type_info *const *types,
0388                             size_t args) {
0389         // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr,
0390         // we do not want this to destruct the pointer. `initialize` (the caller) still relies on
0391         // the pointee being alive after this call. Only move out if a `capsule` is going to keep
0392         // it alive.
0393         auto *rec = unique_rec.get();
0394 
0395         // Keep track of strdup'ed strings, and clean them up as long as the function's capsule
0396         // has not taken ownership yet (when `unique_rec.release()` is called).
0397         // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the
0398         // strings are only referenced before strdup'ing. So only *after* the following block could
0399         // `destruct` safely be called, but even then, `repr` could still throw in the middle of
0400         // copying all strings.
0401         strdup_guard guarded_strdup;
0402 
0403         /* Create copies of all referenced C-style strings */
0404         rec->name = guarded_strdup(rec->name ? rec->name : "");
0405         if (rec->doc) {
0406             rec->doc = guarded_strdup(rec->doc);
0407         }
0408         for (auto &a : rec->args) {
0409             if (a.name) {
0410                 a.name = guarded_strdup(a.name);
0411             }
0412             if (a.descr) {
0413                 a.descr = guarded_strdup(a.descr);
0414             } else if (a.value) {
0415                 a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());
0416             }
0417         }
0418 
0419         rec->is_constructor = (std::strcmp(rec->name, "__init__") == 0)
0420                               || (std::strcmp(rec->name, "__setstate__") == 0);
0421 
0422 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
0423         if (rec->is_constructor && !rec->is_new_style_constructor) {
0424             const auto class_name
0425                 = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
0426             const auto func_name = std::string(rec->name);
0427             PyErr_WarnEx(PyExc_FutureWarning,
0428                          ("pybind11-bound class '" + class_name
0429                           + "' is using an old-style "
0430                             "placement-new '"
0431                           + func_name
0432                           + "' which has been deprecated. See "
0433                             "the upgrade guide in pybind11's docs. This message is only visible "
0434                             "when compiled in debug mode.")
0435                              .c_str(),
0436                          0);
0437         }
0438 #endif
0439 
0440         /* Generate a proper function signature */
0441         std::string signature;
0442         size_t type_index = 0, arg_index = 0;
0443         bool is_starred = false;
0444         for (const auto *pc = text; *pc != '\0'; ++pc) {
0445             const auto c = *pc;
0446 
0447             if (c == '{') {
0448                 // Write arg name for everything except *args and **kwargs.
0449                 is_starred = *(pc + 1) == '*';
0450                 if (is_starred) {
0451                     continue;
0452                 }
0453                 // Separator for keyword-only arguments, placed before the kw
0454                 // arguments start (unless we are already putting an *args)
0455                 if (!rec->has_args && arg_index == rec->nargs_pos) {
0456                     signature += "*, ";
0457                 }
0458                 if (arg_index < rec->args.size() && rec->args[arg_index].name) {
0459                     signature += rec->args[arg_index].name;
0460                 } else if (arg_index == 0 && rec->is_method) {
0461                     signature += "self";
0462                 } else {
0463                     signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
0464                 }
0465                 signature += ": ";
0466             } else if (c == '}') {
0467                 // Write default value if available.
0468                 if (!is_starred && arg_index < rec->args.size() && rec->args[arg_index].descr) {
0469                     signature += " = ";
0470                     signature += detail::replace_newlines_and_squash(rec->args[arg_index].descr);
0471                 }
0472                 // Separator for positional-only arguments (placed after the
0473                 // argument, rather than before like *
0474                 if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
0475                     signature += ", /";
0476                 }
0477                 if (!is_starred) {
0478                     arg_index++;
0479                 }
0480             } else if (c == '%') {
0481                 const std::type_info *t = types[type_index++];
0482                 if (!t) {
0483                     pybind11_fail("Internal error while parsing type signature (1)");
0484                 }
0485                 if (auto *tinfo = detail::get_type_info(*t)) {
0486                     handle th((PyObject *) tinfo->type);
0487                     signature += th.attr("__module__").cast<std::string>() + "."
0488                                  + th.attr("__qualname__").cast<std::string>();
0489                 } else if (rec->is_new_style_constructor && arg_index == 0) {
0490                     // A new-style `__init__` takes `self` as `value_and_holder`.
0491                     // Rewrite it to the proper class type.
0492                     signature += rec->scope.attr("__module__").cast<std::string>() + "."
0493                                  + rec->scope.attr("__qualname__").cast<std::string>();
0494                 } else {
0495                     signature += detail::quote_cpp_type_name(detail::clean_type_id(t->name()));
0496                 }
0497             } else {
0498                 signature += c;
0499             }
0500         }
0501 
0502         if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] != nullptr) {
0503             pybind11_fail("Internal error while parsing type signature (2)");
0504         }
0505 
0506         rec->signature = guarded_strdup(signature.c_str());
0507         rec->args.shrink_to_fit();
0508         rec->nargs = (std::uint16_t) args;
0509 
0510         if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) {
0511             rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
0512         }
0513 
0514         detail::function_record *chain = nullptr, *chain_start = rec;
0515         if (rec->sibling) {
0516             if (PyCFunction_Check(rec->sibling.ptr())) {
0517                 auto *self = PyCFunction_GET_SELF(rec->sibling.ptr());
0518                 if (!isinstance<capsule>(self)) {
0519                     chain = nullptr;
0520                 } else {
0521                     auto rec_capsule = reinterpret_borrow<capsule>(self);
0522                     if (detail::is_function_record_capsule(rec_capsule)) {
0523                         chain = rec_capsule.get_pointer<detail::function_record>();
0524                         /* Never append a method to an overload chain of a parent class;
0525                            instead, hide the parent's overloads in this case */
0526                         if (!chain->scope.is(rec->scope)) {
0527                             chain = nullptr;
0528                         }
0529                     } else {
0530                         chain = nullptr;
0531                     }
0532                 }
0533             }
0534             // Don't trigger for things like the default __init__, which are wrapper_descriptors
0535             // that we are intentionally replacing
0536             else if (!rec->sibling.is_none() && rec->name[0] != '_') {
0537                 pybind11_fail("Cannot overload existing non-function object \""
0538                               + std::string(rec->name) + "\" with a function of the same name");
0539             }
0540         }
0541 
0542         if (!chain) {
0543             /* No existing overload was found, create a new function object */
0544             rec->def = new PyMethodDef();
0545             std::memset(rec->def, 0, sizeof(PyMethodDef));
0546             rec->def->ml_name = rec->name;
0547             rec->def->ml_meth
0548                 = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher));
0549             rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
0550 
0551             capsule rec_capsule(unique_rec.release(),
0552                                 detail::get_function_record_capsule_name(),
0553                                 [](void *ptr) { destruct((detail::function_record *) ptr); });
0554             guarded_strdup.release();
0555 
0556             object scope_module;
0557             if (rec->scope) {
0558                 if (hasattr(rec->scope, "__module__")) {
0559                     scope_module = rec->scope.attr("__module__");
0560                 } else if (hasattr(rec->scope, "__name__")) {
0561                     scope_module = rec->scope.attr("__name__");
0562                 }
0563             }
0564 
0565             m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
0566             if (!m_ptr) {
0567                 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
0568             }
0569         } else {
0570             /* Append at the beginning or end of the overload chain */
0571             m_ptr = rec->sibling.ptr();
0572             inc_ref();
0573             if (chain->is_method != rec->is_method) {
0574                 pybind11_fail(
0575                     "overloading a method with both static and instance methods is not supported; "
0576 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
0577                     "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more "
0578                     "details"
0579 #else
0580                     "error while attempting to bind "
0581                     + std::string(rec->is_method ? "instance" : "static") + " method "
0582                     + std::string(pybind11::str(rec->scope.attr("__name__"))) + "."
0583                     + std::string(rec->name) + signature
0584 #endif
0585                 );
0586             }
0587 
0588             if (rec->prepend) {
0589                 // Beginning of chain; we need to replace the capsule's current head-of-the-chain
0590                 // pointer with this one, then make this one point to the previous head of the
0591                 // chain.
0592                 chain_start = rec;
0593                 rec->next = chain;
0594                 auto rec_capsule
0595                     = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self);
0596                 rec_capsule.set_pointer(unique_rec.release());
0597                 guarded_strdup.release();
0598             } else {
0599                 // Or end of chain (normal behavior)
0600                 chain_start = chain;
0601                 while (chain->next) {
0602                     chain = chain->next;
0603                 }
0604                 chain->next = unique_rec.release();
0605                 guarded_strdup.release();
0606             }
0607         }
0608 
0609         std::string signatures;
0610         int index = 0;
0611         /* Create a nice pydoc rec including all signatures and
0612            docstrings of the functions in the overload chain */
0613         if (chain && options::show_function_signatures()) {
0614             // First a generic signature
0615             signatures += rec->name;
0616             signatures += "(*args, **kwargs)\n";
0617             signatures += "Overloaded function.\n\n";
0618         }
0619         // Then specific overload signatures
0620         bool first_user_def = true;
0621         for (auto *it = chain_start; it != nullptr; it = it->next) {
0622             if (options::show_function_signatures()) {
0623                 if (index > 0) {
0624                     signatures += '\n';
0625                 }
0626                 if (chain) {
0627                     signatures += std::to_string(++index) + ". ";
0628                 }
0629                 signatures += rec->name;
0630                 signatures += it->signature;
0631                 signatures += '\n';
0632             }
0633             if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) {
0634                 // If we're appending another docstring, and aren't printing function signatures,
0635                 // we need to append a newline first:
0636                 if (!options::show_function_signatures()) {
0637                     if (first_user_def) {
0638                         first_user_def = false;
0639                     } else {
0640                         signatures += '\n';
0641                     }
0642                 }
0643                 if (options::show_function_signatures()) {
0644                     signatures += '\n';
0645                 }
0646                 signatures += it->doc;
0647                 if (options::show_function_signatures()) {
0648                     signatures += '\n';
0649                 }
0650             }
0651         }
0652 
0653         /* Install docstring */
0654         auto *func = (PyCFunctionObject *) m_ptr;
0655         std::free(const_cast<char *>(func->m_ml->ml_doc));
0656         // Install docstring if it's non-empty (when at least one option is enabled)
0657         func->m_ml->ml_doc
0658             = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());
0659 
0660         if (rec->is_method) {
0661             m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
0662             if (!m_ptr) {
0663                 pybind11_fail(
0664                     "cpp_function::cpp_function(): Could not allocate instance method object");
0665             }
0666             Py_DECREF(func);
0667         }
0668     }
0669 
0670     /// When a cpp_function is GCed, release any memory allocated by pybind11
0671     static void destruct(detail::function_record *rec, bool free_strings = true) {
0672 // If on Python 3.9, check the interpreter "MICRO" (patch) version.
0673 // If this is running on 3.9.0, we have to work around a bug.
0674 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
0675         static bool is_zero = Py_GetVersion()[4] == '0';
0676 #endif
0677 
0678         while (rec) {
0679             detail::function_record *next = rec->next;
0680             if (rec->free_data) {
0681                 rec->free_data(rec);
0682             }
0683             // During initialization, these strings might not have been copied yet,
0684             // so they cannot be freed. Once the function has been created, they can.
0685             // Check `make_function_record` for more details.
0686             if (free_strings) {
0687                 std::free((char *) rec->name);
0688                 std::free((char *) rec->doc);
0689                 std::free((char *) rec->signature);
0690                 for (auto &arg : rec->args) {
0691                     std::free(const_cast<char *>(arg.name));
0692                     std::free(const_cast<char *>(arg.descr));
0693                 }
0694             }
0695             for (auto &arg : rec->args) {
0696                 arg.value.dec_ref();
0697             }
0698             if (rec->def) {
0699                 std::free(const_cast<char *>(rec->def->ml_doc));
0700 // Python 3.9.0 decref's these in the wrong order; rec->def
0701 // If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)
0702 // See https://github.com/python/cpython/pull/22670
0703 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
0704                 if (!is_zero) {
0705                     delete rec->def;
0706                 }
0707 #else
0708                 delete rec->def;
0709 #endif
0710             }
0711             delete rec;
0712             rec = next;
0713         }
0714     }
0715 
0716     /// Main dispatch logic for calls to functions bound using pybind11
0717     static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
0718         using namespace detail;
0719         assert(isinstance<capsule>(self));
0720 
0721         /* Iterator over the list of potentially admissible overloads */
0722         const function_record *overloads = reinterpret_cast<function_record *>(
0723                                   PyCapsule_GetPointer(self, get_function_record_capsule_name())),
0724                               *current_overload = overloads;
0725         assert(overloads != nullptr);
0726 
0727         /* Need to know how many arguments + keyword arguments there are to pick the right
0728            overload */
0729         const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
0730 
0731         handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
0732                result = PYBIND11_TRY_NEXT_OVERLOAD;
0733 
0734         auto self_value_and_holder = value_and_holder();
0735         if (overloads->is_constructor) {
0736             if (!parent
0737                 || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
0738                 set_error(PyExc_TypeError,
0739                           "__init__(self, ...) called with invalid or missing `self` argument");
0740                 return nullptr;
0741             }
0742 
0743             auto *const tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
0744             auto *const pi = reinterpret_cast<instance *>(parent.ptr());
0745             self_value_and_holder = pi->get_value_and_holder(tinfo, true);
0746 
0747             // If this value is already registered it must mean __init__ is invoked multiple times;
0748             // we really can't support that in C++, so just ignore the second __init__.
0749             if (self_value_and_holder.instance_registered()) {
0750                 return none().release().ptr();
0751             }
0752         }
0753 
0754         try {
0755             // We do this in two passes: in the first pass, we load arguments with `convert=false`;
0756             // in the second, we allow conversion (except for arguments with an explicit
0757             // py::arg().noconvert()).  This lets us prefer calls without conversion, with
0758             // conversion as a fallback.
0759             std::vector<function_call> second_pass;
0760 
0761             // However, if there are no overloads, we can just skip the no-convert pass entirely
0762             const bool overloaded
0763                 = current_overload != nullptr && current_overload->next != nullptr;
0764 
0765             for (; current_overload != nullptr; current_overload = current_overload->next) {
0766 
0767                 /* For each overload:
0768                    1. Copy all positional arguments we were given, also checking to make sure that
0769                       named positional arguments weren't *also* specified via kwarg.
0770                    2. If we weren't given enough, try to make up the omitted ones by checking
0771                       whether they were provided by a kwarg matching the `py::arg("name")` name. If
0772                       so, use it (and remove it from kwargs); if not, see if the function binding
0773                       provided a default that we can use.
0774                    3. Ensure that either all keyword arguments were "consumed", or that the
0775                    function takes a kwargs argument to accept unconsumed kwargs.
0776                    4. Any positional arguments still left get put into a tuple (for args), and any
0777                       leftover kwargs get put into a dict.
0778                    5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
0779                       extra tuple or dict at the end of the positional arguments.
0780                    6. Call the function call dispatcher (function_record::impl)
0781 
0782                    If one of these fail, move on to the next overload and keep trying until we get
0783                    a result other than PYBIND11_TRY_NEXT_OVERLOAD.
0784                  */
0785 
0786                 const function_record &func = *current_overload;
0787                 size_t num_args = func.nargs; // Number of positional arguments that we need
0788                 if (func.has_args) {
0789                     --num_args; // (but don't count py::args
0790                 }
0791                 if (func.has_kwargs) {
0792                     --num_args; //  or py::kwargs)
0793                 }
0794                 size_t pos_args = func.nargs_pos;
0795 
0796                 if (!func.has_args && n_args_in > pos_args) {
0797                     continue; // Too many positional arguments for this overload
0798                 }
0799 
0800                 if (n_args_in < pos_args && func.args.size() < pos_args) {
0801                     continue; // Not enough positional arguments given, and not enough defaults to
0802                               // fill in the blanks
0803                 }
0804 
0805                 function_call call(func, parent);
0806 
0807                 // Protect std::min with parentheses
0808                 size_t args_to_copy = (std::min)(pos_args, n_args_in);
0809                 size_t args_copied = 0;
0810 
0811                 // 0. Inject new-style `self` argument
0812                 if (func.is_new_style_constructor) {
0813                     // The `value` may have been preallocated by an old-style `__init__`
0814                     // if it was a preceding candidate for overload resolution.
0815                     if (self_value_and_holder) {
0816                         self_value_and_holder.type->dealloc(self_value_and_holder);
0817                     }
0818 
0819                     call.init_self = PyTuple_GET_ITEM(args_in, 0);
0820                     call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
0821                     call.args_convert.push_back(false);
0822                     ++args_copied;
0823                 }
0824 
0825                 // 1. Copy any position arguments given.
0826                 bool bad_arg = false;
0827                 for (; args_copied < args_to_copy; ++args_copied) {
0828                     const argument_record *arg_rec
0829                         = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
0830                     if (kwargs_in && arg_rec && arg_rec->name
0831                         && dict_getitemstring(kwargs_in, arg_rec->name)) {
0832                         bad_arg = true;
0833                         break;
0834                     }
0835 
0836                     handle arg(PyTuple_GET_ITEM(args_in, args_copied));
0837                     if (arg_rec && !arg_rec->none && arg.is_none()) {
0838                         bad_arg = true;
0839                         break;
0840                     }
0841                     call.args.push_back(arg);
0842                     call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
0843                 }
0844                 if (bad_arg) {
0845                     continue; // Maybe it was meant for another overload (issue #688)
0846                 }
0847 
0848                 // Keep track of how many position args we copied out in case we need to come back
0849                 // to copy the rest into a py::args argument.
0850                 size_t positional_args_copied = args_copied;
0851 
0852                 // We'll need to copy this if we steal some kwargs for defaults
0853                 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
0854 
0855                 // 1.5. Fill in any missing pos_only args from defaults if they exist
0856                 if (args_copied < func.nargs_pos_only) {
0857                     for (; args_copied < func.nargs_pos_only; ++args_copied) {
0858                         const auto &arg_rec = func.args[args_copied];
0859                         handle value;
0860 
0861                         if (arg_rec.value) {
0862                             value = arg_rec.value;
0863                         }
0864                         if (value) {
0865                             call.args.push_back(value);
0866                             call.args_convert.push_back(arg_rec.convert);
0867                         } else {
0868                             break;
0869                         }
0870                     }
0871 
0872                     if (args_copied < func.nargs_pos_only) {
0873                         continue; // Not enough defaults to fill the positional arguments
0874                     }
0875                 }
0876 
0877                 // 2. Check kwargs and, failing that, defaults that may help complete the list
0878                 if (args_copied < num_args) {
0879                     bool copied_kwargs = false;
0880 
0881                     for (; args_copied < num_args; ++args_copied) {
0882                         const auto &arg_rec = func.args[args_copied];
0883 
0884                         handle value;
0885                         if (kwargs_in && arg_rec.name) {
0886                             value = dict_getitemstring(kwargs.ptr(), arg_rec.name);
0887                         }
0888 
0889                         if (value) {
0890                             // Consume a kwargs value
0891                             if (!copied_kwargs) {
0892                                 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
0893                                 copied_kwargs = true;
0894                             }
0895                             if (PyDict_DelItemString(kwargs.ptr(), arg_rec.name) == -1) {
0896                                 throw error_already_set();
0897                             }
0898                         } else if (arg_rec.value) {
0899                             value = arg_rec.value;
0900                         }
0901 
0902                         if (!arg_rec.none && value.is_none()) {
0903                             break;
0904                         }
0905 
0906                         if (value) {
0907                             // If we're at the py::args index then first insert a stub for it to be
0908                             // replaced later
0909                             if (func.has_args && call.args.size() == func.nargs_pos) {
0910                                 call.args.push_back(none());
0911                             }
0912 
0913                             call.args.push_back(value);
0914                             call.args_convert.push_back(arg_rec.convert);
0915                         } else {
0916                             break;
0917                         }
0918                     }
0919 
0920                     if (args_copied < num_args) {
0921                         continue; // Not enough arguments, defaults, or kwargs to fill the
0922                                   // positional arguments
0923                     }
0924                 }
0925 
0926                 // 3. Check everything was consumed (unless we have a kwargs arg)
0927                 if (kwargs && !kwargs.empty() && !func.has_kwargs) {
0928                     continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
0929                 }
0930 
0931                 // 4a. If we have a py::args argument, create a new tuple with leftovers
0932                 if (func.has_args) {
0933                     tuple extra_args;
0934                     if (args_to_copy == 0) {
0935                         // We didn't copy out any position arguments from the args_in tuple, so we
0936                         // can reuse it directly without copying:
0937                         extra_args = reinterpret_borrow<tuple>(args_in);
0938                     } else if (positional_args_copied >= n_args_in) {
0939                         extra_args = tuple(0);
0940                     } else {
0941                         size_t args_size = n_args_in - positional_args_copied;
0942                         extra_args = tuple(args_size);
0943                         for (size_t i = 0; i < args_size; ++i) {
0944                             extra_args[i] = PyTuple_GET_ITEM(args_in, positional_args_copied + i);
0945                         }
0946                     }
0947                     if (call.args.size() <= func.nargs_pos) {
0948                         call.args.push_back(extra_args);
0949                     } else {
0950                         call.args[func.nargs_pos] = extra_args;
0951                     }
0952                     call.args_convert.push_back(false);
0953                     call.args_ref = std::move(extra_args);
0954                 }
0955 
0956                 // 4b. If we have a py::kwargs, pass on any remaining kwargs
0957                 if (func.has_kwargs) {
0958                     if (!kwargs.ptr()) {
0959                         kwargs = dict(); // If we didn't get one, send an empty one
0960                     }
0961                     call.args.push_back(kwargs);
0962                     call.args_convert.push_back(false);
0963                     call.kwargs_ref = std::move(kwargs);
0964                 }
0965 
0966 // 5. Put everything in a vector.  Not technically step 5, we've been building it
0967 // in `call.args` all along.
0968 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
0969                 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) {
0970                     pybind11_fail("Internal error: function call dispatcher inserted wrong number "
0971                                   "of arguments!");
0972                 }
0973 #endif
0974 
0975                 std::vector<bool> second_pass_convert;
0976                 if (overloaded) {
0977                     // We're in the first no-convert pass, so swap out the conversion flags for a
0978                     // set of all-false flags.  If the call fails, we'll swap the flags back in for
0979                     // the conversion-allowed call below.
0980                     second_pass_convert.resize(func.nargs, false);
0981                     call.args_convert.swap(second_pass_convert);
0982                 }
0983 
0984                 // 6. Call the function.
0985                 try {
0986                     loader_life_support guard{};
0987                     result = func.impl(call);
0988                 } catch (reference_cast_error &) {
0989                     result = PYBIND11_TRY_NEXT_OVERLOAD;
0990                 }
0991 
0992                 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
0993                     break;
0994                 }
0995 
0996                 if (overloaded) {
0997                     // The (overloaded) call failed; if the call has at least one argument that
0998                     // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
0999                     // then add this call to the list of second pass overloads to try.
1000                     for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
1001                         if (second_pass_convert[i]) {
1002                             // Found one: swap the converting flags back in and store the call for
1003                             // the second pass.
1004                             call.args_convert.swap(second_pass_convert);
1005                             second_pass.push_back(std::move(call));
1006                             break;
1007                         }
1008                     }
1009                 }
1010             }
1011 
1012             if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
1013                 // The no-conversion pass finished without success, try again with conversion
1014                 // allowed
1015                 for (auto &call : second_pass) {
1016                     try {
1017                         loader_life_support guard{};
1018                         result = call.func.impl(call);
1019                     } catch (reference_cast_error &) {
1020                         result = PYBIND11_TRY_NEXT_OVERLOAD;
1021                     }
1022 
1023                     if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
1024                         // The error reporting logic below expects 'current_overload' to be valid,
1025                         // as it would be if we'd encountered this failure in the first-pass loop.
1026                         if (!result) {
1027                             current_overload = &call.func;
1028                         }
1029                         break;
1030                     }
1031                 }
1032             }
1033         } catch (error_already_set &e) {
1034             e.restore();
1035             return nullptr;
1036 #ifdef __GLIBCXX__
1037         } catch (abi::__forced_unwind &) {
1038             throw;
1039 #endif
1040         } catch (...) {
1041             /* When an exception is caught, give each registered exception
1042                translator a chance to translate it to a Python exception. First
1043                all module-local translators will be tried in reverse order of
1044                registration. If none of the module-locale translators handle
1045                the exception (or there are no module-locale translators) then
1046                the global translators will be tried, also in reverse order of
1047                registration.
1048 
1049                A translator may choose to do one of the following:
1050 
1051                 - catch the exception and call py::set_error()
1052                   to set a standard (or custom) Python exception, or
1053                 - do nothing and let the exception fall through to the next translator, or
1054                 - delegate translation to the next translator by throwing a new type of exception.
1055              */
1056 
1057             bool handled = with_internals([&](internals &internals) {
1058                 auto &local_exception_translators
1059                     = get_local_internals().registered_exception_translators;
1060                 if (detail::apply_exception_translators(local_exception_translators)) {
1061                     return true;
1062                 }
1063                 auto &exception_translators = internals.registered_exception_translators;
1064                 if (detail::apply_exception_translators(exception_translators)) {
1065                     return true;
1066                 }
1067                 return false;
1068             });
1069 
1070             if (handled) {
1071                 return nullptr;
1072             }
1073 
1074             set_error(PyExc_SystemError, "Exception escaped from default exception translator!");
1075             return nullptr;
1076         }
1077 
1078         auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
1079             if (msg.find("std::") != std::string::npos) {
1080                 msg += "\n\n"
1081                        "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1082                        "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1083                        "conversions are optional and require extra headers to be included\n"
1084                        "when compiling your pybind11 module.";
1085             }
1086         };
1087 
1088         if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
1089             if (overloads->is_operator) {
1090                 return handle(Py_NotImplemented).inc_ref().ptr();
1091             }
1092 
1093             std::string msg = std::string(overloads->name) + "(): incompatible "
1094                               + std::string(overloads->is_constructor ? "constructor" : "function")
1095                               + " arguments. The following argument types are supported:\n";
1096 
1097             int ctr = 0;
1098             for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
1099                 msg += "    " + std::to_string(++ctr) + ". ";
1100 
1101                 bool wrote_sig = false;
1102                 if (overloads->is_constructor) {
1103                     // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as
1104                     // `Object(arg0, ...)`
1105                     std::string sig = it2->signature;
1106                     size_t start = sig.find('(') + 7; // skip "(self: "
1107                     if (start < sig.size()) {
1108                         // End at the , for the next argument
1109                         size_t end = sig.find(", "), next = end + 2;
1110                         size_t ret = sig.rfind(" -> ");
1111                         // Or the ), if there is no comma:
1112                         if (end >= sig.size()) {
1113                             next = end = sig.find(')');
1114                         }
1115                         if (start < end && next < sig.size()) {
1116                             msg.append(sig, start, end - start);
1117                             msg += '(';
1118                             msg.append(sig, next, ret - next);
1119                             wrote_sig = true;
1120                         }
1121                     }
1122                 }
1123                 if (!wrote_sig) {
1124                     msg += it2->signature;
1125                 }
1126 
1127                 msg += '\n';
1128             }
1129             msg += "\nInvoked with: ";
1130             auto args_ = reinterpret_borrow<tuple>(args_in);
1131             bool some_args = false;
1132             for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
1133                 if (!some_args) {
1134                     some_args = true;
1135                 } else {
1136                     msg += ", ";
1137                 }
1138                 try {
1139                     msg += pybind11::repr(args_[ti]);
1140                 } catch (const error_already_set &) {
1141                     msg += "<repr raised Error>";
1142                 }
1143             }
1144             if (kwargs_in) {
1145                 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
1146                 if (!kwargs.empty()) {
1147                     if (some_args) {
1148                         msg += "; ";
1149                     }
1150                     msg += "kwargs: ";
1151                     bool first = true;
1152                     for (const auto &kwarg : kwargs) {
1153                         if (first) {
1154                             first = false;
1155                         } else {
1156                             msg += ", ";
1157                         }
1158                         msg += pybind11::str("{}=").format(kwarg.first);
1159                         try {
1160                             msg += pybind11::repr(kwarg.second);
1161                         } catch (const error_already_set &) {
1162                             msg += "<repr raised Error>";
1163                         }
1164                     }
1165                 }
1166             }
1167 
1168             append_note_if_missing_header_is_suspected(msg);
1169             // Attach additional error info to the exception if supported
1170             if (PyErr_Occurred()) {
1171                 // #HelpAppreciated: unit test coverage for this branch.
1172                 raise_from(PyExc_TypeError, msg.c_str());
1173                 return nullptr;
1174             }
1175             set_error(PyExc_TypeError, msg.c_str());
1176             return nullptr;
1177         }
1178         if (!result) {
1179             std::string msg = "Unable to convert function return value to a "
1180                               "Python type! The signature was\n\t";
1181             assert(current_overload != nullptr);
1182             msg += current_overload->signature;
1183             append_note_if_missing_header_is_suspected(msg);
1184             // Attach additional error info to the exception if supported
1185             if (PyErr_Occurred()) {
1186                 raise_from(PyExc_TypeError, msg.c_str());
1187                 return nullptr;
1188             }
1189             set_error(PyExc_TypeError, msg.c_str());
1190             return nullptr;
1191         }
1192         if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
1193             auto *pi = reinterpret_cast<instance *>(parent.ptr());
1194             self_value_and_holder.type->init_instance(pi, nullptr);
1195         }
1196         return result.ptr();
1197     }
1198 };
1199 
1200 PYBIND11_NAMESPACE_BEGIN(detail)
1201 
1202 template <>
1203 struct handle_type_name<cpp_function> {
1204     static constexpr auto name = const_name("Callable");
1205 };
1206 
1207 PYBIND11_NAMESPACE_END(detail)
1208 
1209 // Use to activate Py_MOD_GIL_NOT_USED.
1210 class mod_gil_not_used {
1211 public:
1212     explicit mod_gil_not_used(bool flag = true) : flag_(flag) {}
1213     bool flag() const { return flag_; }
1214 
1215 private:
1216     bool flag_;
1217 };
1218 
1219 /// Wrapper for Python extension modules
1220 class module_ : public object {
1221 public:
1222     PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)
1223 
1224     /// Create a new top-level Python module with the given name and docstring
1225     PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead")
1226     explicit module_(const char *name, const char *doc = nullptr) {
1227         *this = create_extension_module(name, doc, new PyModuleDef());
1228     }
1229 
1230     /** \rst
1231         Create Python binding for a new function within the module scope. ``Func``
1232         can be a plain C++ function, a function pointer, or a lambda function. For
1233         details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
1234     \endrst */
1235     template <typename Func, typename... Extra>
1236     module_ &def(const char *name_, Func &&f, const Extra &...extra) {
1237         cpp_function func(std::forward<Func>(f),
1238                           name(name_),
1239                           scope(*this),
1240                           sibling(getattr(*this, name_, none())),
1241                           extra...);
1242         // NB: allow overwriting here because cpp_function sets up a chain with the intention of
1243         // overwriting (and has already checked internally that it isn't overwriting
1244         // non-functions).
1245         add_object(name_, func, true /* overwrite */);
1246         return *this;
1247     }
1248 
1249     /** \rst
1250         Create and return a new Python submodule with the given name and docstring.
1251         This also works recursively, i.e.
1252 
1253         .. code-block:: cpp
1254 
1255             py::module_ m("example", "pybind11 example plugin");
1256             py::module_ m2 = m.def_submodule("sub", "A submodule of 'example'");
1257             py::module_ m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
1258     \endrst */
1259     module_ def_submodule(const char *name, const char *doc = nullptr) {
1260         const char *this_name = PyModule_GetName(m_ptr);
1261         if (this_name == nullptr) {
1262             throw error_already_set();
1263         }
1264         std::string full_name = std::string(this_name) + '.' + name;
1265         handle submodule = PyImport_AddModule(full_name.c_str());
1266         if (!submodule) {
1267             throw error_already_set();
1268         }
1269         auto result = reinterpret_borrow<module_>(submodule);
1270         if (doc && options::show_user_defined_docstrings()) {
1271             result.attr("__doc__") = pybind11::str(doc);
1272         }
1273         attr(name) = result;
1274         return result;
1275     }
1276 
1277     /// Import and return a module or throws `error_already_set`.
1278     static module_ import(const char *name) {
1279         PyObject *obj = PyImport_ImportModule(name);
1280         if (!obj) {
1281             throw error_already_set();
1282         }
1283         return reinterpret_steal<module_>(obj);
1284     }
1285 
1286     /// Reload the module or throws `error_already_set`.
1287     void reload() {
1288         PyObject *obj = PyImport_ReloadModule(ptr());
1289         if (!obj) {
1290             throw error_already_set();
1291         }
1292         *this = reinterpret_steal<module_>(obj);
1293     }
1294 
1295     /** \rst
1296         Adds an object to the module using the given name.  Throws if an object with the given name
1297         already exists.
1298 
1299         ``overwrite`` should almost always be false: attempting to overwrite objects that pybind11
1300         has established will, in most cases, break things.
1301     \endrst */
1302     PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
1303         if (!overwrite && hasattr(*this, name)) {
1304             pybind11_fail(
1305                 "Error during initialization: multiple incompatible definitions with name \""
1306                 + std::string(name) + "\"");
1307         }
1308 
1309         PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
1310     }
1311 
1312     using module_def = PyModuleDef; // TODO: Can this be removed (it was needed only for Python 2)?
1313 
1314     /** \rst
1315         Create a new top-level module that can be used as the main module of a C extension.
1316 
1317         ``def`` should point to a statically allocated module_def.
1318     \endrst */
1319     static module_ create_extension_module(const char *name,
1320                                            const char *doc,
1321                                            module_def *def,
1322                                            mod_gil_not_used gil_not_used
1323                                            = mod_gil_not_used(false)) {
1324         // module_def is PyModuleDef
1325         // Placement new (not an allocation).
1326         def = new (def)
1327             PyModuleDef{/* m_base */ PyModuleDef_HEAD_INIT,
1328                         /* m_name */ name,
1329                         /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr,
1330                         /* m_size */ -1,
1331                         /* m_methods */ nullptr,
1332                         /* m_slots */ nullptr,
1333                         /* m_traverse */ nullptr,
1334                         /* m_clear */ nullptr,
1335                         /* m_free */ nullptr};
1336         auto *m = PyModule_Create(def);
1337         if (m == nullptr) {
1338             if (PyErr_Occurred()) {
1339                 throw error_already_set();
1340             }
1341             pybind11_fail("Internal error in module_::create_extension_module()");
1342         }
1343         if (gil_not_used.flag()) {
1344 #ifdef Py_GIL_DISABLED
1345             PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
1346 #endif
1347         }
1348         // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when
1349         //       returned from PyInit_...
1350         //       For Python 2, reinterpret_borrow was correct.
1351         return reinterpret_borrow<module_>(m);
1352     }
1353 };
1354 
1355 PYBIND11_NAMESPACE_BEGIN(detail)
1356 
1357 template <>
1358 struct handle_type_name<module_> {
1359     static constexpr auto name = const_name("module");
1360 };
1361 
1362 PYBIND11_NAMESPACE_END(detail)
1363 
1364 // When inside a namespace (or anywhere as long as it's not the first item on a line),
1365 // C++20 allows "module" to be used. This is provided for backward compatibility, and for
1366 // simplicity, if someone wants to use py::module for example, that is perfectly safe.
1367 using module = module_;
1368 
1369 /// \ingroup python_builtins
1370 /// Return a dictionary representing the global variables in the current execution frame,
1371 /// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
1372 inline dict globals() {
1373 #if PY_VERSION_HEX >= 0x030d0000
1374     PyObject *p = PyEval_GetFrameGlobals();
1375     return p ? reinterpret_steal<dict>(p)
1376              : reinterpret_borrow<dict>(module_::import("__main__").attr("__dict__").ptr());
1377 #else
1378     PyObject *p = PyEval_GetGlobals();
1379     return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
1380 #endif
1381 }
1382 
1383 template <typename... Args, typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>>
1384 PYBIND11_DEPRECATED("make_simple_namespace should be replaced with "
1385                     "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
1386 object make_simple_namespace(Args &&...args_) {
1387     return module_::import("types").attr("SimpleNamespace")(std::forward<Args>(args_)...);
1388 }
1389 
1390 PYBIND11_NAMESPACE_BEGIN(detail)
1391 /// Generic support for creating new Python heap types
1392 class generic_type : public object {
1393 public:
1394     PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
1395 protected:
1396     void initialize(const type_record &rec) {
1397         if (rec.scope && hasattr(rec.scope, "__dict__")
1398             && rec.scope.attr("__dict__").contains(rec.name)) {
1399             pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name)
1400                           + "\": an object with that name is already defined");
1401         }
1402 
1403         if ((rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
1404             != nullptr) {
1405             pybind11_fail("generic_type: type \"" + std::string(rec.name)
1406                           + "\" is already registered!");
1407         }
1408 
1409         m_ptr = make_new_python_type(rec);
1410 
1411         /* Register supplemental type information in C++ dict */
1412         auto *tinfo = new detail::type_info();
1413         tinfo->type = (PyTypeObject *) m_ptr;
1414         tinfo->cpptype = rec.type;
1415         tinfo->type_size = rec.type_size;
1416         tinfo->type_align = rec.type_align;
1417         tinfo->operator_new = rec.operator_new;
1418         tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
1419         tinfo->init_instance = rec.init_instance;
1420         tinfo->dealloc = rec.dealloc;
1421         tinfo->simple_type = true;
1422         tinfo->simple_ancestors = true;
1423         tinfo->default_holder = rec.default_holder;
1424         tinfo->module_local = rec.module_local;
1425 
1426         with_internals([&](internals &internals) {
1427             auto tindex = std::type_index(*rec.type);
1428             tinfo->direct_conversions = &internals.direct_conversions[tindex];
1429             if (rec.module_local) {
1430                 get_local_internals().registered_types_cpp[tindex] = tinfo;
1431             } else {
1432                 internals.registered_types_cpp[tindex] = tinfo;
1433             }
1434             internals.registered_types_py[(PyTypeObject *) m_ptr] = {tinfo};
1435         });
1436 
1437         if (rec.bases.size() > 1 || rec.multiple_inheritance) {
1438             mark_parents_nonsimple(tinfo->type);
1439             tinfo->simple_ancestors = false;
1440         } else if (rec.bases.size() == 1) {
1441             auto *parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
1442             assert(parent_tinfo != nullptr);
1443             bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1444             tinfo->simple_ancestors = parent_simple_ancestors;
1445             // The parent can no longer be a simple type if it has MI and has a child
1446             parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1447         }
1448 
1449         if (rec.module_local) {
1450             // Stash the local typeinfo and loader so that external modules can access it.
1451             tinfo->module_local_load = &type_caster_generic::local_load;
1452             setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
1453         }
1454     }
1455 
1456     /// Helper function which tags all parents of a type using mult. inheritance
1457     void mark_parents_nonsimple(PyTypeObject *value) {
1458         auto t = reinterpret_borrow<tuple>(value->tp_bases);
1459         for (handle h : t) {
1460             auto *tinfo2 = get_type_info((PyTypeObject *) h.ptr());
1461             if (tinfo2) {
1462                 tinfo2->simple_type = false;
1463             }
1464             mark_parents_nonsimple((PyTypeObject *) h.ptr());
1465         }
1466     }
1467 
1468     void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *),
1469                               void *get_buffer_data) {
1470         auto *type = (PyHeapTypeObject *) m_ptr;
1471         auto *tinfo = detail::get_type_info(&type->ht_type);
1472 
1473         if (!type->ht_type.tp_as_buffer) {
1474             pybind11_fail("To be able to register buffer protocol support for the type '"
1475                           + get_fully_qualified_tp_name(tinfo->type)
1476                           + "' the associated class<>(..) invocation must "
1477                             "include the pybind11::buffer_protocol() annotation!");
1478         }
1479 
1480         tinfo->get_buffer = get_buffer;
1481         tinfo->get_buffer_data = get_buffer_data;
1482     }
1483 
1484     // rec_func must be set for either fget or fset.
1485     void def_property_static_impl(const char *name,
1486                                   handle fget,
1487                                   handle fset,
1488                                   detail::function_record *rec_func) {
1489         const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);
1490         const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)
1491                              && pybind11::options::show_user_defined_docstrings();
1492         auto property = handle(
1493             (PyObject *) (is_static ? get_internals().static_property_type : &PyProperty_Type));
1494         attr(name) = property(fget.ptr() ? fget : none(),
1495                               fset.ptr() ? fset : none(),
1496                               /*deleter*/ none(),
1497                               pybind11::str(has_doc ? rec_func->doc : ""));
1498     }
1499 };
1500 
1501 /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
1502 template <typename T,
1503           typename = void_t<decltype(static_cast<void *(*) (size_t)>(T::operator new))>>
1504 void set_operator_new(type_record *r) {
1505     r->operator_new = &T::operator new;
1506 }
1507 
1508 template <typename>
1509 void set_operator_new(...) {}
1510 
1511 template <typename T, typename SFINAE = void>
1512 struct has_operator_delete : std::false_type {};
1513 template <typename T>
1514 struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
1515     : std::true_type {};
1516 template <typename T, typename SFINAE = void>
1517 struct has_operator_delete_size : std::false_type {};
1518 template <typename T>
1519 struct has_operator_delete_size<
1520     T,
1521     void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type {
1522 };
1523 /// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
1524 template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
1525 void call_operator_delete(T *p, size_t, size_t) {
1526     T::operator delete(p);
1527 }
1528 template <typename T,
1529           enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int>
1530           = 0>
1531 void call_operator_delete(T *p, size_t s, size_t) {
1532     T::operator delete(p, s);
1533 }
1534 
1535 inline void call_operator_delete(void *p, size_t s, size_t a) {
1536     (void) s;
1537     (void) a;
1538 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1539     if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1540 #    ifdef __cpp_sized_deallocation
1541         ::operator delete(p, s, std::align_val_t(a));
1542 #    else
1543         ::operator delete(p, std::align_val_t(a));
1544 #    endif
1545         return;
1546     }
1547 #endif
1548 #ifdef __cpp_sized_deallocation
1549     ::operator delete(p, s);
1550 #else
1551     ::operator delete(p);
1552 #endif
1553 }
1554 
1555 inline void add_class_method(object &cls, const char *name_, const cpp_function &cf) {
1556     cls.attr(cf.name()) = cf;
1557     if (std::strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) {
1558         cls.attr("__hash__") = none();
1559     }
1560 }
1561 
1562 PYBIND11_NAMESPACE_END(detail)
1563 
1564 /// Given a pointer to a member function, cast it to its `Derived` version.
1565 /// Forward everything else unchanged.
1566 template <typename /*Derived*/, typename F>
1567 auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
1568     return std::forward<F>(f);
1569 }
1570 
1571 template <typename Derived, typename Return, typename Class, typename... Args>
1572 auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
1573     static_assert(
1574         detail::is_accessible_base_of<Class, Derived>::value,
1575         "Cannot bind an inaccessible base class method; use a lambda definition instead");
1576     return pmf;
1577 }
1578 
1579 template <typename Derived, typename Return, typename Class, typename... Args>
1580 auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
1581     static_assert(
1582         detail::is_accessible_base_of<Class, Derived>::value,
1583         "Cannot bind an inaccessible base class method; use a lambda definition instead");
1584     return pmf;
1585 }
1586 
1587 template <typename type_, typename... options>
1588 class class_ : public detail::generic_type {
1589     template <typename T>
1590     using is_holder = detail::is_holder_type<type_, T>;
1591     template <typename T>
1592     using is_subtype = detail::is_strict_base_of<type_, T>;
1593     template <typename T>
1594     using is_base = detail::is_strict_base_of<T, type_>;
1595     // struct instead of using here to help MSVC:
1596     template <typename T>
1597     struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
1598 
1599 public:
1600     using type = type_;
1601     using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
1602     constexpr static bool has_alias = !std::is_void<type_alias>::value;
1603     using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
1604 
1605     static_assert(detail::all_of<is_valid_class_option<options>...>::value,
1606                   "Unknown/invalid class_ template parameters provided");
1607 
1608     static_assert(!has_alias || std::is_polymorphic<type>::value,
1609                   "Cannot use an alias class with a non-polymorphic type");
1610 
1611     PYBIND11_OBJECT(class_, generic_type, PyType_Check)
1612 
1613     template <typename... Extra>
1614     class_(handle scope, const char *name, const Extra &...extra) {
1615         using namespace detail;
1616 
1617         // MI can only be specified via class_ template options, not constructor parameters
1618         static_assert(
1619             none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
1620                 (constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
1621                  constexpr_sum(is_base<options>::value...) == 0 &&   // no template option bases
1622                  // no multiple_inheritance attr
1623                  none_of<std::is_same<multiple_inheritance, Extra>...>::value),
1624             "Error: multiple inheritance bases must be specified via class_ template options");
1625 
1626         type_record record;
1627         record.scope = scope;
1628         record.name = name;
1629         record.type = &typeid(type);
1630         record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
1631         record.type_align = alignof(conditional_t<has_alias, type_alias, type> &);
1632         record.holder_size = sizeof(holder_type);
1633         record.init_instance = init_instance;
1634         record.dealloc = dealloc;
1635         record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
1636 
1637         set_operator_new<type>(&record);
1638 
1639         /* Register base classes specified via template arguments to class_, if any */
1640         PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
1641 
1642         /* Process optional arguments, if any */
1643         process_attributes<Extra...>::init(extra..., &record);
1644 
1645         generic_type::initialize(record);
1646 
1647         if (has_alias) {
1648             with_internals([&](internals &internals) {
1649                 auto &instances = record.module_local ? get_local_internals().registered_types_cpp
1650                                                       : internals.registered_types_cpp;
1651                 instances[std::type_index(typeid(type_alias))]
1652                     = instances[std::type_index(typeid(type))];
1653             });
1654         }
1655     }
1656 
1657     template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
1658     static void add_base(detail::type_record &rec) {
1659         rec.add_base(typeid(Base), [](void *src) -> void * {
1660             return static_cast<Base *>(reinterpret_cast<type *>(src));
1661         });
1662     }
1663 
1664     template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
1665     static void add_base(detail::type_record &) {}
1666 
1667     template <typename Func, typename... Extra>
1668     class_ &def(const char *name_, Func &&f, const Extra &...extra) {
1669         cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
1670                         name(name_),
1671                         is_method(*this),
1672                         sibling(getattr(*this, name_, none())),
1673                         extra...);
1674         add_class_method(*this, name_, cf);
1675         return *this;
1676     }
1677 
1678     template <typename Func, typename... Extra>
1679     class_ &def_static(const char *name_, Func &&f, const Extra &...extra) {
1680         static_assert(!std::is_member_function_pointer<Func>::value,
1681                       "def_static(...) called with a non-static member function pointer");
1682         cpp_function cf(std::forward<Func>(f),
1683                         name(name_),
1684                         scope(*this),
1685                         sibling(getattr(*this, name_, none())),
1686                         extra...);
1687         auto cf_name = cf.name();
1688         attr(std::move(cf_name)) = staticmethod(std::move(cf));
1689         return *this;
1690     }
1691 
1692     template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1693     class_ &def(const T &op, const Extra &...extra) {
1694         op.execute(*this, extra...);
1695         return *this;
1696     }
1697 
1698     template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1699     class_ &def_cast(const T &op, const Extra &...extra) {
1700         op.execute_cast(*this, extra...);
1701         return *this;
1702     }
1703 
1704     template <typename... Args, typename... Extra>
1705     class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra &...extra) {
1706         PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
1707         init.execute(*this, extra...);
1708         return *this;
1709     }
1710 
1711     template <typename... Args, typename... Extra>
1712     class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra &...extra) {
1713         PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
1714         init.execute(*this, extra...);
1715         return *this;
1716     }
1717 
1718     template <typename... Args, typename... Extra>
1719     class_ &def(detail::initimpl::factory<Args...> &&init, const Extra &...extra) {
1720         std::move(init).execute(*this, extra...);
1721         return *this;
1722     }
1723 
1724     template <typename... Args, typename... Extra>
1725     class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
1726         std::move(pf).execute(*this, extra...);
1727         return *this;
1728     }
1729 
1730     template <typename Func>
1731     class_ &def_buffer(Func &&func) {
1732         struct capture {
1733             Func func;
1734         };
1735         auto *ptr = new capture{std::forward<Func>(func)};
1736         install_buffer_funcs(
1737             [](PyObject *obj, void *ptr) -> buffer_info * {
1738                 detail::make_caster<type> caster;
1739                 if (!caster.load(obj, false)) {
1740                     return nullptr;
1741                 }
1742                 return new buffer_info(((capture *) ptr)->func(std::move(caster)));
1743             },
1744             ptr);
1745         weakref(m_ptr, cpp_function([ptr](handle wr) {
1746                     delete ptr;
1747                     wr.dec_ref();
1748                 }))
1749             .release();
1750         return *this;
1751     }
1752 
1753     template <typename Return, typename Class, typename... Args>
1754     class_ &def_buffer(Return (Class::*func)(Args...)) {
1755         return def_buffer([func](type &obj) { return (obj.*func)(); });
1756     }
1757 
1758     template <typename Return, typename Class, typename... Args>
1759     class_ &def_buffer(Return (Class::*func)(Args...) const) {
1760         return def_buffer([func](const type &obj) { return (obj.*func)(); });
1761     }
1762 
1763     template <typename C, typename D, typename... Extra>
1764     class_ &def_readwrite(const char *name, D C::*pm, const Extra &...extra) {
1765         static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
1766                       "def_readwrite() requires a class member (or base class member)");
1767         cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this)),
1768             fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
1769         def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
1770         return *this;
1771     }
1772 
1773     template <typename C, typename D, typename... Extra>
1774     class_ &def_readonly(const char *name, const D C::*pm, const Extra &...extra) {
1775         static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
1776                       "def_readonly() requires a class member (or base class member)");
1777         cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this));
1778         def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
1779         return *this;
1780     }
1781 
1782     template <typename D, typename... Extra>
1783     class_ &def_readwrite_static(const char *name, D *pm, const Extra &...extra) {
1784         cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)),
1785             fset([pm](const object &, const D &value) { *pm = value; }, scope(*this));
1786         def_property_static(name, fget, fset, return_value_policy::reference, extra...);
1787         return *this;
1788     }
1789 
1790     template <typename D, typename... Extra>
1791     class_ &def_readonly_static(const char *name, const D *pm, const Extra &...extra) {
1792         cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this));
1793         def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
1794         return *this;
1795     }
1796 
1797     /// Uses return_value_policy::reference_internal by default
1798     template <typename Getter, typename... Extra>
1799     class_ &def_property_readonly(const char *name, const Getter &fget, const Extra &...extra) {
1800         return def_property_readonly(name,
1801                                      cpp_function(method_adaptor<type>(fget)),
1802                                      return_value_policy::reference_internal,
1803                                      extra...);
1804     }
1805 
1806     /// Uses cpp_function's return_value_policy by default
1807     template <typename... Extra>
1808     class_ &
1809     def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra) {
1810         return def_property(name, fget, nullptr, extra...);
1811     }
1812 
1813     /// Uses return_value_policy::reference by default
1814     template <typename Getter, typename... Extra>
1815     class_ &
1816     def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra) {
1817         return def_property_readonly_static(
1818             name, cpp_function(fget), return_value_policy::reference, extra...);
1819     }
1820 
1821     /// Uses cpp_function's return_value_policy by default
1822     template <typename... Extra>
1823     class_ &def_property_readonly_static(const char *name,
1824                                          const cpp_function &fget,
1825                                          const Extra &...extra) {
1826         return def_property_static(name, fget, nullptr, extra...);
1827     }
1828 
1829     /// Uses return_value_policy::reference_internal by default
1830     template <typename Getter, typename Setter, typename... Extra>
1831     class_ &
1832     def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) {
1833         return def_property(
1834             name, fget, cpp_function(method_adaptor<type>(fset), is_setter()), extra...);
1835     }
1836     template <typename Getter, typename... Extra>
1837     class_ &def_property(const char *name,
1838                          const Getter &fget,
1839                          const cpp_function &fset,
1840                          const Extra &...extra) {
1841         return def_property(name,
1842                             cpp_function(method_adaptor<type>(fget)),
1843                             fset,
1844                             return_value_policy::reference_internal,
1845                             extra...);
1846     }
1847 
1848     /// Uses cpp_function's return_value_policy by default
1849     template <typename... Extra>
1850     class_ &def_property(const char *name,
1851                          const cpp_function &fget,
1852                          const cpp_function &fset,
1853                          const Extra &...extra) {
1854         return def_property_static(name, fget, fset, is_method(*this), extra...);
1855     }
1856 
1857     /// Uses return_value_policy::reference by default
1858     template <typename Getter, typename... Extra>
1859     class_ &def_property_static(const char *name,
1860                                 const Getter &fget,
1861                                 const cpp_function &fset,
1862                                 const Extra &...extra) {
1863         return def_property_static(
1864             name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1865     }
1866 
1867     /// Uses cpp_function's return_value_policy by default
1868     template <typename... Extra>
1869     class_ &def_property_static(const char *name,
1870                                 const cpp_function &fget,
1871                                 const cpp_function &fset,
1872                                 const Extra &...extra) {
1873         static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
1874                       "Argument annotations are not allowed for properties");
1875         auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1876         auto *rec_active = rec_fget;
1877         if (rec_fget) {
1878             char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific
1879                                                documentation string */
1880             detail::process_attributes<Extra...>::init(extra..., rec_fget);
1881             if (rec_fget->doc && rec_fget->doc != doc_prev) {
1882                 std::free(doc_prev);
1883                 rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc);
1884             }
1885         }
1886         if (rec_fset) {
1887             char *doc_prev = rec_fset->doc;
1888             detail::process_attributes<Extra...>::init(extra..., rec_fset);
1889             if (rec_fset->doc && rec_fset->doc != doc_prev) {
1890                 std::free(doc_prev);
1891                 rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc);
1892             }
1893             if (!rec_active) {
1894                 rec_active = rec_fset;
1895             }
1896         }
1897         def_property_static_impl(name, fget, fset, rec_active);
1898         return *this;
1899     }
1900 
1901 private:
1902     /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1903     template <typename T>
1904     static void init_holder(detail::instance *inst,
1905                             detail::value_and_holder &v_h,
1906                             const holder_type * /* unused */,
1907                             const std::enable_shared_from_this<T> * /* dummy */) {
1908 
1909         auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1910             detail::try_get_shared_from_this(v_h.value_ptr<type>()));
1911         if (sh) {
1912             new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
1913             v_h.set_holder_constructed();
1914         }
1915 
1916         if (!v_h.holder_constructed() && inst->owned) {
1917             new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1918             v_h.set_holder_constructed();
1919         }
1920     }
1921 
1922     static void init_holder_from_existing(const detail::value_and_holder &v_h,
1923                                           const holder_type *holder_ptr,
1924                                           std::true_type /*is_copy_constructible*/) {
1925         new (std::addressof(v_h.holder<holder_type>()))
1926             holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1927     }
1928 
1929     static void init_holder_from_existing(const detail::value_and_holder &v_h,
1930                                           const holder_type *holder_ptr,
1931                                           std::false_type /*is_copy_constructible*/) {
1932         new (std::addressof(v_h.holder<holder_type>()))
1933             holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1934     }
1935 
1936     /// Initialize holder object, variant 2: try to construct from existing holder object, if
1937     /// possible
1938     static void init_holder(detail::instance *inst,
1939                             detail::value_and_holder &v_h,
1940                             const holder_type *holder_ptr,
1941                             const void * /* dummy -- not enable_shared_from_this<T>) */) {
1942         if (holder_ptr) {
1943             init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1944             v_h.set_holder_constructed();
1945         } else if (detail::always_construct_holder<holder_type>::value || inst->owned) {
1946             new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1947             v_h.set_holder_constructed();
1948         }
1949     }
1950 
1951     /// Performs instance initialization including constructing a holder and registering the known
1952     /// instance.  Should be called as soon as the `type` value_ptr is set for an instance.  Takes
1953     /// an optional pointer to an existing holder to use; if not specified and the instance is
1954     /// `.owned`, a new holder will be constructed to manage the value pointer.
1955     static void init_instance(detail::instance *inst, const void *holder_ptr) {
1956         auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
1957         if (!v_h.instance_registered()) {
1958             register_instance(inst, v_h.value_ptr(), v_h.type);
1959             v_h.set_instance_registered();
1960         }
1961         init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
1962     }
1963 
1964     /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
1965     static void dealloc(detail::value_and_holder &v_h) {
1966         // We could be deallocating because we are cleaning up after a Python exception.
1967         // If so, the Python error indicator will be set. We need to clear that before
1968         // running the destructor, in case the destructor code calls more Python.
1969         // If we don't, the Python API will exit with an exception, and pybind11 will
1970         // throw error_already_set from the C++ destructor which is forbidden and triggers
1971         // std::terminate().
1972         error_scope scope;
1973         if (v_h.holder_constructed()) {
1974             v_h.holder<holder_type>().~holder_type();
1975             v_h.set_holder_constructed(false);
1976         } else {
1977             detail::call_operator_delete(
1978                 v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align);
1979         }
1980         v_h.value_ptr() = nullptr;
1981     }
1982 
1983     static detail::function_record *get_function_record(handle h) {
1984         h = detail::get_function(h);
1985         if (!h) {
1986             return nullptr;
1987         }
1988 
1989         handle func_self = PyCFunction_GET_SELF(h.ptr());
1990         if (!func_self) {
1991             throw error_already_set();
1992         }
1993         if (!isinstance<capsule>(func_self)) {
1994             return nullptr;
1995         }
1996         auto cap = reinterpret_borrow<capsule>(func_self);
1997         if (!detail::is_function_record_capsule(cap)) {
1998             return nullptr;
1999         }
2000         return cap.get_pointer<detail::function_record>();
2001     }
2002 };
2003 
2004 /// Binds an existing constructor taking arguments Args...
2005 template <typename... Args>
2006 detail::initimpl::constructor<Args...> init() {
2007     return {};
2008 }
2009 /// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
2010 /// when not inheriting on the Python side).
2011 template <typename... Args>
2012 detail::initimpl::alias_constructor<Args...> init_alias() {
2013     return {};
2014 }
2015 
2016 /// Binds a factory function as a constructor
2017 template <typename Func, typename Ret = detail::initimpl::factory<Func>>
2018 Ret init(Func &&f) {
2019     return {std::forward<Func>(f)};
2020 }
2021 
2022 /// Dual-argument factory function: the first function is called when no alias is needed, the
2023 /// second when an alias is needed (i.e. due to python-side inheritance).  Arguments must be
2024 /// identical.
2025 template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
2026 Ret init(CFunc &&c, AFunc &&a) {
2027     return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
2028 }
2029 
2030 /// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
2031 /// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
2032 template <typename GetState, typename SetState>
2033 detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
2034     return {std::forward<GetState>(g), std::forward<SetState>(s)};
2035 }
2036 
2037 PYBIND11_NAMESPACE_BEGIN(detail)
2038 
2039 inline str enum_name(handle arg) {
2040     dict entries = arg.get_type().attr("__entries");
2041     for (auto kv : entries) {
2042         if (handle(kv.second[int_(0)]).equal(arg)) {
2043             return pybind11::str(kv.first);
2044         }
2045     }
2046     return "???";
2047 }
2048 
2049 struct enum_base {
2050     enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) {}
2051 
2052     PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
2053         m_base.attr("__entries") = dict();
2054         auto property = handle((PyObject *) &PyProperty_Type);
2055         auto static_property = handle((PyObject *) get_internals().static_property_type);
2056 
2057         m_base.attr("__repr__") = cpp_function(
2058             [](const object &arg) -> str {
2059                 handle type = type::handle_of(arg);
2060                 object type_name = type.attr("__name__");
2061                 return pybind11::str("<{}.{}: {}>")
2062                     .format(std::move(type_name), enum_name(arg), int_(arg));
2063             },
2064             name("__repr__"),
2065             is_method(m_base));
2066 
2067         m_base.attr("name") = property(cpp_function(&enum_name, name("name"), is_method(m_base)));
2068 
2069         m_base.attr("__str__") = cpp_function(
2070             [](handle arg) -> str {
2071                 object type_name = type::handle_of(arg).attr("__name__");
2072                 return pybind11::str("{}.{}").format(std::move(type_name), enum_name(arg));
2073             },
2074             name("__str__"),
2075             is_method(m_base));
2076 
2077         if (options::show_enum_members_docstring()) {
2078             m_base.attr("__doc__") = static_property(
2079                 cpp_function(
2080                     [](handle arg) -> std::string {
2081                         std::string docstring;
2082                         dict entries = arg.attr("__entries");
2083                         if (((PyTypeObject *) arg.ptr())->tp_doc) {
2084                             docstring += std::string(
2085                                 reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);
2086                             docstring += "\n\n";
2087                         }
2088                         docstring += "Members:";
2089                         for (auto kv : entries) {
2090                             auto key = std::string(pybind11::str(kv.first));
2091                             auto comment = kv.second[int_(1)];
2092                             docstring += "\n\n  ";
2093                             docstring += key;
2094                             if (!comment.is_none()) {
2095                                 docstring += " : ";
2096                                 docstring += pybind11::str(comment).cast<std::string>();
2097                             }
2098                         }
2099                         return docstring;
2100                     },
2101                     name("__doc__")),
2102                 none(),
2103                 none(),
2104                 "");
2105         }
2106 
2107         m_base.attr("__members__") = static_property(cpp_function(
2108                                                          [](handle arg) -> dict {
2109                                                              dict entries = arg.attr("__entries"),
2110                                                                   m;
2111                                                              for (auto kv : entries) {
2112                                                                  m[kv.first] = kv.second[int_(0)];
2113                                                              }
2114                                                              return m;
2115                                                          },
2116                                                          name("__members__")),
2117                                                      none(),
2118                                                      none(),
2119                                                      "");
2120 
2121 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)                                        \
2122     m_base.attr(op) = cpp_function(                                                               \
2123         [](const object &a, const object &b) {                                                    \
2124             if (!type::handle_of(a).is(type::handle_of(b)))                                       \
2125                 strict_behavior; /* NOLINT(bugprone-macro-parentheses) */                         \
2126             return expr;                                                                          \
2127         },                                                                                        \
2128         name(op),                                                                                 \
2129         is_method(m_base),                                                                        \
2130         arg("other"))
2131 
2132 #define PYBIND11_ENUM_OP_CONV(op, expr)                                                           \
2133     m_base.attr(op) = cpp_function(                                                               \
2134         [](const object &a_, const object &b_) {                                                  \
2135             int_ a(a_), b(b_);                                                                    \
2136             return expr;                                                                          \
2137         },                                                                                        \
2138         name(op),                                                                                 \
2139         is_method(m_base),                                                                        \
2140         arg("other"))
2141 
2142 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr)                                                       \
2143     m_base.attr(op) = cpp_function(                                                               \
2144         [](const object &a_, const object &b) {                                                   \
2145             int_ a(a_);                                                                           \
2146             return expr;                                                                          \
2147         },                                                                                        \
2148         name(op),                                                                                 \
2149         is_method(m_base),                                                                        \
2150         arg("other"))
2151 
2152         if (is_convertible) {
2153             PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
2154             PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
2155 
2156             if (is_arithmetic) {
2157                 PYBIND11_ENUM_OP_CONV("__lt__", a < b);
2158                 PYBIND11_ENUM_OP_CONV("__gt__", a > b);
2159                 PYBIND11_ENUM_OP_CONV("__le__", a <= b);
2160                 PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
2161                 PYBIND11_ENUM_OP_CONV("__and__", a & b);
2162                 PYBIND11_ENUM_OP_CONV("__rand__", a & b);
2163                 PYBIND11_ENUM_OP_CONV("__or__", a | b);
2164                 PYBIND11_ENUM_OP_CONV("__ror__", a | b);
2165                 PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
2166                 PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
2167                 m_base.attr("__invert__")
2168                     = cpp_function([](const object &arg) { return ~(int_(arg)); },
2169                                    name("__invert__"),
2170                                    is_method(m_base));
2171             }
2172         } else {
2173             PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
2174             PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
2175 
2176             if (is_arithmetic) {
2177 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
2178                 PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
2179                 PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
2180                 PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
2181                 PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
2182 #undef PYBIND11_THROW
2183             }
2184         }
2185 
2186 #undef PYBIND11_ENUM_OP_CONV_LHS
2187 #undef PYBIND11_ENUM_OP_CONV
2188 #undef PYBIND11_ENUM_OP_STRICT
2189 
2190         m_base.attr("__getstate__") = cpp_function(
2191             [](const object &arg) { return int_(arg); }, name("__getstate__"), is_method(m_base));
2192 
2193         m_base.attr("__hash__") = cpp_function(
2194             [](const object &arg) { return int_(arg); }, name("__hash__"), is_method(m_base));
2195     }
2196 
2197     PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc = nullptr) {
2198         dict entries = m_base.attr("__entries");
2199         str name(name_);
2200         if (entries.contains(name)) {
2201             std::string type_name = (std::string) str(m_base.attr("__name__"));
2202             throw value_error(std::move(type_name) + ": element \"" + std::string(name_)
2203                               + "\" already exists!");
2204         }
2205 
2206         entries[name] = pybind11::make_tuple(value, doc);
2207         m_base.attr(std::move(name)) = std::move(value);
2208     }
2209 
2210     PYBIND11_NOINLINE void export_values() {
2211         dict entries = m_base.attr("__entries");
2212         for (auto kv : entries) {
2213             m_parent.attr(kv.first) = kv.second[int_(0)];
2214         }
2215     }
2216 
2217     handle m_base;
2218     handle m_parent;
2219 };
2220 
2221 template <bool is_signed, size_t length>
2222 struct equivalent_integer {};
2223 template <>
2224 struct equivalent_integer<true, 1> {
2225     using type = int8_t;
2226 };
2227 template <>
2228 struct equivalent_integer<false, 1> {
2229     using type = uint8_t;
2230 };
2231 template <>
2232 struct equivalent_integer<true, 2> {
2233     using type = int16_t;
2234 };
2235 template <>
2236 struct equivalent_integer<false, 2> {
2237     using type = uint16_t;
2238 };
2239 template <>
2240 struct equivalent_integer<true, 4> {
2241     using type = int32_t;
2242 };
2243 template <>
2244 struct equivalent_integer<false, 4> {
2245     using type = uint32_t;
2246 };
2247 template <>
2248 struct equivalent_integer<true, 8> {
2249     using type = int64_t;
2250 };
2251 template <>
2252 struct equivalent_integer<false, 8> {
2253     using type = uint64_t;
2254 };
2255 
2256 template <typename IntLike>
2257 using equivalent_integer_t =
2258     typename equivalent_integer<std::is_signed<IntLike>::value, sizeof(IntLike)>::type;
2259 
2260 PYBIND11_NAMESPACE_END(detail)
2261 
2262 /// Binds C++ enumerations and enumeration classes to Python
2263 template <typename Type>
2264 class enum_ : public class_<Type> {
2265 public:
2266     using Base = class_<Type>;
2267     using Base::attr;
2268     using Base::def;
2269     using Base::def_property_readonly;
2270     using Base::def_property_readonly_static;
2271     using Underlying = typename std::underlying_type<Type>::type;
2272     // Scalar is the integer representation of underlying type
2273     using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2274                                                         std::is_same<Underlying, bool>>::value,
2275                                          detail::equivalent_integer_t<Underlying>,
2276                                          Underlying>;
2277 
2278     template <typename... Extra>
2279     enum_(const handle &scope, const char *name, const Extra &...extra)
2280         : class_<Type>(scope, name, extra...), m_base(*this, scope) {
2281         constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
2282         constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
2283         m_base.init(is_arithmetic, is_convertible);
2284 
2285         def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
2286         def_property_readonly("value", [](Type value) { return (Scalar) value; });
2287         def("__int__", [](Type value) { return (Scalar) value; });
2288         def("__index__", [](Type value) { return (Scalar) value; });
2289         attr("__setstate__") = cpp_function(
2290             [](detail::value_and_holder &v_h, Scalar arg) {
2291                 detail::initimpl::setstate<Base>(
2292                     v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type);
2293             },
2294             detail::is_new_style_constructor(),
2295             pybind11::name("__setstate__"),
2296             is_method(*this),
2297             arg("state"));
2298     }
2299 
2300     /// Export enumeration entries into the parent scope
2301     enum_ &export_values() {
2302         m_base.export_values();
2303         return *this;
2304     }
2305 
2306     /// Add an enumeration entry
2307     enum_ &value(char const *name, Type value, const char *doc = nullptr) {
2308         m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
2309         return *this;
2310     }
2311 
2312 private:
2313     detail::enum_base m_base;
2314 };
2315 
2316 PYBIND11_NAMESPACE_BEGIN(detail)
2317 
2318 PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient) {
2319     if (!nurse || !patient) {
2320         pybind11_fail("Could not activate keep_alive!");
2321     }
2322 
2323     if (patient.is_none() || nurse.is_none()) {
2324         return; /* Nothing to keep alive or nothing to be kept alive by */
2325     }
2326 
2327     auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
2328     if (!tinfo.empty()) {
2329         /* It's a pybind-registered type, so we can store the patient in the
2330          * internal list. */
2331         add_patient(nurse.ptr(), patient.ptr());
2332     } else {
2333         /* Fall back to clever approach based on weak references taken from
2334          * Boost.Python. This is not used for pybind-registered types because
2335          * the objects can be destroyed out-of-order in a GC pass. */
2336         cpp_function disable_lifesupport([patient](handle weakref) {
2337             patient.dec_ref();
2338             weakref.dec_ref();
2339         });
2340 
2341         weakref wr(nurse, disable_lifesupport);
2342 
2343         patient.inc_ref(); /* reference patient and leak the weak reference */
2344         (void) wr.release();
2345     }
2346 }
2347 
2348 PYBIND11_NOINLINE void
2349 keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
2350     auto get_arg = [&](size_t n) {
2351         if (n == 0) {
2352             return ret;
2353         }
2354         if (n == 1 && call.init_self) {
2355             return call.init_self;
2356         }
2357         if (n <= call.args.size()) {
2358             return call.args[n - 1];
2359         }
2360         return handle();
2361     };
2362 
2363     keep_alive_impl(get_arg(Nurse), get_arg(Patient));
2364 }
2365 
2366 inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
2367 all_type_info_get_cache(PyTypeObject *type) {
2368     auto res = with_internals([type](internals &internals) {
2369         return internals
2370             .registered_types_py
2371 #ifdef __cpp_lib_unordered_map_try_emplace
2372             .try_emplace(type);
2373 #else
2374             .emplace(type, std::vector<detail::type_info *>());
2375 #endif
2376     });
2377     if (res.second) {
2378         // New cache entry created; set up a weak reference to automatically remove it if the type
2379         // gets destroyed:
2380         weakref((PyObject *) type, cpp_function([type](handle wr) {
2381                     with_internals([type](internals &internals) {
2382                         internals.registered_types_py.erase(type);
2383 
2384                         // TODO consolidate the erasure code in pybind11_meta_dealloc() in class.h
2385                         auto &cache = internals.inactive_override_cache;
2386                         for (auto it = cache.begin(), last = cache.end(); it != last;) {
2387                             if (it->first == reinterpret_cast<PyObject *>(type)) {
2388                                 it = cache.erase(it);
2389                             } else {
2390                                 ++it;
2391                             }
2392                         }
2393                     });
2394 
2395                     wr.dec_ref();
2396                 }))
2397             .release();
2398     }
2399 
2400     return res;
2401 }
2402 
2403 /* There are a large number of apparently unused template arguments because
2404  * each combination requires a separate py::class_ registration.
2405  */
2406 template <typename Access,
2407           return_value_policy Policy,
2408           typename Iterator,
2409           typename Sentinel,
2410           typename ValueType,
2411           typename... Extra>
2412 struct iterator_state {
2413     Iterator it;
2414     Sentinel end;
2415     bool first_or_done;
2416 };
2417 
2418 // Note: these helpers take the iterator by non-const reference because some
2419 // iterators in the wild can't be dereferenced when const. The & after Iterator
2420 // is required for MSVC < 16.9. SFINAE cannot be reused for result_type due to
2421 // bugs in ICC, NVCC, and PGI compilers. See PR #3293.
2422 template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
2423 struct iterator_access {
2424     using result_type = decltype(*std::declval<Iterator &>());
2425     // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
2426     result_type operator()(Iterator &it) const { return *it; }
2427 };
2428 
2429 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).first)>
2430 class iterator_key_access {
2431 private:
2432     using pair_type = decltype(*std::declval<Iterator &>());
2433 
2434 public:
2435     /* If either the pair itself or the element of the pair is a reference, we
2436      * want to return a reference, otherwise a value. When the decltype
2437      * expression is parenthesized it is based on the value category of the
2438      * expression; otherwise it is the declared type of the pair member.
2439      * The use of declval<pair_type> in the second branch rather than directly
2440      * using *std::declval<Iterator &>() is a workaround for nvcc
2441      * (it's not used in the first branch because going via decltype and back
2442      * through declval does not perfectly preserve references).
2443      */
2444     using result_type
2445         = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
2446                         decltype(((*std::declval<Iterator &>()).first)),
2447                         decltype(std::declval<pair_type>().first)>;
2448     result_type operator()(Iterator &it) const { return (*it).first; }
2449 };
2450 
2451 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
2452 class iterator_value_access {
2453 private:
2454     using pair_type = decltype(*std::declval<Iterator &>());
2455 
2456 public:
2457     using result_type
2458         = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
2459                         decltype(((*std::declval<Iterator &>()).second)),
2460                         decltype(std::declval<pair_type>().second)>;
2461     result_type operator()(Iterator &it) const { return (*it).second; }
2462 };
2463 
2464 template <typename Access,
2465           return_value_policy Policy,
2466           typename Iterator,
2467           typename Sentinel,
2468           typename ValueType,
2469           typename... Extra>
2470 iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra) {
2471     using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
2472     // TODO: state captures only the types of Extra, not the values
2473 
2474     if (!detail::get_type_info(typeid(state), false)) {
2475         class_<state>(handle(), "iterator", pybind11::module_local())
2476             .def("__iter__", [](state &s) -> state & { return s; })
2477             .def(
2478                 "__next__",
2479                 [](state &s) -> ValueType {
2480                     if (!s.first_or_done) {
2481                         ++s.it;
2482                     } else {
2483                         s.first_or_done = false;
2484                     }
2485                     if (s.it == s.end) {
2486                         s.first_or_done = true;
2487                         throw stop_iteration();
2488                     }
2489                     return Access()(s.it);
2490                     // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
2491                 },
2492                 std::forward<Extra>(extra)...,
2493                 Policy);
2494     }
2495 
2496     return cast(state{std::forward<Iterator>(first), std::forward<Sentinel>(last), true});
2497 }
2498 
2499 PYBIND11_NAMESPACE_END(detail)
2500 
2501 /// Makes a python iterator from a first and past-the-end C++ InputIterator.
2502 template <return_value_policy Policy = return_value_policy::reference_internal,
2503           typename Iterator,
2504           typename Sentinel,
2505           typename ValueType = typename detail::iterator_access<Iterator>::result_type,
2506           typename... Extra>
2507 typing::Iterator<ValueType> make_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2508     return detail::make_iterator_impl<detail::iterator_access<Iterator>,
2509                                       Policy,
2510                                       Iterator,
2511                                       Sentinel,
2512                                       ValueType,
2513                                       Extra...>(std::forward<Iterator>(first),
2514                                                 std::forward<Sentinel>(last),
2515                                                 std::forward<Extra>(extra)...);
2516 }
2517 
2518 /// Makes a python iterator over the keys (`.first`) of a iterator over pairs from a
2519 /// first and past-the-end InputIterator.
2520 template <return_value_policy Policy = return_value_policy::reference_internal,
2521           typename Iterator,
2522           typename Sentinel,
2523           typename KeyType = typename detail::iterator_key_access<Iterator>::result_type,
2524           typename... Extra>
2525 typing::Iterator<KeyType> make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2526     return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
2527                                       Policy,
2528                                       Iterator,
2529                                       Sentinel,
2530                                       KeyType,
2531                                       Extra...>(std::forward<Iterator>(first),
2532                                                 std::forward<Sentinel>(last),
2533                                                 std::forward<Extra>(extra)...);
2534 }
2535 
2536 /// Makes a python iterator over the values (`.second`) of a iterator over pairs from a
2537 /// first and past-the-end InputIterator.
2538 template <return_value_policy Policy = return_value_policy::reference_internal,
2539           typename Iterator,
2540           typename Sentinel,
2541           typename ValueType = typename detail::iterator_value_access<Iterator>::result_type,
2542           typename... Extra>
2543 typing::Iterator<ValueType> make_value_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2544     return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
2545                                       Policy,
2546                                       Iterator,
2547                                       Sentinel,
2548                                       ValueType,
2549                                       Extra...>(std::forward<Iterator>(first),
2550                                                 std::forward<Sentinel>(last),
2551                                                 std::forward<Extra>(extra)...);
2552 }
2553 
2554 /// Makes an iterator over values of an stl container or other container supporting
2555 /// `std::begin()`/`std::end()`
2556 template <return_value_policy Policy = return_value_policy::reference_internal,
2557           typename Type,
2558           typename ValueType = typename detail::iterator_access<
2559               decltype(std::begin(std::declval<Type &>()))>::result_type,
2560           typename... Extra>
2561 typing::Iterator<ValueType> make_iterator(Type &value, Extra &&...extra) {
2562     return make_iterator<Policy>(
2563         std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2564 }
2565 
2566 /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
2567 /// `std::begin()`/`std::end()`
2568 template <return_value_policy Policy = return_value_policy::reference_internal,
2569           typename Type,
2570           typename KeyType = typename detail::iterator_key_access<
2571               decltype(std::begin(std::declval<Type &>()))>::result_type,
2572           typename... Extra>
2573 typing::Iterator<KeyType> make_key_iterator(Type &value, Extra &&...extra) {
2574     return make_key_iterator<Policy>(
2575         std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2576 }
2577 
2578 /// Makes an iterator over the values (`.second`) of a stl map-like container supporting
2579 /// `std::begin()`/`std::end()`
2580 template <return_value_policy Policy = return_value_policy::reference_internal,
2581           typename Type,
2582           typename ValueType = typename detail::iterator_value_access<
2583               decltype(std::begin(std::declval<Type &>()))>::result_type,
2584           typename... Extra>
2585 typing::Iterator<ValueType> make_value_iterator(Type &value, Extra &&...extra) {
2586     return make_value_iterator<Policy>(
2587         std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2588 }
2589 
2590 template <typename InputType, typename OutputType>
2591 void implicitly_convertible() {
2592     struct set_flag {
2593         bool &flag;
2594         explicit set_flag(bool &flag_) : flag(flag_) { flag_ = true; }
2595         ~set_flag() { flag = false; }
2596     };
2597     auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
2598 #ifdef Py_GIL_DISABLED
2599         thread_local bool currently_used = false;
2600 #else
2601         static bool currently_used = false;
2602 #endif
2603         if (currently_used) { // implicit conversions are non-reentrant
2604             return nullptr;
2605         }
2606         set_flag flag_helper(currently_used);
2607         if (!detail::make_caster<InputType>().load(obj, false)) {
2608             return nullptr;
2609         }
2610         tuple args(1);
2611         args[0] = obj;
2612         PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
2613         if (result == nullptr) {
2614             PyErr_Clear();
2615         }
2616         return result;
2617     };
2618 
2619     if (auto *tinfo = detail::get_type_info(typeid(OutputType))) {
2620         tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
2621     } else {
2622         pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
2623     }
2624 }
2625 
2626 inline void register_exception_translator(ExceptionTranslator &&translator) {
2627     detail::with_internals([&](detail::internals &internals) {
2628         internals.registered_exception_translators.push_front(
2629             std::forward<ExceptionTranslator>(translator));
2630     });
2631 }
2632 
2633 /**
2634  * Add a new module-local exception translator. Locally registered functions
2635  * will be tried before any globally registered exception translators, which
2636  * will only be invoked if the module-local handlers do not deal with
2637  * the exception.
2638  */
2639 inline void register_local_exception_translator(ExceptionTranslator &&translator) {
2640     detail::with_internals([&](detail::internals &internals) {
2641         (void) internals;
2642         detail::get_local_internals().registered_exception_translators.push_front(
2643             std::forward<ExceptionTranslator>(translator));
2644     });
2645 }
2646 
2647 /**
2648  * Wrapper to generate a new Python exception type.
2649  *
2650  * This should only be used with py::set_error() for now.
2651  * It is not (yet) possible to use as a py::base.
2652  * Template type argument is reserved for future use.
2653  */
2654 template <typename type>
2655 class exception : public object {
2656 public:
2657     exception() = default;
2658     exception(handle scope, const char *name, handle base = PyExc_Exception) {
2659         std::string full_name
2660             = scope.attr("__name__").cast<std::string>() + std::string(".") + name;
2661         m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), nullptr);
2662         if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name)) {
2663             pybind11_fail("Error during initialization: multiple incompatible "
2664                           "definitions with name \""
2665                           + std::string(name) + "\"");
2666         }
2667         scope.attr(name) = *this;
2668     }
2669 
2670     // Sets the current python exception to this exception object with the given message
2671     PYBIND11_DEPRECATED("Please use py::set_error() instead "
2672                         "(https://github.com/pybind/pybind11/pull/4772)")
2673     void operator()(const char *message) const { set_error(*this, message); }
2674 };
2675 
2676 PYBIND11_NAMESPACE_BEGIN(detail)
2677 
2678 template <>
2679 struct handle_type_name<exception<void>> {
2680     static constexpr auto name = const_name("Exception");
2681 };
2682 
2683 // Helper function for register_exception and register_local_exception
2684 template <typename CppException>
2685 exception<CppException> &
2686 register_exception_impl(handle scope, const char *name, handle base, bool isLocal) {
2687     PYBIND11_CONSTINIT static gil_safe_call_once_and_store<exception<CppException>> exc_storage;
2688     exc_storage.call_once_and_store_result(
2689         [&]() { return exception<CppException>(scope, name, base); });
2690 
2691     auto register_func
2692         = isLocal ? &register_local_exception_translator : &register_exception_translator;
2693 
2694     register_func([](std::exception_ptr p) {
2695         if (!p) {
2696             return;
2697         }
2698         try {
2699             std::rethrow_exception(p);
2700         } catch (const CppException &e) {
2701             set_error(exc_storage.get_stored(), e.what());
2702         }
2703     });
2704     return exc_storage.get_stored();
2705 }
2706 
2707 PYBIND11_NAMESPACE_END(detail)
2708 
2709 /**
2710  * Registers a Python exception in `m` of the given `name` and installs a translator to
2711  * translate the C++ exception to the created Python exception using the what() method.
2712  * This is intended for simple exception translations; for more complex translation, register the
2713  * exception object and translator directly.
2714  */
2715 template <typename CppException>
2716 exception<CppException> &
2717 register_exception(handle scope, const char *name, handle base = PyExc_Exception) {
2718     return detail::register_exception_impl<CppException>(scope, name, base, false /* isLocal */);
2719 }
2720 
2721 /**
2722  * Registers a Python exception in `m` of the given `name` and installs a translator to
2723  * translate the C++ exception to the created Python exception using the what() method.
2724  * This translator will only be used for exceptions that are thrown in this module and will be
2725  * tried before global exception translators, including those registered with register_exception.
2726  * This is intended for simple exception translations; for more complex translation, register the
2727  * exception object and translator directly.
2728  */
2729 template <typename CppException>
2730 exception<CppException> &
2731 register_local_exception(handle scope, const char *name, handle base = PyExc_Exception) {
2732     return detail::register_exception_impl<CppException>(scope, name, base, true /* isLocal */);
2733 }
2734 
2735 PYBIND11_NAMESPACE_BEGIN(detail)
2736 PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) {
2737     auto strings = tuple(args.size());
2738     for (size_t i = 0; i < args.size(); ++i) {
2739         strings[i] = str(args[i]);
2740     }
2741     auto sep = kwargs.contains("sep") ? kwargs["sep"] : str(" ");
2742     auto line = sep.attr("join")(std::move(strings));
2743 
2744     object file;
2745     if (kwargs.contains("file")) {
2746         file = kwargs["file"].cast<object>();
2747     } else {
2748         try {
2749             file = module_::import("sys").attr("stdout");
2750         } catch (const error_already_set &) {
2751             /* If print() is called from code that is executed as
2752                part of garbage collection during interpreter shutdown,
2753                importing 'sys' can fail. Give up rather than crashing the
2754                interpreter in this case. */
2755             return;
2756         }
2757     }
2758 
2759     auto write = file.attr("write");
2760     write(std::move(line));
2761     write(kwargs.contains("end") ? kwargs["end"] : str("\n"));
2762 
2763     if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) {
2764         file.attr("flush")();
2765     }
2766 }
2767 PYBIND11_NAMESPACE_END(detail)
2768 
2769 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
2770 void print(Args &&...args) {
2771     auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
2772     detail::print(c.args(), c.kwargs());
2773 }
2774 
2775 inline void
2776 error_already_set::m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr) {
2777     gil_scoped_acquire gil;
2778     error_scope scope;
2779     delete raw_ptr;
2780 }
2781 
2782 inline const char *error_already_set::what() const noexcept {
2783     gil_scoped_acquire gil;
2784     error_scope scope;
2785     return m_fetched_error->error_string().c_str();
2786 }
2787 
2788 PYBIND11_NAMESPACE_BEGIN(detail)
2789 
2790 inline function
2791 get_type_override(const void *this_ptr, const type_info *this_type, const char *name) {
2792     handle self = get_object_handle(this_ptr, this_type);
2793     if (!self) {
2794         return function();
2795     }
2796     handle type = type::handle_of(self);
2797     auto key = std::make_pair(type.ptr(), name);
2798 
2799     /* Cache functions that aren't overridden in Python to avoid
2800        many costly Python dictionary lookups below */
2801     bool not_overridden = with_internals([&key](internals &internals) {
2802         auto &cache = internals.inactive_override_cache;
2803         return cache.find(key) != cache.end();
2804     });
2805     if (not_overridden) {
2806         return function();
2807     }
2808 
2809     function override = getattr(self, name, function());
2810     if (override.is_cpp_function()) {
2811         with_internals([&](internals &internals) {
2812             internals.inactive_override_cache.insert(std::move(key));
2813         });
2814         return function();
2815     }
2816 
2817     /* Don't call dispatch code if invoked from overridden function.
2818        Unfortunately this doesn't work on PyPy. */
2819 #if !defined(PYPY_VERSION)
2820 #    if PY_VERSION_HEX >= 0x03090000
2821     PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
2822     if (frame != nullptr) {
2823         PyCodeObject *f_code = PyFrame_GetCode(frame);
2824         // f_code is guaranteed to not be NULL
2825         if ((std::string) str(f_code->co_name) == name && f_code->co_argcount > 0) {
2826 #        if PY_VERSION_HEX >= 0x030d0000
2827             PyObject *locals = PyEval_GetFrameLocals();
2828 #        else
2829             PyObject *locals = PyEval_GetLocals();
2830             Py_XINCREF(locals);
2831 #        endif
2832             if (locals != nullptr) {
2833 #        if PY_VERSION_HEX >= 0x030b0000
2834                 PyObject *co_varnames = PyCode_GetVarnames(f_code);
2835 #        else
2836                 PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code, "co_varnames");
2837 #        endif
2838                 PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
2839                 Py_DECREF(co_varnames);
2840                 PyObject *self_caller = dict_getitem(locals, self_arg);
2841                 Py_DECREF(locals);
2842                 if (self_caller == self.ptr()) {
2843                     Py_DECREF(f_code);
2844                     Py_DECREF(frame);
2845                     return function();
2846                 }
2847             }
2848         }
2849         Py_DECREF(f_code);
2850         Py_DECREF(frame);
2851     }
2852 #    else
2853     PyFrameObject *frame = PyThreadState_Get()->frame;
2854     if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name
2855         && frame->f_code->co_argcount > 0) {
2856         PyFrame_FastToLocals(frame);
2857         PyObject *self_caller
2858             = dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2859         if (self_caller == self.ptr()) {
2860             return function();
2861         }
2862     }
2863 #    endif
2864 
2865 #else
2866     /* PyPy currently doesn't provide a detailed cpyext emulation of
2867        frame objects, so we have to emulate this using Python. This
2868        is going to be slow..*/
2869     dict d;
2870     d["self"] = self;
2871     d["name"] = pybind11::str(name);
2872     PyObject *result
2873         = PyRun_String("import inspect\n"
2874                        "frame = inspect.currentframe()\n"
2875                        "if frame is not None:\n"
2876                        "    frame = frame.f_back\n"
2877                        "    if frame is not None and str(frame.f_code.co_name) == name and "
2878                        "frame.f_code.co_argcount > 0:\n"
2879                        "        self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2880                        "        if self_caller == self:\n"
2881                        "            self = None\n",
2882                        Py_file_input,
2883                        d.ptr(),
2884                        d.ptr());
2885     if (result == nullptr)
2886         throw error_already_set();
2887     Py_DECREF(result);
2888     if (d["self"].is_none())
2889         return function();
2890 #endif
2891 
2892     return override;
2893 }
2894 PYBIND11_NAMESPACE_END(detail)
2895 
2896 /** \rst
2897   Try to retrieve a python method by the provided name from the instance pointed to by the
2898   this_ptr.
2899 
2900   :this_ptr: The pointer to the object the overridden method should be retrieved for. This should
2901              be the first non-trampoline class encountered in the inheritance chain.
2902   :name: The name of the overridden Python method to retrieve.
2903   :return: The Python method by this name from the object or an empty function wrapper.
2904  \endrst */
2905 template <class T>
2906 function get_override(const T *this_ptr, const char *name) {
2907     auto *tinfo = detail::get_type_info(typeid(T));
2908     return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
2909 }
2910 
2911 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...)                                        \
2912     do {                                                                                          \
2913         pybind11::gil_scoped_acquire gil;                                                         \
2914         pybind11::function override                                                               \
2915             = pybind11::get_override(static_cast<const cname *>(this), name);                     \
2916         if (override) {                                                                           \
2917             auto o = override(__VA_ARGS__);                                                       \
2918             PYBIND11_WARNING_PUSH                                                                 \
2919             PYBIND11_WARNING_DISABLE_MSVC(4127)                                                   \
2920             if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value              \
2921                 && !pybind11::detail::is_same_ignoring_cvref<ret_type, PyObject *>::value) {      \
2922                 static pybind11::detail::override_caster_t<ret_type> caster;                      \
2923                 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster);                \
2924             }                                                                                     \
2925             PYBIND11_WARNING_POP                                                                  \
2926             return pybind11::detail::cast_safe<ret_type>(std::move(o));                           \
2927         }                                                                                         \
2928     } while (false)
2929 
2930 /** \rst
2931     Macro to populate the virtual method in the trampoline class. This macro tries to look up a
2932     method named 'fn' from the Python side, deals with the :ref:`gil` and necessary argument
2933     conversions to call this method and return the appropriate type.
2934     See :ref:`overriding_virtuals` for more information. This macro should be used when the method
2935     name in C is not the same as the method name in Python. For example with `__str__`.
2936 
2937     .. code-block:: cpp
2938 
2939       std::string toString() override {
2940         PYBIND11_OVERRIDE_NAME(
2941             std::string, // Return type (ret_type)
2942             Animal,      // Parent class (cname)
2943             "__str__",   // Name of method in Python (name)
2944             toString,    // Name of function in C++ (fn)
2945         );
2946       }
2947 \endrst */
2948 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...)                                    \
2949     do {                                                                                          \
2950         PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2951         return cname::fn(__VA_ARGS__);                                                            \
2952     } while (false)
2953 
2954 /** \rst
2955     Macro for pure virtual functions, this function is identical to
2956     :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it throws if no override can be found.
2957 \endrst */
2958 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...)                               \
2959     do {                                                                                          \
2960         PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2961         pybind11::pybind11_fail(                                                                  \
2962             "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\"");   \
2963     } while (false)
2964 
2965 /** \rst
2966     Macro to populate the virtual method in the trampoline class. This macro tries to look up the
2967     method from the Python side, deals with the :ref:`gil` and necessary argument conversions to
2968     call this method and return the appropriate type. This macro should be used if the method name
2969     in C and in Python are identical.
2970     See :ref:`overriding_virtuals` for more information.
2971 
2972     .. code-block:: cpp
2973 
2974       class PyAnimal : public Animal {
2975       public:
2976           // Inherit the constructors
2977           using Animal::Animal;
2978 
2979           // Trampoline (need one for each virtual function)
2980           std::string go(int n_times) override {
2981               PYBIND11_OVERRIDE_PURE(
2982                   std::string, // Return type (ret_type)
2983                   Animal,      // Parent class (cname)
2984                   go,          // Name of function in C++ (must match Python name) (fn)
2985                   n_times      // Argument(s) (...)
2986               );
2987           }
2988       };
2989 \endrst */
2990 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...)                                               \
2991     PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2992 
2993 /** \rst
2994     Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`,
2995     except that it throws if no override can be found.
2996 \endrst */
2997 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...)                                          \
2998     PYBIND11_OVERRIDE_PURE_NAME(                                                                  \
2999         PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
3000 
3001 // Deprecated versions
3002 
3003 PYBIND11_DEPRECATED("get_type_overload has been deprecated")
3004 inline function
3005 get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
3006     return detail::get_type_override(this_ptr, this_type, name);
3007 }
3008 
3009 template <class T>
3010 inline function get_overload(const T *this_ptr, const char *name) {
3011     return get_override(this_ptr, name);
3012 }
3013 
3014 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...)                                         \
3015     PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
3016 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...)                                    \
3017     PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
3018 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...)                               \
3019     PYBIND11_OVERRIDE_PURE_NAME(                                                                  \
3020         PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
3021 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...)                                               \
3022     PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
3023 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...)                                          \
3024     PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
3025 
3026 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)