cast.h 91 KB

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