cast.h 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  1. /*
  2. pybind11/cast.h: Partial template specializations to cast between
  3. C++ and Python types
  4. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #pragma once
  9. #include "detail/common.h"
  10. #include "detail/descr.h"
  11. #include "detail/type_caster_base.h"
  12. #include "detail/typeid.h"
  13. #include "pytypes.h"
  14. #include <array>
  15. #include <cstring>
  16. #include <functional>
  17. #include <iosfwd>
  18. #include <iterator>
  19. #include <memory>
  20. #include <string>
  21. #include <tuple>
  22. #include <type_traits>
  23. #include <utility>
  24. #include <vector>
  25. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  26. PYBIND11_WARNING_DISABLE_MSVC(4127)
  27. PYBIND11_NAMESPACE_BEGIN(detail)
  28. template <typename type, typename SFINAE = void>
  29. class type_caster : public type_caster_base<type> {};
  30. template <typename type>
  31. using make_caster = type_caster<intrinsic_t<type>>;
  32. // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
  33. template <typename T>
  34. typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
  35. using result_t = typename make_caster<T>::template cast_op_type<T>; // See PR #4893
  36. return caster.operator result_t();
  37. }
  38. template <typename T>
  39. typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
  40. cast_op(make_caster<T> &&caster) {
  41. using result_t = typename make_caster<T>::template cast_op_type<
  42. typename std::add_rvalue_reference<T>::type>; // See PR #4893
  43. return std::move(caster).operator result_t();
  44. }
  45. template <typename type>
  46. class type_caster<std::reference_wrapper<type>> {
  47. private:
  48. using caster_t = make_caster<type>;
  49. caster_t subcaster;
  50. using reference_t = type &;
  51. using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
  52. static_assert(
  53. std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
  54. || std::is_same<reference_t, subcaster_cast_op_type>::value,
  55. "std::reference_wrapper<T> caster requires T to have a caster with an "
  56. "`operator T &()` or `operator const T &()`");
  57. public:
  58. bool load(handle src, bool convert) { return subcaster.load(src, convert); }
  59. static constexpr auto name = caster_t::name;
  60. static handle
  61. cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
  62. // It is definitely wrong to take ownership of this pointer, so mask that rvp
  63. if (policy == return_value_policy::take_ownership
  64. || policy == return_value_policy::automatic) {
  65. policy = return_value_policy::automatic_reference;
  66. }
  67. return caster_t::cast(&src.get(), policy, parent);
  68. }
  69. template <typename T>
  70. using cast_op_type = std::reference_wrapper<type>;
  71. explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
  72. };
  73. #define PYBIND11_TYPE_CASTER(type, py_name) \
  74. protected: \
  75. type value; \
  76. \
  77. public: \
  78. static constexpr auto name = py_name; \
  79. template <typename T_, \
  80. ::pybind11::detail::enable_if_t< \
  81. std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value, \
  82. int> \
  83. = 0> \
  84. static ::pybind11::handle cast( \
  85. T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) { \
  86. if (!src) \
  87. return ::pybind11::none().release(); \
  88. if (policy == ::pybind11::return_value_policy::take_ownership) { \
  89. auto h = cast(std::move(*src), policy, parent); \
  90. delete src; \
  91. return h; \
  92. } \
  93. return cast(*src, policy, parent); \
  94. } \
  95. operator type *() { return &value; } /* NOLINT(bugprone-macro-parentheses) */ \
  96. operator type &() { return value; } /* NOLINT(bugprone-macro-parentheses) */ \
  97. operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */ \
  98. template <typename T_> \
  99. using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
  100. template <typename CharT>
  101. using is_std_char_type = any_of<std::is_same<CharT, char>, /* std::string */
  102. #if defined(PYBIND11_HAS_U8STRING)
  103. std::is_same<CharT, char8_t>, /* std::u8string */
  104. #endif
  105. std::is_same<CharT, char16_t>, /* std::u16string */
  106. std::is_same<CharT, char32_t>, /* std::u32string */
  107. std::is_same<CharT, wchar_t> /* std::wstring */
  108. >;
  109. template <typename T>
  110. struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
  111. using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
  112. using _py_type_1 = conditional_t<std::is_signed<T>::value,
  113. _py_type_0,
  114. typename std::make_unsigned<_py_type_0>::type>;
  115. using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
  116. public:
  117. bool load(handle src, bool convert) {
  118. py_type py_value;
  119. if (!src) {
  120. return false;
  121. }
  122. #if !defined(PYPY_VERSION)
  123. auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
  124. #else
  125. // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
  126. // while CPython only considers the existence of `nb_index`/`__index__`.
  127. auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
  128. #endif
  129. if (std::is_floating_point<T>::value) {
  130. if (convert || PyFloat_Check(src.ptr())) {
  131. py_value = (py_type) PyFloat_AsDouble(src.ptr());
  132. } else {
  133. return false;
  134. }
  135. } else if (PyFloat_Check(src.ptr())
  136. || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
  137. return false;
  138. } else {
  139. handle src_or_index = src;
  140. // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
  141. #if PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
  142. object index;
  143. if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
  144. index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
  145. if (!index) {
  146. PyErr_Clear();
  147. if (!convert)
  148. return false;
  149. } else {
  150. src_or_index = index;
  151. }
  152. }
  153. #endif
  154. if (std::is_unsigned<py_type>::value) {
  155. py_value = as_unsigned<py_type>(src_or_index.ptr());
  156. } else { // signed integer:
  157. py_value = sizeof(T) <= sizeof(long)
  158. ? (py_type) PyLong_AsLong(src_or_index.ptr())
  159. : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
  160. }
  161. }
  162. // Python API reported an error
  163. bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
  164. // Check to see if the conversion is valid (integers should match exactly)
  165. // Signed/unsigned checks happen elsewhere
  166. if (py_err
  167. || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
  168. && py_value != (py_type) (T) py_value)) {
  169. PyErr_Clear();
  170. if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
  171. auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
  172. ? PyNumber_Float(src.ptr())
  173. : PyNumber_Long(src.ptr()));
  174. PyErr_Clear();
  175. return load(tmp, false);
  176. }
  177. return false;
  178. }
  179. value = (T) py_value;
  180. return true;
  181. }
  182. template <typename U = T>
  183. static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
  184. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  185. return PyFloat_FromDouble((double) src);
  186. }
  187. template <typename U = T>
  188. static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
  189. && (sizeof(U) <= sizeof(long)),
  190. handle>::type
  191. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  192. return PYBIND11_LONG_FROM_SIGNED((long) src);
  193. }
  194. template <typename U = T>
  195. static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
  196. && (sizeof(U) <= sizeof(unsigned long)),
  197. handle>::type
  198. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  199. return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
  200. }
  201. template <typename U = T>
  202. static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
  203. && (sizeof(U) > sizeof(long)),
  204. handle>::type
  205. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  206. return PyLong_FromLongLong((long long) src);
  207. }
  208. template <typename U = T>
  209. static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
  210. && (sizeof(U) > sizeof(unsigned long)),
  211. handle>::type
  212. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  213. return PyLong_FromUnsignedLongLong((unsigned long long) src);
  214. }
  215. PYBIND11_TYPE_CASTER(T, const_name<std::is_integral<T>::value>("int", "float"));
  216. };
  217. template <typename T>
  218. struct void_caster {
  219. public:
  220. bool load(handle src, bool) {
  221. if (src && src.is_none()) {
  222. return true;
  223. }
  224. return false;
  225. }
  226. static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
  227. return none().release();
  228. }
  229. PYBIND11_TYPE_CASTER(T, const_name("None"));
  230. };
  231. template <>
  232. class type_caster<void_type> : public void_caster<void_type> {};
  233. template <>
  234. class type_caster<void> : public type_caster<void_type> {
  235. public:
  236. using type_caster<void_type>::cast;
  237. bool load(handle h, bool) {
  238. if (!h) {
  239. return false;
  240. }
  241. if (h.is_none()) {
  242. value = nullptr;
  243. return true;
  244. }
  245. /* Check if this is a capsule */
  246. if (isinstance<capsule>(h)) {
  247. value = reinterpret_borrow<capsule>(h);
  248. return true;
  249. }
  250. /* Check if this is a C++ type */
  251. const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
  252. if (bases.size() == 1) { // Only allowing loading from a single-value type
  253. value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
  254. return true;
  255. }
  256. /* Fail */
  257. return false;
  258. }
  259. static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
  260. if (ptr) {
  261. return capsule(ptr).release();
  262. }
  263. return none().release();
  264. }
  265. template <typename T>
  266. using cast_op_type = void *&;
  267. explicit operator void *&() { return value; }
  268. static constexpr auto name = const_name("capsule");
  269. private:
  270. void *value = nullptr;
  271. };
  272. template <>
  273. class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
  274. template <>
  275. class type_caster<bool> {
  276. public:
  277. bool load(handle src, bool convert) {
  278. if (!src) {
  279. return false;
  280. }
  281. if (src.ptr() == Py_True) {
  282. value = true;
  283. return true;
  284. }
  285. if (src.ptr() == Py_False) {
  286. value = false;
  287. return true;
  288. }
  289. if (convert || is_numpy_bool(src)) {
  290. // (allow non-implicit conversion for numpy booleans), use strncmp
  291. // since NumPy 1.x had an additional trailing underscore.
  292. Py_ssize_t res = -1;
  293. if (src.is_none()) {
  294. res = 0; // None is implicitly converted to False
  295. }
  296. #if defined(PYPY_VERSION)
  297. // On PyPy, check that "__bool__" attr exists
  298. else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
  299. res = PyObject_IsTrue(src.ptr());
  300. }
  301. #else
  302. // Alternate approach for CPython: this does the same as the above, but optimized
  303. // using the CPython API so as to avoid an unneeded attribute lookup.
  304. else if (auto *tp_as_number = src.ptr()->ob_type->tp_as_number) {
  305. if (PYBIND11_NB_BOOL(tp_as_number)) {
  306. res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
  307. }
  308. }
  309. #endif
  310. if (res == 0 || res == 1) {
  311. value = (res != 0);
  312. return true;
  313. }
  314. PyErr_Clear();
  315. }
  316. return false;
  317. }
  318. static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
  319. return handle(src ? Py_True : Py_False).inc_ref();
  320. }
  321. PYBIND11_TYPE_CASTER(bool, const_name("bool"));
  322. private:
  323. // Test if an object is a NumPy boolean (without fetching the type).
  324. static inline bool is_numpy_bool(handle object) {
  325. const char *type_name = Py_TYPE(object.ptr())->tp_name;
  326. // Name changed to `numpy.bool` in NumPy 2, `numpy.bool_` is needed for 1.x support
  327. return std::strcmp("numpy.bool", type_name) == 0
  328. || std::strcmp("numpy.bool_", type_name) == 0;
  329. }
  330. };
  331. // Helper class for UTF-{8,16,32} C++ stl strings:
  332. template <typename StringType, bool IsView = false>
  333. struct string_caster {
  334. using CharT = typename StringType::value_type;
  335. // Simplify life by being able to assume standard char sizes (the standard only guarantees
  336. // minimums, but Python requires exact sizes)
  337. static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
  338. "Unsupported char size != 1");
  339. #if defined(PYBIND11_HAS_U8STRING)
  340. static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
  341. "Unsupported char8_t size != 1");
  342. #endif
  343. static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
  344. "Unsupported char16_t size != 2");
  345. static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
  346. "Unsupported char32_t size != 4");
  347. // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
  348. static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
  349. "Unsupported wchar_t size != 2/4");
  350. static constexpr size_t UTF_N = 8 * sizeof(CharT);
  351. bool load(handle src, bool) {
  352. handle load_src = src;
  353. if (!src) {
  354. return false;
  355. }
  356. if (!PyUnicode_Check(load_src.ptr())) {
  357. return load_raw(load_src);
  358. }
  359. // For UTF-8 we avoid the need for a temporary `bytes` object by using
  360. // `PyUnicode_AsUTF8AndSize`.
  361. if (UTF_N == 8) {
  362. Py_ssize_t size = -1;
  363. const auto *buffer
  364. = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
  365. if (!buffer) {
  366. PyErr_Clear();
  367. return false;
  368. }
  369. value = StringType(buffer, static_cast<size_t>(size));
  370. return true;
  371. }
  372. auto utfNbytes
  373. = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
  374. UTF_N == 8 ? "utf-8"
  375. : UTF_N == 16 ? "utf-16"
  376. : "utf-32",
  377. nullptr));
  378. if (!utfNbytes) {
  379. PyErr_Clear();
  380. return false;
  381. }
  382. const auto *buffer
  383. = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
  384. size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
  385. // Skip BOM for UTF-16/32
  386. if (UTF_N > 8) {
  387. buffer++;
  388. length--;
  389. }
  390. value = StringType(buffer, length);
  391. // If we're loading a string_view we need to keep the encoded Python object alive:
  392. if (IsView) {
  393. loader_life_support::add_patient(utfNbytes);
  394. }
  395. return true;
  396. }
  397. static handle
  398. cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
  399. const char *buffer = reinterpret_cast<const char *>(src.data());
  400. auto nbytes = ssize_t(src.size() * sizeof(CharT));
  401. handle s = decode_utfN(buffer, nbytes);
  402. if (!s) {
  403. throw error_already_set();
  404. }
  405. return s;
  406. }
  407. PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
  408. private:
  409. static handle decode_utfN(const char *buffer, ssize_t nbytes) {
  410. #if !defined(PYPY_VERSION)
  411. return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
  412. : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
  413. : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
  414. #else
  415. // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
  416. // well), so bypass the whole thing by just passing the encoding as a string value, which
  417. // works properly:
  418. return PyUnicode_Decode(buffer,
  419. nbytes,
  420. UTF_N == 8 ? "utf-8"
  421. : UTF_N == 16 ? "utf-16"
  422. : "utf-32",
  423. nullptr);
  424. #endif
  425. }
  426. // When loading into a std::string or char*, accept a bytes/bytearray object as-is (i.e.
  427. // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
  428. // which supports loading a unicode from a str, doesn't take this path.
  429. template <typename C = CharT>
  430. bool load_raw(enable_if_t<std::is_same<C, char>::value, handle> src) {
  431. if (PYBIND11_BYTES_CHECK(src.ptr())) {
  432. // We were passed raw bytes; accept it into a std::string or char*
  433. // without any encoding attempt.
  434. const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
  435. if (!bytes) {
  436. pybind11_fail("Unexpected PYBIND11_BYTES_AS_STRING() failure.");
  437. }
  438. value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
  439. return true;
  440. }
  441. if (PyByteArray_Check(src.ptr())) {
  442. // We were passed a bytearray; accept it into a std::string or char*
  443. // without any encoding attempt.
  444. const char *bytearray = PyByteArray_AsString(src.ptr());
  445. if (!bytearray) {
  446. pybind11_fail("Unexpected PyByteArray_AsString() failure.");
  447. }
  448. value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr()));
  449. return true;
  450. }
  451. return false;
  452. }
  453. template <typename C = CharT>
  454. bool load_raw(enable_if_t<!std::is_same<C, char>::value, handle>) {
  455. return false;
  456. }
  457. };
  458. template <typename CharT, class Traits, class Allocator>
  459. struct type_caster<std::basic_string<CharT, Traits, Allocator>,
  460. enable_if_t<is_std_char_type<CharT>::value>>
  461. : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
  462. #ifdef PYBIND11_HAS_STRING_VIEW
  463. template <typename CharT, class Traits>
  464. struct type_caster<std::basic_string_view<CharT, Traits>,
  465. enable_if_t<is_std_char_type<CharT>::value>>
  466. : string_caster<std::basic_string_view<CharT, Traits>, true> {};
  467. #endif
  468. // Type caster for C-style strings. We basically use a std::string type caster, but also add the
  469. // ability to use None as a nullptr char* (which the string caster doesn't allow).
  470. template <typename CharT>
  471. struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
  472. using StringType = std::basic_string<CharT>;
  473. using StringCaster = make_caster<StringType>;
  474. StringCaster str_caster;
  475. bool none = false;
  476. CharT one_char = 0;
  477. public:
  478. bool load(handle src, bool convert) {
  479. if (!src) {
  480. return false;
  481. }
  482. if (src.is_none()) {
  483. // Defer accepting None to other overloads (if we aren't in convert mode):
  484. if (!convert) {
  485. return false;
  486. }
  487. none = true;
  488. return true;
  489. }
  490. return str_caster.load(src, convert);
  491. }
  492. static handle cast(const CharT *src, return_value_policy policy, handle parent) {
  493. if (src == nullptr) {
  494. return pybind11::none().release();
  495. }
  496. return StringCaster::cast(StringType(src), policy, parent);
  497. }
  498. static handle cast(CharT src, return_value_policy policy, handle parent) {
  499. if (std::is_same<char, CharT>::value) {
  500. handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
  501. if (!s) {
  502. throw error_already_set();
  503. }
  504. return s;
  505. }
  506. return StringCaster::cast(StringType(1, src), policy, parent);
  507. }
  508. explicit operator CharT *() {
  509. return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
  510. }
  511. explicit operator CharT &() {
  512. if (none) {
  513. throw value_error("Cannot convert None to a character");
  514. }
  515. auto &value = static_cast<StringType &>(str_caster);
  516. size_t str_len = value.size();
  517. if (str_len == 0) {
  518. throw value_error("Cannot convert empty string to a character");
  519. }
  520. // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
  521. // is too high, and one for multiple unicode characters (caught later), so we need to
  522. // figure out how long the first encoded character is in bytes to distinguish between these
  523. // two errors. We also allow want to allow unicode characters U+0080 through U+00FF, as
  524. // those can fit into a single char value.
  525. if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
  526. auto v0 = static_cast<unsigned char>(value[0]);
  527. // low bits only: 0-127
  528. // 0b110xxxxx - start of 2-byte sequence
  529. // 0b1110xxxx - start of 3-byte sequence
  530. // 0b11110xxx - start of 4-byte sequence
  531. size_t char0_bytes = (v0 & 0x80) == 0 ? 1
  532. : (v0 & 0xE0) == 0xC0 ? 2
  533. : (v0 & 0xF0) == 0xE0 ? 3
  534. : 4;
  535. if (char0_bytes == str_len) {
  536. // If we have a 128-255 value, we can decode it into a single char:
  537. if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
  538. one_char = static_cast<CharT>(((v0 & 3) << 6)
  539. + (static_cast<unsigned char>(value[1]) & 0x3F));
  540. return one_char;
  541. }
  542. // Otherwise we have a single character, but it's > U+00FF
  543. throw value_error("Character code point not in range(0x100)");
  544. }
  545. }
  546. // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
  547. // surrogate pair with total length 2 instantly indicates a range error (but not a "your
  548. // string was too long" error).
  549. else if (StringCaster::UTF_N == 16 && str_len == 2) {
  550. one_char = static_cast<CharT>(value[0]);
  551. if (one_char >= 0xD800 && one_char < 0xE000) {
  552. throw value_error("Character code point not in range(0x10000)");
  553. }
  554. }
  555. if (str_len != 1) {
  556. throw value_error("Expected a character, but multi-character string found");
  557. }
  558. one_char = value[0];
  559. return one_char;
  560. }
  561. static constexpr auto name = const_name(PYBIND11_STRING_NAME);
  562. template <typename _T>
  563. using cast_op_type = pybind11::detail::cast_op_type<_T>;
  564. };
  565. // Base implementation for std::tuple and std::pair
  566. template <template <typename...> class Tuple, typename... Ts>
  567. class tuple_caster {
  568. using type = Tuple<Ts...>;
  569. static constexpr auto size = sizeof...(Ts);
  570. using indices = make_index_sequence<size>;
  571. public:
  572. bool load(handle src, bool convert) {
  573. if (!isinstance<sequence>(src)) {
  574. return false;
  575. }
  576. const auto seq = reinterpret_borrow<sequence>(src);
  577. if (seq.size() != size) {
  578. return false;
  579. }
  580. return load_impl(seq, convert, indices{});
  581. }
  582. template <typename T>
  583. static handle cast(T &&src, return_value_policy policy, handle parent) {
  584. return cast_impl(std::forward<T>(src), policy, parent, indices{});
  585. }
  586. // copied from the PYBIND11_TYPE_CASTER macro
  587. template <typename T>
  588. static handle cast(T *src, return_value_policy policy, handle parent) {
  589. if (!src) {
  590. return none().release();
  591. }
  592. if (policy == return_value_policy::take_ownership) {
  593. auto h = cast(std::move(*src), policy, parent);
  594. delete src;
  595. return h;
  596. }
  597. return cast(*src, policy, parent);
  598. }
  599. static constexpr auto name = const_name("tuple[")
  600. + ::pybind11::detail::concat(make_caster<Ts>::name...)
  601. + const_name("]");
  602. template <typename T>
  603. using cast_op_type = type;
  604. explicit operator type() & { return implicit_cast(indices{}); }
  605. explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
  606. protected:
  607. template <size_t... Is>
  608. type implicit_cast(index_sequence<Is...>) & {
  609. return type(cast_op<Ts>(std::get<Is>(subcasters))...);
  610. }
  611. template <size_t... Is>
  612. type implicit_cast(index_sequence<Is...>) && {
  613. return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
  614. }
  615. static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
  616. template <size_t... Is>
  617. bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
  618. #ifdef __cpp_fold_expressions
  619. if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
  620. return false;
  621. }
  622. #else
  623. for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
  624. if (!r) {
  625. return false;
  626. }
  627. }
  628. #endif
  629. return true;
  630. }
  631. /* Implementation: Convert a C++ tuple into a Python tuple */
  632. template <typename T, size_t... Is>
  633. static handle
  634. cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
  635. PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
  636. PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
  637. std::array<object, size> entries{{reinterpret_steal<object>(
  638. make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
  639. for (const auto &entry : entries) {
  640. if (!entry) {
  641. return handle();
  642. }
  643. }
  644. tuple result(size);
  645. int counter = 0;
  646. for (auto &entry : entries) {
  647. PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
  648. }
  649. return result.release();
  650. }
  651. Tuple<make_caster<Ts>...> subcasters;
  652. };
  653. template <typename T1, typename T2>
  654. class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
  655. template <typename... Ts>
  656. class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
  657. /// Helper class which abstracts away certain actions. Users can provide specializations for
  658. /// custom holders, but it's only necessary if the type has a non-standard interface.
  659. template <typename T>
  660. struct holder_helper {
  661. static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
  662. };
  663. /// Type caster for holder types like std::shared_ptr, etc.
  664. /// The SFINAE hook is provided to help work around the current lack of support
  665. /// for smart-pointer interoperability. Please consider it an implementation
  666. /// detail that may change in the future, as formal support for smart-pointer
  667. /// interoperability is added into pybind11.
  668. template <typename type, typename holder_type, typename SFINAE = void>
  669. struct copyable_holder_caster : public type_caster_base<type> {
  670. public:
  671. using base = type_caster_base<type>;
  672. static_assert(std::is_base_of<base, type_caster<type>>::value,
  673. "Holder classes are only supported for custom types");
  674. using base::base;
  675. using base::cast;
  676. using base::typeinfo;
  677. using base::value;
  678. bool load(handle src, bool convert) {
  679. return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
  680. }
  681. explicit operator type *() { return this->value; }
  682. // static_cast works around compiler error with MSVC 17 and CUDA 10.2
  683. // see issue #2180
  684. explicit operator type &() { return *(static_cast<type *>(this->value)); }
  685. explicit operator holder_type *() { return std::addressof(holder); }
  686. explicit operator holder_type &() { return holder; }
  687. static handle cast(const holder_type &src, return_value_policy, handle) {
  688. const auto *ptr = holder_helper<holder_type>::get(src);
  689. return type_caster_base<type>::cast_holder(ptr, &src);
  690. }
  691. protected:
  692. friend class type_caster_generic;
  693. void check_holder_compat() {
  694. if (typeinfo->default_holder) {
  695. throw cast_error("Unable to load a custom holder type from a default-holder instance");
  696. }
  697. }
  698. bool load_value(value_and_holder &&v_h) {
  699. if (v_h.holder_constructed()) {
  700. value = v_h.value_ptr();
  701. holder = v_h.template holder<holder_type>();
  702. return true;
  703. }
  704. throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
  705. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  706. "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
  707. "type information)");
  708. #else
  709. "of type '"
  710. + type_id<holder_type>() + "''");
  711. #endif
  712. }
  713. template <typename T = holder_type,
  714. detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
  715. bool try_implicit_casts(handle, bool) {
  716. return false;
  717. }
  718. template <typename T = holder_type,
  719. detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
  720. bool try_implicit_casts(handle src, bool convert) {
  721. for (auto &cast : typeinfo->implicit_casts) {
  722. copyable_holder_caster sub_caster(*cast.first);
  723. if (sub_caster.load(src, convert)) {
  724. value = cast.second(sub_caster.value);
  725. holder = holder_type(sub_caster.holder, (type *) value);
  726. return true;
  727. }
  728. }
  729. return false;
  730. }
  731. static bool try_direct_conversions(handle) { return false; }
  732. holder_type holder;
  733. };
  734. /// Specialize for the common std::shared_ptr, so users don't need to
  735. template <typename T>
  736. class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
  737. /// Type caster for holder types like std::unique_ptr.
  738. /// Please consider the SFINAE hook an implementation detail, as explained
  739. /// in the comment for the copyable_holder_caster.
  740. template <typename type, typename holder_type, typename SFINAE = void>
  741. struct move_only_holder_caster {
  742. static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
  743. "Holder classes are only supported for custom types");
  744. static handle cast(holder_type &&src, return_value_policy, handle) {
  745. auto *ptr = holder_helper<holder_type>::get(src);
  746. return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
  747. }
  748. static constexpr auto name = type_caster_base<type>::name;
  749. };
  750. template <typename type, typename deleter>
  751. class type_caster<std::unique_ptr<type, deleter>>
  752. : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
  753. template <typename type, typename holder_type>
  754. using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
  755. copyable_holder_caster<type, holder_type>,
  756. move_only_holder_caster<type, holder_type>>;
  757. template <typename T, bool Value = false>
  758. struct always_construct_holder {
  759. static constexpr bool value = Value;
  760. };
  761. /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
  762. #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
  763. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
  764. namespace detail { \
  765. template <typename type> \
  766. struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { \
  767. }; \
  768. template <typename type> \
  769. class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
  770. : public type_caster_holder<type, holder_type> {}; \
  771. } \
  772. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
  773. // PYBIND11_DECLARE_HOLDER_TYPE holder types:
  774. template <typename base, typename holder>
  775. struct is_holder_type
  776. : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
  777. // Specialization for always-supported unique_ptr holders:
  778. template <typename base, typename deleter>
  779. struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
  780. #ifdef PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION // See PR #4888
  781. // This leads to compilation errors if a specialization is missing.
  782. template <typename T>
  783. struct handle_type_name;
  784. #else
  785. template <typename T>
  786. struct handle_type_name {
  787. static constexpr auto name = const_name<T>();
  788. };
  789. #endif
  790. template <>
  791. struct handle_type_name<object> {
  792. static constexpr auto name = const_name("object");
  793. };
  794. template <>
  795. struct handle_type_name<list> {
  796. static constexpr auto name = const_name("list");
  797. };
  798. template <>
  799. struct handle_type_name<dict> {
  800. static constexpr auto name = const_name("dict");
  801. };
  802. template <>
  803. struct handle_type_name<anyset> {
  804. static constexpr auto name = const_name("Union[set, frozenset]");
  805. };
  806. template <>
  807. struct handle_type_name<set> {
  808. static constexpr auto name = const_name("set");
  809. };
  810. template <>
  811. struct handle_type_name<frozenset> {
  812. static constexpr auto name = const_name("frozenset");
  813. };
  814. template <>
  815. struct handle_type_name<str> {
  816. static constexpr auto name = const_name("str");
  817. };
  818. template <>
  819. struct handle_type_name<tuple> {
  820. static constexpr auto name = const_name("tuple");
  821. };
  822. template <>
  823. struct handle_type_name<bool_> {
  824. static constexpr auto name = const_name("bool");
  825. };
  826. template <>
  827. struct handle_type_name<bytes> {
  828. static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
  829. };
  830. template <>
  831. struct handle_type_name<buffer> {
  832. static constexpr auto name = const_name("Buffer");
  833. };
  834. template <>
  835. struct handle_type_name<int_> {
  836. static constexpr auto name = const_name("int");
  837. };
  838. template <>
  839. struct handle_type_name<iterable> {
  840. static constexpr auto name = const_name("Iterable");
  841. };
  842. template <>
  843. struct handle_type_name<iterator> {
  844. static constexpr auto name = const_name("Iterator");
  845. };
  846. template <>
  847. struct handle_type_name<float_> {
  848. static constexpr auto name = const_name("float");
  849. };
  850. template <>
  851. struct handle_type_name<function> {
  852. static constexpr auto name = const_name("Callable");
  853. };
  854. template <>
  855. struct handle_type_name<handle> {
  856. static constexpr auto name = handle_type_name<object>::name;
  857. };
  858. template <>
  859. struct handle_type_name<none> {
  860. static constexpr auto name = const_name("None");
  861. };
  862. template <>
  863. struct handle_type_name<sequence> {
  864. static constexpr auto name = const_name("Sequence");
  865. };
  866. template <>
  867. struct handle_type_name<bytearray> {
  868. static constexpr auto name = const_name("bytearray");
  869. };
  870. template <>
  871. struct handle_type_name<memoryview> {
  872. static constexpr auto name = const_name("memoryview");
  873. };
  874. template <>
  875. struct handle_type_name<slice> {
  876. static constexpr auto name = const_name("slice");
  877. };
  878. template <>
  879. struct handle_type_name<type> {
  880. static constexpr auto name = const_name("type");
  881. };
  882. template <>
  883. struct handle_type_name<capsule> {
  884. static constexpr auto name = const_name("capsule");
  885. };
  886. template <>
  887. struct handle_type_name<ellipsis> {
  888. static constexpr auto name = const_name("ellipsis");
  889. };
  890. template <>
  891. struct handle_type_name<weakref> {
  892. static constexpr auto name = const_name("weakref");
  893. };
  894. template <>
  895. struct handle_type_name<args> {
  896. static constexpr auto name = const_name("*args");
  897. };
  898. template <>
  899. struct handle_type_name<kwargs> {
  900. static constexpr auto name = const_name("**kwargs");
  901. };
  902. template <>
  903. struct handle_type_name<obj_attr_accessor> {
  904. static constexpr auto name = const_name<obj_attr_accessor>();
  905. };
  906. template <>
  907. struct handle_type_name<str_attr_accessor> {
  908. static constexpr auto name = const_name<str_attr_accessor>();
  909. };
  910. template <>
  911. struct handle_type_name<item_accessor> {
  912. static constexpr auto name = const_name<item_accessor>();
  913. };
  914. template <>
  915. struct handle_type_name<sequence_accessor> {
  916. static constexpr auto name = const_name<sequence_accessor>();
  917. };
  918. template <>
  919. struct handle_type_name<list_accessor> {
  920. static constexpr auto name = const_name<list_accessor>();
  921. };
  922. template <>
  923. struct handle_type_name<tuple_accessor> {
  924. static constexpr auto name = const_name<tuple_accessor>();
  925. };
  926. template <typename type>
  927. struct pyobject_caster {
  928. template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
  929. pyobject_caster() : value() {}
  930. // `type` may not be default constructible (e.g. frozenset, anyset). Initializing `value`
  931. // to a nil handle is safe since it will only be accessed if `load` succeeds.
  932. template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
  933. pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
  934. template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
  935. bool load(handle src, bool /* convert */) {
  936. value = src;
  937. return static_cast<bool>(value);
  938. }
  939. template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
  940. bool load(handle src, bool /* convert */) {
  941. if (!isinstance<type>(src)) {
  942. return false;
  943. }
  944. value = reinterpret_borrow<type>(src);
  945. return true;
  946. }
  947. static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
  948. return src.inc_ref();
  949. }
  950. PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
  951. };
  952. template <typename T>
  953. class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
  954. // Our conditions for enabling moving are quite restrictive:
  955. // At compile time:
  956. // - T needs to be a non-const, non-pointer, non-reference type
  957. // - type_caster<T>::operator T&() must exist
  958. // - the type must be move constructible (obviously)
  959. // At run-time:
  960. // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
  961. // must have ref_count() == 1)h
  962. // If any of the above are not satisfied, we fall back to copying.
  963. template <typename T>
  964. using move_is_plain_type
  965. = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
  966. template <typename T, typename SFINAE = void>
  967. struct move_always : std::false_type {};
  968. template <typename T>
  969. struct move_always<
  970. T,
  971. enable_if_t<
  972. all_of<move_is_plain_type<T>,
  973. negation<is_copy_constructible<T>>,
  974. is_move_constructible<T>,
  975. std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
  976. : std::true_type {};
  977. template <typename T, typename SFINAE = void>
  978. struct move_if_unreferenced : std::false_type {};
  979. template <typename T>
  980. struct move_if_unreferenced<
  981. T,
  982. enable_if_t<
  983. all_of<move_is_plain_type<T>,
  984. negation<move_always<T>>,
  985. is_move_constructible<T>,
  986. std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
  987. : std::true_type {};
  988. template <typename T>
  989. using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
  990. // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
  991. // reference or pointer to a local variable of the type_caster. Basically, only
  992. // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
  993. // everything else returns a reference/pointer to a local variable.
  994. template <typename type>
  995. using cast_is_temporary_value_reference
  996. = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
  997. && !std::is_base_of<type_caster_generic, make_caster<type>>::value
  998. && !std::is_same<intrinsic_t<type>, void>::value>;
  999. // When a value returned from a C++ function is being cast back to Python, we almost always want to
  1000. // force `policy = move`, regardless of the return value policy the function/method was declared
  1001. // with.
  1002. template <typename Return, typename SFINAE = void>
  1003. struct return_value_policy_override {
  1004. static return_value_policy policy(return_value_policy p) { return p; }
  1005. };
  1006. template <typename Return>
  1007. struct return_value_policy_override<
  1008. Return,
  1009. detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
  1010. static return_value_policy policy(return_value_policy p) {
  1011. return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
  1012. ? return_value_policy::move
  1013. : p;
  1014. }
  1015. };
  1016. // Basic python -> C++ casting; throws if casting fails
  1017. template <typename T, typename SFINAE>
  1018. type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
  1019. static_assert(!detail::is_pyobject<T>::value,
  1020. "Internal error: type_caster should only be used for C++ types");
  1021. if (!conv.load(handle, true)) {
  1022. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1023. throw cast_error(
  1024. "Unable to cast Python instance of type "
  1025. + str(type::handle_of(handle)).cast<std::string>()
  1026. + " to C++ type '?' (#define "
  1027. "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1028. #else
  1029. throw cast_error("Unable to cast Python instance of type "
  1030. + str(type::handle_of(handle)).cast<std::string>() + " to C++ type '"
  1031. + type_id<T>() + "'");
  1032. #endif
  1033. }
  1034. return conv;
  1035. }
  1036. // Wrapper around the above that also constructs and returns a type_caster
  1037. template <typename T>
  1038. make_caster<T> load_type(const handle &handle) {
  1039. make_caster<T> conv;
  1040. load_type(conv, handle);
  1041. return conv;
  1042. }
  1043. PYBIND11_NAMESPACE_END(detail)
  1044. // pytype -> C++ type
  1045. template <typename T,
  1046. detail::enable_if_t<!detail::is_pyobject<T>::value
  1047. && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
  1048. int>
  1049. = 0>
  1050. T cast(const handle &handle) {
  1051. using namespace detail;
  1052. static_assert(!cast_is_temporary_value_reference<T>::value,
  1053. "Unable to cast type to reference: value is local to type caster");
  1054. return cast_op<T>(load_type<T>(handle));
  1055. }
  1056. // pytype -> pytype (calls converting constructor)
  1057. template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
  1058. T cast(const handle &handle) {
  1059. return T(reinterpret_borrow<object>(handle));
  1060. }
  1061. // Note that `cast<PyObject *>(obj)` increments the reference count of `obj`.
  1062. // This is necessary for the case that `obj` is a temporary, and could
  1063. // not possibly be different, given
  1064. // 1. the established convention that the passed `handle` is borrowed, and
  1065. // 2. we don't want to force all generic code using `cast<T>()` to special-case
  1066. // handling of `T` = `PyObject *` (to increment the reference count there).
  1067. // It is the responsibility of the caller to ensure that the reference count
  1068. // is decremented.
  1069. template <typename T,
  1070. typename Handle,
  1071. detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
  1072. && detail::is_same_ignoring_cvref<Handle, handle>::value,
  1073. int>
  1074. = 0>
  1075. T cast(Handle &&handle) {
  1076. return handle.inc_ref().ptr();
  1077. }
  1078. // To optimize way an inc_ref/dec_ref cycle:
  1079. template <typename T,
  1080. typename Object,
  1081. detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
  1082. && detail::is_same_ignoring_cvref<Object, object>::value,
  1083. int>
  1084. = 0>
  1085. T cast(Object &&obj) {
  1086. return obj.release().ptr();
  1087. }
  1088. // C++ type -> py::object
  1089. template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
  1090. object cast(T &&value,
  1091. return_value_policy policy = return_value_policy::automatic_reference,
  1092. handle parent = handle()) {
  1093. using no_ref_T = typename std::remove_reference<T>::type;
  1094. if (policy == return_value_policy::automatic) {
  1095. policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
  1096. : std::is_lvalue_reference<T>::value ? return_value_policy::copy
  1097. : return_value_policy::move;
  1098. } else if (policy == return_value_policy::automatic_reference) {
  1099. policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
  1100. : std::is_lvalue_reference<T>::value ? return_value_policy::copy
  1101. : return_value_policy::move;
  1102. }
  1103. return reinterpret_steal<object>(
  1104. detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
  1105. }
  1106. template <typename T>
  1107. T handle::cast() const {
  1108. return pybind11::cast<T>(*this);
  1109. }
  1110. template <>
  1111. inline void handle::cast() const {
  1112. return;
  1113. }
  1114. template <typename T>
  1115. detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
  1116. if (obj.ref_count() > 1) {
  1117. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1118. throw cast_error(
  1119. "Unable to cast Python " + str(type::handle_of(obj)).cast<std::string>()
  1120. + " instance to C++ rvalue: instance has multiple references"
  1121. " (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1122. #else
  1123. throw cast_error("Unable to move from Python "
  1124. + str(type::handle_of(obj)).cast<std::string>() + " instance to C++ "
  1125. + type_id<T>() + " instance: instance has multiple references");
  1126. #endif
  1127. }
  1128. // Move into a temporary and return that, because the reference may be a local value of `conv`
  1129. T ret = std::move(detail::load_type<T>(obj).operator T &());
  1130. return ret;
  1131. }
  1132. // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
  1133. // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
  1134. // object has multiple references, but trying to copy will fail to compile.
  1135. // - If both movable and copyable, check ref count: if 1, move; otherwise copy
  1136. // - Otherwise (not movable), copy.
  1137. template <typename T>
  1138. detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>
  1139. cast(object &&object) {
  1140. return move<T>(std::move(object));
  1141. }
  1142. template <typename T>
  1143. detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>
  1144. cast(object &&object) {
  1145. if (object.ref_count() > 1) {
  1146. return cast<T>(object);
  1147. }
  1148. return move<T>(std::move(object));
  1149. }
  1150. template <typename T>
  1151. detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>
  1152. cast(object &&object) {
  1153. return cast<T>(object);
  1154. }
  1155. // pytype rvalue -> pytype (calls converting constructor)
  1156. template <typename T>
  1157. detail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {
  1158. return T(std::move(object));
  1159. }
  1160. template <typename T>
  1161. T object::cast() const & {
  1162. return pybind11::cast<T>(*this);
  1163. }
  1164. template <typename T>
  1165. T object::cast() && {
  1166. return pybind11::cast<T>(std::move(*this));
  1167. }
  1168. template <>
  1169. inline void object::cast() const & {
  1170. return;
  1171. }
  1172. template <>
  1173. inline void object::cast() && {
  1174. return;
  1175. }
  1176. PYBIND11_NAMESPACE_BEGIN(detail)
  1177. // Declared in pytypes.h:
  1178. template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
  1179. object object_or_cast(T &&o) {
  1180. return pybind11::cast(std::forward<T>(o));
  1181. }
  1182. // Placeholder type for the unneeded (and dead code) static variable in the
  1183. // PYBIND11_OVERRIDE_OVERRIDE macro
  1184. struct override_unused {};
  1185. template <typename ret_type>
  1186. using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
  1187. make_caster<ret_type>,
  1188. override_unused>;
  1189. // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
  1190. // store the result in the given variable. For other types, this is a no-op.
  1191. template <typename T>
  1192. enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
  1193. make_caster<T> &caster) {
  1194. return cast_op<T>(load_type(caster, o));
  1195. }
  1196. template <typename T>
  1197. enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
  1198. override_unused &) {
  1199. pybind11_fail("Internal error: cast_ref fallback invoked");
  1200. }
  1201. // Trampoline use: Having a pybind11::cast with an invalid reference type is going to
  1202. // static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
  1203. // that only does anything in cases where pybind11::cast is valid.
  1204. template <typename T>
  1205. enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
  1206. pybind11_fail("Internal error: cast_safe fallback invoked");
  1207. }
  1208. template <typename T>
  1209. enable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}
  1210. template <typename T>
  1211. enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>, std::is_void<T>>::value, T>
  1212. cast_safe(object &&o) {
  1213. return pybind11::cast<T>(std::move(o));
  1214. }
  1215. PYBIND11_NAMESPACE_END(detail)
  1216. // The overloads could coexist, i.e. the #if is not strictly speaking needed,
  1217. // but it is an easy minor optimization.
  1218. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1219. inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name) {
  1220. return cast_error("Unable to convert call argument '" + name
  1221. + "' to Python object (#define "
  1222. "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1223. }
  1224. #else
  1225. inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
  1226. const std::string &type) {
  1227. return cast_error("Unable to convert call argument '" + name + "' of type '" + type
  1228. + "' to Python object");
  1229. }
  1230. #endif
  1231. template <return_value_policy policy = return_value_policy::automatic_reference>
  1232. tuple make_tuple() {
  1233. return tuple(0);
  1234. }
  1235. template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
  1236. tuple make_tuple(Args &&...args_) {
  1237. constexpr size_t size = sizeof...(Args);
  1238. std::array<object, size> args{{reinterpret_steal<object>(
  1239. detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
  1240. for (size_t i = 0; i < args.size(); i++) {
  1241. if (!args[i]) {
  1242. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1243. throw cast_error_unable_to_convert_call_arg(std::to_string(i));
  1244. #else
  1245. std::array<std::string, size> argtypes{{type_id<Args>()...}};
  1246. throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
  1247. #endif
  1248. }
  1249. }
  1250. tuple result(size);
  1251. int counter = 0;
  1252. for (auto &arg_value : args) {
  1253. PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
  1254. }
  1255. return result;
  1256. }
  1257. /// \ingroup annotations
  1258. /// Annotation for arguments
  1259. struct arg {
  1260. /// Constructs an argument with the name of the argument; if null or omitted, this is a
  1261. /// positional argument.
  1262. constexpr explicit arg(const char *name = nullptr)
  1263. : name(name), flag_noconvert(false), flag_none(true) {}
  1264. /// Assign a value to this argument
  1265. template <typename T>
  1266. arg_v operator=(T &&value) const;
  1267. /// Indicate that the type should not be converted in the type caster
  1268. arg &noconvert(bool flag = true) {
  1269. flag_noconvert = flag;
  1270. return *this;
  1271. }
  1272. /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
  1273. arg &none(bool flag = true) {
  1274. flag_none = flag;
  1275. return *this;
  1276. }
  1277. const char *name; ///< If non-null, this is a named kwargs argument
  1278. bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type
  1279. ///< caster!)
  1280. bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
  1281. };
  1282. /// \ingroup annotations
  1283. /// Annotation for arguments with values
  1284. struct arg_v : arg {
  1285. private:
  1286. template <typename T>
  1287. arg_v(arg &&base, T &&x, const char *descr = nullptr)
  1288. : arg(base), value(reinterpret_steal<object>(detail::make_caster<T>::cast(
  1289. std::forward<T>(x), return_value_policy::automatic, {}))),
  1290. descr(descr)
  1291. #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1292. ,
  1293. type(type_id<T>())
  1294. #endif
  1295. {
  1296. // Workaround! See:
  1297. // https://github.com/pybind/pybind11/issues/2336
  1298. // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
  1299. if (PyErr_Occurred()) {
  1300. PyErr_Clear();
  1301. }
  1302. }
  1303. public:
  1304. /// Direct construction with name, default, and description
  1305. template <typename T>
  1306. arg_v(const char *name, T &&x, const char *descr = nullptr)
  1307. : arg_v(arg(name), std::forward<T>(x), descr) {}
  1308. /// Called internally when invoking `py::arg("a") = value`
  1309. template <typename T>
  1310. arg_v(const arg &base, T &&x, const char *descr = nullptr)
  1311. : arg_v(arg(base), std::forward<T>(x), descr) {}
  1312. /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
  1313. arg_v &noconvert(bool flag = true) {
  1314. arg::noconvert(flag);
  1315. return *this;
  1316. }
  1317. /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
  1318. arg_v &none(bool flag = true) {
  1319. arg::none(flag);
  1320. return *this;
  1321. }
  1322. /// The default value
  1323. object value;
  1324. /// The (optional) description of the default value
  1325. const char *descr;
  1326. #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1327. /// The C++ type name of the default value (only available when compiled in debug mode)
  1328. std::string type;
  1329. #endif
  1330. };
  1331. /// \ingroup annotations
  1332. /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of
  1333. /// an unnamed '*' argument
  1334. struct kw_only {};
  1335. /// \ingroup annotations
  1336. /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of
  1337. /// an unnamed '/' argument (in Python 3.8)
  1338. struct pos_only {};
  1339. template <typename T>
  1340. arg_v arg::operator=(T &&value) const {
  1341. return {*this, std::forward<T>(value)};
  1342. }
  1343. /// Alias for backward compatibility -- to be removed in version 2.0
  1344. template <typename /*unused*/>
  1345. using arg_t = arg_v;
  1346. inline namespace literals {
  1347. /** \rst
  1348. String literal version of `arg`
  1349. \endrst */
  1350. constexpr arg
  1351. #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
  1352. operator"" _a // gcc 4.8.5 insists on having a space (hard error).
  1353. #else
  1354. operator""_a // clang 17 generates a deprecation warning if there is a space.
  1355. #endif
  1356. (const char *name, size_t) {
  1357. return arg(name);
  1358. }
  1359. } // namespace literals
  1360. PYBIND11_NAMESPACE_BEGIN(detail)
  1361. template <typename T>
  1362. using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
  1363. template <typename T>
  1364. using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
  1365. // forward declaration (definition in attr.h)
  1366. struct function_record;
  1367. /// Internal data associated with a single function call
  1368. struct function_call {
  1369. function_call(const function_record &f, handle p); // Implementation in attr.h
  1370. /// The function data:
  1371. const function_record &func;
  1372. /// Arguments passed to the function:
  1373. std::vector<handle> args;
  1374. /// The `convert` value the arguments should be loaded with
  1375. std::vector<bool> args_convert;
  1376. /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
  1377. /// present, are also in `args` but without a reference).
  1378. object args_ref, kwargs_ref;
  1379. /// The parent, if any
  1380. handle parent;
  1381. /// If this is a call to an initializer, this argument contains `self`
  1382. handle init_self;
  1383. };
  1384. /// Helper class which loads arguments for C++ functions called from Python
  1385. template <typename... Args>
  1386. class argument_loader {
  1387. using indices = make_index_sequence<sizeof...(Args)>;
  1388. template <typename Arg>
  1389. using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
  1390. template <typename Arg>
  1391. using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
  1392. // Get kwargs argument position, or -1 if not present:
  1393. static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
  1394. static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
  1395. "py::kwargs is only permitted as the last argument of a function");
  1396. public:
  1397. static constexpr bool has_kwargs = kwargs_pos != -1;
  1398. // py::args argument position; -1 if not present.
  1399. static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
  1400. static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
  1401. "py::args cannot be specified more than once");
  1402. static constexpr auto arg_names
  1403. = ::pybind11::detail::concat(type_descr(make_caster<Args>::name)...);
  1404. bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
  1405. template <typename Return, typename Guard, typename Func>
  1406. // NOLINTNEXTLINE(readability-const-return-type)
  1407. enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
  1408. return std::move(*this).template call_impl<remove_cv_t<Return>>(
  1409. std::forward<Func>(f), indices{}, Guard{});
  1410. }
  1411. template <typename Return, typename Guard, typename Func>
  1412. enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
  1413. std::move(*this).template call_impl<remove_cv_t<Return>>(
  1414. std::forward<Func>(f), indices{}, Guard{});
  1415. return void_type();
  1416. }
  1417. private:
  1418. static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
  1419. template <size_t... Is>
  1420. bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
  1421. #ifdef __cpp_fold_expressions
  1422. if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
  1423. return false;
  1424. }
  1425. #else
  1426. for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
  1427. if (!r) {
  1428. return false;
  1429. }
  1430. }
  1431. #endif
  1432. return true;
  1433. }
  1434. template <typename Return, typename Func, size_t... Is, typename Guard>
  1435. Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
  1436. return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
  1437. }
  1438. std::tuple<make_caster<Args>...> argcasters;
  1439. };
  1440. /// Helper class which collects only positional arguments for a Python function call.
  1441. /// A fancier version below can collect any argument, but this one is optimal for simple calls.
  1442. template <return_value_policy policy>
  1443. class simple_collector {
  1444. public:
  1445. template <typename... Ts>
  1446. explicit simple_collector(Ts &&...values)
  1447. : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) {}
  1448. const tuple &args() const & { return m_args; }
  1449. dict kwargs() const { return {}; }
  1450. tuple args() && { return std::move(m_args); }
  1451. /// Call a Python function and pass the collected arguments
  1452. object call(PyObject *ptr) const {
  1453. PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
  1454. if (!result) {
  1455. throw error_already_set();
  1456. }
  1457. return reinterpret_steal<object>(result);
  1458. }
  1459. private:
  1460. tuple m_args;
  1461. };
  1462. /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
  1463. template <return_value_policy policy>
  1464. class unpacking_collector {
  1465. public:
  1466. template <typename... Ts>
  1467. explicit unpacking_collector(Ts &&...values) {
  1468. // Tuples aren't (easily) resizable so a list is needed for collection,
  1469. // but the actual function call strictly requires a tuple.
  1470. auto args_list = list();
  1471. using expander = int[];
  1472. (void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...};
  1473. m_args = std::move(args_list);
  1474. }
  1475. const tuple &args() const & { return m_args; }
  1476. const dict &kwargs() const & { return m_kwargs; }
  1477. tuple args() && { return std::move(m_args); }
  1478. dict kwargs() && { return std::move(m_kwargs); }
  1479. /// Call a Python function and pass the collected arguments
  1480. object call(PyObject *ptr) const {
  1481. PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
  1482. if (!result) {
  1483. throw error_already_set();
  1484. }
  1485. return reinterpret_steal<object>(result);
  1486. }
  1487. private:
  1488. template <typename T>
  1489. void process(list &args_list, T &&x) {
  1490. auto o = reinterpret_steal<object>(
  1491. detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
  1492. if (!o) {
  1493. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1494. throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()));
  1495. #else
  1496. throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()),
  1497. type_id<T>());
  1498. #endif
  1499. }
  1500. args_list.append(std::move(o));
  1501. }
  1502. void process(list &args_list, detail::args_proxy ap) {
  1503. for (auto a : ap) {
  1504. args_list.append(a);
  1505. }
  1506. }
  1507. void process(list & /*args_list*/, arg_v a) {
  1508. if (!a.name) {
  1509. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1510. nameless_argument_error();
  1511. #else
  1512. nameless_argument_error(a.type);
  1513. #endif
  1514. }
  1515. if (m_kwargs.contains(a.name)) {
  1516. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1517. multiple_values_error();
  1518. #else
  1519. multiple_values_error(a.name);
  1520. #endif
  1521. }
  1522. if (!a.value) {
  1523. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1524. throw cast_error_unable_to_convert_call_arg(a.name);
  1525. #else
  1526. throw cast_error_unable_to_convert_call_arg(a.name, a.type);
  1527. #endif
  1528. }
  1529. m_kwargs[a.name] = std::move(a.value);
  1530. }
  1531. void process(list & /*args_list*/, detail::kwargs_proxy kp) {
  1532. if (!kp) {
  1533. return;
  1534. }
  1535. for (auto k : reinterpret_borrow<dict>(kp)) {
  1536. if (m_kwargs.contains(k.first)) {
  1537. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1538. multiple_values_error();
  1539. #else
  1540. multiple_values_error(str(k.first));
  1541. #endif
  1542. }
  1543. m_kwargs[k.first] = k.second;
  1544. }
  1545. }
  1546. [[noreturn]] static void nameless_argument_error() {
  1547. throw type_error(
  1548. "Got kwargs without a name; only named arguments "
  1549. "may be passed via py::arg() to a python function call. "
  1550. "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1551. }
  1552. [[noreturn]] static void nameless_argument_error(const std::string &type) {
  1553. throw type_error("Got kwargs without a name of type '" + type
  1554. + "'; only named "
  1555. "arguments may be passed via py::arg() to a python function call. ");
  1556. }
  1557. [[noreturn]] static void multiple_values_error() {
  1558. throw type_error(
  1559. "Got multiple values for keyword argument "
  1560. "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1561. }
  1562. [[noreturn]] static void multiple_values_error(const std::string &name) {
  1563. throw type_error("Got multiple values for keyword argument '" + name + "'");
  1564. }
  1565. private:
  1566. tuple m_args;
  1567. dict m_kwargs;
  1568. };
  1569. // [workaround(intel)] Separate function required here
  1570. // We need to put this into a separate function because the Intel compiler
  1571. // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
  1572. // (tested with ICC 2021.1 Beta 20200827).
  1573. template <typename... Args>
  1574. constexpr bool args_are_all_positional() {
  1575. return all_of<is_positional<Args>...>::value;
  1576. }
  1577. /// Collect only positional arguments for a Python function call
  1578. template <return_value_policy policy,
  1579. typename... Args,
  1580. typename = enable_if_t<args_are_all_positional<Args...>()>>
  1581. simple_collector<policy> collect_arguments(Args &&...args) {
  1582. return simple_collector<policy>(std::forward<Args>(args)...);
  1583. }
  1584. /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
  1585. template <return_value_policy policy,
  1586. typename... Args,
  1587. typename = enable_if_t<!args_are_all_positional<Args...>()>>
  1588. unpacking_collector<policy> collect_arguments(Args &&...args) {
  1589. // Following argument order rules for generalized unpacking according to PEP 448
  1590. static_assert(constexpr_last<is_positional, Args...>()
  1591. < constexpr_first<is_keyword_or_ds, Args...>()
  1592. && constexpr_last<is_s_unpacking, Args...>()
  1593. < constexpr_first<is_ds_unpacking, Args...>(),
  1594. "Invalid function call: positional args must precede keywords and ** unpacking; "
  1595. "* unpacking must precede ** unpacking");
  1596. return unpacking_collector<policy>(std::forward<Args>(args)...);
  1597. }
  1598. template <typename Derived>
  1599. template <return_value_policy policy, typename... Args>
  1600. object object_api<Derived>::operator()(Args &&...args) const {
  1601. #ifndef NDEBUG
  1602. if (!PyGILState_Check()) {
  1603. pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
  1604. }
  1605. #endif
  1606. return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
  1607. }
  1608. template <typename Derived>
  1609. template <return_value_policy policy, typename... Args>
  1610. object object_api<Derived>::call(Args &&...args) const {
  1611. return operator()<policy>(std::forward<Args>(args)...);
  1612. }
  1613. PYBIND11_NAMESPACE_END(detail)
  1614. template <typename T>
  1615. handle type::handle_of() {
  1616. static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
  1617. "py::type::of<T> only supports the case where T is a registered C++ types.");
  1618. return detail::get_type_handle(typeid(T), true);
  1619. }
  1620. #define PYBIND11_MAKE_OPAQUE(...) \
  1621. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
  1622. namespace detail { \
  1623. template <> \
  1624. class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
  1625. } \
  1626. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
  1627. /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
  1628. /// typedef, e.g.:
  1629. /// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
  1630. #define PYBIND11_TYPE(...) __VA_ARGS__
  1631. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)