cast.h 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361
  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/native_enum_data.h"
  12. #include "detail/type_caster_base.h"
  13. #include "detail/typeid.h"
  14. #include "pytypes.h"
  15. #include <array>
  16. #include <cstring>
  17. #include <functional>
  18. #include <iosfwd>
  19. #include <iterator>
  20. #include <memory>
  21. #include <string>
  22. #include <tuple>
  23. #include <type_traits>
  24. #include <utility>
  25. #include <vector>
  26. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  27. PYBIND11_WARNING_DISABLE_MSVC(4127)
  28. PYBIND11_NAMESPACE_BEGIN(detail)
  29. template <typename type, typename SFINAE = void>
  30. class type_caster : public type_caster_base<type> {};
  31. template <typename type>
  32. using make_caster = type_caster<intrinsic_t<type>>;
  33. // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
  34. template <typename T>
  35. typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
  36. using result_t = typename make_caster<T>::template cast_op_type<T>; // See PR #4893
  37. return caster.operator result_t();
  38. }
  39. template <typename T>
  40. typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
  41. cast_op(make_caster<T> &&caster) {
  42. using result_t = typename make_caster<T>::template cast_op_type<
  43. typename std::add_rvalue_reference<T>::type>; // See PR #4893
  44. return std::move(caster).operator result_t();
  45. }
  46. template <typename EnumType>
  47. class type_caster_enum_type {
  48. private:
  49. using Underlying = typename std::underlying_type<EnumType>::type;
  50. public:
  51. static constexpr auto name = const_name<EnumType>();
  52. template <typename SrcType>
  53. static handle cast(SrcType &&src, return_value_policy, handle parent) {
  54. handle native_enum
  55. = global_internals_native_enum_type_map_get_item(std::type_index(typeid(EnumType)));
  56. if (native_enum) {
  57. return native_enum(static_cast<Underlying>(src)).release();
  58. }
  59. return type_caster_base<EnumType>::cast(
  60. std::forward<SrcType>(src),
  61. // Fixes https://github.com/pybind/pybind11/pull/3643#issuecomment-1022987818:
  62. return_value_policy::copy,
  63. parent);
  64. }
  65. template <typename SrcType>
  66. static handle cast(SrcType *src, return_value_policy policy, handle parent) {
  67. return cast(*src, policy, parent);
  68. }
  69. bool load(handle src, bool convert) {
  70. handle native_enum
  71. = global_internals_native_enum_type_map_get_item(std::type_index(typeid(EnumType)));
  72. if (native_enum) {
  73. if (!isinstance(src, native_enum)) {
  74. return false;
  75. }
  76. type_caster<Underlying> underlying_caster;
  77. if (!underlying_caster.load(src.attr("value"), convert)) {
  78. pybind11_fail("native_enum internal consistency failure.");
  79. }
  80. value = static_cast<EnumType>(static_cast<Underlying>(underlying_caster));
  81. return true;
  82. }
  83. if (!pybind11_enum_) {
  84. pybind11_enum_.reset(new type_caster_base<EnumType>());
  85. }
  86. return pybind11_enum_->load(src, convert);
  87. }
  88. template <typename T>
  89. using cast_op_type = detail::cast_op_type<T>;
  90. // NOLINTNEXTLINE(google-explicit-constructor)
  91. operator EnumType *() {
  92. if (!pybind11_enum_) {
  93. return &value;
  94. }
  95. return pybind11_enum_->operator EnumType *();
  96. }
  97. // NOLINTNEXTLINE(google-explicit-constructor)
  98. operator EnumType &() {
  99. if (!pybind11_enum_) {
  100. return value;
  101. }
  102. return pybind11_enum_->operator EnumType &();
  103. }
  104. private:
  105. std::unique_ptr<type_caster_base<EnumType>> pybind11_enum_;
  106. EnumType value;
  107. };
  108. template <typename EnumType, typename SFINAE = void>
  109. struct type_caster_enum_type_enabled : std::true_type {};
  110. template <typename T>
  111. struct type_uses_type_caster_enum_type {
  112. static constexpr bool value
  113. = std::is_enum<T>::value && type_caster_enum_type_enabled<T>::value;
  114. };
  115. template <typename EnumType>
  116. class type_caster<EnumType, detail::enable_if_t<type_uses_type_caster_enum_type<EnumType>::value>>
  117. : public type_caster_enum_type<EnumType> {};
  118. template <typename T, detail::enable_if_t<std::is_enum<T>::value, int> = 0>
  119. bool isinstance_native_enum_impl(handle obj, const std::type_info &tp) {
  120. handle native_enum = global_internals_native_enum_type_map_get_item(tp);
  121. if (!native_enum) {
  122. return false;
  123. }
  124. return isinstance(obj, native_enum);
  125. }
  126. template <typename T, detail::enable_if_t<!std::is_enum<T>::value, int> = 0>
  127. bool isinstance_native_enum_impl(handle, const std::type_info &) {
  128. return false;
  129. }
  130. template <typename T>
  131. bool isinstance_native_enum(handle obj, const std::type_info &tp) {
  132. return isinstance_native_enum_impl<intrinsic_t<T>>(obj, tp);
  133. }
  134. template <typename type>
  135. class type_caster<std::reference_wrapper<type>> {
  136. private:
  137. using caster_t = make_caster<type>;
  138. caster_t subcaster;
  139. using reference_t = type &;
  140. using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
  141. static_assert(
  142. std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
  143. || std::is_same<reference_t, subcaster_cast_op_type>::value,
  144. "std::reference_wrapper<T> caster requires T to have a caster with an "
  145. "`operator T &()` or `operator const T &()`");
  146. public:
  147. bool load(handle src, bool convert) { return subcaster.load(src, convert); }
  148. static constexpr auto name = caster_t::name;
  149. static handle
  150. cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
  151. // It is definitely wrong to take ownership of this pointer, so mask that rvp
  152. if (policy == return_value_policy::take_ownership
  153. || policy == return_value_policy::automatic) {
  154. policy = return_value_policy::automatic_reference;
  155. }
  156. return caster_t::cast(&src.get(), policy, parent);
  157. }
  158. template <typename T>
  159. using cast_op_type = std::reference_wrapper<type>;
  160. explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
  161. };
  162. #define PYBIND11_TYPE_CASTER(type, py_name) \
  163. protected: \
  164. type value; \
  165. \
  166. public: \
  167. static constexpr auto name = py_name; \
  168. template <typename T_, \
  169. ::pybind11::detail::enable_if_t< \
  170. std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value, \
  171. int> \
  172. = 0> \
  173. static ::pybind11::handle cast( \
  174. T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) { \
  175. if (!src) \
  176. return ::pybind11::none().release(); \
  177. if (policy == ::pybind11::return_value_policy::take_ownership) { \
  178. auto h = cast(std::move(*src), policy, parent); \
  179. delete src; \
  180. return h; \
  181. } \
  182. return cast(*src, policy, parent); \
  183. } \
  184. operator type *() { return &value; } /* NOLINT(bugprone-macro-parentheses) */ \
  185. operator type &() { return value; } /* NOLINT(bugprone-macro-parentheses) */ \
  186. operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */ \
  187. template <typename T_> \
  188. using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
  189. template <typename CharT>
  190. using is_std_char_type = any_of<std::is_same<CharT, char>, /* std::string */
  191. #if defined(PYBIND11_HAS_U8STRING)
  192. std::is_same<CharT, char8_t>, /* std::u8string */
  193. #endif
  194. std::is_same<CharT, char16_t>, /* std::u16string */
  195. std::is_same<CharT, char32_t>, /* std::u32string */
  196. std::is_same<CharT, wchar_t> /* std::wstring */
  197. >;
  198. template <typename T>
  199. struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
  200. using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
  201. using _py_type_1 = conditional_t<std::is_signed<T>::value,
  202. _py_type_0,
  203. typename std::make_unsigned<_py_type_0>::type>;
  204. using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
  205. public:
  206. bool load(handle src, bool convert) {
  207. py_type py_value;
  208. if (!src) {
  209. return false;
  210. }
  211. #if !defined(PYPY_VERSION)
  212. auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
  213. #else
  214. // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
  215. // while CPython only considers the existence of `nb_index`/`__index__`.
  216. auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
  217. #endif
  218. if (std::is_floating_point<T>::value) {
  219. if (convert || PyFloat_Check(src.ptr())) {
  220. py_value = (py_type) PyFloat_AsDouble(src.ptr());
  221. } else {
  222. return false;
  223. }
  224. } else if (PyFloat_Check(src.ptr())
  225. || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
  226. return false;
  227. } else {
  228. handle src_or_index = src;
  229. // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
  230. #if defined(PYPY_VERSION)
  231. object index;
  232. if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
  233. index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
  234. if (!index) {
  235. PyErr_Clear();
  236. if (!convert)
  237. return false;
  238. } else {
  239. src_or_index = index;
  240. }
  241. }
  242. #endif
  243. if (std::is_unsigned<py_type>::value) {
  244. py_value = as_unsigned<py_type>(src_or_index.ptr());
  245. } else { // signed integer:
  246. py_value = sizeof(T) <= sizeof(long)
  247. ? (py_type) PyLong_AsLong(src_or_index.ptr())
  248. : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
  249. }
  250. }
  251. // Python API reported an error
  252. bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
  253. // Check to see if the conversion is valid (integers should match exactly)
  254. // Signed/unsigned checks happen elsewhere
  255. if (py_err
  256. || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
  257. && py_value != (py_type) (T) py_value)) {
  258. PyErr_Clear();
  259. if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
  260. auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
  261. ? PyNumber_Float(src.ptr())
  262. : PyNumber_Long(src.ptr()));
  263. PyErr_Clear();
  264. return load(tmp, false);
  265. }
  266. return false;
  267. }
  268. value = (T) py_value;
  269. return true;
  270. }
  271. template <typename U = T>
  272. static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
  273. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  274. return PyFloat_FromDouble((double) src);
  275. }
  276. template <typename U = T>
  277. static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
  278. && (sizeof(U) <= sizeof(long)),
  279. handle>::type
  280. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  281. return PYBIND11_LONG_FROM_SIGNED((long) src);
  282. }
  283. template <typename U = T>
  284. static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
  285. && (sizeof(U) <= sizeof(unsigned long)),
  286. handle>::type
  287. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  288. return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
  289. }
  290. template <typename U = T>
  291. static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
  292. && (sizeof(U) > sizeof(long)),
  293. handle>::type
  294. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  295. return PyLong_FromLongLong((long long) src);
  296. }
  297. template <typename U = T>
  298. static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
  299. && (sizeof(U) > sizeof(unsigned long)),
  300. handle>::type
  301. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  302. return PyLong_FromUnsignedLongLong((unsigned long long) src);
  303. }
  304. PYBIND11_TYPE_CASTER(T,
  305. io_name<std::is_integral<T>::value>(
  306. "typing.SupportsInt", "int", "typing.SupportsFloat", "float"));
  307. };
  308. template <typename T>
  309. struct void_caster {
  310. public:
  311. bool load(handle src, bool) {
  312. if (src && src.is_none()) {
  313. return true;
  314. }
  315. return false;
  316. }
  317. static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
  318. return none().release();
  319. }
  320. PYBIND11_TYPE_CASTER(T, const_name("None"));
  321. };
  322. template <>
  323. class type_caster<void_type> : public void_caster<void_type> {};
  324. template <>
  325. class type_caster<void> : public type_caster<void_type> {
  326. public:
  327. using type_caster<void_type>::cast;
  328. bool load(handle h, bool) {
  329. if (!h) {
  330. return false;
  331. }
  332. if (h.is_none()) {
  333. value = nullptr;
  334. return true;
  335. }
  336. /* Check if this is a capsule */
  337. if (isinstance<capsule>(h)) {
  338. value = reinterpret_borrow<capsule>(h);
  339. return true;
  340. }
  341. /* Check if this is a C++ type */
  342. const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
  343. if (bases.size() == 1) { // Only allowing loading from a single-value type
  344. value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
  345. return true;
  346. }
  347. /* Fail */
  348. return false;
  349. }
  350. static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
  351. if (ptr) {
  352. return capsule(ptr).release();
  353. }
  354. return none().release();
  355. }
  356. template <typename T>
  357. using cast_op_type = void *&;
  358. explicit operator void *&() { return value; }
  359. static constexpr auto name = const_name(PYBIND11_CAPSULE_TYPE_TYPE_HINT);
  360. private:
  361. void *value = nullptr;
  362. };
  363. template <>
  364. class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
  365. template <>
  366. class type_caster<bool> {
  367. public:
  368. bool load(handle src, bool convert) {
  369. if (!src) {
  370. return false;
  371. }
  372. if (src.ptr() == Py_True) {
  373. value = true;
  374. return true;
  375. }
  376. if (src.ptr() == Py_False) {
  377. value = false;
  378. return true;
  379. }
  380. if (convert || is_numpy_bool(src)) {
  381. // (allow non-implicit conversion for numpy booleans), use strncmp
  382. // since NumPy 1.x had an additional trailing underscore.
  383. Py_ssize_t res = -1;
  384. if (src.is_none()) {
  385. res = 0; // None is implicitly converted to False
  386. }
  387. #if defined(PYPY_VERSION)
  388. // On PyPy, check that "__bool__" attr exists
  389. else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
  390. res = PyObject_IsTrue(src.ptr());
  391. }
  392. #else
  393. // Alternate approach for CPython: this does the same as the above, but optimized
  394. // using the CPython API so as to avoid an unneeded attribute lookup.
  395. else if (auto *tp_as_number = Py_TYPE(src.ptr())->tp_as_number) {
  396. if (PYBIND11_NB_BOOL(tp_as_number)) {
  397. res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
  398. }
  399. }
  400. #endif
  401. if (res == 0 || res == 1) {
  402. value = (res != 0);
  403. return true;
  404. }
  405. PyErr_Clear();
  406. }
  407. return false;
  408. }
  409. static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
  410. return handle(src ? Py_True : Py_False).inc_ref();
  411. }
  412. PYBIND11_TYPE_CASTER(bool, const_name("bool"));
  413. private:
  414. // Test if an object is a NumPy boolean (without fetching the type).
  415. static inline bool is_numpy_bool(handle object) {
  416. const char *type_name = Py_TYPE(object.ptr())->tp_name;
  417. // Name changed to `numpy.bool` in NumPy 2, `numpy.bool_` is needed for 1.x support
  418. return std::strcmp("numpy.bool", type_name) == 0
  419. || std::strcmp("numpy.bool_", type_name) == 0;
  420. }
  421. };
  422. // Helper class for UTF-{8,16,32} C++ stl strings:
  423. template <typename StringType, bool IsView = false>
  424. struct string_caster {
  425. using CharT = typename StringType::value_type;
  426. // Simplify life by being able to assume standard char sizes (the standard only guarantees
  427. // minimums, but Python requires exact sizes)
  428. static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
  429. "Unsupported char size != 1");
  430. #if defined(PYBIND11_HAS_U8STRING)
  431. static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
  432. "Unsupported char8_t size != 1");
  433. #endif
  434. static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
  435. "Unsupported char16_t size != 2");
  436. static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
  437. "Unsupported char32_t size != 4");
  438. // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
  439. static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
  440. "Unsupported wchar_t size != 2/4");
  441. static constexpr size_t UTF_N = 8 * sizeof(CharT);
  442. bool load(handle src, bool) {
  443. handle load_src = src;
  444. if (!src) {
  445. return false;
  446. }
  447. if (!PyUnicode_Check(load_src.ptr())) {
  448. return load_raw(load_src);
  449. }
  450. // For UTF-8 we avoid the need for a temporary `bytes` object by using
  451. // `PyUnicode_AsUTF8AndSize`.
  452. if (UTF_N == 8) {
  453. Py_ssize_t size = -1;
  454. const auto *buffer
  455. = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
  456. if (!buffer) {
  457. PyErr_Clear();
  458. return false;
  459. }
  460. value = StringType(buffer, static_cast<size_t>(size));
  461. return true;
  462. }
  463. auto utfNbytes
  464. = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
  465. UTF_N == 8 ? "utf-8"
  466. : UTF_N == 16 ? "utf-16"
  467. : "utf-32",
  468. nullptr));
  469. if (!utfNbytes) {
  470. PyErr_Clear();
  471. return false;
  472. }
  473. const auto *buffer
  474. = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
  475. size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
  476. // Skip BOM for UTF-16/32
  477. if (UTF_N > 8) {
  478. buffer++;
  479. length--;
  480. }
  481. value = StringType(buffer, length);
  482. // If we're loading a string_view we need to keep the encoded Python object alive:
  483. if (IsView) {
  484. loader_life_support::add_patient(utfNbytes);
  485. }
  486. return true;
  487. }
  488. static handle
  489. cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
  490. const char *buffer = reinterpret_cast<const char *>(src.data());
  491. auto nbytes = ssize_t(src.size() * sizeof(CharT));
  492. handle s = decode_utfN(buffer, nbytes);
  493. if (!s) {
  494. throw error_already_set();
  495. }
  496. return s;
  497. }
  498. PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
  499. private:
  500. static handle decode_utfN(const char *buffer, ssize_t nbytes) {
  501. #if !defined(PYPY_VERSION)
  502. return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
  503. : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
  504. : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
  505. #else
  506. // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
  507. // well), so bypass the whole thing by just passing the encoding as a string value, which
  508. // works properly:
  509. return PyUnicode_Decode(buffer,
  510. nbytes,
  511. UTF_N == 8 ? "utf-8"
  512. : UTF_N == 16 ? "utf-16"
  513. : "utf-32",
  514. nullptr);
  515. #endif
  516. }
  517. // When loading into a std::string or char*, accept a bytes/bytearray object as-is (i.e.
  518. // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
  519. // which supports loading a unicode from a str, doesn't take this path.
  520. template <typename C = CharT>
  521. bool load_raw(enable_if_t<std::is_same<C, char>::value, handle> src) {
  522. if (PYBIND11_BYTES_CHECK(src.ptr())) {
  523. // We were passed raw bytes; accept it into a std::string or char*
  524. // without any encoding attempt.
  525. const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
  526. if (!bytes) {
  527. pybind11_fail("Unexpected PYBIND11_BYTES_AS_STRING() failure.");
  528. }
  529. value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
  530. return true;
  531. }
  532. if (PyByteArray_Check(src.ptr())) {
  533. // We were passed a bytearray; accept it into a std::string or char*
  534. // without any encoding attempt.
  535. const char *bytearray = PyByteArray_AsString(src.ptr());
  536. if (!bytearray) {
  537. pybind11_fail("Unexpected PyByteArray_AsString() failure.");
  538. }
  539. value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr()));
  540. return true;
  541. }
  542. return false;
  543. }
  544. template <typename C = CharT>
  545. bool load_raw(enable_if_t<!std::is_same<C, char>::value, handle>) {
  546. return false;
  547. }
  548. };
  549. template <typename CharT, class Traits, class Allocator>
  550. struct type_caster<std::basic_string<CharT, Traits, Allocator>,
  551. enable_if_t<is_std_char_type<CharT>::value>>
  552. : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
  553. #ifdef PYBIND11_HAS_STRING_VIEW
  554. template <typename CharT, class Traits>
  555. struct type_caster<std::basic_string_view<CharT, Traits>,
  556. enable_if_t<is_std_char_type<CharT>::value>>
  557. : string_caster<std::basic_string_view<CharT, Traits>, true> {};
  558. #endif
  559. // Type caster for C-style strings. We basically use a std::string type caster, but also add the
  560. // ability to use None as a nullptr char* (which the string caster doesn't allow).
  561. template <typename CharT>
  562. struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
  563. using StringType = std::basic_string<CharT>;
  564. using StringCaster = make_caster<StringType>;
  565. StringCaster str_caster;
  566. bool none = false;
  567. CharT one_char = 0;
  568. public:
  569. bool load(handle src, bool convert) {
  570. if (!src) {
  571. return false;
  572. }
  573. if (src.is_none()) {
  574. // Defer accepting None to other overloads (if we aren't in convert mode):
  575. if (!convert) {
  576. return false;
  577. }
  578. none = true;
  579. return true;
  580. }
  581. return str_caster.load(src, convert);
  582. }
  583. static handle cast(const CharT *src, return_value_policy policy, handle parent) {
  584. if (src == nullptr) {
  585. return pybind11::none().release();
  586. }
  587. return StringCaster::cast(StringType(src), policy, parent);
  588. }
  589. static handle cast(CharT src, return_value_policy policy, handle parent) {
  590. if (std::is_same<char, CharT>::value) {
  591. handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
  592. if (!s) {
  593. throw error_already_set();
  594. }
  595. return s;
  596. }
  597. return StringCaster::cast(StringType(1, src), policy, parent);
  598. }
  599. explicit operator CharT *() {
  600. return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
  601. }
  602. explicit operator CharT &() {
  603. if (none) {
  604. throw value_error("Cannot convert None to a character");
  605. }
  606. auto &value = static_cast<StringType &>(str_caster);
  607. size_t str_len = value.size();
  608. if (str_len == 0) {
  609. throw value_error("Cannot convert empty string to a character");
  610. }
  611. // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
  612. // is too high, and one for multiple unicode characters (caught later), so we need to
  613. // figure out how long the first encoded character is in bytes to distinguish between these
  614. // two errors. We also allow want to allow unicode characters U+0080 through U+00FF, as
  615. // those can fit into a single char value.
  616. if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
  617. auto v0 = static_cast<unsigned char>(value[0]);
  618. // low bits only: 0-127
  619. // 0b110xxxxx - start of 2-byte sequence
  620. // 0b1110xxxx - start of 3-byte sequence
  621. // 0b11110xxx - start of 4-byte sequence
  622. size_t char0_bytes = (v0 & 0x80) == 0 ? 1
  623. : (v0 & 0xE0) == 0xC0 ? 2
  624. : (v0 & 0xF0) == 0xE0 ? 3
  625. : 4;
  626. if (char0_bytes == str_len) {
  627. // If we have a 128-255 value, we can decode it into a single char:
  628. if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
  629. one_char = static_cast<CharT>(((v0 & 3) << 6)
  630. + (static_cast<unsigned char>(value[1]) & 0x3F));
  631. return one_char;
  632. }
  633. // Otherwise we have a single character, but it's > U+00FF
  634. throw value_error("Character code point not in range(0x100)");
  635. }
  636. }
  637. // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
  638. // surrogate pair with total length 2 instantly indicates a range error (but not a "your
  639. // string was too long" error).
  640. else if (StringCaster::UTF_N == 16 && str_len == 2) {
  641. one_char = static_cast<CharT>(value[0]);
  642. if (one_char >= 0xD800 && one_char < 0xE000) {
  643. throw value_error("Character code point not in range(0x10000)");
  644. }
  645. }
  646. if (str_len != 1) {
  647. throw value_error("Expected a character, but multi-character string found");
  648. }
  649. one_char = value[0];
  650. return one_char;
  651. }
  652. static constexpr auto name = const_name(PYBIND11_STRING_NAME);
  653. template <typename _T>
  654. using cast_op_type = pybind11::detail::cast_op_type<_T>;
  655. };
  656. // Base implementation for std::tuple and std::pair
  657. template <template <typename...> class Tuple, typename... Ts>
  658. class tuple_caster {
  659. using type = Tuple<Ts...>;
  660. static constexpr auto size = sizeof...(Ts);
  661. using indices = make_index_sequence<size>;
  662. public:
  663. bool load(handle src, bool convert) {
  664. if (!isinstance<sequence>(src)) {
  665. return false;
  666. }
  667. const auto seq = reinterpret_borrow<sequence>(src);
  668. if (seq.size() != size) {
  669. return false;
  670. }
  671. return load_impl(seq, convert, indices{});
  672. }
  673. template <typename T>
  674. static handle cast(T &&src, return_value_policy policy, handle parent) {
  675. return cast_impl(std::forward<T>(src), policy, parent, indices{});
  676. }
  677. // copied from the PYBIND11_TYPE_CASTER macro
  678. template <typename T>
  679. static handle cast(T *src, return_value_policy policy, handle parent) {
  680. if (!src) {
  681. return none().release();
  682. }
  683. if (policy == return_value_policy::take_ownership) {
  684. auto h = cast(std::move(*src), policy, parent);
  685. delete src;
  686. return h;
  687. }
  688. return cast(*src, policy, parent);
  689. }
  690. static constexpr auto name = const_name("tuple[")
  691. + ::pybind11::detail::concat(make_caster<Ts>::name...)
  692. + const_name("]");
  693. template <typename T>
  694. using cast_op_type = type;
  695. explicit operator type() & { return implicit_cast(indices{}); }
  696. explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
  697. protected:
  698. template <size_t... Is>
  699. type implicit_cast(index_sequence<Is...>) & {
  700. return type(cast_op<Ts>(std::get<Is>(subcasters))...);
  701. }
  702. template <size_t... Is>
  703. type implicit_cast(index_sequence<Is...>) && {
  704. return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
  705. }
  706. static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
  707. template <size_t... Is>
  708. bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
  709. #ifdef __cpp_fold_expressions
  710. if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
  711. return false;
  712. }
  713. #else
  714. for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
  715. if (!r) {
  716. return false;
  717. }
  718. }
  719. #endif
  720. return true;
  721. }
  722. /* Implementation: Convert a C++ tuple into a Python tuple */
  723. template <typename T, size_t... Is>
  724. static handle
  725. cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
  726. PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
  727. PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
  728. std::array<object, size> entries{{reinterpret_steal<object>(
  729. // NOLINTNEXTLINE(bugprone-use-after-move)
  730. make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
  731. for (const auto &entry : entries) {
  732. if (!entry) {
  733. return handle();
  734. }
  735. }
  736. tuple result(size);
  737. int counter = 0;
  738. for (auto &entry : entries) {
  739. PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
  740. }
  741. return result.release();
  742. }
  743. Tuple<make_caster<Ts>...> subcasters;
  744. };
  745. template <typename T1, typename T2>
  746. class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
  747. template <typename... Ts>
  748. class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
  749. template <>
  750. class type_caster<std::tuple<>> : public tuple_caster<std::tuple> {
  751. public:
  752. // PEP 484 specifies this syntax for an empty tuple
  753. static constexpr auto name = const_name("tuple[()]");
  754. };
  755. /// Helper class which abstracts away certain actions. Users can provide specializations for
  756. /// custom holders, but it's only necessary if the type has a non-standard interface.
  757. template <typename T>
  758. struct holder_helper {
  759. static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
  760. };
  761. // SMART_HOLDER_BAKEIN_FOLLOW_ON: Rewrite comment, with reference to shared_ptr specialization.
  762. /// Type caster for holder types like std::shared_ptr, etc.
  763. /// The SFINAE hook is provided to help work around the current lack of support
  764. /// for smart-pointer interoperability. Please consider it an implementation
  765. /// detail that may change in the future, as formal support for smart-pointer
  766. /// interoperability is added into pybind11.
  767. template <typename type, typename holder_type, typename SFINAE = void>
  768. struct copyable_holder_caster : public type_caster_base<type> {
  769. public:
  770. using base = type_caster_base<type>;
  771. static_assert(std::is_base_of<base, type_caster<type>>::value,
  772. "Holder classes are only supported for custom types");
  773. using base::base;
  774. using base::cast;
  775. using base::typeinfo;
  776. using base::value;
  777. bool load(handle src, bool convert) {
  778. return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
  779. }
  780. explicit operator type *() { return this->value; }
  781. // static_cast works around compiler error with MSVC 17 and CUDA 10.2
  782. // see issue #2180
  783. explicit operator type &() { return *(static_cast<type *>(this->value)); }
  784. explicit operator holder_type *() { return std::addressof(holder); }
  785. explicit operator holder_type &() { return holder; }
  786. static handle cast(const holder_type &src, return_value_policy, handle) {
  787. const auto *ptr = holder_helper<holder_type>::get(src);
  788. return type_caster_base<type>::cast_holder(ptr, &src);
  789. }
  790. protected:
  791. friend class type_caster_generic;
  792. void check_holder_compat() {
  793. // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.
  794. bool inst_has_unique_ptr_holder
  795. = (typeinfo->holder_enum_v == holder_enum_t::std_unique_ptr);
  796. if (inst_has_unique_ptr_holder) {
  797. throw cast_error("Unable to load a custom holder type from a default-holder instance");
  798. }
  799. }
  800. void load_value(value_and_holder &&v_h) {
  801. if (v_h.holder_constructed()) {
  802. value = v_h.value_ptr();
  803. holder = v_h.template holder<holder_type>();
  804. return;
  805. }
  806. throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
  807. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  808. "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
  809. "type information)");
  810. #else
  811. "of type '"
  812. + type_id<holder_type>() + "''");
  813. #endif
  814. }
  815. template <typename T = holder_type,
  816. detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
  817. bool try_implicit_casts(handle, bool) {
  818. return false;
  819. }
  820. template <typename T = holder_type,
  821. detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
  822. bool try_implicit_casts(handle src, bool convert) {
  823. for (auto &cast : typeinfo->implicit_casts) {
  824. copyable_holder_caster sub_caster(*cast.first);
  825. if (sub_caster.load(src, convert)) {
  826. value = cast.second(sub_caster.value);
  827. holder = holder_type(sub_caster.holder, (type *) value);
  828. return true;
  829. }
  830. }
  831. return false;
  832. }
  833. static bool try_direct_conversions(handle) { return false; }
  834. holder_type holder;
  835. };
  836. template <typename, typename SFINAE = void>
  837. struct copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled : std::true_type {};
  838. // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refactor copyable_holder_caster to reduce code duplication.
  839. template <typename type>
  840. struct copyable_holder_caster<
  841. type,
  842. std::shared_ptr<type>,
  843. enable_if_t<copyable_holder_caster_shared_ptr_with_smart_holder_support_enabled<type>::value>>
  844. : public type_caster_base<type> {
  845. public:
  846. using base = type_caster_base<type>;
  847. static_assert(std::is_base_of<base, type_caster<type>>::value,
  848. "Holder classes are only supported for custom types");
  849. using base::base;
  850. using base::cast;
  851. using base::typeinfo;
  852. using base::value;
  853. bool load(handle src, bool convert) {
  854. if (base::template load_impl<copyable_holder_caster<type, std::shared_ptr<type>>>(
  855. src, convert)) {
  856. sh_load_helper.maybe_set_python_instance_is_alias(src);
  857. return true;
  858. }
  859. return false;
  860. }
  861. explicit operator std::shared_ptr<type> *() {
  862. if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
  863. pybind11_fail("Passing `std::shared_ptr<T> *` from Python to C++ is not supported "
  864. "(inherently unsafe).");
  865. }
  866. return std::addressof(shared_ptr_storage);
  867. }
  868. explicit operator std::shared_ptr<type> &() {
  869. if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
  870. shared_ptr_storage = sh_load_helper.load_as_shared_ptr(typeinfo, value);
  871. }
  872. return shared_ptr_storage;
  873. }
  874. std::weak_ptr<type> potentially_slicing_weak_ptr() {
  875. if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
  876. // Reusing shared_ptr code to minimize code complexity.
  877. shared_ptr_storage
  878. = sh_load_helper.load_as_shared_ptr(typeinfo,
  879. value,
  880. /*responsible_parent=*/nullptr,
  881. /*force_potentially_slicing_shared_ptr=*/true);
  882. }
  883. return shared_ptr_storage;
  884. }
  885. static handle
  886. cast(const std::shared_ptr<type> &src, return_value_policy policy, handle parent) {
  887. const auto *ptr = src.get();
  888. auto st = type_caster_base<type>::src_and_type(ptr);
  889. if (st.second == nullptr) {
  890. return handle(); // no type info: error will be set already
  891. }
  892. if (st.second->holder_enum_v == detail::holder_enum_t::smart_holder) {
  893. return smart_holder_type_caster_support::smart_holder_from_shared_ptr(
  894. src, policy, parent, st);
  895. }
  896. return type_caster_base<type>::cast_holder(ptr, &src);
  897. }
  898. // This function will succeed even if the `responsible_parent` does not own the
  899. // wrapped C++ object directly.
  900. // It is the responsibility of the caller to ensure that the `responsible_parent`
  901. // has a `keep_alive` relationship with the owner of the wrapped C++ object, or
  902. // that the wrapped C++ object lives for the duration of the process.
  903. static std::shared_ptr<type> shared_ptr_with_responsible_parent(handle responsible_parent) {
  904. copyable_holder_caster loader;
  905. loader.load(responsible_parent, /*convert=*/false);
  906. assert(loader.typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder);
  907. return loader.sh_load_helper.load_as_shared_ptr(
  908. loader.typeinfo, loader.value, responsible_parent);
  909. }
  910. protected:
  911. friend class type_caster_generic;
  912. void check_holder_compat() {
  913. // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.
  914. bool inst_has_unique_ptr_holder
  915. = (typeinfo->holder_enum_v == holder_enum_t::std_unique_ptr);
  916. if (inst_has_unique_ptr_holder) {
  917. throw cast_error("Unable to load a custom holder type from a default-holder instance");
  918. }
  919. }
  920. void load_value(value_and_holder &&v_h) {
  921. if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
  922. sh_load_helper.loaded_v_h = v_h;
  923. sh_load_helper.was_populated = true;
  924. value = sh_load_helper.get_void_ptr_or_nullptr();
  925. return;
  926. }
  927. if (v_h.holder_constructed()) {
  928. value = v_h.value_ptr();
  929. shared_ptr_storage = v_h.template holder<std::shared_ptr<type>>();
  930. return;
  931. }
  932. throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
  933. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  934. "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
  935. "type information)");
  936. #else
  937. "of type '"
  938. + type_id<std::shared_ptr<type>>() + "''");
  939. #endif
  940. }
  941. template <typename T = std::shared_ptr<type>,
  942. detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
  943. bool try_implicit_casts(handle, bool) {
  944. return false;
  945. }
  946. template <typename T = std::shared_ptr<type>,
  947. detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
  948. bool try_implicit_casts(handle src, bool convert) {
  949. for (auto &cast : typeinfo->implicit_casts) {
  950. copyable_holder_caster sub_caster(*cast.first);
  951. if (sub_caster.load(src, convert)) {
  952. value = cast.second(sub_caster.value);
  953. if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
  954. sh_load_helper.loaded_v_h = sub_caster.sh_load_helper.loaded_v_h;
  955. } else {
  956. shared_ptr_storage
  957. = std::shared_ptr<type>(sub_caster.shared_ptr_storage, (type *) value);
  958. }
  959. return true;
  960. }
  961. }
  962. return false;
  963. }
  964. static bool try_direct_conversions(handle) { return false; }
  965. smart_holder_type_caster_support::load_helper<remove_cv_t<type>> sh_load_helper; // Const2Mutbl
  966. std::shared_ptr<type> shared_ptr_storage;
  967. };
  968. /// Specialize for the common std::shared_ptr, so users don't need to
  969. template <typename T>
  970. class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
  971. PYBIND11_NAMESPACE_END(detail)
  972. /// Return a std::shared_ptr with the SAME CONTROL BLOCK as the std::shared_ptr owned by the
  973. /// class_ holder. For class_-wrapped types with trampolines, the returned std::shared_ptr
  974. /// does NOT keep any derived Python objects alive (see issue #1333).
  975. ///
  976. /// For class_-wrapped types using std::shared_ptr as the holder, the following expressions
  977. /// produce equivalent results (see tests/test_potentially_slicing_weak_ptr.cpp,py):
  978. ///
  979. /// - obj.cast<std::shared_ptr<T>>()
  980. /// - py::potentially_slicing_weak_ptr<T>(obj).lock()
  981. ///
  982. /// For class_-wrapped types with trampolines and using py::smart_holder, obj.cast<>()
  983. /// produces a std::shared_ptr that keeps any derived Python objects alive for its own lifetime,
  984. /// but this is achieved by introducing a std::shared_ptr control block that is independent of
  985. /// the one owned by the py::smart_holder. This can lead to surprising std::weak_ptr behavior
  986. /// (see issue #5623). An easy solution is to use py::potentially_slicing_weak_ptr<>(obj),
  987. /// as exercised in tests/test_potentially_slicing_weak_ptr.cpp,py (look for
  988. /// "set_wp_potentially_slicing"). Note, however, that this reintroduces the inheritance
  989. /// slicing issue (see issue #1333). The ideal — but usually more involved — solution is to use
  990. /// a Python weakref to the derived Python object, instead of a C++ base-class std::weak_ptr.
  991. ///
  992. /// It is not possible (at least no known approach exists at the time of this writing) to
  993. /// simultaneously achieve both desirable properties:
  994. ///
  995. /// - the same std::shared_ptr control block as the class_ holder
  996. /// - automatic lifetime extension of any derived Python objects
  997. ///
  998. /// The reason is that this would introduce a reference cycle that cannot be garbage collected:
  999. ///
  1000. /// - the derived Python object owns the class_ holder
  1001. /// - the class_ holder owns the std::shared_ptr
  1002. /// - the std::shared_ptr would own a reference to the derived Python object,
  1003. /// completing the cycle
  1004. template <typename T>
  1005. std::weak_ptr<T> potentially_slicing_weak_ptr(handle obj) {
  1006. detail::make_caster<std::shared_ptr<T>> caster;
  1007. if (caster.load(obj, /*convert=*/true)) {
  1008. return caster.potentially_slicing_weak_ptr();
  1009. }
  1010. const char *obj_type_name = detail::obj_class_name(obj.ptr());
  1011. throw type_error("\"" + std::string(obj_type_name)
  1012. + "\" object is not convertible to std::weak_ptr<T> (with T = " + type_id<T>()
  1013. + ")");
  1014. }
  1015. PYBIND11_NAMESPACE_BEGIN(detail)
  1016. // SMART_HOLDER_BAKEIN_FOLLOW_ON: Rewrite comment, with reference to unique_ptr specialization.
  1017. /// Type caster for holder types like std::unique_ptr.
  1018. /// Please consider the SFINAE hook an implementation detail, as explained
  1019. /// in the comment for the copyable_holder_caster.
  1020. template <typename type, typename holder_type, typename SFINAE = void>
  1021. struct move_only_holder_caster {
  1022. static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
  1023. "Holder classes are only supported for custom types");
  1024. static handle cast(holder_type &&src, return_value_policy, handle) {
  1025. auto *ptr = holder_helper<holder_type>::get(src);
  1026. return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
  1027. }
  1028. static constexpr auto name = type_caster_base<type>::name;
  1029. };
  1030. template <typename, typename SFINAE = void>
  1031. struct move_only_holder_caster_unique_ptr_with_smart_holder_support_enabled : std::true_type {};
  1032. // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refactor move_only_holder_caster to reduce code duplication.
  1033. template <typename type, typename deleter>
  1034. struct move_only_holder_caster<
  1035. type,
  1036. std::unique_ptr<type, deleter>,
  1037. enable_if_t<move_only_holder_caster_unique_ptr_with_smart_holder_support_enabled<type>::value>>
  1038. : public type_caster_base<type> {
  1039. public:
  1040. using base = type_caster_base<type>;
  1041. static_assert(std::is_base_of<base, type_caster<type>>::value,
  1042. "Holder classes are only supported for custom types");
  1043. using base::base;
  1044. using base::cast;
  1045. using base::typeinfo;
  1046. using base::value;
  1047. static handle
  1048. cast(std::unique_ptr<type, deleter> &&src, return_value_policy policy, handle parent) {
  1049. auto *ptr = src.get();
  1050. auto st = type_caster_base<type>::src_and_type(ptr);
  1051. if (st.second == nullptr) {
  1052. return handle(); // no type info: error will be set already
  1053. }
  1054. if (st.second->holder_enum_v == detail::holder_enum_t::smart_holder) {
  1055. return smart_holder_type_caster_support::smart_holder_from_unique_ptr(
  1056. std::move(src), policy, parent, st);
  1057. }
  1058. return type_caster_generic::cast(st.first,
  1059. return_value_policy::take_ownership,
  1060. {},
  1061. st.second,
  1062. nullptr,
  1063. nullptr,
  1064. std::addressof(src));
  1065. }
  1066. static handle
  1067. cast(const std::unique_ptr<type, deleter> &src, return_value_policy policy, handle parent) {
  1068. if (!src) {
  1069. return none().release();
  1070. }
  1071. if (policy == return_value_policy::automatic) {
  1072. policy = return_value_policy::reference_internal;
  1073. }
  1074. if (policy != return_value_policy::reference_internal) {
  1075. throw cast_error("Invalid return_value_policy for const unique_ptr&");
  1076. }
  1077. return type_caster_base<type>::cast(src.get(), policy, parent);
  1078. }
  1079. bool load(handle src, bool convert) {
  1080. if (base::template load_impl<
  1081. move_only_holder_caster<type, std::unique_ptr<type, deleter>>>(src, convert)) {
  1082. sh_load_helper.maybe_set_python_instance_is_alias(src);
  1083. return true;
  1084. }
  1085. return false;
  1086. }
  1087. void load_value(value_and_holder &&v_h) {
  1088. if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
  1089. sh_load_helper.loaded_v_h = v_h;
  1090. sh_load_helper.loaded_v_h.type = typeinfo;
  1091. sh_load_helper.was_populated = true;
  1092. value = sh_load_helper.get_void_ptr_or_nullptr();
  1093. return;
  1094. }
  1095. pybind11_fail("Passing `std::unique_ptr<T>` from Python to C++ requires `py::class_<T, "
  1096. "py::smart_holder>` (with T = "
  1097. + clean_type_id(typeinfo->cpptype->name()) + ")");
  1098. }
  1099. template <typename T_>
  1100. using cast_op_type
  1101. = conditional_t<std::is_same<typename std::remove_volatile<T_>::type,
  1102. const std::unique_ptr<type, deleter> &>::value
  1103. || std::is_same<typename std::remove_volatile<T_>::type,
  1104. const std::unique_ptr<const type, deleter> &>::value,
  1105. const std::unique_ptr<type, deleter> &,
  1106. std::unique_ptr<type, deleter>>;
  1107. explicit operator std::unique_ptr<type, deleter>() {
  1108. if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
  1109. return sh_load_helper.template load_as_unique_ptr<deleter>(typeinfo, value);
  1110. }
  1111. pybind11_fail("Expected to be UNREACHABLE: " __FILE__ ":" PYBIND11_TOSTRING(__LINE__));
  1112. }
  1113. explicit operator const std::unique_ptr<type, deleter> &() {
  1114. if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
  1115. // Get shared_ptr to ensure that the Python object is not disowned elsewhere.
  1116. shared_ptr_storage = sh_load_helper.load_as_shared_ptr(typeinfo, value);
  1117. // Build a temporary unique_ptr that is meant to never expire.
  1118. unique_ptr_storage = std::shared_ptr<std::unique_ptr<type, deleter>>(
  1119. new std::unique_ptr<type, deleter>{
  1120. sh_load_helper.template load_as_const_unique_ptr<deleter>(
  1121. typeinfo, shared_ptr_storage.get())},
  1122. [](std::unique_ptr<type, deleter> *ptr) {
  1123. if (!ptr) {
  1124. pybind11_fail("FATAL: `const std::unique_ptr<T, D> &` was disowned "
  1125. "(EXPECT UNDEFINED BEHAVIOR).");
  1126. }
  1127. (void) ptr->release();
  1128. delete ptr;
  1129. });
  1130. return *unique_ptr_storage;
  1131. }
  1132. pybind11_fail("Expected to be UNREACHABLE: " __FILE__ ":" PYBIND11_TOSTRING(__LINE__));
  1133. }
  1134. bool try_implicit_casts(handle src, bool convert) {
  1135. for (auto &cast : typeinfo->implicit_casts) {
  1136. move_only_holder_caster sub_caster(*cast.first);
  1137. if (sub_caster.load(src, convert)) {
  1138. value = cast.second(sub_caster.value);
  1139. if (typeinfo->holder_enum_v == detail::holder_enum_t::smart_holder) {
  1140. sh_load_helper.loaded_v_h = sub_caster.sh_load_helper.loaded_v_h;
  1141. } else {
  1142. pybind11_fail("Expected to be UNREACHABLE: " __FILE__
  1143. ":" PYBIND11_TOSTRING(__LINE__));
  1144. }
  1145. return true;
  1146. }
  1147. }
  1148. return false;
  1149. }
  1150. static bool try_direct_conversions(handle) { return false; }
  1151. smart_holder_type_caster_support::load_helper<remove_cv_t<type>> sh_load_helper; // Const2Mutbl
  1152. std::shared_ptr<type> shared_ptr_storage; // Serves as a pseudo lock.
  1153. std::shared_ptr<std::unique_ptr<type, deleter>> unique_ptr_storage;
  1154. };
  1155. template <typename type, typename deleter>
  1156. class type_caster<std::unique_ptr<type, deleter>>
  1157. : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
  1158. template <typename type, typename holder_type>
  1159. using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
  1160. copyable_holder_caster<type, holder_type>,
  1161. move_only_holder_caster<type, holder_type>>;
  1162. template <bool Value = false>
  1163. struct always_construct_holder_value {
  1164. static constexpr bool value = Value;
  1165. };
  1166. template <typename T, bool Value = false>
  1167. struct always_construct_holder : always_construct_holder_value<Value> {};
  1168. /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
  1169. #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
  1170. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
  1171. namespace detail { \
  1172. template <typename type> \
  1173. struct always_construct_holder<holder_type> : always_construct_holder_value<__VA_ARGS__> {}; \
  1174. template <typename type> \
  1175. class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
  1176. : public type_caster_holder<type, holder_type> {}; \
  1177. } \
  1178. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
  1179. // PYBIND11_DECLARE_HOLDER_TYPE holder types:
  1180. template <typename base, typename holder>
  1181. struct is_holder_type
  1182. : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
  1183. // Specializations for always-supported holders:
  1184. template <typename base, typename deleter>
  1185. struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
  1186. template <typename base>
  1187. struct is_holder_type<base, smart_holder> : std::true_type {};
  1188. #ifdef PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION // See PR #4888
  1189. // This leads to compilation errors if a specialization is missing.
  1190. template <typename T>
  1191. struct handle_type_name;
  1192. #else
  1193. template <typename T>
  1194. struct handle_type_name {
  1195. static constexpr auto name = const_name<T>();
  1196. };
  1197. #endif
  1198. template <>
  1199. struct handle_type_name<object> {
  1200. static constexpr auto name = const_name("object");
  1201. };
  1202. template <>
  1203. struct handle_type_name<list> {
  1204. static constexpr auto name = const_name("list");
  1205. };
  1206. template <>
  1207. struct handle_type_name<dict> {
  1208. static constexpr auto name = const_name("dict");
  1209. };
  1210. template <>
  1211. struct handle_type_name<anyset> {
  1212. static constexpr auto name = const_name("set | frozenset");
  1213. };
  1214. template <>
  1215. struct handle_type_name<set> {
  1216. static constexpr auto name = const_name("set");
  1217. };
  1218. template <>
  1219. struct handle_type_name<frozenset> {
  1220. static constexpr auto name = const_name("frozenset");
  1221. };
  1222. template <>
  1223. struct handle_type_name<str> {
  1224. static constexpr auto name = const_name("str");
  1225. };
  1226. template <>
  1227. struct handle_type_name<tuple> {
  1228. static constexpr auto name = const_name("tuple");
  1229. };
  1230. template <>
  1231. struct handle_type_name<bool_> {
  1232. static constexpr auto name = const_name("bool");
  1233. };
  1234. template <>
  1235. struct handle_type_name<bytes> {
  1236. static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
  1237. };
  1238. template <>
  1239. struct handle_type_name<buffer> {
  1240. static constexpr auto name = const_name(PYBIND11_BUFFER_TYPE_HINT);
  1241. };
  1242. template <>
  1243. struct handle_type_name<int_> {
  1244. static constexpr auto name = io_name("typing.SupportsInt", "int");
  1245. };
  1246. template <>
  1247. struct handle_type_name<iterable> {
  1248. static constexpr auto name = const_name("collections.abc.Iterable");
  1249. };
  1250. template <>
  1251. struct handle_type_name<iterator> {
  1252. static constexpr auto name = const_name("collections.abc.Iterator");
  1253. };
  1254. template <>
  1255. struct handle_type_name<float_> {
  1256. static constexpr auto name = io_name("typing.SupportsFloat", "float");
  1257. };
  1258. template <>
  1259. struct handle_type_name<function> {
  1260. static constexpr auto name = const_name("collections.abc.Callable");
  1261. };
  1262. template <>
  1263. struct handle_type_name<handle> {
  1264. static constexpr auto name = handle_type_name<object>::name;
  1265. };
  1266. template <>
  1267. struct handle_type_name<none> {
  1268. static constexpr auto name = const_name("None");
  1269. };
  1270. template <>
  1271. struct handle_type_name<sequence> {
  1272. static constexpr auto name = const_name("collections.abc.Sequence");
  1273. };
  1274. template <>
  1275. struct handle_type_name<bytearray> {
  1276. static constexpr auto name = const_name("bytearray");
  1277. };
  1278. template <>
  1279. struct handle_type_name<memoryview> {
  1280. static constexpr auto name = const_name("memoryview");
  1281. };
  1282. template <>
  1283. struct handle_type_name<slice> {
  1284. static constexpr auto name = const_name("slice");
  1285. };
  1286. template <>
  1287. struct handle_type_name<type> {
  1288. static constexpr auto name = const_name("type");
  1289. };
  1290. template <>
  1291. struct handle_type_name<capsule> {
  1292. static constexpr auto name = const_name(PYBIND11_CAPSULE_TYPE_TYPE_HINT);
  1293. };
  1294. template <>
  1295. struct handle_type_name<ellipsis> {
  1296. static constexpr auto name = const_name("ellipsis");
  1297. };
  1298. template <>
  1299. struct handle_type_name<weakref> {
  1300. static constexpr auto name = const_name("weakref.ReferenceType");
  1301. };
  1302. template <>
  1303. struct handle_type_name<args> {
  1304. static constexpr auto name = const_name("*args");
  1305. };
  1306. template <typename T>
  1307. struct handle_type_name<Args<T>> {
  1308. static constexpr auto name = const_name("*args: ") + make_caster<T>::name;
  1309. };
  1310. template <>
  1311. struct handle_type_name<kwargs> {
  1312. static constexpr auto name = const_name("**kwargs");
  1313. };
  1314. template <typename T>
  1315. struct handle_type_name<KWArgs<T>> {
  1316. static constexpr auto name = const_name("**kwargs: ") + make_caster<T>::name;
  1317. };
  1318. template <>
  1319. struct handle_type_name<obj_attr_accessor> {
  1320. static constexpr auto name = const_name<obj_attr_accessor>();
  1321. };
  1322. template <>
  1323. struct handle_type_name<str_attr_accessor> {
  1324. static constexpr auto name = const_name<str_attr_accessor>();
  1325. };
  1326. template <>
  1327. struct handle_type_name<item_accessor> {
  1328. static constexpr auto name = const_name<item_accessor>();
  1329. };
  1330. template <>
  1331. struct handle_type_name<sequence_accessor> {
  1332. static constexpr auto name = const_name<sequence_accessor>();
  1333. };
  1334. template <>
  1335. struct handle_type_name<list_accessor> {
  1336. static constexpr auto name = const_name<list_accessor>();
  1337. };
  1338. template <>
  1339. struct handle_type_name<tuple_accessor> {
  1340. static constexpr auto name = const_name<tuple_accessor>();
  1341. };
  1342. template <typename type>
  1343. struct pyobject_caster {
  1344. template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
  1345. pyobject_caster() : value() {}
  1346. // `type` may not be default constructible (e.g. frozenset, anyset). Initializing `value`
  1347. // to a nil handle is safe since it will only be accessed if `load` succeeds.
  1348. template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
  1349. pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
  1350. template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
  1351. bool load(handle src, bool /* convert */) {
  1352. value = src;
  1353. return static_cast<bool>(value);
  1354. }
  1355. template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
  1356. bool load(handle src, bool /* convert */) {
  1357. if (!isinstance<type>(src)) {
  1358. return false;
  1359. }
  1360. value = reinterpret_borrow<type>(src);
  1361. return true;
  1362. }
  1363. static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
  1364. return src.inc_ref();
  1365. }
  1366. PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
  1367. };
  1368. template <typename T>
  1369. class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
  1370. // Our conditions for enabling moving are quite restrictive:
  1371. // At compile time:
  1372. // - T needs to be a non-const, non-pointer, non-reference type
  1373. // - type_caster<T>::operator T&() must exist
  1374. // - the type must be move constructible (obviously)
  1375. // At run-time:
  1376. // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
  1377. // must have ref_count() == 1)h
  1378. // If any of the above are not satisfied, we fall back to copying.
  1379. template <typename T>
  1380. using move_is_plain_type
  1381. = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
  1382. template <typename T, typename SFINAE = void>
  1383. struct move_always : std::false_type {};
  1384. template <typename T>
  1385. struct move_always<
  1386. T,
  1387. enable_if_t<
  1388. all_of<move_is_plain_type<T>,
  1389. negation<is_copy_constructible<T>>,
  1390. is_move_constructible<T>,
  1391. std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
  1392. : std::true_type {};
  1393. template <typename T, typename SFINAE = void>
  1394. struct move_if_unreferenced : std::false_type {};
  1395. template <typename T>
  1396. struct move_if_unreferenced<
  1397. T,
  1398. enable_if_t<
  1399. all_of<move_is_plain_type<T>,
  1400. negation<move_always<T>>,
  1401. is_move_constructible<T>,
  1402. std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
  1403. : std::true_type {};
  1404. template <typename T>
  1405. using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
  1406. // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
  1407. // reference or pointer to a local variable of the type_caster. Basically, only
  1408. // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
  1409. // everything else returns a reference/pointer to a local variable.
  1410. template <typename type>
  1411. using cast_is_temporary_value_reference
  1412. = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
  1413. && !std::is_base_of<type_caster_generic, make_caster<type>>::value
  1414. && !std::is_same<intrinsic_t<type>, void>::value>;
  1415. // When a value returned from a C++ function is being cast back to Python, we almost always want to
  1416. // force `policy = move`, regardless of the return value policy the function/method was declared
  1417. // with.
  1418. template <typename Return, typename SFINAE = void>
  1419. struct return_value_policy_override {
  1420. static return_value_policy policy(return_value_policy p) { return p; }
  1421. };
  1422. template <typename Return>
  1423. struct return_value_policy_override<
  1424. Return,
  1425. detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
  1426. static return_value_policy policy(return_value_policy p) {
  1427. return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
  1428. ? return_value_policy::move
  1429. : p;
  1430. }
  1431. };
  1432. // Basic python -> C++ casting; throws if casting fails
  1433. template <typename T, typename SFINAE>
  1434. type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
  1435. static_assert(!detail::is_pyobject<T>::value,
  1436. "Internal error: type_caster should only be used for C++ types");
  1437. if (!conv.load(handle, true)) {
  1438. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1439. throw cast_error(
  1440. "Unable to cast Python instance of type "
  1441. + str(type::handle_of(handle)).cast<std::string>()
  1442. + " to C++ type '?' (#define "
  1443. "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1444. #else
  1445. throw cast_error("Unable to cast Python instance of type "
  1446. + str(type::handle_of(handle)).cast<std::string>() + " to C++ type '"
  1447. + type_id<T>() + "'");
  1448. #endif
  1449. }
  1450. return conv;
  1451. }
  1452. // Wrapper around the above that also constructs and returns a type_caster
  1453. template <typename T>
  1454. make_caster<T> load_type(const handle &handle) {
  1455. make_caster<T> conv;
  1456. load_type(conv, handle);
  1457. return conv;
  1458. }
  1459. PYBIND11_NAMESPACE_END(detail)
  1460. // pytype -> C++ type
  1461. template <typename T,
  1462. detail::enable_if_t<!detail::is_pyobject<T>::value
  1463. && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
  1464. int>
  1465. = 0>
  1466. T cast(const handle &handle) {
  1467. using namespace detail;
  1468. constexpr bool is_enum_cast = type_uses_type_caster_enum_type<intrinsic_t<T>>::value;
  1469. static_assert(!cast_is_temporary_value_reference<T>::value || is_enum_cast,
  1470. "Unable to cast type to reference: value is local to type caster");
  1471. #ifndef NDEBUG
  1472. if (is_enum_cast && cast_is_temporary_value_reference<T>::value) {
  1473. if (detail::global_internals_native_enum_type_map_contains(
  1474. std::type_index(typeid(intrinsic_t<T>)))) {
  1475. pybind11_fail("Unable to cast native enum type to reference");
  1476. }
  1477. }
  1478. #endif
  1479. return cast_op<T>(load_type<T>(handle));
  1480. }
  1481. // pytype -> pytype (calls converting constructor)
  1482. template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
  1483. T cast(const handle &handle) {
  1484. return T(reinterpret_borrow<object>(handle));
  1485. }
  1486. // Note that `cast<PyObject *>(obj)` increments the reference count of `obj`.
  1487. // This is necessary for the case that `obj` is a temporary, and could
  1488. // not possibly be different, given
  1489. // 1. the established convention that the passed `handle` is borrowed, and
  1490. // 2. we don't want to force all generic code using `cast<T>()` to special-case
  1491. // handling of `T` = `PyObject *` (to increment the reference count there).
  1492. // It is the responsibility of the caller to ensure that the reference count
  1493. // is decremented.
  1494. template <typename T,
  1495. typename Handle,
  1496. detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
  1497. && detail::is_same_ignoring_cvref<Handle, handle>::value,
  1498. int>
  1499. = 0>
  1500. T cast(Handle &&handle) {
  1501. return handle.inc_ref().ptr();
  1502. }
  1503. // To optimize way an inc_ref/dec_ref cycle:
  1504. template <typename T,
  1505. typename Object,
  1506. detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
  1507. && detail::is_same_ignoring_cvref<Object, object>::value,
  1508. int>
  1509. = 0>
  1510. T cast(Object &&obj) {
  1511. return obj.release().ptr();
  1512. }
  1513. // C++ type -> py::object
  1514. template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
  1515. object cast(T &&value,
  1516. return_value_policy policy = return_value_policy::automatic_reference,
  1517. handle parent = handle()) {
  1518. using no_ref_T = typename std::remove_reference<T>::type;
  1519. if (policy == return_value_policy::automatic) {
  1520. policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
  1521. : std::is_lvalue_reference<T>::value ? return_value_policy::copy
  1522. : return_value_policy::move;
  1523. } else if (policy == return_value_policy::automatic_reference) {
  1524. policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
  1525. : std::is_lvalue_reference<T>::value ? return_value_policy::copy
  1526. : return_value_policy::move;
  1527. }
  1528. return reinterpret_steal<object>(
  1529. detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
  1530. }
  1531. template <typename T>
  1532. T handle::cast() const {
  1533. return pybind11::cast<T>(*this);
  1534. }
  1535. template <>
  1536. inline void handle::cast() const {
  1537. return;
  1538. }
  1539. template <typename T>
  1540. detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
  1541. if (obj.ref_count() > 1) {
  1542. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1543. throw cast_error(
  1544. "Unable to cast Python " + str(type::handle_of(obj)).cast<std::string>()
  1545. + " instance to C++ rvalue: instance has multiple references"
  1546. " (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1547. #else
  1548. throw cast_error("Unable to move from Python "
  1549. + str(type::handle_of(obj)).cast<std::string>() + " instance to C++ "
  1550. + type_id<T>() + " instance: instance has multiple references");
  1551. #endif
  1552. }
  1553. // Move into a temporary and return that, because the reference may be a local value of `conv`
  1554. T ret = std::move(detail::load_type<T>(obj).operator T &());
  1555. return ret;
  1556. }
  1557. // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
  1558. // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
  1559. // object has multiple references, but trying to copy will fail to compile.
  1560. // - If both movable and copyable, check ref count: if 1, move; otherwise copy
  1561. // - Otherwise (not movable), copy.
  1562. template <typename T>
  1563. detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>
  1564. cast(object &&object) {
  1565. return move<T>(std::move(object));
  1566. }
  1567. template <typename T>
  1568. detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>
  1569. cast(object &&object) {
  1570. if (object.ref_count() > 1) {
  1571. return cast<T>(object);
  1572. }
  1573. return move<T>(std::move(object));
  1574. }
  1575. template <typename T>
  1576. detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>
  1577. cast(object &&object) {
  1578. return cast<T>(object);
  1579. }
  1580. // pytype rvalue -> pytype (calls converting constructor)
  1581. template <typename T>
  1582. detail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {
  1583. return T(std::move(object));
  1584. }
  1585. template <typename T>
  1586. T object::cast() const & {
  1587. return pybind11::cast<T>(*this);
  1588. }
  1589. template <typename T>
  1590. T object::cast() && {
  1591. return pybind11::cast<T>(std::move(*this));
  1592. }
  1593. template <>
  1594. inline void object::cast() const & {
  1595. return;
  1596. }
  1597. template <>
  1598. inline void object::cast() && {
  1599. return;
  1600. }
  1601. PYBIND11_NAMESPACE_BEGIN(detail)
  1602. // forward declaration (definition in pybind11.h)
  1603. template <typename T>
  1604. std::string generate_type_signature();
  1605. // Declared in pytypes.h:
  1606. template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
  1607. object object_or_cast(T &&o) {
  1608. return pybind11::cast(std::forward<T>(o));
  1609. }
  1610. // Declared in pytypes.h:
  1611. // Implemented here so that make_caster<T> can be used.
  1612. template <typename D>
  1613. template <typename T>
  1614. str_attr_accessor object_api<D>::attr_with_type_hint(const char *key) const {
  1615. #if !defined(__cpp_inline_variables)
  1616. static_assert(always_false<T>::value,
  1617. "C++17 feature __cpp_inline_variables not available: "
  1618. "https://en.cppreference.com/w/cpp/language/static#Static_data_members");
  1619. #endif
  1620. object ann = annotations();
  1621. if (ann.contains(key)) {
  1622. throw std::runtime_error("__annotations__[\"" + std::string(key) + "\"] was set already.");
  1623. }
  1624. ann[key] = generate_type_signature<T>();
  1625. return {derived(), key};
  1626. }
  1627. template <typename D>
  1628. template <typename T>
  1629. obj_attr_accessor object_api<D>::attr_with_type_hint(handle key) const {
  1630. (void) attr_with_type_hint<T>(key.cast<std::string>().c_str());
  1631. return {derived(), reinterpret_borrow<object>(key)};
  1632. }
  1633. // Placeholder type for the unneeded (and dead code) static variable in the
  1634. // PYBIND11_OVERRIDE_OVERRIDE macro
  1635. struct override_unused {};
  1636. template <typename ret_type>
  1637. using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
  1638. make_caster<ret_type>,
  1639. override_unused>;
  1640. // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
  1641. // store the result in the given variable. For other types, this is a no-op.
  1642. template <typename T>
  1643. enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
  1644. make_caster<T> &caster) {
  1645. return cast_op<T>(load_type(caster, o));
  1646. }
  1647. template <typename T>
  1648. enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
  1649. override_unused &) {
  1650. pybind11_fail("Internal error: cast_ref fallback invoked");
  1651. }
  1652. // Trampoline use: Having a pybind11::cast with an invalid reference type is going to
  1653. // static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
  1654. // that only does anything in cases where pybind11::cast is valid.
  1655. template <typename T>
  1656. enable_if_t<cast_is_temporary_value_reference<T>::value
  1657. && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
  1658. T>
  1659. cast_safe(object &&) {
  1660. pybind11_fail("Internal error: cast_safe fallback invoked");
  1661. }
  1662. template <typename T>
  1663. enable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}
  1664. template <typename T>
  1665. enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value, PyObject *>
  1666. cast_safe(object &&o) {
  1667. return o.release().ptr();
  1668. }
  1669. template <typename T>
  1670. enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>,
  1671. detail::is_same_ignoring_cvref<T, PyObject *>,
  1672. std::is_void<T>>::value,
  1673. T>
  1674. cast_safe(object &&o) {
  1675. return pybind11::cast<T>(std::move(o));
  1676. }
  1677. PYBIND11_NAMESPACE_END(detail)
  1678. // The overloads could coexist, i.e. the #if is not strictly speaking needed,
  1679. // but it is an easy minor optimization.
  1680. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1681. inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name) {
  1682. return cast_error("Unable to convert call argument '" + name
  1683. + "' to Python object (#define "
  1684. "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  1685. }
  1686. #else
  1687. inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
  1688. const std::string &type) {
  1689. return cast_error("Unable to convert call argument '" + name + "' of type '" + type
  1690. + "' to Python object");
  1691. }
  1692. #endif
  1693. template <return_value_policy policy = return_value_policy::automatic_reference>
  1694. tuple make_tuple() {
  1695. return tuple(0);
  1696. }
  1697. template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
  1698. tuple make_tuple(Args &&...args_) {
  1699. constexpr size_t size = sizeof...(Args);
  1700. std::array<object, size> args{{reinterpret_steal<object>(
  1701. detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
  1702. for (size_t i = 0; i < args.size(); i++) {
  1703. if (!args[i]) {
  1704. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1705. throw cast_error_unable_to_convert_call_arg(std::to_string(i));
  1706. #else
  1707. std::array<std::string, size> argtypes{{type_id<Args>()...}};
  1708. throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
  1709. #endif
  1710. }
  1711. }
  1712. tuple result(size);
  1713. int counter = 0;
  1714. for (auto &arg_value : args) {
  1715. PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
  1716. }
  1717. return result;
  1718. }
  1719. /// \ingroup annotations
  1720. /// Annotation for arguments
  1721. struct arg {
  1722. /// Constructs an argument with the name of the argument; if null or omitted, this is a
  1723. /// positional argument.
  1724. constexpr explicit arg(const char *name = nullptr)
  1725. : name(name), flag_noconvert(false), flag_none(true) {}
  1726. /// Assign a value to this argument
  1727. template <typename T>
  1728. arg_v operator=(T &&value) const;
  1729. /// Indicate that the type should not be converted in the type caster
  1730. arg &noconvert(bool flag = true) {
  1731. flag_noconvert = flag;
  1732. return *this;
  1733. }
  1734. /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
  1735. arg &none(bool flag = true) {
  1736. flag_none = flag;
  1737. return *this;
  1738. }
  1739. const char *name; ///< If non-null, this is a named kwargs argument
  1740. bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type
  1741. ///< caster!)
  1742. bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
  1743. };
  1744. /// \ingroup annotations
  1745. /// Annotation for arguments with values
  1746. struct arg_v : arg {
  1747. private:
  1748. template <typename T>
  1749. arg_v(arg &&base, T &&x, const char *descr = nullptr)
  1750. : arg(base), value(reinterpret_steal<object>(detail::make_caster<T>::cast(
  1751. std::forward<T>(x), return_value_policy::automatic, {}))),
  1752. descr(descr)
  1753. #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1754. ,
  1755. type(type_id<T>())
  1756. #endif
  1757. {
  1758. // Workaround! See:
  1759. // https://github.com/pybind/pybind11/issues/2336
  1760. // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
  1761. if (PyErr_Occurred()) {
  1762. PyErr_Clear();
  1763. }
  1764. }
  1765. public:
  1766. /// Direct construction with name, default, and description
  1767. template <typename T>
  1768. arg_v(const char *name, T &&x, const char *descr = nullptr)
  1769. : arg_v(arg(name), std::forward<T>(x), descr) {}
  1770. /// Called internally when invoking `py::arg("a") = value`
  1771. template <typename T>
  1772. arg_v(const arg &base, T &&x, const char *descr = nullptr)
  1773. : arg_v(arg(base), std::forward<T>(x), descr) {}
  1774. /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
  1775. arg_v &noconvert(bool flag = true) {
  1776. arg::noconvert(flag);
  1777. return *this;
  1778. }
  1779. /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
  1780. arg_v &none(bool flag = true) {
  1781. arg::none(flag);
  1782. return *this;
  1783. }
  1784. /// The default value
  1785. object value;
  1786. /// The (optional) description of the default value
  1787. const char *descr;
  1788. #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1789. /// The C++ type name of the default value (only available when compiled in debug mode)
  1790. std::string type;
  1791. #endif
  1792. };
  1793. /// \ingroup annotations
  1794. /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of
  1795. /// an unnamed '*' argument
  1796. struct kw_only {};
  1797. /// \ingroup annotations
  1798. /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of
  1799. /// an unnamed '/' argument
  1800. struct pos_only {};
  1801. template <typename T>
  1802. arg_v arg::operator=(T &&value) const {
  1803. return {*this, std::forward<T>(value)};
  1804. }
  1805. /// Alias for backward compatibility -- to be removed in version 2.0
  1806. template <typename /*unused*/>
  1807. using arg_t = arg_v;
  1808. inline namespace literals {
  1809. /** \rst
  1810. String literal version of `arg`
  1811. \endrst */
  1812. constexpr arg
  1813. #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
  1814. operator"" _a // gcc 4.8.5 insists on having a space (hard error).
  1815. #else
  1816. operator""_a // clang 17 generates a deprecation warning if there is a space.
  1817. #endif
  1818. (const char *name, size_t) {
  1819. return arg(name);
  1820. }
  1821. } // namespace literals
  1822. PYBIND11_NAMESPACE_BEGIN(detail)
  1823. template <typename T>
  1824. using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
  1825. template <typename T>
  1826. using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
  1827. // forward declaration (definition in attr.h)
  1828. struct function_record;
  1829. /// Internal data associated with a single function call
  1830. struct function_call {
  1831. function_call(const function_record &f, handle p); // Implementation in attr.h
  1832. /// The function data:
  1833. const function_record &func;
  1834. /// Arguments passed to the function:
  1835. std::vector<handle> args;
  1836. /// The `convert` value the arguments should be loaded with
  1837. std::vector<bool> args_convert;
  1838. /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
  1839. /// present, are also in `args` but without a reference).
  1840. object args_ref, kwargs_ref;
  1841. /// The parent, if any
  1842. handle parent;
  1843. /// If this is a call to an initializer, this argument contains `self`
  1844. handle init_self;
  1845. };
  1846. // See PR #5396 for the discussion that led to this
  1847. template <typename Base, typename Derived, typename = void>
  1848. struct is_same_or_base_of : std::is_same<Base, Derived> {};
  1849. // Only evaluate is_base_of if Derived is complete.
  1850. // is_base_of raises a compiler error if Derived is incomplete.
  1851. template <typename Base, typename Derived>
  1852. struct is_same_or_base_of<Base, Derived, decltype(void(sizeof(Derived)))>
  1853. : any_of<std::is_same<Base, Derived>, std::is_base_of<Base, Derived>> {};
  1854. /// Helper class which loads arguments for C++ functions called from Python
  1855. template <typename... Args>
  1856. class argument_loader {
  1857. using indices = make_index_sequence<sizeof...(Args)>;
  1858. template <typename Arg>
  1859. using argument_is_args = is_same_or_base_of<args, intrinsic_t<Arg>>;
  1860. template <typename Arg>
  1861. using argument_is_kwargs = is_same_or_base_of<kwargs, intrinsic_t<Arg>>;
  1862. // Get kwargs argument position, or -1 if not present:
  1863. static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
  1864. static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
  1865. "py::kwargs is only permitted as the last argument of a function");
  1866. public:
  1867. static constexpr bool has_kwargs = kwargs_pos != -1;
  1868. // py::args argument position; -1 if not present.
  1869. static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
  1870. static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
  1871. "py::args cannot be specified more than once");
  1872. static constexpr auto arg_names
  1873. = ::pybind11::detail::concat(type_descr(make_caster<Args>::name)...);
  1874. bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
  1875. template <typename Return, typename Guard, typename Func>
  1876. // NOLINTNEXTLINE(readability-const-return-type)
  1877. enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
  1878. return std::move(*this).template call_impl<remove_cv_t<Return>>(
  1879. std::forward<Func>(f), indices{}, Guard{});
  1880. }
  1881. template <typename Return, typename Guard, typename Func>
  1882. enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
  1883. std::move(*this).template call_impl<remove_cv_t<Return>>(
  1884. std::forward<Func>(f), indices{}, Guard{});
  1885. return void_type();
  1886. }
  1887. private:
  1888. static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
  1889. template <size_t... Is>
  1890. bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
  1891. #ifdef __cpp_fold_expressions
  1892. if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
  1893. return false;
  1894. }
  1895. #else
  1896. for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
  1897. if (!r) {
  1898. return false;
  1899. }
  1900. }
  1901. #endif
  1902. return true;
  1903. }
  1904. template <typename Return, typename Func, size_t... Is, typename Guard>
  1905. Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
  1906. return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
  1907. }
  1908. std::tuple<make_caster<Args>...> argcasters;
  1909. };
  1910. /// Helper class which collects only positional arguments for a Python function call.
  1911. /// A fancier version below can collect any argument, but this one is optimal for simple calls.
  1912. template <return_value_policy policy>
  1913. class simple_collector {
  1914. public:
  1915. template <typename... Ts>
  1916. explicit simple_collector(Ts &&...values)
  1917. : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) {}
  1918. const tuple &args() const & { return m_args; }
  1919. dict kwargs() const { return {}; }
  1920. tuple args() && { return std::move(m_args); }
  1921. /// Call a Python function and pass the collected arguments
  1922. object call(PyObject *ptr) const {
  1923. PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
  1924. if (!result) {
  1925. throw error_already_set();
  1926. }
  1927. return reinterpret_steal<object>(result);
  1928. }
  1929. private:
  1930. tuple m_args;
  1931. };
  1932. /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
  1933. template <return_value_policy policy>
  1934. class unpacking_collector {
  1935. public:
  1936. template <typename... Ts>
  1937. explicit unpacking_collector(Ts &&...values) {
  1938. // Tuples aren't (easily) resizable so a list is needed for collection,
  1939. // but the actual function call strictly requires a tuple.
  1940. auto args_list = list();
  1941. using expander = int[];
  1942. (void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...};
  1943. m_args = std::move(args_list);
  1944. }
  1945. const tuple &args() const & { return m_args; }
  1946. const dict &kwargs() const & { return m_kwargs; }
  1947. tuple args() && { return std::move(m_args); }
  1948. dict kwargs() && { return std::move(m_kwargs); }
  1949. /// Call a Python function and pass the collected arguments
  1950. object call(PyObject *ptr) const {
  1951. PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
  1952. if (!result) {
  1953. throw error_already_set();
  1954. }
  1955. return reinterpret_steal<object>(result);
  1956. }
  1957. private:
  1958. template <typename T>
  1959. void process(list &args_list, T &&x) {
  1960. auto o = reinterpret_steal<object>(
  1961. detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
  1962. if (!o) {
  1963. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1964. throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()));
  1965. #else
  1966. throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()),
  1967. type_id<T>());
  1968. #endif
  1969. }
  1970. args_list.append(std::move(o));
  1971. }
  1972. void process(list &args_list, detail::args_proxy ap) {
  1973. for (auto a : ap) {
  1974. args_list.append(a);
  1975. }
  1976. }
  1977. void process(list & /*args_list*/, arg_v a) {
  1978. if (!a.name) {
  1979. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1980. nameless_argument_error();
  1981. #else
  1982. nameless_argument_error(a.type);
  1983. #endif
  1984. }
  1985. if (m_kwargs.contains(a.name)) {
  1986. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1987. multiple_values_error();
  1988. #else
  1989. multiple_values_error(a.name);
  1990. #endif
  1991. }
  1992. if (!a.value) {
  1993. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  1994. throw cast_error_unable_to_convert_call_arg(a.name);
  1995. #else
  1996. throw cast_error_unable_to_convert_call_arg(a.name, a.type);
  1997. #endif
  1998. }
  1999. m_kwargs[a.name] = std::move(a.value);
  2000. }
  2001. void process(list & /*args_list*/, detail::kwargs_proxy kp) {
  2002. if (!kp) {
  2003. return;
  2004. }
  2005. for (auto k : reinterpret_borrow<dict>(kp)) {
  2006. if (m_kwargs.contains(k.first)) {
  2007. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  2008. multiple_values_error();
  2009. #else
  2010. multiple_values_error(str(k.first));
  2011. #endif
  2012. }
  2013. m_kwargs[k.first] = k.second;
  2014. }
  2015. }
  2016. [[noreturn]] static void nameless_argument_error() {
  2017. throw type_error(
  2018. "Got kwargs without a name; only named arguments "
  2019. "may be passed via py::arg() to a python function call. "
  2020. "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  2021. }
  2022. [[noreturn]] static void nameless_argument_error(const std::string &type) {
  2023. throw type_error("Got kwargs without a name of type '" + type
  2024. + "'; only named "
  2025. "arguments may be passed via py::arg() to a python function call. ");
  2026. }
  2027. [[noreturn]] static void multiple_values_error() {
  2028. throw type_error(
  2029. "Got multiple values for keyword argument "
  2030. "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
  2031. }
  2032. [[noreturn]] static void multiple_values_error(const std::string &name) {
  2033. throw type_error("Got multiple values for keyword argument '" + name + "'");
  2034. }
  2035. private:
  2036. tuple m_args;
  2037. dict m_kwargs;
  2038. };
  2039. // [workaround(intel)] Separate function required here
  2040. // We need to put this into a separate function because the Intel compiler
  2041. // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
  2042. // (tested with ICC 2021.1 Beta 20200827).
  2043. template <typename... Args>
  2044. constexpr bool args_are_all_positional() {
  2045. return all_of<is_positional<Args>...>::value;
  2046. }
  2047. /// Collect only positional arguments for a Python function call
  2048. template <return_value_policy policy,
  2049. typename... Args,
  2050. typename = enable_if_t<args_are_all_positional<Args...>()>>
  2051. simple_collector<policy> collect_arguments(Args &&...args) {
  2052. return simple_collector<policy>(std::forward<Args>(args)...);
  2053. }
  2054. /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
  2055. template <return_value_policy policy,
  2056. typename... Args,
  2057. typename = enable_if_t<!args_are_all_positional<Args...>()>>
  2058. unpacking_collector<policy> collect_arguments(Args &&...args) {
  2059. // Following argument order rules for generalized unpacking according to PEP 448
  2060. static_assert(constexpr_last<is_positional, Args...>()
  2061. < constexpr_first<is_keyword_or_ds, Args...>()
  2062. && constexpr_last<is_s_unpacking, Args...>()
  2063. < constexpr_first<is_ds_unpacking, Args...>(),
  2064. "Invalid function call: positional args must precede keywords and ** unpacking; "
  2065. "* unpacking must precede ** unpacking");
  2066. return unpacking_collector<policy>(std::forward<Args>(args)...);
  2067. }
  2068. template <typename Derived>
  2069. template <return_value_policy policy, typename... Args>
  2070. object object_api<Derived>::operator()(Args &&...args) const {
  2071. #ifndef NDEBUG
  2072. if (!PyGILState_Check()) {
  2073. pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
  2074. }
  2075. #endif
  2076. return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
  2077. }
  2078. template <typename Derived>
  2079. template <return_value_policy policy, typename... Args>
  2080. object object_api<Derived>::call(Args &&...args) const {
  2081. return operator()<policy>(std::forward<Args>(args)...);
  2082. }
  2083. PYBIND11_NAMESPACE_END(detail)
  2084. template <typename T>
  2085. handle type::handle_of() {
  2086. static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
  2087. "py::type::of<T> only supports the case where T is a registered C++ types.");
  2088. return detail::get_type_handle(typeid(T), true);
  2089. }
  2090. #define PYBIND11_MAKE_OPAQUE(...) \
  2091. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
  2092. namespace detail { \
  2093. template <> \
  2094. class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
  2095. } \
  2096. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
  2097. /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
  2098. /// typedef, e.g.:
  2099. /// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
  2100. #define PYBIND11_TYPE(...) __VA_ARGS__
  2101. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)