File indexing completed on 2025-01-18 10:17:46
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011 #pragma once
0012
0013 #include "detail/common.h"
0014 #include "detail/descr.h"
0015 #include "detail/type_caster_base.h"
0016 #include "detail/typeid.h"
0017 #include "pytypes.h"
0018
0019 #include <array>
0020 #include <cstring>
0021 #include <functional>
0022 #include <iosfwd>
0023 #include <iterator>
0024 #include <memory>
0025 #include <string>
0026 #include <tuple>
0027 #include <type_traits>
0028 #include <utility>
0029 #include <vector>
0030
0031 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0032
0033 PYBIND11_WARNING_DISABLE_MSVC(4127)
0034
0035 PYBIND11_NAMESPACE_BEGIN(detail)
0036
0037 template <typename type, typename SFINAE = void>
0038 class type_caster : public type_caster_base<type> {};
0039 template <typename type>
0040 using make_caster = type_caster<intrinsic_t<type>>;
0041
0042
0043 template <typename T>
0044 typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
0045 return caster.operator typename make_caster<T>::template cast_op_type<T>();
0046 }
0047 template <typename T>
0048 typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
0049 cast_op(make_caster<T> &&caster) {
0050 return std::move(caster).operator typename make_caster<T>::
0051 template cast_op_type<typename std::add_rvalue_reference<T>::type>();
0052 }
0053
0054 template <typename type>
0055 class type_caster<std::reference_wrapper<type>> {
0056 private:
0057 using caster_t = make_caster<type>;
0058 caster_t subcaster;
0059 using reference_t = type &;
0060 using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
0061
0062 static_assert(
0063 std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
0064 || std::is_same<reference_t, subcaster_cast_op_type>::value,
0065 "std::reference_wrapper<T> caster requires T to have a caster with an "
0066 "`operator T &()` or `operator const T &()`");
0067
0068 public:
0069 bool load(handle src, bool convert) { return subcaster.load(src, convert); }
0070 static constexpr auto name = caster_t::name;
0071 static handle
0072 cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
0073
0074 if (policy == return_value_policy::take_ownership
0075 || policy == return_value_policy::automatic) {
0076 policy = return_value_policy::automatic_reference;
0077 }
0078 return caster_t::cast(&src.get(), policy, parent);
0079 }
0080 template <typename T>
0081 using cast_op_type = std::reference_wrapper<type>;
0082 explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
0083 };
0084
0085 #define PYBIND11_TYPE_CASTER(type, py_name) \
0086 protected: \
0087 type value; \
0088 \
0089 public: \
0090 static constexpr auto name = py_name; \
0091 template <typename T_, \
0092 ::pybind11::detail::enable_if_t< \
0093 std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value, \
0094 int> \
0095 = 0> \
0096 static ::pybind11::handle cast( \
0097 T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) { \
0098 if (!src) \
0099 return ::pybind11::none().release(); \
0100 if (policy == ::pybind11::return_value_policy::take_ownership) { \
0101 auto h = cast(std::move(*src), policy, parent); \
0102 delete src; \
0103 return h; \
0104 } \
0105 return cast(*src, policy, parent); \
0106 } \
0107 operator type *() { return &value; } \
0108 operator type &() { return value; } \
0109 operator type &&() && { return std::move(value); } \
0110 template <typename T_> \
0111 using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
0112
0113 template <typename CharT>
0114 using is_std_char_type = any_of<std::is_same<CharT, char>,
0115 #if defined(PYBIND11_HAS_U8STRING)
0116 std::is_same<CharT, char8_t>,
0117 #endif
0118 std::is_same<CharT, char16_t>,
0119 std::is_same<CharT, char32_t>,
0120 std::is_same<CharT, wchar_t>
0121 >;
0122
0123 template <typename T>
0124 struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
0125 using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
0126 using _py_type_1 = conditional_t<std::is_signed<T>::value,
0127 _py_type_0,
0128 typename std::make_unsigned<_py_type_0>::type>;
0129 using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
0130
0131 public:
0132 bool load(handle src, bool convert) {
0133 py_type py_value;
0134
0135 if (!src) {
0136 return false;
0137 }
0138
0139 #if !defined(PYPY_VERSION)
0140 auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
0141 #else
0142
0143
0144 auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
0145 #endif
0146
0147 if (std::is_floating_point<T>::value) {
0148 if (convert || PyFloat_Check(src.ptr())) {
0149 py_value = (py_type) PyFloat_AsDouble(src.ptr());
0150 } else {
0151 return false;
0152 }
0153 } else if (PyFloat_Check(src.ptr())
0154 || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
0155 return false;
0156 } else {
0157 handle src_or_index = src;
0158
0159 #if PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
0160 object index;
0161 if (!PYBIND11_LONG_CHECK(src.ptr())) {
0162 index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
0163 if (!index) {
0164 PyErr_Clear();
0165 if (!convert)
0166 return false;
0167 } else {
0168 src_or_index = index;
0169 }
0170 }
0171 #endif
0172 if (std::is_unsigned<py_type>::value) {
0173 py_value = as_unsigned<py_type>(src_or_index.ptr());
0174 } else {
0175 py_value = sizeof(T) <= sizeof(long)
0176 ? (py_type) PyLong_AsLong(src_or_index.ptr())
0177 : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
0178 }
0179 }
0180
0181
0182 bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
0183
0184
0185
0186 if (py_err
0187 || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
0188 && py_value != (py_type) (T) py_value)) {
0189 PyErr_Clear();
0190 if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
0191 auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
0192 ? PyNumber_Float(src.ptr())
0193 : PyNumber_Long(src.ptr()));
0194 PyErr_Clear();
0195 return load(tmp, false);
0196 }
0197 return false;
0198 }
0199
0200 value = (T) py_value;
0201 return true;
0202 }
0203
0204 template <typename U = T>
0205 static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
0206 cast(U src, return_value_policy , handle ) {
0207 return PyFloat_FromDouble((double) src);
0208 }
0209
0210 template <typename U = T>
0211 static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
0212 && (sizeof(U) <= sizeof(long)),
0213 handle>::type
0214 cast(U src, return_value_policy , handle ) {
0215 return PYBIND11_LONG_FROM_SIGNED((long) src);
0216 }
0217
0218 template <typename U = T>
0219 static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
0220 && (sizeof(U) <= sizeof(unsigned long)),
0221 handle>::type
0222 cast(U src, return_value_policy , handle ) {
0223 return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
0224 }
0225
0226 template <typename U = T>
0227 static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
0228 && (sizeof(U) > sizeof(long)),
0229 handle>::type
0230 cast(U src, return_value_policy , handle ) {
0231 return PyLong_FromLongLong((long long) src);
0232 }
0233
0234 template <typename U = T>
0235 static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
0236 && (sizeof(U) > sizeof(unsigned long)),
0237 handle>::type
0238 cast(U src, return_value_policy , handle ) {
0239 return PyLong_FromUnsignedLongLong((unsigned long long) src);
0240 }
0241
0242 PYBIND11_TYPE_CASTER(T, const_name<std::is_integral<T>::value>("int", "float"));
0243 };
0244
0245 template <typename T>
0246 struct void_caster {
0247 public:
0248 bool load(handle src, bool) {
0249 if (src && src.is_none()) {
0250 return true;
0251 }
0252 return false;
0253 }
0254 static handle cast(T, return_value_policy , handle ) {
0255 return none().release();
0256 }
0257 PYBIND11_TYPE_CASTER(T, const_name("None"));
0258 };
0259
0260 template <>
0261 class type_caster<void_type> : public void_caster<void_type> {};
0262
0263 template <>
0264 class type_caster<void> : public type_caster<void_type> {
0265 public:
0266 using type_caster<void_type>::cast;
0267
0268 bool load(handle h, bool) {
0269 if (!h) {
0270 return false;
0271 }
0272 if (h.is_none()) {
0273 value = nullptr;
0274 return true;
0275 }
0276
0277
0278 if (isinstance<capsule>(h)) {
0279 value = reinterpret_borrow<capsule>(h);
0280 return true;
0281 }
0282
0283
0284 const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
0285 if (bases.size() == 1) {
0286 value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
0287 return true;
0288 }
0289
0290
0291 return false;
0292 }
0293
0294 static handle cast(const void *ptr, return_value_policy , handle ) {
0295 if (ptr) {
0296 return capsule(ptr).release();
0297 }
0298 return none().release();
0299 }
0300
0301 template <typename T>
0302 using cast_op_type = void *&;
0303 explicit operator void *&() { return value; }
0304 static constexpr auto name = const_name("capsule");
0305
0306 private:
0307 void *value = nullptr;
0308 };
0309
0310 template <>
0311 class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
0312
0313 template <>
0314 class type_caster<bool> {
0315 public:
0316 bool load(handle src, bool convert) {
0317 if (!src) {
0318 return false;
0319 }
0320 if (src.ptr() == Py_True) {
0321 value = true;
0322 return true;
0323 }
0324 if (src.ptr() == Py_False) {
0325 value = false;
0326 return true;
0327 }
0328 if (convert || (std::strcmp("numpy.bool_", Py_TYPE(src.ptr())->tp_name) == 0)) {
0329
0330
0331 Py_ssize_t res = -1;
0332 if (src.is_none()) {
0333 res = 0;
0334 }
0335 #if defined(PYPY_VERSION)
0336
0337 else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
0338 res = PyObject_IsTrue(src.ptr());
0339 }
0340 #else
0341
0342
0343 else if (auto *tp_as_number = src.ptr()->ob_type->tp_as_number) {
0344 if (PYBIND11_NB_BOOL(tp_as_number)) {
0345 res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
0346 }
0347 }
0348 #endif
0349 if (res == 0 || res == 1) {
0350 value = (res != 0);
0351 return true;
0352 }
0353 PyErr_Clear();
0354 }
0355 return false;
0356 }
0357 static handle cast(bool src, return_value_policy , handle ) {
0358 return handle(src ? Py_True : Py_False).inc_ref();
0359 }
0360 PYBIND11_TYPE_CASTER(bool, const_name("bool"));
0361 };
0362
0363
0364 template <typename StringType, bool IsView = false>
0365 struct string_caster {
0366 using CharT = typename StringType::value_type;
0367
0368
0369
0370 static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
0371 "Unsupported char size != 1");
0372 #if defined(PYBIND11_HAS_U8STRING)
0373 static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
0374 "Unsupported char8_t size != 1");
0375 #endif
0376 static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
0377 "Unsupported char16_t size != 2");
0378 static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
0379 "Unsupported char32_t size != 4");
0380
0381 static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
0382 "Unsupported wchar_t size != 2/4");
0383 static constexpr size_t UTF_N = 8 * sizeof(CharT);
0384
0385 bool load(handle src, bool) {
0386 handle load_src = src;
0387 if (!src) {
0388 return false;
0389 }
0390 if (!PyUnicode_Check(load_src.ptr())) {
0391 return load_raw(load_src);
0392 }
0393
0394
0395
0396 if (UTF_N == 8) {
0397 Py_ssize_t size = -1;
0398 const auto *buffer
0399 = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
0400 if (!buffer) {
0401 PyErr_Clear();
0402 return false;
0403 }
0404 value = StringType(buffer, static_cast<size_t>(size));
0405 return true;
0406 }
0407
0408 auto utfNbytes
0409 = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
0410 UTF_N == 8 ? "utf-8"
0411 : UTF_N == 16 ? "utf-16"
0412 : "utf-32",
0413 nullptr));
0414 if (!utfNbytes) {
0415 PyErr_Clear();
0416 return false;
0417 }
0418
0419 const auto *buffer
0420 = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
0421 size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
0422
0423 if (UTF_N > 8) {
0424 buffer++;
0425 length--;
0426 }
0427 value = StringType(buffer, length);
0428
0429
0430 if (IsView) {
0431 loader_life_support::add_patient(utfNbytes);
0432 }
0433
0434 return true;
0435 }
0436
0437 static handle
0438 cast(const StringType &src, return_value_policy , handle ) {
0439 const char *buffer = reinterpret_cast<const char *>(src.data());
0440 auto nbytes = ssize_t(src.size() * sizeof(CharT));
0441 handle s = decode_utfN(buffer, nbytes);
0442 if (!s) {
0443 throw error_already_set();
0444 }
0445 return s;
0446 }
0447
0448 PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
0449
0450 private:
0451 static handle decode_utfN(const char *buffer, ssize_t nbytes) {
0452 #if !defined(PYPY_VERSION)
0453 return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
0454 : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
0455 : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
0456 #else
0457
0458
0459
0460 return PyUnicode_Decode(buffer,
0461 nbytes,
0462 UTF_N == 8 ? "utf-8"
0463 : UTF_N == 16 ? "utf-16"
0464 : "utf-32",
0465 nullptr);
0466 #endif
0467 }
0468
0469
0470
0471
0472 template <typename C = CharT>
0473 bool load_raw(enable_if_t<std::is_same<C, char>::value, handle> src) {
0474 if (PYBIND11_BYTES_CHECK(src.ptr())) {
0475
0476
0477 const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
0478 if (!bytes) {
0479 pybind11_fail("Unexpected PYBIND11_BYTES_AS_STRING() failure.");
0480 }
0481 value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
0482 return true;
0483 }
0484 if (PyByteArray_Check(src.ptr())) {
0485
0486
0487 const char *bytearray = PyByteArray_AsString(src.ptr());
0488 if (!bytearray) {
0489 pybind11_fail("Unexpected PyByteArray_AsString() failure.");
0490 }
0491 value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr()));
0492 return true;
0493 }
0494
0495 return false;
0496 }
0497
0498 template <typename C = CharT>
0499 bool load_raw(enable_if_t<!std::is_same<C, char>::value, handle>) {
0500 return false;
0501 }
0502 };
0503
0504 template <typename CharT, class Traits, class Allocator>
0505 struct type_caster<std::basic_string<CharT, Traits, Allocator>,
0506 enable_if_t<is_std_char_type<CharT>::value>>
0507 : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
0508
0509 #ifdef PYBIND11_HAS_STRING_VIEW
0510 template <typename CharT, class Traits>
0511 struct type_caster<std::basic_string_view<CharT, Traits>,
0512 enable_if_t<is_std_char_type<CharT>::value>>
0513 : string_caster<std::basic_string_view<CharT, Traits>, true> {};
0514 #endif
0515
0516
0517
0518 template <typename CharT>
0519 struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
0520 using StringType = std::basic_string<CharT>;
0521 using StringCaster = make_caster<StringType>;
0522 StringCaster str_caster;
0523 bool none = false;
0524 CharT one_char = 0;
0525
0526 public:
0527 bool load(handle src, bool convert) {
0528 if (!src) {
0529 return false;
0530 }
0531 if (src.is_none()) {
0532
0533 if (!convert) {
0534 return false;
0535 }
0536 none = true;
0537 return true;
0538 }
0539 return str_caster.load(src, convert);
0540 }
0541
0542 static handle cast(const CharT *src, return_value_policy policy, handle parent) {
0543 if (src == nullptr) {
0544 return pybind11::none().release();
0545 }
0546 return StringCaster::cast(StringType(src), policy, parent);
0547 }
0548
0549 static handle cast(CharT src, return_value_policy policy, handle parent) {
0550 if (std::is_same<char, CharT>::value) {
0551 handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
0552 if (!s) {
0553 throw error_already_set();
0554 }
0555 return s;
0556 }
0557 return StringCaster::cast(StringType(1, src), policy, parent);
0558 }
0559
0560 explicit operator CharT *() {
0561 return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
0562 }
0563 explicit operator CharT &() {
0564 if (none) {
0565 throw value_error("Cannot convert None to a character");
0566 }
0567
0568 auto &value = static_cast<StringType &>(str_caster);
0569 size_t str_len = value.size();
0570 if (str_len == 0) {
0571 throw value_error("Cannot convert empty string to a character");
0572 }
0573
0574
0575
0576
0577
0578
0579 if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
0580 auto v0 = static_cast<unsigned char>(value[0]);
0581
0582
0583
0584
0585 size_t char0_bytes = (v0 & 0x80) == 0 ? 1
0586 : (v0 & 0xE0) == 0xC0 ? 2
0587 : (v0 & 0xF0) == 0xE0 ? 3
0588 : 4;
0589
0590 if (char0_bytes == str_len) {
0591
0592 if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) {
0593 one_char = static_cast<CharT>(((v0 & 3) << 6)
0594 + (static_cast<unsigned char>(value[1]) & 0x3F));
0595 return one_char;
0596 }
0597
0598 throw value_error("Character code point not in range(0x100)");
0599 }
0600 }
0601
0602
0603
0604
0605 else if (StringCaster::UTF_N == 16 && str_len == 2) {
0606 one_char = static_cast<CharT>(value[0]);
0607 if (one_char >= 0xD800 && one_char < 0xE000) {
0608 throw value_error("Character code point not in range(0x10000)");
0609 }
0610 }
0611
0612 if (str_len != 1) {
0613 throw value_error("Expected a character, but multi-character string found");
0614 }
0615
0616 one_char = value[0];
0617 return one_char;
0618 }
0619
0620 static constexpr auto name = const_name(PYBIND11_STRING_NAME);
0621 template <typename _T>
0622 using cast_op_type = pybind11::detail::cast_op_type<_T>;
0623 };
0624
0625
0626 template <template <typename...> class Tuple, typename... Ts>
0627 class tuple_caster {
0628 using type = Tuple<Ts...>;
0629 static constexpr auto size = sizeof...(Ts);
0630 using indices = make_index_sequence<size>;
0631
0632 public:
0633 bool load(handle src, bool convert) {
0634 if (!isinstance<sequence>(src)) {
0635 return false;
0636 }
0637 const auto seq = reinterpret_borrow<sequence>(src);
0638 if (seq.size() != size) {
0639 return false;
0640 }
0641 return load_impl(seq, convert, indices{});
0642 }
0643
0644 template <typename T>
0645 static handle cast(T &&src, return_value_policy policy, handle parent) {
0646 return cast_impl(std::forward<T>(src), policy, parent, indices{});
0647 }
0648
0649
0650 template <typename T>
0651 static handle cast(T *src, return_value_policy policy, handle parent) {
0652 if (!src) {
0653 return none().release();
0654 }
0655 if (policy == return_value_policy::take_ownership) {
0656 auto h = cast(std::move(*src), policy, parent);
0657 delete src;
0658 return h;
0659 }
0660 return cast(*src, policy, parent);
0661 }
0662
0663 static constexpr auto name
0664 = const_name("Tuple[") + concat(make_caster<Ts>::name...) + const_name("]");
0665
0666 template <typename T>
0667 using cast_op_type = type;
0668
0669 explicit operator type() & { return implicit_cast(indices{}); }
0670 explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
0671
0672 protected:
0673 template <size_t... Is>
0674 type implicit_cast(index_sequence<Is...>) & {
0675 return type(cast_op<Ts>(std::get<Is>(subcasters))...);
0676 }
0677 template <size_t... Is>
0678 type implicit_cast(index_sequence<Is...>) && {
0679 return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
0680 }
0681
0682 static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
0683
0684 template <size_t... Is>
0685 bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
0686 #ifdef __cpp_fold_expressions
0687 if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
0688 return false;
0689 }
0690 #else
0691 for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
0692 if (!r) {
0693 return false;
0694 }
0695 }
0696 #endif
0697 return true;
0698 }
0699
0700
0701 template <typename T, size_t... Is>
0702 static handle
0703 cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
0704 PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
0705 PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
0706 std::array<object, size> entries{{reinterpret_steal<object>(
0707 make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
0708 for (const auto &entry : entries) {
0709 if (!entry) {
0710 return handle();
0711 }
0712 }
0713 tuple result(size);
0714 int counter = 0;
0715 for (auto &entry : entries) {
0716 PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
0717 }
0718 return result.release();
0719 }
0720
0721 Tuple<make_caster<Ts>...> subcasters;
0722 };
0723
0724 template <typename T1, typename T2>
0725 class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
0726
0727 template <typename... Ts>
0728 class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
0729
0730
0731
0732 template <typename T>
0733 struct holder_helper {
0734 static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
0735 };
0736
0737
0738
0739
0740
0741
0742 template <typename type, typename holder_type, typename SFINAE = void>
0743 struct copyable_holder_caster : public type_caster_base<type> {
0744 public:
0745 using base = type_caster_base<type>;
0746 static_assert(std::is_base_of<base, type_caster<type>>::value,
0747 "Holder classes are only supported for custom types");
0748 using base::base;
0749 using base::cast;
0750 using base::typeinfo;
0751 using base::value;
0752
0753 bool load(handle src, bool convert) {
0754 return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
0755 }
0756
0757 explicit operator type *() { return this->value; }
0758
0759
0760 explicit operator type &() { return *(static_cast<type *>(this->value)); }
0761 explicit operator holder_type *() { return std::addressof(holder); }
0762 explicit operator holder_type &() { return holder; }
0763
0764 static handle cast(const holder_type &src, return_value_policy, handle) {
0765 const auto *ptr = holder_helper<holder_type>::get(src);
0766 return type_caster_base<type>::cast_holder(ptr, &src);
0767 }
0768
0769 protected:
0770 friend class type_caster_generic;
0771 void check_holder_compat() {
0772 if (typeinfo->default_holder) {
0773 throw cast_error("Unable to load a custom holder type from a default-holder instance");
0774 }
0775 }
0776
0777 bool load_value(value_and_holder &&v_h) {
0778 if (v_h.holder_constructed()) {
0779 value = v_h.value_ptr();
0780 holder = v_h.template holder<holder_type>();
0781 return true;
0782 }
0783 throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
0784 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
0785 "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
0786 "type information)");
0787 #else
0788 "of type '"
0789 + type_id<holder_type>() + "''");
0790 #endif
0791 }
0792
0793 template <typename T = holder_type,
0794 detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
0795 bool try_implicit_casts(handle, bool) {
0796 return false;
0797 }
0798
0799 template <typename T = holder_type,
0800 detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
0801 bool try_implicit_casts(handle src, bool convert) {
0802 for (auto &cast : typeinfo->implicit_casts) {
0803 copyable_holder_caster sub_caster(*cast.first);
0804 if (sub_caster.load(src, convert)) {
0805 value = cast.second(sub_caster.value);
0806 holder = holder_type(sub_caster.holder, (type *) value);
0807 return true;
0808 }
0809 }
0810 return false;
0811 }
0812
0813 static bool try_direct_conversions(handle) { return false; }
0814
0815 holder_type holder;
0816 };
0817
0818
0819 template <typename T>
0820 class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
0821
0822
0823
0824
0825 template <typename type, typename holder_type, typename SFINAE = void>
0826 struct move_only_holder_caster {
0827 static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
0828 "Holder classes are only supported for custom types");
0829
0830 static handle cast(holder_type &&src, return_value_policy, handle) {
0831 auto *ptr = holder_helper<holder_type>::get(src);
0832 return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
0833 }
0834 static constexpr auto name = type_caster_base<type>::name;
0835 };
0836
0837 template <typename type, typename deleter>
0838 class type_caster<std::unique_ptr<type, deleter>>
0839 : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
0840
0841 template <typename type, typename holder_type>
0842 using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
0843 copyable_holder_caster<type, holder_type>,
0844 move_only_holder_caster<type, holder_type>>;
0845
0846 template <typename T, bool Value = false>
0847 struct always_construct_holder {
0848 static constexpr bool value = Value;
0849 };
0850
0851
0852 #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
0853 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
0854 namespace detail { \
0855 template <typename type> \
0856 struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { \
0857 }; \
0858 template <typename type> \
0859 class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
0860 : public type_caster_holder<type, holder_type> {}; \
0861 } \
0862 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
0863
0864
0865 template <typename base, typename holder>
0866 struct is_holder_type
0867 : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
0868
0869 template <typename base, typename deleter>
0870 struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
0871
0872 template <typename T>
0873 struct handle_type_name {
0874 static constexpr auto name = const_name<T>();
0875 };
0876 template <>
0877 struct handle_type_name<bool_> {
0878 static constexpr auto name = const_name("bool");
0879 };
0880 template <>
0881 struct handle_type_name<bytes> {
0882 static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
0883 };
0884 template <>
0885 struct handle_type_name<int_> {
0886 static constexpr auto name = const_name("int");
0887 };
0888 template <>
0889 struct handle_type_name<iterable> {
0890 static constexpr auto name = const_name("Iterable");
0891 };
0892 template <>
0893 struct handle_type_name<iterator> {
0894 static constexpr auto name = const_name("Iterator");
0895 };
0896 template <>
0897 struct handle_type_name<float_> {
0898 static constexpr auto name = const_name("float");
0899 };
0900 template <>
0901 struct handle_type_name<none> {
0902 static constexpr auto name = const_name("None");
0903 };
0904 template <>
0905 struct handle_type_name<args> {
0906 static constexpr auto name = const_name("*args");
0907 };
0908 template <>
0909 struct handle_type_name<kwargs> {
0910 static constexpr auto name = const_name("**kwargs");
0911 };
0912
0913 template <typename type>
0914 struct pyobject_caster {
0915 template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
0916 pyobject_caster() : value() {}
0917
0918
0919
0920 template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
0921 pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
0922
0923 template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
0924 bool load(handle src, bool ) {
0925 value = src;
0926 return static_cast<bool>(value);
0927 }
0928
0929 template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
0930 bool load(handle src, bool ) {
0931 if (!isinstance<type>(src)) {
0932 return false;
0933 }
0934 value = reinterpret_borrow<type>(src);
0935 return true;
0936 }
0937
0938 static handle cast(const handle &src, return_value_policy , handle ) {
0939 return src.inc_ref();
0940 }
0941 PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
0942 };
0943
0944 template <typename T>
0945 class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
0946
0947
0948
0949
0950
0951
0952
0953
0954
0955
0956 template <typename T>
0957 using move_is_plain_type
0958 = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
0959 template <typename T, typename SFINAE = void>
0960 struct move_always : std::false_type {};
0961 template <typename T>
0962 struct move_always<
0963 T,
0964 enable_if_t<
0965 all_of<move_is_plain_type<T>,
0966 negation<is_copy_constructible<T>>,
0967 std::is_move_constructible<T>,
0968 std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
0969 : std::true_type {};
0970 template <typename T, typename SFINAE = void>
0971 struct move_if_unreferenced : std::false_type {};
0972 template <typename T>
0973 struct move_if_unreferenced<
0974 T,
0975 enable_if_t<
0976 all_of<move_is_plain_type<T>,
0977 negation<move_always<T>>,
0978 std::is_move_constructible<T>,
0979 std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
0980 : std::true_type {};
0981 template <typename T>
0982 using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
0983
0984
0985
0986
0987
0988 template <typename type>
0989 using cast_is_temporary_value_reference
0990 = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
0991 && !std::is_base_of<type_caster_generic, make_caster<type>>::value
0992 && !std::is_same<intrinsic_t<type>, void>::value>;
0993
0994
0995
0996
0997 template <typename Return, typename SFINAE = void>
0998 struct return_value_policy_override {
0999 static return_value_policy policy(return_value_policy p) { return p; }
1000 };
1001
1002 template <typename Return>
1003 struct return_value_policy_override<
1004 Return,
1005 detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1006 static return_value_policy policy(return_value_policy p) {
1007 return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
1008 ? return_value_policy::move
1009 : p;
1010 }
1011 };
1012
1013
1014 template <typename T, typename SFINAE>
1015 type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
1016 static_assert(!detail::is_pyobject<T>::value,
1017 "Internal error: type_caster should only be used for C++ types");
1018 if (!conv.load(handle, true)) {
1019 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1020 throw cast_error("Unable to cast Python instance to C++ type (#define "
1021 "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1022 #else
1023 throw cast_error("Unable to cast Python instance of type "
1024 + (std::string) str(type::handle_of(handle)) + " to C++ type '"
1025 + type_id<T>() + "'");
1026 #endif
1027 }
1028 return conv;
1029 }
1030
1031 template <typename T>
1032 make_caster<T> load_type(const handle &handle) {
1033 make_caster<T> conv;
1034 load_type(conv, handle);
1035 return conv;
1036 }
1037
1038 PYBIND11_NAMESPACE_END(detail)
1039
1040
1041 template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1042 T cast(const handle &handle) {
1043 using namespace detail;
1044 static_assert(!cast_is_temporary_value_reference<T>::value,
1045 "Unable to cast type to reference: value is local to type caster");
1046 return cast_op<T>(load_type<T>(handle));
1047 }
1048
1049
1050 template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
1051 T cast(const handle &handle) {
1052 return T(reinterpret_borrow<object>(handle));
1053 }
1054
1055
1056 template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1057 object cast(T &&value,
1058 return_value_policy policy = return_value_policy::automatic_reference,
1059 handle parent = handle()) {
1060 using no_ref_T = typename std::remove_reference<T>::type;
1061 if (policy == return_value_policy::automatic) {
1062 policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
1063 : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1064 : return_value_policy::move;
1065 } else if (policy == return_value_policy::automatic_reference) {
1066 policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
1067 : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1068 : return_value_policy::move;
1069 }
1070 return reinterpret_steal<object>(
1071 detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
1072 }
1073
1074 template <typename T>
1075 T handle::cast() const {
1076 return pybind11::cast<T>(*this);
1077 }
1078 template <>
1079 inline void handle::cast() const {
1080 return;
1081 }
1082
1083 template <typename T>
1084 detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
1085 if (obj.ref_count() > 1) {
1086 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1087 throw cast_error(
1088 "Unable to cast Python instance to C++ rvalue: instance has multiple references"
1089 " (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1090 #else
1091 throw cast_error("Unable to move from Python " + (std::string) str(type::handle_of(obj))
1092 + " instance to C++ " + type_id<T>()
1093 + " instance: instance has multiple references");
1094 #endif
1095 }
1096
1097
1098 T ret = std::move(detail::load_type<T>(obj).operator T &());
1099 return ret;
1100 }
1101
1102
1103
1104
1105
1106
1107 template <typename T>
1108 detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>
1109 cast(object &&object) {
1110 return move<T>(std::move(object));
1111 }
1112 template <typename T>
1113 detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>
1114 cast(object &&object) {
1115 if (object.ref_count() > 1) {
1116 return cast<T>(object);
1117 }
1118 return move<T>(std::move(object));
1119 }
1120 template <typename T>
1121 detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>
1122 cast(object &&object) {
1123 return cast<T>(object);
1124 }
1125
1126
1127 template <typename T>
1128 detail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {
1129 return T(std::move(object));
1130 }
1131
1132 template <typename T>
1133 T object::cast() const & {
1134 return pybind11::cast<T>(*this);
1135 }
1136 template <typename T>
1137 T object::cast() && {
1138 return pybind11::cast<T>(std::move(*this));
1139 }
1140 template <>
1141 inline void object::cast() const & {
1142 return;
1143 }
1144 template <>
1145 inline void object::cast() && {
1146 return;
1147 }
1148
1149 PYBIND11_NAMESPACE_BEGIN(detail)
1150
1151
1152 template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
1153 object object_or_cast(T &&o) {
1154 return pybind11::cast(std::forward<T>(o));
1155 }
1156
1157
1158
1159 struct override_unused {};
1160 template <typename ret_type>
1161 using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
1162 make_caster<ret_type>,
1163 override_unused>;
1164
1165
1166
1167 template <typename T>
1168 enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
1169 make_caster<T> &caster) {
1170 return cast_op<T>(load_type(caster, o));
1171 }
1172 template <typename T>
1173 enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
1174 override_unused &) {
1175 pybind11_fail("Internal error: cast_ref fallback invoked");
1176 }
1177
1178
1179
1180
1181 template <typename T>
1182 enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
1183 pybind11_fail("Internal error: cast_safe fallback invoked");
1184 }
1185 template <typename T>
1186 enable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}
1187 template <typename T>
1188 enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>, std::is_void<T>>::value, T>
1189 cast_safe(object &&o) {
1190 return pybind11::cast<T>(std::move(o));
1191 }
1192
1193 PYBIND11_NAMESPACE_END(detail)
1194
1195
1196
1197 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1198 inline cast_error cast_error_unable_to_convert_call_arg() {
1199 return cast_error("Unable to convert call argument to Python object (#define "
1200 "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1201 }
1202 #else
1203 inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
1204 const std::string &type) {
1205 return cast_error("Unable to convert call argument '" + name + "' of type '" + type
1206 + "' to Python object");
1207 }
1208 #endif
1209
1210 template <return_value_policy policy = return_value_policy::automatic_reference>
1211 tuple make_tuple() {
1212 return tuple(0);
1213 }
1214
1215 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1216 tuple make_tuple(Args &&...args_) {
1217 constexpr size_t size = sizeof...(Args);
1218 std::array<object, size> args{{reinterpret_steal<object>(
1219 detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
1220 for (size_t i = 0; i < args.size(); i++) {
1221 if (!args[i]) {
1222 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1223 throw cast_error_unable_to_convert_call_arg();
1224 #else
1225 std::array<std::string, size> argtypes{{type_id<Args>()...}};
1226 throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
1227 #endif
1228 }
1229 }
1230 tuple result(size);
1231 int counter = 0;
1232 for (auto &arg_value : args) {
1233 PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1234 }
1235 return result;
1236 }
1237
1238
1239
1240 struct arg {
1241
1242
1243 constexpr explicit arg(const char *name = nullptr)
1244 : name(name), flag_noconvert(false), flag_none(true) {}
1245
1246 template <typename T>
1247 arg_v operator=(T &&value) const;
1248
1249 arg &noconvert(bool flag = true) {
1250 flag_noconvert = flag;
1251 return *this;
1252 }
1253
1254 arg &none(bool flag = true) {
1255 flag_none = flag;
1256 return *this;
1257 }
1258
1259 const char *name;
1260 bool flag_noconvert : 1;
1261
1262 bool flag_none : 1;
1263 };
1264
1265
1266
1267 struct arg_v : arg {
1268 private:
1269 template <typename T>
1270 arg_v(arg &&base, T &&x, const char *descr = nullptr)
1271 : arg(base), value(reinterpret_steal<object>(detail::make_caster<T>::cast(
1272 std::forward<T>(x), return_value_policy::automatic, {}))),
1273 descr(descr)
1274 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1275 ,
1276 type(type_id<T>())
1277 #endif
1278 {
1279
1280
1281
1282 if (PyErr_Occurred()) {
1283 PyErr_Clear();
1284 }
1285 }
1286
1287 public:
1288
1289 template <typename T>
1290 arg_v(const char *name, T &&x, const char *descr = nullptr)
1291 : arg_v(arg(name), std::forward<T>(x), descr) {}
1292
1293
1294 template <typename T>
1295 arg_v(const arg &base, T &&x, const char *descr = nullptr)
1296 : arg_v(arg(base), std::forward<T>(x), descr) {}
1297
1298
1299 arg_v &noconvert(bool flag = true) {
1300 arg::noconvert(flag);
1301 return *this;
1302 }
1303
1304
1305 arg_v &none(bool flag = true) {
1306 arg::none(flag);
1307 return *this;
1308 }
1309
1310
1311 object value;
1312
1313 const char *descr;
1314 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1315
1316 std::string type;
1317 #endif
1318 };
1319
1320
1321
1322
1323 struct kw_only {};
1324
1325
1326
1327
1328 struct pos_only {};
1329
1330 template <typename T>
1331 arg_v arg::operator=(T &&value) const {
1332 return {*this, std::forward<T>(value)};
1333 }
1334
1335
1336 template <typename >
1337 using arg_t = arg_v;
1338
1339 inline namespace literals {
1340
1341
1342
1343 constexpr arg operator"" _a(const char *name, size_t) { return arg(name); }
1344 }
1345
1346 PYBIND11_NAMESPACE_BEGIN(detail)
1347
1348 template <typename T>
1349 using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
1350 template <typename T>
1351 using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
1352
1353
1354 struct function_record;
1355
1356
1357 struct function_call {
1358 function_call(const function_record &f, handle p);
1359
1360
1361 const function_record &func;
1362
1363
1364 std::vector<handle> args;
1365
1366
1367 std::vector<bool> args_convert;
1368
1369
1370
1371 object args_ref, kwargs_ref;
1372
1373
1374 handle parent;
1375
1376
1377 handle init_self;
1378 };
1379
1380
1381 template <typename... Args>
1382 class argument_loader {
1383 using indices = make_index_sequence<sizeof...(Args)>;
1384
1385 template <typename Arg>
1386 using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
1387 template <typename Arg>
1388 using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
1389
1390 static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
1391
1392 static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
1393 "py::kwargs is only permitted as the last argument of a function");
1394
1395 public:
1396 static constexpr bool has_kwargs = kwargs_pos != -1;
1397
1398
1399 static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
1400
1401 static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
1402 "py::args cannot be specified more than once");
1403
1404 static constexpr auto arg_names = concat(type_descr(make_caster<Args>::name)...);
1405
1406 bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
1407
1408 template <typename Return, typename Guard, typename Func>
1409
1410 enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
1411 return std::move(*this).template call_impl<remove_cv_t<Return>>(
1412 std::forward<Func>(f), indices{}, Guard{});
1413 }
1414
1415 template <typename Return, typename Guard, typename Func>
1416 enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
1417 std::move(*this).template call_impl<remove_cv_t<Return>>(
1418 std::forward<Func>(f), indices{}, Guard{});
1419 return void_type();
1420 }
1421
1422 private:
1423 static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
1424
1425 template <size_t... Is>
1426 bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
1427 #ifdef __cpp_fold_expressions
1428 if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
1429 return false;
1430 }
1431 #else
1432 for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
1433 if (!r) {
1434 return false;
1435 }
1436 }
1437 #endif
1438 return true;
1439 }
1440
1441 template <typename Return, typename Func, size_t... Is, typename Guard>
1442 Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
1443 return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
1444 }
1445
1446 std::tuple<make_caster<Args>...> argcasters;
1447 };
1448
1449
1450
1451 template <return_value_policy policy>
1452 class simple_collector {
1453 public:
1454 template <typename... Ts>
1455 explicit simple_collector(Ts &&...values)
1456 : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) {}
1457
1458 const tuple &args() const & { return m_args; }
1459 dict kwargs() const { return {}; }
1460
1461 tuple args() && { return std::move(m_args); }
1462
1463
1464 object call(PyObject *ptr) const {
1465 PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
1466 if (!result) {
1467 throw error_already_set();
1468 }
1469 return reinterpret_steal<object>(result);
1470 }
1471
1472 private:
1473 tuple m_args;
1474 };
1475
1476
1477 template <return_value_policy policy>
1478 class unpacking_collector {
1479 public:
1480 template <typename... Ts>
1481 explicit unpacking_collector(Ts &&...values) {
1482
1483
1484 auto args_list = list();
1485 using expander = int[];
1486 (void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...};
1487
1488 m_args = std::move(args_list);
1489 }
1490
1491 const tuple &args() const & { return m_args; }
1492 const dict &kwargs() const & { return m_kwargs; }
1493
1494 tuple args() && { return std::move(m_args); }
1495 dict kwargs() && { return std::move(m_kwargs); }
1496
1497
1498 object call(PyObject *ptr) const {
1499 PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
1500 if (!result) {
1501 throw error_already_set();
1502 }
1503 return reinterpret_steal<object>(result);
1504 }
1505
1506 private:
1507 template <typename T>
1508 void process(list &args_list, T &&x) {
1509 auto o = reinterpret_steal<object>(
1510 detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
1511 if (!o) {
1512 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1513 throw cast_error_unable_to_convert_call_arg();
1514 #else
1515 throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()),
1516 type_id<T>());
1517 #endif
1518 }
1519 args_list.append(std::move(o));
1520 }
1521
1522 void process(list &args_list, detail::args_proxy ap) {
1523 for (auto a : ap) {
1524 args_list.append(a);
1525 }
1526 }
1527
1528 void process(list & , arg_v a) {
1529 if (!a.name) {
1530 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1531 nameless_argument_error();
1532 #else
1533 nameless_argument_error(a.type);
1534 #endif
1535 }
1536 if (m_kwargs.contains(a.name)) {
1537 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1538 multiple_values_error();
1539 #else
1540 multiple_values_error(a.name);
1541 #endif
1542 }
1543 if (!a.value) {
1544 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1545 throw cast_error_unable_to_convert_call_arg();
1546 #else
1547 throw cast_error_unable_to_convert_call_arg(a.name, a.type);
1548 #endif
1549 }
1550 m_kwargs[a.name] = std::move(a.value);
1551 }
1552
1553 void process(list & , detail::kwargs_proxy kp) {
1554 if (!kp) {
1555 return;
1556 }
1557 for (auto k : reinterpret_borrow<dict>(kp)) {
1558 if (m_kwargs.contains(k.first)) {
1559 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1560 multiple_values_error();
1561 #else
1562 multiple_values_error(str(k.first));
1563 #endif
1564 }
1565 m_kwargs[k.first] = k.second;
1566 }
1567 }
1568
1569 [[noreturn]] static void nameless_argument_error() {
1570 throw type_error(
1571 "Got kwargs without a name; only named arguments "
1572 "may be passed via py::arg() to a python function call. "
1573 "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1574 }
1575 [[noreturn]] static void nameless_argument_error(const std::string &type) {
1576 throw type_error("Got kwargs without a name of type '" + type
1577 + "'; only named "
1578 "arguments may be passed via py::arg() to a python function call. ");
1579 }
1580 [[noreturn]] static void multiple_values_error() {
1581 throw type_error(
1582 "Got multiple values for keyword argument "
1583 "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1584 }
1585
1586 [[noreturn]] static void multiple_values_error(const std::string &name) {
1587 throw type_error("Got multiple values for keyword argument '" + name + "'");
1588 }
1589
1590 private:
1591 tuple m_args;
1592 dict m_kwargs;
1593 };
1594
1595
1596
1597
1598
1599 template <typename... Args>
1600 constexpr bool args_are_all_positional() {
1601 return all_of<is_positional<Args>...>::value;
1602 }
1603
1604
1605 template <return_value_policy policy,
1606 typename... Args,
1607 typename = enable_if_t<args_are_all_positional<Args...>()>>
1608 simple_collector<policy> collect_arguments(Args &&...args) {
1609 return simple_collector<policy>(std::forward<Args>(args)...);
1610 }
1611
1612
1613 template <return_value_policy policy,
1614 typename... Args,
1615 typename = enable_if_t<!args_are_all_positional<Args...>()>>
1616 unpacking_collector<policy> collect_arguments(Args &&...args) {
1617
1618 static_assert(constexpr_last<is_positional, Args...>()
1619 < constexpr_first<is_keyword_or_ds, Args...>()
1620 && constexpr_last<is_s_unpacking, Args...>()
1621 < constexpr_first<is_ds_unpacking, Args...>(),
1622 "Invalid function call: positional args must precede keywords and ** unpacking; "
1623 "* unpacking must precede ** unpacking");
1624 return unpacking_collector<policy>(std::forward<Args>(args)...);
1625 }
1626
1627 template <typename Derived>
1628 template <return_value_policy policy, typename... Args>
1629 object object_api<Derived>::operator()(Args &&...args) const {
1630 #ifndef NDEBUG
1631 if (!PyGILState_Check()) {
1632 pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
1633 }
1634 #endif
1635 return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
1636 }
1637
1638 template <typename Derived>
1639 template <return_value_policy policy, typename... Args>
1640 object object_api<Derived>::call(Args &&...args) const {
1641 return operator()<policy>(std::forward<Args>(args)...);
1642 }
1643
1644 PYBIND11_NAMESPACE_END(detail)
1645
1646 template <typename T>
1647 handle type::handle_of() {
1648 static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
1649 "py::type::of<T> only supports the case where T is a registered C++ types.");
1650
1651 return detail::get_type_handle(typeid(T), true);
1652 }
1653
1654 #define PYBIND11_MAKE_OPAQUE(...) \
1655 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
1656 namespace detail { \
1657 template <> \
1658 class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
1659 } \
1660 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
1661
1662
1663
1664
1665 #define PYBIND11_TYPE(...) __VA_ARGS__
1666
1667 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)