Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-10-30 09:31:00

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/dynamic_raw_ptr_cast_if_possible.h"
0014 #include "detail/exception_translation.h"
0015 #include "detail/function_record_pyobject.h"
0016 #include "detail/init.h"
0017 #include "detail/native_enum_data.h"
0018 #include "detail/using_smart_holder.h"
0019 #include "attr.h"
0020 #include "gil.h"
0021 #include "gil_safe_call_once.h"
0022 #include "options.h"
0023 #include "trampoline_self_life_support.h"
0024 #include "typing.h"
0025 
0026 #include <cassert>
0027 #include <cstdlib>
0028 #include <cstring>
0029 #include <memory>
0030 #include <new>
0031 #include <stack>
0032 #include <string>
0033 #include <utility>
0034 #include <vector>
0035 
0036 // See PR #5448. This warning suppression is needed for the PYBIND11_OVERRIDE macro family.
0037 // NOTE that this is NOT embedded in a push/pop pair because that is very difficult to achieve.
0038 #if defined(__clang_major__) && __clang_major__ < 14
0039 PYBIND11_WARNING_DISABLE_CLANG("-Wgnu-zero-variadic-macro-arguments")
0040 #endif
0041 
0042 #if defined(__GNUG__) && !defined(__clang__)
0043 #    include <cxxabi.h>
0044 #endif
0045 
0046 #if defined(__cpp_if_constexpr) && __cpp_if_constexpr >= 201606
0047 #    define PYBIND11_MAYBE_CONSTEXPR constexpr
0048 #else
0049 #    define PYBIND11_MAYBE_CONSTEXPR
0050 #endif
0051 
0052 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0053 
0054 /* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning
0055    This warning is about ABI compatibility, not code health.
0056    It is only actually needed in a couple places, but apparently GCC 7 "generates this warning if
0057    and only if the first template instantiation ... involves noexcept" [stackoverflow], therefore
0058    it could get triggered from seemingly random places, depending on user code.
0059    No other GCC version generates this warning.
0060  */
0061 #if defined(__GNUC__) && __GNUC__ == 7
0062 PYBIND11_WARNING_DISABLE_GCC("-Wnoexcept-type")
0063 #endif
0064 
0065 PYBIND11_WARNING_DISABLE_MSVC(4127)
0066 
0067 PYBIND11_NAMESPACE_BEGIN(detail)
0068 
0069 inline std::string replace_newlines_and_squash(const char *text) {
0070     const char *whitespaces = " \t\n\r\f\v";
0071     std::string result(text);
0072     bool previous_is_whitespace = false;
0073 
0074     if (result.size() >= 2) {
0075         // Do not modify string representations
0076         char first_char = result[0];
0077         char last_char = result[result.size() - 1];
0078         if (first_char == last_char && first_char == '\'') {
0079             return result;
0080         }
0081     }
0082     result.clear();
0083 
0084     // Replace characters in whitespaces array with spaces and squash consecutive spaces
0085     while (*text != '\0') {
0086         if (std::strchr(whitespaces, *text)) {
0087             if (!previous_is_whitespace) {
0088                 result += ' ';
0089                 previous_is_whitespace = true;
0090             }
0091         } else {
0092             result += *text;
0093             previous_is_whitespace = false;
0094         }
0095         ++text;
0096     }
0097 
0098     // Strip leading and trailing whitespaces
0099     const size_t str_begin = result.find_first_not_of(whitespaces);
0100     if (str_begin == std::string::npos) {
0101         return "";
0102     }
0103 
0104     const size_t str_end = result.find_last_not_of(whitespaces);
0105     const size_t str_range = str_end - str_begin + 1;
0106 
0107     return result.substr(str_begin, str_range);
0108 }
0109 
0110 /* Generate a proper function signature */
0111 inline std::string generate_function_signature(const char *type_caster_name_field,
0112                                                detail::function_record *func_rec,
0113                                                const std::type_info *const *types,
0114                                                size_t &type_index,
0115                                                size_t &arg_index) {
0116     std::string signature;
0117     bool is_starred = false;
0118     // `is_return_value.top()` is true if we are currently inside the return type of the
0119     // signature. Using `@^`/`@$` we can force types to be arg/return types while `@!` pops
0120     // back to the previous state.
0121     std::stack<bool> is_return_value({false});
0122     // The following characters have special meaning in the signature parsing. Literals
0123     // containing these are escaped with `!`.
0124     std::string special_chars("!@%{}-");
0125     for (const auto *pc = type_caster_name_field; *pc != '\0'; ++pc) {
0126         const auto c = *pc;
0127         if (c == '{') {
0128             // Write arg name for everything except *args and **kwargs.
0129             // Detect {@*args...} or {@**kwargs...}
0130             is_starred = *(pc + 1) == '@' && *(pc + 2) == '*';
0131             if (is_starred) {
0132                 continue;
0133             }
0134             // Separator for keyword-only arguments, placed before the kw
0135             // arguments start (unless we are already putting an *args)
0136             if (!func_rec->has_args && arg_index == func_rec->nargs_pos) {
0137                 signature += "*, ";
0138             }
0139             if (arg_index < func_rec->args.size() && func_rec->args[arg_index].name) {
0140                 signature += func_rec->args[arg_index].name;
0141             } else if (arg_index == 0 && func_rec->is_method) {
0142                 signature += "self";
0143             } else {
0144                 signature += "arg" + std::to_string(arg_index - (func_rec->is_method ? 1 : 0));
0145             }
0146             signature += ": ";
0147         } else if (c == '}') {
0148             // Write default value if available.
0149             if (!is_starred && arg_index < func_rec->args.size()
0150                 && func_rec->args[arg_index].descr) {
0151                 signature += " = ";
0152                 signature += detail::replace_newlines_and_squash(func_rec->args[arg_index].descr);
0153             }
0154             // Separator for positional-only arguments (placed after the
0155             // argument, rather than before like *
0156             if (func_rec->nargs_pos_only > 0 && (arg_index + 1) == func_rec->nargs_pos_only) {
0157                 signature += ", /";
0158             }
0159             if (!is_starred) {
0160                 arg_index++;
0161             }
0162         } else if (c == '%') {
0163             const std::type_info *t = types[type_index++];
0164             if (!t) {
0165                 pybind11_fail("Internal error while parsing type signature (1)");
0166             }
0167             if (auto *tinfo = detail::get_type_info(*t)) {
0168                 handle th(reinterpret_cast<PyObject *>(tinfo->type));
0169                 signature += th.attr("__module__").cast<std::string>() + "."
0170                              + th.attr("__qualname__").cast<std::string>();
0171             } else if (auto th = detail::global_internals_native_enum_type_map_get_item(*t)) {
0172                 signature += th.attr("__module__").cast<std::string>() + "."
0173                              + th.attr("__qualname__").cast<std::string>();
0174             } else if (func_rec->is_new_style_constructor && arg_index == 0) {
0175                 // A new-style `__init__` takes `self` as `value_and_holder`.
0176                 // Rewrite it to the proper class type.
0177                 signature += func_rec->scope.attr("__module__").cast<std::string>() + "."
0178                              + func_rec->scope.attr("__qualname__").cast<std::string>();
0179             } else {
0180                 signature += detail::quote_cpp_type_name(detail::clean_type_id(t->name()));
0181             }
0182         } else if (c == '!' && special_chars.find(*(pc + 1)) != std::string::npos) {
0183             // typing::Literal escapes special characters with !
0184             signature += *++pc;
0185         } else if (c == '@') {
0186             // `@^ ... @!` and `@$ ... @!` are used to force arg/return value type (see
0187             // typing::Callable/detail::arg_descr/detail::return_descr)
0188             if (*(pc + 1) == '^') {
0189                 is_return_value.emplace(false);
0190                 ++pc;
0191                 continue;
0192             }
0193             if (*(pc + 1) == '$') {
0194                 is_return_value.emplace(true);
0195                 ++pc;
0196                 continue;
0197             }
0198             if (*(pc + 1) == '!') {
0199                 is_return_value.pop();
0200                 ++pc;
0201                 continue;
0202             }
0203             // Handle types that differ depending on whether they appear
0204             // in an argument or a return value position (see io_name<text1, text2>).
0205             // For named arguments (py::arg()) with noconvert set, return value type is used.
0206             ++pc;
0207             if (!is_return_value.top()
0208                 && (!(arg_index < func_rec->args.size() && !func_rec->args[arg_index].convert))) {
0209                 while (*pc != '\0' && *pc != '@') {
0210                     signature += *pc++;
0211                 }
0212                 if (*pc == '@') {
0213                     ++pc;
0214                 }
0215                 while (*pc != '\0' && *pc != '@') {
0216                     ++pc;
0217                 }
0218             } else {
0219                 while (*pc != '\0' && *pc != '@') {
0220                     ++pc;
0221                 }
0222                 if (*pc == '@') {
0223                     ++pc;
0224                 }
0225                 while (*pc != '\0' && *pc != '@') {
0226                     signature += *pc++;
0227                 }
0228             }
0229         } else {
0230             if (c == '-' && *(pc + 1) == '>') {
0231                 is_return_value.emplace(true);
0232             }
0233             signature += c;
0234         }
0235     }
0236     return signature;
0237 }
0238 
0239 template <typename T>
0240 inline std::string generate_type_signature() {
0241     static constexpr auto caster_name_field = make_caster<T>::name;
0242     PYBIND11_DESCR_CONSTEXPR auto descr_types = decltype(caster_name_field)::types();
0243     // Create a default function_record to ensure the function signature has the proper
0244     // configuration e.g. no_convert.
0245     auto func_rec = function_record();
0246     size_t type_index = 0;
0247     size_t arg_index = 0;
0248     return generate_function_signature(
0249         caster_name_field.text, &func_rec, descr_types.data(), type_index, arg_index);
0250 }
0251 
0252 #if defined(_MSC_VER)
0253 #    define PYBIND11_COMPAT_STRDUP _strdup
0254 #else
0255 #    define PYBIND11_COMPAT_STRDUP strdup
0256 #endif
0257 
0258 #define PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR                                                 \
0259     detail::const_name("(") + cast_in::arg_names + detail::const_name(") -> ") + cast_out::name
0260 
0261 // We factor out readable function signatures to a specific template
0262 // so that they don't get duplicated across different instantiations of
0263 // cpp_function::initialize (which is templated on more types).
0264 template <typename cast_in, typename cast_out>
0265 class ReadableFunctionSignature {
0266 public:
0267     using sig_type = decltype(PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR);
0268 
0269 private:
0270     // We have to repeat PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR in decltype()
0271     // because C++11 doesn't allow functions to return `auto`. (We don't
0272     // know the type because it's some variant of detail::descr<N> with
0273     // unknown N.)
0274     static constexpr sig_type sig() { return PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR; }
0275 
0276 public:
0277     static constexpr sig_type kSig = sig();
0278     // We can only stash the result of detail::descr::types() in a
0279     // constexpr variable if we aren't on MSVC (see
0280     // PYBIND11_DESCR_CONSTEXPR).
0281 #if !defined(_MSC_VER)
0282     using types_type = decltype(sig_type::types());
0283     static constexpr types_type kTypes = sig_type::types();
0284 #endif
0285 };
0286 #undef PYBIND11_READABLE_FUNCTION_SIGNATURE_EXPR
0287 
0288 // Prior to C++17, we don't have inline variables, so we have to
0289 // provide an out-of-line definition of the class member.
0290 #if !defined(PYBIND11_CPP17)
0291 template <typename cast_in, typename cast_out>
0292 constexpr typename ReadableFunctionSignature<cast_in, cast_out>::sig_type
0293     ReadableFunctionSignature<cast_in, cast_out>::kSig;
0294 #    if !defined(_MSC_VER)
0295 template <typename cast_in, typename cast_out>
0296 constexpr typename ReadableFunctionSignature<cast_in, cast_out>::types_type
0297     ReadableFunctionSignature<cast_in, cast_out>::kTypes;
0298 #    endif
0299 #endif
0300 
0301 PYBIND11_NAMESPACE_END(detail)
0302 
0303 /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
0304 class cpp_function : public function {
0305 public:
0306     cpp_function() = default;
0307     // NOLINTNEXTLINE(google-explicit-constructor)
0308     cpp_function(std::nullptr_t) {}
0309     cpp_function(std::nullptr_t, const is_setter &) {}
0310 
0311     /// Construct a cpp_function from a vanilla function pointer
0312     template <typename Return, typename... Args, typename... Extra>
0313     // NOLINTNEXTLINE(google-explicit-constructor)
0314     cpp_function(Return (*f)(Args...), const Extra &...extra) {
0315         initialize(f, f, extra...);
0316     }
0317 
0318     /// Construct a cpp_function from a lambda function (possibly with internal state)
0319     template <typename Func,
0320               typename... Extra,
0321               typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
0322     // NOLINTNEXTLINE(google-explicit-constructor)
0323     cpp_function(Func &&f, const Extra &...extra) {
0324         initialize(
0325             std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...);
0326     }
0327 
0328     /// Construct a cpp_function from a class method (non-const, no ref-qualifier)
0329     template <typename Return, typename Class, typename... Arg, typename... Extra>
0330     // NOLINTNEXTLINE(google-explicit-constructor)
0331     cpp_function(Return (Class::*f)(Arg...), const Extra &...extra) {
0332         initialize(
0333             [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0334             (Return (*)(Class *, Arg...)) nullptr,
0335             extra...);
0336     }
0337 
0338     /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier)
0339     /// A copy of the overload for non-const functions without explicit ref-qualifier
0340     /// but with an added `&`.
0341     template <typename Return, typename Class, typename... Arg, typename... Extra>
0342     // NOLINTNEXTLINE(google-explicit-constructor)
0343     cpp_function(Return (Class::*f)(Arg...) &, const Extra &...extra) {
0344         initialize(
0345             [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0346             (Return (*)(Class *, Arg...)) nullptr,
0347             extra...);
0348     }
0349 
0350     /// Construct a cpp_function from a class method (const, no ref-qualifier)
0351     template <typename Return, typename Class, typename... Arg, typename... Extra>
0352     // NOLINTNEXTLINE(google-explicit-constructor)
0353     cpp_function(Return (Class::*f)(Arg...) const, const Extra &...extra) {
0354         initialize([f](const Class *c,
0355                        Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0356                    (Return (*)(const Class *, Arg...)) nullptr,
0357                    extra...);
0358     }
0359 
0360     /// Construct a cpp_function from a class method (const, lvalue ref-qualifier)
0361     /// A copy of the overload for const functions without explicit ref-qualifier
0362     /// but with an added `&`.
0363     template <typename Return, typename Class, typename... Arg, typename... Extra>
0364     // NOLINTNEXTLINE(google-explicit-constructor)
0365     cpp_function(Return (Class::*f)(Arg...) const &, const Extra &...extra) {
0366         initialize([f](const Class *c,
0367                        Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0368                    (Return (*)(const Class *, Arg...)) nullptr,
0369                    extra...);
0370     }
0371 
0372     /// Construct a cpp_function from a class method (non-const, rvalue ref-qualifier)
0373     template <typename Return, typename Class, typename... Arg, typename... Extra>
0374     // NOLINTNEXTLINE(google-explicit-constructor)
0375     cpp_function(Return (Class::*f)(Arg...) &&, const Extra &...extra) {
0376         initialize(
0377             [f](Class *c, Arg... args) -> Return {
0378                 return (std::move(*c).*f)(std::forward<Arg>(args)...);
0379             },
0380             (Return (*)(Class *, Arg...)) nullptr,
0381             extra...);
0382     }
0383 
0384     /// Construct a cpp_function from a class method (const, rvalue ref-qualifier)
0385     template <typename Return, typename Class, typename... Arg, typename... Extra>
0386     // NOLINTNEXTLINE(google-explicit-constructor)
0387     cpp_function(Return (Class::*f)(Arg...) const &&, const Extra &...extra) {
0388         initialize(
0389             [f](const Class *c, Arg... args) -> Return {
0390                 return (std::move(*c).*f)(std::forward<Arg>(args)...);
0391             },
0392             (Return (*)(const Class *, Arg...)) nullptr,
0393             extra...);
0394     }
0395 
0396 #ifdef __cpp_noexcept_function_type
0397     /// Construct a cpp_function from a class method (non-const, no ref-qualifier, noexcept)
0398     template <typename Return, typename Class, typename... Arg, typename... Extra>
0399     // NOLINTNEXTLINE(google-explicit-constructor)
0400     cpp_function(Return (Class::*f)(Arg...) noexcept, const Extra &...extra) {
0401         initialize(
0402             [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0403             (Return (*)(Class *, Arg...)) nullptr,
0404             extra...);
0405     }
0406 
0407     /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier, noexcept)
0408     template <typename Return, typename Class, typename... Arg, typename... Extra>
0409     // NOLINTNEXTLINE(google-explicit-constructor)
0410     cpp_function(Return (Class::*f)(Arg...) & noexcept, const Extra &...extra) {
0411         initialize(
0412             [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0413             (Return (*)(Class *, Arg...)) nullptr,
0414             extra...);
0415     }
0416 
0417     /// Construct a cpp_function from a class method (const, no ref-qualifier, noexcept)
0418     template <typename Return, typename Class, typename... Arg, typename... Extra>
0419     // NOLINTNEXTLINE(google-explicit-constructor)
0420     cpp_function(Return (Class::*f)(Arg...) const noexcept, const Extra &...extra) {
0421         initialize([f](const Class *c,
0422                        Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0423                    (Return (*)(const Class *, Arg...)) nullptr,
0424                    extra...);
0425     }
0426 
0427     /// Construct a cpp_function from a class method (const, lvalue ref-qualifier, noexcept)
0428     template <typename Return, typename Class, typename... Arg, typename... Extra>
0429     // NOLINTNEXTLINE(google-explicit-constructor)
0430     cpp_function(Return (Class::*f)(Arg...) const & noexcept, const Extra &...extra) {
0431         initialize([f](const Class *c,
0432                        Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0433                    (Return (*)(const Class *, Arg...)) nullptr,
0434                    extra...);
0435     }
0436 
0437     /// Construct a cpp_function from a class method (non-const, rvalue ref-qualifier, noexcept)
0438     template <typename Return, typename Class, typename... Arg, typename... Extra>
0439     // NOLINTNEXTLINE(google-explicit-constructor)
0440     cpp_function(Return (Class::*f)(Arg...) && noexcept, const Extra &...extra) {
0441         initialize(
0442             [f](Class *c, Arg... args) -> Return {
0443                 return (std::move(*c).*f)(std::forward<Arg>(args)...);
0444             },
0445             (Return (*)(Class *, Arg...)) nullptr,
0446             extra...);
0447     }
0448 
0449     /// Construct a cpp_function from a class method (const, rvalue ref-qualifier, noexcept)
0450     template <typename Return, typename Class, typename... Arg, typename... Extra>
0451     // NOLINTNEXTLINE(google-explicit-constructor)
0452     cpp_function(Return (Class::*f)(Arg...) const && noexcept, const Extra &...extra) {
0453         initialize(
0454             [f](const Class *c, Arg... args) -> Return {
0455                 return (std::move(*c).*f)(std::forward<Arg>(args)...);
0456             },
0457             (Return (*)(const Class *, Arg...)) nullptr,
0458             extra...);
0459     }
0460 #endif
0461 
0462     /// Return the function name
0463     object name() const { return attr("__name__"); }
0464 
0465 protected:
0466     struct InitializingFunctionRecordDeleter {
0467         // `destruct(function_record, false)`: `initialize_generic` copies strings and
0468         // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`.
0469         void operator()(detail::function_record *rec) { destruct(rec, false); }
0470     };
0471     using unique_function_record
0472         = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
0473 
0474     /// Space optimization: don't inline this frequently instantiated fragment
0475     PYBIND11_NOINLINE unique_function_record make_function_record() {
0476         return unique_function_record(new detail::function_record());
0477     }
0478 
0479     /// Special internal constructor for functors, lambda functions, etc.
0480     template <typename Func, typename Return, typename... Args, typename... Extra>
0481     void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) {
0482         using namespace detail;
0483         struct capture {
0484             remove_reference_t<Func> f;
0485 
0486             static capture *from_data(void **data) {
0487                 return PYBIND11_STD_LAUNDER(reinterpret_cast<capture *>(data));
0488             }
0489         };
0490 
0491         /* Store the function including any extra state it might have (e.g. a lambda capture
0492          * object) */
0493         // The unique_ptr makes sure nothing is leaked in case of an exception.
0494         auto unique_rec = make_function_record();
0495         auto *rec = unique_rec.get();
0496 
0497         /* Store the capture object directly in the function record if there is enough space */
0498         if (sizeof(capture) <= sizeof(rec->data)) {
0499             /* Without these pragmas, GCC warns that there might not be
0500                enough space to use the placement new operator. However, the
0501                'if' statement above ensures that this is the case. */
0502             PYBIND11_WARNING_PUSH
0503 
0504 #if defined(__GNUG__) && __GNUC__ >= 6
0505             PYBIND11_WARNING_DISABLE_GCC("-Wplacement-new")
0506 #endif
0507 
0508             new (capture::from_data(rec->data)) capture{std::forward<Func>(f)};
0509 
0510 #if !PYBIND11_HAS_STD_LAUNDER
0511             PYBIND11_WARNING_DISABLE_GCC("-Wstrict-aliasing")
0512 #endif
0513 
0514             // UB without std::launder, but without breaking ABI and/or
0515             // a significant refactoring it's "impossible" to solve.
0516             if (!std::is_trivially_destructible<capture>::value) {
0517                 rec->free_data = [](function_record *r) {
0518                     auto data = capture::from_data(r->data);
0519                     (void) data; // suppress "unused variable" warnings
0520                     data->~capture();
0521                 };
0522             }
0523             PYBIND11_WARNING_POP
0524         } else {
0525             rec->data[0] = new capture{std::forward<Func>(f)};
0526             rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
0527         }
0528 
0529         /* Type casters for the function arguments and return value */
0530         using cast_in = argument_loader<Args...>;
0531         using cast_out
0532             = make_caster<conditional_t<std::is_void<Return>::value, void_type, Return>>;
0533 
0534         static_assert(
0535             expected_num_args<Extra...>(
0536                 sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
0537             "The number of argument annotations does not match the number of function arguments");
0538 
0539         /* Dispatch code which converts function arguments and performs the actual function call */
0540         rec->impl = [](function_call &call) -> handle {
0541             cast_in args_converter;
0542 
0543             /* Try to cast the function arguments into the C++ domain */
0544             if (!args_converter.load_args(call)) {
0545                 return PYBIND11_TRY_NEXT_OVERLOAD;
0546             }
0547 
0548             /* Invoke call policy pre-call hook */
0549             process_attributes<Extra...>::precall(call);
0550 
0551             /* Get a pointer to the capture object */
0552             const auto *data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data
0553                                                                           : call.func.data[0]);
0554             auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
0555 
0556             /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
0557             return_value_policy policy
0558                 = return_value_policy_override<Return>::policy(call.func.policy);
0559 
0560             /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
0561             using Guard = extract_guard_t<Extra...>;
0562 
0563             /* Perform the function call */
0564             handle result;
0565             if (call.func.is_setter) {
0566                 (void) std::move(args_converter).template call<Return, Guard>(cap->f);
0567                 result = none().release();
0568             } else {
0569                 result = cast_out::cast(
0570                     std::move(args_converter).template call<Return, Guard>(cap->f),
0571                     policy,
0572                     call.parent);
0573             }
0574 
0575             /* Invoke call policy post-call hook */
0576             process_attributes<Extra...>::postcall(call, result);
0577 
0578             return result;
0579         };
0580 
0581         rec->nargs_pos = cast_in::args_pos >= 0
0582                              ? static_cast<std::uint16_t>(cast_in::args_pos)
0583                              : sizeof...(Args) - cast_in::has_kwargs; // Will get reduced more if
0584                                                                       // we have a kw_only
0585         rec->has_args = cast_in::args_pos >= 0;
0586         rec->has_kwargs = cast_in::has_kwargs;
0587 
0588         /* Process any user-provided function attributes */
0589         process_attributes<Extra...>::init(extra..., rec);
0590 
0591         {
0592             constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
0593                            has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
0594                            has_arg_annotations = any_of<is_keyword<Extra>...>::value;
0595             constexpr bool has_is_method = any_of<std::is_same<is_method, Extra>...>::value;
0596             // The implicit `self` argument is not present and not counted in method definitions.
0597             constexpr bool has_args = cast_in::args_pos >= 0;
0598             constexpr bool is_method_with_self_arg_only = has_is_method && !has_args;
0599             static_assert(has_arg_annotations || !has_kw_only_args,
0600                           "py::kw_only requires the use of argument annotations");
0601             static_assert(((/* Need `py::arg("arg_name")` annotation in function/method. */
0602                             has_arg_annotations)
0603                            || (/* Allow methods with no arguments `def method(self, /): ...`.
0604                                 * A method has at least one argument `self`. There can be no
0605                                 * `py::arg` annotation. E.g. `class.def("method", py::pos_only())`.
0606                                 */
0607                                is_method_with_self_arg_only))
0608                               || !has_pos_only_args,
0609                           "py::pos_only requires the use of argument annotations (for docstrings "
0610                           "and aligning the annotations to the argument)");
0611 
0612             static_assert(constexpr_sum(is_kw_only<Extra>::value...) <= 1,
0613                           "py::kw_only may be specified only once");
0614             static_assert(constexpr_sum(is_pos_only<Extra>::value...) <= 1,
0615                           "py::pos_only may be specified only once");
0616             constexpr auto kw_only_pos = constexpr_first<is_kw_only, Extra...>();
0617             constexpr auto pos_only_pos = constexpr_first<is_pos_only, Extra...>();
0618             static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
0619                           "py::pos_only must come before py::kw_only");
0620         }
0621 
0622         /* Generate a readable signature describing the function's arguments and return
0623            value types */
0624         static constexpr const auto &signature
0625             = detail::ReadableFunctionSignature<cast_in, cast_out>::kSig;
0626 #if !defined(_MSC_VER)
0627         static constexpr const auto &types
0628             = detail::ReadableFunctionSignature<cast_in, cast_out>::kTypes;
0629 #else
0630         PYBIND11_DESCR_CONSTEXPR auto types = std::decay<decltype(signature)>::type::types();
0631 #endif
0632 
0633         /* Register the function with Python from generic (non-templated) code */
0634         // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid.
0635         initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));
0636 
0637         /* Stash some additional information used by an important optimization in 'functional.h' */
0638         using FunctionType = Return (*)(Args...);
0639         constexpr bool is_function_ptr
0640             = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *);
0641         PYBIND11_ENSURE_PRECONDITION_FOR_FUNCTIONAL_H_PERFORMANCE_OPTIMIZATIONS(
0642             !is_function_ptr || std::is_standard_layout<capture>::value);
0643         if (is_function_ptr) {
0644             rec->is_stateless = true;
0645             rec->data[1]
0646                 = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
0647         }
0648     }
0649 
0650     // Utility class that keeps track of all duplicated strings, and cleans them up in its
0651     // destructor, unless they are released. Basically a RAII-solution to deal with exceptions
0652     // along the way.
0653     class strdup_guard {
0654     public:
0655         strdup_guard() = default;
0656         strdup_guard(const strdup_guard &) = delete;
0657         strdup_guard &operator=(const strdup_guard &) = delete;
0658 
0659         ~strdup_guard() {
0660             for (auto *s : strings) {
0661                 std::free(s);
0662             }
0663         }
0664         char *operator()(const char *s) {
0665             auto *t = PYBIND11_COMPAT_STRDUP(s);
0666             strings.push_back(t);
0667             return t;
0668         }
0669         void release() { strings.clear(); }
0670 
0671     private:
0672         std::vector<char *> strings;
0673     };
0674 
0675     /// Register a function call with Python (generic non-templated code goes here)
0676     void initialize_generic(unique_function_record &&unique_rec,
0677                             const char *text,
0678                             const std::type_info *const *types,
0679                             size_t args) {
0680         // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr,
0681         // we do not want this to destruct the pointer. `initialize` (the caller) still relies on
0682         // the pointee being alive after this call. Only move out if a `capsule` is going to keep
0683         // it alive.
0684         auto *rec = unique_rec.get();
0685 
0686         // Keep track of strdup'ed strings, and clean them up as long as the function's capsule
0687         // has not taken ownership yet (when `unique_rec.release()` is called).
0688         // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the
0689         // strings are only referenced before strdup'ing. So only *after* the following block could
0690         // `destruct` safely be called, but even then, `repr` could still throw in the middle of
0691         // copying all strings.
0692         strdup_guard guarded_strdup;
0693 
0694         /* Create copies of all referenced C-style strings */
0695         rec->name = guarded_strdup(rec->name ? rec->name : "");
0696         if (rec->doc) {
0697             rec->doc = guarded_strdup(rec->doc);
0698         }
0699         for (auto &a : rec->args) {
0700             if (a.name) {
0701                 a.name = guarded_strdup(a.name);
0702             }
0703             if (a.descr) {
0704                 a.descr = guarded_strdup(a.descr);
0705             } else if (a.value) {
0706                 a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());
0707             }
0708         }
0709 
0710         rec->is_constructor = (std::strcmp(rec->name, "__init__") == 0)
0711                               || (std::strcmp(rec->name, "__setstate__") == 0);
0712 
0713 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
0714         if (rec->is_constructor && !rec->is_new_style_constructor) {
0715             const auto class_name
0716                 = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
0717             const auto func_name = std::string(rec->name);
0718             PyErr_WarnEx(PyExc_FutureWarning,
0719                          ("pybind11-bound class '" + class_name
0720                           + "' is using an old-style "
0721                             "placement-new '"
0722                           + func_name
0723                           + "' which has been deprecated. See "
0724                             "the upgrade guide in pybind11's docs. This message is only visible "
0725                             "when compiled in debug mode.")
0726                              .c_str(),
0727                          0);
0728         }
0729 #endif
0730 
0731         size_t type_index = 0, arg_index = 0;
0732         std::string signature
0733             = detail::generate_function_signature(text, rec, types, type_index, arg_index);
0734 
0735         if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] != nullptr) {
0736             pybind11_fail("Internal error while parsing type signature (2)");
0737         }
0738 
0739         rec->signature = guarded_strdup(signature.c_str());
0740         rec->args.shrink_to_fit();
0741         rec->nargs = static_cast<std::uint16_t>(args);
0742 
0743         if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) {
0744             rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
0745         }
0746 
0747         detail::function_record *chain = nullptr, *chain_start = rec;
0748         if (rec->sibling) {
0749             if (PyCFunction_Check(rec->sibling.ptr())) {
0750                 auto *self = PyCFunction_GET_SELF(rec->sibling.ptr());
0751                 if (self == nullptr) {
0752                     pybind11_fail(
0753                         "initialize_generic: Unexpected nullptr from PyCFunction_GET_SELF");
0754                 }
0755                 chain = detail::function_record_ptr_from_PyObject(self);
0756                 if (chain && !chain->scope.is(rec->scope)) {
0757                     /* Never append a method to an overload chain of a parent class;
0758                        instead, hide the parent's overloads in this case */
0759                     chain = nullptr;
0760                 }
0761             }
0762             // Don't trigger for things like the default __init__, which are wrapper_descriptors
0763             // that we are intentionally replacing
0764             else if (!rec->sibling.is_none() && rec->name[0] != '_') {
0765                 pybind11_fail("Cannot overload existing non-function object \""
0766                               + std::string(rec->name) + "\" with a function of the same name");
0767             }
0768         }
0769 
0770         if (!chain) {
0771             /* No existing overload was found, create a new function object */
0772             rec->def = new PyMethodDef();
0773             std::memset(rec->def, 0, sizeof(PyMethodDef));
0774             rec->def->ml_name = rec->name;
0775             rec->def->ml_meth
0776                 = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher));
0777             rec->def->ml_flags = METH_FASTCALL | METH_KEYWORDS;
0778 
0779             object py_func_rec = detail::function_record_PyObject_New();
0780             (reinterpret_cast<detail::function_record_PyObject *>(py_func_rec.ptr()))->cpp_func_rec
0781                 = unique_rec.release();
0782             guarded_strdup.release();
0783 
0784             object scope_module = detail::get_scope_module(rec->scope);
0785             m_ptr = PyCFunction_NewEx(rec->def, py_func_rec.ptr(), scope_module.ptr());
0786             if (!m_ptr) {
0787                 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
0788             }
0789         } else {
0790             /* Append at the beginning or end of the overload chain */
0791             m_ptr = rec->sibling.ptr();
0792             inc_ref();
0793             if (chain->is_method != rec->is_method) {
0794                 pybind11_fail(
0795                     "overloading a method with both static and instance methods is not supported; "
0796 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
0797                     "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more "
0798                     "details"
0799 #else
0800                     "error while attempting to bind "
0801                     + std::string(rec->is_method ? "instance" : "static") + " method "
0802                     + std::string(pybind11::str(rec->scope.attr("__name__"))) + "."
0803                     + std::string(rec->name) + signature
0804 #endif
0805                 );
0806             }
0807 
0808             if (rec->prepend) {
0809                 // Beginning of chain; we need to replace the capsule's current head-of-the-chain
0810                 // pointer with this one, then make this one point to the previous head of the
0811                 // chain.
0812                 chain_start = rec;
0813                 rec->next = chain;
0814                 auto *py_func_rec = reinterpret_cast<detail::function_record_PyObject *>(
0815                     PyCFunction_GET_SELF(m_ptr));
0816                 py_func_rec->cpp_func_rec = unique_rec.release();
0817                 guarded_strdup.release();
0818             } else {
0819                 // Or end of chain (normal behavior)
0820                 chain_start = chain;
0821                 while (chain->next) {
0822                     chain = chain->next;
0823                 }
0824                 chain->next = unique_rec.release();
0825                 guarded_strdup.release();
0826             }
0827         }
0828 
0829         std::string signatures;
0830         int index = 0;
0831         /* Create a nice pydoc rec including all signatures and
0832            docstrings of the functions in the overload chain */
0833         if (chain && options::show_function_signatures()
0834             && std::strcmp(rec->name, "_pybind11_conduit_v1_") != 0) {
0835             // First a generic signature
0836             signatures += rec->name;
0837             signatures += "(*args, **kwargs)\n";
0838             signatures += "Overloaded function.\n\n";
0839         }
0840         // Then specific overload signatures
0841         bool first_user_def = true;
0842         for (auto *it = chain_start; it != nullptr; it = it->next) {
0843             if (options::show_function_signatures()
0844                 && std::strcmp(rec->name, "_pybind11_conduit_v1_") != 0) {
0845                 if (index > 0) {
0846                     signatures += '\n';
0847                 }
0848                 if (chain) {
0849                     signatures += std::to_string(++index) + ". ";
0850                 }
0851                 signatures += rec->name;
0852                 signatures += it->signature;
0853                 signatures += '\n';
0854             }
0855             if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) {
0856                 // If we're appending another docstring, and aren't printing function signatures,
0857                 // we need to append a newline first:
0858                 if (!options::show_function_signatures()) {
0859                     if (first_user_def) {
0860                         first_user_def = false;
0861                     } else {
0862                         signatures += '\n';
0863                     }
0864                 }
0865                 if (options::show_function_signatures()) {
0866                     signatures += '\n';
0867                 }
0868                 signatures += it->doc;
0869                 if (options::show_function_signatures()) {
0870                     signatures += '\n';
0871                 }
0872             }
0873         }
0874 
0875         auto *func = reinterpret_cast<PyCFunctionObject *>(m_ptr);
0876         // Install docstring if it's non-empty (when at least one option is enabled)
0877         auto *doc = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());
0878         std::free(const_cast<char *>(PYBIND11_PYCFUNCTION_GET_DOC(func)));
0879         PYBIND11_PYCFUNCTION_SET_DOC(func, doc);
0880 
0881         if (rec->is_method) {
0882             m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
0883             if (!m_ptr) {
0884                 pybind11_fail(
0885                     "cpp_function::cpp_function(): Could not allocate instance method object");
0886             }
0887             Py_DECREF(func);
0888         }
0889     }
0890 
0891     friend void detail::function_record_PyTypeObject_methods::tp_dealloc_impl(PyObject *);
0892 
0893     /// When a cpp_function is GCed, release any memory allocated by pybind11
0894     static void destruct(detail::function_record *rec, bool free_strings = true) {
0895 // If on Python 3.9, check the interpreter "MICRO" (patch) version.
0896 // If this is running on 3.9.0, we have to work around a bug.
0897 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
0898         static bool is_zero = Py_GetVersion()[4] == '0';
0899 #endif
0900 
0901         while (rec) {
0902             detail::function_record *next = rec->next;
0903             if (rec->free_data) {
0904                 rec->free_data(rec);
0905             }
0906             // During initialization, these strings might not have been copied yet,
0907             // so they cannot be freed. Once the function has been created, they can.
0908             // Check `make_function_record` for more details.
0909             if (free_strings) {
0910                 std::free(rec->name);
0911                 std::free(rec->doc);
0912                 std::free(rec->signature);
0913                 for (auto &arg : rec->args) {
0914                     std::free(const_cast<char *>(arg.name));
0915                     std::free(const_cast<char *>(arg.descr));
0916                 }
0917             }
0918             for (auto &arg : rec->args) {
0919                 arg.value.dec_ref();
0920             }
0921             if (rec->def) {
0922                 std::free(const_cast<char *>(rec->def->ml_doc));
0923 // Python 3.9.0 decref's these in the wrong order; rec->def
0924 // If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)
0925 // See https://github.com/python/cpython/pull/22670
0926 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
0927                 if (!is_zero) {
0928                     delete rec->def;
0929                 }
0930 #else
0931                 delete rec->def;
0932 #endif
0933             }
0934             delete rec;
0935             rec = next;
0936         }
0937     }
0938 
0939     /// Main dispatch logic for calls to functions bound using pybind11
0940     static PyObject *
0941     dispatcher(PyObject *self, PyObject *const *args_in_arr, size_t nargsf, PyObject *kwnames_in) {
0942         using namespace detail;
0943         const function_record *overloads = function_record_ptr_from_PyObject(self);
0944         assert(overloads != nullptr);
0945 
0946         /* Iterator over the list of potentially admissible overloads */
0947         const function_record *current_overload = overloads;
0948 
0949         /* Need to know how many arguments + keyword arguments there are to pick the right
0950            overload */
0951         const auto n_args_in = static_cast<size_t>(PyVectorcall_NARGS(nargsf));
0952 
0953         handle parent = n_args_in > 0 ? args_in_arr[0] : nullptr,
0954                result = PYBIND11_TRY_NEXT_OVERLOAD;
0955 
0956         auto self_value_and_holder = value_and_holder();
0957         if (overloads->is_constructor) {
0958             if (!parent
0959                 || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
0960                 set_error(PyExc_TypeError,
0961                           "__init__(self, ...) called with invalid or missing `self` argument");
0962                 return nullptr;
0963             }
0964 
0965             auto *const tinfo
0966                 = get_type_info(reinterpret_cast<PyTypeObject *>(overloads->scope.ptr()));
0967             auto *const pi = reinterpret_cast<instance *>(parent.ptr());
0968             self_value_and_holder = pi->get_value_and_holder(tinfo, true);
0969 
0970             // If this value is already registered it must mean __init__ is invoked multiple times;
0971             // we really can't support that in C++, so just ignore the second __init__.
0972             if (self_value_and_holder.instance_registered()) {
0973                 return none().release().ptr();
0974             }
0975         }
0976 
0977         try {
0978             // We do this in two passes: in the first pass, we load arguments with `convert=false`;
0979             // in the second, we allow conversion (except for arguments with an explicit
0980             // py::arg().noconvert()).  This lets us prefer calls without conversion, with
0981             // conversion as a fallback.
0982             std::vector<function_call> second_pass;
0983 
0984             // However, if there are no overloads, we can just skip the no-convert pass entirely
0985             const bool overloaded
0986                 = current_overload != nullptr && current_overload->next != nullptr;
0987 
0988             for (; current_overload != nullptr; current_overload = current_overload->next) {
0989 
0990                 /* For each overload:
0991                    1. Copy all positional arguments we were given, also checking to make sure that
0992                       named positional arguments weren't *also* specified via kwarg.
0993                    2. If we weren't given enough, try to make up the omitted ones by checking
0994                       whether they were provided by a kwarg matching the `py::arg("name")` name. If
0995                       so, use it (and remove it from kwargs); if not, see if the function binding
0996                       provided a default that we can use.
0997                    3. Ensure that either all keyword arguments were "consumed", or that the
0998                    function takes a kwargs argument to accept unconsumed kwargs.
0999                    4. Any positional arguments still left get put into a tuple (for args), and any
1000                       leftover kwargs get put into a dict.
1001                    5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
1002                       extra tuple or dict at the end of the positional arguments.
1003                    6. Call the function call dispatcher (function_record::impl)
1004 
1005                    If one of these fail, move on to the next overload and keep trying until we get
1006                    a result other than PYBIND11_TRY_NEXT_OVERLOAD.
1007                  */
1008 
1009                 const function_record &func = *current_overload;
1010                 size_t num_args = func.nargs; // Number of positional arguments that we need
1011                 if (func.has_args) {
1012                     --num_args; // (but don't count py::args
1013                 }
1014                 if (func.has_kwargs) {
1015                     --num_args; //  or py::kwargs)
1016                 }
1017                 size_t pos_args = func.nargs_pos;
1018 
1019                 if (!func.has_args && n_args_in > pos_args) {
1020                     continue; // Too many positional arguments for this overload
1021                 }
1022 
1023                 if (n_args_in < pos_args && func.args.size() < pos_args) {
1024                     continue; // Not enough positional arguments given, and not enough defaults to
1025                               // fill in the blanks
1026                 }
1027 
1028                 function_call call(func, parent);
1029 
1030                 // Protect std::min with parentheses
1031                 size_t args_to_copy = (std::min) (pos_args, n_args_in);
1032                 size_t args_copied = 0;
1033 
1034                 // 0. Inject new-style `self` argument
1035                 if (func.is_new_style_constructor) {
1036                     // The `value` may have been preallocated by an old-style `__init__`
1037                     // if it was a preceding candidate for overload resolution.
1038                     if (self_value_and_holder) {
1039                         self_value_and_holder.type->dealloc(self_value_and_holder);
1040                     }
1041 
1042                     call.init_self = args_in_arr[0];
1043                     call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
1044                     call.args_convert.push_back(false);
1045                     ++args_copied;
1046                 }
1047 
1048                 // 1. Copy any position arguments given.
1049                 bool bad_arg = false;
1050                 for (; args_copied < args_to_copy; ++args_copied) {
1051                     const argument_record *arg_rec
1052                         = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
1053 
1054                     /* if the argument is listed in the call site's kwargs, but the argument is
1055                     also fulfilled positionally, then the call can't match this overload. for
1056                     example, the call site is: foo(0, key=1) but our overload is foo(key:int) then
1057                     this call can't be for us, because it would be invalid.
1058                     */
1059                     if (kwnames_in && arg_rec && arg_rec->name
1060                         && keyword_index(kwnames_in, arg_rec->name) >= 0) {
1061                         bad_arg = true;
1062                         break;
1063                     }
1064 
1065                     handle arg(args_in_arr[args_copied]);
1066                     if (arg_rec && !arg_rec->none && arg.is_none()) {
1067                         bad_arg = true;
1068                         break;
1069                     }
1070 
1071                     call.args.push_back(arg);
1072                     call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
1073                 }
1074                 if (bad_arg) {
1075                     continue; // Maybe it was meant for another overload (issue #688)
1076                 }
1077 
1078                 // Keep track of how many position args we copied out in case we need to come back
1079                 // to copy the rest into a py::args argument.
1080                 size_t positional_args_copied = args_copied;
1081 
1082                 // 1.5. Fill in any missing pos_only args from defaults if they exist
1083                 if (args_copied < func.nargs_pos_only) {
1084                     for (; args_copied < func.nargs_pos_only; ++args_copied) {
1085                         const auto &arg_rec = func.args[args_copied];
1086                         if (arg_rec.value) {
1087                             call.args.push_back(arg_rec.value);
1088                             call.args_convert.push_back(arg_rec.convert);
1089                         } else {
1090                             break;
1091                         }
1092                     }
1093 
1094                     if (args_copied < func.nargs_pos_only) {
1095                         continue; // Not enough defaults to fill the positional arguments
1096                     }
1097                 }
1098 
1099                 // 2. Check kwargs and, failing that, defaults that may help complete the list
1100                 small_vector<bool, arg_vector_small_size> used_kwargs(
1101                     kwnames_in ? static_cast<size_t>(PyTuple_GET_SIZE(kwnames_in)) : 0, false);
1102                 size_t used_kwargs_count = 0;
1103                 if (args_copied < num_args) {
1104                     for (; args_copied < num_args; ++args_copied) {
1105                         const auto &arg_rec = func.args[args_copied];
1106 
1107                         handle value;
1108                         if (kwnames_in && arg_rec.name) {
1109                             ssize_t i = keyword_index(kwnames_in, arg_rec.name);
1110                             if (i >= 0) {
1111                                 value = args_in_arr[n_args_in + static_cast<size_t>(i)];
1112                                 used_kwargs.set(static_cast<size_t>(i), true);
1113                                 used_kwargs_count++;
1114                             }
1115                         }
1116 
1117                         if (!value) {
1118                             value = arg_rec.value;
1119                             if (!value) {
1120                                 break;
1121                             }
1122                         }
1123 
1124                         if (!arg_rec.none && value.is_none()) {
1125                             break;
1126                         }
1127 
1128                         // If we're at the py::args index then first insert a stub for it to be
1129                         // replaced later
1130                         if (func.has_args && call.args.size() == func.nargs_pos) {
1131                             call.args.push_back(none());
1132                         }
1133 
1134                         call.args.push_back(value);
1135                         call.args_convert.push_back(arg_rec.convert);
1136                     }
1137 
1138                     if (args_copied < num_args) {
1139                         continue; // Not enough arguments, defaults, or kwargs to fill the
1140                                   // positional arguments
1141                     }
1142                 }
1143 
1144                 // 3. Check everything was consumed (unless we have a kwargs arg)
1145                 if (!func.has_kwargs && used_kwargs_count < used_kwargs.size()) {
1146                     continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
1147                 }
1148 
1149                 // 4a. If we have a py::args argument, create a new tuple with leftovers
1150                 if (func.has_args) {
1151                     if (positional_args_copied >= n_args_in) {
1152                         call.args_ref = tuple(0);
1153                     } else {
1154                         size_t args_size = n_args_in - positional_args_copied;
1155                         tuple extra_args(args_size);
1156                         for (size_t i = 0; i < args_size; ++i) {
1157                             extra_args[i] = args_in_arr[positional_args_copied + i];
1158                         }
1159                         call.args_ref = std::move(extra_args);
1160                     }
1161                     if (call.args.size() <= func.nargs_pos) {
1162                         call.args.push_back(call.args_ref);
1163                     } else {
1164                         call.args[func.nargs_pos] = call.args_ref;
1165                     }
1166                     call.args_convert.push_back(false);
1167                 }
1168 
1169                 // 4b. If we have a py::kwargs, pass on any remaining kwargs
1170                 if (func.has_kwargs) {
1171                     dict kwargs;
1172                     for (size_t i = 0; i < used_kwargs.size(); ++i) {
1173                         if (!used_kwargs[i]) {
1174                             // Cast values into handles before indexing into kwargs to ensure
1175                             // well-defined evaluation order (MSVC C4866).
1176                             handle arg_in_arr = args_in_arr[n_args_in + i],
1177                                    kwname = PyTuple_GET_ITEM(kwnames_in, i);
1178                             kwargs[kwname] = arg_in_arr;
1179                         }
1180                     }
1181                     call.args.push_back(kwargs);
1182                     call.args_convert.push_back(false);
1183                     call.kwargs_ref = std::move(kwargs);
1184                 }
1185 
1186                 // 5. Put everything in a vector.  Not technically step 5, we've been building it
1187                 // in `call.args` all along.
1188 
1189 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1190                 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) {
1191                     pybind11_fail("Internal error: function call dispatcher inserted wrong number "
1192                                   "of arguments!");
1193                 }
1194 #endif
1195 
1196                 args_convert_vector<arg_vector_small_size> second_pass_convert;
1197                 if (overloaded) {
1198                     // We're in the first no-convert pass, so swap out the conversion flags for a
1199                     // set of all-false flags.  If the call fails, we'll swap the flags back in for
1200                     // the conversion-allowed call below.
1201                     second_pass_convert = std::move(call.args_convert);
1202                     call.args_convert
1203                         = args_convert_vector<arg_vector_small_size>(func.nargs, false);
1204                 }
1205 
1206                 // 6. Call the function.
1207                 try {
1208                     loader_life_support guard{};
1209                     result = func.impl(call);
1210                 } catch (reference_cast_error &) {
1211                     result = PYBIND11_TRY_NEXT_OVERLOAD;
1212                 }
1213 
1214                 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
1215                     break;
1216                 }
1217 
1218                 if (overloaded) {
1219                     // The (overloaded) call failed; if the call has at least one argument that
1220                     // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
1221                     // then add this call to the list of second pass overloads to try.
1222                     for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
1223                         if (second_pass_convert[i]) {
1224                             // Found one: swap the converting flags back in and store the call for
1225                             // the second pass.
1226                             call.args_convert.swap(second_pass_convert);
1227                             second_pass.push_back(std::move(call));
1228                             break;
1229                         }
1230                     }
1231                 }
1232             }
1233 
1234             if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
1235                 // The no-conversion pass finished without success, try again with conversion
1236                 // allowed
1237                 for (auto &call : second_pass) {
1238                     try {
1239                         loader_life_support guard{};
1240                         result = call.func.impl(call);
1241                     } catch (reference_cast_error &) {
1242                         result = PYBIND11_TRY_NEXT_OVERLOAD;
1243                     }
1244 
1245                     if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
1246                         // The error reporting logic below expects 'current_overload' to be valid,
1247                         // as it would be if we'd encountered this failure in the first-pass loop.
1248                         if (!result) {
1249                             current_overload = &call.func;
1250                         }
1251                         break;
1252                     }
1253                 }
1254             }
1255         } catch (error_already_set &e) {
1256             e.restore();
1257             return nullptr;
1258 #ifdef __GLIBCXX__
1259         } catch (abi::__forced_unwind &) {
1260             throw;
1261 #endif
1262         } catch (...) {
1263             try_translate_exceptions();
1264             return nullptr;
1265         }
1266 
1267         auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
1268             if (msg.find("std::") != std::string::npos) {
1269                 msg += "\n\n"
1270                        "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1271                        "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1272                        "conversions are optional and require extra headers to be included\n"
1273                        "when compiling your pybind11 module.";
1274             }
1275         };
1276 
1277         if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
1278             if (overloads->is_operator) {
1279                 return handle(Py_NotImplemented).inc_ref().ptr();
1280             }
1281 
1282             std::string msg = std::string(overloads->name) + "(): incompatible "
1283                               + std::string(overloads->is_constructor ? "constructor" : "function")
1284                               + " arguments. The following argument types are supported:\n";
1285 
1286             int ctr = 0;
1287             for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
1288                 msg += "    " + std::to_string(++ctr) + ". ";
1289 
1290                 bool wrote_sig = false;
1291                 if (overloads->is_constructor) {
1292                     // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as
1293                     // `Object(arg0, ...)`
1294                     std::string sig = it2->signature;
1295                     size_t start = sig.find('(') + 7; // skip "(self: "
1296                     if (start < sig.size()) {
1297                         // End at the , for the next argument
1298                         size_t end = sig.find(", "), next = end + 2;
1299                         size_t ret = sig.rfind(" -> ");
1300                         // Or the ), if there is no comma:
1301                         if (end >= sig.size()) {
1302                             next = end = sig.find(')');
1303                         }
1304                         if (start < end && next < sig.size()) {
1305                             msg.append(sig, start, end - start);
1306                             msg += '(';
1307                             msg.append(sig, next, ret - next);
1308                             wrote_sig = true;
1309                         }
1310                     }
1311                 }
1312                 if (!wrote_sig) {
1313                     msg += it2->signature;
1314                 }
1315 
1316                 msg += '\n';
1317             }
1318             msg += "\nInvoked with: ";
1319             bool some_args = false;
1320             for (size_t ti = overloads->is_constructor ? 1 : 0; ti < n_args_in; ++ti) {
1321                 if (!some_args) {
1322                     some_args = true;
1323                 } else {
1324                     msg += ", ";
1325                 }
1326                 try {
1327                     msg += pybind11::repr(args_in_arr[ti]);
1328                 } catch (const error_already_set &) {
1329                     msg += "<repr raised Error>";
1330                 }
1331             }
1332             if (kwnames_in && PyTuple_GET_SIZE(kwnames_in) > 0) {
1333                 if (some_args) {
1334                     msg += "; ";
1335                 }
1336                 msg += "kwargs: ";
1337                 bool first = true;
1338                 for (size_t i = 0; i < static_cast<size_t>(PyTuple_GET_SIZE(kwnames_in)); ++i) {
1339                     if (first) {
1340                         first = false;
1341                     } else {
1342                         msg += ", ";
1343                     }
1344                     msg += reinterpret_borrow<pybind11::str>(PyTuple_GET_ITEM(kwnames_in, i));
1345                     msg += '=';
1346                     try {
1347                         msg += pybind11::repr(args_in_arr[n_args_in + i]);
1348                     } catch (const error_already_set &) {
1349                         msg += "<repr raised Error>";
1350                     }
1351                 }
1352             }
1353 
1354             append_note_if_missing_header_is_suspected(msg);
1355             // Attach additional error info to the exception if supported
1356             if (PyErr_Occurred()) {
1357                 // #HelpAppreciated: unit test coverage for this branch.
1358                 raise_from(PyExc_TypeError, msg.c_str());
1359                 return nullptr;
1360             }
1361             set_error(PyExc_TypeError, msg.c_str());
1362             return nullptr;
1363         }
1364         if (!result) {
1365             std::string msg = "Unable to convert function return value to a "
1366                               "Python type! The signature was\n\t";
1367             assert(current_overload != nullptr);
1368             msg += current_overload->signature;
1369             append_note_if_missing_header_is_suspected(msg);
1370             // Attach additional error info to the exception if supported
1371             if (PyErr_Occurred()) {
1372                 raise_from(PyExc_TypeError, msg.c_str());
1373                 return nullptr;
1374             }
1375             set_error(PyExc_TypeError, msg.c_str());
1376             return nullptr;
1377         }
1378         if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
1379             auto *pi = reinterpret_cast<instance *>(parent.ptr());
1380             self_value_and_holder.type->init_instance(pi, nullptr);
1381         }
1382         return result.ptr();
1383     }
1384 
1385     static ssize_t keyword_index(PyObject *haystack, char const *needle) {
1386         /* kwargs is usually very small (<= 5 entries).  The arg strings are typically interned.
1387          * CPython itself implements the search this way, first comparing all pointers ... which is
1388          * cheap and will work if the strings are interned.  If it fails, then it falls back to a
1389          * second lexicographic check. This is wildly expensive for huge argument lists, but those
1390          * are incredibly rare so we optimize for the vastly common case of just a couple of args.
1391          */
1392         auto n = PyTuple_GET_SIZE(haystack);
1393         auto s = reinterpret_steal<pybind11::str>(PyUnicode_InternFromString(needle));
1394         for (ssize_t i = 0; i < n; ++i) {
1395             if (PyTuple_GET_ITEM(haystack, i) == s.ptr()) {
1396                 return i;
1397             }
1398         }
1399         for (ssize_t i = 0; i < n; ++i) {
1400             if (PyUnicode_Compare(PyTuple_GET_ITEM(haystack, i), s.ptr()) == 0) {
1401                 return i;
1402             }
1403         }
1404         return -1;
1405     }
1406 };
1407 
1408 PYBIND11_NAMESPACE_BEGIN(detail)
1409 
1410 PYBIND11_NAMESPACE_BEGIN(function_record_PyTypeObject_methods)
1411 
1412 // This implementation needs the definition of `class cpp_function`.
1413 inline void tp_dealloc_impl(PyObject *self) {
1414     // Save type before PyObject_Free invalidates self.
1415     auto *type = Py_TYPE(self);
1416     auto *py_func_rec = reinterpret_cast<function_record_PyObject *>(self);
1417     cpp_function::destruct(py_func_rec->cpp_func_rec);
1418     py_func_rec->cpp_func_rec = nullptr;
1419     // PyObject_New increments the heap type refcount and allocates via
1420     // PyObject_Malloc; balance both here
1421     PyObject_Free(self);
1422     Py_DECREF(type);
1423 }
1424 
1425 PYBIND11_NAMESPACE_END(function_record_PyTypeObject_methods)
1426 
1427 template <>
1428 struct handle_type_name<cpp_function> {
1429     static constexpr auto name = const_name("collections.abc.Callable");
1430 };
1431 
1432 PYBIND11_NAMESPACE_END(detail)
1433 
1434 // Use to activate Py_MOD_GIL_NOT_USED.
1435 class mod_gil_not_used {
1436 public:
1437     explicit mod_gil_not_used(bool flag = true) : flag_(flag) {}
1438     bool flag() const { return flag_; }
1439 
1440 private:
1441     bool flag_;
1442 };
1443 
1444 class multiple_interpreters {
1445 public:
1446     enum class level {
1447         not_supported,      /// Use to activate Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED
1448         shared_gil,         /// Use to activate Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED
1449         per_interpreter_gil /// Use to activate Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
1450     };
1451 
1452     static multiple_interpreters not_supported() {
1453         return multiple_interpreters(level::not_supported);
1454     }
1455     static multiple_interpreters shared_gil() { return multiple_interpreters(level::shared_gil); }
1456     static multiple_interpreters per_interpreter_gil() {
1457         return multiple_interpreters(level::per_interpreter_gil);
1458     }
1459 
1460     explicit constexpr multiple_interpreters(level l) : level_(l) {}
1461     level value() const { return level_; }
1462 
1463 private:
1464     level level_;
1465 };
1466 
1467 PYBIND11_NAMESPACE_BEGIN(detail)
1468 
1469 inline bool gil_not_used_option() { return false; }
1470 template <typename F, typename... O>
1471 bool gil_not_used_option(F &&, O &&...o);
1472 template <typename... O>
1473 inline bool gil_not_used_option(mod_gil_not_used f, O &&...o) {
1474     return f.flag() || gil_not_used_option(o...);
1475 }
1476 template <typename F, typename... O>
1477 inline bool gil_not_used_option(F &&, O &&...o) {
1478     return gil_not_used_option(o...);
1479 }
1480 
1481 #ifdef Py_mod_multiple_interpreters
1482 inline void *multi_interp_slot() { return Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED; }
1483 template <typename... O>
1484 inline void *multi_interp_slot(multiple_interpreters mi, O &&...o) {
1485     switch (mi.value()) {
1486         case multiple_interpreters::level::per_interpreter_gil:
1487             return Py_MOD_PER_INTERPRETER_GIL_SUPPORTED;
1488         case multiple_interpreters::level::shared_gil:
1489             return Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED;
1490         case multiple_interpreters::level::not_supported:
1491             return Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED;
1492     }
1493     // silence warnings with this unreachable line:
1494     return multi_interp_slot(o...);
1495 }
1496 template <typename F, typename... O>
1497 inline void *multi_interp_slot(F &&, O &&...o) {
1498     return multi_interp_slot(o...);
1499 }
1500 #endif
1501 
1502 /*
1503 Return a borrowed reference to the named module if it has been successfully initialized within this
1504 interpreter before. nullptr if it has not been successfully initialized.
1505 */
1506 inline PyObject *get_cached_module(pybind11::str const &nameobj) {
1507     dict state = detail::get_python_state_dict();
1508     if (!state.contains("__pybind11_module_cache")) {
1509         return nullptr;
1510     }
1511     dict cache = state["__pybind11_module_cache"];
1512     if (!cache.contains(nameobj)) {
1513         return nullptr;
1514     }
1515     return cache[nameobj].ptr();
1516 }
1517 
1518 /*
1519 Add successfully initialized a module object to the internal cache.
1520 
1521 The module must have a __spec__ attribute with a name attribute.
1522 */
1523 inline void cache_completed_module(pybind11::object const &mod) {
1524     dict state = detail::get_python_state_dict();
1525     if (!state.contains("__pybind11_module_cache")) {
1526         state["__pybind11_module_cache"] = dict();
1527     }
1528     state["__pybind11_module_cache"][mod.attr("__spec__").attr("name")] = mod;
1529 }
1530 
1531 /*
1532 A Py_mod_create slot function which will return the previously created module from the cache if one
1533 exists, and otherwise will create a new module object.
1534 */
1535 inline PyObject *cached_create_module(PyObject *spec, PyModuleDef *) {
1536     (void) &cache_completed_module; // silence unused-function warnings, it is used in a macro
1537 
1538     auto nameobj = getattr(reinterpret_borrow<object>(spec), "name", none());
1539     if (nameobj.is_none()) {
1540         set_error(PyExc_ImportError, "module spec is missing a name");
1541         return nullptr;
1542     }
1543 
1544     auto *mod = get_cached_module(nameobj);
1545     if (mod) {
1546         Py_INCREF(mod);
1547     } else {
1548         mod = PyModule_NewObject(nameobj.ptr());
1549     }
1550     return mod;
1551 }
1552 
1553 /// Must be a POD type, and must hold enough entries for all of the possible slots PLUS ONE for
1554 /// the sentinel (0) end slot.
1555 using slots_array = std::array<PyModuleDef_Slot, 5>;
1556 
1557 /// Initialize an array of slots based on the supplied exec slot and options.
1558 template <typename... Options>
1559 inline slots_array init_slots(int (*exec_fn)(PyObject *), Options &&...options) noexcept {
1560     /* NOTE: slots_array MUST be large enough to hold all possible options.  If you add an option
1561     here, you MUST also increase the size of slots_array in the type alias above! */
1562     slots_array mod_def_slots;
1563     size_t next_slot = 0;
1564 
1565     mod_def_slots[next_slot++] = {Py_mod_create, reinterpret_cast<void *>(&cached_create_module)};
1566 
1567     if (exec_fn != nullptr) {
1568         mod_def_slots[next_slot++] = {Py_mod_exec, reinterpret_cast<void *>(exec_fn)};
1569     }
1570 
1571 #ifdef Py_mod_multiple_interpreters
1572     mod_def_slots[next_slot++] = {Py_mod_multiple_interpreters, multi_interp_slot(options...)};
1573 #endif
1574 
1575     if (gil_not_used_option(options...)) {
1576 #if defined(Py_mod_gil) && defined(Py_GIL_DISABLED)
1577         mod_def_slots[next_slot++] = {Py_mod_gil, Py_MOD_GIL_NOT_USED};
1578 #endif
1579     }
1580 
1581     // slots must have a zero end sentinel
1582     mod_def_slots[next_slot++] = {0, nullptr};
1583 
1584     return mod_def_slots;
1585 }
1586 
1587 PYBIND11_NAMESPACE_END(detail)
1588 
1589 /// Wrapper for Python extension modules
1590 class module_ : public object {
1591 public:
1592     PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)
1593 
1594     /// Create a new top-level Python module with the given name and docstring
1595     PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead")
1596     explicit module_(const char *name, const char *doc = nullptr) {
1597         *this = create_extension_module(name, doc, new PyModuleDef());
1598     }
1599 
1600     /** \rst
1601         Create Python binding for a new function within the module scope. ``Func``
1602         can be a plain C++ function, a function pointer, or a lambda function. For
1603         details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
1604     \endrst */
1605     template <typename Func, typename... Extra>
1606     module_ &def(const char *name_, Func &&f, const Extra &...extra) {
1607         cpp_function func(std::forward<Func>(f),
1608                           name(name_),
1609                           scope(*this),
1610                           sibling(getattr(*this, name_, none())),
1611                           extra...);
1612         // NB: allow overwriting here because cpp_function sets up a chain with the intention of
1613         // overwriting (and has already checked internally that it isn't overwriting
1614         // non-functions).
1615         add_object(name_, func, true /* overwrite */);
1616         return *this;
1617     }
1618 
1619     /** \rst
1620         Create and return a new Python submodule with the given name and docstring.
1621         This also works recursively, i.e.
1622 
1623         .. code-block:: cpp
1624 
1625             py::module_ m("example", "pybind11 example plugin");
1626             py::module_ m2 = m.def_submodule("sub", "A submodule of 'example'");
1627             py::module_ m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
1628     \endrst */
1629     module_ def_submodule(const char *name, const char *doc = nullptr) {
1630         const char *this_name = PyModule_GetName(m_ptr);
1631         if (this_name == nullptr) {
1632             throw error_already_set();
1633         }
1634         std::string full_name = std::string(this_name) + '.' + name;
1635         handle submodule = PyImport_AddModule(full_name.c_str());
1636         if (!submodule) {
1637             throw error_already_set();
1638         }
1639         auto result = reinterpret_borrow<module_>(submodule);
1640         if (doc && options::show_user_defined_docstrings()) {
1641             result.attr("__doc__") = pybind11::str(doc);
1642         }
1643 
1644 #if defined(GRAALVM_PYTHON) && (!defined(GRAALPY_VERSION_NUM) || GRAALPY_VERSION_NUM < 0x190000)
1645         // GraalPy doesn't support PyModule_GetFilenameObject,
1646         // so getting by attribute (see PR #5584)
1647         handle this_module = m_ptr;
1648         if (object this_file = getattr(this_module, "__file__", none())) {
1649             result.attr("__file__") = this_file;
1650         }
1651 #else
1652         handle this_file = PyModule_GetFilenameObject(m_ptr);
1653         if (this_file) {
1654             result.attr("__file__") = this_file;
1655         } else if (PyErr_ExceptionMatches(PyExc_SystemError) != 0) {
1656             PyErr_Clear();
1657         } else {
1658             throw error_already_set();
1659         }
1660 #endif
1661         attr(name) = result;
1662         return result;
1663     }
1664 
1665     /// Import and return a module or throws `error_already_set`.
1666     static module_ import(const char *name) {
1667         PyObject *obj = PyImport_ImportModule(name);
1668         if (!obj) {
1669             throw error_already_set();
1670         }
1671         return reinterpret_steal<module_>(obj);
1672     }
1673 
1674     /// Reload the module or throws `error_already_set`.
1675     void reload() {
1676         PyObject *obj = PyImport_ReloadModule(ptr());
1677         if (!obj) {
1678             throw error_already_set();
1679         }
1680         *this = reinterpret_steal<module_>(obj);
1681     }
1682 
1683     /** \rst
1684         Adds an object to the module using the given name.  Throws if an object with the given name
1685         already exists.
1686 
1687         ``overwrite`` should almost always be false: attempting to overwrite objects that pybind11
1688         has established will, in most cases, break things.
1689     \endrst */
1690     PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
1691         if (!overwrite && hasattr(*this, name)) {
1692             pybind11_fail(
1693                 "Error during initialization: multiple incompatible definitions with name \""
1694                 + std::string(name) + "\"");
1695         }
1696 
1697         PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
1698     }
1699 
1700     // DEPRECATED (since PR #5688): Use PyModuleDef directly instead.
1701     using module_def = PyModuleDef;
1702 
1703     /** \rst
1704         Create a new top-level module that can be used as the main module of a C extension.
1705 
1706         ``def`` should point to a statically allocated PyModuleDef.
1707     \endrst */
1708     static module_ create_extension_module(const char *name,
1709                                            const char *doc,
1710                                            PyModuleDef *def,
1711                                            mod_gil_not_used gil_not_used
1712                                            = mod_gil_not_used(false)) {
1713         // Placement new (not an allocation).
1714         new (def) PyModuleDef{/* m_base */ PyModuleDef_HEAD_INIT,
1715                               /* m_name */ name,
1716                               /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr,
1717                               /* m_size */ -1,
1718                               /* m_methods */ nullptr,
1719                               /* m_slots */ nullptr,
1720                               /* m_traverse */ nullptr,
1721                               /* m_clear */ nullptr,
1722                               /* m_free */ nullptr};
1723         auto *m = PyModule_Create(def);
1724         if (m == nullptr) {
1725             if (PyErr_Occurred()) {
1726                 throw error_already_set();
1727             }
1728             pybind11_fail("Internal error in module_::create_extension_module()");
1729         }
1730         if (gil_not_used.flag()) {
1731 #ifdef Py_GIL_DISABLED
1732             PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
1733 #endif
1734         }
1735         // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when
1736         //       returned from PyInit_...
1737         //       For Python 2, reinterpret_borrow was correct.
1738         return reinterpret_borrow<module_>(m);
1739     }
1740 };
1741 
1742 PYBIND11_NAMESPACE_BEGIN(detail)
1743 
1744 template <>
1745 struct handle_type_name<module_> {
1746     static constexpr auto name = const_name("types.ModuleType");
1747 };
1748 
1749 PYBIND11_NAMESPACE_END(detail)
1750 
1751 // When inside a namespace (or anywhere as long as it's not the first item on a line),
1752 // C++20 allows "module" to be used. This is provided for backward compatibility, and for
1753 // simplicity, if someone wants to use py::module for example, that is perfectly safe.
1754 using module = module_;
1755 
1756 /// \ingroup python_builtins
1757 /// Return a dictionary representing the global variables in the current execution frame,
1758 /// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
1759 inline dict globals() {
1760 #if PY_VERSION_HEX >= 0x030d0000
1761     PyObject *p = PyEval_GetFrameGlobals();
1762     return p ? reinterpret_steal<dict>(p)
1763              : reinterpret_borrow<dict>(module_::import("__main__").attr("__dict__").ptr());
1764 #else
1765     PyObject *p = PyEval_GetGlobals();
1766     return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
1767 #endif
1768 }
1769 
1770 PYBIND11_NAMESPACE_BEGIN(detail)
1771 /// Generic support for creating new Python heap types
1772 class generic_type : public object {
1773 public:
1774     PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
1775 protected:
1776     void initialize(const type_record &rec) {
1777         if (rec.scope && hasattr(rec.scope, "__dict__")
1778             && rec.scope.attr("__dict__").contains(rec.name)) {
1779             pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name)
1780                           + "\": an object with that name is already defined");
1781         }
1782 
1783         if ((rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
1784             != nullptr) {
1785             pybind11_fail("generic_type: type \"" + std::string(rec.name)
1786                           + "\" is already registered!");
1787         }
1788 
1789         m_ptr = make_new_python_type(rec);
1790 
1791         /* Register supplemental type information in C++ dict */
1792         auto *tinfo = new detail::type_info();
1793         tinfo->type = reinterpret_cast<PyTypeObject *>(m_ptr);
1794         tinfo->cpptype = rec.type;
1795         tinfo->type_size = rec.type_size;
1796         tinfo->type_align = rec.type_align;
1797         tinfo->operator_new = rec.operator_new;
1798         tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
1799         tinfo->init_instance = rec.init_instance;
1800         tinfo->dealloc = rec.dealloc;
1801         tinfo->get_trampoline_self_life_support = rec.get_trampoline_self_life_support;
1802         tinfo->simple_type = true;
1803         tinfo->simple_ancestors = true;
1804         tinfo->module_local = rec.module_local;
1805         tinfo->holder_enum_v = rec.holder_enum_v;
1806 
1807         with_internals([&](internals &internals) {
1808             auto tindex = std::type_index(*rec.type);
1809             tinfo->direct_conversions = &internals.direct_conversions[tindex];
1810             auto &local_internals = get_local_internals();
1811             if (rec.module_local) {
1812                 local_internals.registered_types_cpp[rec.type] = tinfo;
1813             } else {
1814                 internals.registered_types_cpp[tindex] = tinfo;
1815 #if PYBIND11_INTERNALS_VERSION >= 12
1816                 internals.registered_types_cpp_fast[rec.type] = tinfo;
1817 #endif
1818             }
1819 
1820             PYBIND11_WARNING_PUSH
1821 #if defined(__GNUC__) && __GNUC__ == 12
1822             // When using GCC 12 these warnings are disabled as they trigger
1823             // false positive warnings.  Discussed here:
1824             // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115824.
1825             PYBIND11_WARNING_DISABLE_GCC("-Warray-bounds")
1826             PYBIND11_WARNING_DISABLE_GCC("-Wstringop-overread")
1827 #endif
1828             internals.registered_types_py[reinterpret_cast<PyTypeObject *>(m_ptr)] = {tinfo};
1829             PYBIND11_WARNING_POP
1830         });
1831 
1832         if (rec.bases.size() > 1 || rec.multiple_inheritance) {
1833             mark_parents_nonsimple(tinfo->type);
1834             tinfo->simple_ancestors = false;
1835         } else if (rec.bases.size() == 1) {
1836             auto *parent_tinfo
1837                 = get_type_info(reinterpret_cast<PyTypeObject *>(rec.bases[0].ptr()));
1838             assert(parent_tinfo != nullptr);
1839             bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1840             tinfo->simple_ancestors = parent_simple_ancestors;
1841             // The parent can no longer be a simple type if it has MI and has a child
1842             parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1843         }
1844 
1845         if (rec.module_local) {
1846             // Stash the local typeinfo and loader so that external modules can access it.
1847             tinfo->module_local_load = &type_caster_generic::local_load;
1848             setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
1849         }
1850     }
1851 
1852     /// Helper function which tags all parents of a type using mult. inheritance
1853     void mark_parents_nonsimple(PyTypeObject *value) {
1854         auto t = reinterpret_borrow<tuple>(value->tp_bases);
1855         for (handle h : t) {
1856             auto *tinfo2 = get_type_info(reinterpret_cast<PyTypeObject *>(h.ptr()));
1857             if (tinfo2) {
1858                 tinfo2->simple_type = false;
1859             }
1860             mark_parents_nonsimple(reinterpret_cast<PyTypeObject *>(h.ptr()));
1861         }
1862     }
1863 
1864     void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *),
1865                               void *get_buffer_data) {
1866         auto *type = reinterpret_cast<PyHeapTypeObject *>(m_ptr);
1867         auto *tinfo = detail::get_type_info(&type->ht_type);
1868 
1869         if (!type->ht_type.tp_as_buffer) {
1870             pybind11_fail("To be able to register buffer protocol support for the type '"
1871                           + get_fully_qualified_tp_name(tinfo->type)
1872                           + "' the associated class<>(..) invocation must "
1873                             "include the pybind11::buffer_protocol() annotation!");
1874         }
1875 
1876         tinfo->get_buffer = get_buffer;
1877         tinfo->get_buffer_data = get_buffer_data;
1878     }
1879 
1880     // rec_func must be set for either fget or fset.
1881     void def_property_static_impl(const char *name,
1882                                   handle fget,
1883                                   handle fset,
1884                                   detail::function_record *rec_func) {
1885         const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);
1886         const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)
1887                              && pybind11::options::show_user_defined_docstrings();
1888         auto property = handle(reinterpret_cast<PyObject *>(
1889             is_static ? get_internals().static_property_type : &PyProperty_Type));
1890         attr(name) = property(fget.ptr() ? fget : none(),
1891                               fset.ptr() ? fset : none(),
1892                               /*deleter*/ none(),
1893                               pybind11::str(has_doc ? rec_func->doc : ""));
1894     }
1895 };
1896 
1897 /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
1898 template <typename T,
1899           typename = void_t<decltype(static_cast<void *(*) (size_t)>(T::operator new))>>
1900 void set_operator_new(type_record *r) {
1901     r->operator_new = &T::operator new;
1902 }
1903 
1904 template <typename>
1905 void set_operator_new(...) {}
1906 
1907 template <typename T, typename SFINAE = void>
1908 struct has_operator_delete : std::false_type {};
1909 template <typename T>
1910 struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
1911     : std::true_type {};
1912 template <typename T, typename SFINAE = void>
1913 struct has_operator_delete_size : std::false_type {};
1914 template <typename T>
1915 struct has_operator_delete_size<
1916     T,
1917     void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type {
1918 };
1919 /// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
1920 template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
1921 void call_operator_delete(T *p, size_t, size_t) {
1922     T::operator delete(p);
1923 }
1924 template <typename T,
1925           enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int>
1926           = 0>
1927 void call_operator_delete(T *p, size_t s, size_t) {
1928     T::operator delete(p, s);
1929 }
1930 
1931 inline void call_operator_delete(void *p, size_t s, size_t a) {
1932     (void) s;
1933     (void) a;
1934 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1935     if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1936 #    ifdef __cpp_sized_deallocation
1937         ::operator delete(p, s, std::align_val_t(a));
1938 #    else
1939         ::operator delete(p, std::align_val_t(a));
1940 #    endif
1941         return;
1942     }
1943 #endif
1944 #ifdef __cpp_sized_deallocation
1945     ::operator delete(p, s);
1946 #else
1947     ::operator delete(p);
1948 #endif
1949 }
1950 
1951 inline void add_class_method(object &cls, const char *name_, const cpp_function &cf) {
1952     cls.attr(cf.name()) = cf;
1953     if (std::strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) {
1954         cls.attr("__hash__") = none();
1955     }
1956 }
1957 
1958 /// Type trait to rebind a member function pointer's class to `Derived`, preserving all
1959 /// cv/ref/noexcept qualifiers. The primary template has no `type` member, providing SFINAE
1960 /// failure for unsupported member function pointer types. `source_class` holds the original
1961 /// class for use in `is_accessible_base_of` checks.
1962 template <typename Derived, typename T>
1963 struct rebind_member_ptr {};
1964 
1965 // Define one specialization per supported qualifier combination via a local macro.
1966 // The qualifiers argument appears in type position, not expression position, so
1967 // parenthesizing it would produce invalid C++.
1968 // The no-qualifier specialization is written out explicitly to avoid invoking the macro with an
1969 // empty argument, which triggers MSVC warning C4003.
1970 template <typename Derived, typename Return, typename Class, typename... Args>
1971 struct rebind_member_ptr<Derived, Return (Class::*)(Args...)> {
1972     using type = Return (Derived::*)(Args...);
1973     using source_class = Class;
1974 };
1975 // NOLINTBEGIN(bugprone-macro-parentheses)
1976 #define PYBIND11_REBIND_MEMBER_PTR(qualifiers)                                                    \
1977     template <typename Derived, typename Return, typename Class, typename... Args>                \
1978     struct rebind_member_ptr<Derived, Return (Class::*)(Args...) qualifiers> {                    \
1979         using type = Return (Derived::*)(Args...) qualifiers;                                     \
1980         using source_class = Class;                                                               \
1981     }
1982 PYBIND11_REBIND_MEMBER_PTR(const);
1983 PYBIND11_REBIND_MEMBER_PTR(&);
1984 PYBIND11_REBIND_MEMBER_PTR(const &);
1985 PYBIND11_REBIND_MEMBER_PTR(&&);
1986 PYBIND11_REBIND_MEMBER_PTR(const &&);
1987 #ifdef __cpp_noexcept_function_type
1988 PYBIND11_REBIND_MEMBER_PTR(noexcept);
1989 PYBIND11_REBIND_MEMBER_PTR(const noexcept);
1990 PYBIND11_REBIND_MEMBER_PTR(& noexcept);
1991 PYBIND11_REBIND_MEMBER_PTR(const & noexcept);
1992 PYBIND11_REBIND_MEMBER_PTR(&& noexcept);
1993 PYBIND11_REBIND_MEMBER_PTR(const && noexcept);
1994 #endif
1995 #undef PYBIND11_REBIND_MEMBER_PTR
1996 // NOLINTEND(bugprone-macro-parentheses)
1997 
1998 /// Shared implementation body for all method_adaptor member-function-pointer overloads.
1999 /// Asserts Base is accessible from Derived, then casts the member pointer.
2000 template <typename Derived,
2001           typename T,
2002           typename Traits = rebind_member_ptr<Derived, T>,
2003           typename Adapted = typename Traits::type>
2004 constexpr PYBIND11_ALWAYS_INLINE Adapted adapt_member_ptr(T pmf) {
2005     static_assert(
2006         detail::is_accessible_base_of<typename Traits::source_class, Derived>::value,
2007         "Cannot bind an inaccessible base class method; use a lambda definition instead");
2008     return pmf;
2009 }
2010 
2011 PYBIND11_NAMESPACE_END(detail)
2012 
2013 /// Given a pointer to a member function, cast it to its `Derived` version.
2014 /// For all other callables (lambdas, function pointers, etc.), forward unchanged.
2015 ///
2016 /// Two overloads cover all cases without explicit per-qualifier instantiations:
2017 ///
2018 ///  (1) Generic fallback — disabled for member function pointers so that (2) wins
2019 ///      without any partial-ordering ambiguity.
2020 ///  (2) MFP overload — SFINAE on rebind_member_ptr::type, which exists for every
2021 ///      supported qualifier combination (const, &, &&, noexcept, ...).  A single
2022 ///      template therefore covers all combinations that rebind_member_ptr handles.
2023 template <
2024     typename /*Derived*/,
2025     typename F,
2026     detail::enable_if_t<!std::is_member_function_pointer<detail::remove_reference_t<F>>::value,
2027                         int> = 0>
2028 constexpr auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
2029     return std::forward<F>(f);
2030 }
2031 
2032 template <typename Derived,
2033           typename T,
2034           typename Adapted = typename detail::rebind_member_ptr<Derived, T>::type>
2035 constexpr Adapted method_adaptor(T pmf) {
2036     // Expected to be redundant (SFINAE on rebind_member_ptr) but cheap and makes the intent
2037     // explicit.
2038     static_assert(std::is_member_function_pointer<T>::value,
2039                   "method_adaptor: T must be a member function pointer");
2040     return detail::adapt_member_ptr<Derived>(pmf);
2041 }
2042 
2043 PYBIND11_NAMESPACE_BEGIN(detail)
2044 
2045 // Helper for the property_cpp_function static member functions below.
2046 // The only purpose of these functions is to support .def_readonly & .def_readwrite.
2047 // In this context, the PM template parameter is certain to be a Pointer to a Member.
2048 // The main purpose of must_be_member_function_pointer is to make this obvious, and to guard
2049 // against accidents. As a side-effect, it also explains why the syntactical overhead for
2050 // perfect forwarding is not needed.
2051 template <typename PM>
2052 using must_be_member_function_pointer = enable_if_t<std::is_member_pointer<PM>::value, int>;
2053 
2054 // Note that property_cpp_function is intentionally in the main pybind11 namespace,
2055 // because user-defined specializations could be useful.
2056 
2057 // Classic (non-smart_holder) implementations for .def_readonly and .def_readwrite
2058 // getter and setter functions.
2059 // WARNING: This classic implementation can lead to dangling pointers for raw pointer members.
2060 // See test_ptr() in tests/test_class_sh_property.py
2061 // However, this implementation works as-is (and safely) for smart_holder std::shared_ptr members.
2062 template <typename T, typename D>
2063 struct property_cpp_function_classic {
2064     template <typename PM, must_be_member_function_pointer<PM> = 0>
2065     static cpp_function readonly(PM pm, const handle &hdl) {
2066         return cpp_function([pm](const T &c) -> const D & { return c.*pm; }, is_method(hdl));
2067     }
2068 
2069     template <typename PM, must_be_member_function_pointer<PM> = 0>
2070     static cpp_function read(PM pm, const handle &hdl) {
2071         return readonly(pm, hdl);
2072     }
2073 
2074     template <typename PM, must_be_member_function_pointer<PM> = 0>
2075     static cpp_function write(PM pm, const handle &hdl) {
2076         return cpp_function([pm](T &c, const D &value) { c.*pm = value; }, is_method(hdl));
2077     }
2078 };
2079 
2080 PYBIND11_NAMESPACE_END(detail)
2081 
2082 template <typename T, typename D, typename SFINAE = void>
2083 struct property_cpp_function : detail::property_cpp_function_classic<T, D> {};
2084 
2085 PYBIND11_NAMESPACE_BEGIN(detail)
2086 
2087 template <typename T, typename D, typename SFINAE = void>
2088 struct both_t_and_d_use_type_caster_base : std::false_type {};
2089 
2090 // `T` is assumed to be equivalent to `intrinsic_t<T>`.
2091 // `D` is may or may not be equivalent to `intrinsic_t<D>`.
2092 template <typename T, typename D>
2093 struct both_t_and_d_use_type_caster_base<
2094     T,
2095     D,
2096     enable_if_t<all_of<std::is_base_of<type_caster_base<T>, type_caster<T>>,
2097                        std::is_base_of<type_caster_base<intrinsic_t<D>>, make_caster<D>>>::value>>
2098     : std::true_type {};
2099 
2100 // Specialization for raw pointer members, using smart_holder if that is the class_ holder,
2101 // or falling back to the classic implementation if not.
2102 // WARNING: Like the classic implementation, this implementation can lead to dangling pointers.
2103 // See test_ptr() in tests/test_class_sh_property.py
2104 // However, the read functions return a shared_ptr to the member, emulating the PyCLIF approach:
2105 // https://github.com/google/clif/blob/c371a6d4b28d25d53a16e6d2a6d97305fb1be25a/clif/python/instance.h#L233
2106 // This prevents disowning of the Python object owning the raw pointer member.
2107 template <typename T, typename D>
2108 struct property_cpp_function_sh_raw_ptr_member {
2109     using drp = typename std::remove_pointer<D>::type;
2110 
2111     template <typename PM, must_be_member_function_pointer<PM> = 0>
2112     static cpp_function readonly(PM pm, const handle &hdl) {
2113         type_info *tinfo = get_type_info(typeid(T), /*throw_if_missing=*/true);
2114         if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
2115             return cpp_function(
2116                 [pm](handle c_hdl) -> std::shared_ptr<drp> {
2117                     std::shared_ptr<T> c_sp
2118                         = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(
2119                             c_hdl);
2120                     D ptr = (*c_sp).*pm;
2121                     return std::shared_ptr<drp>(c_sp, ptr);
2122                 },
2123                 is_method(hdl));
2124         }
2125         return property_cpp_function_classic<T, D>::readonly(pm, hdl);
2126     }
2127 
2128     template <typename PM, must_be_member_function_pointer<PM> = 0>
2129     static cpp_function read(PM pm, const handle &hdl) {
2130         return readonly(pm, hdl);
2131     }
2132 
2133     template <typename PM, must_be_member_function_pointer<PM> = 0>
2134     static cpp_function write(PM pm, const handle &hdl) {
2135         type_info *tinfo = get_type_info(typeid(T), /*throw_if_missing=*/true);
2136         if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
2137             return cpp_function([pm](T &c, D value) { c.*pm = std::forward<D>(std::move(value)); },
2138                                 is_method(hdl));
2139         }
2140         return property_cpp_function_classic<T, D>::write(pm, hdl);
2141     }
2142 };
2143 
2144 // Specialization for members held by-value, using smart_holder if that is the class_ holder,
2145 // or falling back to the classic implementation if not.
2146 // The read functions return a shared_ptr to the member, emulating the PyCLIF approach:
2147 // https://github.com/google/clif/blob/c371a6d4b28d25d53a16e6d2a6d97305fb1be25a/clif/python/instance.h#L233
2148 // This prevents disowning of the Python object owning the member.
2149 template <typename T, typename D>
2150 struct property_cpp_function_sh_member_held_by_value {
2151     template <typename PM, must_be_member_function_pointer<PM> = 0>
2152     static cpp_function readonly(PM pm, const handle &hdl) {
2153         type_info *tinfo = get_type_info(typeid(T), /*throw_if_missing=*/true);
2154         if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
2155             return cpp_function(
2156                 [pm](handle c_hdl) -> std::shared_ptr<typename std::add_const<D>::type> {
2157                     std::shared_ptr<T> c_sp
2158                         = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(
2159                             c_hdl);
2160                     return std::shared_ptr<typename std::add_const<D>::type>(c_sp,
2161                                                                              &(c_sp.get()->*pm));
2162                 },
2163                 is_method(hdl));
2164         }
2165         return property_cpp_function_classic<T, D>::readonly(pm, hdl);
2166     }
2167 
2168     template <typename PM, must_be_member_function_pointer<PM> = 0>
2169     static cpp_function read(PM pm, const handle &hdl) {
2170         type_info *tinfo = get_type_info(typeid(T), /*throw_if_missing=*/true);
2171         if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
2172             return cpp_function(
2173                 [pm](handle c_hdl) -> std::shared_ptr<D> {
2174                     std::shared_ptr<T> c_sp
2175                         = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(
2176                             c_hdl);
2177                     return std::shared_ptr<D>(c_sp, &(c_sp.get()->*pm));
2178                 },
2179                 is_method(hdl));
2180         }
2181         return property_cpp_function_classic<T, D>::read(pm, hdl);
2182     }
2183 
2184     template <typename PM, must_be_member_function_pointer<PM> = 0>
2185     static cpp_function write(PM pm, const handle &hdl) {
2186         type_info *tinfo = get_type_info(typeid(T), /*throw_if_missing=*/true);
2187         if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
2188             return cpp_function([pm](T &c, const D &value) { c.*pm = value; }, is_method(hdl));
2189         }
2190         return property_cpp_function_classic<T, D>::write(pm, hdl);
2191     }
2192 };
2193 
2194 // Specialization for std::unique_ptr members, using smart_holder if that is the class_ holder,
2195 // or falling back to the classic implementation if not.
2196 // read disowns the member unique_ptr.
2197 // write disowns the passed Python object.
2198 // readonly is disabled (static_assert) because there is no safe & intuitive way to make the member
2199 // accessible as a Python object without disowning the member unique_ptr. A .def_readonly disowning
2200 // the unique_ptr member is deemed highly prone to misunderstandings.
2201 template <typename T, typename D>
2202 struct property_cpp_function_sh_unique_ptr_member {
2203     template <typename PM, must_be_member_function_pointer<PM> = 0>
2204     static cpp_function readonly(PM, const handle &) {
2205         static_assert(!is_instantiation<std::unique_ptr, D>::value,
2206                       "def_readonly cannot be used for std::unique_ptr members.");
2207         return cpp_function{}; // Unreachable.
2208     }
2209 
2210     template <typename PM, must_be_member_function_pointer<PM> = 0>
2211     static cpp_function read(PM pm, const handle &hdl) {
2212         type_info *tinfo = get_type_info(typeid(T), /*throw_if_missing=*/true);
2213         if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
2214             return cpp_function(
2215                 [pm](handle c_hdl) -> D {
2216                     std::shared_ptr<T> c_sp
2217                         = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(
2218                             c_hdl);
2219                     return D{std::move(c_sp.get()->*pm)};
2220                 },
2221                 is_method(hdl));
2222         }
2223         return property_cpp_function_classic<T, D>::read(pm, hdl);
2224     }
2225 
2226     template <typename PM, must_be_member_function_pointer<PM> = 0>
2227     static cpp_function write(PM pm, const handle &hdl) {
2228         return cpp_function([pm](T &c, D &&value) { c.*pm = std::move(value); }, is_method(hdl));
2229     }
2230 };
2231 
2232 PYBIND11_NAMESPACE_END(detail)
2233 
2234 template <typename T, typename D>
2235 struct property_cpp_function<
2236     T,
2237     D,
2238     detail::enable_if_t<detail::all_of<std::is_pointer<D>,
2239                                        detail::both_t_and_d_use_type_caster_base<T, D>>::value>>
2240     : detail::property_cpp_function_sh_raw_ptr_member<T, D> {};
2241 
2242 template <typename T, typename D>
2243 struct property_cpp_function<T,
2244                              D,
2245                              detail::enable_if_t<detail::all_of<
2246                                  detail::none_of<std::is_pointer<D>,
2247                                                  std::is_array<D>,
2248                                                  detail::is_instantiation<std::unique_ptr, D>,
2249                                                  detail::is_instantiation<std::shared_ptr, D>>,
2250                                  detail::both_t_and_d_use_type_caster_base<T, D>>::value>>
2251     : detail::property_cpp_function_sh_member_held_by_value<T, D> {};
2252 
2253 template <typename T, typename D>
2254 struct property_cpp_function<
2255     T,
2256     D,
2257     detail::enable_if_t<detail::all_of<
2258         detail::is_instantiation<std::unique_ptr, D>,
2259         detail::both_t_and_d_use_type_caster_base<T, typename D::element_type>>::value>>
2260     : detail::property_cpp_function_sh_unique_ptr_member<T, D> {};
2261 
2262 #ifdef PYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE
2263 // NOTE: THIS IS MEANT FOR STRESS-TESTING OR TRIAGING ONLY!
2264 //       Running the pybind11 unit tests with smart_holder as the default holder is to ensure
2265 //       that `py::smart_holder` / `py::classh` is backward-compatible with all pre-existing
2266 //       functionality.
2267 //       Be careful not to link translation units compiled with different default holders, because
2268 //       this will cause ODR violations (https://en.wikipedia.org/wiki/One_Definition_Rule).
2269 template <typename>
2270 using default_holder_type = smart_holder;
2271 #else
2272 template <typename T>
2273 using default_holder_type = std::unique_ptr<T>;
2274 #endif
2275 
2276 template <typename type_, typename... options>
2277 class class_ : public detail::generic_type {
2278     template <typename T>
2279     using is_holder = detail::is_holder_type<type_, T>;
2280     template <typename T>
2281     using is_subtype = detail::is_strict_base_of<type_, T>;
2282     template <typename T>
2283     using is_base = detail::is_strict_base_of<T, type_>;
2284     // struct instead of using here to help MSVC:
2285     template <typename T>
2286     struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
2287 
2288 public:
2289     using type = type_;
2290     using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
2291     constexpr static bool has_alias = !std::is_void<type_alias>::value;
2292     using holder_type = detail::exactly_one_t<is_holder, default_holder_type<type>, options...>;
2293 
2294     static_assert(detail::all_of<is_valid_class_option<options>...>::value,
2295                   "Unknown/invalid class_ template parameters provided");
2296 
2297     static_assert(!has_alias || std::is_polymorphic<type>::value,
2298                   "Cannot use an alias class (aka trampoline) with a non-polymorphic type");
2299 
2300 #ifndef PYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE
2301     static_assert(!has_alias || !detail::is_smart_holder<holder_type>::value
2302                       || std::is_base_of<trampoline_self_life_support, type_alias>::value,
2303                   "Alias class (aka trampoline) must inherit from"
2304                   " pybind11::trampoline_self_life_support if used in combination with"
2305                   " pybind11::smart_holder");
2306 #endif
2307     static_assert(!has_alias || detail::is_smart_holder<holder_type>::value
2308                       || !std::is_base_of<trampoline_self_life_support, type_alias>::value,
2309                   "pybind11::trampoline_self_life_support is a smart_holder feature, therefore"
2310                   " an alias class (aka trampoline) should inherit from"
2311                   " pybind11::trampoline_self_life_support only if used in combination with"
2312                   " pybind11::smart_holder");
2313 
2314     PYBIND11_OBJECT(class_, generic_type, PyType_Check)
2315 
2316     template <typename... Extra>
2317     class_(handle scope, const char *name, const Extra &...extra) {
2318         using namespace detail;
2319 
2320         // MI can only be specified via class_ template options, not constructor parameters
2321         static_assert(
2322             none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
2323                 (constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
2324                  constexpr_sum(is_base<options>::value...) == 0 &&   // no template option bases
2325                  // no multiple_inheritance attr
2326                  none_of<std::is_same<multiple_inheritance, Extra>...>::value),
2327             "Error: multiple inheritance bases must be specified via class_ template options");
2328 
2329         type_record record;
2330         record.scope = scope;
2331         record.name = name;
2332         record.type = &typeid(type);
2333         record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
2334         record.type_align = alignof(conditional_t<has_alias, type_alias, type> &);
2335         record.holder_size = sizeof(holder_type);
2336         record.init_instance = init_instance;
2337 
2338         if (detail::is_instantiation<std::unique_ptr, holder_type>::value) {
2339             record.holder_enum_v = detail::holder_enum_t::std_unique_ptr;
2340         } else if (detail::is_instantiation<std::shared_ptr, holder_type>::value) {
2341             record.holder_enum_v = detail::holder_enum_t::std_shared_ptr;
2342         } else if (std::is_same<holder_type, smart_holder>::value) {
2343             record.holder_enum_v = detail::holder_enum_t::smart_holder;
2344         } else {
2345             record.holder_enum_v = detail::holder_enum_t::custom_holder;
2346         }
2347 
2348         set_operator_new<type>(&record);
2349 
2350         /* Register base classes specified via template arguments to class_, if any */
2351         PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
2352 
2353         /* Process optional arguments, if any */
2354         process_attributes<Extra...>::init(extra..., &record);
2355 
2356         if (record.release_gil_before_calling_cpp_dtor) {
2357             record.dealloc = dealloc_release_gil_before_calling_cpp_dtor;
2358         } else {
2359             record.dealloc = dealloc_without_manipulating_gil;
2360         }
2361 
2362         if (std::is_base_of<trampoline_self_life_support, type_alias>::value) {
2363             // Store a cross-DSO-safe getter.
2364             // This lambda is defined in the same DSO that instantiates
2365             // class_<type, alias_type>, but it can be called safely from any other DSO.
2366             record.get_trampoline_self_life_support = [](void *type_ptr) {
2367                 return dynamic_raw_ptr_cast_if_possible<trampoline_self_life_support>(
2368                     static_cast<type *>(type_ptr));
2369             };
2370         }
2371 
2372         generic_type::initialize(record);
2373 
2374         if (has_alias) {
2375             with_internals([&](internals &internals) {
2376                 auto &local_internals = get_local_internals();
2377                 if (record.module_local) {
2378                     local_internals.registered_types_cpp[&typeid(type_alias)]
2379                         = local_internals.registered_types_cpp[&typeid(type)];
2380                 } else {
2381                     type_info *const val
2382                         = internals.registered_types_cpp[std::type_index(typeid(type))];
2383                     internals.registered_types_cpp[std::type_index(typeid(type_alias))] = val;
2384 #if PYBIND11_INTERNALS_VERSION >= 12
2385                     internals.registered_types_cpp_fast[&typeid(type_alias)] = val;
2386 #endif
2387                 }
2388             });
2389         }
2390         def("_pybind11_conduit_v1_", cpp_conduit_method);
2391     }
2392 
2393     template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
2394     static void add_base(detail::type_record &rec) {
2395         rec.add_base(typeid(Base), [](void *src) -> void * {
2396             return static_cast<Base *>(reinterpret_cast<type *>(src));
2397         });
2398         // Virtual inheritance means the base subobject is at a dynamic offset,
2399         // so the reinterpret_cast shortcut in load_impl Case 2a is invalid.
2400         // Force the MI path (implicit_casts) for correct pointer adjustment.
2401         // Detection: static_cast<Derived*>(Base*) is ill-formed for virtual bases.
2402         if PYBIND11_MAYBE_CONSTEXPR (!detail::is_static_downcastable<Base, type>::value) {
2403             rec.multiple_inheritance = true;
2404         }
2405     }
2406 
2407     template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
2408     static void add_base(detail::type_record &) {}
2409 
2410     template <typename Func, typename... Extra>
2411     class_ &def(const char *name_, Func &&f, const Extra &...extra) {
2412         cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
2413                         name(name_),
2414                         is_method(*this),
2415                         sibling(getattr(*this, name_, none())),
2416                         extra...);
2417         add_class_method(*this, name_, cf);
2418         return *this;
2419     }
2420 
2421     template <typename Func, typename... Extra>
2422     class_ &def_static(const char *name_, Func &&f, const Extra &...extra) {
2423         static_assert(!std::is_member_function_pointer<Func>::value,
2424                       "def_static(...) called with a non-static member function pointer");
2425         cpp_function cf(std::forward<Func>(f),
2426                         name(name_),
2427                         scope(*this),
2428                         sibling(getattr(*this, name_, none())),
2429                         extra...);
2430         auto cf_name = cf.name();
2431         attr(std::move(cf_name)) = staticmethod(std::move(cf));
2432         return *this;
2433     }
2434 
2435     template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
2436     class_ &def(const T &op, const Extra &...extra) {
2437         op.execute(*this, extra...);
2438         return *this;
2439     }
2440 
2441     template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
2442     class_ &def_cast(const T &op, const Extra &...extra) {
2443         op.execute_cast(*this, extra...);
2444         return *this;
2445     }
2446 
2447     template <typename... Args, typename... Extra>
2448     class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra &...extra) {
2449         PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
2450         init.execute(*this, extra...);
2451         return *this;
2452     }
2453 
2454     template <typename... Args, typename... Extra>
2455     class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra &...extra) {
2456         PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
2457         init.execute(*this, extra...);
2458         return *this;
2459     }
2460 
2461     template <typename... Args, typename... Extra>
2462     class_ &def(detail::initimpl::factory<Args...> &&init, const Extra &...extra) {
2463         std::move(init).execute(*this, extra...);
2464         return *this;
2465     }
2466 
2467     template <typename... Args, typename... Extra>
2468     class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
2469         std::move(pf).execute(*this, extra...);
2470         return *this;
2471     }
2472 
2473     template <typename Func>
2474     class_ &def_buffer(Func &&func) {
2475         struct capture {
2476             Func func;
2477         };
2478         auto *ptr = new capture{std::forward<Func>(func)};
2479         install_buffer_funcs(
2480             [](PyObject *obj, void *ptr) -> buffer_info * {
2481                 detail::make_caster<type> caster;
2482                 if (!caster.load(obj, false)) {
2483                     return nullptr;
2484                 }
2485                 return new buffer_info(((capture *) ptr)->func(std::move(caster)));
2486             },
2487             ptr);
2488         weakref(m_ptr, cpp_function([ptr](handle wr) {
2489                     delete ptr;
2490                     wr.dec_ref();
2491                 }))
2492             .release();
2493         return *this;
2494     }
2495 
2496     template <typename Return, typename Class, typename... Args>
2497     class_ &def_buffer(Return (Class::*func)(Args...)) {
2498         return def_buffer([func](type &obj) { return (obj.*func)(); });
2499     }
2500 
2501     template <typename Return, typename Class, typename... Args>
2502     class_ &def_buffer(Return (Class::*func)(Args...) const) {
2503         return def_buffer([func](const type &obj) { return (obj.*func)(); });
2504     }
2505 
2506     // Intentionally no &&/const&& overloads: buffer protocol callbacks are invoked on an
2507     // existing Python object and should not move-from self.
2508     template <typename Return, typename Class, typename... Args>
2509     class_ &def_buffer(Return (Class::*func)(Args...) &) {
2510         return def_buffer([func](type &obj) { return (obj.*func)(); });
2511     }
2512 
2513     template <typename Return, typename Class, typename... Args>
2514     class_ &def_buffer(Return (Class::*func)(Args...) const &) {
2515         return def_buffer([func](const type &obj) { return (obj.*func)(); });
2516     }
2517 
2518 #ifdef __cpp_noexcept_function_type
2519     template <typename Return, typename Class, typename... Args>
2520     class_ &def_buffer(Return (Class::*func)(Args...) noexcept) {
2521         return def_buffer([func](type &obj) { return (obj.*func)(); });
2522     }
2523 
2524     template <typename Return, typename Class, typename... Args>
2525     class_ &def_buffer(Return (Class::*func)(Args...) const noexcept) {
2526         return def_buffer([func](const type &obj) { return (obj.*func)(); });
2527     }
2528 
2529     template <typename Return, typename Class, typename... Args>
2530     class_ &def_buffer(Return (Class::*func)(Args...) & noexcept) {
2531         return def_buffer([func](type &obj) { return (obj.*func)(); });
2532     }
2533 
2534     template <typename Return, typename Class, typename... Args>
2535     class_ &def_buffer(Return (Class::*func)(Args...) const & noexcept) {
2536         return def_buffer([func](const type &obj) { return (obj.*func)(); });
2537     }
2538 #endif
2539 
2540     template <typename C, typename D, typename... Extra>
2541     class_ &def_readwrite(const char *name, D C::*pm, const Extra &...extra) {
2542         static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
2543                       "def_readwrite() requires a class member (or base class member)");
2544         def_property(name,
2545                      property_cpp_function<type, D>::read(pm, *this),
2546                      property_cpp_function<type, D>::write(pm, *this),
2547                      return_value_policy::reference_internal,
2548                      extra...);
2549         return *this;
2550     }
2551 
2552     template <typename C, typename D, typename... Extra>
2553     class_ &def_readonly(const char *name, const D C::*pm, const Extra &...extra) {
2554         static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
2555                       "def_readonly() requires a class member (or base class member)");
2556         def_property_readonly(name,
2557                               property_cpp_function<type, D>::readonly(pm, *this),
2558                               return_value_policy::reference_internal,
2559                               extra...);
2560         return *this;
2561     }
2562 
2563     template <typename D, typename... Extra>
2564     class_ &def_readwrite_static(const char *name, D *pm, const Extra &...extra) {
2565         cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)),
2566             fset([pm](const object &, const D &value) { *pm = value; }, scope(*this));
2567         def_property_static(name, fget, fset, return_value_policy::reference, extra...);
2568         return *this;
2569     }
2570 
2571     template <typename D, typename... Extra>
2572     class_ &def_readonly_static(const char *name, const D *pm, const Extra &...extra) {
2573         cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this));
2574         def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
2575         return *this;
2576     }
2577 
2578     /// Uses return_value_policy::reference_internal by default
2579     template <typename Getter, typename... Extra>
2580     class_ &def_property_readonly(const char *name, const Getter &fget, const Extra &...extra) {
2581         return def_property_readonly(name,
2582                                      cpp_function(method_adaptor<type>(fget)),
2583                                      return_value_policy::reference_internal,
2584                                      extra...);
2585     }
2586 
2587     /// Uses cpp_function's return_value_policy by default
2588     template <typename... Extra>
2589     class_ &
2590     def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra) {
2591         return def_property(name, fget, nullptr, extra...);
2592     }
2593 
2594     /// Uses return_value_policy::reference by default
2595     template <typename Getter, typename... Extra>
2596     class_ &
2597     def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra) {
2598         return def_property_readonly_static(
2599             name, cpp_function(fget), return_value_policy::reference, extra...);
2600     }
2601 
2602     /// Uses cpp_function's return_value_policy by default
2603     template <typename... Extra>
2604     class_ &def_property_readonly_static(const char *name,
2605                                          const cpp_function &fget,
2606                                          const Extra &...extra) {
2607         return def_property_static(name, fget, nullptr, extra...);
2608     }
2609 
2610     /// Uses return_value_policy::reference_internal by default
2611     template <typename Getter, typename Setter, typename... Extra>
2612     class_ &
2613     def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) {
2614         return def_property(
2615             name, fget, cpp_function(method_adaptor<type>(fset), is_setter()), extra...);
2616     }
2617     template <typename Getter, typename... Extra>
2618     class_ &def_property(const char *name,
2619                          const Getter &fget,
2620                          const cpp_function &fset,
2621                          const Extra &...extra) {
2622         return def_property(name,
2623                             cpp_function(method_adaptor<type>(fget)),
2624                             fset,
2625                             return_value_policy::reference_internal,
2626                             extra...);
2627     }
2628 
2629     /// Uses cpp_function's return_value_policy by default
2630     template <typename... Extra>
2631     class_ &def_property(const char *name,
2632                          const cpp_function &fget,
2633                          const cpp_function &fset,
2634                          const Extra &...extra) {
2635         return def_property_static(name, fget, fset, is_method(*this), extra...);
2636     }
2637 
2638     /// Uses return_value_policy::reference by default
2639     template <typename Getter, typename... Extra>
2640     class_ &def_property_static(const char *name,
2641                                 const Getter &fget,
2642                                 const cpp_function &fset,
2643                                 const Extra &...extra) {
2644         return def_property_static(
2645             name, cpp_function(fget), fset, return_value_policy::reference, extra...);
2646     }
2647 
2648     /// Uses cpp_function's return_value_policy by default
2649     template <typename... Extra>
2650     class_ &def_property_static(const char *name,
2651                                 const cpp_function &fget,
2652                                 const cpp_function &fset,
2653                                 const Extra &...extra) {
2654         static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
2655                       "Argument annotations are not allowed for properties");
2656         static_assert(0 == detail::constexpr_sum(detail::is_call_guard<Extra>::value...),
2657                       "def_property family does not currently support call_guard. Use a "
2658                       "py::cpp_function instead.");
2659         static_assert(0 == detail::constexpr_sum(detail::is_keep_alive<Extra>::value...),
2660                       "def_property family does not currently support keep_alive. Use a "
2661                       "py::cpp_function instead.");
2662         auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
2663         auto *rec_active = rec_fget;
2664         if (rec_fget) {
2665             char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific
2666                                                documentation string */
2667             auto args_before = rec_fget->args.size();
2668             detail::process_attributes<Extra...>::init(extra..., rec_fget);
2669             if (rec_fget->doc && rec_fget->doc != doc_prev) {
2670                 std::free(doc_prev);
2671                 rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc);
2672             }
2673             // Args added by process_attributes (e.g. "self" via is_method + pos_only/kw_only)
2674             // need their strings strdup'd: initialize_generic's strdup loop already ran during
2675             // cpp_function construction, so it won't process these late additions. Without this,
2676             // destruct() would call free() on string literals. See gh-5976.
2677             for (auto i = args_before; i < rec_fget->args.size(); ++i) {
2678                 if (rec_fget->args[i].name) {
2679                     rec_fget->args[i].name = PYBIND11_COMPAT_STRDUP(rec_fget->args[i].name);
2680                 }
2681                 if (rec_fget->args[i].descr) {
2682                     rec_fget->args[i].descr = PYBIND11_COMPAT_STRDUP(rec_fget->args[i].descr);
2683                 }
2684             }
2685         }
2686         if (rec_fset) {
2687             char *doc_prev = rec_fset->doc;
2688             auto args_before = rec_fset->args.size();
2689             detail::process_attributes<Extra...>::init(extra..., rec_fset);
2690             if (rec_fset->doc && rec_fset->doc != doc_prev) {
2691                 std::free(doc_prev);
2692                 rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc);
2693             }
2694             for (auto i = args_before; i < rec_fset->args.size(); ++i) {
2695                 if (rec_fset->args[i].name) {
2696                     rec_fset->args[i].name = PYBIND11_COMPAT_STRDUP(rec_fset->args[i].name);
2697                 }
2698                 if (rec_fset->args[i].descr) {
2699                     rec_fset->args[i].descr = PYBIND11_COMPAT_STRDUP(rec_fset->args[i].descr);
2700                 }
2701             }
2702             if (!rec_active) {
2703                 rec_active = rec_fset;
2704             }
2705         }
2706         def_property_static_impl(name, fget, fset, rec_active);
2707         return *this;
2708     }
2709 
2710 private:
2711     /// Initialize holder object, variant 1: object derives from enable_shared_from_this
2712     template <typename T>
2713     static void init_holder(detail::instance *inst,
2714                             detail::value_and_holder &v_h,
2715                             const holder_type * /* unused */,
2716                             const std::enable_shared_from_this<T> * /* dummy */) {
2717 
2718         auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
2719             detail::try_get_shared_from_this(v_h.value_ptr<type>()));
2720         if (sh) {
2721             new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
2722             v_h.set_holder_constructed();
2723         }
2724 
2725         if (!v_h.holder_constructed() && inst->owned) {
2726             new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
2727             v_h.set_holder_constructed();
2728         }
2729     }
2730 
2731     static void init_holder_from_existing(const detail::value_and_holder &v_h,
2732                                           const holder_type *holder_ptr,
2733                                           std::true_type /*is_copy_constructible*/) {
2734         new (std::addressof(v_h.holder<holder_type>())) holder_type(*holder_ptr);
2735     }
2736 
2737     static void init_holder_from_existing(const detail::value_and_holder &v_h,
2738                                           const holder_type *holder_ptr,
2739                                           std::false_type /*is_copy_constructible*/) {
2740         new (std::addressof(v_h.holder<holder_type>()))
2741             holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
2742     }
2743 
2744     /// Initialize holder object, variant 2: try to construct from existing holder object, if
2745     /// possible
2746     static void init_holder(detail::instance *inst,
2747                             detail::value_and_holder &v_h,
2748                             const holder_type *holder_ptr,
2749                             const void * /* dummy -- not enable_shared_from_this<T>) */) {
2750         if (holder_ptr) {
2751             init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
2752             v_h.set_holder_constructed();
2753         } else if (detail::always_construct_holder<holder_type>::value || inst->owned) {
2754             new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
2755             v_h.set_holder_constructed();
2756         }
2757     }
2758 
2759     /// Performs instance initialization including constructing a holder and registering the known
2760     /// instance.  Should be called as soon as the `type` value_ptr is set for an instance.  Takes
2761     /// an optional pointer to an existing holder to use; if not specified and the instance is
2762     /// `.owned`, a new holder will be constructed to manage the value pointer.
2763     template <typename H = holder_type,
2764               detail::enable_if_t<!detail::is_smart_holder<H>::value, int> = 0>
2765     static void init_instance(detail::instance *inst, const void *holder_ptr) {
2766         auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
2767         if (!v_h.instance_registered()) {
2768             register_instance(inst, v_h.value_ptr(), v_h.type);
2769             v_h.set_instance_registered();
2770         }
2771         init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
2772     }
2773 
2774     template <typename WrappedType>
2775     static bool try_initialization_using_shared_from_this(holder_type *, WrappedType *, ...) {
2776         return false;
2777     }
2778 
2779     // Adopting existing approach used by type_caster_base, although it leads to somewhat fuzzy
2780     // ownership semantics: if we detected via shared_from_this that a shared_ptr exists already,
2781     // it is reused, irrespective of the return_value_policy in effect.
2782     // "SomeBaseOfWrappedType" is needed because std::enable_shared_from_this is not necessarily a
2783     // direct base of WrappedType.
2784     template <typename WrappedType, typename SomeBaseOfWrappedType>
2785     static bool try_initialization_using_shared_from_this(
2786         holder_type *uninitialized_location,
2787         WrappedType *value_ptr_w_t,
2788         const std::enable_shared_from_this<SomeBaseOfWrappedType> *) {
2789         auto shd_ptr = std::dynamic_pointer_cast<WrappedType>(
2790             detail::try_get_shared_from_this(value_ptr_w_t));
2791         if (!shd_ptr) {
2792             return false;
2793         }
2794         // Note: inst->owned ignored.
2795         new (uninitialized_location) holder_type(holder_type::from_shared_ptr(shd_ptr));
2796         return true;
2797     }
2798 
2799     template <typename H = holder_type,
2800               detail::enable_if_t<detail::is_smart_holder<H>::value, int> = 0>
2801     static void init_instance(detail::instance *inst, const void *holder_const_void_ptr) {
2802         // Need for const_cast is a consequence of the type_info::init_instance type:
2803         // void (*init_instance)(instance *, const void *);
2804         auto *holder_void_ptr = const_cast<void *>(holder_const_void_ptr);
2805 
2806         auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
2807         if (!v_h.instance_registered()) {
2808             register_instance(inst, v_h.value_ptr(), v_h.type);
2809             v_h.set_instance_registered();
2810         }
2811         auto *uninitialized_location = std::addressof(v_h.holder<holder_type>());
2812         auto *value_ptr_w_t = v_h.value_ptr<type>();
2813         // Try downcast from `type` to `type_alias`:
2814         inst->is_alias
2815             = detail::dynamic_raw_ptr_cast_if_possible<type_alias>(value_ptr_w_t) != nullptr;
2816         if (holder_void_ptr) {
2817             // Note: inst->owned ignored.
2818             auto *holder_ptr = static_cast<holder_type *>(holder_void_ptr);
2819             new (uninitialized_location) holder_type(std::move(*holder_ptr));
2820         } else if (!try_initialization_using_shared_from_this(
2821                        uninitialized_location, value_ptr_w_t, value_ptr_w_t)) {
2822             if (inst->owned) {
2823                 new (uninitialized_location) holder_type(holder_type::from_raw_ptr_take_ownership(
2824                     value_ptr_w_t, /*void_cast_raw_ptr*/ inst->is_alias));
2825             } else {
2826                 new (uninitialized_location)
2827                     holder_type(holder_type::from_raw_ptr_unowned(value_ptr_w_t));
2828             }
2829         }
2830         v_h.set_holder_constructed();
2831     }
2832 
2833     // Deallocates an instance; via holder, if constructed; otherwise via operator delete.
2834     // NOTE: The Python error indicator needs to cleared BEFORE this function is called.
2835     // This is because we could be deallocating while cleaning up after a Python exception.
2836     // If the error indicator is not cleared but the C++ destructor code makes Python C API
2837     // calls, those calls are likely to generate a new exception, and pybind11 will then
2838     // throw `error_already_set` from the C++ destructor. This is forbidden and will
2839     // trigger std::terminate().
2840     static void dealloc_impl(detail::value_and_holder &v_h) {
2841         if (v_h.holder_constructed()) {
2842             v_h.holder<holder_type>().~holder_type();
2843             v_h.set_holder_constructed(false);
2844         } else {
2845             detail::call_operator_delete(
2846                 v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align);
2847         }
2848         v_h.value_ptr() = nullptr;
2849     }
2850 
2851     static void dealloc_without_manipulating_gil(detail::value_and_holder &v_h) {
2852         error_scope scope;
2853         dealloc_impl(v_h);
2854     }
2855 
2856     static void dealloc_release_gil_before_calling_cpp_dtor(detail::value_and_holder &v_h) {
2857         error_scope scope;
2858         // Intentionally not using `gil_scoped_release` because the non-simple
2859         // version unconditionally calls `get_internals()`.
2860         // `Py_BEGIN_ALLOW_THREADS`, `Py_END_ALLOW_THREADS` cannot be used
2861         // because those macros include `{` and `}`.
2862         PyThreadState *py_ts = PyEval_SaveThread();
2863         try {
2864             dealloc_impl(v_h);
2865         } catch (...) {
2866             // This code path is expected to be unreachable unless there is a
2867             // bug in pybind11 itself.
2868             // An alternative would be to mark this function, or
2869             // `dealloc_impl()`, with `nothrow`, but that would be a subtle
2870             // behavior change and could make debugging more difficult.
2871             PyEval_RestoreThread(py_ts);
2872             throw;
2873         }
2874         PyEval_RestoreThread(py_ts);
2875     }
2876 
2877     static detail::function_record *get_function_record(handle h) {
2878         h = detail::get_function(h);
2879         if (!h) {
2880             return nullptr;
2881         }
2882 
2883         handle func_self = PyCFunction_GET_SELF(h.ptr());
2884         if (!func_self) {
2885             throw error_already_set();
2886         }
2887         return detail::function_record_ptr_from_PyObject(func_self.ptr());
2888     }
2889 };
2890 
2891 // Supports easier switching between py::class_<T> and py::class_<T, py::smart_holder>:
2892 // users can simply replace the `_` in `class_` with `h` or vice versa.
2893 template <typename type_, typename... options>
2894 using classh = class_<type_, smart_holder, options...>;
2895 
2896 /// Binds an existing constructor taking arguments Args...
2897 template <typename... Args>
2898 detail::initimpl::constructor<Args...> init() {
2899     return {};
2900 }
2901 /// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
2902 /// when not inheriting on the Python side).
2903 template <typename... Args>
2904 detail::initimpl::alias_constructor<Args...> init_alias() {
2905     return {};
2906 }
2907 
2908 /// Binds a factory function as a constructor
2909 template <typename Func, typename Ret = detail::initimpl::factory<Func>>
2910 Ret init(Func &&f) {
2911     return {std::forward<Func>(f)};
2912 }
2913 
2914 /// Dual-argument factory function: the first function is called when no alias is needed, the
2915 /// second when an alias is needed (i.e. due to python-side inheritance).  Arguments must be
2916 /// identical.
2917 template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
2918 Ret init(CFunc &&c, AFunc &&a) {
2919     return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
2920 }
2921 
2922 /// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
2923 /// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
2924 template <typename GetState, typename SetState>
2925 detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
2926     return {std::forward<GetState>(g), std::forward<SetState>(s)};
2927 }
2928 
2929 PYBIND11_NAMESPACE_BEGIN(detail)
2930 
2931 inline str enum_name(handle arg) {
2932     dict entries = type::handle_of(arg).attr("__entries");
2933     for (auto kv : entries) {
2934         if (handle(kv.second[int_(0)]).equal(arg)) {
2935             return pybind11::str(kv.first);
2936         }
2937     }
2938     return "???";
2939 }
2940 
2941 struct enum_base {
2942     enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) {}
2943 
2944     PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
2945         m_base.attr("__entries") = dict();
2946         auto property = handle(reinterpret_cast<PyObject *>(&PyProperty_Type));
2947         auto static_property
2948             = handle(reinterpret_cast<PyObject *>(get_internals().static_property_type));
2949 
2950         m_base.attr("__repr__") = cpp_function(
2951             [](const object &arg) -> str {
2952                 handle type = type::handle_of(arg);
2953                 object type_name = type.attr("__name__");
2954                 return pybind11::str("<{}.{}: {}>")
2955                     .format(std::move(type_name), enum_name(arg), int_(arg));
2956             },
2957             name("__repr__"),
2958             is_method(m_base),
2959             pos_only());
2960 
2961         m_base.attr("name")
2962             = property(cpp_function(&enum_name, name("name"), is_method(m_base), pos_only()));
2963 
2964         m_base.attr("__str__") = cpp_function(
2965             [](handle arg) -> str {
2966                 object type_name = type::handle_of(arg).attr("__name__");
2967                 return pybind11::str("{}.{}").format(std::move(type_name), enum_name(arg));
2968             },
2969             name("__str__"),
2970             is_method(m_base),
2971             pos_only());
2972 
2973         if (options::show_enum_members_docstring()) {
2974             m_base.attr("__doc__") = static_property(
2975                 cpp_function(
2976                     [](handle arg) -> std::string {
2977                         std::string docstring;
2978                         dict entries = arg.attr("__entries");
2979                         if ((reinterpret_cast<PyTypeObject *>(arg.ptr()))->tp_doc) {
2980                             docstring += std::string(
2981                                 reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);
2982                             docstring += "\n\n";
2983                         }
2984                         docstring += "Members:";
2985                         for (auto kv : entries) {
2986                             auto key = std::string(pybind11::str(kv.first));
2987                             auto comment = kv.second[int_(1)];
2988                             docstring += "\n\n  ";
2989                             docstring += key;
2990                             if (!comment.is_none()) {
2991                                 docstring += " : ";
2992                                 docstring += pybind11::str(comment).cast<std::string>();
2993                             }
2994                         }
2995                         return docstring;
2996                     },
2997                     name("__doc__")),
2998                 none(),
2999                 none(),
3000                 "");
3001         }
3002 
3003         m_base.attr("__members__") = static_property(cpp_function(
3004                                                          [](handle arg) -> dict {
3005                                                              dict entries = arg.attr("__entries"),
3006                                                                   m;
3007                                                              for (auto kv : entries) {
3008                                                                  m[kv.first] = kv.second[int_(0)];
3009                                                              }
3010                                                              return m;
3011                                                          },
3012                                                          name("__members__")),
3013                                                      none(),
3014                                                      none(),
3015                                                      "");
3016 
3017 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)                                        \
3018     m_base.attr(op) = cpp_function(                                                               \
3019         [](const object &a, const object &b) {                                                    \
3020             if (!type::handle_of(a).is(type::handle_of(b)))                                       \
3021                 strict_behavior; /* NOLINT(bugprone-macro-parentheses) */                         \
3022             return expr;                                                                          \
3023         },                                                                                        \
3024         name(op),                                                                                 \
3025         is_method(m_base),                                                                        \
3026         arg("other"),                                                                             \
3027         pos_only())
3028 
3029 #define PYBIND11_ENUM_OP_CONV(op, expr)                                                           \
3030     m_base.attr(op) = cpp_function(                                                               \
3031         [](const object &a_, const object &b_) {                                                  \
3032             int_ a(a_), b(b_);                                                                    \
3033             return expr;                                                                          \
3034         },                                                                                        \
3035         name(op),                                                                                 \
3036         is_method(m_base),                                                                        \
3037         arg("other"),                                                                             \
3038         pos_only())
3039 
3040 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr)                                                       \
3041     m_base.attr(op) = cpp_function(                                                               \
3042         [](const object &a_, const object &b) {                                                   \
3043             int_ a(a_);                                                                           \
3044             return expr;                                                                          \
3045         },                                                                                        \
3046         name(op),                                                                                 \
3047         is_method(m_base),                                                                        \
3048         arg("other"),                                                                             \
3049         pos_only())
3050 
3051         if (is_convertible) {
3052             PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
3053             PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
3054 
3055             if (is_arithmetic) {
3056                 PYBIND11_ENUM_OP_CONV("__lt__", a < b);
3057                 PYBIND11_ENUM_OP_CONV("__gt__", a > b);
3058                 PYBIND11_ENUM_OP_CONV("__le__", a <= b);
3059                 PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
3060                 PYBIND11_ENUM_OP_CONV("__and__", a & b);
3061                 PYBIND11_ENUM_OP_CONV("__rand__", a & b);
3062                 PYBIND11_ENUM_OP_CONV("__or__", a | b);
3063                 PYBIND11_ENUM_OP_CONV("__ror__", a | b);
3064                 PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
3065                 PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
3066                 m_base.attr("__invert__")
3067                     = cpp_function([](const object &arg) { return ~(int_(arg)); },
3068                                    name("__invert__"),
3069                                    is_method(m_base),
3070                                    pos_only());
3071             }
3072         } else {
3073             PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
3074             PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
3075 
3076             if (is_arithmetic) {
3077 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
3078                 PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
3079                 PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
3080                 PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
3081                 PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
3082 #undef PYBIND11_THROW
3083             }
3084         }
3085 
3086 #undef PYBIND11_ENUM_OP_CONV_LHS
3087 #undef PYBIND11_ENUM_OP_CONV
3088 #undef PYBIND11_ENUM_OP_STRICT
3089 
3090         m_base.attr("__getstate__") = cpp_function([](const object &arg) { return int_(arg); },
3091                                                    name("__getstate__"),
3092                                                    is_method(m_base),
3093                                                    pos_only());
3094 
3095         m_base.attr("__hash__") = cpp_function([](const object &arg) { return int_(arg); },
3096                                                name("__hash__"),
3097                                                is_method(m_base),
3098                                                pos_only());
3099     }
3100 
3101     PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc = nullptr) {
3102         dict entries = m_base.attr("__entries");
3103         str name(name_);
3104         if (entries.contains(name)) {
3105             std::string type_name = std::string(str(m_base.attr("__name__")));
3106             throw value_error(std::move(type_name) + ": element \"" + std::string(name_)
3107                               + "\" already exists!");
3108         }
3109 
3110         entries[name] = pybind11::make_tuple(value, doc);
3111         m_base.attr(std::move(name)) = std::move(value);
3112     }
3113 
3114     PYBIND11_NOINLINE void export_values() {
3115         dict entries = m_base.attr("__entries");
3116         for (auto kv : entries) {
3117             m_parent.attr(kv.first) = kv.second[int_(0)];
3118         }
3119     }
3120 
3121     handle m_base;
3122     handle m_parent;
3123 };
3124 
3125 template <bool is_signed, size_t length>
3126 struct equivalent_integer {};
3127 template <>
3128 struct equivalent_integer<true, 1> {
3129     using type = int8_t;
3130 };
3131 template <>
3132 struct equivalent_integer<false, 1> {
3133     using type = uint8_t;
3134 };
3135 template <>
3136 struct equivalent_integer<true, 2> {
3137     using type = int16_t;
3138 };
3139 template <>
3140 struct equivalent_integer<false, 2> {
3141     using type = uint16_t;
3142 };
3143 template <>
3144 struct equivalent_integer<true, 4> {
3145     using type = int32_t;
3146 };
3147 template <>
3148 struct equivalent_integer<false, 4> {
3149     using type = uint32_t;
3150 };
3151 template <>
3152 struct equivalent_integer<true, 8> {
3153     using type = int64_t;
3154 };
3155 template <>
3156 struct equivalent_integer<false, 8> {
3157     using type = uint64_t;
3158 };
3159 
3160 template <typename IntLike>
3161 using equivalent_integer_t =
3162     typename equivalent_integer<std::is_signed<IntLike>::value, sizeof(IntLike)>::type;
3163 
3164 PYBIND11_NAMESPACE_END(detail)
3165 
3166 /// Binds C++ enumerations and enumeration classes to Python
3167 template <typename Type>
3168 class enum_ : public class_<Type> {
3169 public:
3170     using Base = class_<Type>;
3171     using Base::attr;
3172     using Base::def;
3173     using Base::def_property_readonly;
3174     using Base::def_property_readonly_static;
3175     using Underlying = typename std::underlying_type<Type>::type;
3176     // Scalar is the integer representation of underlying type
3177     using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
3178                                                         std::is_same<Underlying, bool>>::value,
3179                                          detail::equivalent_integer_t<Underlying>,
3180                                          Underlying>;
3181 
3182     template <typename... Extra>
3183     enum_(const handle &scope, const char *name, const Extra &...extra)
3184         : class_<Type>(scope, name, extra...), m_base(*this, scope) {
3185         {
3186             if (detail::global_internals_native_enum_type_map_contains(
3187                     std::type_index(typeid(Type)))) {
3188                 pybind11_fail("pybind11::enum_ \"" + std::string(name)
3189                               + "\" is already registered as a pybind11::native_enum!");
3190             }
3191         }
3192 
3193         constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
3194         constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
3195         m_base.init(is_arithmetic, is_convertible);
3196 
3197         def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
3198         def_property_readonly("value", [](Type value) { return (Scalar) value; }, pos_only());
3199         def("__int__", [](Type value) { return (Scalar) value; }, pos_only());
3200         def("__index__", [](Type value) { return (Scalar) value; }, pos_only());
3201         attr("__setstate__") = cpp_function(
3202             [](detail::value_and_holder &v_h, Scalar arg) {
3203                 detail::initimpl::setstate<Base>(
3204                     v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type);
3205             },
3206             detail::is_new_style_constructor(),
3207             pybind11::name("__setstate__"),
3208             is_method(*this),
3209             arg("state"),
3210             pos_only());
3211     }
3212 
3213     /// Export enumeration entries into the parent scope
3214     enum_ &export_values() {
3215         m_base.export_values();
3216         return *this;
3217     }
3218 
3219     /// Add an enumeration entry
3220     enum_ &value(char const *name, Type value, const char *doc = nullptr) {
3221         m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
3222         return *this;
3223     }
3224 
3225 private:
3226     detail::enum_base m_base;
3227 };
3228 
3229 PYBIND11_NAMESPACE_BEGIN(detail)
3230 
3231 PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient) {
3232     if (!nurse || !patient) {
3233         pybind11_fail("Could not activate keep_alive!");
3234     }
3235 
3236     if (patient.is_none() || nurse.is_none()) {
3237         return; /* Nothing to keep alive or nothing to be kept alive by */
3238     }
3239 
3240     auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
3241     if (!tinfo.empty()) {
3242         /* It's a pybind-registered type, so we can store the patient in the
3243          * internal list. */
3244         add_patient(nurse.ptr(), patient.ptr());
3245     } else {
3246         /* Fall back to clever approach based on weak references taken from
3247          * Boost.Python. This is not used for pybind-registered types because
3248          * the objects can be destroyed out-of-order in a GC pass. */
3249         cpp_function disable_lifesupport([patient](handle weakref) {
3250             patient.dec_ref();
3251             weakref.dec_ref();
3252         });
3253 
3254         weakref wr(nurse, disable_lifesupport);
3255 
3256         patient.inc_ref(); /* reference patient and leak the weak reference */
3257         (void) wr.release();
3258     }
3259 }
3260 
3261 PYBIND11_NOINLINE void
3262 keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
3263     auto get_arg = [&](size_t n) {
3264         if (n == 0) {
3265             return ret;
3266         }
3267         if (n == 1 && call.init_self) {
3268             return call.init_self;
3269         }
3270         if (n <= call.args.size()) {
3271             return call.args[n - 1];
3272         }
3273         return handle();
3274     };
3275 
3276     keep_alive_impl(get_arg(Nurse), get_arg(Patient));
3277 }
3278 
3279 inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
3280 all_type_info_get_cache(PyTypeObject *type) {
3281     auto res = with_internals([type](internals &internals) {
3282         auto ins = internals
3283                        .registered_types_py
3284 #ifdef __cpp_lib_unordered_map_try_emplace
3285                        .try_emplace(type);
3286 #else
3287                        .emplace(type, std::vector<detail::type_info *>());
3288 #endif
3289         if (ins.second) {
3290             // For free-threading mode, this call must be under
3291             // the with_internals() mutex lock, to avoid that other threads
3292             // continue running with the empty ins.first->second.
3293             all_type_info_populate(type, ins.first->second);
3294         }
3295         return ins;
3296     });
3297     if (res.second) {
3298         // New cache entry created; set up a weak reference to automatically remove it if the type
3299         // gets destroyed:
3300         weakref(reinterpret_cast<PyObject *>(type), cpp_function([type](handle wr) {
3301                     with_internals([type](internals &internals) {
3302                         internals.registered_types_py.erase(type);
3303 
3304                         // TODO consolidate the erasure code in pybind11_meta_dealloc() in class.h
3305                         auto &cache = internals.inactive_override_cache;
3306                         for (auto it = cache.begin(), last = cache.end(); it != last;) {
3307                             if (it->first == reinterpret_cast<PyObject *>(type)) {
3308                                 it = cache.erase(it);
3309                             } else {
3310                                 ++it;
3311                             }
3312                         }
3313                     });
3314 
3315                     wr.dec_ref();
3316                 }))
3317             .release();
3318     }
3319 
3320     return res;
3321 }
3322 
3323 /* There are a large number of apparently unused template arguments because
3324  * each combination requires a separate py::class_ registration.
3325  */
3326 template <typename Access,
3327           return_value_policy Policy,
3328           typename Iterator,
3329           typename Sentinel,
3330           typename ValueType,
3331           typename... Extra>
3332 struct iterator_state {
3333     Iterator it;
3334     Sentinel end;
3335     bool first_or_done;
3336 };
3337 
3338 // Note: these helpers take the iterator by non-const reference because some
3339 // iterators in the wild can't be dereferenced when const. The & after Iterator
3340 // is required for MSVC < 16.9. SFINAE cannot be reused for result_type due to
3341 // bugs in ICC, NVCC, and PGI compilers. See PR #3293.
3342 template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
3343 struct iterator_access {
3344     using result_type = decltype(*std::declval<Iterator &>());
3345     // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
3346     result_type operator()(Iterator &it) const { return *it; }
3347 };
3348 
3349 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).first)>
3350 class iterator_key_access {
3351 private:
3352     using pair_type = decltype(*std::declval<Iterator &>());
3353 
3354 public:
3355     /* If either the pair itself or the element of the pair is a reference, we
3356      * want to return a reference, otherwise a value. When the decltype
3357      * expression is parenthesized it is based on the value category of the
3358      * expression; otherwise it is the declared type of the pair member.
3359      * The use of declval<pair_type> in the second branch rather than directly
3360      * using *std::declval<Iterator &>() is a workaround for nvcc
3361      * (it's not used in the first branch because going via decltype and back
3362      * through declval does not perfectly preserve references).
3363      */
3364     using result_type
3365         = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
3366                         decltype(((*std::declval<Iterator &>()).first)),
3367                         decltype(std::declval<pair_type>().first)>;
3368     result_type operator()(Iterator &it) const { return (*it).first; }
3369 };
3370 
3371 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
3372 class iterator_value_access {
3373 private:
3374     using pair_type = decltype(*std::declval<Iterator &>());
3375 
3376 public:
3377     using result_type
3378         = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
3379                         decltype(((*std::declval<Iterator &>()).second)),
3380                         decltype(std::declval<pair_type>().second)>;
3381     result_type operator()(Iterator &it) const { return (*it).second; }
3382 };
3383 
3384 template <typename Access,
3385           return_value_policy Policy,
3386           typename Iterator,
3387           typename Sentinel,
3388           typename ValueType,
3389           typename... Extra>
3390 // NOLINTNEXTLINE(performance-unnecessary-value-param)
3391 iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra) {
3392     using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
3393     // TODO: state captures only the types of Extra, not the values
3394 
3395     // For Python < 3.14.0rc1, pycritical_section uses direct mutex locking (same as a unique
3396     // lock), which may deadlock during type registration. See detail/internals.h for details.
3397 #if PY_VERSION_HEX >= 0x030E00C1 // 3.14.0rc1
3398     PYBIND11_LOCK_INTERNALS(get_internals());
3399 #endif
3400     if (!detail::get_type_info(typeid(state), false)) {
3401         class_<state>(handle(), "iterator", pybind11::module_local())
3402             .def(
3403                 "__iter__", [](state &s) -> state & { return s; }, pos_only())
3404             .def(
3405                 "__next__",
3406                 [](state &s) -> ValueType {
3407                     if (!s.first_or_done) {
3408                         ++s.it;
3409                     } else {
3410                         s.first_or_done = false;
3411                     }
3412                     if (s.it == s.end) {
3413                         s.first_or_done = true;
3414                         throw stop_iteration();
3415                     }
3416                     return Access()(s.it);
3417                     // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
3418                 },
3419                 std::forward<Extra>(extra)...,
3420                 pos_only(),
3421                 Policy);
3422     }
3423 
3424     return cast(state{std::forward<Iterator>(first), std::forward<Sentinel>(last), true});
3425 }
3426 
3427 PYBIND11_NAMESPACE_END(detail)
3428 
3429 /// Makes a python iterator from a first and past-the-end C++ InputIterator.
3430 template <return_value_policy Policy = return_value_policy::reference_internal,
3431           typename Iterator,
3432           typename Sentinel,
3433           typename ValueType = typename detail::iterator_access<Iterator>::result_type,
3434           typename... Extra>
3435 // NOLINTNEXTLINE(performance-unnecessary-value-param)
3436 typing::Iterator<ValueType> make_iterator(Iterator first, Sentinel last, Extra &&...extra) {
3437     return detail::make_iterator_impl<detail::iterator_access<Iterator>,
3438                                       Policy,
3439                                       Iterator,
3440                                       Sentinel,
3441                                       ValueType,
3442                                       Extra...>(std::forward<Iterator>(first),
3443                                                 std::forward<Sentinel>(last),
3444                                                 std::forward<Extra>(extra)...);
3445 }
3446 
3447 /// Makes a python iterator over the keys (`.first`) of a iterator over pairs from a
3448 /// first and past-the-end InputIterator.
3449 template <return_value_policy Policy = return_value_policy::reference_internal,
3450           typename Iterator,
3451           typename Sentinel,
3452           typename KeyType = typename detail::iterator_key_access<Iterator>::result_type,
3453           typename... Extra>
3454 typing::Iterator<KeyType> make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) {
3455     return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
3456                                       Policy,
3457                                       Iterator,
3458                                       Sentinel,
3459                                       KeyType,
3460                                       Extra...>(std::forward<Iterator>(first),
3461                                                 std::forward<Sentinel>(last),
3462                                                 std::forward<Extra>(extra)...);
3463 }
3464 
3465 /// Makes a python iterator over the values (`.second`) of a iterator over pairs from a
3466 /// first and past-the-end InputIterator.
3467 template <return_value_policy Policy = return_value_policy::reference_internal,
3468           typename Iterator,
3469           typename Sentinel,
3470           typename ValueType = typename detail::iterator_value_access<Iterator>::result_type,
3471           typename... Extra>
3472 typing::Iterator<ValueType> make_value_iterator(Iterator first, Sentinel last, Extra &&...extra) {
3473     return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
3474                                       Policy,
3475                                       Iterator,
3476                                       Sentinel,
3477                                       ValueType,
3478                                       Extra...>(std::forward<Iterator>(first),
3479                                                 std::forward<Sentinel>(last),
3480                                                 std::forward<Extra>(extra)...);
3481 }
3482 
3483 /// Makes an iterator over values of an stl container or other container supporting
3484 /// `std::begin()`/`std::end()`
3485 template <return_value_policy Policy = return_value_policy::reference_internal,
3486           typename Type,
3487           typename ValueType = typename detail::iterator_access<
3488               decltype(std::begin(std::declval<Type &>()))>::result_type,
3489           typename... Extra>
3490 typing::Iterator<ValueType> make_iterator(Type &value, Extra &&...extra) {
3491     return make_iterator<Policy>(
3492         std::begin(value), std::end(value), std::forward<Extra>(extra)...);
3493 }
3494 
3495 /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
3496 /// `std::begin()`/`std::end()`
3497 template <return_value_policy Policy = return_value_policy::reference_internal,
3498           typename Type,
3499           typename KeyType = typename detail::iterator_key_access<
3500               decltype(std::begin(std::declval<Type &>()))>::result_type,
3501           typename... Extra>
3502 typing::Iterator<KeyType> make_key_iterator(Type &value, Extra &&...extra) {
3503     return make_key_iterator<Policy>(
3504         std::begin(value), std::end(value), std::forward<Extra>(extra)...);
3505 }
3506 
3507 /// Makes an iterator over the values (`.second`) of a stl map-like container supporting
3508 /// `std::begin()`/`std::end()`
3509 template <return_value_policy Policy = return_value_policy::reference_internal,
3510           typename Type,
3511           typename ValueType = typename detail::iterator_value_access<
3512               decltype(std::begin(std::declval<Type &>()))>::result_type,
3513           typename... Extra>
3514 typing::Iterator<ValueType> make_value_iterator(Type &value, Extra &&...extra) {
3515     return make_value_iterator<Policy>(
3516         std::begin(value), std::end(value), std::forward<Extra>(extra)...);
3517 }
3518 
3519 template <typename InputType, typename OutputType>
3520 void implicitly_convertible() {
3521     struct set_flag {
3522         bool &flag;
3523         explicit set_flag(bool &flag_) : flag(flag_) { flag_ = true; }
3524         ~set_flag() { flag = false; }
3525 
3526         // Prevent copying/moving to ensure RAII guard is used safely
3527         set_flag(const set_flag &) = delete;
3528         set_flag(set_flag &&) = delete;
3529         set_flag &operator=(const set_flag &) = delete;
3530         set_flag &operator=(set_flag &&) = delete;
3531     };
3532     auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
3533         thread_local bool currently_used = false;
3534         if (currently_used) { // implicit conversions are non-reentrant
3535             return nullptr;
3536         }
3537         set_flag flag_helper(currently_used);
3538         if (!detail::make_caster<InputType>().load(obj, false)) {
3539             return nullptr;
3540         }
3541         tuple args(1);
3542         args[0] = obj;
3543         PyObject *result = PyObject_Call(reinterpret_cast<PyObject *>(type), args.ptr(), nullptr);
3544         if (result == nullptr) {
3545             PyErr_Clear();
3546         }
3547         return result;
3548     };
3549 
3550     if (auto *tinfo = detail::get_type_info(typeid(OutputType))) {
3551         tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
3552     } else {
3553         pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
3554     }
3555 }
3556 
3557 inline void register_exception_translator(ExceptionTranslator &&translator) {
3558     detail::with_exception_translators(
3559         [&](std::forward_list<ExceptionTranslator> &exception_translators,
3560             std::forward_list<ExceptionTranslator> &local_exception_translators) {
3561             (void) local_exception_translators;
3562             exception_translators.push_front(std::forward<ExceptionTranslator>(translator));
3563         });
3564 }
3565 
3566 /**
3567  * Add a new module-local exception translator. Locally registered functions
3568  * will be tried before any globally registered exception translators, which
3569  * will only be invoked if the module-local handlers do not deal with
3570  * the exception.
3571  */
3572 inline void register_local_exception_translator(ExceptionTranslator &&translator) {
3573     detail::with_exception_translators(
3574         [&](std::forward_list<ExceptionTranslator> &exception_translators,
3575             std::forward_list<ExceptionTranslator> &local_exception_translators) {
3576             (void) exception_translators;
3577             local_exception_translators.push_front(std::forward<ExceptionTranslator>(translator));
3578         });
3579 }
3580 
3581 /**
3582  * Wrapper to generate a new Python exception type.
3583  *
3584  * This should only be used with py::set_error() for now.
3585  * It is not (yet) possible to use as a py::base.
3586  * Template type argument is reserved for future use.
3587  */
3588 template <typename type>
3589 class exception : public object {
3590 public:
3591     exception() = default;
3592     exception(handle scope, const char *name, handle base = PyExc_Exception) {
3593         std::string full_name
3594             = scope.attr("__name__").cast<std::string>() + std::string(".") + name;
3595         m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), nullptr);
3596         if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name)) {
3597             pybind11_fail("Error during initialization: multiple incompatible "
3598                           "definitions with name \""
3599                           + std::string(name) + "\"");
3600         }
3601         scope.attr(name) = *this;
3602     }
3603 
3604     // Sets the current python exception to this exception object with the given message
3605     PYBIND11_DEPRECATED("Please use py::set_error() instead "
3606                         "(https://github.com/pybind/pybind11/pull/4772)")
3607     void operator()(const char *message) const { set_error(*this, message); }
3608 };
3609 
3610 PYBIND11_NAMESPACE_BEGIN(detail)
3611 
3612 template <>
3613 struct handle_type_name<exception<void>> {
3614     static constexpr auto name = const_name("Exception");
3615 };
3616 
3617 // Helper function for register_exception and register_local_exception
3618 template <typename CppException>
3619 exception<CppException> &
3620 register_exception_impl(handle scope, const char *name, handle base, bool isLocal) {
3621     PYBIND11_CONSTINIT static gil_safe_call_once_and_store<exception<CppException>> exc_storage;
3622     exc_storage.call_once_and_store_result(
3623         [&]() { return exception<CppException>(scope, name, base); });
3624 
3625     auto register_func
3626         = isLocal ? &register_local_exception_translator : &register_exception_translator;
3627 
3628     register_func([](std::exception_ptr p) {
3629         if (!p) {
3630             return;
3631         }
3632         try {
3633             std::rethrow_exception(p);
3634         } catch (const CppException &e) {
3635             set_error(exc_storage.get_stored(), e.what());
3636         }
3637     });
3638     return exc_storage.get_stored();
3639 }
3640 
3641 PYBIND11_NAMESPACE_END(detail)
3642 
3643 /**
3644  * Registers a Python exception in `m` of the given `name` and installs a translator to
3645  * translate the C++ exception to the created Python exception using the what() method.
3646  * This is intended for simple exception translations; for more complex translation, register the
3647  * exception object and translator directly.
3648  */
3649 template <typename CppException>
3650 exception<CppException> &
3651 register_exception(handle scope, const char *name, handle base = PyExc_Exception) {
3652     return detail::register_exception_impl<CppException>(scope, name, base, false /* isLocal */);
3653 }
3654 
3655 /**
3656  * Registers a Python exception in `m` of the given `name` and installs a translator to
3657  * translate the C++ exception to the created Python exception using the what() method.
3658  * This translator will only be used for exceptions that are thrown in this module and will be
3659  * tried before global exception translators, including those registered with register_exception.
3660  * This is intended for simple exception translations; for more complex translation, register the
3661  * exception object and translator directly.
3662  */
3663 template <typename CppException>
3664 exception<CppException> &
3665 register_local_exception(handle scope, const char *name, handle base = PyExc_Exception) {
3666     return detail::register_exception_impl<CppException>(scope, name, base, true /* isLocal */);
3667 }
3668 
3669 PYBIND11_NAMESPACE_BEGIN(detail)
3670 PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) {
3671     auto strings = tuple(args.size());
3672     for (size_t i = 0; i < args.size(); ++i) {
3673         strings[i] = str(args[i]);
3674     }
3675     auto sep = kwargs.contains("sep") ? kwargs["sep"] : str(" ");
3676     auto line = sep.attr("join")(std::move(strings));
3677 
3678     object file;
3679     if (kwargs.contains("file")) {
3680         file = kwargs["file"].cast<object>();
3681     } else {
3682         try {
3683             file = module_::import("sys").attr("stdout");
3684         } catch (const error_already_set &) {
3685             /* If print() is called from code that is executed as
3686                part of garbage collection during interpreter shutdown,
3687                importing 'sys' can fail. Give up rather than crashing the
3688                interpreter in this case. */
3689             return;
3690         }
3691     }
3692 
3693     auto write = file.attr("write");
3694     write(std::move(line));
3695     write(kwargs.contains("end") ? kwargs["end"] : str("\n"));
3696 
3697     if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) {
3698         file.attr("flush")();
3699     }
3700 }
3701 PYBIND11_NAMESPACE_END(detail)
3702 
3703 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
3704 void print(Args &&...args) {
3705     auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
3706     detail::print(c.args(), c.kwargs());
3707 }
3708 
3709 inline void
3710 error_already_set::m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr) {
3711     gil_scoped_acquire gil;
3712     error_scope scope;
3713     delete raw_ptr;
3714 }
3715 
3716 inline const char *error_already_set::what() const noexcept {
3717     gil_scoped_acquire gil;
3718     error_scope scope;
3719     return m_fetched_error->error_string().c_str();
3720 }
3721 
3722 PYBIND11_NAMESPACE_BEGIN(detail)
3723 
3724 inline function
3725 get_type_override(const void *this_ptr, const type_info *this_type, const char *name) {
3726     handle self = get_object_handle(this_ptr, this_type);
3727     if (!self) {
3728         return function();
3729     }
3730     handle type = type::handle_of(self);
3731     auto key = std::make_pair(type.ptr(), name);
3732 
3733     /* Cache functions that aren't overridden in Python to avoid
3734        many costly Python dictionary lookups below */
3735     bool not_overridden = with_internals([&key](internals &internals) {
3736         auto &cache = internals.inactive_override_cache;
3737         return cache.find(key) != cache.end();
3738     });
3739     if (not_overridden) {
3740         return function();
3741     }
3742 
3743     function override = getattr(self, name, function());
3744     if (override.is_cpp_function()) {
3745         with_internals([&](internals &internals) {
3746             internals.inactive_override_cache.insert(std::move(key));
3747         });
3748         return function();
3749     }
3750 
3751     /* Don't call dispatch code if invoked from overridden function.
3752        Unfortunately this doesn't work on PyPy and GraalPy. */
3753 #if !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON)
3754 #    if PY_VERSION_HEX >= 0x03090000
3755     PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
3756     if (frame != nullptr) {
3757         PyCodeObject *f_code = PyFrame_GetCode(frame);
3758         // f_code is guaranteed to not be NULL
3759         if (std::string(str(f_code->co_name)) == name && f_code->co_argcount > 0) {
3760 #        if PY_VERSION_HEX >= 0x030d0000
3761             PyObject *locals = PyEval_GetFrameLocals();
3762 #        else
3763             PyObject *locals = PyEval_GetLocals();
3764             Py_XINCREF(locals);
3765 #        endif
3766             if (locals != nullptr) {
3767 #        if PY_VERSION_HEX >= 0x030b0000
3768                 PyObject *co_varnames = PyCode_GetVarnames(f_code);
3769 #        else
3770                 PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code, "co_varnames");
3771 #        endif
3772                 PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
3773                 Py_DECREF(co_varnames);
3774                 PyObject *self_caller = dict_getitem(locals, self_arg);
3775                 Py_DECREF(locals);
3776                 if (self_caller == self.ptr()) {
3777                     Py_DECREF(f_code);
3778                     Py_DECREF(frame);
3779                     return function();
3780                 }
3781             }
3782         }
3783         Py_DECREF(f_code);
3784         Py_DECREF(frame);
3785     }
3786 #    else
3787     PyFrameObject *frame = PyThreadState_Get()->frame;
3788     if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name
3789         && frame->f_code->co_argcount > 0) {
3790         PyFrame_FastToLocals(frame);
3791         PyObject *self_caller
3792             = dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
3793         if (self_caller == self.ptr()) {
3794             return function();
3795         }
3796     }
3797 #    endif
3798 
3799 #else
3800     /* PyPy currently doesn't provide a detailed cpyext emulation of
3801        frame objects, so we have to emulate this using Python. This
3802        is going to be slow..*/
3803     dict d;
3804     d["self"] = self;
3805     d["name"] = pybind11::str(name);
3806     PyObject *result
3807         = PyRun_String("import inspect\n"
3808                        "frame = inspect.currentframe()\n"
3809                        "if frame is not None:\n"
3810                        "    frame = frame.f_back\n"
3811                        "    if frame is not None and str(frame.f_code.co_name) == name and "
3812                        "frame.f_code.co_argcount > 0:\n"
3813                        "        self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
3814                        "        if self_caller == self:\n"
3815                        "            self = None\n",
3816                        Py_file_input,
3817                        d.ptr(),
3818                        d.ptr());
3819     if (result == nullptr)
3820         throw error_already_set();
3821     Py_DECREF(result);
3822     if (d["self"].is_none())
3823         return function();
3824 #endif
3825 
3826     return override;
3827 }
3828 PYBIND11_NAMESPACE_END(detail)
3829 
3830 /** \rst
3831   Try to retrieve a python method by the provided name from the instance pointed to by the
3832   this_ptr.
3833 
3834   :this_ptr: The pointer to the object the overridden method should be retrieved for. This should
3835              be the first non-trampoline class encountered in the inheritance chain.
3836   :name: The name of the overridden Python method to retrieve.
3837   :return: The Python method by this name from the object or an empty function wrapper.
3838  \endrst */
3839 template <class T>
3840 function get_override(const T *this_ptr, const char *name) {
3841     auto *tinfo = detail::get_type_info(typeid(T));
3842     return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
3843 }
3844 
3845 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...)                                        \
3846     do {                                                                                          \
3847         pybind11::gil_scoped_acquire gil;                                                         \
3848         pybind11::function override                                                               \
3849             = pybind11::get_override(static_cast<const cname *>(this), name);                     \
3850         if (override) {                                                                           \
3851             auto o = override(__VA_ARGS__);                                                       \
3852             PYBIND11_WARNING_PUSH                                                                 \
3853             PYBIND11_WARNING_DISABLE_MSVC(4127)                                                   \
3854             if PYBIND11_MAYBE_CONSTEXPR (                                                         \
3855                 pybind11::detail::cast_is_temporary_value_reference<ret_type>::value              \
3856                 && !pybind11::detail::is_same_ignoring_cvref<ret_type, PyObject *>::value) {      \
3857                 static pybind11::detail::override_caster_t<ret_type> caster;                      \
3858                 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster);                \
3859             } else {                                                                              \
3860                 return pybind11::detail::cast_safe<ret_type>(std::move(o));                       \
3861             }                                                                                     \
3862             PYBIND11_WARNING_POP                                                                  \
3863         }                                                                                         \
3864     } while (false)
3865 
3866 /** \rst
3867     Macro to populate the virtual method in the trampoline class. This macro tries to look up a
3868     method named 'fn' from the Python side, deals with the :ref:`gil` and necessary argument
3869     conversions to call this method and return the appropriate type.
3870     See :ref:`overriding_virtuals` for more information. This macro should be used when the method
3871     name in C is not the same as the method name in Python. For example with `__str__`.
3872 
3873     .. code-block:: cpp
3874 
3875       std::string toString() override {
3876         PYBIND11_OVERRIDE_NAME(
3877             std::string, // Return type (ret_type)
3878             Animal,      // Parent class (cname)
3879             "__str__",   // Name of method in Python (name)
3880             toString,    // Name of function in C++ (fn)
3881         );
3882       }
3883 \endrst */
3884 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...)                                    \
3885     do {                                                                                          \
3886         PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
3887         return cname::fn(__VA_ARGS__);                                                            \
3888     } while (false)
3889 
3890 /** \rst
3891     Macro for pure virtual functions, this function is identical to
3892     :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it throws if no override can be found.
3893 \endrst */
3894 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...)                               \
3895     do {                                                                                          \
3896         PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
3897         pybind11::pybind11_fail(                                                                  \
3898             "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\"");   \
3899     } while (false)
3900 
3901 /** \rst
3902     Macro to populate the virtual method in the trampoline class. This macro tries to look up the
3903     method from the Python side, deals with the :ref:`gil` and necessary argument conversions to
3904     call this method and return the appropriate type. This macro should be used if the method name
3905     in C and in Python are identical.
3906     See :ref:`overriding_virtuals` for more information.
3907 
3908     .. code-block:: cpp
3909 
3910       class PyAnimal : public Animal {
3911       public:
3912           // Inherit the constructors
3913           using Animal::Animal;
3914 
3915           // Trampoline (need one for each virtual function)
3916           std::string go(int n_times) override {
3917               PYBIND11_OVERRIDE_PURE(
3918                   std::string, // Return type (ret_type)
3919                   Animal,      // Parent class (cname)
3920                   go,          // Name of function in C++ (must match Python name) (fn)
3921                   n_times      // Argument(s) (...)
3922               );
3923           }
3924       };
3925 \endrst */
3926 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...)                                               \
3927     PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
3928 
3929 /** \rst
3930     Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`,
3931     except that it throws if no override can be found.
3932 \endrst */
3933 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...)                                          \
3934     PYBIND11_OVERRIDE_PURE_NAME(                                                                  \
3935         PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
3936 
3937 // Deprecated versions
3938 
3939 PYBIND11_DEPRECATED("get_type_overload has been deprecated")
3940 inline function
3941 get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
3942     return detail::get_type_override(this_ptr, this_type, name);
3943 }
3944 
3945 template <class T>
3946 inline function get_overload(const T *this_ptr, const char *name) {
3947     return get_override(this_ptr, name);
3948 }
3949 
3950 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...)                                         \
3951     PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
3952 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...)                                    \
3953     PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
3954 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...)                               \
3955     PYBIND11_OVERRIDE_PURE_NAME(                                                                  \
3956         PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
3957 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...)                                               \
3958     PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
3959 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...)                                          \
3960     PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
3961 
3962 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)