cast.h 64 KB

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