Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-09-15 09:06:34

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