cast.h 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  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 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 = Py_TYPE(src.ptr())->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. template <>
  658. class type_caster<std::tuple<>> : public tuple_caster<std::tuple> {
  659. public:
  660. // PEP 484 specifies this syntax for an empty tuple
  661. static constexpr auto name = const_name("tuple[()]");
  662. };
  663. /// Helper class which abstracts away certain actions. Users can provide specializations for
  664. /// custom holders, but it's only necessary if the type has a non-standard interface.
  665. template <typename T>
  666. struct holder_helper {
  667. static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
  668. };
  669. /// Type caster for holder types like std::shared_ptr, etc.
  670. /// The SFINAE hook is provided to help work around the current lack of support
  671. /// for smart-pointer interoperability. Please consider it an implementation
  672. /// detail that may change in the future, as formal support for smart-pointer
  673. /// interoperability is added into pybind11.
  674. template <typename type, typename holder_type, typename SFINAE = void>
  675. struct copyable_holder_caster : public type_caster_base<type> {
  676. public:
  677. using base = type_caster_base<type>;
  678. static_assert(std::is_base_of<base, type_caster<type>>::value,
  679. "Holder classes are only supported for custom types");
  680. using base::base;
  681. using base::cast;
  682. using base::typeinfo;
  683. using base::value;
  684. bool load(handle src, bool convert) {
  685. return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
  686. }
  687. explicit operator type *() { return this->value; }
  688. // static_cast works around compiler error with MSVC 17 and CUDA 10.2
  689. // see issue #2180
  690. explicit operator type &() { return *(static_cast<type *>(this->value)); }
  691. explicit operator holder_type *() { return std::addressof(holder); }
  692. explicit operator holder_type &() { return holder; }
  693. static handle cast(const holder_type &src, return_value_policy, handle) {
  694. const auto *ptr = holder_helper<holder_type>::get(src);
  695. return type_caster_base<type>::cast_holder(ptr, &src);
  696. }
  697. protected:
  698. friend class type_caster_generic;
  699. void check_holder_compat() {
  700. if (typeinfo->default_holder) {
  701. throw cast_error("Unable to load a custom holder type from a default-holder instance");
  702. }
  703. }
  704. void load_value(value_and_holder &&v_h) {
  705. if (v_h.holder_constructed()) {
  706. value = v_h.value_ptr();
  707. holder = v_h.template holder<holder_type>();
  708. return;
  709. }
  710. throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
  711. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  712. "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
  713. "type information)");
  714. #else
  715. "of type '"
  716. + type_id<holder_type>() + "''");
  717. #endif
  718. }
  719. template <typename T = holder_type,
  720. detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
  721. bool try_implicit_casts(handle, bool) {
  722. return false;
  723. }
  724. template <typename T = holder_type,
  725. detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
  726. bool try_implicit_casts(handle src, bool convert) {
  727. for (auto &cast : typeinfo->implicit_casts) {
  728. copyable_holder_caster sub_caster(*cast.first);
  729. if (sub_caster.load(src, convert)) {
  730. value = cast.second(sub_caster.value);
  731. holder = holder_type(sub_caster.holder, (type *) value);
  732. return true;
  733. }
  734. }
  735. return false;
  736. }
  737. static bool try_direct_conversions(handle) { return false; }
  738. holder_type holder;
  739. };
  740. /// Specialize for the common std::shared_ptr, so users don't need to
  741. template <typename T>
  742. class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
  743. /// Type caster for holder types like std::unique_ptr.
  744. /// Please consider the SFINAE hook an implementation detail, as explained
  745. /// in the comment for the copyable_holder_caster.
  746. template <typename type, typename holder_type, typename SFINAE = void>
  747. struct move_only_holder_caster {
  748. static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
  749. "Holder classes are only supported for custom types");
  750. static handle cast(holder_type &&src, return_value_policy, handle) {
  751. auto *ptr = holder_helper<holder_type>::get(src);
  752. return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
  753. }
  754. static constexpr auto name = type_caster_base<type>::name;
  755. };
  756. template <typename type, typename deleter>
  757. class type_caster<std::unique_ptr<type, deleter>>
  758. : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
  759. template <typename type, typename holder_type>
  760. using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
  761. copyable_holder_caster<type, holder_type>,
  762. move_only_holder_caster<type, holder_type>>;
  763. template <typename T, bool Value = false>
  764. struct always_construct_holder {
  765. static constexpr bool value = Value;
  766. };
  767. /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
  768. #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
  769. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
  770. namespace detail { \
  771. template <typename type> \
  772. struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { \
  773. }; \
  774. template <typename type> \
  775. class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
  776. : public type_caster_holder<type, holder_type> {}; \
  777. } \
  778. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
  779. // PYBIND11_DECLARE_HOLDER_TYPE holder types:
  780. template <typename base, typename holder>
  781. struct is_holder_type
  782. : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
  783. // Specialization for always-supported unique_ptr holders:
  784. template <typename base, typename deleter>
  785. struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
  786. #ifdef PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION // See PR #4888
  787. // This leads to compilation errors if a specialization is missing.
  788. template <typename T>
  789. struct handle_type_name;
  790. #else
  791. template <typename T>
  792. struct handle_type_name {
  793. static constexpr auto name = const_name<T>();
  794. };
  795. #endif
  796. template <>
  797. struct handle_type_name<object> {
  798. static constexpr auto name = const_name("object");
  799. };
  800. template <>
  801. struct handle_type_name<list> {
  802. static constexpr auto name = const_name("list");
  803. };
  804. template <>
  805. struct handle_type_name<dict> {
  806. static constexpr auto name = const_name("dict");
  807. };
  808. template <>
  809. struct handle_type_name<anyset> {
  810. static constexpr auto name = const_name("Union[set, frozenset]");
  811. };
  812. template <>
  813. struct handle_type_name<set> {
  814. static constexpr auto name = const_name("set");
  815. };
  816. template <>
  817. struct handle_type_name<frozenset> {
  818. static constexpr auto name = const_name("frozenset");
  819. };
  820. template <>
  821. struct handle_type_name<str> {
  822. static constexpr auto name = const_name("str");
  823. };
  824. template <>
  825. struct handle_type_name<tuple> {
  826. static constexpr auto name = const_name("tuple");
  827. };
  828. template <>
  829. struct handle_type_name<bool_> {
  830. static constexpr auto name = const_name("bool");
  831. };
  832. template <>
  833. struct handle_type_name<bytes> {
  834. static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
  835. };
  836. template <>
  837. struct handle_type_name<buffer> {
  838. static constexpr auto name = const_name("Buffer");
  839. };
  840. template <>
  841. struct handle_type_name<int_> {
  842. static constexpr auto name = const_name("int");
  843. };
  844. template <>
  845. struct handle_type_name<iterable> {
  846. static constexpr auto name = const_name("Iterable");
  847. };
  848. template <>
  849. struct handle_type_name<iterator> {
  850. static constexpr auto name = const_name("Iterator");
  851. };
  852. template <>
  853. struct handle_type_name<float_> {
  854. static constexpr auto name = const_name("float");
  855. };
  856. template <>
  857. struct handle_type_name<function> {
  858. static constexpr auto name = const_name("Callable");
  859. };
  860. template <>
  861. struct handle_type_name<handle> {
  862. static constexpr auto name = handle_type_name<object>::name;
  863. };
  864. template <>
  865. struct handle_type_name<none> {
  866. static constexpr auto name = const_name("None");
  867. };
  868. template <>
  869. struct handle_type_name<sequence> {
  870. static constexpr auto name = const_name("Sequence");
  871. };
  872. template <>
  873. struct handle_type_name<bytearray> {
  874. static constexpr auto name = const_name("bytearray");
  875. };
  876. template <>
  877. struct handle_type_name<memoryview> {
  878. static constexpr auto name = const_name("memoryview");
  879. };
  880. template <>
  881. struct handle_type_name<slice> {
  882. static constexpr auto name = const_name("slice");
  883. };
  884. template <>
  885. struct handle_type_name<type> {
  886. static constexpr auto name = const_name("type");
  887. };
  888. template <>
  889. struct handle_type_name<capsule> {
  890. static constexpr auto name = const_name("capsule");
  891. };
  892. template <>
  893. struct handle_type_name<ellipsis> {
  894. static constexpr auto name = const_name("ellipsis");
  895. };
  896. template <>
  897. struct handle_type_name<weakref> {
  898. static constexpr auto name = const_name("weakref");
  899. };
  900. template <>
  901. struct handle_type_name<args> {
  902. static constexpr auto name = const_name("*args");
  903. };
  904. template <>
  905. struct handle_type_name<kwargs> {
  906. static constexpr auto name = const_name("**kwargs");
  907. };
  908. template <>
  909. struct handle_type_name<obj_attr_accessor> {
  910. static constexpr auto name = const_name<obj_attr_accessor>();
  911. };
  912. template <>
  913. struct handle_type_name<str_attr_accessor> {
  914. static constexpr auto name = const_name<str_attr_accessor>();
  915. };
  916. template <>
  917. struct handle_type_name<item_accessor> {
  918. static constexpr auto name = const_name<item_accessor>();
  919. };
  920. template <>
  921. struct handle_type_name<sequence_accessor> {
  922. static constexpr auto name = const_name<sequence_accessor>();
  923. };
  924. template <>
  925. struct handle_type_name<list_accessor> {
  926. static constexpr auto name = const_name<list_accessor>();
  927. };
  928. template <>
  929. struct handle_type_name<tuple_accessor> {
  930. static constexpr auto name = const_name<tuple_accessor>();
  931. };
  932. template <typename type>
  933. struct pyobject_caster {
  934. template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
  935. pyobject_caster() : value() {}
  936. // `type` may not be default constructible (e.g. frozenset, anyset). Initializing `value`
  937. // to a nil handle is safe since it will only be accessed if `load` succeeds.
  938. template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
  939. pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
  940. template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
  941. bool load(handle src, bool /* convert */) {
  942. value = src;
  943. return static_cast<bool>(value);
  944. }
  945. template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
  946. bool load(handle src, bool /* convert */) {
  947. if (!isinstance<type>(src)) {
  948. return false;
  949. }
  950. value = reinterpret_borrow<type>(src);
  951. return true;
  952. }
  953. static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
  954. return src.inc_ref();
  955. }
  956. PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
  957. };
  958. template <typename T>
  959. class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
  960. // Our conditions for enabling moving are quite restrictive:
  961. // At compile time:
  962. // - T needs to be a non-const, non-pointer, non-reference type
  963. // - type_caster<T>::operator T&() must exist
  964. // - the type must be move constructible (obviously)
  965. // At run-time:
  966. // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
  967. // must have ref_count() == 1)h
  968. // If any of the above are not satisfied, we fall back to copying.
  969. template <typename T>
  970. using move_is_plain_type
  971. = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
  972. template <typename T, typename SFINAE = void>
  973. struct move_always : std::false_type {};
  974. template <typename T>
  975. struct move_always<
  976. T,
  977. enable_if_t<
  978. all_of<move_is_plain_type<T>,
  979. negation<is_copy_constructible<T>>,
  980. is_move_constructible<T>,
  981. std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
  982. : std::true_type {};
  983. template <typename T, typename SFINAE = void>
  984. struct move_if_unreferenced : std::false_type {};
  985. template <typename T>
  986. struct move_if_unreferenced<
  987. T,
  988. enable_if_t<
  989. all_of<move_is_plain_type<T>,
  990. negation<move_always<T>>,
  991. is_move_constructible<T>,
  992. std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
  993. : std::true_type {};
  994. template <typename T>
  995. using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
  996. // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
  997. // reference or pointer to a local variable of the type_caster. Basically, only
  998. // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
  999. // everything else returns a reference/pointer to a local variable.
  1000. template <typename type>
  1001. using cast_is_temporary_value_reference
  1002. = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
  1003. && !std::is_base_of<type_caster_generic, make_caster<type>>::value
  1004. && !std::is_same<intrinsic_t<type>, void>::value>;
  1005. // When a value returned from a C++ function is being cast back to Python, we almost always want to
  1006. // force `policy = move`, regardless of the return value policy the function/method was declared
  1007. // with.
  1008. template <typename Return, typename SFINAE = void>
  1009. struct return_value_policy_override {
  1010. static return_value_policy policy(return_value_policy p) { return p; }
  1011. };
  1012. template <typename Return>
  1013. struct return_value_policy_override<
  1014. Return,
  1015. detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
  1016. static return_value_policy policy(return_value_policy p) {
  1017. return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
  1018. ? return_value_policy::move
  1019. : p;
  1020. }
  1021. };
  1022. // Basic python -> C++ casting; throws if casting fails
  1023. template <typename T, typename SFINAE>
  1024. type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
  1025. static_assert(!detail::is_pyobject<T>::value,
  1026. "Internal error: type_caster should only be used for C++ types");
  1027. if (!conv.load(handle, true)) {
  1028. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1029. throw cast_error(
  1030. "Unable to cast Python instance of type "
  1031. + str(type::handle_of(handle)).cast<std::string>()
  1032. + " to C++ type '?' (#define "
  1033. "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1034. #else
  1035. throw cast_error("Unable to cast Python instance of type "
  1036. + str(type::handle_of(handle)).cast<std::string>() + " to C++ type '"
  1037. + type_id<T>() + "'");
  1038. #endif
  1039. }
  1040. return conv;
  1041. }
  1042. // Wrapper around the above that also constructs and returns a type_caster
  1043. template <typename T>
  1044. make_caster<T> load_type(const handle &handle) {
  1045. make_caster<T> conv;
  1046. load_type(conv, handle);
  1047. return conv;
  1048. }
  1049. PYBIND11_NAMESPACE_END(detail)
  1050. // pytype -> C++ type
  1051. template <typename T,
  1052. detail::enable_if_t<!detail::is_pyobject<T>::value
  1053. && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
  1054. int>
  1055. = 0>
  1056. T cast(const handle &handle) {
  1057. using namespace detail;
  1058. static_assert(!cast_is_temporary_value_reference<T>::value,
  1059. "Unable to cast type to reference: value is local to type caster");
  1060. return cast_op<T>(load_type<T>(handle));
  1061. }
  1062. // pytype -> pytype (calls converting constructor)
  1063. template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
  1064. T cast(const handle &handle) {
  1065. return T(reinterpret_borrow<object>(handle));
  1066. }
  1067. // Note that `cast<PyObject *>(obj)` increments the reference count of `obj`.
  1068. // This is necessary for the case that `obj` is a temporary, and could
  1069. // not possibly be different, given
  1070. // 1. the established convention that the passed `handle` is borrowed, and
  1071. // 2. we don't want to force all generic code using `cast<T>()` to special-case
  1072. // handling of `T` = `PyObject *` (to increment the reference count there).
  1073. // It is the responsibility of the caller to ensure that the reference count
  1074. // is decremented.
  1075. template <typename T,
  1076. typename Handle,
  1077. detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
  1078. && detail::is_same_ignoring_cvref<Handle, handle>::value,
  1079. int>
  1080. = 0>
  1081. T cast(Handle &&handle) {
  1082. return handle.inc_ref().ptr();
  1083. }
  1084. // To optimize way an inc_ref/dec_ref cycle:
  1085. template <typename T,
  1086. typename Object,
  1087. detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
  1088. && detail::is_same_ignoring_cvref<Object, object>::value,
  1089. int>
  1090. = 0>
  1091. T cast(Object &&obj) {
  1092. return obj.release().ptr();
  1093. }
  1094. // C++ type -> py::object
  1095. template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
  1096. object cast(T &&value,
  1097. return_value_policy policy = return_value_policy::automatic_reference,
  1098. handle parent = handle()) {
  1099. using no_ref_T = typename std::remove_reference<T>::type;
  1100. if (policy == return_value_policy::automatic) {
  1101. policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
  1102. : std::is_lvalue_reference<T>::value ? return_value_policy::copy
  1103. : return_value_policy::move;
  1104. } else if (policy == return_value_policy::automatic_reference) {
  1105. policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
  1106. : std::is_lvalue_reference<T>::value ? return_value_policy::copy
  1107. : return_value_policy::move;
  1108. }
  1109. return reinterpret_steal<object>(
  1110. detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
  1111. }
  1112. template <typename T>
  1113. T handle::cast() const {
  1114. return pybind11::cast<T>(*this);
  1115. }
  1116. template <>
  1117. inline void handle::cast() const {
  1118. return;
  1119. }
  1120. template <typename T>
  1121. detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
  1122. if (obj.ref_count() > 1) {
  1123. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1124. throw cast_error(
  1125. "Unable to cast Python " + str(type::handle_of(obj)).cast<std::string>()
  1126. + " instance to C++ rvalue: instance has multiple references"
  1127. " (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1128. #else
  1129. throw cast_error("Unable to move from Python "
  1130. + str(type::handle_of(obj)).cast<std::string>() + " instance to C++ "
  1131. + type_id<T>() + " instance: instance has multiple references");
  1132. #endif
  1133. }
  1134. // Move into a temporary and return that, because the reference may be a local value of `conv`
  1135. T ret = std::move(detail::load_type<T>(obj).operator T &());
  1136. return ret;
  1137. }
  1138. // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
  1139. // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
  1140. // object has multiple references, but trying to copy will fail to compile.
  1141. // - If both movable and copyable, check ref count: if 1, move; otherwise copy
  1142. // - Otherwise (not movable), copy.
  1143. template <typename T>
  1144. detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>
  1145. cast(object &&object) {
  1146. return move<T>(std::move(object));
  1147. }
  1148. template <typename T>
  1149. detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>
  1150. cast(object &&object) {
  1151. if (object.ref_count() > 1) {
  1152. return cast<T>(object);
  1153. }
  1154. return move<T>(std::move(object));
  1155. }
  1156. template <typename T>
  1157. detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>
  1158. cast(object &&object) {
  1159. return cast<T>(object);
  1160. }
  1161. // pytype rvalue -> pytype (calls converting constructor)
  1162. template <typename T>
  1163. detail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {
  1164. return T(std::move(object));
  1165. }
  1166. template <typename T>
  1167. T object::cast() const & {
  1168. return pybind11::cast<T>(*this);
  1169. }
  1170. template <typename T>
  1171. T object::cast() && {
  1172. return pybind11::cast<T>(std::move(*this));
  1173. }
  1174. template <>
  1175. inline void object::cast() const & {
  1176. return;
  1177. }
  1178. template <>
  1179. inline void object::cast() && {
  1180. return;
  1181. }
  1182. PYBIND11_NAMESPACE_BEGIN(detail)
  1183. // Declared in pytypes.h:
  1184. template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
  1185. object object_or_cast(T &&o) {
  1186. return pybind11::cast(std::forward<T>(o));
  1187. }
  1188. // Placeholder type for the unneeded (and dead code) static variable in the
  1189. // PYBIND11_OVERRIDE_OVERRIDE macro
  1190. struct override_unused {};
  1191. template <typename ret_type>
  1192. using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
  1193. make_caster<ret_type>,
  1194. override_unused>;
  1195. // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
  1196. // store the result in the given variable. For other types, this is a no-op.
  1197. template <typename T>
  1198. enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
  1199. make_caster<T> &caster) {
  1200. return cast_op<T>(load_type(caster, o));
  1201. }
  1202. template <typename T>
  1203. enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
  1204. override_unused &) {
  1205. pybind11_fail("Internal error: cast_ref fallback invoked");
  1206. }
  1207. // Trampoline use: Having a pybind11::cast with an invalid reference type is going to
  1208. // static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
  1209. // that only does anything in cases where pybind11::cast is valid.
  1210. template <typename T>
  1211. enable_if_t<cast_is_temporary_value_reference<T>::value
  1212. && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
  1213. T>
  1214. cast_safe(object &&) {
  1215. pybind11_fail("Internal error: cast_safe fallback invoked");
  1216. }
  1217. template <typename T>
  1218. enable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}
  1219. template <typename T>
  1220. enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value, PyObject *>
  1221. cast_safe(object &&o) {
  1222. return o.release().ptr();
  1223. }
  1224. template <typename T>
  1225. enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>,
  1226. detail::is_same_ignoring_cvref<T, PyObject *>,
  1227. std::is_void<T>>::value,
  1228. T>
  1229. cast_safe(object &&o) {
  1230. return pybind11::cast<T>(std::move(o));
  1231. }
  1232. PYBIND11_NAMESPACE_END(detail)
  1233. // The overloads could coexist, i.e. the #if is not strictly speaking needed,
  1234. // but it is an easy minor optimization.
  1235. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1236. inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name) {
  1237. return cast_error("Unable to convert call argument '" + name
  1238. + "' to Python object (#define "
  1239. "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1240. }
  1241. #else
  1242. inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
  1243. const std::string &type) {
  1244. return cast_error("Unable to convert call argument '" + name + "' of type '" + type
  1245. + "' to Python object");
  1246. }
  1247. #endif
  1248. template <return_value_policy policy = return_value_policy::automatic_reference>
  1249. tuple make_tuple() {
  1250. return tuple(0);
  1251. }
  1252. template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
  1253. tuple make_tuple(Args &&...args_) {
  1254. constexpr size_t size = sizeof...(Args);
  1255. std::array<object, size> args{{reinterpret_steal<object>(
  1256. detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
  1257. for (size_t i = 0; i < args.size(); i++) {
  1258. if (!args[i]) {
  1259. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1260. throw cast_error_unable_to_convert_call_arg(std::to_string(i));
  1261. #else
  1262. std::array<std::string, size> argtypes{{type_id<Args>()...}};
  1263. throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
  1264. #endif
  1265. }
  1266. }
  1267. tuple result(size);
  1268. int counter = 0;
  1269. for (auto &arg_value : args) {
  1270. PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
  1271. }
  1272. return result;
  1273. }
  1274. /// \ingroup annotations
  1275. /// Annotation for arguments
  1276. struct arg {
  1277. /// Constructs an argument with the name of the argument; if null or omitted, this is a
  1278. /// positional argument.
  1279. constexpr explicit arg(const char *name = nullptr)
  1280. : name(name), flag_noconvert(false), flag_none(true) {}
  1281. /// Assign a value to this argument
  1282. template <typename T>
  1283. arg_v operator=(T &&value) const;
  1284. /// Indicate that the type should not be converted in the type caster
  1285. arg &noconvert(bool flag = true) {
  1286. flag_noconvert = flag;
  1287. return *this;
  1288. }
  1289. /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
  1290. arg &none(bool flag = true) {
  1291. flag_none = flag;
  1292. return *this;
  1293. }
  1294. const char *name; ///< If non-null, this is a named kwargs argument
  1295. bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type
  1296. ///< caster!)
  1297. bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
  1298. };
  1299. /// \ingroup annotations
  1300. /// Annotation for arguments with values
  1301. struct arg_v : arg {
  1302. private:
  1303. template <typename T>
  1304. arg_v(arg &&base, T &&x, const char *descr = nullptr)
  1305. : arg(base), value(reinterpret_steal<object>(detail::make_caster<T>::cast(
  1306. std::forward<T>(x), return_value_policy::automatic, {}))),
  1307. descr(descr)
  1308. #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1309. ,
  1310. type(type_id<T>())
  1311. #endif
  1312. {
  1313. // Workaround! See:
  1314. // https://github.com/pybind/pybind11/issues/2336
  1315. // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
  1316. if (PyErr_Occurred()) {
  1317. PyErr_Clear();
  1318. }
  1319. }
  1320. public:
  1321. /// Direct construction with name, default, and description
  1322. template <typename T>
  1323. arg_v(const char *name, T &&x, const char *descr = nullptr)
  1324. : arg_v(arg(name), std::forward<T>(x), descr) {}
  1325. /// Called internally when invoking `py::arg("a") = value`
  1326. template <typename T>
  1327. arg_v(const arg &base, T &&x, const char *descr = nullptr)
  1328. : arg_v(arg(base), std::forward<T>(x), descr) {}
  1329. /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
  1330. arg_v &noconvert(bool flag = true) {
  1331. arg::noconvert(flag);
  1332. return *this;
  1333. }
  1334. /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
  1335. arg_v &none(bool flag = true) {
  1336. arg::none(flag);
  1337. return *this;
  1338. }
  1339. /// The default value
  1340. object value;
  1341. /// The (optional) description of the default value
  1342. const char *descr;
  1343. #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1344. /// The C++ type name of the default value (only available when compiled in debug mode)
  1345. std::string type;
  1346. #endif
  1347. };
  1348. /// \ingroup annotations
  1349. /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of
  1350. /// an unnamed '*' argument
  1351. struct kw_only {};
  1352. /// \ingroup annotations
  1353. /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of
  1354. /// an unnamed '/' argument
  1355. struct pos_only {};
  1356. template <typename T>
  1357. arg_v arg::operator=(T &&value) const {
  1358. return {*this, std::forward<T>(value)};
  1359. }
  1360. /// Alias for backward compatibility -- to be removed in version 2.0
  1361. template <typename /*unused*/>
  1362. using arg_t = arg_v;
  1363. inline namespace literals {
  1364. /** \rst
  1365. String literal version of `arg`
  1366. \endrst */
  1367. constexpr arg
  1368. #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
  1369. operator"" _a // gcc 4.8.5 insists on having a space (hard error).
  1370. #else
  1371. operator""_a // clang 17 generates a deprecation warning if there is a space.
  1372. #endif
  1373. (const char *name, size_t) {
  1374. return arg(name);
  1375. }
  1376. } // namespace literals
  1377. PYBIND11_NAMESPACE_BEGIN(detail)
  1378. template <typename T>
  1379. using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
  1380. template <typename T>
  1381. using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
  1382. // forward declaration (definition in attr.h)
  1383. struct function_record;
  1384. /// Internal data associated with a single function call
  1385. struct function_call {
  1386. function_call(const function_record &f, handle p); // Implementation in attr.h
  1387. /// The function data:
  1388. const function_record &func;
  1389. /// Arguments passed to the function:
  1390. std::vector<handle> args;
  1391. /// The `convert` value the arguments should be loaded with
  1392. std::vector<bool> args_convert;
  1393. /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
  1394. /// present, are also in `args` but without a reference).
  1395. object args_ref, kwargs_ref;
  1396. /// The parent, if any
  1397. handle parent;
  1398. /// If this is a call to an initializer, this argument contains `self`
  1399. handle init_self;
  1400. };
  1401. // See PR #5396 for the discussion that led to this
  1402. template <typename Base, typename Derived, typename = void>
  1403. struct is_same_or_base_of : std::is_same<Base, Derived> {};
  1404. // Only evaluate is_base_of if Derived is complete.
  1405. // is_base_of raises a compiler error if Derived is incomplete.
  1406. template <typename Base, typename Derived>
  1407. struct is_same_or_base_of<Base, Derived, decltype(void(sizeof(Derived)))>
  1408. : any_of<std::is_same<Base, Derived>, std::is_base_of<Base, Derived>> {};
  1409. /// Helper class which loads arguments for C++ functions called from Python
  1410. template <typename... Args>
  1411. class argument_loader {
  1412. using indices = make_index_sequence<sizeof...(Args)>;
  1413. template <typename Arg>
  1414. using argument_is_args = is_same_or_base_of<args, intrinsic_t<Arg>>;
  1415. template <typename Arg>
  1416. using argument_is_kwargs = is_same_or_base_of<kwargs, intrinsic_t<Arg>>;
  1417. // Get kwargs argument position, or -1 if not present:
  1418. static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
  1419. static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
  1420. "py::kwargs is only permitted as the last argument of a function");
  1421. public:
  1422. static constexpr bool has_kwargs = kwargs_pos != -1;
  1423. // py::args argument position; -1 if not present.
  1424. static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
  1425. static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
  1426. "py::args cannot be specified more than once");
  1427. static constexpr auto arg_names
  1428. = ::pybind11::detail::concat(type_descr(make_caster<Args>::name)...);
  1429. bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
  1430. template <typename Return, typename Guard, typename Func>
  1431. // NOLINTNEXTLINE(readability-const-return-type)
  1432. enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
  1433. return std::move(*this).template call_impl<remove_cv_t<Return>>(
  1434. std::forward<Func>(f), indices{}, Guard{});
  1435. }
  1436. template <typename Return, typename Guard, typename Func>
  1437. enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
  1438. std::move(*this).template call_impl<remove_cv_t<Return>>(
  1439. std::forward<Func>(f), indices{}, Guard{});
  1440. return void_type();
  1441. }
  1442. private:
  1443. static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
  1444. template <size_t... Is>
  1445. bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
  1446. #ifdef __cpp_fold_expressions
  1447. if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
  1448. return false;
  1449. }
  1450. #else
  1451. for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
  1452. if (!r) {
  1453. return false;
  1454. }
  1455. }
  1456. #endif
  1457. return true;
  1458. }
  1459. template <typename Return, typename Func, size_t... Is, typename Guard>
  1460. Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
  1461. return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
  1462. }
  1463. std::tuple<make_caster<Args>...> argcasters;
  1464. };
  1465. /// Helper class which collects only positional arguments for a Python function call.
  1466. /// A fancier version below can collect any argument, but this one is optimal for simple calls.
  1467. template <return_value_policy policy>
  1468. class simple_collector {
  1469. public:
  1470. template <typename... Ts>
  1471. explicit simple_collector(Ts &&...values)
  1472. : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) {}
  1473. const tuple &args() const & { return m_args; }
  1474. dict kwargs() const { return {}; }
  1475. tuple args() && { return std::move(m_args); }
  1476. /// Call a Python function and pass the collected arguments
  1477. object call(PyObject *ptr) const {
  1478. PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
  1479. if (!result) {
  1480. throw error_already_set();
  1481. }
  1482. return reinterpret_steal<object>(result);
  1483. }
  1484. private:
  1485. tuple m_args;
  1486. };
  1487. /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
  1488. template <return_value_policy policy>
  1489. class unpacking_collector {
  1490. public:
  1491. template <typename... Ts>
  1492. explicit unpacking_collector(Ts &&...values) {
  1493. // Tuples aren't (easily) resizable so a list is needed for collection,
  1494. // but the actual function call strictly requires a tuple.
  1495. auto args_list = list();
  1496. using expander = int[];
  1497. (void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...};
  1498. m_args = std::move(args_list);
  1499. }
  1500. const tuple &args() const & { return m_args; }
  1501. const dict &kwargs() const & { return m_kwargs; }
  1502. tuple args() && { return std::move(m_args); }
  1503. dict kwargs() && { return std::move(m_kwargs); }
  1504. /// Call a Python function and pass the collected arguments
  1505. object call(PyObject *ptr) const {
  1506. PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
  1507. if (!result) {
  1508. throw error_already_set();
  1509. }
  1510. return reinterpret_steal<object>(result);
  1511. }
  1512. private:
  1513. template <typename T>
  1514. void process(list &args_list, T &&x) {
  1515. auto o = reinterpret_steal<object>(
  1516. detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
  1517. if (!o) {
  1518. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1519. throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()));
  1520. #else
  1521. throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()),
  1522. type_id<T>());
  1523. #endif
  1524. }
  1525. args_list.append(std::move(o));
  1526. }
  1527. void process(list &args_list, detail::args_proxy ap) {
  1528. for (auto a : ap) {
  1529. args_list.append(a);
  1530. }
  1531. }
  1532. void process(list & /*args_list*/, arg_v a) {
  1533. if (!a.name) {
  1534. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1535. nameless_argument_error();
  1536. #else
  1537. nameless_argument_error(a.type);
  1538. #endif
  1539. }
  1540. if (m_kwargs.contains(a.name)) {
  1541. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1542. multiple_values_error();
  1543. #else
  1544. multiple_values_error(a.name);
  1545. #endif
  1546. }
  1547. if (!a.value) {
  1548. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1549. throw cast_error_unable_to_convert_call_arg(a.name);
  1550. #else
  1551. throw cast_error_unable_to_convert_call_arg(a.name, a.type);
  1552. #endif
  1553. }
  1554. m_kwargs[a.name] = std::move(a.value);
  1555. }
  1556. void process(list & /*args_list*/, detail::kwargs_proxy kp) {
  1557. if (!kp) {
  1558. return;
  1559. }
  1560. for (auto k : reinterpret_borrow<dict>(kp)) {
  1561. if (m_kwargs.contains(k.first)) {
  1562. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1563. multiple_values_error();
  1564. #else
  1565. multiple_values_error(str(k.first));
  1566. #endif
  1567. }
  1568. m_kwargs[k.first] = k.second;
  1569. }
  1570. }
  1571. [[noreturn]] static void nameless_argument_error() {
  1572. throw type_error(
  1573. "Got kwargs without a name; only named arguments "
  1574. "may be passed via py::arg() to a python function call. "
  1575. "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1576. }
  1577. [[noreturn]] static void nameless_argument_error(const std::string &type) {
  1578. throw type_error("Got kwargs without a name of type '" + type
  1579. + "'; only named "
  1580. "arguments may be passed via py::arg() to a python function call. ");
  1581. }
  1582. [[noreturn]] static void multiple_values_error() {
  1583. throw type_error(
  1584. "Got multiple values for keyword argument "
  1585. "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1586. }
  1587. [[noreturn]] static void multiple_values_error(const std::string &name) {
  1588. throw type_error("Got multiple values for keyword argument '" + name + "'");
  1589. }
  1590. private:
  1591. tuple m_args;
  1592. dict m_kwargs;
  1593. };
  1594. // [workaround(intel)] Separate function required here
  1595. // We need to put this into a separate function because the Intel compiler
  1596. // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
  1597. // (tested with ICC 2021.1 Beta 20200827).
  1598. template <typename... Args>
  1599. constexpr bool args_are_all_positional() {
  1600. return all_of<is_positional<Args>...>::value;
  1601. }
  1602. /// Collect only positional arguments for a Python function call
  1603. template <return_value_policy policy,
  1604. typename... Args,
  1605. typename = enable_if_t<args_are_all_positional<Args...>()>>
  1606. simple_collector<policy> collect_arguments(Args &&...args) {
  1607. return simple_collector<policy>(std::forward<Args>(args)...);
  1608. }
  1609. /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
  1610. template <return_value_policy policy,
  1611. typename... Args,
  1612. typename = enable_if_t<!args_are_all_positional<Args...>()>>
  1613. unpacking_collector<policy> collect_arguments(Args &&...args) {
  1614. // Following argument order rules for generalized unpacking according to PEP 448
  1615. static_assert(constexpr_last<is_positional, Args...>()
  1616. < constexpr_first<is_keyword_or_ds, Args...>()
  1617. && constexpr_last<is_s_unpacking, Args...>()
  1618. < constexpr_first<is_ds_unpacking, Args...>(),
  1619. "Invalid function call: positional args must precede keywords and ** unpacking; "
  1620. "* unpacking must precede ** unpacking");
  1621. return unpacking_collector<policy>(std::forward<Args>(args)...);
  1622. }
  1623. template <typename Derived>
  1624. template <return_value_policy policy, typename... Args>
  1625. object object_api<Derived>::operator()(Args &&...args) const {
  1626. #ifndef NDEBUG
  1627. if (!PyGILState_Check()) {
  1628. pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
  1629. }
  1630. #endif
  1631. return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
  1632. }
  1633. template <typename Derived>
  1634. template <return_value_policy policy, typename... Args>
  1635. object object_api<Derived>::call(Args &&...args) const {
  1636. return operator()<policy>(std::forward<Args>(args)...);
  1637. }
  1638. PYBIND11_NAMESPACE_END(detail)
  1639. template <typename T>
  1640. handle type::handle_of() {
  1641. static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
  1642. "py::type::of<T> only supports the case where T is a registered C++ types.");
  1643. return detail::get_type_handle(typeid(T), true);
  1644. }
  1645. #define PYBIND11_MAKE_OPAQUE(...) \
  1646. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
  1647. namespace detail { \
  1648. template <> \
  1649. class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
  1650. } \
  1651. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
  1652. /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
  1653. /// typedef, e.g.:
  1654. /// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
  1655. #define PYBIND11_TYPE(...) __VA_ARGS__
  1656. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)