Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-09-12 09:20:27

0001 /*
0002     pybind11/cast.h: Partial template specializations to cast between
0003     C++ and Python types
0004 
0005     Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
0006 
0007     All rights reserved. Use of this source code is governed by a
0008     BSD-style license that can be found in the LICENSE file.
0009 */
0010 
0011 #pragma once
0012 
0013 #include "detail/argument_vector.h"
0014 #include "detail/common.h"
0015 #include "detail/descr.h"
0016 #include "detail/holder_caster_foreign_helpers.h"
0017 #include "detail/native_enum_data.h"
0018 #include "detail/type_caster_base.h"
0019 #include "detail/typeid.h"
0020 #include "pytypes.h"
0021 
0022 #include <array>
0023 #include <cstring>
0024 #include <functional>
0025 #include <iosfwd>
0026 #include <iterator>
0027 #include <memory>
0028 #include <string>
0029 #include <tuple>
0030 #include <type_traits>
0031 #include <utility>
0032 #include <vector>
0033 
0034 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0035 
0036 PYBIND11_WARNING_DISABLE_MSVC(4127)
0037 
0038 PYBIND11_NAMESPACE_BEGIN(detail)
0039 
0040 template <typename type, typename SFINAE = void>
0041 class type_caster : public type_caster_base<type> {};
0042 template <typename type>
0043 using make_caster = type_caster<intrinsic_t<type>>;
0044 
0045 // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
0046 template <typename T>
0047 typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
0048     using result_t = typename make_caster<T>::template cast_op_type<T>; // See PR #4893
0049     return caster.operator result_t();
0050 }
0051 template <typename T>
0052 typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
0053 cast_op(make_caster<T> &&caster) {
0054     using result_t = typename make_caster<T>::template cast_op_type<
0055         typename std::add_rvalue_reference<T>::type>; // See PR #4893
0056     return std::move(caster).operator result_t();
0057 }
0058 
0059 template <typename EnumType>
0060 class type_caster_enum_type {
0061 private:
0062     using Underlying = typename std::underlying_type<EnumType>::type;
0063 
0064 public:
0065     static constexpr auto name = const_name<EnumType>();
0066 
0067     template <typename SrcType>
0068     static handle cast(SrcType &&src, return_value_policy, handle parent) {
0069         handle native_enum
0070             = global_internals_native_enum_type_map_get_item(std::type_index(typeid(EnumType)));
0071         if (native_enum) {
0072             return native_enum(static_cast<Underlying>(src)).release();
0073         }
0074         return type_caster_base<EnumType>::cast(
0075             std::forward<SrcType>(src),
0076             // Fixes https://github.com/pybind/pybind11/pull/3643#issuecomment-1022987818:
0077             return_value_policy::copy,
0078             parent);
0079     }
0080 
0081     template <typename SrcType>
0082     static handle cast(SrcType *src, return_value_policy policy, handle parent) {
0083         return cast(*src, policy, parent);
0084     }
0085 
0086     bool load(handle src, bool convert) {
0087         handle native_enum
0088             = global_internals_native_enum_type_map_get_item(std::type_index(typeid(EnumType)));
0089         if (native_enum) {
0090             if (!isinstance(src, native_enum)) {
0091                 return false;
0092             }
0093             type_caster<Underlying> underlying_caster;
0094             if (!underlying_caster.load(src.attr("value"), convert)) {
0095                 pybind11_fail("native_enum internal consistency failure.");
0096             }
0097             native_value = static_cast<EnumType>(static_cast<Underlying>(underlying_caster));
0098             native_loaded = true;
0099             return true;
0100         }
0101 
0102         type_caster_base<EnumType> legacy_caster;
0103         if (legacy_caster.load(src, convert)) {
0104             legacy_ptr = static_cast<EnumType *>(legacy_caster);
0105             return true;
0106         }
0107         return false;
0108     }
0109 
0110     template <typename T>
0111     using cast_op_type = detail::cast_op_type<T>;
0112 
0113     // NOLINTNEXTLINE(google-explicit-constructor)
0114     operator EnumType *() { return native_loaded ? &native_value : legacy_ptr; }
0115 
0116     // NOLINTNEXTLINE(google-explicit-constructor)
0117     operator EnumType &() {
0118         if (!native_loaded && !legacy_ptr) {
0119             throw reference_cast_error();
0120         }
0121         return native_loaded ? native_value : *legacy_ptr;
0122     }
0123 
0124 private:
0125     EnumType native_value; // if loading a py::native_enum
0126     bool native_loaded = false;
0127     EnumType *legacy_ptr = nullptr; // if loading a py::enum_
0128 };
0129 
0130 template <typename EnumType, typename SFINAE = void>
0131 struct type_caster_enum_type_enabled : std::true_type {};
0132 
0133 template <typename T>
0134 struct type_uses_type_caster_enum_type {
0135     static constexpr bool value
0136         = std::is_enum<T>::value && type_caster_enum_type_enabled<T>::value;
0137 };
0138 
0139 template <typename EnumType>
0140 class type_caster<EnumType, detail::enable_if_t<type_uses_type_caster_enum_type<EnumType>::value>>
0141     : public type_caster_enum_type<EnumType> {};
0142 
0143 template <typename T, detail::enable_if_t<std::is_enum<T>::value, int> = 0>
0144 bool isinstance_native_enum_impl(handle obj, const std::type_info &tp) {
0145     handle native_enum = global_internals_native_enum_type_map_get_item(tp);
0146     if (!native_enum) {
0147         return false;
0148     }
0149     return isinstance(obj, native_enum);
0150 }
0151 
0152 template <typename T, detail::enable_if_t<!std::is_enum<T>::value, int> = 0>
0153 bool isinstance_native_enum_impl(handle, const std::type_info &) {
0154     return false;
0155 }
0156 
0157 template <typename T>
0158 bool isinstance_native_enum(handle obj, const std::type_info &tp) {
0159     return isinstance_native_enum_impl<intrinsic_t<T>>(obj, tp);
0160 }
0161 
0162 template <typename type>
0163 class type_caster<std::reference_wrapper<type>> {
0164 private:
0165     using caster_t = make_caster<type>;
0166     caster_t subcaster;
0167     using reference_t = type &;
0168     using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
0169 
0170     static_assert(
0171         std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
0172             || std::is_same<reference_t, subcaster_cast_op_type>::value,
0173         "std::reference_wrapper<T> caster requires T to have a caster with an "
0174         "`operator T &()` or `operator const T &()`");
0175 
0176 public:
0177     bool load(handle src, bool convert) { return subcaster.load(src, convert); }
0178     static constexpr auto name = caster_t::name;
0179     static handle
0180     cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
0181         // It is definitely wrong to take ownership of this pointer, so mask that rvp
0182         if (policy == return_value_policy::take_ownership
0183             || policy == return_value_policy::automatic) {
0184             policy = return_value_policy::automatic_reference;
0185         }
0186         return caster_t::cast(&src.get(), policy, parent);
0187     }
0188     template <typename T>
0189     using cast_op_type = std::reference_wrapper<type>;
0190     explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
0191 };
0192 
0193 #define PYBIND11_TYPE_CASTER(type, py_name)                                                       \
0194 protected:                                                                                        \
0195     type value;                                                                                   \
0196                                                                                                   \
0197 public:                                                                                           \
0198     static constexpr auto name = py_name;                                                         \
0199     template <typename T_,                                                                        \
0200               ::pybind11::detail::enable_if_t<                                                    \
0201                   std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value,                 \
0202                   int>                                                                            \
0203               = 0>                                                                                \
0204     static ::pybind11::handle cast(                                                               \
0205         T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) {             \
0206         if (!src)                                                                                 \
0207             return ::pybind11::none().release();                                                  \
0208         if (policy == ::pybind11::return_value_policy::take_ownership) {                          \
0209             auto h = cast(std::move(*src), policy, parent);                                       \
0210             delete src;                                                                           \
0211             return h;                                                                             \
0212         }                                                                                         \
0213         return cast(*src, policy, parent);                                                        \
0214     }                                                                                             \
0215     operator type *() { return &value; }               /* NOLINT(bugprone-macro-parentheses) */   \
0216     operator type &() { return value; }                /* NOLINT(bugprone-macro-parentheses) */   \
0217     operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */   \
0218     template <typename T_>                                                                        \
0219     using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
0220 
0221 template <typename CharT>
0222 using is_std_char_type = any_of<std::is_same<CharT, char>, /* std::string */
0223 #if defined(PYBIND11_HAS_U8STRING)
0224                                 std::is_same<CharT, char8_t>, /* std::u8string */
0225 #endif
0226                                 std::is_same<CharT, char16_t>, /* std::u16string */
0227                                 std::is_same<CharT, char32_t>, /* std::u32string */
0228                                 std::is_same<CharT, wchar_t>   /* std::wstring */
0229                                 >;
0230 
0231 template <typename T>
0232 struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
0233     using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
0234     using _py_type_1 = conditional_t<std::is_signed<T>::value,
0235                                      _py_type_0,
0236                                      typename std::make_unsigned<_py_type_0>::type>;
0237     using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
0238 
0239 public:
0240     bool load(handle src, bool convert) {
0241         py_type py_value;
0242 
0243         if (!src) {
0244             return false;
0245         }
0246 
0247 #if !defined(PYPY_VERSION)
0248         auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
0249 #else
0250         // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
0251         // while CPython only considers the existence of `nb_index`/`__index__`.
0252         auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
0253 #endif
0254 
0255         if (std::is_floating_point<T>::value) {
0256             if (convert || PyFloat_Check(src.ptr())) {
0257                 py_value = (py_type) PyFloat_AsDouble(src.ptr());
0258             } else {
0259                 return false;
0260             }
0261         } else if (PyFloat_Check(src.ptr())
0262                    || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
0263             return false;
0264         } else {
0265             handle src_or_index = src;
0266             // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
0267 #if defined(PYPY_VERSION)
0268             object index;
0269             if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
0270                 index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
0271                 if (!index) {
0272                     PyErr_Clear();
0273                     if (!convert)
0274                         return false;
0275                 } else {
0276                     src_or_index = index;
0277                 }
0278             }
0279 #endif
0280             if (std::is_unsigned<py_type>::value) {
0281                 py_value = as_unsigned<py_type>(src_or_index.ptr());
0282             } else { // signed integer:
0283                 py_value = sizeof(T) <= sizeof(long)
0284                                ? (py_type) PyLong_AsLong(src_or_index.ptr())
0285                                : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
0286             }
0287         }
0288 
0289         // Python API reported an error
0290         bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
0291 
0292         // Check to see if the conversion is valid (integers should match exactly)
0293         // Signed/unsigned checks happen elsewhere
0294         if (py_err
0295             || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
0296                 && py_value != (py_type) (T) py_value)) {
0297             PyErr_Clear();
0298             if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
0299                 auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
0300                                                          ? PyNumber_Float(src.ptr())
0301                                                          : PyNumber_Long(src.ptr()));
0302                 PyErr_Clear();
0303                 return load(tmp, false);
0304             }
0305             return false;
0306         }
0307 
0308         value = (T) py_value;
0309         return true;
0310     }
0311 
0312     template <typename U = T>
0313     static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
0314     cast(U src, return_value_policy /* policy */, handle /* parent */) {
0315         return PyFloat_FromDouble((double) src);
0316     }
0317 
0318     template <typename U = T>
0319     static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
0320                                        && (sizeof(U) <= sizeof(long)),
0321                                    handle>::type
0322     cast(U src, return_value_policy /* policy */, handle /* parent */) {
0323         return PYBIND11_LONG_FROM_SIGNED((long) src);
0324     }
0325 
0326     template <typename U = T>
0327     static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
0328                                        && (sizeof(U) <= sizeof(unsigned long)),
0329                                    handle>::type
0330     cast(U src, return_value_policy /* policy */, handle /* parent */) {
0331         return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
0332     }
0333 
0334     template <typename U = T>
0335     static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
0336                                        && (sizeof(U) > sizeof(long)),
0337                                    handle>::type
0338     cast(U src, return_value_policy /* policy */, handle /* parent */) {
0339         return PyLong_FromLongLong((long long) src);
0340     }
0341 
0342     template <typename U = T>
0343     static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
0344                                        && (sizeof(U) > sizeof(unsigned long)),
0345                                    handle>::type
0346     cast(U src, return_value_policy /* policy */, handle /* parent */) {
0347         return PyLong_FromUnsignedLongLong((unsigned long long) src);
0348     }
0349 
0350     PYBIND11_TYPE_CASTER(
0351         T,
0352         io_name<std::is_integral<T>::value>("typing.SupportsInt | typing.SupportsIndex",
0353                                             "int",
0354                                             "typing.SupportsFloat | typing.SupportsIndex",
0355                                             "float"));
0356 };
0357 
0358 template <typename T>
0359 struct void_caster {
0360 public:
0361     bool load(handle src, bool) {
0362         if (src && src.is_none()) {
0363             return true;
0364         }
0365         return false;
0366     }
0367     static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
0368         return none().release();
0369     }
0370     PYBIND11_TYPE_CASTER(T, const_name("None"));
0371 };
0372 
0373 template <>
0374 class type_caster<void_type> : public void_caster<void_type> {};
0375 
0376 template <>
0377 class type_caster<void> : public type_caster<void_type> {
0378 public:
0379     using type_caster<void_type>::cast;
0380 
0381     bool load(handle h, bool) {
0382         if (!h) {
0383             return false;
0384         }
0385         if (h.is_none()) {
0386             value = nullptr;
0387             return true;
0388         }
0389 
0390         /* Check if this is a capsule */
0391         if (isinstance<capsule>(h)) {
0392             value = reinterpret_borrow<capsule>(h);
0393             return true;
0394         }
0395 
0396         /* Check if this is a C++ type */
0397         const auto &bases
0398             = all_type_info(reinterpret_cast<PyTypeObject *>(type::handle_of(h).ptr()));
0399         if (bases.size() == 1) { // Only allowing loading from a single-value type
0400             value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
0401             return true;
0402         }
0403 
0404         /* Fail */
0405         return false;
0406     }
0407 
0408     static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
0409         if (ptr) {
0410             return capsule(ptr).release();
0411         }
0412         return none().release();
0413     }
0414 
0415     template <typename T>
0416     using cast_op_type = void *&;
0417     explicit operator void *&() { return value; }
0418     static constexpr auto name = const_name(PYBIND11_CAPSULE_TYPE_TYPE_HINT);
0419 
0420 private:
0421     void *value = nullptr;
0422 };
0423 
0424 template <>
0425 class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
0426 
0427 template <>
0428 class type_caster<bool> {
0429 public:
0430     bool load(handle src, bool convert) {
0431         if (!src) {
0432             return false;
0433         }
0434         if (src.ptr() == Py_True) {
0435             value = true;
0436             return true;
0437         }
0438         if (src.ptr() == Py_False) {
0439             value = false;
0440             return true;
0441         }
0442         if (convert || is_numpy_bool(src)) {
0443             // (allow non-implicit conversion for numpy booleans), use strncmp
0444             // since NumPy 1.x had an additional trailing underscore.
0445 
0446             Py_ssize_t res = -1;
0447             if (src.is_none()) {
0448                 res = 0; // None is implicitly converted to False
0449             }
0450 #if defined(PYPY_VERSION)
0451             // On PyPy, check that "__bool__" attr exists
0452             else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
0453                 res = PyObject_IsTrue(src.ptr());
0454             }
0455 #else
0456             // Alternate approach for CPython: this does the same as the above, but optimized
0457             // using the CPython API so as to avoid an unneeded attribute lookup.
0458             else if (auto *tp_as_number = Py_TYPE(src.ptr())->tp_as_number) {
0459                 if (PYBIND11_NB_BOOL(tp_as_number)) {
0460                     res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
0461                 }
0462             }
0463 #endif
0464             if (res == 0 || res == 1) {
0465                 value = (res != 0);
0466                 return true;
0467             }
0468             PyErr_Clear();
0469         }
0470         return false;
0471     }
0472     static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
0473         return handle(src ? Py_True : Py_False).inc_ref();
0474     }
0475     PYBIND11_TYPE_CASTER(bool, const_name("bool"));
0476 
0477 private:
0478     // Test if an object is a NumPy boolean (without fetching the type).
0479     static bool is_numpy_bool(handle object) {
0480         const char *type_name = Py_TYPE(object.ptr())->tp_name;
0481         // Name changed to `numpy.bool` in NumPy 2, `numpy.bool_` is needed for 1.x support
0482         return std::strcmp("numpy.bool", type_name) == 0
0483                || std::strcmp("numpy.bool_", type_name) == 0;
0484     }
0485 };
0486 
0487 // Helper class for UTF-{8,16,32} C++ stl strings:
0488 template <typename StringType, bool IsView = false>
0489 struct string_caster {
0490     using CharT = typename StringType::value_type;
0491 
0492     // Simplify life by being able to assume standard char sizes (the standard only guarantees
0493     // minimums, but Python requires exact sizes)
0494     static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
0495                   "Unsupported char size != 1");
0496 #if defined(PYBIND11_HAS_U8STRING)
0497     static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
0498                   "Unsupported char8_t size != 1");
0499 #endif
0500     static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
0501                   "Unsupported char16_t size != 2");
0502     static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
0503                   "Unsupported char32_t size != 4");
0504     // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
0505     static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
0506                   "Unsupported wchar_t size != 2/4");
0507     static constexpr size_t UTF_N = 8 * sizeof(CharT);
0508 
0509     bool load(handle src, bool) {
0510         handle load_src = src;
0511         if (!src) {
0512             return false;
0513         }
0514         if (!PyUnicode_Check(load_src.ptr())) {
0515             return load_raw(load_src);
0516         }
0517 
0518         // For UTF-8 we avoid the need for a temporary `bytes` object by using
0519         // `PyUnicode_AsUTF8AndSize`.
0520         if (UTF_N == 8) {
0521             Py_ssize_t size = -1;
0522             const auto *buffer
0523                 = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
0524             if (!buffer) {
0525                 PyErr_Clear();
0526                 return false;
0527             }
0528             value = StringType(buffer, static_cast<size_t>(size));
0529             return true;
0530         }
0531 
0532         auto utfNbytes
0533             = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
0534                                                                   UTF_N == 8    ? "utf-8"
0535                                                                   : UTF_N == 16 ? "utf-16"
0536                                                                                 : "utf-32",
0537                                                                   nullptr));
0538         if (!utfNbytes) {
0539             PyErr_Clear();
0540             return false;
0541         }
0542 
0543         const auto *buffer
0544             = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
0545         size_t length = static_cast<size_t>(PYBIND11_BYTES_SIZE(utfNbytes.ptr())) / sizeof(CharT);
0546         // Skip BOM for UTF-16/32
0547         if (UTF_N > 8) {
0548             buffer++;
0549             length--;
0550         }
0551         value = StringType(buffer, length);
0552 
0553         // If we're loading a string_view we need to keep the encoded Python object alive:
0554         if (IsView) {
0555             loader_life_support::add_patient(utfNbytes);
0556         }
0557 
0558         return true;
0559     }
0560 
0561     static handle
0562     cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
0563         const char *buffer = reinterpret_cast<const char *>(src.data());
0564         auto nbytes = ssize_t(src.size() * sizeof(CharT));
0565         handle s = decode_utfN(buffer, nbytes);
0566         if (!s) {
0567             throw error_already_set();
0568         }
0569         return s;
0570     }
0571 
0572     PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
0573 
0574 private:
0575     static handle decode_utfN(const char *buffer, ssize_t nbytes) {
0576 #if !defined(PYPY_VERSION)
0577         return UTF_N == 8    ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
0578                : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
0579                              : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
0580 #else
0581         // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
0582         // well), so bypass the whole thing by just passing the encoding as a string value, which
0583         // works properly:
0584         return PyUnicode_Decode(buffer,
0585                                 nbytes,
0586                                 UTF_N == 8    ? "utf-8"
0587                                 : UTF_N == 16 ? "utf-16"
0588                                               : "utf-32",
0589                                 nullptr);
0590 #endif
0591     }
0592 
0593     // When loading into a std::string or char*, accept a bytes/bytearray object as-is (i.e.
0594     // without any encoding/decoding attempt).  For other C++ char sizes this is a no-op.
0595     // which supports loading a unicode from a str, doesn't take this path.
0596     template <typename C = CharT>
0597     bool load_raw(enable_if_t<std::is_same<C, char>::value, handle> src) {
0598         if (PYBIND11_BYTES_CHECK(src.ptr())) {
0599             // We were passed raw bytes; accept it into a std::string or char*
0600             // without any encoding attempt.
0601             const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
0602             if (!bytes) {
0603                 pybind11_fail("Unexpected PYBIND11_BYTES_AS_STRING() failure.");
0604             }
0605             value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
0606             return true;
0607         }
0608         if (PyByteArray_Check(src.ptr())) {
0609             // We were passed a bytearray; accept it into a std::string or char*
0610             // without any encoding attempt.
0611             const char *bytearray = PyByteArray_AsString(src.ptr());
0612             if (!bytearray) {
0613                 pybind11_fail("Unexpected PyByteArray_AsString() failure.");
0614             }
0615             value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr()));
0616             return true;
0617         }
0618 
0619         return false;
0620     }
0621 
0622     template <typename C = CharT>
0623     bool load_raw(enable_if_t<!std::is_same<C, char>::value, handle>) {
0624         return false;
0625     }
0626 };
0627 
0628 template <typename CharT, class Traits, class Allocator>
0629 struct type_caster<std::basic_string<CharT, Traits, Allocator>,
0630                    enable_if_t<is_std_char_type<CharT>::value>>
0631     : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
0632 
0633 #ifdef PYBIND11_HAS_STRING_VIEW
0634 template <typename CharT, class Traits>
0635 struct type_caster<std::basic_string_view<CharT, Traits>,
0636                    enable_if_t<is_std_char_type<CharT>::value>>
0637     : string_caster<std::basic_string_view<CharT, Traits>, true> {};
0638 #endif
0639 
0640 // Type caster for C-style strings.  We basically use a std::string type caster, but also add the
0641 // ability to use None as a nullptr char* (which the string caster doesn't allow).
0642 template <typename CharT>
0643 struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
0644     using StringType = std::basic_string<CharT>;
0645     using StringCaster = make_caster<StringType>;
0646     StringCaster str_caster;
0647     bool none = false;
0648     CharT one_char = 0;
0649 
0650 public:
0651     bool load(handle src, bool convert) {
0652         if (!src) {
0653             return false;
0654         }
0655         if (src.is_none()) {
0656             // Defer accepting None to other overloads (if we aren't in convert mode):
0657             if (!convert) {
0658                 return false;
0659             }
0660             none = true;
0661             return true;
0662         }
0663         return str_caster.load(src, convert);
0664     }
0665 
0666     static handle cast(const CharT *src, return_value_policy policy, handle parent) {
0667         if (src == nullptr) {
0668             return pybind11::none().release();
0669         }
0670         return StringCaster::cast(StringType(src), policy, parent);
0671     }
0672 
0673     static handle cast(CharT src, return_value_policy policy, handle parent) {
0674         if (std::is_same<char, CharT>::value) {
0675             handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
0676             if (!s) {
0677                 throw error_already_set();
0678             }
0679             return s;
0680         }
0681         return StringCaster::cast(StringType(1, src), policy, parent);
0682     }
0683 
0684     explicit operator CharT *() {
0685         return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
0686     }
0687     explicit operator CharT &() {
0688         if (none) {
0689             throw value_error("Cannot convert None to a character");
0690         }
0691 
0692         auto &value = static_cast<StringType &>(str_caster);
0693         size_t str_len = value.size();
0694         if (str_len == 0) {
0695             throw value_error("Cannot convert empty string to a character");
0696         }
0697 
0698         // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
0699         // is too high, and one for multiple unicode characters (caught later), so we need to
0700         // figure out how long the first encoded character is in bytes to distinguish between these
0701         // two errors.  We also allow want to allow unicode characters U+0080 through U+00FF, as
0702         // those can fit into a single char value.
0703         if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
0704             auto v0 = static_cast<unsigned char>(value[0]);
0705             // low bits only: 0-127
0706             // 0b110xxxxx - start of 2-byte sequence
0707             // 0b1110xxxx - start of 3-byte sequence
0708             // 0b11110xxx - start of 4-byte sequence
0709             size_t char0_bytes = (v0 & 0x80) == 0      ? 1
0710                                  : (v0 & 0xE0) == 0xC0 ? 2
0711                                  : (v0 & 0xF0) == 0xE0 ? 3
0712                                                        : 4;
0713 
0714             if (char0_bytes == str_len) {
0715                 // If we have a 128-255 value, we can decode it into a single char:
0716                 if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
0717                     one_char = static_cast<CharT>(((v0 & 3) << 6)
0718                                                   + (static_cast<unsigned char>(value[1]) & 0x3F));
0719                     return one_char;
0720                 }
0721                 // Otherwise we have a single character, but it's > U+00FF
0722                 throw value_error("Character code point not in range(0x100)");
0723             }
0724         }
0725 
0726         // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
0727         // surrogate pair with total length 2 instantly indicates a range error (but not a "your
0728         // string was too long" error).
0729         else if (StringCaster::UTF_N == 16 && str_len == 2) {
0730             one_char = static_cast<CharT>(value[0]);
0731             if (one_char >= 0xD800 && one_char < 0xE000) {
0732                 throw value_error("Character code point not in range(0x10000)");
0733             }
0734         }
0735 
0736         if (str_len != 1) {
0737             throw value_error("Expected a character, but multi-character string found");
0738         }
0739 
0740         one_char = value[0];
0741         return one_char;
0742     }
0743 
0744     static constexpr auto name = const_name(PYBIND11_STRING_NAME);
0745     template <typename _T>
0746     using cast_op_type = pybind11::detail::cast_op_type<_T>;
0747 };
0748 
0749 // Base implementation for std::tuple and std::pair
0750 template <template <typename...> class Tuple, typename... Ts>
0751 class tuple_caster {
0752     using type = Tuple<Ts...>;
0753     static constexpr auto size = sizeof...(Ts);
0754     using indices = make_index_sequence<size>;
0755 
0756 public:
0757     bool load(handle src, bool convert) {
0758         if (!isinstance<sequence>(src)) {
0759             return false;
0760         }
0761         const auto seq = reinterpret_borrow<sequence>(src);
0762         if (seq.size() != size) {
0763             return false;
0764         }
0765         return load_impl(seq, convert, indices{});
0766     }
0767 
0768     template <typename T>
0769     static handle cast(T &&src, return_value_policy policy, handle parent) {
0770         return cast_impl(std::forward<T>(src), policy, parent, indices{});
0771     }
0772 
0773     // copied from the PYBIND11_TYPE_CASTER macro
0774     template <typename T>
0775     static handle cast(T *src, return_value_policy policy, handle parent) {
0776         if (!src) {
0777             return none().release();
0778         }
0779         if (policy == return_value_policy::take_ownership) {
0780             auto h = cast(std::move(*src), policy, parent);
0781             delete src;
0782             return h;
0783         }
0784         return cast(*src, policy, parent);
0785     }
0786 
0787     static constexpr auto name = const_name("tuple[")
0788                                  + ::pybind11::detail::concat(make_caster<Ts>::name...)
0789                                  + const_name("]");
0790 
0791     template <typename T>
0792     using cast_op_type = type;
0793 
0794     explicit operator type() & { return implicit_cast(indices{}); }
0795     explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
0796 
0797 protected:
0798     template <size_t... Is>
0799     type implicit_cast(index_sequence<Is...>) & {
0800         return type(cast_op<Ts>(std::get<Is>(subcasters))...);
0801     }
0802     template <size_t... Is>
0803     type implicit_cast(index_sequence<Is...>) && {
0804         return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
0805     }
0806 
0807     static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
0808 
0809     template <size_t... Is>
0810     bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
0811 #ifdef __cpp_fold_expressions
0812         if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
0813             return false;
0814         }
0815 #else
0816         for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
0817             if (!r) {
0818                 return false;
0819             }
0820         }
0821 #endif
0822         return true;
0823     }
0824 
0825     /* Implementation: Convert a C++ tuple into a Python tuple */
0826     template <typename T, size_t... Is>
0827     static handle
0828     cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
0829         PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
0830         PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
0831 
0832         std::array<object, size> entries{{reinterpret_steal<object>(
0833             // NOLINTNEXTLINE(bugprone-use-after-move)
0834             make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
0835         for (const auto &entry : entries) {
0836             if (!entry) {
0837                 return handle();
0838             }
0839         }
0840         tuple result(size);
0841         int counter = 0;
0842         for (auto &entry : entries) {
0843             PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
0844         }
0845         return result.release();
0846     }
0847 
0848     Tuple<make_caster<Ts>...> subcasters;
0849 };
0850 
0851 template <typename T1, typename T2>
0852 class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
0853 
0854 template <typename... Ts>
0855 class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
0856 
0857 template <>
0858 class type_caster<std::tuple<>> : public tuple_caster<std::tuple> {
0859 public:
0860     // PEP 484 specifies this syntax for an empty tuple
0861     static constexpr auto name = const_name("tuple[()]");
0862 };
0863 
0864 /// Helper class which abstracts away certain actions. Users can provide specializations for
0865 /// custom holders, but it's only necessary if the type has a non-standard interface.
0866 template <typename T>
0867 struct holder_helper {
0868     static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
0869 };
0870 
0871 // SMART_HOLDER_BAKEIN_FOLLOW_ON: Rewrite comment, with reference to shared_ptr specialization.
0872 /// Type caster for holder types like std::shared_ptr, etc.
0873 /// The SFINAE hook is provided to help work around the current lack of support
0874 /// for smart-pointer interoperability. Please consider it an implementation
0875 /// detail that may change in the future, as formal support for smart-pointer
0876 /// interoperability is added into pybind11.
0877 template <typename type, typename holder_type, typename SFINAE = void>
0878 struct copyable_holder_caster : public type_caster_base<type> {
0879 public:
0880     using base = type_caster_base<type>;
0881     static_assert(std::is_base_of<base, type_caster<type>>::value,
0882                   "Holder classes are only supported for custom types");
0883     using base::base;
0884     using base::cast;
0885     using base::typeinfo;
0886     using base::value;
0887 
0888     bool load(handle src, bool convert) {
0889         return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
0890     }
0891 
0892     explicit operator type *() { return this->value; }
0893     // static_cast works around compiler error with MSVC 17 and CUDA 10.2
0894     // see issue #2180
0895     explicit operator type &() { return *(static_cast<type *>(this->value)); }
0896     explicit operator holder_type *() { return std::addressof(holder); }
0897     explicit operator holder_type &() { return holder; }
0898 
0899     static handle cast(const holder_type &src, return_value_policy, handle) {
0900         const auto *ptr = holder_helper<holder_type>::get(src);
0901         return type_caster_base<type>::cast_holder(ptr, &src);
0902     }
0903 
0904 protected:
0905     friend class type_caster_generic;
0906     void check_holder_compat() {
0907         // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.
0908         bool inst_has_unique_ptr_holder
0909             = (typeinfo->holder_enum_v == holder_enum_t::std_unique_ptr);
0910         if (inst_has_unique_ptr_holder) {
0911             throw cast_error("Unable to load a custom holder type from a default-holder instance");
0912         }
0913     }
0914 
0915     bool set_foreign_holder(handle src) {
0916         return holder_caster_foreign_helpers::set_foreign_holder(src, (type *) value, &holder);
0917     }
0918 
0919     void load_value(value_and_holder &&v_h) {
0920         if (v_h.holder_constructed()) {
0921             value = v_h.value_ptr();
0922             holder = v_h.template holder<holder_type>();
0923             return;
0924         }
0925         throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
0926 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
0927                          "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
0928                          "type information)");
0929 #else
0930                          "of type '"
0931                          + type_id<holder_type>() + "''");
0932 #endif
0933     }
0934 
0935     template <typename T = holder_type,
0936               detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
0937     bool try_implicit_casts(handle, bool) {
0938         return false;
0939     }
0940 
0941     template <typename T = holder_type,
0942               detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
0943     bool try_implicit_casts(handle src, bool convert) {
0944         for (auto &cast : typeinfo->implicit_casts) {
0945             copyable_holder_caster sub_caster(*cast.first);
0946             if (sub_caster.load(src, convert)) {
0947                 value = cast.second(sub_caster.value);
0948                 holder = holder_type(sub_caster.holder, (type *) value);
0949                 return true;
0950             }
0951         }
0952         return false;
0953     }
0954 
0955     static bool try_direct_conversions(handle) { return false; }
0956 
0957     holder_type holder;
0958 };
0959 
0960 template <typename, typename SFINAE = void>
0961 struct copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled : std::true_type {};
0962 
0963 // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refactor copyable_holder_caster to reduce code duplication.
0964 template <typename type>
0965 struct copyable_holder_caster<
0966     type,
0967     std::shared_ptr<type>,
0968     enable_if_t<copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled<type>::value>>
0969     : public type_caster_base<type> {
0970 public:
0971     using base = type_caster_base<type>;
0972     static_assert(std::is_base_of<base, type_caster<type>>::value,
0973                   "Holder classes are only supported for custom types");
0974     using base::base;
0975     using base::cast;
0976     using base::typeinfo;
0977     using base::value;
0978 
0979     bool load(handle src, bool convert) {
0980         if (base::template load_impl<copyable_holder_caster<type, std::shared_ptr<type>>>(
0981                 src, convert)) {
0982             sh_load_helper.maybe_set_python_instance_is_alias(src);
0983             return true;
0984         }
0985         return false;
0986     }
0987 
0988     explicit operator std::shared_ptr<type> *() {
0989         if (sh_load_helper.was_populated) {
0990             pybind11_fail("Passing `std::shared_ptr<T> *` from Python to C++ is not supported "
0991                           "(inherently unsafe).");
0992         }
0993         return std::addressof(shared_ptr_storage);
0994     }
0995 
0996     explicit operator std::shared_ptr<type> &() {
0997         if (sh_load_helper.was_populated) {
0998             shared_ptr_storage = sh_load_helper.load_as_shared_ptr(typeinfo, value);
0999         }
1000         return shared_ptr_storage;
1001     }
1002 
1003     std::weak_ptr<type> potentially_slicing_weak_ptr() {
1004         if (sh_load_helper.was_populated) {
1005             // Reusing shared_ptr code to minimize code complexity.
1006             shared_ptr_storage
1007                 = sh_load_helper.load_as_shared_ptr(typeinfo,
1008                                                     value,
1009                                                     /*responsible_parent=*/nullptr,
1010                                                     /*force_potentially_slicing_shared_ptr=*/true);
1011         }
1012         return shared_ptr_storage;
1013     }
1014 
1015     static handle
1016     cast(const std::shared_ptr<type> &src, return_value_policy policy, handle parent) {
1017         const auto *ptr = src.get();
1018         typename type_caster_base<type>::cast_sources srcs{ptr};
1019         if (srcs.creates_smart_holder()) {
1020             return smart_holder_type_caster_support::smart_holder_from_shared_ptr(
1021                 src, policy, parent, srcs.result);
1022         }
1023         return type_caster_base<type>::cast_holder(srcs, &src);
1024     }
1025 
1026     // This function will succeed even if the `responsible_parent` does not own the
1027     // wrapped C++ object directly.
1028     // It is the responsibility of the caller to ensure that the `responsible_parent`
1029     // has a `keep_alive` relationship with the owner of the wrapped C++ object, or
1030     // that the wrapped C++ object lives for the duration of the process.
1031     static std::shared_ptr<type> shared_ptr_with_responsible_parent(handle responsible_parent) {
1032         copyable_holder_caster loader;
1033         loader.load(responsible_parent, /*convert=*/false);
1034         assert(loader.typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder);
1035         return loader.sh_load_helper.load_as_shared_ptr(
1036             loader.typeinfo, loader.value, responsible_parent);
1037     }
1038 
1039 protected:
1040     friend class type_caster_generic;
1041     void check_holder_compat() {
1042         // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.
1043         bool inst_has_unique_ptr_holder
1044             = (typeinfo->holder_enum_v == holder_enum_t::std_unique_ptr);
1045         if (inst_has_unique_ptr_holder) {
1046             throw cast_error("Unable to load a custom holder type from a default-holder instance");
1047         }
1048     }
1049 
1050     bool set_foreign_holder(handle src) {
1051         return holder_caster_foreign_helpers::set_foreign_holder(
1052             src, (type *) value, &shared_ptr_storage);
1053     }
1054 
1055     void load_value(value_and_holder &&v_h) {
1056         if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1057             sh_load_helper.loaded_v_h = v_h;
1058             sh_load_helper.was_populated = true;
1059             value = sh_load_helper.get_void_ptr_or_nullptr();
1060             return;
1061         }
1062         if (v_h.holder_constructed()) {
1063             value = v_h.value_ptr();
1064             shared_ptr_storage = v_h.template holder<std::shared_ptr<type>>();
1065             return;
1066         }
1067         throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
1068 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1069                          "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
1070                          "type information)");
1071 #else
1072                          "of type '"
1073                          + type_id<std::shared_ptr<type>>() + "''");
1074 #endif
1075     }
1076 
1077     template <typename T = std::shared_ptr<type>,
1078               detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
1079     bool try_implicit_casts(handle, bool) {
1080         return false;
1081     }
1082 
1083     template <typename T = std::shared_ptr<type>,
1084               detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
1085     bool try_implicit_casts(handle src, bool convert) {
1086         for (auto &cast : typeinfo->implicit_casts) {
1087             copyable_holder_caster sub_caster(*cast.first);
1088             if (sub_caster.load(src, convert)) {
1089                 value = cast.second(sub_caster.value);
1090                 if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1091                     sh_load_helper.loaded_v_h = sub_caster.sh_load_helper.loaded_v_h;
1092                     sh_load_helper.was_populated = true;
1093                 } else {
1094                     shared_ptr_storage
1095                         = std::shared_ptr<type>(sub_caster.shared_ptr_storage, (type *) value);
1096                 }
1097                 return true;
1098             }
1099         }
1100         return false;
1101     }
1102 
1103     static bool try_direct_conversions(handle) { return false; }
1104 
1105     smart_holder_type_caster_support::load_helper<remove_cv_t<type>> sh_load_helper; // Const2Mutbl
1106     std::shared_ptr<type> shared_ptr_storage;
1107 };
1108 
1109 /// Specialize for the common std::shared_ptr, so users don't need to
1110 template <typename T>
1111 class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
1112 
1113 PYBIND11_NAMESPACE_END(detail)
1114 
1115 /// Return a std::shared_ptr with the SAME CONTROL BLOCK as the std::shared_ptr owned by the
1116 /// class_ holder. For class_-wrapped types with trampolines, the returned std::shared_ptr
1117 /// does NOT keep any derived Python objects alive (see issue #1333).
1118 ///
1119 /// For class_-wrapped types using std::shared_ptr as the holder, the following expressions
1120 /// produce equivalent results (see tests/test_potentially_slicing_weak_ptr.cpp,py):
1121 ///
1122 ///     - obj.cast<std::shared_ptr<T>>()
1123 ///     - py::potentially_slicing_weak_ptr<T>(obj).lock()
1124 ///
1125 /// For class_-wrapped types with trampolines and using py::smart_holder, obj.cast<>()
1126 /// produces a std::shared_ptr that keeps any derived Python objects alive for its own lifetime,
1127 /// but this is achieved by introducing a std::shared_ptr control block that is independent of
1128 /// the one owned by the py::smart_holder. This can lead to surprising std::weak_ptr behavior
1129 /// (see issue #5623). An easy solution is to use py::potentially_slicing_weak_ptr<>(obj),
1130 /// as exercised in tests/test_potentially_slicing_weak_ptr.cpp,py (look for
1131 /// "set_wp_potentially_slicing"). Note, however, that this reintroduces the inheritance
1132 /// slicing issue (see issue #1333). The ideal — but usually more involved — solution is to use
1133 /// a Python weakref to the derived Python object, instead of a C++ base-class std::weak_ptr.
1134 ///
1135 /// It is not possible (at least no known approach exists at the time of this writing) to
1136 /// simultaneously achieve both desirable properties:
1137 ///
1138 ///     - the same std::shared_ptr control block as the class_ holder
1139 ///     - automatic lifetime extension of any derived Python objects
1140 ///
1141 /// The reason is that this would introduce a reference cycle that cannot be garbage collected:
1142 ///
1143 ///     - the derived Python object owns the class_ holder
1144 ///     - the class_ holder owns the std::shared_ptr
1145 ///     - the std::shared_ptr would own a reference to the derived Python object,
1146 ///       completing the cycle
1147 template <typename T>
1148 std::weak_ptr<T> potentially_slicing_weak_ptr(handle obj) {
1149     detail::make_caster<std::shared_ptr<T>> caster;
1150     if (caster.load(obj, /*convert=*/true)) {
1151         return caster.potentially_slicing_weak_ptr();
1152     }
1153     const char *obj_type_name = detail::obj_class_name(obj.ptr());
1154     throw type_error("\"" + std::string(obj_type_name)
1155                      + "\" object is not convertible to std::weak_ptr<T> (with T = " + type_id<T>()
1156                      + ")");
1157 }
1158 
1159 PYBIND11_NAMESPACE_BEGIN(detail)
1160 
1161 // SMART_HOLDER_BAKEIN_FOLLOW_ON: Rewrite comment, with reference to unique_ptr specialization.
1162 /// Type caster for holder types like std::unique_ptr.
1163 /// Please consider the SFINAE hook an implementation detail, as explained
1164 /// in the comment for the copyable_holder_caster.
1165 template <typename type, typename holder_type, typename SFINAE = void>
1166 struct move_only_holder_caster {
1167     static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
1168                   "Holder classes are only supported for custom types");
1169 
1170     static handle cast(holder_type &&src, return_value_policy, handle) {
1171         auto *ptr = holder_helper<holder_type>::get(src);
1172         return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
1173     }
1174     static constexpr auto name = type_caster_base<type>::name;
1175 };
1176 
1177 template <typename, typename SFINAE = void>
1178 struct move_only_holder_caster_unique_ptr_with_smart_holder_support_enabled : std::true_type {};
1179 
1180 // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refactor move_only_holder_caster to reduce code duplication.
1181 template <typename type, typename deleter>
1182 struct move_only_holder_caster<
1183     type,
1184     std::unique_ptr<type, deleter>,
1185     enable_if_t<move_only_holder_caster_unique_ptr_with_smart_holder_support_enabled<type>::value>>
1186     : public type_caster_base<type> {
1187 public:
1188     using base = type_caster_base<type>;
1189     static_assert(std::is_base_of<base, type_caster<type>>::value,
1190                   "Holder classes are only supported for custom types");
1191     using base::base;
1192     using base::cast;
1193     using base::typeinfo;
1194     using base::value;
1195 
1196     static handle
1197     cast(std::unique_ptr<type, deleter> &&src, return_value_policy policy, handle parent) {
1198         auto *ptr = src.get();
1199         typename type_caster_base<type>::cast_sources srcs{ptr};
1200         if (srcs.creates_smart_holder()) {
1201             return smart_holder_type_caster_support::smart_holder_from_unique_ptr(
1202                 std::move(src), policy, parent, srcs.result);
1203         }
1204         return type_caster_base<type>::cast_holder(srcs, &src);
1205     }
1206 
1207     static handle
1208     cast(const std::unique_ptr<type, deleter> &src, return_value_policy policy, handle parent) {
1209         if (!src) {
1210             return none().release();
1211         }
1212         if (policy == return_value_policy::automatic) {
1213             policy = return_value_policy::reference_internal;
1214         }
1215         if (policy != return_value_policy::reference_internal) {
1216             throw cast_error("Invalid return_value_policy for const unique_ptr&");
1217         }
1218         return type_caster_base<type>::cast(src.get(), policy, parent);
1219     }
1220 
1221     bool load(handle src, bool convert) {
1222         if (base::template load_impl<
1223                 move_only_holder_caster<type, std::unique_ptr<type, deleter>>>(src, convert)) {
1224             sh_load_helper.maybe_set_python_instance_is_alias(src);
1225             return true;
1226         }
1227         return false;
1228     }
1229 
1230     bool set_foreign_holder(handle) {
1231         throw cast_error("Foreign instance cannot be converted to std::unique_ptr "
1232                          "because we don't know how to make it relinquish "
1233                          "ownership");
1234     }
1235 
1236     void load_value(value_and_holder &&v_h) {
1237         if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1238             sh_load_helper.loaded_v_h = v_h;
1239             sh_load_helper.loaded_v_h.type = typeinfo;
1240             sh_load_helper.was_populated = true;
1241             value = sh_load_helper.get_void_ptr_or_nullptr();
1242             return;
1243         }
1244         pybind11_fail("Passing `std::unique_ptr<T>` from Python to C++ requires `py::class_<T, "
1245                       "py::smart_holder>` (with T = "
1246                       + clean_type_id(typeinfo->cpptype->name()) + ")");
1247     }
1248 
1249     template <typename T_>
1250     using cast_op_type
1251         = conditional_t<std::is_same<typename std::remove_volatile<T_>::type,
1252                                      const std::unique_ptr<type, deleter> &>::value
1253                             || std::is_same<typename std::remove_volatile<T_>::type,
1254                                             const std::unique_ptr<const type, deleter> &>::value,
1255                         const std::unique_ptr<type, deleter> &,
1256                         std::unique_ptr<type, deleter>>;
1257 
1258     explicit operator std::unique_ptr<type, deleter>() {
1259         if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1260             return sh_load_helper.template load_as_unique_ptr<deleter>(typeinfo, value);
1261         }
1262         pybind11_fail("Expected to be UNREACHABLE: " __FILE__ ":" PYBIND11_TOSTRING(__LINE__));
1263     }
1264 
1265     explicit operator const std::unique_ptr<type, deleter> &() {
1266         if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1267             // Get shared_ptr to ensure that the Python object is not disowned elsewhere.
1268             shared_ptr_storage = sh_load_helper.load_as_shared_ptr(typeinfo, value);
1269             // Build a temporary unique_ptr that is meant to never expire.
1270             unique_ptr_storage = std::shared_ptr<std::unique_ptr<type, deleter>>(
1271                 new std::unique_ptr<type, deleter>{
1272                     sh_load_helper.template load_as_const_unique_ptr<deleter>(
1273                         typeinfo, shared_ptr_storage.get())},
1274                 [](std::unique_ptr<type, deleter> *ptr) {
1275                     if (!ptr) {
1276                         pybind11_fail("FATAL: `const std::unique_ptr<T, D> &` was disowned "
1277                                       "(EXPECT UNDEFINED BEHAVIOR).");
1278                     }
1279                     (void) ptr->release();
1280                     delete ptr;
1281                 });
1282             return *unique_ptr_storage;
1283         }
1284         pybind11_fail("Expected to be UNREACHABLE: " __FILE__ ":" PYBIND11_TOSTRING(__LINE__));
1285     }
1286 
1287     bool try_implicit_casts(handle src, bool convert) {
1288         for (auto &cast : typeinfo->implicit_casts) {
1289             move_only_holder_caster sub_caster(*cast.first);
1290             if (sub_caster.load(src, convert)) {
1291                 value = cast.second(sub_caster.value);
1292                 if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
1293                     sh_load_helper.loaded_v_h = sub_caster.sh_load_helper.loaded_v_h;
1294                     sh_load_helper.was_populated = true;
1295                 } else {
1296                     pybind11_fail("Expected to be UNREACHABLE: " __FILE__
1297                                   ":" PYBIND11_TOSTRING(__LINE__));
1298                 }
1299                 return true;
1300             }
1301         }
1302         return false;
1303     }
1304 
1305     static bool try_direct_conversions(handle) { return false; }
1306 
1307     smart_holder_type_caster_support::load_helper<remove_cv_t<type>> sh_load_helper; // Const2Mutbl
1308     std::shared_ptr<type> shared_ptr_storage; // Serves as a pseudo lock.
1309     std::shared_ptr<std::unique_ptr<type, deleter>> unique_ptr_storage;
1310 };
1311 
1312 template <typename type, typename deleter>
1313 class type_caster<std::unique_ptr<type, deleter>>
1314     : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
1315 
1316 template <typename type, typename holder_type>
1317 using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
1318                                          copyable_holder_caster<type, holder_type>,
1319                                          move_only_holder_caster<type, holder_type>>;
1320 
1321 template <bool Value = false>
1322 struct always_construct_holder_value {
1323     static constexpr bool value = Value;
1324 };
1325 
1326 template <typename T, bool Value = false>
1327 struct always_construct_holder : always_construct_holder_value<Value> {};
1328 
1329 /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
1330 #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...)                                      \
1331     PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)                                                  \
1332     namespace detail {                                                                            \
1333     template <typename type>                                                                      \
1334     struct always_construct_holder<holder_type> : always_construct_holder_value<__VA_ARGS__> {};  \
1335     template <typename type>                                                                      \
1336     class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>>               \
1337         : public type_caster_holder<type, holder_type> {};                                        \
1338     }                                                                                             \
1339     PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
1340 
1341 // PYBIND11_DECLARE_HOLDER_TYPE holder types:
1342 template <typename base, typename holder>
1343 struct is_holder_type
1344     : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
1345 
1346 // Specializations for always-supported holders:
1347 template <typename base, typename deleter>
1348 struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
1349 
1350 template <typename base>
1351 struct is_holder_type<base, smart_holder> : std::true_type {};
1352 
1353 #ifdef PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION // See PR #4888
1354 
1355 // This leads to compilation errors if a specialization is missing.
1356 template <typename T>
1357 struct handle_type_name;
1358 
1359 #else
1360 
1361 template <typename T>
1362 struct handle_type_name {
1363     static constexpr auto name = const_name<T>();
1364 };
1365 
1366 #endif
1367 
1368 template <>
1369 struct handle_type_name<object> {
1370     static constexpr auto name = const_name("object");
1371 };
1372 template <>
1373 struct handle_type_name<list> {
1374     static constexpr auto name = const_name("list");
1375 };
1376 template <>
1377 struct handle_type_name<dict> {
1378     static constexpr auto name = const_name("dict");
1379 };
1380 template <>
1381 struct handle_type_name<anyset> {
1382     static constexpr auto name = const_name("set | frozenset");
1383 };
1384 template <>
1385 struct handle_type_name<set> {
1386     static constexpr auto name = const_name("set");
1387 };
1388 template <>
1389 struct handle_type_name<frozenset> {
1390     static constexpr auto name = const_name("frozenset");
1391 };
1392 template <>
1393 struct handle_type_name<str> {
1394     static constexpr auto name = const_name("str");
1395 };
1396 template <>
1397 struct handle_type_name<tuple> {
1398     static constexpr auto name = const_name("tuple");
1399 };
1400 template <>
1401 struct handle_type_name<bool_> {
1402     static constexpr auto name = const_name("bool");
1403 };
1404 template <>
1405 struct handle_type_name<bytes> {
1406     static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
1407 };
1408 template <>
1409 struct handle_type_name<buffer> {
1410     static constexpr auto name = const_name(PYBIND11_BUFFER_TYPE_HINT);
1411 };
1412 template <>
1413 struct handle_type_name<int_> {
1414     static constexpr auto name = const_name("int");
1415 };
1416 template <>
1417 struct handle_type_name<iterable> {
1418     static constexpr auto name = const_name("collections.abc.Iterable");
1419 };
1420 template <>
1421 struct handle_type_name<iterator> {
1422     static constexpr auto name = const_name("collections.abc.Iterator");
1423 };
1424 template <>
1425 struct handle_type_name<float_> {
1426     static constexpr auto name = const_name("float");
1427 };
1428 template <>
1429 struct handle_type_name<function> {
1430     static constexpr auto name = const_name("collections.abc.Callable");
1431 };
1432 template <>
1433 struct handle_type_name<handle> {
1434     static constexpr auto name = handle_type_name<object>::name;
1435 };
1436 template <>
1437 struct handle_type_name<none> {
1438     static constexpr auto name = const_name("None");
1439 };
1440 template <>
1441 struct handle_type_name<sequence> {
1442     static constexpr auto name = const_name("collections.abc.Sequence");
1443 };
1444 template <>
1445 struct handle_type_name<bytearray> {
1446     static constexpr auto name = const_name("bytearray");
1447 };
1448 template <>
1449 struct handle_type_name<memoryview> {
1450     static constexpr auto name = const_name("memoryview");
1451 };
1452 template <>
1453 struct handle_type_name<slice> {
1454     static constexpr auto name = const_name("slice");
1455 };
1456 template <>
1457 struct handle_type_name<type> {
1458     static constexpr auto name = const_name("type");
1459 };
1460 template <>
1461 struct handle_type_name<capsule> {
1462     static constexpr auto name = const_name(PYBIND11_CAPSULE_TYPE_TYPE_HINT);
1463 };
1464 template <>
1465 struct handle_type_name<ellipsis> {
1466     static constexpr auto name = const_name("ellipsis");
1467 };
1468 template <>
1469 struct handle_type_name<weakref> {
1470     static constexpr auto name = const_name("weakref.ReferenceType");
1471 };
1472 // args/Args/kwargs/KWArgs have name as well as typehint included
1473 template <>
1474 struct handle_type_name<args> {
1475     static constexpr auto name = io_name("*args", "tuple");
1476 };
1477 template <typename T>
1478 struct handle_type_name<Args<T>> {
1479     static constexpr auto name
1480         = io_name("*args: ", "tuple[") + make_caster<T>::name + io_name("", ", ...]");
1481 };
1482 template <>
1483 struct handle_type_name<kwargs> {
1484     static constexpr auto name = io_name("**kwargs", "dict[str, typing.Any]");
1485 };
1486 template <typename T>
1487 struct handle_type_name<KWArgs<T>> {
1488     static constexpr auto name
1489         = io_name("**kwargs: ", "dict[str, ") + make_caster<T>::name + io_name("", "]");
1490 };
1491 template <>
1492 struct handle_type_name<obj_attr_accessor> {
1493     static constexpr auto name = const_name<obj_attr_accessor>();
1494 };
1495 template <>
1496 struct handle_type_name<str_attr_accessor> {
1497     static constexpr auto name = const_name<str_attr_accessor>();
1498 };
1499 template <>
1500 struct handle_type_name<item_accessor> {
1501     static constexpr auto name = const_name<item_accessor>();
1502 };
1503 template <>
1504 struct handle_type_name<sequence_accessor> {
1505     static constexpr auto name = const_name<sequence_accessor>();
1506 };
1507 template <>
1508 struct handle_type_name<list_accessor> {
1509     static constexpr auto name = const_name<list_accessor>();
1510 };
1511 template <>
1512 struct handle_type_name<tuple_accessor> {
1513     static constexpr auto name = const_name<tuple_accessor>();
1514 };
1515 
1516 template <typename type>
1517 struct pyobject_caster {
1518     template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
1519     pyobject_caster() : value() {}
1520 
1521     // `type` may not be default constructible (e.g. frozenset, anyset).  Initializing `value`
1522     // to a nil handle is safe since it will only be accessed if `load` succeeds.
1523     template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
1524     pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
1525 
1526     template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
1527     bool load(handle src, bool /* convert */) {
1528         value = src;
1529         return static_cast<bool>(value);
1530     }
1531 
1532     template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
1533     bool load(handle src, bool /* convert */) {
1534         if (!isinstance<type>(src)) {
1535             return false;
1536         }
1537         value = reinterpret_borrow<type>(src);
1538         return true;
1539     }
1540 
1541     static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
1542         return src.inc_ref();
1543     }
1544     PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
1545 };
1546 
1547 template <typename T>
1548 class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
1549 
1550 template <>
1551 class type_caster<float_> : public pyobject_caster<float_> {
1552 public:
1553     bool load(handle src, bool /* convert */) {
1554         if (isinstance<float_>(src)) {
1555             value = reinterpret_borrow<float_>(src);
1556         } else if (isinstance<int_>(src)) {
1557             value = float_(reinterpret_borrow<int_>(src));
1558         } else {
1559             return false;
1560         }
1561         return true;
1562     }
1563 };
1564 
1565 // Our conditions for enabling moving are quite restrictive:
1566 // At compile time:
1567 // - T needs to be a non-const, non-pointer, non-reference type
1568 // - type_caster<T>::operator T&() must exist
1569 // - the type must be move constructible (obviously)
1570 // At run-time:
1571 // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
1572 //   must have ref_count() == 1)h
1573 // If any of the above are not satisfied, we fall back to copying.
1574 template <typename T>
1575 using move_is_plain_type
1576     = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
1577 template <typename T, typename SFINAE = void>
1578 struct move_always : std::false_type {};
1579 template <typename T>
1580 struct move_always<
1581     T,
1582     enable_if_t<
1583         all_of<move_is_plain_type<T>,
1584                negation<is_copy_constructible<T>>,
1585                is_move_constructible<T>,
1586                std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
1587     : std::true_type {};
1588 template <typename T, typename SFINAE = void>
1589 struct move_if_unreferenced : std::false_type {};
1590 template <typename T>
1591 struct move_if_unreferenced<
1592     T,
1593     enable_if_t<
1594         all_of<move_is_plain_type<T>,
1595                negation<move_always<T>>,
1596                is_move_constructible<T>,
1597                std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
1598     : std::true_type {};
1599 template <typename T>
1600 using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
1601 
1602 // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
1603 // reference or pointer to a local variable of the type_caster.  Basically, only
1604 // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
1605 // everything else returns a reference/pointer to a local variable.
1606 template <typename type>
1607 using cast_is_temporary_value_reference
1608     = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
1609                     && !std::is_base_of<type_caster_generic, make_caster<type>>::value
1610                     && !std::is_same<intrinsic_t<type>, void>::value>;
1611 
1612 // When a value returned from a C++ function is being cast back to Python, we almost always want to
1613 // force `policy = move`, regardless of the return value policy the function/method was declared
1614 // with.
1615 template <typename Return, typename SFINAE = void>
1616 struct return_value_policy_override {
1617     static return_value_policy policy(return_value_policy p) { return p; }
1618 };
1619 
1620 template <typename Return>
1621 struct return_value_policy_override<
1622     Return,
1623     detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1624     static return_value_policy policy(return_value_policy p) {
1625         return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
1626                    ? return_value_policy::move
1627                    : p;
1628     }
1629 };
1630 
1631 // Basic python -> C++ casting; throws if casting fails
1632 template <typename T, typename SFINAE>
1633 type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
1634     static_assert(!detail::is_pyobject<T>::value,
1635                   "Internal error: type_caster should only be used for C++ types");
1636     if (!conv.load(handle, true)) {
1637 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1638         throw cast_error(
1639             "Unable to cast Python instance of type "
1640             + str(type::handle_of(handle)).cast<std::string>()
1641             + " to C++ type '?' (#define "
1642               "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1643 #else
1644         throw cast_error("Unable to cast Python instance of type "
1645                          + str(type::handle_of(handle)).cast<std::string>() + " to C++ type '"
1646                          + type_id<T>() + "'");
1647 #endif
1648     }
1649     return conv;
1650 }
1651 // Wrapper around the above that also constructs and returns a type_caster
1652 template <typename T>
1653 make_caster<T> load_type(const handle &handle) {
1654     make_caster<T> conv;
1655     load_type(conv, handle);
1656     return conv;
1657 }
1658 
1659 PYBIND11_NAMESPACE_END(detail)
1660 
1661 // pytype -> C++ type
1662 template <typename T,
1663           detail::enable_if_t<!detail::is_pyobject<T>::value
1664                                   && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
1665                               int>
1666           = 0>
1667 T cast(const handle &handle) {
1668     using namespace detail;
1669     constexpr bool is_enum_cast = type_uses_type_caster_enum_type<intrinsic_t<T>>::value;
1670     static_assert(!cast_is_temporary_value_reference<T>::value || is_enum_cast,
1671                   "Unable to cast type to reference: value is local to type caster");
1672 #ifndef NDEBUG
1673     if (is_enum_cast && cast_is_temporary_value_reference<T>::value) {
1674         if (detail::global_internals_native_enum_type_map_contains(
1675                 std::type_index(typeid(intrinsic_t<T>)))) {
1676             pybind11_fail("Unable to cast native enum type to reference");
1677         }
1678     }
1679 #endif
1680     return cast_op<T>(load_type<T>(handle));
1681 }
1682 
1683 // pytype -> pytype (calls converting constructor)
1684 template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
1685 T cast(const handle &handle) {
1686     return T(reinterpret_borrow<object>(handle));
1687 }
1688 
1689 // Note that `cast<PyObject *>(obj)` increments the reference count of `obj`.
1690 // This is necessary for the case that `obj` is a temporary, and could
1691 // not possibly be different, given
1692 // 1. the established convention that the passed `handle` is borrowed, and
1693 // 2. we don't want to force all generic code using `cast<T>()` to special-case
1694 //    handling of `T` = `PyObject *` (to increment the reference count there).
1695 // It is the responsibility of the caller to ensure that the reference count
1696 // is decremented.
1697 template <typename T,
1698           typename Handle,
1699           detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
1700                                   && detail::is_same_ignoring_cvref<Handle, handle>::value,
1701                               int>
1702           = 0>
1703 T cast(Handle &&handle) {
1704     return handle.inc_ref().ptr();
1705 }
1706 // To optimize way an inc_ref/dec_ref cycle:
1707 template <typename T,
1708           typename Object,
1709           detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
1710                                   && detail::is_same_ignoring_cvref<Object, object>::value,
1711                               int>
1712           = 0>
1713 T cast(Object &&obj) {
1714     return obj.release().ptr();
1715 }
1716 
1717 // C++ type -> py::object
1718 template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1719 object cast(T &&value,
1720             return_value_policy policy = return_value_policy::automatic_reference,
1721             handle parent = handle()) {
1722     using no_ref_T = typename std::remove_reference<T>::type;
1723     if (policy == return_value_policy::automatic) {
1724         policy = std::is_pointer<no_ref_T>::value     ? return_value_policy::take_ownership
1725                  : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1726                                                       : return_value_policy::move;
1727     } else if (policy == return_value_policy::automatic_reference) {
1728         policy = std::is_pointer<no_ref_T>::value     ? return_value_policy::reference
1729                  : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1730                                                       : return_value_policy::move;
1731     }
1732     return reinterpret_steal<object>(
1733         detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
1734 }
1735 
1736 template <typename T>
1737 T handle::cast() const {
1738     return pybind11::cast<T>(*this);
1739 }
1740 template <>
1741 inline void handle::cast() const {
1742     return;
1743 }
1744 
1745 template <typename T>
1746 detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
1747     if (obj.ref_count() > 1) {
1748 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1749         throw cast_error(
1750             "Unable to cast Python " + str(type::handle_of(obj)).cast<std::string>()
1751             + " instance to C++ rvalue: instance has multiple references"
1752               " (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1753 #else
1754         throw cast_error("Unable to move from Python "
1755                          + str(type::handle_of(obj)).cast<std::string>() + " instance to C++ "
1756                          + type_id<T>() + " instance: instance has multiple references");
1757 #endif
1758     }
1759 
1760     // Move into a temporary and return that, because the reference may be a local value of `conv`
1761     T ret = std::move(detail::load_type<T>(obj).operator T &());
1762     return ret;
1763 }
1764 
1765 // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
1766 // - If we have to move (because T has no copy constructor), do it.  This will fail if the moved
1767 //   object has multiple references, but trying to copy will fail to compile.
1768 // - If both movable and copyable, check ref count: if 1, move; otherwise copy
1769 // - Otherwise (not movable), copy.
1770 template <typename T>
1771 detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>
1772 cast(object &&object) {
1773     return move<T>(std::move(object));
1774 }
1775 template <typename T>
1776 detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>
1777 cast(object &&object) {
1778     if (object.ref_count() > 1) {
1779         return cast<T>(object);
1780     }
1781     return move<T>(std::move(object));
1782 }
1783 template <typename T>
1784 detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>
1785 cast(object &&object) {
1786     return cast<T>(object);
1787 }
1788 
1789 // pytype rvalue -> pytype (calls converting constructor)
1790 template <typename T>
1791 detail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {
1792     return T(std::move(object));
1793 }
1794 
1795 template <typename T>
1796 T object::cast() const & {
1797     return pybind11::cast<T>(*this);
1798 }
1799 template <typename T>
1800 T object::cast() && {
1801     return pybind11::cast<T>(std::move(*this));
1802 }
1803 template <>
1804 inline void object::cast() const & {
1805     return;
1806 }
1807 template <>
1808 inline void object::cast() && {
1809     return;
1810 }
1811 
1812 PYBIND11_NAMESPACE_BEGIN(detail)
1813 
1814 // forward declaration (definition in pybind11.h)
1815 template <typename T>
1816 std::string generate_type_signature();
1817 
1818 // Declared in pytypes.h:
1819 template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
1820 object object_or_cast(T &&o) {
1821     return pybind11::cast(std::forward<T>(o));
1822 }
1823 
1824 // Declared in pytypes.h:
1825 // Implemented here so that make_caster<T> can be used.
1826 template <typename D>
1827 template <typename T>
1828 str_attr_accessor object_api<D>::attr_with_type_hint(const char *key) const {
1829 #if !defined(__cpp_inline_variables)
1830     static_assert(always_false<T>::value,
1831                   "C++17 feature __cpp_inline_variables not available: "
1832                   "https://en.cppreference.com/w/cpp/language/static#Static_data_members");
1833 #endif
1834     object ann = annotations();
1835     if (ann.contains(key)) {
1836         throw std::runtime_error("__annotations__[\"" + std::string(key) + "\"] was set already.");
1837     }
1838 
1839     ann[key] = generate_type_signature<T>();
1840     return {derived(), key};
1841 }
1842 
1843 template <typename D>
1844 template <typename T>
1845 obj_attr_accessor object_api<D>::attr_with_type_hint(handle key) const {
1846     (void) attr_with_type_hint<T>(key.cast<std::string>().c_str());
1847     return {derived(), reinterpret_borrow<object>(key)};
1848 }
1849 
1850 // Placeholder type for the unneeded (and dead code) static variable in the
1851 // PYBIND11_OVERRIDE_OVERRIDE macro
1852 struct override_unused {};
1853 template <typename ret_type>
1854 using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
1855                                         make_caster<ret_type>,
1856                                         override_unused>;
1857 
1858 // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
1859 // store the result in the given variable.  For other types, this is a no-op.
1860 template <typename T>
1861 enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
1862                                                                      make_caster<T> &caster) {
1863     return cast_op<T>(load_type(caster, o));
1864 }
1865 template <typename T>
1866 enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
1867                                                                       override_unused &) {
1868     pybind11_fail("Internal error: cast_ref fallback invoked");
1869 }
1870 
1871 // Trampoline use: Having a pybind11::cast with an invalid reference type is going to
1872 // static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
1873 // that only does anything in cases where pybind11::cast is valid.
1874 template <typename T>
1875 enable_if_t<cast_is_temporary_value_reference<T>::value
1876                 && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
1877             T>
1878 cast_safe(object &&) {
1879     pybind11_fail("Internal error: cast_safe fallback invoked");
1880 }
1881 template <typename T>
1882 enable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}
1883 template <typename T>
1884 enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value, PyObject *>
1885 cast_safe(object &&o) {
1886     return o.release().ptr();
1887 }
1888 template <typename T>
1889 enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>,
1890                             detail::is_same_ignoring_cvref<T, PyObject *>,
1891                             std::is_void<T>>::value,
1892             T>
1893 cast_safe(object &&o) {
1894     return pybind11::cast<T>(std::move(o));
1895 }
1896 
1897 PYBIND11_NAMESPACE_END(detail)
1898 
1899 // The overloads could coexist, i.e. the #if is not strictly speaking needed,
1900 // but it is an easy minor optimization.
1901 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1902 inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name) {
1903     return cast_error("Unable to convert call argument '" + name
1904                       + "' to Python object (#define "
1905                         "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1906 }
1907 #else
1908 inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
1909                                                         const std::string &type) {
1910     return cast_error("Unable to convert call argument '" + name + "' of type '" + type
1911                       + "' to Python object");
1912 }
1913 #endif
1914 
1915 namespace typing {
1916 template <typename... Types>
1917 class Tuple : public tuple {
1918     using tuple::tuple;
1919 };
1920 } // namespace typing
1921 
1922 template <return_value_policy policy = return_value_policy::automatic_reference>
1923 typing::Tuple<> make_tuple() {
1924     return tuple(0);
1925 }
1926 
1927 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1928 typing::Tuple<Args...> make_tuple(Args &&...args_) {
1929     constexpr size_t size = sizeof...(Args);
1930     std::array<object, size> args{{reinterpret_steal<object>(
1931         detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
1932     for (size_t i = 0; i < args.size(); i++) {
1933         if (!args[i]) {
1934 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1935             throw cast_error_unable_to_convert_call_arg(std::to_string(i));
1936 #else
1937             std::array<std::string, size> argtypes{{type_id<Args>()...}};
1938             throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
1939 #endif
1940         }
1941     }
1942     tuple result(size);
1943     int counter = 0;
1944     for (auto &arg_value : args) {
1945         PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1946     }
1947     PYBIND11_WARNING_PUSH
1948 #ifdef PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
1949     PYBIND11_WARNING_DISABLE_CLANG("-Wreturn-std-move")
1950 #endif
1951     return result;
1952     PYBIND11_WARNING_POP
1953 }
1954 
1955 /// \ingroup annotations
1956 /// Annotation for arguments
1957 struct arg {
1958     /// Constructs an argument with the name of the argument; if null or omitted, this is a
1959     /// positional argument.
1960     constexpr explicit arg(const char *name = nullptr)
1961         : name(name), flag_noconvert(false), flag_none(true) {}
1962     /// Assign a value to this argument
1963     template <typename T>
1964     arg_v operator=(T &&value) const;
1965     /// Indicate that the type should not be converted in the type caster
1966     arg &noconvert(bool flag = true) {
1967         flag_noconvert = flag;
1968         return *this;
1969     }
1970     /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
1971     arg &none(bool flag = true) {
1972         flag_none = flag;
1973         return *this;
1974     }
1975 
1976     const char *name;        ///< If non-null, this is a named kwargs argument
1977     bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type
1978                              ///< caster!)
1979     bool flag_none : 1;      ///< If set (the default), allow None to be passed to this argument
1980 };
1981 
1982 /// \ingroup annotations
1983 /// Annotation for arguments with values
1984 struct arg_v : arg {
1985 private:
1986     template <typename T>
1987     arg_v(arg &&base, T &&x, const char *descr = nullptr)
1988         : arg(base), value(reinterpret_steal<object>(detail::make_caster<T>::cast(
1989                          std::forward<T>(x), return_value_policy::automatic, {}))),
1990           descr(descr)
1991 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1992           ,
1993           type(type_id<T>())
1994 #endif
1995     {
1996         // Workaround! See:
1997         // https://github.com/pybind/pybind11/issues/2336
1998         // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
1999         if (PyErr_Occurred()) {
2000             PyErr_Clear();
2001         }
2002     }
2003 
2004 public:
2005     /// Direct construction with name, default, and description
2006     template <typename T>
2007     arg_v(const char *name, T &&x, const char *descr = nullptr)
2008         : arg_v(arg(name), std::forward<T>(x), descr) {}
2009 
2010     /// Called internally when invoking `py::arg("a") = value`
2011     template <typename T>
2012     arg_v(const arg &base, T &&x, const char *descr = nullptr)
2013         : arg_v(arg(base), std::forward<T>(x), descr) {}
2014 
2015     /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
2016     arg_v &noconvert(bool flag = true) {
2017         arg::noconvert(flag);
2018         return *this;
2019     }
2020 
2021     /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
2022     arg_v &none(bool flag = true) {
2023         arg::none(flag);
2024         return *this;
2025     }
2026 
2027     /// The default value
2028     object value;
2029     /// The (optional) description of the default value
2030     const char *descr;
2031 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2032     /// The C++ type name of the default value (only available when compiled in debug mode)
2033     std::string type;
2034 #endif
2035 };
2036 
2037 /// \ingroup annotations
2038 /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of
2039 /// an unnamed '*' argument
2040 struct kw_only {};
2041 
2042 /// \ingroup annotations
2043 /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of
2044 /// an unnamed '/' argument
2045 struct pos_only {};
2046 
2047 template <typename T>
2048 arg_v arg::operator=(T &&value) const {
2049     return {*this, std::forward<T>(value)};
2050 }
2051 
2052 /// Alias for backward compatibility -- to be removed in version 2.0
2053 template <typename /*unused*/>
2054 using arg_t = arg_v;
2055 
2056 inline namespace literals {
2057 /** \rst
2058     String literal version of `arg`
2059  \endrst */
2060 constexpr arg
2061 #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
2062 operator"" _a // gcc 4.8.5 insists on having a space (hard error).
2063 #else
2064 operator""_a // clang 17 generates a deprecation warning if there is a space.
2065 #endif
2066     (const char *name, size_t) {
2067     return arg(name);
2068 }
2069 } // namespace literals
2070 
2071 PYBIND11_NAMESPACE_BEGIN(detail)
2072 
2073 template <typename T>
2074 using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
2075 template <typename T>
2076 using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
2077 
2078 // forward declaration (definition in attr.h)
2079 struct function_record;
2080 
2081 /// Inline size chosen mostly arbitrarily.
2082 constexpr std::size_t arg_vector_small_size = 6;
2083 
2084 /// Internal data associated with a single function call
2085 struct function_call {
2086     function_call(const function_record &f, handle p); // Implementation in attr.h
2087 
2088     /// The function data:
2089     const function_record &func;
2090 
2091     /// Arguments passed to the function:
2092     argument_vector<arg_vector_small_size> args;
2093 
2094     /// The `convert` value the arguments should be loaded with
2095     args_convert_vector<arg_vector_small_size> args_convert;
2096 
2097     /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
2098     /// present, are also in `args` but without a reference).
2099     object args_ref, kwargs_ref;
2100 
2101     /// The parent, if any
2102     handle parent;
2103 
2104     /// If this is a call to an initializer, this argument contains `self`
2105     handle init_self;
2106 };
2107 
2108 // See PR #5396 for the discussion that led to this
2109 template <typename Base, typename Derived, typename = void>
2110 struct is_same_or_base_of : std::is_same<Base, Derived> {};
2111 
2112 // Only evaluate is_base_of if Derived is complete.
2113 // is_base_of raises a compiler error if Derived is incomplete.
2114 template <typename Base, typename Derived>
2115 struct is_same_or_base_of<Base, Derived, decltype(void(sizeof(Derived)))>
2116     : any_of<std::is_same<Base, Derived>, std::is_base_of<Base, Derived>> {};
2117 
2118 /// Helper class which loads arguments for C++ functions called from Python
2119 template <typename... Args>
2120 class argument_loader {
2121     using indices = make_index_sequence<sizeof...(Args)>;
2122     template <typename Arg>
2123     using argument_is_args = is_same_or_base_of<args, intrinsic_t<Arg>>;
2124     template <typename Arg>
2125     using argument_is_kwargs = is_same_or_base_of<kwargs, intrinsic_t<Arg>>;
2126     // Get kwargs argument position, or -1 if not present:
2127     static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
2128 
2129     static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
2130                   "py::kwargs is only permitted as the last argument of a function");
2131 
2132 public:
2133     static constexpr bool has_kwargs = kwargs_pos != -1;
2134 
2135     // py::args argument position; -1 if not present.
2136     static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
2137 
2138     static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
2139                   "py::args cannot be specified more than once");
2140 
2141     static constexpr auto arg_names
2142         = ::pybind11::detail::concat(type_descr(make_caster<Args>::name)...);
2143 
2144     bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
2145 
2146     template <typename Return, typename Guard, typename Func>
2147     // NOLINTNEXTLINE(readability-const-return-type)
2148     enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
2149         return std::move(*this).template call_impl<remove_cv_t<Return>>(
2150             std::forward<Func>(f), indices{}, Guard{});
2151     }
2152 
2153     template <typename Return, typename Guard, typename Func>
2154     enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
2155         std::move(*this).template call_impl<remove_cv_t<Return>>(
2156             std::forward<Func>(f), indices{}, Guard{});
2157         return void_type();
2158     }
2159 
2160 private:
2161     static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
2162 
2163     template <size_t... Is>
2164     bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
2165         PYBIND11_WARNING_PUSH
2166 #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 13
2167         // Work around a GCC -Warray-bounds false positive in argument_vector usage.
2168         PYBIND11_WARNING_DISABLE_GCC("-Warray-bounds")
2169 #endif
2170 #ifdef __cpp_fold_expressions
2171         if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
2172             return false;
2173         }
2174 #else
2175         for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
2176             if (!r) {
2177                 return false;
2178             }
2179         }
2180 #endif
2181         PYBIND11_WARNING_POP
2182         return true;
2183     }
2184 
2185     template <typename Return, typename Func, size_t... Is, typename Guard>
2186     Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
2187         return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
2188     }
2189 
2190     std::tuple<make_caster<Args>...> argcasters;
2191 };
2192 
2193 // [workaround(intel)] Separate function required here
2194 // We need to put this into a separate function because the Intel compiler
2195 // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
2196 // (tested with ICC 2021.1 Beta 20200827).
2197 template <typename... Args>
2198 constexpr bool args_has_keyword_or_ds() {
2199     return any_of<is_keyword_or_ds<Args>...>::value;
2200 }
2201 
2202 /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
2203 template <return_value_policy policy>
2204 class unpacking_collector {
2205 public:
2206     template <typename... Ts>
2207     explicit unpacking_collector(Ts &&...values)
2208         : m_names(reinterpret_steal<tuple>(
2209               handle())) // initialize to null to avoid useless allocation of 0-length tuple
2210     {
2211         /*
2212         Python can sometimes utilize an extra space before the arguments to prepend `self`.
2213         This is important enough that there is a special flag for it:
2214         PY_VECTORCALL_ARGUMENTS_OFFSET.
2215         All we have to do is allocate an extra space at the beginning of this array, and set the
2216         flag. Note that the extra space is not passed directly in to vectorcall.
2217         */
2218         m_args.reserve(sizeof...(values) + 1);
2219         m_args.push_back_null();
2220 
2221         if (args_has_keyword_or_ds<Ts...>()) {
2222             list names_list;
2223 
2224             // collect_arguments guarantees this can't be constructed with kwargs before the last
2225             // positional so we don't need to worry about Ts... being in anything but normal python
2226             // order.
2227             using expander = int[];
2228             (void) expander{0, (process(names_list, std::forward<Ts>(values)), 0)...};
2229 
2230             m_names = reinterpret_steal<tuple>(PyList_AsTuple(names_list.ptr()));
2231         } else {
2232             auto not_used
2233                 = reinterpret_steal<list>(handle()); // initialize as null (to avoid an allocation)
2234 
2235             using expander = int[];
2236             (void) expander{0, (process(not_used, std::forward<Ts>(values)), 0)...};
2237         }
2238     }
2239 
2240     /// Call a Python function and pass the collected arguments
2241     object call(PyObject *ptr) const {
2242         size_t nargs = m_args.size() - 1; // -1 for PY_VECTORCALL_ARGUMENTS_OFFSET (see ctor)
2243         if (m_names) {
2244             nargs -= m_names.size();
2245         }
2246         PyObject *result = _PyObject_Vectorcall(
2247             ptr, m_args.data() + 1, nargs | PY_VECTORCALL_ARGUMENTS_OFFSET, m_names.ptr());
2248         if (!result) {
2249             throw error_already_set();
2250         }
2251         return reinterpret_steal<object>(result);
2252     }
2253 
2254     tuple args() const {
2255         size_t nargs = m_args.size() - 1; // -1 for PY_VECTORCALL_ARGUMENTS_OFFSET (see ctor)
2256         if (m_names) {
2257             nargs -= m_names.size();
2258         }
2259         tuple val(nargs);
2260         for (size_t i = 0; i < nargs; ++i) {
2261             // +1 for PY_VECTORCALL_ARGUMENTS_OFFSET (see ctor)
2262             val[i] = reinterpret_borrow<object>(m_args[i + 1]);
2263         }
2264         return val;
2265     }
2266 
2267     dict kwargs() const {
2268         dict val;
2269         if (m_names) {
2270             size_t offset = m_args.size() - m_names.size();
2271             for (size_t i = 0; i < m_names.size(); ++i, ++offset) {
2272                 val[m_names[i]] = reinterpret_borrow<object>(m_args[offset]);
2273             }
2274         }
2275         return val;
2276     }
2277 
2278 private:
2279     // normal argument, possibly needing conversion
2280     template <typename T>
2281     void process(list & /*names_list*/, T &&x) {
2282         handle h = detail::make_caster<T>::cast(std::forward<T>(x), policy, {});
2283         if (!h) {
2284 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2285             throw cast_error_unable_to_convert_call_arg(std::to_string(m_args.size() - 1));
2286 #else
2287             throw cast_error_unable_to_convert_call_arg(std::to_string(m_args.size() - 1),
2288                                                         type_id<T>());
2289 #endif
2290         }
2291         m_args.push_back_steal(h.ptr()); // cast returns a new reference
2292     }
2293 
2294     // * unpacking
2295     void process(list & /*names_list*/, detail::args_proxy ap) {
2296         if (!ap) {
2297             return;
2298         }
2299         for (auto a : ap) {
2300             m_args.push_back_borrow(a.ptr());
2301         }
2302     }
2303 
2304     // named argument
2305     // NOLINTNEXTLINE(performance-unnecessary-value-param)
2306     void process(list &names_list, arg_v a) {
2307         assert(names_list);
2308         if (!a.name) {
2309 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2310             nameless_argument_error();
2311 #else
2312             nameless_argument_error(a.type);
2313 #endif
2314         }
2315         auto name = str(a.name);
2316         if (names_list.contains(name)) {
2317 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2318             multiple_values_error();
2319 #else
2320             multiple_values_error(a.name);
2321 #endif
2322         }
2323         if (!a.value) {
2324 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2325             throw cast_error_unable_to_convert_call_arg(a.name);
2326 #else
2327             throw cast_error_unable_to_convert_call_arg(a.name, a.type);
2328 #endif
2329         }
2330         names_list.append(std::move(name));
2331         m_args.push_back_borrow(a.value.ptr());
2332     }
2333 
2334     // ** unpacking
2335     void process(list &names_list, detail::kwargs_proxy kp) {
2336         if (!kp) {
2337             return;
2338         }
2339         assert(names_list);
2340         for (auto &&k : reinterpret_borrow<dict>(kp)) {
2341             auto name = str(k.first);
2342             if (names_list.contains(name)) {
2343 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
2344                 multiple_values_error();
2345 #else
2346                 multiple_values_error(name);
2347 #endif
2348             }
2349             names_list.append(std::move(name));
2350             m_args.push_back_borrow(k.second.ptr());
2351         }
2352     }
2353 
2354     [[noreturn]] static void nameless_argument_error() {
2355         throw type_error(
2356             "Got kwargs without a name; only named arguments "
2357             "may be passed via py::arg() to a python function call. "
2358             "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
2359     }
2360     [[noreturn]] static void nameless_argument_error(const std::string &type) {
2361         throw type_error("Got kwargs without a name of type '" + type
2362                          + "'; only named "
2363                            "arguments may be passed via py::arg() to a python function call. ");
2364     }
2365     [[noreturn]] static void multiple_values_error() {
2366         throw type_error(
2367             "Got multiple values for keyword argument "
2368             "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
2369     }
2370 
2371     [[noreturn]] static void multiple_values_error(const std::string &name) {
2372         throw type_error("Got multiple values for keyword argument '" + name + "'");
2373     }
2374 
2375 private:
2376     ref_small_vector<arg_vector_small_size> m_args;
2377     tuple m_names;
2378 };
2379 
2380 /// Collect all arguments, including keywords and unpacking
2381 template <return_value_policy policy, typename... Args>
2382 unpacking_collector<policy> collect_arguments(Args &&...args) {
2383     // Following argument order rules for generalized unpacking according to PEP 448
2384     static_assert(
2385         constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>(),
2386         "Invalid function call: positional args must precede keywords and */** unpacking;");
2387     static_assert(constexpr_last<is_s_unpacking, Args...>()
2388                       < constexpr_first<is_ds_unpacking, Args...>(),
2389                   "Invalid function call: * unpacking must precede ** unpacking");
2390     return unpacking_collector<policy>(std::forward<Args>(args)...);
2391 }
2392 
2393 template <typename Derived>
2394 template <return_value_policy policy, typename... Args>
2395 object object_api<Derived>::operator()(Args &&...args) const {
2396 #ifndef NDEBUG
2397     if (!PyGILState_Check()) {
2398         pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
2399     }
2400 #endif
2401     return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
2402 }
2403 
2404 template <typename Derived>
2405 template <return_value_policy policy, typename... Args>
2406 object object_api<Derived>::call(Args &&...args) const {
2407     return operator()<policy>(std::forward<Args>(args)...);
2408 }
2409 
2410 PYBIND11_NAMESPACE_END(detail)
2411 
2412 template <typename T>
2413 handle type::handle_of() {
2414     static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
2415                   "py::type::of<T> only supports the case where T is a registered C++ types.");
2416 
2417     return detail::get_type_handle(typeid(T), true);
2418 }
2419 
2420 #define PYBIND11_MAKE_OPAQUE(...)                                                                 \
2421     PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)                                                  \
2422     namespace detail {                                                                            \
2423     template <>                                                                                   \
2424     class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {};                     \
2425     }                                                                                             \
2426     PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
2427 
2428 /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
2429 /// typedef, e.g.:
2430 /// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
2431 #define PYBIND11_TYPE(...) __VA_ARGS__
2432 
2433 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)