cast.h 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261
  1. /*
  2. pybind11/cast.h: Partial template specializations to cast between
  3. C++ and Python types
  4. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #pragma once
  9. #include "pytypes.h"
  10. #include "detail/typeid.h"
  11. #include "detail/descr.h"
  12. #include "detail/internals.h"
  13. #include <array>
  14. #include <limits>
  15. #include <tuple>
  16. #include <type_traits>
  17. #if defined(PYBIND11_CPP17)
  18. # if defined(__has_include)
  19. # if __has_include(<string_view>)
  20. # define PYBIND11_HAS_STRING_VIEW
  21. # endif
  22. # elif defined(_MSC_VER)
  23. # define PYBIND11_HAS_STRING_VIEW
  24. # endif
  25. #endif
  26. #ifdef PYBIND11_HAS_STRING_VIEW
  27. #include <string_view>
  28. #endif
  29. #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
  30. # define PYBIND11_HAS_U8STRING
  31. #endif
  32. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  33. PYBIND11_NAMESPACE_BEGIN(detail)
  34. /// A life support system for temporary objects created by `type_caster::load()`.
  35. /// Adding a patient will keep it alive up until the enclosing function returns.
  36. class loader_life_support {
  37. public:
  38. /// A new patient frame is created when a function is entered
  39. loader_life_support() {
  40. get_internals().loader_patient_stack.push_back(nullptr);
  41. }
  42. /// ... and destroyed after it returns
  43. ~loader_life_support() {
  44. auto &stack = get_internals().loader_patient_stack;
  45. if (stack.empty())
  46. pybind11_fail("loader_life_support: internal error");
  47. auto ptr = stack.back();
  48. stack.pop_back();
  49. Py_CLEAR(ptr);
  50. // A heuristic to reduce the stack's capacity (e.g. after long recursive calls)
  51. if (stack.capacity() > 16 && !stack.empty() && stack.capacity() / stack.size() > 2)
  52. stack.shrink_to_fit();
  53. }
  54. /// This can only be used inside a pybind11-bound function, either by `argument_loader`
  55. /// at argument preparation time or by `py::cast()` at execution time.
  56. PYBIND11_NOINLINE static void add_patient(handle h) {
  57. auto &stack = get_internals().loader_patient_stack;
  58. if (stack.empty())
  59. throw cast_error("When called outside a bound function, py::cast() cannot "
  60. "do Python -> C++ conversions which require the creation "
  61. "of temporary values");
  62. auto &list_ptr = stack.back();
  63. if (list_ptr == nullptr) {
  64. list_ptr = PyList_New(1);
  65. if (!list_ptr)
  66. pybind11_fail("loader_life_support: error allocating list");
  67. PyList_SET_ITEM(list_ptr, 0, h.inc_ref().ptr());
  68. } else {
  69. auto result = PyList_Append(list_ptr, h.ptr());
  70. if (result == -1)
  71. pybind11_fail("loader_life_support: error adding patient");
  72. }
  73. }
  74. };
  75. // Gets the cache entry for the given type, creating it if necessary. The return value is the pair
  76. // returned by emplace, i.e. an iterator for the entry and a bool set to `true` if the entry was
  77. // just created.
  78. inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type);
  79. // Populates a just-created cache entry.
  80. PYBIND11_NOINLINE inline void all_type_info_populate(PyTypeObject *t, std::vector<type_info *> &bases) {
  81. std::vector<PyTypeObject *> check;
  82. for (handle parent : reinterpret_borrow<tuple>(t->tp_bases))
  83. check.push_back((PyTypeObject *) parent.ptr());
  84. auto const &type_dict = get_internals().registered_types_py;
  85. for (size_t i = 0; i < check.size(); i++) {
  86. auto type = check[i];
  87. // Ignore Python2 old-style class super type:
  88. if (!PyType_Check((PyObject *) type)) continue;
  89. // Check `type` in the current set of registered python types:
  90. auto it = type_dict.find(type);
  91. if (it != type_dict.end()) {
  92. // We found a cache entry for it, so it's either pybind-registered or has pre-computed
  93. // pybind bases, but we have to make sure we haven't already seen the type(s) before: we
  94. // want to follow Python/virtual C++ rules that there should only be one instance of a
  95. // common base.
  96. for (auto *tinfo : it->second) {
  97. // NB: Could use a second set here, rather than doing a linear search, but since
  98. // having a large number of immediate pybind11-registered types seems fairly
  99. // unlikely, that probably isn't worthwhile.
  100. bool found = false;
  101. for (auto *known : bases) {
  102. if (known == tinfo) { found = true; break; }
  103. }
  104. if (!found) bases.push_back(tinfo);
  105. }
  106. }
  107. else if (type->tp_bases) {
  108. // It's some python type, so keep follow its bases classes to look for one or more
  109. // registered types
  110. if (i + 1 == check.size()) {
  111. // When we're at the end, we can pop off the current element to avoid growing
  112. // `check` when adding just one base (which is typical--i.e. when there is no
  113. // multiple inheritance)
  114. check.pop_back();
  115. i--;
  116. }
  117. for (handle parent : reinterpret_borrow<tuple>(type->tp_bases))
  118. check.push_back((PyTypeObject *) parent.ptr());
  119. }
  120. }
  121. }
  122. /**
  123. * Extracts vector of type_info pointers of pybind-registered roots of the given Python type. Will
  124. * be just 1 pybind type for the Python type of a pybind-registered class, or for any Python-side
  125. * derived class that uses single inheritance. Will contain as many types as required for a Python
  126. * class that uses multiple inheritance to inherit (directly or indirectly) from multiple
  127. * pybind-registered classes. Will be empty if neither the type nor any base classes are
  128. * pybind-registered.
  129. *
  130. * The value is cached for the lifetime of the Python type.
  131. */
  132. inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {
  133. auto ins = all_type_info_get_cache(type);
  134. if (ins.second)
  135. // New cache entry: populate it
  136. all_type_info_populate(type, ins.first->second);
  137. return ins.first->second;
  138. }
  139. /**
  140. * Gets a single pybind11 type info for a python type. Returns nullptr if neither the type nor any
  141. * ancestors are pybind11-registered. Throws an exception if there are multiple bases--use
  142. * `all_type_info` instead if you want to support multiple bases.
  143. */
  144. PYBIND11_NOINLINE inline detail::type_info* get_type_info(PyTypeObject *type) {
  145. auto &bases = all_type_info(type);
  146. if (bases.empty())
  147. return nullptr;
  148. if (bases.size() > 1)
  149. pybind11_fail("pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
  150. return bases.front();
  151. }
  152. inline detail::type_info *get_local_type_info(const std::type_index &tp) {
  153. auto &locals = registered_local_types_cpp();
  154. auto it = locals.find(tp);
  155. if (it != locals.end())
  156. return it->second;
  157. return nullptr;
  158. }
  159. inline detail::type_info *get_global_type_info(const std::type_index &tp) {
  160. auto &types = get_internals().registered_types_cpp;
  161. auto it = types.find(tp);
  162. if (it != types.end())
  163. return it->second;
  164. return nullptr;
  165. }
  166. /// Return the type info for a given C++ type; on lookup failure can either throw or return nullptr.
  167. PYBIND11_NOINLINE inline detail::type_info *get_type_info(const std::type_index &tp,
  168. bool throw_if_missing = false) {
  169. if (auto ltype = get_local_type_info(tp))
  170. return ltype;
  171. if (auto gtype = get_global_type_info(tp))
  172. return gtype;
  173. if (throw_if_missing) {
  174. std::string tname = tp.name();
  175. detail::clean_type_id(tname);
  176. pybind11_fail("pybind11::detail::get_type_info: unable to find type info for \"" + tname + "\"");
  177. }
  178. return nullptr;
  179. }
  180. PYBIND11_NOINLINE inline handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
  181. detail::type_info *type_info = get_type_info(tp, throw_if_missing);
  182. return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
  183. }
  184. struct value_and_holder {
  185. instance *inst = nullptr;
  186. size_t index = 0u;
  187. const detail::type_info *type = nullptr;
  188. void **vh = nullptr;
  189. // Main constructor for a found value/holder:
  190. value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index) :
  191. inst{i}, index{index}, type{type},
  192. vh{inst->simple_layout ? inst->simple_value_holder : &inst->nonsimple.values_and_holders[vpos]}
  193. {}
  194. // Default constructor (used to signal a value-and-holder not found by get_value_and_holder())
  195. value_and_holder() = default;
  196. // Used for past-the-end iterator
  197. value_and_holder(size_t index) : index{index} {}
  198. template <typename V = void> V *&value_ptr() const {
  199. return reinterpret_cast<V *&>(vh[0]);
  200. }
  201. // True if this `value_and_holder` has a non-null value pointer
  202. explicit operator bool() const { return value_ptr(); }
  203. template <typename H> H &holder() const {
  204. return reinterpret_cast<H &>(vh[1]);
  205. }
  206. bool holder_constructed() const {
  207. return inst->simple_layout
  208. ? inst->simple_holder_constructed
  209. : inst->nonsimple.status[index] & instance::status_holder_constructed;
  210. }
  211. void set_holder_constructed(bool v = true) {
  212. if (inst->simple_layout)
  213. inst->simple_holder_constructed = v;
  214. else if (v)
  215. inst->nonsimple.status[index] |= instance::status_holder_constructed;
  216. else
  217. inst->nonsimple.status[index] &= (uint8_t) ~instance::status_holder_constructed;
  218. }
  219. bool instance_registered() const {
  220. return inst->simple_layout
  221. ? inst->simple_instance_registered
  222. : inst->nonsimple.status[index] & instance::status_instance_registered;
  223. }
  224. void set_instance_registered(bool v = true) {
  225. if (inst->simple_layout)
  226. inst->simple_instance_registered = v;
  227. else if (v)
  228. inst->nonsimple.status[index] |= instance::status_instance_registered;
  229. else
  230. inst->nonsimple.status[index] &= (uint8_t) ~instance::status_instance_registered;
  231. }
  232. };
  233. // Container for accessing and iterating over an instance's values/holders
  234. struct values_and_holders {
  235. private:
  236. instance *inst;
  237. using type_vec = std::vector<detail::type_info *>;
  238. const type_vec &tinfo;
  239. public:
  240. values_and_holders(instance *inst) : inst{inst}, tinfo(all_type_info(Py_TYPE(inst))) {}
  241. struct iterator {
  242. private:
  243. instance *inst = nullptr;
  244. const type_vec *types = nullptr;
  245. value_and_holder curr;
  246. friend struct values_and_holders;
  247. iterator(instance *inst, const type_vec *tinfo)
  248. : inst{inst}, types{tinfo},
  249. curr(inst /* instance */,
  250. types->empty() ? nullptr : (*types)[0] /* type info */,
  251. 0, /* vpos: (non-simple types only): the first vptr comes first */
  252. 0 /* index */)
  253. {}
  254. // Past-the-end iterator:
  255. iterator(size_t end) : curr(end) {}
  256. public:
  257. bool operator==(const iterator &other) const { return curr.index == other.curr.index; }
  258. bool operator!=(const iterator &other) const { return curr.index != other.curr.index; }
  259. iterator &operator++() {
  260. if (!inst->simple_layout)
  261. curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;
  262. ++curr.index;
  263. curr.type = curr.index < types->size() ? (*types)[curr.index] : nullptr;
  264. return *this;
  265. }
  266. value_and_holder &operator*() { return curr; }
  267. value_and_holder *operator->() { return &curr; }
  268. };
  269. iterator begin() { return iterator(inst, &tinfo); }
  270. iterator end() { return iterator(tinfo.size()); }
  271. iterator find(const type_info *find_type) {
  272. auto it = begin(), endit = end();
  273. while (it != endit && it->type != find_type) ++it;
  274. return it;
  275. }
  276. size_t size() { return tinfo.size(); }
  277. };
  278. /**
  279. * Extracts C++ value and holder pointer references from an instance (which may contain multiple
  280. * values/holders for python-side multiple inheritance) that match the given type. Throws an error
  281. * if the given type (or ValueType, if omitted) is not a pybind11 base of the given instance. If
  282. * `find_type` is omitted (or explicitly specified as nullptr) the first value/holder are returned,
  283. * regardless of type (and the resulting .type will be nullptr).
  284. *
  285. * The returned object should be short-lived: in particular, it must not outlive the called-upon
  286. * instance.
  287. */
  288. PYBIND11_NOINLINE inline value_and_holder instance::get_value_and_holder(const type_info *find_type /*= nullptr default in common.h*/, bool throw_if_missing /*= true in common.h*/) {
  289. // Optimize common case:
  290. if (!find_type || Py_TYPE(this) == find_type->type)
  291. return value_and_holder(this, find_type, 0, 0);
  292. detail::values_and_holders vhs(this);
  293. auto it = vhs.find(find_type);
  294. if (it != vhs.end())
  295. return *it;
  296. if (!throw_if_missing)
  297. return value_and_holder();
  298. #if defined(NDEBUG)
  299. pybind11_fail("pybind11::detail::instance::get_value_and_holder: "
  300. "type is not a pybind11 base of the given instance "
  301. "(compile in debug mode for type details)");
  302. #else
  303. pybind11_fail("pybind11::detail::instance::get_value_and_holder: `" +
  304. get_fully_qualified_tp_name(find_type->type) + "' is not a pybind11 base of the given `" +
  305. get_fully_qualified_tp_name(Py_TYPE(this)) + "' instance");
  306. #endif
  307. }
  308. PYBIND11_NOINLINE inline void instance::allocate_layout() {
  309. auto &tinfo = all_type_info(Py_TYPE(this));
  310. const size_t n_types = tinfo.size();
  311. if (n_types == 0)
  312. pybind11_fail("instance allocation failed: new instance has no pybind11-registered base types");
  313. simple_layout =
  314. n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
  315. // Simple path: no python-side multiple inheritance, and a small-enough holder
  316. if (simple_layout) {
  317. simple_value_holder[0] = nullptr;
  318. simple_holder_constructed = false;
  319. simple_instance_registered = false;
  320. }
  321. else { // multiple base types or a too-large holder
  322. // Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
  323. // [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
  324. // values that tracks whether each associated holder has been initialized. Each [block] is
  325. // padded, if necessary, to an integer multiple of sizeof(void *).
  326. size_t space = 0;
  327. for (auto t : tinfo) {
  328. space += 1; // value pointer
  329. space += t->holder_size_in_ptrs; // holder instance
  330. }
  331. size_t flags_at = space;
  332. space += size_in_ptrs(n_types); // status bytes (holder_constructed and instance_registered)
  333. // Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
  334. // in particular, need to be 0). Use Python's memory allocation functions: in Python 3.6
  335. // they default to using pymalloc, which is designed to be efficient for small allocations
  336. // like the one we're doing here; in earlier versions (and for larger allocations) they are
  337. // just wrappers around malloc.
  338. #if PY_VERSION_HEX >= 0x03050000
  339. nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
  340. if (!nonsimple.values_and_holders) throw std::bad_alloc();
  341. #else
  342. nonsimple.values_and_holders = (void **) PyMem_New(void *, space);
  343. if (!nonsimple.values_and_holders) throw std::bad_alloc();
  344. std::memset(nonsimple.values_and_holders, 0, space * sizeof(void *));
  345. #endif
  346. nonsimple.status = reinterpret_cast<uint8_t *>(&nonsimple.values_and_holders[flags_at]);
  347. }
  348. owned = true;
  349. }
  350. PYBIND11_NOINLINE inline void instance::deallocate_layout() {
  351. if (!simple_layout)
  352. PyMem_Free(nonsimple.values_and_holders);
  353. }
  354. PYBIND11_NOINLINE inline bool isinstance_generic(handle obj, const std::type_info &tp) {
  355. handle type = detail::get_type_handle(tp, false);
  356. if (!type)
  357. return false;
  358. return isinstance(obj, type);
  359. }
  360. PYBIND11_NOINLINE inline std::string error_string() {
  361. if (!PyErr_Occurred()) {
  362. PyErr_SetString(PyExc_RuntimeError, "Unknown internal error occurred");
  363. return "Unknown internal error occurred";
  364. }
  365. error_scope scope; // Preserve error state
  366. std::string errorString;
  367. if (scope.type) {
  368. errorString += handle(scope.type).attr("__name__").cast<std::string>();
  369. errorString += ": ";
  370. }
  371. if (scope.value)
  372. errorString += (std::string) str(scope.value);
  373. PyErr_NormalizeException(&scope.type, &scope.value, &scope.trace);
  374. #if PY_MAJOR_VERSION >= 3
  375. if (scope.trace != nullptr)
  376. PyException_SetTraceback(scope.value, scope.trace);
  377. #endif
  378. #if !defined(PYPY_VERSION)
  379. if (scope.trace) {
  380. auto *trace = (PyTracebackObject *) scope.trace;
  381. /* Get the deepest trace possible */
  382. while (trace->tb_next)
  383. trace = trace->tb_next;
  384. PyFrameObject *frame = trace->tb_frame;
  385. errorString += "\n\nAt:\n";
  386. while (frame) {
  387. int lineno = PyFrame_GetLineNumber(frame);
  388. errorString +=
  389. " " + handle(frame->f_code->co_filename).cast<std::string>() +
  390. "(" + std::to_string(lineno) + "): " +
  391. handle(frame->f_code->co_name).cast<std::string>() + "\n";
  392. frame = frame->f_back;
  393. }
  394. }
  395. #endif
  396. return errorString;
  397. }
  398. PYBIND11_NOINLINE inline handle get_object_handle(const void *ptr, const detail::type_info *type ) {
  399. auto &instances = get_internals().registered_instances;
  400. auto range = instances.equal_range(ptr);
  401. for (auto it = range.first; it != range.second; ++it) {
  402. for (const auto &vh : values_and_holders(it->second)) {
  403. if (vh.type == type)
  404. return handle((PyObject *) it->second);
  405. }
  406. }
  407. return handle();
  408. }
  409. inline PyThreadState *get_thread_state_unchecked() {
  410. #if defined(PYPY_VERSION)
  411. return PyThreadState_GET();
  412. #elif PY_VERSION_HEX < 0x03000000
  413. return _PyThreadState_Current;
  414. #elif PY_VERSION_HEX < 0x03050000
  415. return (PyThreadState*) _Py_atomic_load_relaxed(&_PyThreadState_Current);
  416. #elif PY_VERSION_HEX < 0x03050200
  417. return (PyThreadState*) _PyThreadState_Current.value;
  418. #else
  419. return _PyThreadState_UncheckedGet();
  420. #endif
  421. }
  422. // Forward declarations
  423. inline void keep_alive_impl(handle nurse, handle patient);
  424. inline PyObject *make_new_instance(PyTypeObject *type);
  425. class type_caster_generic {
  426. public:
  427. PYBIND11_NOINLINE type_caster_generic(const std::type_info &type_info)
  428. : typeinfo(get_type_info(type_info)), cpptype(&type_info) { }
  429. type_caster_generic(const type_info *typeinfo)
  430. : typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) { }
  431. bool load(handle src, bool convert) {
  432. return load_impl<type_caster_generic>(src, convert);
  433. }
  434. PYBIND11_NOINLINE static handle cast(const void *_src, return_value_policy policy, handle parent,
  435. const detail::type_info *tinfo,
  436. void *(*copy_constructor)(const void *),
  437. void *(*move_constructor)(const void *),
  438. const void *existing_holder = nullptr) {
  439. if (!tinfo) // no type info: error will be set already
  440. return handle();
  441. void *src = const_cast<void *>(_src);
  442. if (src == nullptr)
  443. return none().release();
  444. auto it_instances = get_internals().registered_instances.equal_range(src);
  445. for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
  446. for (auto instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
  447. if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype))
  448. return handle((PyObject *) it_i->second).inc_ref();
  449. }
  450. }
  451. auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
  452. auto wrapper = reinterpret_cast<instance *>(inst.ptr());
  453. wrapper->owned = false;
  454. void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
  455. switch (policy) {
  456. case return_value_policy::automatic:
  457. case return_value_policy::take_ownership:
  458. valueptr = src;
  459. wrapper->owned = true;
  460. break;
  461. case return_value_policy::automatic_reference:
  462. case return_value_policy::reference:
  463. valueptr = src;
  464. wrapper->owned = false;
  465. break;
  466. case return_value_policy::copy:
  467. if (copy_constructor)
  468. valueptr = copy_constructor(src);
  469. else {
  470. #if defined(NDEBUG)
  471. throw cast_error("return_value_policy = copy, but type is "
  472. "non-copyable! (compile in debug mode for details)");
  473. #else
  474. std::string type_name(tinfo->cpptype->name());
  475. detail::clean_type_id(type_name);
  476. throw cast_error("return_value_policy = copy, but type " +
  477. type_name + " is non-copyable!");
  478. #endif
  479. }
  480. wrapper->owned = true;
  481. break;
  482. case return_value_policy::move:
  483. if (move_constructor)
  484. valueptr = move_constructor(src);
  485. else if (copy_constructor)
  486. valueptr = copy_constructor(src);
  487. else {
  488. #if defined(NDEBUG)
  489. throw cast_error("return_value_policy = move, but type is neither "
  490. "movable nor copyable! "
  491. "(compile in debug mode for details)");
  492. #else
  493. std::string type_name(tinfo->cpptype->name());
  494. detail::clean_type_id(type_name);
  495. throw cast_error("return_value_policy = move, but type " +
  496. type_name + " is neither movable nor copyable!");
  497. #endif
  498. }
  499. wrapper->owned = true;
  500. break;
  501. case return_value_policy::reference_internal:
  502. valueptr = src;
  503. wrapper->owned = false;
  504. keep_alive_impl(inst, parent);
  505. break;
  506. default:
  507. throw cast_error("unhandled return_value_policy: should not happen!");
  508. }
  509. tinfo->init_instance(wrapper, existing_holder);
  510. return inst.release();
  511. }
  512. // Base methods for generic caster; there are overridden in copyable_holder_caster
  513. void load_value(value_and_holder &&v_h) {
  514. auto *&vptr = v_h.value_ptr();
  515. // Lazy allocation for unallocated values:
  516. if (vptr == nullptr) {
  517. auto *type = v_h.type ? v_h.type : typeinfo;
  518. if (type->operator_new) {
  519. vptr = type->operator_new(type->type_size);
  520. } else {
  521. #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
  522. if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
  523. vptr = ::operator new(type->type_size,
  524. std::align_val_t(type->type_align));
  525. else
  526. #endif
  527. vptr = ::operator new(type->type_size);
  528. }
  529. }
  530. value = vptr;
  531. }
  532. bool try_implicit_casts(handle src, bool convert) {
  533. for (auto &cast : typeinfo->implicit_casts) {
  534. type_caster_generic sub_caster(*cast.first);
  535. if (sub_caster.load(src, convert)) {
  536. value = cast.second(sub_caster.value);
  537. return true;
  538. }
  539. }
  540. return false;
  541. }
  542. bool try_direct_conversions(handle src) {
  543. for (auto &converter : *typeinfo->direct_conversions) {
  544. if (converter(src.ptr(), value))
  545. return true;
  546. }
  547. return false;
  548. }
  549. void check_holder_compat() {}
  550. PYBIND11_NOINLINE static void *local_load(PyObject *src, const type_info *ti) {
  551. auto caster = type_caster_generic(ti);
  552. if (caster.load(src, false))
  553. return caster.value;
  554. return nullptr;
  555. }
  556. /// Try to load with foreign typeinfo, if available. Used when there is no
  557. /// native typeinfo, or when the native one wasn't able to produce a value.
  558. PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) {
  559. constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;
  560. const auto pytype = type::handle_of(src);
  561. if (!hasattr(pytype, local_key))
  562. return false;
  563. type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
  564. // Only consider this foreign loader if actually foreign and is a loader of the correct cpp type
  565. if (foreign_typeinfo->module_local_load == &local_load
  566. || (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype)))
  567. return false;
  568. if (auto result = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo)) {
  569. value = result;
  570. return true;
  571. }
  572. return false;
  573. }
  574. // Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant
  575. // bits of code between here and copyable_holder_caster where the two classes need different
  576. // logic (without having to resort to virtual inheritance).
  577. template <typename ThisT>
  578. PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
  579. if (!src) return false;
  580. if (!typeinfo) return try_load_foreign_module_local(src);
  581. if (src.is_none()) {
  582. // Defer accepting None to other overloads (if we aren't in convert mode):
  583. if (!convert) return false;
  584. value = nullptr;
  585. return true;
  586. }
  587. auto &this_ = static_cast<ThisT &>(*this);
  588. this_.check_holder_compat();
  589. PyTypeObject *srctype = Py_TYPE(src.ptr());
  590. // Case 1: If src is an exact type match for the target type then we can reinterpret_cast
  591. // the instance's value pointer to the target type:
  592. if (srctype == typeinfo->type) {
  593. this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
  594. return true;
  595. }
  596. // Case 2: We have a derived class
  597. else if (PyType_IsSubtype(srctype, typeinfo->type)) {
  598. auto &bases = all_type_info(srctype);
  599. bool no_cpp_mi = typeinfo->simple_type;
  600. // Case 2a: the python type is a Python-inherited derived class that inherits from just
  601. // one simple (no MI) pybind11 class, or is an exact match, so the C++ instance is of
  602. // the right type and we can use reinterpret_cast.
  603. // (This is essentially the same as case 2b, but because not using multiple inheritance
  604. // is extremely common, we handle it specially to avoid the loop iterator and type
  605. // pointer lookup overhead)
  606. if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
  607. this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
  608. return true;
  609. }
  610. // Case 2b: the python type inherits from multiple C++ bases. Check the bases to see if
  611. // we can find an exact match (or, for a simple C++ type, an inherited match); if so, we
  612. // can safely reinterpret_cast to the relevant pointer.
  613. else if (bases.size() > 1) {
  614. for (auto base : bases) {
  615. if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type) : base->type == typeinfo->type) {
  616. this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
  617. return true;
  618. }
  619. }
  620. }
  621. // Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type match
  622. // in the registered bases, above, so try implicit casting (needed for proper C++ casting
  623. // when MI is involved).
  624. if (this_.try_implicit_casts(src, convert))
  625. return true;
  626. }
  627. // Perform an implicit conversion
  628. if (convert) {
  629. for (auto &converter : typeinfo->implicit_conversions) {
  630. auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
  631. if (load_impl<ThisT>(temp, false)) {
  632. loader_life_support::add_patient(temp);
  633. return true;
  634. }
  635. }
  636. if (this_.try_direct_conversions(src))
  637. return true;
  638. }
  639. // Failed to match local typeinfo. Try again with global.
  640. if (typeinfo->module_local) {
  641. if (auto gtype = get_global_type_info(*typeinfo->cpptype)) {
  642. typeinfo = gtype;
  643. return load(src, false);
  644. }
  645. }
  646. // Global typeinfo has precedence over foreign module_local
  647. return try_load_foreign_module_local(src);
  648. }
  649. // Called to do type lookup and wrap the pointer and type in a pair when a dynamic_cast
  650. // isn't needed or can't be used. If the type is unknown, sets the error and returns a pair
  651. // with .second = nullptr. (p.first = nullptr is not an error: it becomes None).
  652. PYBIND11_NOINLINE static std::pair<const void *, const type_info *> src_and_type(
  653. const void *src, const std::type_info &cast_type, const std::type_info *rtti_type = nullptr) {
  654. if (auto *tpi = get_type_info(cast_type))
  655. return {src, const_cast<const type_info *>(tpi)};
  656. // Not found, set error:
  657. std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
  658. detail::clean_type_id(tname);
  659. std::string msg = "Unregistered type : " + tname;
  660. PyErr_SetString(PyExc_TypeError, msg.c_str());
  661. return {nullptr, nullptr};
  662. }
  663. const type_info *typeinfo = nullptr;
  664. const std::type_info *cpptype = nullptr;
  665. void *value = nullptr;
  666. };
  667. /**
  668. * Determine suitable casting operator for pointer-or-lvalue-casting type casters. The type caster
  669. * needs to provide `operator T*()` and `operator T&()` operators.
  670. *
  671. * If the type supports moving the value away via an `operator T&&() &&` method, it should use
  672. * `movable_cast_op_type` instead.
  673. */
  674. template <typename T>
  675. using cast_op_type =
  676. conditional_t<std::is_pointer<remove_reference_t<T>>::value,
  677. typename std::add_pointer<intrinsic_t<T>>::type,
  678. typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
  679. /**
  680. * Determine suitable casting operator for a type caster with a movable value. Such a type caster
  681. * needs to provide `operator T*()`, `operator T&()`, and `operator T&&() &&`. The latter will be
  682. * called in appropriate contexts where the value can be moved rather than copied.
  683. *
  684. * These operator are automatically provided when using the PYBIND11_TYPE_CASTER macro.
  685. */
  686. template <typename T>
  687. using movable_cast_op_type =
  688. conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,
  689. typename std::add_pointer<intrinsic_t<T>>::type,
  690. conditional_t<std::is_rvalue_reference<T>::value,
  691. typename std::add_rvalue_reference<intrinsic_t<T>>::type,
  692. typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
  693. // std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when
  694. // T is non-copyable, but code containing such a copy constructor fails to actually compile.
  695. template <typename T, typename SFINAE = void> struct is_copy_constructible : std::is_copy_constructible<T> {};
  696. // Specialization for types that appear to be copy constructible but also look like stl containers
  697. // (we specifically check for: has `value_type` and `reference` with `reference = value_type&`): if
  698. // so, copy constructability depends on whether the value_type is copy constructible.
  699. template <typename Container> struct is_copy_constructible<Container, enable_if_t<all_of<
  700. std::is_copy_constructible<Container>,
  701. std::is_same<typename Container::value_type &, typename Container::reference>,
  702. // Avoid infinite recursion
  703. negation<std::is_same<Container, typename Container::value_type>>
  704. >::value>> : is_copy_constructible<typename Container::value_type> {};
  705. // Likewise for std::pair
  706. // (after C++17 it is mandatory that the copy constructor not exist when the two types aren't themselves
  707. // copy constructible, but this can not be relied upon when T1 or T2 are themselves containers).
  708. template <typename T1, typename T2> struct is_copy_constructible<std::pair<T1, T2>>
  709. : all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
  710. // The same problems arise with std::is_copy_assignable, so we use the same workaround.
  711. template <typename T, typename SFINAE = void> struct is_copy_assignable : std::is_copy_assignable<T> {};
  712. template <typename Container> struct is_copy_assignable<Container, enable_if_t<all_of<
  713. std::is_copy_assignable<Container>,
  714. std::is_same<typename Container::value_type &, typename Container::reference>
  715. >::value>> : is_copy_assignable<typename Container::value_type> {};
  716. template <typename T1, typename T2> struct is_copy_assignable<std::pair<T1, T2>>
  717. : all_of<is_copy_assignable<T1>, is_copy_assignable<T2>> {};
  718. PYBIND11_NAMESPACE_END(detail)
  719. // polymorphic_type_hook<itype>::get(src, tinfo) determines whether the object pointed
  720. // to by `src` actually is an instance of some class derived from `itype`.
  721. // If so, it sets `tinfo` to point to the std::type_info representing that derived
  722. // type, and returns a pointer to the start of the most-derived object of that type
  723. // (in which `src` is a subobject; this will be the same address as `src` in most
  724. // single inheritance cases). If not, or if `src` is nullptr, it simply returns `src`
  725. // and leaves `tinfo` at its default value of nullptr.
  726. //
  727. // The default polymorphic_type_hook just returns src. A specialization for polymorphic
  728. // types determines the runtime type of the passed object and adjusts the this-pointer
  729. // appropriately via dynamic_cast<void*>. This is what enables a C++ Animal* to appear
  730. // to Python as a Dog (if Dog inherits from Animal, Animal is polymorphic, Dog is
  731. // registered with pybind11, and this Animal is in fact a Dog).
  732. //
  733. // You may specialize polymorphic_type_hook yourself for types that want to appear
  734. // polymorphic to Python but do not use C++ RTTI. (This is a not uncommon pattern
  735. // in performance-sensitive applications, used most notably in LLVM.)
  736. //
  737. // polymorphic_type_hook_base allows users to specialize polymorphic_type_hook with
  738. // std::enable_if. User provided specializations will always have higher priority than
  739. // the default implementation and specialization provided in polymorphic_type_hook_base.
  740. template <typename itype, typename SFINAE = void>
  741. struct polymorphic_type_hook_base
  742. {
  743. static const void *get(const itype *src, const std::type_info*&) { return src; }
  744. };
  745. template <typename itype>
  746. struct polymorphic_type_hook_base<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>>
  747. {
  748. static const void *get(const itype *src, const std::type_info*& type) {
  749. type = src ? &typeid(*src) : nullptr;
  750. return dynamic_cast<const void*>(src);
  751. }
  752. };
  753. template <typename itype, typename SFINAE = void>
  754. struct polymorphic_type_hook : public polymorphic_type_hook_base<itype> {};
  755. PYBIND11_NAMESPACE_BEGIN(detail)
  756. /// Generic type caster for objects stored on the heap
  757. template <typename type> class type_caster_base : public type_caster_generic {
  758. using itype = intrinsic_t<type>;
  759. public:
  760. static constexpr auto name = _<type>();
  761. type_caster_base() : type_caster_base(typeid(type)) { }
  762. explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) { }
  763. static handle cast(const itype &src, return_value_policy policy, handle parent) {
  764. if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
  765. policy = return_value_policy::copy;
  766. return cast(&src, policy, parent);
  767. }
  768. static handle cast(itype &&src, return_value_policy, handle parent) {
  769. return cast(&src, return_value_policy::move, parent);
  770. }
  771. // Returns a (pointer, type_info) pair taking care of necessary type lookup for a
  772. // polymorphic type (using RTTI by default, but can be overridden by specializing
  773. // polymorphic_type_hook). If the instance isn't derived, returns the base version.
  774. static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
  775. auto &cast_type = typeid(itype);
  776. const std::type_info *instance_type = nullptr;
  777. const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
  778. if (instance_type && !same_type(cast_type, *instance_type)) {
  779. // This is a base pointer to a derived type. If the derived type is registered
  780. // with pybind11, we want to make the full derived object available.
  781. // In the typical case where itype is polymorphic, we get the correct
  782. // derived pointer (which may be != base pointer) by a dynamic_cast to
  783. // most derived type. If itype is not polymorphic, we won't get here
  784. // except via a user-provided specialization of polymorphic_type_hook,
  785. // and the user has promised that no this-pointer adjustment is
  786. // required in that case, so it's OK to use static_cast.
  787. if (const auto *tpi = get_type_info(*instance_type))
  788. return {vsrc, tpi};
  789. }
  790. // Otherwise we have either a nullptr, an `itype` pointer, or an unknown derived pointer, so
  791. // don't do a cast
  792. return type_caster_generic::src_and_type(src, cast_type, instance_type);
  793. }
  794. static handle cast(const itype *src, return_value_policy policy, handle parent) {
  795. auto st = src_and_type(src);
  796. return type_caster_generic::cast(
  797. st.first, policy, parent, st.second,
  798. make_copy_constructor(src), make_move_constructor(src));
  799. }
  800. static handle cast_holder(const itype *src, const void *holder) {
  801. auto st = src_and_type(src);
  802. return type_caster_generic::cast(
  803. st.first, return_value_policy::take_ownership, {}, st.second,
  804. nullptr, nullptr, holder);
  805. }
  806. template <typename T> using cast_op_type = detail::cast_op_type<T>;
  807. operator itype*() { return (type *) value; }
  808. operator itype&() { if (!value) throw reference_cast_error(); return *((itype *) value); }
  809. protected:
  810. using Constructor = void *(*)(const void *);
  811. /* Only enabled when the types are {copy,move}-constructible *and* when the type
  812. does not have a private operator new implementation. */
  813. template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
  814. static auto make_copy_constructor(const T *x) -> decltype(new T(*x), Constructor{}) {
  815. return [](const void *arg) -> void * {
  816. return new T(*reinterpret_cast<const T *>(arg));
  817. };
  818. }
  819. template <typename T, typename = enable_if_t<std::is_move_constructible<T>::value>>
  820. static auto make_move_constructor(const T *x) -> decltype(new T(std::move(*const_cast<T *>(x))), Constructor{}) {
  821. return [](const void *arg) -> void * {
  822. return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
  823. };
  824. }
  825. static Constructor make_copy_constructor(...) { return nullptr; }
  826. static Constructor make_move_constructor(...) { return nullptr; }
  827. };
  828. template <typename type, typename SFINAE = void> class type_caster : public type_caster_base<type> { };
  829. template <typename type> using make_caster = type_caster<intrinsic_t<type>>;
  830. // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
  831. template <typename T> typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
  832. return caster.operator typename make_caster<T>::template cast_op_type<T>();
  833. }
  834. template <typename T> typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
  835. cast_op(make_caster<T> &&caster) {
  836. return std::move(caster).operator
  837. typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>();
  838. }
  839. template <typename type> class type_caster<std::reference_wrapper<type>> {
  840. private:
  841. using caster_t = make_caster<type>;
  842. caster_t subcaster;
  843. using reference_t = type&;
  844. using subcaster_cast_op_type =
  845. typename caster_t::template cast_op_type<reference_t>;
  846. static_assert(std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value ||
  847. std::is_same<reference_t, subcaster_cast_op_type>::value,
  848. "std::reference_wrapper<T> caster requires T to have a caster with an "
  849. "`operator T &()` or `operator const T &()`");
  850. public:
  851. bool load(handle src, bool convert) { return subcaster.load(src, convert); }
  852. static constexpr auto name = caster_t::name;
  853. static handle cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
  854. // It is definitely wrong to take ownership of this pointer, so mask that rvp
  855. if (policy == return_value_policy::take_ownership || policy == return_value_policy::automatic)
  856. policy = return_value_policy::automatic_reference;
  857. return caster_t::cast(&src.get(), policy, parent);
  858. }
  859. template <typename T> using cast_op_type = std::reference_wrapper<type>;
  860. operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
  861. };
  862. #define PYBIND11_TYPE_CASTER(type, py_name) \
  863. protected: \
  864. type value; \
  865. public: \
  866. static constexpr auto name = py_name; \
  867. template <typename T_, enable_if_t<std::is_same<type, remove_cv_t<T_>>::value, int> = 0> \
  868. static handle cast(T_ *src, return_value_policy policy, handle parent) { \
  869. if (!src) return none().release(); \
  870. if (policy == return_value_policy::take_ownership) { \
  871. auto h = cast(std::move(*src), policy, parent); delete src; return h; \
  872. } else { \
  873. return cast(*src, policy, parent); \
  874. } \
  875. } \
  876. operator type*() { return &value; } \
  877. operator type&() { return value; } \
  878. operator type&&() && { return std::move(value); } \
  879. template <typename T_> using cast_op_type = pybind11::detail::movable_cast_op_type<T_>
  880. template <typename CharT> using is_std_char_type = any_of<
  881. std::is_same<CharT, char>, /* std::string */
  882. #if defined(PYBIND11_HAS_U8STRING)
  883. std::is_same<CharT, char8_t>, /* std::u8string */
  884. #endif
  885. std::is_same<CharT, char16_t>, /* std::u16string */
  886. std::is_same<CharT, char32_t>, /* std::u32string */
  887. std::is_same<CharT, wchar_t> /* std::wstring */
  888. >;
  889. template <typename T>
  890. struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
  891. using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
  892. using _py_type_1 = conditional_t<std::is_signed<T>::value, _py_type_0, typename std::make_unsigned<_py_type_0>::type>;
  893. using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
  894. public:
  895. bool load(handle src, bool convert) {
  896. py_type py_value;
  897. if (!src)
  898. return false;
  899. #if !defined(PYPY_VERSION)
  900. auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
  901. #else
  902. // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
  903. // while CPython only considers the existence of `nb_index`/`__index__`.
  904. auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
  905. #endif
  906. if (std::is_floating_point<T>::value) {
  907. if (convert || PyFloat_Check(src.ptr()))
  908. py_value = (py_type) PyFloat_AsDouble(src.ptr());
  909. else
  910. return false;
  911. } else if (PyFloat_Check(src.ptr())) {
  912. return false;
  913. } else if (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr())) {
  914. return false;
  915. } else {
  916. handle src_or_index = src;
  917. #if PY_VERSION_HEX < 0x03080000
  918. object index;
  919. if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
  920. index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
  921. if (!index) {
  922. PyErr_Clear();
  923. if (!convert)
  924. return false;
  925. }
  926. else {
  927. src_or_index = index;
  928. }
  929. }
  930. #endif
  931. if (std::is_unsigned<py_type>::value) {
  932. py_value = as_unsigned<py_type>(src_or_index.ptr());
  933. } else { // signed integer:
  934. py_value = sizeof(T) <= sizeof(long)
  935. ? (py_type) PyLong_AsLong(src_or_index.ptr())
  936. : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
  937. }
  938. }
  939. // Python API reported an error
  940. bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
  941. // Check to see if the conversion is valid (integers should match exactly)
  942. // Signed/unsigned checks happen elsewhere
  943. if (py_err || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T) && py_value != (py_type) (T) py_value)) {
  944. PyErr_Clear();
  945. if (py_err && convert && PyNumber_Check(src.ptr())) {
  946. auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
  947. ? PyNumber_Float(src.ptr())
  948. : PyNumber_Long(src.ptr()));
  949. PyErr_Clear();
  950. return load(tmp, false);
  951. }
  952. return false;
  953. }
  954. value = (T) py_value;
  955. return true;
  956. }
  957. template<typename U = T>
  958. static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
  959. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  960. return PyFloat_FromDouble((double) src);
  961. }
  962. template<typename U = T>
  963. static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (sizeof(U) <= sizeof(long)), handle>::type
  964. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  965. return PYBIND11_LONG_FROM_SIGNED((long) src);
  966. }
  967. template<typename U = T>
  968. static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (sizeof(U) <= sizeof(unsigned long)), handle>::type
  969. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  970. return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
  971. }
  972. template<typename U = T>
  973. static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (sizeof(U) > sizeof(long)), handle>::type
  974. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  975. return PyLong_FromLongLong((long long) src);
  976. }
  977. template<typename U = T>
  978. static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (sizeof(U) > sizeof(unsigned long)), handle>::type
  979. cast(U src, return_value_policy /* policy */, handle /* parent */) {
  980. return PyLong_FromUnsignedLongLong((unsigned long long) src);
  981. }
  982. PYBIND11_TYPE_CASTER(T, _<std::is_integral<T>::value>("int", "float"));
  983. };
  984. template<typename T> struct void_caster {
  985. public:
  986. bool load(handle src, bool) {
  987. if (src && src.is_none())
  988. return true;
  989. return false;
  990. }
  991. static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
  992. return none().inc_ref();
  993. }
  994. PYBIND11_TYPE_CASTER(T, _("None"));
  995. };
  996. template <> class type_caster<void_type> : public void_caster<void_type> {};
  997. template <> class type_caster<void> : public type_caster<void_type> {
  998. public:
  999. using type_caster<void_type>::cast;
  1000. bool load(handle h, bool) {
  1001. if (!h) {
  1002. return false;
  1003. } else if (h.is_none()) {
  1004. value = nullptr;
  1005. return true;
  1006. }
  1007. /* Check if this is a capsule */
  1008. if (isinstance<capsule>(h)) {
  1009. value = reinterpret_borrow<capsule>(h);
  1010. return true;
  1011. }
  1012. /* Check if this is a C++ type */
  1013. auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
  1014. if (bases.size() == 1) { // Only allowing loading from a single-value type
  1015. value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
  1016. return true;
  1017. }
  1018. /* Fail */
  1019. return false;
  1020. }
  1021. static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
  1022. if (ptr)
  1023. return capsule(ptr).release();
  1024. else
  1025. return none().inc_ref();
  1026. }
  1027. template <typename T> using cast_op_type = void*&;
  1028. operator void *&() { return value; }
  1029. static constexpr auto name = _("capsule");
  1030. private:
  1031. void *value = nullptr;
  1032. };
  1033. template <> class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> { };
  1034. template <> class type_caster<bool> {
  1035. public:
  1036. bool load(handle src, bool convert) {
  1037. if (!src) return false;
  1038. else if (src.ptr() == Py_True) { value = true; return true; }
  1039. else if (src.ptr() == Py_False) { value = false; return true; }
  1040. else if (convert || !strcmp("numpy.bool_", Py_TYPE(src.ptr())->tp_name)) {
  1041. // (allow non-implicit conversion for numpy booleans)
  1042. Py_ssize_t res = -1;
  1043. if (src.is_none()) {
  1044. res = 0; // None is implicitly converted to False
  1045. }
  1046. #if defined(PYPY_VERSION)
  1047. // On PyPy, check that "__bool__" (or "__nonzero__" on Python 2.7) attr exists
  1048. else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
  1049. res = PyObject_IsTrue(src.ptr());
  1050. }
  1051. #else
  1052. // Alternate approach for CPython: this does the same as the above, but optimized
  1053. // using the CPython API so as to avoid an unneeded attribute lookup.
  1054. else if (auto tp_as_number = src.ptr()->ob_type->tp_as_number) {
  1055. if (PYBIND11_NB_BOOL(tp_as_number)) {
  1056. res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
  1057. }
  1058. }
  1059. #endif
  1060. if (res == 0 || res == 1) {
  1061. value = (bool) res;
  1062. return true;
  1063. } else {
  1064. PyErr_Clear();
  1065. }
  1066. }
  1067. return false;
  1068. }
  1069. static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
  1070. return handle(src ? Py_True : Py_False).inc_ref();
  1071. }
  1072. PYBIND11_TYPE_CASTER(bool, _("bool"));
  1073. };
  1074. // Helper class for UTF-{8,16,32} C++ stl strings:
  1075. template <typename StringType, bool IsView = false> struct string_caster {
  1076. using CharT = typename StringType::value_type;
  1077. // Simplify life by being able to assume standard char sizes (the standard only guarantees
  1078. // minimums, but Python requires exact sizes)
  1079. static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1, "Unsupported char size != 1");
  1080. #if defined(PYBIND11_HAS_U8STRING)
  1081. static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1, "Unsupported char8_t size != 1");
  1082. #endif
  1083. static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2, "Unsupported char16_t size != 2");
  1084. static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4, "Unsupported char32_t size != 4");
  1085. // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
  1086. static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
  1087. "Unsupported wchar_t size != 2/4");
  1088. static constexpr size_t UTF_N = 8 * sizeof(CharT);
  1089. bool load(handle src, bool) {
  1090. #if PY_MAJOR_VERSION < 3
  1091. object temp;
  1092. #endif
  1093. handle load_src = src;
  1094. if (!src) {
  1095. return false;
  1096. } else if (!PyUnicode_Check(load_src.ptr())) {
  1097. #if PY_MAJOR_VERSION >= 3
  1098. return load_bytes(load_src);
  1099. #else
  1100. if (std::is_same<CharT, char>::value) {
  1101. return load_bytes(load_src);
  1102. }
  1103. // The below is a guaranteed failure in Python 3 when PyUnicode_Check returns false
  1104. if (!PYBIND11_BYTES_CHECK(load_src.ptr()))
  1105. return false;
  1106. temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.ptr()));
  1107. if (!temp) { PyErr_Clear(); return false; }
  1108. load_src = temp;
  1109. #endif
  1110. }
  1111. auto utfNbytes = reinterpret_steal<object>(PyUnicode_AsEncodedString(
  1112. load_src.ptr(), UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr));
  1113. if (!utfNbytes) { PyErr_Clear(); return false; }
  1114. const auto *buffer = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
  1115. size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
  1116. if (UTF_N > 8) { buffer++; length--; } // Skip BOM for UTF-16/32
  1117. value = StringType(buffer, length);
  1118. // If we're loading a string_view we need to keep the encoded Python object alive:
  1119. if (IsView)
  1120. loader_life_support::add_patient(utfNbytes);
  1121. return true;
  1122. }
  1123. static handle cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
  1124. const char *buffer = reinterpret_cast<const char *>(src.data());
  1125. auto nbytes = ssize_t(src.size() * sizeof(CharT));
  1126. handle s = decode_utfN(buffer, nbytes);
  1127. if (!s) throw error_already_set();
  1128. return s;
  1129. }
  1130. PYBIND11_TYPE_CASTER(StringType, _(PYBIND11_STRING_NAME));
  1131. private:
  1132. static handle decode_utfN(const char *buffer, ssize_t nbytes) {
  1133. #if !defined(PYPY_VERSION)
  1134. return
  1135. UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr) :
  1136. UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr) :
  1137. PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
  1138. #else
  1139. // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as well),
  1140. // so bypass the whole thing by just passing the encoding as a string value, which works properly:
  1141. return PyUnicode_Decode(buffer, nbytes, UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr);
  1142. #endif
  1143. }
  1144. // When loading into a std::string or char*, accept a bytes object as-is (i.e.
  1145. // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
  1146. // which supports loading a unicode from a str, doesn't take this path.
  1147. template <typename C = CharT>
  1148. bool load_bytes(enable_if_t<std::is_same<C, char>::value, handle> src) {
  1149. if (PYBIND11_BYTES_CHECK(src.ptr())) {
  1150. // We were passed a Python 3 raw bytes; accept it into a std::string or char*
  1151. // without any encoding attempt.
  1152. const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
  1153. if (bytes) {
  1154. value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
  1155. return true;
  1156. }
  1157. }
  1158. return false;
  1159. }
  1160. template <typename C = CharT>
  1161. bool load_bytes(enable_if_t<!std::is_same<C, char>::value, handle>) { return false; }
  1162. };
  1163. template <typename CharT, class Traits, class Allocator>
  1164. struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_std_char_type<CharT>::value>>
  1165. : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
  1166. #ifdef PYBIND11_HAS_STRING_VIEW
  1167. template <typename CharT, class Traits>
  1168. struct type_caster<std::basic_string_view<CharT, Traits>, enable_if_t<is_std_char_type<CharT>::value>>
  1169. : string_caster<std::basic_string_view<CharT, Traits>, true> {};
  1170. #endif
  1171. // Type caster for C-style strings. We basically use a std::string type caster, but also add the
  1172. // ability to use None as a nullptr char* (which the string caster doesn't allow).
  1173. template <typename CharT> struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
  1174. using StringType = std::basic_string<CharT>;
  1175. using StringCaster = type_caster<StringType>;
  1176. StringCaster str_caster;
  1177. bool none = false;
  1178. CharT one_char = 0;
  1179. public:
  1180. bool load(handle src, bool convert) {
  1181. if (!src) return false;
  1182. if (src.is_none()) {
  1183. // Defer accepting None to other overloads (if we aren't in convert mode):
  1184. if (!convert) return false;
  1185. none = true;
  1186. return true;
  1187. }
  1188. return str_caster.load(src, convert);
  1189. }
  1190. static handle cast(const CharT *src, return_value_policy policy, handle parent) {
  1191. if (src == nullptr) return pybind11::none().inc_ref();
  1192. return StringCaster::cast(StringType(src), policy, parent);
  1193. }
  1194. static handle cast(CharT src, return_value_policy policy, handle parent) {
  1195. if (std::is_same<char, CharT>::value) {
  1196. handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
  1197. if (!s) throw error_already_set();
  1198. return s;
  1199. }
  1200. return StringCaster::cast(StringType(1, src), policy, parent);
  1201. }
  1202. operator CharT*() { return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str()); }
  1203. operator CharT&() {
  1204. if (none)
  1205. throw value_error("Cannot convert None to a character");
  1206. auto &value = static_cast<StringType &>(str_caster);
  1207. size_t str_len = value.size();
  1208. if (str_len == 0)
  1209. throw value_error("Cannot convert empty string to a character");
  1210. // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
  1211. // is too high, and one for multiple unicode characters (caught later), so we need to figure
  1212. // out how long the first encoded character is in bytes to distinguish between these two
  1213. // errors. We also allow want to allow unicode characters U+0080 through U+00FF, as those
  1214. // can fit into a single char value.
  1215. if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
  1216. auto v0 = static_cast<unsigned char>(value[0]);
  1217. size_t char0_bytes = !(v0 & 0x80) ? 1 : // low bits only: 0-127
  1218. (v0 & 0xE0) == 0xC0 ? 2 : // 0b110xxxxx - start of 2-byte sequence
  1219. (v0 & 0xF0) == 0xE0 ? 3 : // 0b1110xxxx - start of 3-byte sequence
  1220. 4; // 0b11110xxx - start of 4-byte sequence
  1221. if (char0_bytes == str_len) {
  1222. // If we have a 128-255 value, we can decode it into a single char:
  1223. if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
  1224. one_char = static_cast<CharT>(((v0 & 3) << 6) + (static_cast<unsigned char>(value[1]) & 0x3F));
  1225. return one_char;
  1226. }
  1227. // Otherwise we have a single character, but it's > U+00FF
  1228. throw value_error("Character code point not in range(0x100)");
  1229. }
  1230. }
  1231. // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
  1232. // surrogate pair with total length 2 instantly indicates a range error (but not a "your
  1233. // string was too long" error).
  1234. else if (StringCaster::UTF_N == 16 && str_len == 2) {
  1235. one_char = static_cast<CharT>(value[0]);
  1236. if (one_char >= 0xD800 && one_char < 0xE000)
  1237. throw value_error("Character code point not in range(0x10000)");
  1238. }
  1239. if (str_len != 1)
  1240. throw value_error("Expected a character, but multi-character string found");
  1241. one_char = value[0];
  1242. return one_char;
  1243. }
  1244. static constexpr auto name = _(PYBIND11_STRING_NAME);
  1245. template <typename _T> using cast_op_type = pybind11::detail::cast_op_type<_T>;
  1246. };
  1247. // Base implementation for std::tuple and std::pair
  1248. template <template<typename...> class Tuple, typename... Ts> class tuple_caster {
  1249. using type = Tuple<Ts...>;
  1250. static constexpr auto size = sizeof...(Ts);
  1251. using indices = make_index_sequence<size>;
  1252. public:
  1253. bool load(handle src, bool convert) {
  1254. if (!isinstance<sequence>(src))
  1255. return false;
  1256. const auto seq = reinterpret_borrow<sequence>(src);
  1257. if (seq.size() != size)
  1258. return false;
  1259. return load_impl(seq, convert, indices{});
  1260. }
  1261. template <typename T>
  1262. static handle cast(T &&src, return_value_policy policy, handle parent) {
  1263. return cast_impl(std::forward<T>(src), policy, parent, indices{});
  1264. }
  1265. // copied from the PYBIND11_TYPE_CASTER macro
  1266. template <typename T>
  1267. static handle cast(T *src, return_value_policy policy, handle parent) {
  1268. if (!src) return none().release();
  1269. if (policy == return_value_policy::take_ownership) {
  1270. auto h = cast(std::move(*src), policy, parent); delete src; return h;
  1271. } else {
  1272. return cast(*src, policy, parent);
  1273. }
  1274. }
  1275. static constexpr auto name = _("Tuple[") + concat(make_caster<Ts>::name...) + _("]");
  1276. template <typename T> using cast_op_type = type;
  1277. operator type() & { return implicit_cast(indices{}); }
  1278. operator type() && { return std::move(*this).implicit_cast(indices{}); }
  1279. protected:
  1280. template <size_t... Is>
  1281. type implicit_cast(index_sequence<Is...>) & { return type(cast_op<Ts>(std::get<Is>(subcasters))...); }
  1282. template <size_t... Is>
  1283. type implicit_cast(index_sequence<Is...>) && { return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...); }
  1284. static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
  1285. template <size_t... Is>
  1286. bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
  1287. #ifdef __cpp_fold_expressions
  1288. if ((... || !std::get<Is>(subcasters).load(seq[Is], convert)))
  1289. return false;
  1290. #else
  1291. for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...})
  1292. if (!r)
  1293. return false;
  1294. #endif
  1295. return true;
  1296. }
  1297. /* Implementation: Convert a C++ tuple into a Python tuple */
  1298. template <typename T, size_t... Is>
  1299. static handle cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
  1300. std::array<object, size> entries{{
  1301. reinterpret_steal<object>(make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...
  1302. }};
  1303. for (const auto &entry: entries)
  1304. if (!entry)
  1305. return handle();
  1306. tuple result(size);
  1307. int counter = 0;
  1308. for (auto & entry: entries)
  1309. PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
  1310. return result.release();
  1311. }
  1312. Tuple<make_caster<Ts>...> subcasters;
  1313. };
  1314. template <typename T1, typename T2> class type_caster<std::pair<T1, T2>>
  1315. : public tuple_caster<std::pair, T1, T2> {};
  1316. template <typename... Ts> class type_caster<std::tuple<Ts...>>
  1317. : public tuple_caster<std::tuple, Ts...> {};
  1318. /// Helper class which abstracts away certain actions. Users can provide specializations for
  1319. /// custom holders, but it's only necessary if the type has a non-standard interface.
  1320. template <typename T>
  1321. struct holder_helper {
  1322. static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
  1323. };
  1324. /// Type caster for holder types like std::shared_ptr, etc.
  1325. template <typename type, typename holder_type>
  1326. struct copyable_holder_caster : public type_caster_base<type> {
  1327. public:
  1328. using base = type_caster_base<type>;
  1329. static_assert(std::is_base_of<base, type_caster<type>>::value,
  1330. "Holder classes are only supported for custom types");
  1331. using base::base;
  1332. using base::cast;
  1333. using base::typeinfo;
  1334. using base::value;
  1335. bool load(handle src, bool convert) {
  1336. return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
  1337. }
  1338. explicit operator type*() { return this->value; }
  1339. // static_cast works around compiler error with MSVC 17 and CUDA 10.2
  1340. // see issue #2180
  1341. explicit operator type&() { return *(static_cast<type *>(this->value)); }
  1342. explicit operator holder_type*() { return std::addressof(holder); }
  1343. explicit operator holder_type&() { return holder; }
  1344. static handle cast(const holder_type &src, return_value_policy, handle) {
  1345. const auto *ptr = holder_helper<holder_type>::get(src);
  1346. return type_caster_base<type>::cast_holder(ptr, &src);
  1347. }
  1348. protected:
  1349. friend class type_caster_generic;
  1350. void check_holder_compat() {
  1351. if (typeinfo->default_holder)
  1352. throw cast_error("Unable to load a custom holder type from a default-holder instance");
  1353. }
  1354. bool load_value(value_and_holder &&v_h) {
  1355. if (v_h.holder_constructed()) {
  1356. value = v_h.value_ptr();
  1357. holder = v_h.template holder<holder_type>();
  1358. return true;
  1359. } else {
  1360. throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
  1361. #if defined(NDEBUG)
  1362. "(compile in debug mode for type information)");
  1363. #else
  1364. "of type '" + type_id<holder_type>() + "''");
  1365. #endif
  1366. }
  1367. }
  1368. template <typename T = holder_type, detail::enable_if_t<!std::is_constructible<T, const T &, type*>::value, int> = 0>
  1369. bool try_implicit_casts(handle, bool) { return false; }
  1370. template <typename T = holder_type, detail::enable_if_t<std::is_constructible<T, const T &, type*>::value, int> = 0>
  1371. bool try_implicit_casts(handle src, bool convert) {
  1372. for (auto &cast : typeinfo->implicit_casts) {
  1373. copyable_holder_caster sub_caster(*cast.first);
  1374. if (sub_caster.load(src, convert)) {
  1375. value = cast.second(sub_caster.value);
  1376. holder = holder_type(sub_caster.holder, (type *) value);
  1377. return true;
  1378. }
  1379. }
  1380. return false;
  1381. }
  1382. static bool try_direct_conversions(handle) { return false; }
  1383. holder_type holder;
  1384. };
  1385. /// Specialize for the common std::shared_ptr, so users don't need to
  1386. template <typename T>
  1387. class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> { };
  1388. template <typename type, typename holder_type>
  1389. struct move_only_holder_caster {
  1390. static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
  1391. "Holder classes are only supported for custom types");
  1392. static handle cast(holder_type &&src, return_value_policy, handle) {
  1393. auto *ptr = holder_helper<holder_type>::get(src);
  1394. return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
  1395. }
  1396. static constexpr auto name = type_caster_base<type>::name;
  1397. };
  1398. template <typename type, typename deleter>
  1399. class type_caster<std::unique_ptr<type, deleter>>
  1400. : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> { };
  1401. template <typename type, typename holder_type>
  1402. using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
  1403. copyable_holder_caster<type, holder_type>,
  1404. move_only_holder_caster<type, holder_type>>;
  1405. template <typename T, bool Value = false> struct always_construct_holder { static constexpr bool value = Value; };
  1406. /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
  1407. #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
  1408. namespace pybind11 { namespace detail { \
  1409. template <typename type> \
  1410. struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { }; \
  1411. template <typename type> \
  1412. class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
  1413. : public type_caster_holder<type, holder_type> { }; \
  1414. }}
  1415. // PYBIND11_DECLARE_HOLDER_TYPE holder types:
  1416. template <typename base, typename holder> struct is_holder_type :
  1417. std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
  1418. // Specialization for always-supported unique_ptr holders:
  1419. template <typename base, typename deleter> struct is_holder_type<base, std::unique_ptr<base, deleter>> :
  1420. std::true_type {};
  1421. template <typename T> struct handle_type_name { static constexpr auto name = _<T>(); };
  1422. template <> struct handle_type_name<bytes> { static constexpr auto name = _(PYBIND11_BYTES_NAME); };
  1423. template <> struct handle_type_name<int_> { static constexpr auto name = _("int"); };
  1424. template <> struct handle_type_name<iterable> { static constexpr auto name = _("Iterable"); };
  1425. template <> struct handle_type_name<iterator> { static constexpr auto name = _("Iterator"); };
  1426. template <> struct handle_type_name<none> { static constexpr auto name = _("None"); };
  1427. template <> struct handle_type_name<args> { static constexpr auto name = _("*args"); };
  1428. template <> struct handle_type_name<kwargs> { static constexpr auto name = _("**kwargs"); };
  1429. template <typename type>
  1430. struct pyobject_caster {
  1431. template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
  1432. bool load(handle src, bool /* convert */) { value = src; return static_cast<bool>(value); }
  1433. template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
  1434. bool load(handle src, bool /* convert */) {
  1435. if (!isinstance<type>(src))
  1436. return false;
  1437. value = reinterpret_borrow<type>(src);
  1438. return true;
  1439. }
  1440. static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
  1441. return src.inc_ref();
  1442. }
  1443. PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
  1444. };
  1445. template <typename T>
  1446. class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> { };
  1447. // Our conditions for enabling moving are quite restrictive:
  1448. // At compile time:
  1449. // - T needs to be a non-const, non-pointer, non-reference type
  1450. // - type_caster<T>::operator T&() must exist
  1451. // - the type must be move constructible (obviously)
  1452. // At run-time:
  1453. // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
  1454. // must have ref_count() == 1)h
  1455. // If any of the above are not satisfied, we fall back to copying.
  1456. template <typename T> using move_is_plain_type = satisfies_none_of<T,
  1457. std::is_void, std::is_pointer, std::is_reference, std::is_const
  1458. >;
  1459. template <typename T, typename SFINAE = void> struct move_always : std::false_type {};
  1460. template <typename T> struct move_always<T, enable_if_t<all_of<
  1461. move_is_plain_type<T>,
  1462. negation<is_copy_constructible<T>>,
  1463. std::is_move_constructible<T>,
  1464. std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
  1465. >::value>> : std::true_type {};
  1466. template <typename T, typename SFINAE = void> struct move_if_unreferenced : std::false_type {};
  1467. template <typename T> struct move_if_unreferenced<T, enable_if_t<all_of<
  1468. move_is_plain_type<T>,
  1469. negation<move_always<T>>,
  1470. std::is_move_constructible<T>,
  1471. std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
  1472. >::value>> : std::true_type {};
  1473. template <typename T> using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
  1474. // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
  1475. // reference or pointer to a local variable of the type_caster. Basically, only
  1476. // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
  1477. // everything else returns a reference/pointer to a local variable.
  1478. template <typename type> using cast_is_temporary_value_reference = bool_constant<
  1479. (std::is_reference<type>::value || std::is_pointer<type>::value) &&
  1480. !std::is_base_of<type_caster_generic, make_caster<type>>::value &&
  1481. !std::is_same<intrinsic_t<type>, void>::value
  1482. >;
  1483. // When a value returned from a C++ function is being cast back to Python, we almost always want to
  1484. // force `policy = move`, regardless of the return value policy the function/method was declared
  1485. // with.
  1486. template <typename Return, typename SFINAE = void> struct return_value_policy_override {
  1487. static return_value_policy policy(return_value_policy p) { return p; }
  1488. };
  1489. template <typename Return> struct return_value_policy_override<Return,
  1490. detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
  1491. static return_value_policy policy(return_value_policy p) {
  1492. return !std::is_lvalue_reference<Return>::value &&
  1493. !std::is_pointer<Return>::value
  1494. ? return_value_policy::move : p;
  1495. }
  1496. };
  1497. // Basic python -> C++ casting; throws if casting fails
  1498. template <typename T, typename SFINAE> type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
  1499. if (!conv.load(handle, true)) {
  1500. #if defined(NDEBUG)
  1501. throw cast_error("Unable to cast Python instance to C++ type (compile in debug mode for details)");
  1502. #else
  1503. throw cast_error("Unable to cast Python instance of type " +
  1504. (std::string) str(type::handle_of(handle)) + " to C++ type '" + type_id<T>() + "'");
  1505. #endif
  1506. }
  1507. return conv;
  1508. }
  1509. // Wrapper around the above that also constructs and returns a type_caster
  1510. template <typename T> make_caster<T> load_type(const handle &handle) {
  1511. make_caster<T> conv;
  1512. load_type(conv, handle);
  1513. return conv;
  1514. }
  1515. PYBIND11_NAMESPACE_END(detail)
  1516. // pytype -> C++ type
  1517. template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
  1518. T cast(const handle &handle) {
  1519. using namespace detail;
  1520. static_assert(!cast_is_temporary_value_reference<T>::value,
  1521. "Unable to cast type to reference: value is local to type caster");
  1522. return cast_op<T>(load_type<T>(handle));
  1523. }
  1524. // pytype -> pytype (calls converting constructor)
  1525. template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
  1526. T cast(const handle &handle) { return T(reinterpret_borrow<object>(handle)); }
  1527. // C++ type -> py::object
  1528. template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
  1529. object cast(T &&value, return_value_policy policy = return_value_policy::automatic_reference,
  1530. handle parent = handle()) {
  1531. using no_ref_T = typename std::remove_reference<T>::type;
  1532. if (policy == return_value_policy::automatic)
  1533. policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership :
  1534. std::is_lvalue_reference<T>::value ? return_value_policy::copy : return_value_policy::move;
  1535. else if (policy == return_value_policy::automatic_reference)
  1536. policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference :
  1537. std::is_lvalue_reference<T>::value ? return_value_policy::copy : return_value_policy::move;
  1538. return reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
  1539. }
  1540. template <typename T> T handle::cast() const { return pybind11::cast<T>(*this); }
  1541. template <> inline void handle::cast() const { return; }
  1542. template <typename T>
  1543. detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
  1544. if (obj.ref_count() > 1)
  1545. #if defined(NDEBUG)
  1546. throw cast_error("Unable to cast Python instance to C++ rvalue: instance has multiple references"
  1547. " (compile in debug mode for details)");
  1548. #else
  1549. throw cast_error("Unable to move from Python " + (std::string) str(type::handle_of(obj)) +
  1550. " instance to C++ " + type_id<T>() + " instance: instance has multiple references");
  1551. #endif
  1552. // Move into a temporary and return that, because the reference may be a local value of `conv`
  1553. T ret = std::move(detail::load_type<T>(obj).operator T&());
  1554. return ret;
  1555. }
  1556. // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
  1557. // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
  1558. // object has multiple references, but trying to copy will fail to compile.
  1559. // - If both movable and copyable, check ref count: if 1, move; otherwise copy
  1560. // - Otherwise (not movable), copy.
  1561. template <typename T> detail::enable_if_t<detail::move_always<T>::value, T> cast(object &&object) {
  1562. return move<T>(std::move(object));
  1563. }
  1564. template <typename T> detail::enable_if_t<detail::move_if_unreferenced<T>::value, T> cast(object &&object) {
  1565. if (object.ref_count() > 1)
  1566. return cast<T>(object);
  1567. else
  1568. return move<T>(std::move(object));
  1569. }
  1570. template <typename T> detail::enable_if_t<detail::move_never<T>::value, T> cast(object &&object) {
  1571. return cast<T>(object);
  1572. }
  1573. template <typename T> T object::cast() const & { return pybind11::cast<T>(*this); }
  1574. template <typename T> T object::cast() && { return pybind11::cast<T>(std::move(*this)); }
  1575. template <> inline void object::cast() const & { return; }
  1576. template <> inline void object::cast() && { return; }
  1577. PYBIND11_NAMESPACE_BEGIN(detail)
  1578. // Declared in pytypes.h:
  1579. template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
  1580. object object_or_cast(T &&o) { return pybind11::cast(std::forward<T>(o)); }
  1581. struct override_unused {}; // Placeholder type for the unneeded (and dead code) static variable in the PYBIND11_OVERRIDE_OVERRIDE macro
  1582. template <typename ret_type> using override_caster_t = conditional_t<
  1583. cast_is_temporary_value_reference<ret_type>::value, make_caster<ret_type>, override_unused>;
  1584. // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
  1585. // store the result in the given variable. For other types, this is a no-op.
  1586. template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o, make_caster<T> &caster) {
  1587. return cast_op<T>(load_type(caster, o));
  1588. }
  1589. template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&, override_unused &) {
  1590. pybind11_fail("Internal error: cast_ref fallback invoked"); }
  1591. // Trampoline use: Having a pybind11::cast with an invalid reference type is going to static_assert, even
  1592. // though if it's in dead code, so we provide a "trampoline" to pybind11::cast that only does anything in
  1593. // cases where pybind11::cast is valid.
  1594. template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&o) {
  1595. return pybind11::cast<T>(std::move(o)); }
  1596. template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
  1597. pybind11_fail("Internal error: cast_safe fallback invoked"); }
  1598. template <> inline void cast_safe<void>(object &&) {}
  1599. PYBIND11_NAMESPACE_END(detail)
  1600. template <return_value_policy policy = return_value_policy::automatic_reference>
  1601. tuple make_tuple() { return tuple(0); }
  1602. template <return_value_policy policy = return_value_policy::automatic_reference,
  1603. typename... Args> tuple make_tuple(Args&&... args_) {
  1604. constexpr size_t size = sizeof...(Args);
  1605. std::array<object, size> args {
  1606. { reinterpret_steal<object>(detail::make_caster<Args>::cast(
  1607. std::forward<Args>(args_), policy, nullptr))... }
  1608. };
  1609. for (size_t i = 0; i < args.size(); i++) {
  1610. if (!args[i]) {
  1611. #if defined(NDEBUG)
  1612. throw cast_error("make_tuple(): unable to convert arguments to Python object (compile in debug mode for details)");
  1613. #else
  1614. std::array<std::string, size> argtypes { {type_id<Args>()...} };
  1615. throw cast_error("make_tuple(): unable to convert argument of type '" +
  1616. argtypes[i] + "' to Python object");
  1617. #endif
  1618. }
  1619. }
  1620. tuple result(size);
  1621. int counter = 0;
  1622. for (auto &arg_value : args)
  1623. PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
  1624. return result;
  1625. }
  1626. /// \ingroup annotations
  1627. /// Annotation for arguments
  1628. struct arg {
  1629. /// Constructs an argument with the name of the argument; if null or omitted, this is a positional argument.
  1630. constexpr explicit arg(const char *name = nullptr) : name(name), flag_noconvert(false), flag_none(true) { }
  1631. /// Assign a value to this argument
  1632. template <typename T> arg_v operator=(T &&value) const;
  1633. /// Indicate that the type should not be converted in the type caster
  1634. arg &noconvert(bool flag = true) { flag_noconvert = flag; return *this; }
  1635. /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
  1636. arg &none(bool flag = true) { flag_none = flag; return *this; }
  1637. const char *name; ///< If non-null, this is a named kwargs argument
  1638. bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type caster!)
  1639. bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
  1640. };
  1641. /// \ingroup annotations
  1642. /// Annotation for arguments with values
  1643. struct arg_v : arg {
  1644. private:
  1645. template <typename T>
  1646. arg_v(arg &&base, T &&x, const char *descr = nullptr)
  1647. : arg(base),
  1648. value(reinterpret_steal<object>(
  1649. detail::make_caster<T>::cast(x, return_value_policy::automatic, {})
  1650. )),
  1651. descr(descr)
  1652. #if !defined(NDEBUG)
  1653. , type(type_id<T>())
  1654. #endif
  1655. {
  1656. // Workaround! See:
  1657. // https://github.com/pybind/pybind11/issues/2336
  1658. // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
  1659. if (PyErr_Occurred()) {
  1660. PyErr_Clear();
  1661. }
  1662. }
  1663. public:
  1664. /// Direct construction with name, default, and description
  1665. template <typename T>
  1666. arg_v(const char *name, T &&x, const char *descr = nullptr)
  1667. : arg_v(arg(name), std::forward<T>(x), descr) { }
  1668. /// Called internally when invoking `py::arg("a") = value`
  1669. template <typename T>
  1670. arg_v(const arg &base, T &&x, const char *descr = nullptr)
  1671. : arg_v(arg(base), std::forward<T>(x), descr) { }
  1672. /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
  1673. arg_v &noconvert(bool flag = true) { arg::noconvert(flag); return *this; }
  1674. /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
  1675. arg_v &none(bool flag = true) { arg::none(flag); return *this; }
  1676. /// The default value
  1677. object value;
  1678. /// The (optional) description of the default value
  1679. const char *descr;
  1680. #if !defined(NDEBUG)
  1681. /// The C++ type name of the default value (only available when compiled in debug mode)
  1682. std::string type;
  1683. #endif
  1684. };
  1685. /// \ingroup annotations
  1686. /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of an
  1687. /// unnamed '*' argument (in Python 3)
  1688. struct kw_only {};
  1689. /// \ingroup annotations
  1690. /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of an
  1691. /// unnamed '/' argument (in Python 3.8)
  1692. struct pos_only {};
  1693. template <typename T>
  1694. arg_v arg::operator=(T &&value) const { return {std::move(*this), std::forward<T>(value)}; }
  1695. /// Alias for backward compatibility -- to be removed in version 2.0
  1696. template <typename /*unused*/> using arg_t = arg_v;
  1697. inline namespace literals {
  1698. /** \rst
  1699. String literal version of `arg`
  1700. \endrst */
  1701. constexpr arg operator"" _a(const char *name, size_t) { return arg(name); }
  1702. } // namespace literals
  1703. PYBIND11_NAMESPACE_BEGIN(detail)
  1704. // forward declaration (definition in attr.h)
  1705. struct function_record;
  1706. /// Internal data associated with a single function call
  1707. struct function_call {
  1708. function_call(const function_record &f, handle p); // Implementation in attr.h
  1709. /// The function data:
  1710. const function_record &func;
  1711. /// Arguments passed to the function:
  1712. std::vector<handle> args;
  1713. /// The `convert` value the arguments should be loaded with
  1714. std::vector<bool> args_convert;
  1715. /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
  1716. /// present, are also in `args` but without a reference).
  1717. object args_ref, kwargs_ref;
  1718. /// The parent, if any
  1719. handle parent;
  1720. /// If this is a call to an initializer, this argument contains `self`
  1721. handle init_self;
  1722. };
  1723. /// Helper class which loads arguments for C++ functions called from Python
  1724. template <typename... Args>
  1725. class argument_loader {
  1726. using indices = make_index_sequence<sizeof...(Args)>;
  1727. template <typename Arg> using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
  1728. template <typename Arg> using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
  1729. // Get args/kwargs argument positions relative to the end of the argument list:
  1730. static constexpr auto args_pos = constexpr_first<argument_is_args, Args...>() - (int) sizeof...(Args),
  1731. kwargs_pos = constexpr_first<argument_is_kwargs, Args...>() - (int) sizeof...(Args);
  1732. static constexpr bool args_kwargs_are_last = kwargs_pos >= - 1 && args_pos >= kwargs_pos - 1;
  1733. static_assert(args_kwargs_are_last, "py::args/py::kwargs are only permitted as the last argument(s) of a function");
  1734. public:
  1735. static constexpr bool has_kwargs = kwargs_pos < 0;
  1736. static constexpr bool has_args = args_pos < 0;
  1737. static constexpr auto arg_names = concat(type_descr(make_caster<Args>::name)...);
  1738. bool load_args(function_call &call) {
  1739. return load_impl_sequence(call, indices{});
  1740. }
  1741. template <typename Return, typename Guard, typename Func>
  1742. enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
  1743. return std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
  1744. }
  1745. template <typename Return, typename Guard, typename Func>
  1746. enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
  1747. std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
  1748. return void_type();
  1749. }
  1750. private:
  1751. static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
  1752. template <size_t... Is>
  1753. bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
  1754. #ifdef __cpp_fold_expressions
  1755. if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])))
  1756. return false;
  1757. #else
  1758. for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...})
  1759. if (!r)
  1760. return false;
  1761. #endif
  1762. return true;
  1763. }
  1764. template <typename Return, typename Func, size_t... Is, typename Guard>
  1765. Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
  1766. return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
  1767. }
  1768. std::tuple<make_caster<Args>...> argcasters;
  1769. };
  1770. /// Helper class which collects only positional arguments for a Python function call.
  1771. /// A fancier version below can collect any argument, but this one is optimal for simple calls.
  1772. template <return_value_policy policy>
  1773. class simple_collector {
  1774. public:
  1775. template <typename... Ts>
  1776. explicit simple_collector(Ts &&...values)
  1777. : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) { }
  1778. const tuple &args() const & { return m_args; }
  1779. dict kwargs() const { return {}; }
  1780. tuple args() && { return std::move(m_args); }
  1781. /// Call a Python function and pass the collected arguments
  1782. object call(PyObject *ptr) const {
  1783. PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
  1784. if (!result)
  1785. throw error_already_set();
  1786. return reinterpret_steal<object>(result);
  1787. }
  1788. private:
  1789. tuple m_args;
  1790. };
  1791. /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
  1792. template <return_value_policy policy>
  1793. class unpacking_collector {
  1794. public:
  1795. template <typename... Ts>
  1796. explicit unpacking_collector(Ts &&...values) {
  1797. // Tuples aren't (easily) resizable so a list is needed for collection,
  1798. // but the actual function call strictly requires a tuple.
  1799. auto args_list = list();
  1800. int _[] = { 0, (process(args_list, std::forward<Ts>(values)), 0)... };
  1801. ignore_unused(_);
  1802. m_args = std::move(args_list);
  1803. }
  1804. const tuple &args() const & { return m_args; }
  1805. const dict &kwargs() const & { return m_kwargs; }
  1806. tuple args() && { return std::move(m_args); }
  1807. dict kwargs() && { return std::move(m_kwargs); }
  1808. /// Call a Python function and pass the collected arguments
  1809. object call(PyObject *ptr) const {
  1810. PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
  1811. if (!result)
  1812. throw error_already_set();
  1813. return reinterpret_steal<object>(result);
  1814. }
  1815. private:
  1816. template <typename T>
  1817. void process(list &args_list, T &&x) {
  1818. auto o = reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
  1819. if (!o) {
  1820. #if defined(NDEBUG)
  1821. argument_cast_error();
  1822. #else
  1823. argument_cast_error(std::to_string(args_list.size()), type_id<T>());
  1824. #endif
  1825. }
  1826. args_list.append(o);
  1827. }
  1828. void process(list &args_list, detail::args_proxy ap) {
  1829. for (auto a : ap)
  1830. args_list.append(a);
  1831. }
  1832. void process(list &/*args_list*/, arg_v a) {
  1833. if (!a.name)
  1834. #if defined(NDEBUG)
  1835. nameless_argument_error();
  1836. #else
  1837. nameless_argument_error(a.type);
  1838. #endif
  1839. if (m_kwargs.contains(a.name)) {
  1840. #if defined(NDEBUG)
  1841. multiple_values_error();
  1842. #else
  1843. multiple_values_error(a.name);
  1844. #endif
  1845. }
  1846. if (!a.value) {
  1847. #if defined(NDEBUG)
  1848. argument_cast_error();
  1849. #else
  1850. argument_cast_error(a.name, a.type);
  1851. #endif
  1852. }
  1853. m_kwargs[a.name] = a.value;
  1854. }
  1855. void process(list &/*args_list*/, detail::kwargs_proxy kp) {
  1856. if (!kp)
  1857. return;
  1858. for (auto k : reinterpret_borrow<dict>(kp)) {
  1859. if (m_kwargs.contains(k.first)) {
  1860. #if defined(NDEBUG)
  1861. multiple_values_error();
  1862. #else
  1863. multiple_values_error(str(k.first));
  1864. #endif
  1865. }
  1866. m_kwargs[k.first] = k.second;
  1867. }
  1868. }
  1869. [[noreturn]] static void nameless_argument_error() {
  1870. throw type_error("Got kwargs without a name; only named arguments "
  1871. "may be passed via py::arg() to a python function call. "
  1872. "(compile in debug mode for details)");
  1873. }
  1874. [[noreturn]] static void nameless_argument_error(std::string type) {
  1875. throw type_error("Got kwargs without a name of type '" + type + "'; only named "
  1876. "arguments may be passed via py::arg() to a python function call. ");
  1877. }
  1878. [[noreturn]] static void multiple_values_error() {
  1879. throw type_error("Got multiple values for keyword argument "
  1880. "(compile in debug mode for details)");
  1881. }
  1882. [[noreturn]] static void multiple_values_error(std::string name) {
  1883. throw type_error("Got multiple values for keyword argument '" + name + "'");
  1884. }
  1885. [[noreturn]] static void argument_cast_error() {
  1886. throw cast_error("Unable to convert call argument to Python object "
  1887. "(compile in debug mode for details)");
  1888. }
  1889. [[noreturn]] static void argument_cast_error(std::string name, std::string type) {
  1890. throw cast_error("Unable to convert call argument '" + name
  1891. + "' of type '" + type + "' to Python object");
  1892. }
  1893. private:
  1894. tuple m_args;
  1895. dict m_kwargs;
  1896. };
  1897. // [workaround(intel)] Separate function required here
  1898. // We need to put this into a separate function because the Intel compiler
  1899. // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
  1900. // (tested with ICC 2021.1 Beta 20200827).
  1901. template <typename... Args>
  1902. constexpr bool args_are_all_positional()
  1903. {
  1904. return all_of<is_positional<Args>...>::value;
  1905. }
  1906. /// Collect only positional arguments for a Python function call
  1907. template <return_value_policy policy, typename... Args,
  1908. typename = enable_if_t<args_are_all_positional<Args...>()>>
  1909. simple_collector<policy> collect_arguments(Args &&...args) {
  1910. return simple_collector<policy>(std::forward<Args>(args)...);
  1911. }
  1912. /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
  1913. template <return_value_policy policy, typename... Args,
  1914. typename = enable_if_t<!args_are_all_positional<Args...>()>>
  1915. unpacking_collector<policy> collect_arguments(Args &&...args) {
  1916. // Following argument order rules for generalized unpacking according to PEP 448
  1917. static_assert(
  1918. constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>()
  1919. && constexpr_last<is_s_unpacking, Args...>() < constexpr_first<is_ds_unpacking, Args...>(),
  1920. "Invalid function call: positional args must precede keywords and ** unpacking; "
  1921. "* unpacking must precede ** unpacking"
  1922. );
  1923. return unpacking_collector<policy>(std::forward<Args>(args)...);
  1924. }
  1925. template <typename Derived>
  1926. template <return_value_policy policy, typename... Args>
  1927. object object_api<Derived>::operator()(Args &&...args) const {
  1928. return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
  1929. }
  1930. template <typename Derived>
  1931. template <return_value_policy policy, typename... Args>
  1932. object object_api<Derived>::call(Args &&...args) const {
  1933. return operator()<policy>(std::forward<Args>(args)...);
  1934. }
  1935. PYBIND11_NAMESPACE_END(detail)
  1936. template<typename T>
  1937. handle type::handle_of() {
  1938. static_assert(
  1939. std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
  1940. "py::type::of<T> only supports the case where T is a registered C++ types."
  1941. );
  1942. return detail::get_type_handle(typeid(T), true);
  1943. }
  1944. #define PYBIND11_MAKE_OPAQUE(...) \
  1945. namespace pybind11 { namespace detail { \
  1946. template<> class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> { }; \
  1947. }}
  1948. /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
  1949. /// typedef, e.g.: `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
  1950. #define PYBIND11_TYPE(...) __VA_ARGS__
  1951. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)