pybind11.h 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858
  1. /*
  2. pybind11/pybind11.h: Main header file of the C++11 python
  3. binding generator library
  4. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #pragma once
  9. #include "detail/class.h"
  10. #include "detail/init.h"
  11. #include "attr.h"
  12. #include "gil.h"
  13. #include "options.h"
  14. #include <cstdlib>
  15. #include <cstring>
  16. #include <memory>
  17. #include <new>
  18. #include <string>
  19. #include <utility>
  20. #include <vector>
  21. #if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914))
  22. # define PYBIND11_STD_LAUNDER std::launder
  23. # define PYBIND11_HAS_STD_LAUNDER 1
  24. #else
  25. # define PYBIND11_STD_LAUNDER
  26. # define PYBIND11_HAS_STD_LAUNDER 0
  27. #endif
  28. #if defined(__GNUG__) && !defined(__clang__)
  29. # include <cxxabi.h>
  30. #endif
  31. /* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning
  32. This warning is about ABI compatibility, not code health.
  33. It is only actually needed in a couple places, but apparently GCC 7 "generates this warning if
  34. and only if the first template instantiation ... involves noexcept" [stackoverflow], therefore
  35. it could get triggered from seemingly random places, depending on user code.
  36. No other GCC version generates this warning.
  37. */
  38. #if defined(__GNUC__) && __GNUC__ == 7
  39. # pragma GCC diagnostic push
  40. # pragma GCC diagnostic ignored "-Wnoexcept-type"
  41. #endif
  42. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  43. PYBIND11_NAMESPACE_BEGIN(detail)
  44. // Apply all the extensions translators from a list
  45. // Return true if one of the translators completed without raising an exception
  46. // itself. Return of false indicates that if there are other translators
  47. // available, they should be tried.
  48. inline bool apply_exception_translators(std::forward_list<ExceptionTranslator> &translators) {
  49. auto last_exception = std::current_exception();
  50. for (auto &translator : translators) {
  51. try {
  52. translator(last_exception);
  53. return true;
  54. } catch (...) {
  55. last_exception = std::current_exception();
  56. }
  57. }
  58. return false;
  59. }
  60. #if defined(_MSC_VER)
  61. # define PYBIND11_COMPAT_STRDUP _strdup
  62. #else
  63. # define PYBIND11_COMPAT_STRDUP strdup
  64. #endif
  65. PYBIND11_NAMESPACE_END(detail)
  66. /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
  67. class cpp_function : public function {
  68. public:
  69. cpp_function() = default;
  70. // NOLINTNEXTLINE(google-explicit-constructor)
  71. cpp_function(std::nullptr_t) {}
  72. /// Construct a cpp_function from a vanilla function pointer
  73. template <typename Return, typename... Args, typename... Extra>
  74. // NOLINTNEXTLINE(google-explicit-constructor)
  75. cpp_function(Return (*f)(Args...), const Extra &...extra) {
  76. initialize(f, f, extra...);
  77. }
  78. /// Construct a cpp_function from a lambda function (possibly with internal state)
  79. template <typename Func,
  80. typename... Extra,
  81. typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
  82. // NOLINTNEXTLINE(google-explicit-constructor)
  83. cpp_function(Func &&f, const Extra &...extra) {
  84. initialize(
  85. std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...);
  86. }
  87. /// Construct a cpp_function from a class method (non-const, no ref-qualifier)
  88. template <typename Return, typename Class, typename... Arg, typename... Extra>
  89. // NOLINTNEXTLINE(google-explicit-constructor)
  90. cpp_function(Return (Class::*f)(Arg...), const Extra &...extra) {
  91. initialize(
  92. [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
  93. (Return(*)(Class *, Arg...)) nullptr,
  94. extra...);
  95. }
  96. /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier)
  97. /// A copy of the overload for non-const functions without explicit ref-qualifier
  98. /// but with an added `&`.
  99. template <typename Return, typename Class, typename... Arg, typename... Extra>
  100. // NOLINTNEXTLINE(google-explicit-constructor)
  101. cpp_function(Return (Class::*f)(Arg...) &, const Extra &...extra) {
  102. initialize(
  103. [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
  104. (Return(*)(Class *, Arg...)) nullptr,
  105. extra...);
  106. }
  107. /// Construct a cpp_function from a class method (const, no ref-qualifier)
  108. template <typename Return, typename Class, typename... Arg, typename... Extra>
  109. // NOLINTNEXTLINE(google-explicit-constructor)
  110. cpp_function(Return (Class::*f)(Arg...) const, const Extra &...extra) {
  111. initialize([f](const Class *c,
  112. Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
  113. (Return(*)(const Class *, Arg...)) nullptr,
  114. extra...);
  115. }
  116. /// Construct a cpp_function from a class method (const, lvalue ref-qualifier)
  117. /// A copy of the overload for const functions without explicit ref-qualifier
  118. /// but with an added `&`.
  119. template <typename Return, typename Class, typename... Arg, typename... Extra>
  120. // NOLINTNEXTLINE(google-explicit-constructor)
  121. cpp_function(Return (Class::*f)(Arg...) const &, const Extra &...extra) {
  122. initialize([f](const Class *c,
  123. Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
  124. (Return(*)(const Class *, Arg...)) nullptr,
  125. extra...);
  126. }
  127. /// Return the function name
  128. object name() const { return attr("__name__"); }
  129. protected:
  130. struct InitializingFunctionRecordDeleter {
  131. // `destruct(function_record, false)`: `initialize_generic` copies strings and
  132. // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`.
  133. void operator()(detail::function_record *rec) { destruct(rec, false); }
  134. };
  135. using unique_function_record
  136. = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
  137. /// Space optimization: don't inline this frequently instantiated fragment
  138. PYBIND11_NOINLINE unique_function_record make_function_record() {
  139. return unique_function_record(new detail::function_record());
  140. }
  141. /// Special internal constructor for functors, lambda functions, etc.
  142. template <typename Func, typename Return, typename... Args, typename... Extra>
  143. void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) {
  144. using namespace detail;
  145. struct capture {
  146. remove_reference_t<Func> f;
  147. };
  148. /* Store the function including any extra state it might have (e.g. a lambda capture
  149. * object) */
  150. // The unique_ptr makes sure nothing is leaked in case of an exception.
  151. auto unique_rec = make_function_record();
  152. auto *rec = unique_rec.get();
  153. /* Store the capture object directly in the function record if there is enough space */
  154. if (PYBIND11_SILENCE_MSVC_C4127(sizeof(capture) <= sizeof(rec->data))) {
  155. /* Without these pragmas, GCC warns that there might not be
  156. enough space to use the placement new operator. However, the
  157. 'if' statement above ensures that this is the case. */
  158. #if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER)
  159. # pragma GCC diagnostic push
  160. # pragma GCC diagnostic ignored "-Wplacement-new"
  161. #endif
  162. new ((capture *) &rec->data) capture{std::forward<Func>(f)};
  163. #if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER)
  164. # pragma GCC diagnostic pop
  165. #endif
  166. #if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER)
  167. # pragma GCC diagnostic push
  168. # pragma GCC diagnostic ignored "-Wstrict-aliasing"
  169. #endif
  170. // UB without std::launder, but without breaking ABI and/or
  171. // a significant refactoring it's "impossible" to solve.
  172. if (!std::is_trivially_destructible<capture>::value) {
  173. rec->free_data = [](function_record *r) {
  174. auto data = PYBIND11_STD_LAUNDER((capture *) &r->data);
  175. (void) data;
  176. data->~capture();
  177. };
  178. }
  179. #if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER)
  180. # pragma GCC diagnostic pop
  181. #endif
  182. } else {
  183. rec->data[0] = new capture{std::forward<Func>(f)};
  184. rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
  185. }
  186. /* Type casters for the function arguments and return value */
  187. using cast_in = argument_loader<Args...>;
  188. using cast_out
  189. = make_caster<conditional_t<std::is_void<Return>::value, void_type, Return>>;
  190. static_assert(
  191. expected_num_args<Extra...>(
  192. sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
  193. "The number of argument annotations does not match the number of function arguments");
  194. /* Dispatch code which converts function arguments and performs the actual function call */
  195. rec->impl = [](function_call &call) -> handle {
  196. cast_in args_converter;
  197. /* Try to cast the function arguments into the C++ domain */
  198. if (!args_converter.load_args(call)) {
  199. return PYBIND11_TRY_NEXT_OVERLOAD;
  200. }
  201. /* Invoke call policy pre-call hook */
  202. process_attributes<Extra...>::precall(call);
  203. /* Get a pointer to the capture object */
  204. const auto *data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data
  205. : call.func.data[0]);
  206. auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
  207. /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
  208. return_value_policy policy
  209. = return_value_policy_override<Return>::policy(call.func.policy);
  210. /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
  211. using Guard = extract_guard_t<Extra...>;
  212. /* Perform the function call */
  213. handle result
  214. = cast_out::cast(std::move(args_converter).template call<Return, Guard>(cap->f),
  215. policy,
  216. call.parent);
  217. /* Invoke call policy post-call hook */
  218. process_attributes<Extra...>::postcall(call, result);
  219. return result;
  220. };
  221. rec->nargs_pos = cast_in::args_pos >= 0
  222. ? static_cast<std::uint16_t>(cast_in::args_pos)
  223. : sizeof...(Args) - cast_in::has_kwargs; // Will get reduced more if
  224. // we have a kw_only
  225. rec->has_args = cast_in::args_pos >= 0;
  226. rec->has_kwargs = cast_in::has_kwargs;
  227. /* Process any user-provided function attributes */
  228. process_attributes<Extra...>::init(extra..., rec);
  229. {
  230. constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
  231. has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
  232. has_arg_annotations = any_of<is_keyword<Extra>...>::value;
  233. static_assert(has_arg_annotations || !has_kw_only_args,
  234. "py::kw_only requires the use of argument annotations");
  235. static_assert(has_arg_annotations || !has_pos_only_args,
  236. "py::pos_only requires the use of argument annotations (for docstrings "
  237. "and aligning the annotations to the argument)");
  238. static_assert(constexpr_sum(is_kw_only<Extra>::value...) <= 1,
  239. "py::kw_only may be specified only once");
  240. static_assert(constexpr_sum(is_pos_only<Extra>::value...) <= 1,
  241. "py::pos_only may be specified only once");
  242. constexpr auto kw_only_pos = constexpr_first<is_kw_only, Extra...>();
  243. constexpr auto pos_only_pos = constexpr_first<is_pos_only, Extra...>();
  244. static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
  245. "py::pos_only must come before py::kw_only");
  246. }
  247. /* Generate a readable signature describing the function's arguments and return
  248. value types */
  249. static constexpr auto signature
  250. = const_name("(") + cast_in::arg_names + const_name(") -> ") + cast_out::name;
  251. PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
  252. /* Register the function with Python from generic (non-templated) code */
  253. // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid.
  254. initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));
  255. /* Stash some additional information used by an important optimization in 'functional.h' */
  256. using FunctionType = Return (*)(Args...);
  257. constexpr bool is_function_ptr
  258. = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *);
  259. if (is_function_ptr) {
  260. rec->is_stateless = true;
  261. rec->data[1]
  262. = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
  263. }
  264. }
  265. // Utility class that keeps track of all duplicated strings, and cleans them up in its
  266. // destructor, unless they are released. Basically a RAII-solution to deal with exceptions
  267. // along the way.
  268. class strdup_guard {
  269. public:
  270. strdup_guard() = default;
  271. strdup_guard(const strdup_guard &) = delete;
  272. strdup_guard &operator=(const strdup_guard &) = delete;
  273. ~strdup_guard() {
  274. for (auto *s : strings) {
  275. std::free(s);
  276. }
  277. }
  278. char *operator()(const char *s) {
  279. auto *t = PYBIND11_COMPAT_STRDUP(s);
  280. strings.push_back(t);
  281. return t;
  282. }
  283. void release() { strings.clear(); }
  284. private:
  285. std::vector<char *> strings;
  286. };
  287. /// Register a function call with Python (generic non-templated code goes here)
  288. void initialize_generic(unique_function_record &&unique_rec,
  289. const char *text,
  290. const std::type_info *const *types,
  291. size_t args) {
  292. // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr,
  293. // we do not want this to destruct the pointer. `initialize` (the caller) still relies on
  294. // the pointee being alive after this call. Only move out if a `capsule` is going to keep
  295. // it alive.
  296. auto *rec = unique_rec.get();
  297. // Keep track of strdup'ed strings, and clean them up as long as the function's capsule
  298. // has not taken ownership yet (when `unique_rec.release()` is called).
  299. // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the
  300. // strings are only referenced before strdup'ing. So only *after* the following block could
  301. // `destruct` safely be called, but even then, `repr` could still throw in the middle of
  302. // copying all strings.
  303. strdup_guard guarded_strdup;
  304. /* Create copies of all referenced C-style strings */
  305. rec->name = guarded_strdup(rec->name ? rec->name : "");
  306. if (rec->doc) {
  307. rec->doc = guarded_strdup(rec->doc);
  308. }
  309. for (auto &a : rec->args) {
  310. if (a.name) {
  311. a.name = guarded_strdup(a.name);
  312. }
  313. if (a.descr) {
  314. a.descr = guarded_strdup(a.descr);
  315. } else if (a.value) {
  316. a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());
  317. }
  318. }
  319. rec->is_constructor = (std::strcmp(rec->name, "__init__") == 0)
  320. || (std::strcmp(rec->name, "__setstate__") == 0);
  321. #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
  322. if (rec->is_constructor && !rec->is_new_style_constructor) {
  323. const auto class_name
  324. = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
  325. const auto func_name = std::string(rec->name);
  326. PyErr_WarnEx(PyExc_FutureWarning,
  327. ("pybind11-bound class '" + class_name
  328. + "' is using an old-style "
  329. "placement-new '"
  330. + func_name
  331. + "' which has been deprecated. See "
  332. "the upgrade guide in pybind11's docs. This message is only visible "
  333. "when compiled in debug mode.")
  334. .c_str(),
  335. 0);
  336. }
  337. #endif
  338. /* Generate a proper function signature */
  339. std::string signature;
  340. size_t type_index = 0, arg_index = 0;
  341. bool is_starred = false;
  342. for (const auto *pc = text; *pc != '\0'; ++pc) {
  343. const auto c = *pc;
  344. if (c == '{') {
  345. // Write arg name for everything except *args and **kwargs.
  346. is_starred = *(pc + 1) == '*';
  347. if (is_starred) {
  348. continue;
  349. }
  350. // Separator for keyword-only arguments, placed before the kw
  351. // arguments start (unless we are already putting an *args)
  352. if (!rec->has_args && arg_index == rec->nargs_pos) {
  353. signature += "*, ";
  354. }
  355. if (arg_index < rec->args.size() && rec->args[arg_index].name) {
  356. signature += rec->args[arg_index].name;
  357. } else if (arg_index == 0 && rec->is_method) {
  358. signature += "self";
  359. } else {
  360. signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
  361. }
  362. signature += ": ";
  363. } else if (c == '}') {
  364. // Write default value if available.
  365. if (!is_starred && arg_index < rec->args.size() && rec->args[arg_index].descr) {
  366. signature += " = ";
  367. signature += rec->args[arg_index].descr;
  368. }
  369. // Separator for positional-only arguments (placed after the
  370. // argument, rather than before like *
  371. if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
  372. signature += ", /";
  373. }
  374. if (!is_starred) {
  375. arg_index++;
  376. }
  377. } else if (c == '%') {
  378. const std::type_info *t = types[type_index++];
  379. if (!t) {
  380. pybind11_fail("Internal error while parsing type signature (1)");
  381. }
  382. if (auto *tinfo = detail::get_type_info(*t)) {
  383. handle th((PyObject *) tinfo->type);
  384. signature += th.attr("__module__").cast<std::string>() + "."
  385. + th.attr("__qualname__").cast<std::string>();
  386. } else if (rec->is_new_style_constructor && arg_index == 0) {
  387. // A new-style `__init__` takes `self` as `value_and_holder`.
  388. // Rewrite it to the proper class type.
  389. signature += rec->scope.attr("__module__").cast<std::string>() + "."
  390. + rec->scope.attr("__qualname__").cast<std::string>();
  391. } else {
  392. std::string tname(t->name());
  393. detail::clean_type_id(tname);
  394. signature += tname;
  395. }
  396. } else {
  397. signature += c;
  398. }
  399. }
  400. if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] != nullptr) {
  401. pybind11_fail("Internal error while parsing type signature (2)");
  402. }
  403. rec->signature = guarded_strdup(signature.c_str());
  404. rec->args.shrink_to_fit();
  405. rec->nargs = (std::uint16_t) args;
  406. if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) {
  407. rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
  408. }
  409. detail::function_record *chain = nullptr, *chain_start = rec;
  410. if (rec->sibling) {
  411. if (PyCFunction_Check(rec->sibling.ptr())) {
  412. auto *self = PyCFunction_GET_SELF(rec->sibling.ptr());
  413. capsule rec_capsule = isinstance<capsule>(self) ? reinterpret_borrow<capsule>(self)
  414. : capsule(self);
  415. chain = (detail::function_record *) rec_capsule;
  416. /* Never append a method to an overload chain of a parent class;
  417. instead, hide the parent's overloads in this case */
  418. if (!chain->scope.is(rec->scope)) {
  419. chain = nullptr;
  420. }
  421. }
  422. // Don't trigger for things like the default __init__, which are wrapper_descriptors
  423. // that we are intentionally replacing
  424. else if (!rec->sibling.is_none() && rec->name[0] != '_') {
  425. pybind11_fail("Cannot overload existing non-function object \""
  426. + std::string(rec->name) + "\" with a function of the same name");
  427. }
  428. }
  429. if (!chain) {
  430. /* No existing overload was found, create a new function object */
  431. rec->def = new PyMethodDef();
  432. std::memset(rec->def, 0, sizeof(PyMethodDef));
  433. rec->def->ml_name = rec->name;
  434. rec->def->ml_meth
  435. = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher));
  436. rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
  437. capsule rec_capsule(unique_rec.release(),
  438. [](void *ptr) { destruct((detail::function_record *) ptr); });
  439. guarded_strdup.release();
  440. object scope_module;
  441. if (rec->scope) {
  442. if (hasattr(rec->scope, "__module__")) {
  443. scope_module = rec->scope.attr("__module__");
  444. } else if (hasattr(rec->scope, "__name__")) {
  445. scope_module = rec->scope.attr("__name__");
  446. }
  447. }
  448. m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
  449. if (!m_ptr) {
  450. pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
  451. }
  452. } else {
  453. /* Append at the beginning or end of the overload chain */
  454. m_ptr = rec->sibling.ptr();
  455. inc_ref();
  456. if (chain->is_method != rec->is_method) {
  457. pybind11_fail(
  458. "overloading a method with both static and instance methods is not supported; "
  459. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  460. "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more "
  461. "details"
  462. #else
  463. "error while attempting to bind "
  464. + std::string(rec->is_method ? "instance" : "static") + " method "
  465. + std::string(pybind11::str(rec->scope.attr("__name__"))) + "."
  466. + std::string(rec->name) + signature
  467. #endif
  468. );
  469. }
  470. if (rec->prepend) {
  471. // Beginning of chain; we need to replace the capsule's current head-of-the-chain
  472. // pointer with this one, then make this one point to the previous head of the
  473. // chain.
  474. chain_start = rec;
  475. rec->next = chain;
  476. auto rec_capsule
  477. = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self);
  478. rec_capsule.set_pointer(unique_rec.release());
  479. guarded_strdup.release();
  480. } else {
  481. // Or end of chain (normal behavior)
  482. chain_start = chain;
  483. while (chain->next) {
  484. chain = chain->next;
  485. }
  486. chain->next = unique_rec.release();
  487. guarded_strdup.release();
  488. }
  489. }
  490. std::string signatures;
  491. int index = 0;
  492. /* Create a nice pydoc rec including all signatures and
  493. docstrings of the functions in the overload chain */
  494. if (chain && options::show_function_signatures()) {
  495. // First a generic signature
  496. signatures += rec->name;
  497. signatures += "(*args, **kwargs)\n";
  498. signatures += "Overloaded function.\n\n";
  499. }
  500. // Then specific overload signatures
  501. bool first_user_def = true;
  502. for (auto *it = chain_start; it != nullptr; it = it->next) {
  503. if (options::show_function_signatures()) {
  504. if (index > 0) {
  505. signatures += '\n';
  506. }
  507. if (chain) {
  508. signatures += std::to_string(++index) + ". ";
  509. }
  510. signatures += rec->name;
  511. signatures += it->signature;
  512. signatures += '\n';
  513. }
  514. if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) {
  515. // If we're appending another docstring, and aren't printing function signatures,
  516. // we need to append a newline first:
  517. if (!options::show_function_signatures()) {
  518. if (first_user_def) {
  519. first_user_def = false;
  520. } else {
  521. signatures += '\n';
  522. }
  523. }
  524. if (options::show_function_signatures()) {
  525. signatures += '\n';
  526. }
  527. signatures += it->doc;
  528. if (options::show_function_signatures()) {
  529. signatures += '\n';
  530. }
  531. }
  532. }
  533. /* Install docstring */
  534. auto *func = (PyCFunctionObject *) m_ptr;
  535. std::free(const_cast<char *>(func->m_ml->ml_doc));
  536. // Install docstring if it's non-empty (when at least one option is enabled)
  537. func->m_ml->ml_doc
  538. = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());
  539. if (rec->is_method) {
  540. m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
  541. if (!m_ptr) {
  542. pybind11_fail(
  543. "cpp_function::cpp_function(): Could not allocate instance method object");
  544. }
  545. Py_DECREF(func);
  546. }
  547. }
  548. /// When a cpp_function is GCed, release any memory allocated by pybind11
  549. static void destruct(detail::function_record *rec, bool free_strings = true) {
  550. // If on Python 3.9, check the interpreter "MICRO" (patch) version.
  551. // If this is running on 3.9.0, we have to work around a bug.
  552. #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
  553. static bool is_zero = Py_GetVersion()[4] == '0';
  554. #endif
  555. while (rec) {
  556. detail::function_record *next = rec->next;
  557. if (rec->free_data) {
  558. rec->free_data(rec);
  559. }
  560. // During initialization, these strings might not have been copied yet,
  561. // so they cannot be freed. Once the function has been created, they can.
  562. // Check `make_function_record` for more details.
  563. if (free_strings) {
  564. std::free((char *) rec->name);
  565. std::free((char *) rec->doc);
  566. std::free((char *) rec->signature);
  567. for (auto &arg : rec->args) {
  568. std::free(const_cast<char *>(arg.name));
  569. std::free(const_cast<char *>(arg.descr));
  570. }
  571. }
  572. for (auto &arg : rec->args) {
  573. arg.value.dec_ref();
  574. }
  575. if (rec->def) {
  576. std::free(const_cast<char *>(rec->def->ml_doc));
  577. // Python 3.9.0 decref's these in the wrong order; rec->def
  578. // If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)
  579. // See https://github.com/python/cpython/pull/22670
  580. #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
  581. if (!is_zero) {
  582. delete rec->def;
  583. }
  584. #else
  585. delete rec->def;
  586. #endif
  587. }
  588. delete rec;
  589. rec = next;
  590. }
  591. }
  592. /// Main dispatch logic for calls to functions bound using pybind11
  593. static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
  594. using namespace detail;
  595. /* Iterator over the list of potentially admissible overloads */
  596. const function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
  597. *it = overloads;
  598. /* Need to know how many arguments + keyword arguments there are to pick the right
  599. overload */
  600. const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
  601. handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
  602. result = PYBIND11_TRY_NEXT_OVERLOAD;
  603. auto self_value_and_holder = value_and_holder();
  604. if (overloads->is_constructor) {
  605. if (!parent
  606. || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
  607. PyErr_SetString(
  608. PyExc_TypeError,
  609. "__init__(self, ...) called with invalid or missing `self` argument");
  610. return nullptr;
  611. }
  612. auto *const tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
  613. auto *const pi = reinterpret_cast<instance *>(parent.ptr());
  614. self_value_and_holder = pi->get_value_and_holder(tinfo, true);
  615. // If this value is already registered it must mean __init__ is invoked multiple times;
  616. // we really can't support that in C++, so just ignore the second __init__.
  617. if (self_value_and_holder.instance_registered()) {
  618. return none().release().ptr();
  619. }
  620. }
  621. try {
  622. // We do this in two passes: in the first pass, we load arguments with `convert=false`;
  623. // in the second, we allow conversion (except for arguments with an explicit
  624. // py::arg().noconvert()). This lets us prefer calls without conversion, with
  625. // conversion as a fallback.
  626. std::vector<function_call> second_pass;
  627. // However, if there are no overloads, we can just skip the no-convert pass entirely
  628. const bool overloaded = it != nullptr && it->next != nullptr;
  629. for (; it != nullptr; it = it->next) {
  630. /* For each overload:
  631. 1. Copy all positional arguments we were given, also checking to make sure that
  632. named positional arguments weren't *also* specified via kwarg.
  633. 2. If we weren't given enough, try to make up the omitted ones by checking
  634. whether they were provided by a kwarg matching the `py::arg("name")` name. If
  635. so, use it (and remove it from kwargs); if not, see if the function binding
  636. provided a default that we can use.
  637. 3. Ensure that either all keyword arguments were "consumed", or that the
  638. function takes a kwargs argument to accept unconsumed kwargs.
  639. 4. Any positional arguments still left get put into a tuple (for args), and any
  640. leftover kwargs get put into a dict.
  641. 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
  642. extra tuple or dict at the end of the positional arguments.
  643. 6. Call the function call dispatcher (function_record::impl)
  644. If one of these fail, move on to the next overload and keep trying until we get
  645. a result other than PYBIND11_TRY_NEXT_OVERLOAD.
  646. */
  647. const function_record &func = *it;
  648. size_t num_args = func.nargs; // Number of positional arguments that we need
  649. if (func.has_args) {
  650. --num_args; // (but don't count py::args
  651. }
  652. if (func.has_kwargs) {
  653. --num_args; // or py::kwargs)
  654. }
  655. size_t pos_args = func.nargs_pos;
  656. if (!func.has_args && n_args_in > pos_args) {
  657. continue; // Too many positional arguments for this overload
  658. }
  659. if (n_args_in < pos_args && func.args.size() < pos_args) {
  660. continue; // Not enough positional arguments given, and not enough defaults to
  661. // fill in the blanks
  662. }
  663. function_call call(func, parent);
  664. // Protect std::min with parentheses
  665. size_t args_to_copy = (std::min)(pos_args, n_args_in);
  666. size_t args_copied = 0;
  667. // 0. Inject new-style `self` argument
  668. if (func.is_new_style_constructor) {
  669. // The `value` may have been preallocated by an old-style `__init__`
  670. // if it was a preceding candidate for overload resolution.
  671. if (self_value_and_holder) {
  672. self_value_and_holder.type->dealloc(self_value_and_holder);
  673. }
  674. call.init_self = PyTuple_GET_ITEM(args_in, 0);
  675. call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
  676. call.args_convert.push_back(false);
  677. ++args_copied;
  678. }
  679. // 1. Copy any position arguments given.
  680. bool bad_arg = false;
  681. for (; args_copied < args_to_copy; ++args_copied) {
  682. const argument_record *arg_rec
  683. = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
  684. if (kwargs_in && arg_rec && arg_rec->name
  685. && dict_getitemstring(kwargs_in, arg_rec->name)) {
  686. bad_arg = true;
  687. break;
  688. }
  689. handle arg(PyTuple_GET_ITEM(args_in, args_copied));
  690. if (arg_rec && !arg_rec->none && arg.is_none()) {
  691. bad_arg = true;
  692. break;
  693. }
  694. call.args.push_back(arg);
  695. call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
  696. }
  697. if (bad_arg) {
  698. continue; // Maybe it was meant for another overload (issue #688)
  699. }
  700. // Keep track of how many position args we copied out in case we need to come back
  701. // to copy the rest into a py::args argument.
  702. size_t positional_args_copied = args_copied;
  703. // We'll need to copy this if we steal some kwargs for defaults
  704. dict kwargs = reinterpret_borrow<dict>(kwargs_in);
  705. // 1.5. Fill in any missing pos_only args from defaults if they exist
  706. if (args_copied < func.nargs_pos_only) {
  707. for (; args_copied < func.nargs_pos_only; ++args_copied) {
  708. const auto &arg_rec = func.args[args_copied];
  709. handle value;
  710. if (arg_rec.value) {
  711. value = arg_rec.value;
  712. }
  713. if (value) {
  714. call.args.push_back(value);
  715. call.args_convert.push_back(arg_rec.convert);
  716. } else {
  717. break;
  718. }
  719. }
  720. if (args_copied < func.nargs_pos_only) {
  721. continue; // Not enough defaults to fill the positional arguments
  722. }
  723. }
  724. // 2. Check kwargs and, failing that, defaults that may help complete the list
  725. if (args_copied < num_args) {
  726. bool copied_kwargs = false;
  727. for (; args_copied < num_args; ++args_copied) {
  728. const auto &arg_rec = func.args[args_copied];
  729. handle value;
  730. if (kwargs_in && arg_rec.name) {
  731. value = dict_getitemstring(kwargs.ptr(), arg_rec.name);
  732. }
  733. if (value) {
  734. // Consume a kwargs value
  735. if (!copied_kwargs) {
  736. kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
  737. copied_kwargs = true;
  738. }
  739. if (PyDict_DelItemString(kwargs.ptr(), arg_rec.name) == -1) {
  740. throw error_already_set();
  741. }
  742. } else if (arg_rec.value) {
  743. value = arg_rec.value;
  744. }
  745. if (!arg_rec.none && value.is_none()) {
  746. break;
  747. }
  748. if (value) {
  749. // If we're at the py::args index then first insert a stub for it to be
  750. // replaced later
  751. if (func.has_args && call.args.size() == func.nargs_pos) {
  752. call.args.push_back(none());
  753. }
  754. call.args.push_back(value);
  755. call.args_convert.push_back(arg_rec.convert);
  756. } else {
  757. break;
  758. }
  759. }
  760. if (args_copied < num_args) {
  761. continue; // Not enough arguments, defaults, or kwargs to fill the
  762. // positional arguments
  763. }
  764. }
  765. // 3. Check everything was consumed (unless we have a kwargs arg)
  766. if (kwargs && !kwargs.empty() && !func.has_kwargs) {
  767. continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
  768. }
  769. // 4a. If we have a py::args argument, create a new tuple with leftovers
  770. if (func.has_args) {
  771. tuple extra_args;
  772. if (args_to_copy == 0) {
  773. // We didn't copy out any position arguments from the args_in tuple, so we
  774. // can reuse it directly without copying:
  775. extra_args = reinterpret_borrow<tuple>(args_in);
  776. } else if (positional_args_copied >= n_args_in) {
  777. extra_args = tuple(0);
  778. } else {
  779. size_t args_size = n_args_in - positional_args_copied;
  780. extra_args = tuple(args_size);
  781. for (size_t i = 0; i < args_size; ++i) {
  782. extra_args[i] = PyTuple_GET_ITEM(args_in, positional_args_copied + i);
  783. }
  784. }
  785. if (call.args.size() <= func.nargs_pos) {
  786. call.args.push_back(extra_args);
  787. } else {
  788. call.args[func.nargs_pos] = extra_args;
  789. }
  790. call.args_convert.push_back(false);
  791. call.args_ref = std::move(extra_args);
  792. }
  793. // 4b. If we have a py::kwargs, pass on any remaining kwargs
  794. if (func.has_kwargs) {
  795. if (!kwargs.ptr()) {
  796. kwargs = dict(); // If we didn't get one, send an empty one
  797. }
  798. call.args.push_back(kwargs);
  799. call.args_convert.push_back(false);
  800. call.kwargs_ref = std::move(kwargs);
  801. }
  802. // 5. Put everything in a vector. Not technically step 5, we've been building it
  803. // in `call.args` all along.
  804. #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  805. if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) {
  806. pybind11_fail("Internal error: function call dispatcher inserted wrong number "
  807. "of arguments!");
  808. }
  809. #endif
  810. std::vector<bool> second_pass_convert;
  811. if (overloaded) {
  812. // We're in the first no-convert pass, so swap out the conversion flags for a
  813. // set of all-false flags. If the call fails, we'll swap the flags back in for
  814. // the conversion-allowed call below.
  815. second_pass_convert.resize(func.nargs, false);
  816. call.args_convert.swap(second_pass_convert);
  817. }
  818. // 6. Call the function.
  819. try {
  820. loader_life_support guard{};
  821. result = func.impl(call);
  822. } catch (reference_cast_error &) {
  823. result = PYBIND11_TRY_NEXT_OVERLOAD;
  824. }
  825. if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
  826. break;
  827. }
  828. if (overloaded) {
  829. // The (overloaded) call failed; if the call has at least one argument that
  830. // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
  831. // then add this call to the list of second pass overloads to try.
  832. for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
  833. if (second_pass_convert[i]) {
  834. // Found one: swap the converting flags back in and store the call for
  835. // the second pass.
  836. call.args_convert.swap(second_pass_convert);
  837. second_pass.push_back(std::move(call));
  838. break;
  839. }
  840. }
  841. }
  842. }
  843. if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
  844. // The no-conversion pass finished without success, try again with conversion
  845. // allowed
  846. for (auto &call : second_pass) {
  847. try {
  848. loader_life_support guard{};
  849. result = call.func.impl(call);
  850. } catch (reference_cast_error &) {
  851. result = PYBIND11_TRY_NEXT_OVERLOAD;
  852. }
  853. if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
  854. // The error reporting logic below expects 'it' to be valid, as it would be
  855. // if we'd encountered this failure in the first-pass loop.
  856. if (!result) {
  857. it = &call.func;
  858. }
  859. break;
  860. }
  861. }
  862. }
  863. } catch (error_already_set &e) {
  864. e.restore();
  865. return nullptr;
  866. #ifdef __GLIBCXX__
  867. } catch (abi::__forced_unwind &) {
  868. throw;
  869. #endif
  870. } catch (...) {
  871. /* When an exception is caught, give each registered exception
  872. translator a chance to translate it to a Python exception. First
  873. all module-local translators will be tried in reverse order of
  874. registration. If none of the module-locale translators handle
  875. the exception (or there are no module-locale translators) then
  876. the global translators will be tried, also in reverse order of
  877. registration.
  878. A translator may choose to do one of the following:
  879. - catch the exception and call PyErr_SetString or PyErr_SetObject
  880. to set a standard (or custom) Python exception, or
  881. - do nothing and let the exception fall through to the next translator, or
  882. - delegate translation to the next translator by throwing a new type of exception.
  883. */
  884. auto &local_exception_translators
  885. = get_local_internals().registered_exception_translators;
  886. if (detail::apply_exception_translators(local_exception_translators)) {
  887. return nullptr;
  888. }
  889. auto &exception_translators = get_internals().registered_exception_translators;
  890. if (detail::apply_exception_translators(exception_translators)) {
  891. return nullptr;
  892. }
  893. PyErr_SetString(PyExc_SystemError,
  894. "Exception escaped from default exception translator!");
  895. return nullptr;
  896. }
  897. auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
  898. if (msg.find("std::") != std::string::npos) {
  899. msg += "\n\n"
  900. "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
  901. "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
  902. "conversions are optional and require extra headers to be included\n"
  903. "when compiling your pybind11 module.";
  904. }
  905. };
  906. if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
  907. if (overloads->is_operator) {
  908. return handle(Py_NotImplemented).inc_ref().ptr();
  909. }
  910. std::string msg = std::string(overloads->name) + "(): incompatible "
  911. + std::string(overloads->is_constructor ? "constructor" : "function")
  912. + " arguments. The following argument types are supported:\n";
  913. int ctr = 0;
  914. for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
  915. msg += " " + std::to_string(++ctr) + ". ";
  916. bool wrote_sig = false;
  917. if (overloads->is_constructor) {
  918. // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as
  919. // `Object(arg0, ...)`
  920. std::string sig = it2->signature;
  921. size_t start = sig.find('(') + 7; // skip "(self: "
  922. if (start < sig.size()) {
  923. // End at the , for the next argument
  924. size_t end = sig.find(", "), next = end + 2;
  925. size_t ret = sig.rfind(" -> ");
  926. // Or the ), if there is no comma:
  927. if (end >= sig.size()) {
  928. next = end = sig.find(')');
  929. }
  930. if (start < end && next < sig.size()) {
  931. msg.append(sig, start, end - start);
  932. msg += '(';
  933. msg.append(sig, next, ret - next);
  934. wrote_sig = true;
  935. }
  936. }
  937. }
  938. if (!wrote_sig) {
  939. msg += it2->signature;
  940. }
  941. msg += '\n';
  942. }
  943. msg += "\nInvoked with: ";
  944. auto args_ = reinterpret_borrow<tuple>(args_in);
  945. bool some_args = false;
  946. for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
  947. if (!some_args) {
  948. some_args = true;
  949. } else {
  950. msg += ", ";
  951. }
  952. try {
  953. msg += pybind11::repr(args_[ti]);
  954. } catch (const error_already_set &) {
  955. msg += "<repr raised Error>";
  956. }
  957. }
  958. if (kwargs_in) {
  959. auto kwargs = reinterpret_borrow<dict>(kwargs_in);
  960. if (!kwargs.empty()) {
  961. if (some_args) {
  962. msg += "; ";
  963. }
  964. msg += "kwargs: ";
  965. bool first = true;
  966. for (auto kwarg : kwargs) {
  967. if (first) {
  968. first = false;
  969. } else {
  970. msg += ", ";
  971. }
  972. msg += pybind11::str("{}=").format(kwarg.first);
  973. try {
  974. msg += pybind11::repr(kwarg.second);
  975. } catch (const error_already_set &) {
  976. msg += "<repr raised Error>";
  977. }
  978. }
  979. }
  980. }
  981. append_note_if_missing_header_is_suspected(msg);
  982. // Attach additional error info to the exception if supported
  983. if (PyErr_Occurred()) {
  984. // #HelpAppreciated: unit test coverage for this branch.
  985. raise_from(PyExc_TypeError, msg.c_str());
  986. return nullptr;
  987. }
  988. PyErr_SetString(PyExc_TypeError, msg.c_str());
  989. return nullptr;
  990. }
  991. if (!result) {
  992. std::string msg = "Unable to convert function return value to a "
  993. "Python type! The signature was\n\t";
  994. msg += it->signature;
  995. append_note_if_missing_header_is_suspected(msg);
  996. // Attach additional error info to the exception if supported
  997. if (PyErr_Occurred()) {
  998. raise_from(PyExc_TypeError, msg.c_str());
  999. return nullptr;
  1000. }
  1001. PyErr_SetString(PyExc_TypeError, msg.c_str());
  1002. return nullptr;
  1003. }
  1004. if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
  1005. auto *pi = reinterpret_cast<instance *>(parent.ptr());
  1006. self_value_and_holder.type->init_instance(pi, nullptr);
  1007. }
  1008. return result.ptr();
  1009. }
  1010. };
  1011. /// Wrapper for Python extension modules
  1012. class module_ : public object {
  1013. public:
  1014. PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)
  1015. /// Create a new top-level Python module with the given name and docstring
  1016. PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead")
  1017. explicit module_(const char *name, const char *doc = nullptr) {
  1018. *this = create_extension_module(name, doc, new PyModuleDef());
  1019. }
  1020. /** \rst
  1021. Create Python binding for a new function within the module scope. ``Func``
  1022. can be a plain C++ function, a function pointer, or a lambda function. For
  1023. details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
  1024. \endrst */
  1025. template <typename Func, typename... Extra>
  1026. module_ &def(const char *name_, Func &&f, const Extra &...extra) {
  1027. cpp_function func(std::forward<Func>(f),
  1028. name(name_),
  1029. scope(*this),
  1030. sibling(getattr(*this, name_, none())),
  1031. extra...);
  1032. // NB: allow overwriting here because cpp_function sets up a chain with the intention of
  1033. // overwriting (and has already checked internally that it isn't overwriting
  1034. // non-functions).
  1035. add_object(name_, func, true /* overwrite */);
  1036. return *this;
  1037. }
  1038. /** \rst
  1039. Create and return a new Python submodule with the given name and docstring.
  1040. This also works recursively, i.e.
  1041. .. code-block:: cpp
  1042. py::module_ m("example", "pybind11 example plugin");
  1043. py::module_ m2 = m.def_submodule("sub", "A submodule of 'example'");
  1044. py::module_ m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
  1045. \endrst */
  1046. module_ def_submodule(const char *name, const char *doc = nullptr) {
  1047. const char *this_name = PyModule_GetName(m_ptr);
  1048. if (this_name == nullptr) {
  1049. throw error_already_set();
  1050. }
  1051. std::string full_name = std::string(this_name) + '.' + name;
  1052. handle submodule = PyImport_AddModule(full_name.c_str());
  1053. if (!submodule) {
  1054. throw error_already_set();
  1055. }
  1056. auto result = reinterpret_borrow<module_>(submodule);
  1057. if (doc && options::show_user_defined_docstrings()) {
  1058. result.attr("__doc__") = pybind11::str(doc);
  1059. }
  1060. attr(name) = result;
  1061. return result;
  1062. }
  1063. /// Import and return a module or throws `error_already_set`.
  1064. static module_ import(const char *name) {
  1065. PyObject *obj = PyImport_ImportModule(name);
  1066. if (!obj) {
  1067. throw error_already_set();
  1068. }
  1069. return reinterpret_steal<module_>(obj);
  1070. }
  1071. /// Reload the module or throws `error_already_set`.
  1072. void reload() {
  1073. PyObject *obj = PyImport_ReloadModule(ptr());
  1074. if (!obj) {
  1075. throw error_already_set();
  1076. }
  1077. *this = reinterpret_steal<module_>(obj);
  1078. }
  1079. /** \rst
  1080. Adds an object to the module using the given name. Throws if an object with the given name
  1081. already exists.
  1082. ``overwrite`` should almost always be false: attempting to overwrite objects that pybind11
  1083. has established will, in most cases, break things.
  1084. \endrst */
  1085. PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
  1086. if (!overwrite && hasattr(*this, name)) {
  1087. pybind11_fail(
  1088. "Error during initialization: multiple incompatible definitions with name \""
  1089. + std::string(name) + "\"");
  1090. }
  1091. PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
  1092. }
  1093. using module_def = PyModuleDef; // TODO: Can this be removed (it was needed only for Python 2)?
  1094. /** \rst
  1095. Create a new top-level module that can be used as the main module of a C extension.
  1096. ``def`` should point to a statically allocated module_def.
  1097. \endrst */
  1098. static module_ create_extension_module(const char *name, const char *doc, module_def *def) {
  1099. // module_def is PyModuleDef
  1100. // Placement new (not an allocation).
  1101. def = new (def)
  1102. PyModuleDef{/* m_base */ PyModuleDef_HEAD_INIT,
  1103. /* m_name */ name,
  1104. /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr,
  1105. /* m_size */ -1,
  1106. /* m_methods */ nullptr,
  1107. /* m_slots */ nullptr,
  1108. /* m_traverse */ nullptr,
  1109. /* m_clear */ nullptr,
  1110. /* m_free */ nullptr};
  1111. auto *m = PyModule_Create(def);
  1112. if (m == nullptr) {
  1113. if (PyErr_Occurred()) {
  1114. throw error_already_set();
  1115. }
  1116. pybind11_fail("Internal error in module_::create_extension_module()");
  1117. }
  1118. // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when
  1119. // returned from PyInit_...
  1120. // For Python 2, reinterpret_borrow was correct.
  1121. return reinterpret_borrow<module_>(m);
  1122. }
  1123. };
  1124. // When inside a namespace (or anywhere as long as it's not the first item on a line),
  1125. // C++20 allows "module" to be used. This is provided for backward compatibility, and for
  1126. // simplicity, if someone wants to use py::module for example, that is perfectly safe.
  1127. using module = module_;
  1128. /// \ingroup python_builtins
  1129. /// Return a dictionary representing the global variables in the current execution frame,
  1130. /// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
  1131. inline dict globals() {
  1132. PyObject *p = PyEval_GetGlobals();
  1133. return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
  1134. }
  1135. template <typename... Args, typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>>
  1136. PYBIND11_DEPRECATED("make_simple_namespace should be replaced with "
  1137. "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
  1138. object make_simple_namespace(Args &&...args_) {
  1139. return module_::import("types").attr("SimpleNamespace")(std::forward<Args>(args_)...);
  1140. }
  1141. PYBIND11_NAMESPACE_BEGIN(detail)
  1142. /// Generic support for creating new Python heap types
  1143. class generic_type : public object {
  1144. public:
  1145. PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
  1146. protected:
  1147. void initialize(const type_record &rec) {
  1148. if (rec.scope && hasattr(rec.scope, "__dict__")
  1149. && rec.scope.attr("__dict__").contains(rec.name)) {
  1150. pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name)
  1151. + "\": an object with that name is already defined");
  1152. }
  1153. if ((rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
  1154. != nullptr) {
  1155. pybind11_fail("generic_type: type \"" + std::string(rec.name)
  1156. + "\" is already registered!");
  1157. }
  1158. m_ptr = make_new_python_type(rec);
  1159. /* Register supplemental type information in C++ dict */
  1160. auto *tinfo = new detail::type_info();
  1161. tinfo->type = (PyTypeObject *) m_ptr;
  1162. tinfo->cpptype = rec.type;
  1163. tinfo->type_size = rec.type_size;
  1164. tinfo->type_align = rec.type_align;
  1165. tinfo->operator_new = rec.operator_new;
  1166. tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
  1167. tinfo->init_instance = rec.init_instance;
  1168. tinfo->dealloc = rec.dealloc;
  1169. tinfo->simple_type = true;
  1170. tinfo->simple_ancestors = true;
  1171. tinfo->default_holder = rec.default_holder;
  1172. tinfo->module_local = rec.module_local;
  1173. auto &internals = get_internals();
  1174. auto tindex = std::type_index(*rec.type);
  1175. tinfo->direct_conversions = &internals.direct_conversions[tindex];
  1176. if (rec.module_local) {
  1177. get_local_internals().registered_types_cpp[tindex] = tinfo;
  1178. } else {
  1179. internals.registered_types_cpp[tindex] = tinfo;
  1180. }
  1181. internals.registered_types_py[(PyTypeObject *) m_ptr] = {tinfo};
  1182. if (rec.bases.size() > 1 || rec.multiple_inheritance) {
  1183. mark_parents_nonsimple(tinfo->type);
  1184. tinfo->simple_ancestors = false;
  1185. } else if (rec.bases.size() == 1) {
  1186. auto *parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
  1187. assert(parent_tinfo != nullptr);
  1188. bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
  1189. tinfo->simple_ancestors = parent_simple_ancestors;
  1190. // The parent can no longer be a simple type if it has MI and has a child
  1191. parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
  1192. }
  1193. if (rec.module_local) {
  1194. // Stash the local typeinfo and loader so that external modules can access it.
  1195. tinfo->module_local_load = &type_caster_generic::local_load;
  1196. setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
  1197. }
  1198. }
  1199. /// Helper function which tags all parents of a type using mult. inheritance
  1200. void mark_parents_nonsimple(PyTypeObject *value) {
  1201. auto t = reinterpret_borrow<tuple>(value->tp_bases);
  1202. for (handle h : t) {
  1203. auto *tinfo2 = get_type_info((PyTypeObject *) h.ptr());
  1204. if (tinfo2) {
  1205. tinfo2->simple_type = false;
  1206. }
  1207. mark_parents_nonsimple((PyTypeObject *) h.ptr());
  1208. }
  1209. }
  1210. void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *),
  1211. void *get_buffer_data) {
  1212. auto *type = (PyHeapTypeObject *) m_ptr;
  1213. auto *tinfo = detail::get_type_info(&type->ht_type);
  1214. if (!type->ht_type.tp_as_buffer) {
  1215. pybind11_fail("To be able to register buffer protocol support for the type '"
  1216. + get_fully_qualified_tp_name(tinfo->type)
  1217. + "' the associated class<>(..) invocation must "
  1218. "include the pybind11::buffer_protocol() annotation!");
  1219. }
  1220. tinfo->get_buffer = get_buffer;
  1221. tinfo->get_buffer_data = get_buffer_data;
  1222. }
  1223. // rec_func must be set for either fget or fset.
  1224. void def_property_static_impl(const char *name,
  1225. handle fget,
  1226. handle fset,
  1227. detail::function_record *rec_func) {
  1228. const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);
  1229. const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)
  1230. && pybind11::options::show_user_defined_docstrings();
  1231. auto property = handle(
  1232. (PyObject *) (is_static ? get_internals().static_property_type : &PyProperty_Type));
  1233. attr(name) = property(fget.ptr() ? fget : none(),
  1234. fset.ptr() ? fset : none(),
  1235. /*deleter*/ none(),
  1236. pybind11::str(has_doc ? rec_func->doc : ""));
  1237. }
  1238. };
  1239. /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
  1240. template <typename T,
  1241. typename = void_t<decltype(static_cast<void *(*) (size_t)>(T::operator new))>>
  1242. void set_operator_new(type_record *r) {
  1243. r->operator_new = &T::operator new;
  1244. }
  1245. template <typename>
  1246. void set_operator_new(...) {}
  1247. template <typename T, typename SFINAE = void>
  1248. struct has_operator_delete : std::false_type {};
  1249. template <typename T>
  1250. struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
  1251. : std::true_type {};
  1252. template <typename T, typename SFINAE = void>
  1253. struct has_operator_delete_size : std::false_type {};
  1254. template <typename T>
  1255. struct has_operator_delete_size<
  1256. T,
  1257. void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type {
  1258. };
  1259. /// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
  1260. template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
  1261. void call_operator_delete(T *p, size_t, size_t) {
  1262. T::operator delete(p);
  1263. }
  1264. template <
  1265. typename T,
  1266. enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> = 0>
  1267. void call_operator_delete(T *p, size_t s, size_t) {
  1268. T::operator delete(p, s);
  1269. }
  1270. inline void call_operator_delete(void *p, size_t s, size_t a) {
  1271. (void) s;
  1272. (void) a;
  1273. #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
  1274. if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
  1275. # ifdef __cpp_sized_deallocation
  1276. ::operator delete(p, s, std::align_val_t(a));
  1277. # else
  1278. ::operator delete(p, std::align_val_t(a));
  1279. # endif
  1280. return;
  1281. }
  1282. #endif
  1283. #ifdef __cpp_sized_deallocation
  1284. ::operator delete(p, s);
  1285. #else
  1286. ::operator delete(p);
  1287. #endif
  1288. }
  1289. inline void add_class_method(object &cls, const char *name_, const cpp_function &cf) {
  1290. cls.attr(cf.name()) = cf;
  1291. if (std::strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) {
  1292. cls.attr("__hash__") = none();
  1293. }
  1294. }
  1295. PYBIND11_NAMESPACE_END(detail)
  1296. /// Given a pointer to a member function, cast it to its `Derived` version.
  1297. /// Forward everything else unchanged.
  1298. template <typename /*Derived*/, typename F>
  1299. auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
  1300. return std::forward<F>(f);
  1301. }
  1302. template <typename Derived, typename Return, typename Class, typename... Args>
  1303. auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
  1304. static_assert(
  1305. detail::is_accessible_base_of<Class, Derived>::value,
  1306. "Cannot bind an inaccessible base class method; use a lambda definition instead");
  1307. return pmf;
  1308. }
  1309. template <typename Derived, typename Return, typename Class, typename... Args>
  1310. auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
  1311. static_assert(
  1312. detail::is_accessible_base_of<Class, Derived>::value,
  1313. "Cannot bind an inaccessible base class method; use a lambda definition instead");
  1314. return pmf;
  1315. }
  1316. template <typename type_, typename... options>
  1317. class class_ : public detail::generic_type {
  1318. template <typename T>
  1319. using is_holder = detail::is_holder_type<type_, T>;
  1320. template <typename T>
  1321. using is_subtype = detail::is_strict_base_of<type_, T>;
  1322. template <typename T>
  1323. using is_base = detail::is_strict_base_of<T, type_>;
  1324. // struct instead of using here to help MSVC:
  1325. template <typename T>
  1326. struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
  1327. public:
  1328. using type = type_;
  1329. using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
  1330. constexpr static bool has_alias = !std::is_void<type_alias>::value;
  1331. using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
  1332. static_assert(detail::all_of<is_valid_class_option<options>...>::value,
  1333. "Unknown/invalid class_ template parameters provided");
  1334. static_assert(!has_alias || std::is_polymorphic<type>::value,
  1335. "Cannot use an alias class with a non-polymorphic type");
  1336. PYBIND11_OBJECT(class_, generic_type, PyType_Check)
  1337. template <typename... Extra>
  1338. class_(handle scope, const char *name, const Extra &...extra) {
  1339. using namespace detail;
  1340. // MI can only be specified via class_ template options, not constructor parameters
  1341. static_assert(
  1342. none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
  1343. (constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
  1344. constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
  1345. // no multiple_inheritance attr
  1346. none_of<std::is_same<multiple_inheritance, Extra>...>::value),
  1347. "Error: multiple inheritance bases must be specified via class_ template options");
  1348. type_record record;
  1349. record.scope = scope;
  1350. record.name = name;
  1351. record.type = &typeid(type);
  1352. record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
  1353. record.type_align = alignof(conditional_t<has_alias, type_alias, type> &);
  1354. record.holder_size = sizeof(holder_type);
  1355. record.init_instance = init_instance;
  1356. record.dealloc = dealloc;
  1357. record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
  1358. set_operator_new<type>(&record);
  1359. /* Register base classes specified via template arguments to class_, if any */
  1360. PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
  1361. /* Process optional arguments, if any */
  1362. process_attributes<Extra...>::init(extra..., &record);
  1363. generic_type::initialize(record);
  1364. if (has_alias) {
  1365. auto &instances = record.module_local ? get_local_internals().registered_types_cpp
  1366. : get_internals().registered_types_cpp;
  1367. instances[std::type_index(typeid(type_alias))]
  1368. = instances[std::type_index(typeid(type))];
  1369. }
  1370. }
  1371. template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
  1372. static void add_base(detail::type_record &rec) {
  1373. rec.add_base(typeid(Base), [](void *src) -> void * {
  1374. return static_cast<Base *>(reinterpret_cast<type *>(src));
  1375. });
  1376. }
  1377. template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
  1378. static void add_base(detail::type_record &) {}
  1379. template <typename Func, typename... Extra>
  1380. class_ &def(const char *name_, Func &&f, const Extra &...extra) {
  1381. cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
  1382. name(name_),
  1383. is_method(*this),
  1384. sibling(getattr(*this, name_, none())),
  1385. extra...);
  1386. add_class_method(*this, name_, cf);
  1387. return *this;
  1388. }
  1389. template <typename Func, typename... Extra>
  1390. class_ &def_static(const char *name_, Func &&f, const Extra &...extra) {
  1391. static_assert(!std::is_member_function_pointer<Func>::value,
  1392. "def_static(...) called with a non-static member function pointer");
  1393. cpp_function cf(std::forward<Func>(f),
  1394. name(name_),
  1395. scope(*this),
  1396. sibling(getattr(*this, name_, none())),
  1397. extra...);
  1398. auto cf_name = cf.name();
  1399. attr(std::move(cf_name)) = staticmethod(std::move(cf));
  1400. return *this;
  1401. }
  1402. template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
  1403. class_ &def(const T &op, const Extra &...extra) {
  1404. op.execute(*this, extra...);
  1405. return *this;
  1406. }
  1407. template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
  1408. class_ &def_cast(const T &op, const Extra &...extra) {
  1409. op.execute_cast(*this, extra...);
  1410. return *this;
  1411. }
  1412. template <typename... Args, typename... Extra>
  1413. class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra &...extra) {
  1414. PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
  1415. init.execute(*this, extra...);
  1416. return *this;
  1417. }
  1418. template <typename... Args, typename... Extra>
  1419. class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra &...extra) {
  1420. PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
  1421. init.execute(*this, extra...);
  1422. return *this;
  1423. }
  1424. template <typename... Args, typename... Extra>
  1425. class_ &def(detail::initimpl::factory<Args...> &&init, const Extra &...extra) {
  1426. std::move(init).execute(*this, extra...);
  1427. return *this;
  1428. }
  1429. template <typename... Args, typename... Extra>
  1430. class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
  1431. std::move(pf).execute(*this, extra...);
  1432. return *this;
  1433. }
  1434. template <typename Func>
  1435. class_ &def_buffer(Func &&func) {
  1436. struct capture {
  1437. Func func;
  1438. };
  1439. auto *ptr = new capture{std::forward<Func>(func)};
  1440. install_buffer_funcs(
  1441. [](PyObject *obj, void *ptr) -> buffer_info * {
  1442. detail::make_caster<type> caster;
  1443. if (!caster.load(obj, false)) {
  1444. return nullptr;
  1445. }
  1446. return new buffer_info(((capture *) ptr)->func(std::move(caster)));
  1447. },
  1448. ptr);
  1449. weakref(m_ptr, cpp_function([ptr](handle wr) {
  1450. delete ptr;
  1451. wr.dec_ref();
  1452. }))
  1453. .release();
  1454. return *this;
  1455. }
  1456. template <typename Return, typename Class, typename... Args>
  1457. class_ &def_buffer(Return (Class::*func)(Args...)) {
  1458. return def_buffer([func](type &obj) { return (obj.*func)(); });
  1459. }
  1460. template <typename Return, typename Class, typename... Args>
  1461. class_ &def_buffer(Return (Class::*func)(Args...) const) {
  1462. return def_buffer([func](const type &obj) { return (obj.*func)(); });
  1463. }
  1464. template <typename C, typename D, typename... Extra>
  1465. class_ &def_readwrite(const char *name, D C::*pm, const Extra &...extra) {
  1466. static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
  1467. "def_readwrite() requires a class member (or base class member)");
  1468. cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this)),
  1469. fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
  1470. def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
  1471. return *this;
  1472. }
  1473. template <typename C, typename D, typename... Extra>
  1474. class_ &def_readonly(const char *name, const D C::*pm, const Extra &...extra) {
  1475. static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
  1476. "def_readonly() requires a class member (or base class member)");
  1477. cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this));
  1478. def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
  1479. return *this;
  1480. }
  1481. template <typename D, typename... Extra>
  1482. class_ &def_readwrite_static(const char *name, D *pm, const Extra &...extra) {
  1483. cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)),
  1484. fset([pm](const object &, const D &value) { *pm = value; }, scope(*this));
  1485. def_property_static(name, fget, fset, return_value_policy::reference, extra...);
  1486. return *this;
  1487. }
  1488. template <typename D, typename... Extra>
  1489. class_ &def_readonly_static(const char *name, const D *pm, const Extra &...extra) {
  1490. cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this));
  1491. def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
  1492. return *this;
  1493. }
  1494. /// Uses return_value_policy::reference_internal by default
  1495. template <typename Getter, typename... Extra>
  1496. class_ &def_property_readonly(const char *name, const Getter &fget, const Extra &...extra) {
  1497. return def_property_readonly(name,
  1498. cpp_function(method_adaptor<type>(fget)),
  1499. return_value_policy::reference_internal,
  1500. extra...);
  1501. }
  1502. /// Uses cpp_function's return_value_policy by default
  1503. template <typename... Extra>
  1504. class_ &
  1505. def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra) {
  1506. return def_property(name, fget, nullptr, extra...);
  1507. }
  1508. /// Uses return_value_policy::reference by default
  1509. template <typename Getter, typename... Extra>
  1510. class_ &
  1511. def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra) {
  1512. return def_property_readonly_static(
  1513. name, cpp_function(fget), return_value_policy::reference, extra...);
  1514. }
  1515. /// Uses cpp_function's return_value_policy by default
  1516. template <typename... Extra>
  1517. class_ &def_property_readonly_static(const char *name,
  1518. const cpp_function &fget,
  1519. const Extra &...extra) {
  1520. return def_property_static(name, fget, nullptr, extra...);
  1521. }
  1522. /// Uses return_value_policy::reference_internal by default
  1523. template <typename Getter, typename Setter, typename... Extra>
  1524. class_ &
  1525. def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) {
  1526. return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
  1527. }
  1528. template <typename Getter, typename... Extra>
  1529. class_ &def_property(const char *name,
  1530. const Getter &fget,
  1531. const cpp_function &fset,
  1532. const Extra &...extra) {
  1533. return def_property(name,
  1534. cpp_function(method_adaptor<type>(fget)),
  1535. fset,
  1536. return_value_policy::reference_internal,
  1537. extra...);
  1538. }
  1539. /// Uses cpp_function's return_value_policy by default
  1540. template <typename... Extra>
  1541. class_ &def_property(const char *name,
  1542. const cpp_function &fget,
  1543. const cpp_function &fset,
  1544. const Extra &...extra) {
  1545. return def_property_static(name, fget, fset, is_method(*this), extra...);
  1546. }
  1547. /// Uses return_value_policy::reference by default
  1548. template <typename Getter, typename... Extra>
  1549. class_ &def_property_static(const char *name,
  1550. const Getter &fget,
  1551. const cpp_function &fset,
  1552. const Extra &...extra) {
  1553. return def_property_static(
  1554. name, cpp_function(fget), fset, return_value_policy::reference, extra...);
  1555. }
  1556. /// Uses cpp_function's return_value_policy by default
  1557. template <typename... Extra>
  1558. class_ &def_property_static(const char *name,
  1559. const cpp_function &fget,
  1560. const cpp_function &fset,
  1561. const Extra &...extra) {
  1562. static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
  1563. "Argument annotations are not allowed for properties");
  1564. auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
  1565. auto *rec_active = rec_fget;
  1566. if (rec_fget) {
  1567. char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific
  1568. documentation string */
  1569. detail::process_attributes<Extra...>::init(extra..., rec_fget);
  1570. if (rec_fget->doc && rec_fget->doc != doc_prev) {
  1571. std::free(doc_prev);
  1572. rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc);
  1573. }
  1574. }
  1575. if (rec_fset) {
  1576. char *doc_prev = rec_fset->doc;
  1577. detail::process_attributes<Extra...>::init(extra..., rec_fset);
  1578. if (rec_fset->doc && rec_fset->doc != doc_prev) {
  1579. std::free(doc_prev);
  1580. rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc);
  1581. }
  1582. if (!rec_active) {
  1583. rec_active = rec_fset;
  1584. }
  1585. }
  1586. def_property_static_impl(name, fget, fset, rec_active);
  1587. return *this;
  1588. }
  1589. private:
  1590. /// Initialize holder object, variant 1: object derives from enable_shared_from_this
  1591. template <typename T>
  1592. static void init_holder(detail::instance *inst,
  1593. detail::value_and_holder &v_h,
  1594. const holder_type * /* unused */,
  1595. const std::enable_shared_from_this<T> * /* dummy */) {
  1596. auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
  1597. detail::try_get_shared_from_this(v_h.value_ptr<type>()));
  1598. if (sh) {
  1599. new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
  1600. v_h.set_holder_constructed();
  1601. }
  1602. if (!v_h.holder_constructed() && inst->owned) {
  1603. new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
  1604. v_h.set_holder_constructed();
  1605. }
  1606. }
  1607. static void init_holder_from_existing(const detail::value_and_holder &v_h,
  1608. const holder_type *holder_ptr,
  1609. std::true_type /*is_copy_constructible*/) {
  1610. new (std::addressof(v_h.holder<holder_type>()))
  1611. holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
  1612. }
  1613. static void init_holder_from_existing(const detail::value_and_holder &v_h,
  1614. const holder_type *holder_ptr,
  1615. std::false_type /*is_copy_constructible*/) {
  1616. new (std::addressof(v_h.holder<holder_type>()))
  1617. holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
  1618. }
  1619. /// Initialize holder object, variant 2: try to construct from existing holder object, if
  1620. /// possible
  1621. static void init_holder(detail::instance *inst,
  1622. detail::value_and_holder &v_h,
  1623. const holder_type *holder_ptr,
  1624. const void * /* dummy -- not enable_shared_from_this<T>) */) {
  1625. if (holder_ptr) {
  1626. init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
  1627. v_h.set_holder_constructed();
  1628. } else if (PYBIND11_SILENCE_MSVC_C4127(detail::always_construct_holder<holder_type>::value)
  1629. || inst->owned) {
  1630. new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
  1631. v_h.set_holder_constructed();
  1632. }
  1633. }
  1634. /// Performs instance initialization including constructing a holder and registering the known
  1635. /// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes
  1636. /// an optional pointer to an existing holder to use; if not specified and the instance is
  1637. /// `.owned`, a new holder will be constructed to manage the value pointer.
  1638. static void init_instance(detail::instance *inst, const void *holder_ptr) {
  1639. auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
  1640. if (!v_h.instance_registered()) {
  1641. register_instance(inst, v_h.value_ptr(), v_h.type);
  1642. v_h.set_instance_registered();
  1643. }
  1644. init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
  1645. }
  1646. /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
  1647. static void dealloc(detail::value_and_holder &v_h) {
  1648. // We could be deallocating because we are cleaning up after a Python exception.
  1649. // If so, the Python error indicator will be set. We need to clear that before
  1650. // running the destructor, in case the destructor code calls more Python.
  1651. // If we don't, the Python API will exit with an exception, and pybind11 will
  1652. // throw error_already_set from the C++ destructor which is forbidden and triggers
  1653. // std::terminate().
  1654. error_scope scope;
  1655. if (v_h.holder_constructed()) {
  1656. v_h.holder<holder_type>().~holder_type();
  1657. v_h.set_holder_constructed(false);
  1658. } else {
  1659. detail::call_operator_delete(
  1660. v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align);
  1661. }
  1662. v_h.value_ptr() = nullptr;
  1663. }
  1664. static detail::function_record *get_function_record(handle h) {
  1665. h = detail::get_function(h);
  1666. return h ? (detail::function_record *) reinterpret_borrow<capsule>(
  1667. PyCFunction_GET_SELF(h.ptr()))
  1668. : nullptr;
  1669. }
  1670. };
  1671. /// Binds an existing constructor taking arguments Args...
  1672. template <typename... Args>
  1673. detail::initimpl::constructor<Args...> init() {
  1674. return {};
  1675. }
  1676. /// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
  1677. /// when not inheriting on the Python side).
  1678. template <typename... Args>
  1679. detail::initimpl::alias_constructor<Args...> init_alias() {
  1680. return {};
  1681. }
  1682. /// Binds a factory function as a constructor
  1683. template <typename Func, typename Ret = detail::initimpl::factory<Func>>
  1684. Ret init(Func &&f) {
  1685. return {std::forward<Func>(f)};
  1686. }
  1687. /// Dual-argument factory function: the first function is called when no alias is needed, the
  1688. /// second when an alias is needed (i.e. due to python-side inheritance). Arguments must be
  1689. /// identical.
  1690. template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
  1691. Ret init(CFunc &&c, AFunc &&a) {
  1692. return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
  1693. }
  1694. /// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
  1695. /// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
  1696. template <typename GetState, typename SetState>
  1697. detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
  1698. return {std::forward<GetState>(g), std::forward<SetState>(s)};
  1699. }
  1700. PYBIND11_NAMESPACE_BEGIN(detail)
  1701. inline str enum_name(handle arg) {
  1702. dict entries = arg.get_type().attr("__entries");
  1703. for (auto kv : entries) {
  1704. if (handle(kv.second[int_(0)]).equal(arg)) {
  1705. return pybind11::str(kv.first);
  1706. }
  1707. }
  1708. return "???";
  1709. }
  1710. struct enum_base {
  1711. enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) {}
  1712. PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
  1713. m_base.attr("__entries") = dict();
  1714. auto property = handle((PyObject *) &PyProperty_Type);
  1715. auto static_property = handle((PyObject *) get_internals().static_property_type);
  1716. m_base.attr("__repr__") = cpp_function(
  1717. [](const object &arg) -> str {
  1718. handle type = type::handle_of(arg);
  1719. object type_name = type.attr("__name__");
  1720. return pybind11::str("<{}.{}: {}>")
  1721. .format(std::move(type_name), enum_name(arg), int_(arg));
  1722. },
  1723. name("__repr__"),
  1724. is_method(m_base));
  1725. m_base.attr("name") = property(cpp_function(&enum_name, name("name"), is_method(m_base)));
  1726. m_base.attr("__str__") = cpp_function(
  1727. [](handle arg) -> str {
  1728. object type_name = type::handle_of(arg).attr("__name__");
  1729. return pybind11::str("{}.{}").format(std::move(type_name), enum_name(arg));
  1730. },
  1731. name("name"),
  1732. is_method(m_base));
  1733. m_base.attr("__doc__") = static_property(
  1734. cpp_function(
  1735. [](handle arg) -> std::string {
  1736. std::string docstring;
  1737. dict entries = arg.attr("__entries");
  1738. if (((PyTypeObject *) arg.ptr())->tp_doc) {
  1739. docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) + "\n\n";
  1740. }
  1741. docstring += "Members:";
  1742. for (auto kv : entries) {
  1743. auto key = std::string(pybind11::str(kv.first));
  1744. auto comment = kv.second[int_(1)];
  1745. docstring += "\n\n " + key;
  1746. if (!comment.is_none()) {
  1747. docstring += " : " + (std::string) pybind11::str(comment);
  1748. }
  1749. }
  1750. return docstring;
  1751. },
  1752. name("__doc__")),
  1753. none(),
  1754. none(),
  1755. "");
  1756. m_base.attr("__members__") = static_property(cpp_function(
  1757. [](handle arg) -> dict {
  1758. dict entries = arg.attr("__entries"),
  1759. m;
  1760. for (auto kv : entries) {
  1761. m[kv.first] = kv.second[int_(0)];
  1762. }
  1763. return m;
  1764. },
  1765. name("__members__")),
  1766. none(),
  1767. none(),
  1768. "");
  1769. #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
  1770. m_base.attr(op) = cpp_function( \
  1771. [](const object &a, const object &b) { \
  1772. if (!type::handle_of(a).is(type::handle_of(b))) \
  1773. strict_behavior; /* NOLINT(bugprone-macro-parentheses) */ \
  1774. return expr; \
  1775. }, \
  1776. name(op), \
  1777. is_method(m_base), \
  1778. arg("other"))
  1779. #define PYBIND11_ENUM_OP_CONV(op, expr) \
  1780. m_base.attr(op) = cpp_function( \
  1781. [](const object &a_, const object &b_) { \
  1782. int_ a(a_), b(b_); \
  1783. return expr; \
  1784. }, \
  1785. name(op), \
  1786. is_method(m_base), \
  1787. arg("other"))
  1788. #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
  1789. m_base.attr(op) = cpp_function( \
  1790. [](const object &a_, const object &b) { \
  1791. int_ a(a_); \
  1792. return expr; \
  1793. }, \
  1794. name(op), \
  1795. is_method(m_base), \
  1796. arg("other"))
  1797. if (is_convertible) {
  1798. PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
  1799. PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
  1800. if (is_arithmetic) {
  1801. PYBIND11_ENUM_OP_CONV("__lt__", a < b);
  1802. PYBIND11_ENUM_OP_CONV("__gt__", a > b);
  1803. PYBIND11_ENUM_OP_CONV("__le__", a <= b);
  1804. PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
  1805. PYBIND11_ENUM_OP_CONV("__and__", a & b);
  1806. PYBIND11_ENUM_OP_CONV("__rand__", a & b);
  1807. PYBIND11_ENUM_OP_CONV("__or__", a | b);
  1808. PYBIND11_ENUM_OP_CONV("__ror__", a | b);
  1809. PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
  1810. PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
  1811. m_base.attr("__invert__")
  1812. = cpp_function([](const object &arg) { return ~(int_(arg)); },
  1813. name("__invert__"),
  1814. is_method(m_base));
  1815. }
  1816. } else {
  1817. PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
  1818. PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
  1819. if (is_arithmetic) {
  1820. #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
  1821. PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
  1822. PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
  1823. PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
  1824. PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
  1825. #undef PYBIND11_THROW
  1826. }
  1827. }
  1828. #undef PYBIND11_ENUM_OP_CONV_LHS
  1829. #undef PYBIND11_ENUM_OP_CONV
  1830. #undef PYBIND11_ENUM_OP_STRICT
  1831. m_base.attr("__getstate__") = cpp_function(
  1832. [](const object &arg) { return int_(arg); }, name("__getstate__"), is_method(m_base));
  1833. m_base.attr("__hash__") = cpp_function(
  1834. [](const object &arg) { return int_(arg); }, name("__hash__"), is_method(m_base));
  1835. }
  1836. PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc = nullptr) {
  1837. dict entries = m_base.attr("__entries");
  1838. str name(name_);
  1839. if (entries.contains(name)) {
  1840. std::string type_name = (std::string) str(m_base.attr("__name__"));
  1841. throw value_error(std::move(type_name) + ": element \"" + std::string(name_)
  1842. + "\" already exists!");
  1843. }
  1844. entries[name] = pybind11::make_tuple(value, doc);
  1845. m_base.attr(std::move(name)) = std::move(value);
  1846. }
  1847. PYBIND11_NOINLINE void export_values() {
  1848. dict entries = m_base.attr("__entries");
  1849. for (auto kv : entries) {
  1850. m_parent.attr(kv.first) = kv.second[int_(0)];
  1851. }
  1852. }
  1853. handle m_base;
  1854. handle m_parent;
  1855. };
  1856. template <bool is_signed, size_t length>
  1857. struct equivalent_integer {};
  1858. template <>
  1859. struct equivalent_integer<true, 1> {
  1860. using type = int8_t;
  1861. };
  1862. template <>
  1863. struct equivalent_integer<false, 1> {
  1864. using type = uint8_t;
  1865. };
  1866. template <>
  1867. struct equivalent_integer<true, 2> {
  1868. using type = int16_t;
  1869. };
  1870. template <>
  1871. struct equivalent_integer<false, 2> {
  1872. using type = uint16_t;
  1873. };
  1874. template <>
  1875. struct equivalent_integer<true, 4> {
  1876. using type = int32_t;
  1877. };
  1878. template <>
  1879. struct equivalent_integer<false, 4> {
  1880. using type = uint32_t;
  1881. };
  1882. template <>
  1883. struct equivalent_integer<true, 8> {
  1884. using type = int64_t;
  1885. };
  1886. template <>
  1887. struct equivalent_integer<false, 8> {
  1888. using type = uint64_t;
  1889. };
  1890. template <typename IntLike>
  1891. using equivalent_integer_t =
  1892. typename equivalent_integer<std::is_signed<IntLike>::value, sizeof(IntLike)>::type;
  1893. PYBIND11_NAMESPACE_END(detail)
  1894. /// Binds C++ enumerations and enumeration classes to Python
  1895. template <typename Type>
  1896. class enum_ : public class_<Type> {
  1897. public:
  1898. using Base = class_<Type>;
  1899. using Base::attr;
  1900. using Base::def;
  1901. using Base::def_property_readonly;
  1902. using Base::def_property_readonly_static;
  1903. using Underlying = typename std::underlying_type<Type>::type;
  1904. // Scalar is the integer representation of underlying type
  1905. using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
  1906. std::is_same<Underlying, bool>>::value,
  1907. detail::equivalent_integer_t<Underlying>,
  1908. Underlying>;
  1909. template <typename... Extra>
  1910. enum_(const handle &scope, const char *name, const Extra &...extra)
  1911. : class_<Type>(scope, name, extra...), m_base(*this, scope) {
  1912. constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
  1913. constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
  1914. m_base.init(is_arithmetic, is_convertible);
  1915. def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
  1916. def_property_readonly("value", [](Type value) { return (Scalar) value; });
  1917. def("__int__", [](Type value) { return (Scalar) value; });
  1918. def("__index__", [](Type value) { return (Scalar) value; });
  1919. attr("__setstate__") = cpp_function(
  1920. [](detail::value_and_holder &v_h, Scalar arg) {
  1921. detail::initimpl::setstate<Base>(
  1922. v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type);
  1923. },
  1924. detail::is_new_style_constructor(),
  1925. pybind11::name("__setstate__"),
  1926. is_method(*this),
  1927. arg("state"));
  1928. }
  1929. /// Export enumeration entries into the parent scope
  1930. enum_ &export_values() {
  1931. m_base.export_values();
  1932. return *this;
  1933. }
  1934. /// Add an enumeration entry
  1935. enum_ &value(char const *name, Type value, const char *doc = nullptr) {
  1936. m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
  1937. return *this;
  1938. }
  1939. private:
  1940. detail::enum_base m_base;
  1941. };
  1942. PYBIND11_NAMESPACE_BEGIN(detail)
  1943. PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient) {
  1944. if (!nurse || !patient) {
  1945. pybind11_fail("Could not activate keep_alive!");
  1946. }
  1947. if (patient.is_none() || nurse.is_none()) {
  1948. return; /* Nothing to keep alive or nothing to be kept alive by */
  1949. }
  1950. auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
  1951. if (!tinfo.empty()) {
  1952. /* It's a pybind-registered type, so we can store the patient in the
  1953. * internal list. */
  1954. add_patient(nurse.ptr(), patient.ptr());
  1955. } else {
  1956. /* Fall back to clever approach based on weak references taken from
  1957. * Boost.Python. This is not used for pybind-registered types because
  1958. * the objects can be destroyed out-of-order in a GC pass. */
  1959. cpp_function disable_lifesupport([patient](handle weakref) {
  1960. patient.dec_ref();
  1961. weakref.dec_ref();
  1962. });
  1963. weakref wr(nurse, disable_lifesupport);
  1964. patient.inc_ref(); /* reference patient and leak the weak reference */
  1965. (void) wr.release();
  1966. }
  1967. }
  1968. PYBIND11_NOINLINE void
  1969. keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
  1970. auto get_arg = [&](size_t n) {
  1971. if (n == 0) {
  1972. return ret;
  1973. }
  1974. if (n == 1 && call.init_self) {
  1975. return call.init_self;
  1976. }
  1977. if (n <= call.args.size()) {
  1978. return call.args[n - 1];
  1979. }
  1980. return handle();
  1981. };
  1982. keep_alive_impl(get_arg(Nurse), get_arg(Patient));
  1983. }
  1984. inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
  1985. all_type_info_get_cache(PyTypeObject *type) {
  1986. auto res = get_internals()
  1987. .registered_types_py
  1988. #ifdef __cpp_lib_unordered_map_try_emplace
  1989. .try_emplace(type);
  1990. #else
  1991. .emplace(type, std::vector<detail::type_info *>());
  1992. #endif
  1993. if (res.second) {
  1994. // New cache entry created; set up a weak reference to automatically remove it if the type
  1995. // gets destroyed:
  1996. weakref((PyObject *) type, cpp_function([type](handle wr) {
  1997. get_internals().registered_types_py.erase(type);
  1998. // TODO consolidate the erasure code in pybind11_meta_dealloc() in class.h
  1999. auto &cache = get_internals().inactive_override_cache;
  2000. for (auto it = cache.begin(), last = cache.end(); it != last;) {
  2001. if (it->first == reinterpret_cast<PyObject *>(type)) {
  2002. it = cache.erase(it);
  2003. } else {
  2004. ++it;
  2005. }
  2006. }
  2007. wr.dec_ref();
  2008. }))
  2009. .release();
  2010. }
  2011. return res;
  2012. }
  2013. /* There are a large number of apparently unused template arguments because
  2014. * each combination requires a separate py::class_ registration.
  2015. */
  2016. template <typename Access,
  2017. return_value_policy Policy,
  2018. typename Iterator,
  2019. typename Sentinel,
  2020. typename ValueType,
  2021. typename... Extra>
  2022. struct iterator_state {
  2023. Iterator it;
  2024. Sentinel end;
  2025. bool first_or_done;
  2026. };
  2027. // Note: these helpers take the iterator by non-const reference because some
  2028. // iterators in the wild can't be dereferenced when const. The & after Iterator
  2029. // is required for MSVC < 16.9. SFINAE cannot be reused for result_type due to
  2030. // bugs in ICC, NVCC, and PGI compilers. See PR #3293.
  2031. template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
  2032. struct iterator_access {
  2033. using result_type = decltype(*std::declval<Iterator &>());
  2034. // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
  2035. result_type operator()(Iterator &it) const { return *it; }
  2036. };
  2037. template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).first)>
  2038. class iterator_key_access {
  2039. private:
  2040. using pair_type = decltype(*std::declval<Iterator &>());
  2041. public:
  2042. /* If either the pair itself or the element of the pair is a reference, we
  2043. * want to return a reference, otherwise a value. When the decltype
  2044. * expression is parenthesized it is based on the value category of the
  2045. * expression; otherwise it is the declared type of the pair member.
  2046. * The use of declval<pair_type> in the second branch rather than directly
  2047. * using *std::declval<Iterator &>() is a workaround for nvcc
  2048. * (it's not used in the first branch because going via decltype and back
  2049. * through declval does not perfectly preserve references).
  2050. */
  2051. using result_type
  2052. = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
  2053. decltype(((*std::declval<Iterator &>()).first)),
  2054. decltype(std::declval<pair_type>().first)>;
  2055. result_type operator()(Iterator &it) const { return (*it).first; }
  2056. };
  2057. template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
  2058. class iterator_value_access {
  2059. private:
  2060. using pair_type = decltype(*std::declval<Iterator &>());
  2061. public:
  2062. using result_type
  2063. = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
  2064. decltype(((*std::declval<Iterator &>()).second)),
  2065. decltype(std::declval<pair_type>().second)>;
  2066. result_type operator()(Iterator &it) const { return (*it).second; }
  2067. };
  2068. template <typename Access,
  2069. return_value_policy Policy,
  2070. typename Iterator,
  2071. typename Sentinel,
  2072. typename ValueType,
  2073. typename... Extra>
  2074. iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra) {
  2075. using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
  2076. // TODO: state captures only the types of Extra, not the values
  2077. if (!detail::get_type_info(typeid(state), false)) {
  2078. class_<state>(handle(), "iterator", pybind11::module_local())
  2079. .def("__iter__", [](state &s) -> state & { return s; })
  2080. .def(
  2081. "__next__",
  2082. [](state &s) -> ValueType {
  2083. if (!s.first_or_done) {
  2084. ++s.it;
  2085. } else {
  2086. s.first_or_done = false;
  2087. }
  2088. if (s.it == s.end) {
  2089. s.first_or_done = true;
  2090. throw stop_iteration();
  2091. }
  2092. return Access()(s.it);
  2093. // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
  2094. },
  2095. std::forward<Extra>(extra)...,
  2096. Policy);
  2097. }
  2098. return cast(state{first, last, true});
  2099. }
  2100. PYBIND11_NAMESPACE_END(detail)
  2101. /// Makes a python iterator from a first and past-the-end C++ InputIterator.
  2102. template <return_value_policy Policy = return_value_policy::reference_internal,
  2103. typename Iterator,
  2104. typename Sentinel,
  2105. typename ValueType = typename detail::iterator_access<Iterator>::result_type,
  2106. typename... Extra>
  2107. iterator make_iterator(Iterator first, Sentinel last, Extra &&...extra) {
  2108. return detail::make_iterator_impl<detail::iterator_access<Iterator>,
  2109. Policy,
  2110. Iterator,
  2111. Sentinel,
  2112. ValueType,
  2113. Extra...>(first, last, std::forward<Extra>(extra)...);
  2114. }
  2115. /// Makes a python iterator over the keys (`.first`) of a iterator over pairs from a
  2116. /// first and past-the-end InputIterator.
  2117. template <return_value_policy Policy = return_value_policy::reference_internal,
  2118. typename Iterator,
  2119. typename Sentinel,
  2120. typename KeyType = typename detail::iterator_key_access<Iterator>::result_type,
  2121. typename... Extra>
  2122. iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) {
  2123. return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
  2124. Policy,
  2125. Iterator,
  2126. Sentinel,
  2127. KeyType,
  2128. Extra...>(first, last, std::forward<Extra>(extra)...);
  2129. }
  2130. /// Makes a python iterator over the values (`.second`) of a iterator over pairs from a
  2131. /// first and past-the-end InputIterator.
  2132. template <return_value_policy Policy = return_value_policy::reference_internal,
  2133. typename Iterator,
  2134. typename Sentinel,
  2135. typename ValueType = typename detail::iterator_value_access<Iterator>::result_type,
  2136. typename... Extra>
  2137. iterator make_value_iterator(Iterator first, Sentinel last, Extra &&...extra) {
  2138. return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
  2139. Policy,
  2140. Iterator,
  2141. Sentinel,
  2142. ValueType,
  2143. Extra...>(first, last, std::forward<Extra>(extra)...);
  2144. }
  2145. /// Makes an iterator over values of an stl container or other container supporting
  2146. /// `std::begin()`/`std::end()`
  2147. template <return_value_policy Policy = return_value_policy::reference_internal,
  2148. typename Type,
  2149. typename... Extra>
  2150. iterator make_iterator(Type &value, Extra &&...extra) {
  2151. return make_iterator<Policy>(
  2152. std::begin(value), std::end(value), std::forward<Extra>(extra)...);
  2153. }
  2154. /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
  2155. /// `std::begin()`/`std::end()`
  2156. template <return_value_policy Policy = return_value_policy::reference_internal,
  2157. typename Type,
  2158. typename... Extra>
  2159. iterator make_key_iterator(Type &value, Extra &&...extra) {
  2160. return make_key_iterator<Policy>(
  2161. std::begin(value), std::end(value), std::forward<Extra>(extra)...);
  2162. }
  2163. /// Makes an iterator over the values (`.second`) of a stl map-like container supporting
  2164. /// `std::begin()`/`std::end()`
  2165. template <return_value_policy Policy = return_value_policy::reference_internal,
  2166. typename Type,
  2167. typename... Extra>
  2168. iterator make_value_iterator(Type &value, Extra &&...extra) {
  2169. return make_value_iterator<Policy>(
  2170. std::begin(value), std::end(value), std::forward<Extra>(extra)...);
  2171. }
  2172. template <typename InputType, typename OutputType>
  2173. void implicitly_convertible() {
  2174. struct set_flag {
  2175. bool &flag;
  2176. explicit set_flag(bool &flag_) : flag(flag_) { flag_ = true; }
  2177. ~set_flag() { flag = false; }
  2178. };
  2179. auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
  2180. static bool currently_used = false;
  2181. if (currently_used) { // implicit conversions are non-reentrant
  2182. return nullptr;
  2183. }
  2184. set_flag flag_helper(currently_used);
  2185. if (!detail::make_caster<InputType>().load(obj, false)) {
  2186. return nullptr;
  2187. }
  2188. tuple args(1);
  2189. args[0] = obj;
  2190. PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
  2191. if (result == nullptr) {
  2192. PyErr_Clear();
  2193. }
  2194. return result;
  2195. };
  2196. if (auto *tinfo = detail::get_type_info(typeid(OutputType))) {
  2197. tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
  2198. } else {
  2199. pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
  2200. }
  2201. }
  2202. inline void register_exception_translator(ExceptionTranslator &&translator) {
  2203. detail::get_internals().registered_exception_translators.push_front(
  2204. std::forward<ExceptionTranslator>(translator));
  2205. }
  2206. /**
  2207. * Add a new module-local exception translator. Locally registered functions
  2208. * will be tried before any globally registered exception translators, which
  2209. * will only be invoked if the module-local handlers do not deal with
  2210. * the exception.
  2211. */
  2212. inline void register_local_exception_translator(ExceptionTranslator &&translator) {
  2213. detail::get_local_internals().registered_exception_translators.push_front(
  2214. std::forward<ExceptionTranslator>(translator));
  2215. }
  2216. /**
  2217. * Wrapper to generate a new Python exception type.
  2218. *
  2219. * This should only be used with PyErr_SetString for now.
  2220. * It is not (yet) possible to use as a py::base.
  2221. * Template type argument is reserved for future use.
  2222. */
  2223. template <typename type>
  2224. class exception : public object {
  2225. public:
  2226. exception() = default;
  2227. exception(handle scope, const char *name, handle base = PyExc_Exception) {
  2228. std::string full_name
  2229. = scope.attr("__name__").cast<std::string>() + std::string(".") + name;
  2230. m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), nullptr);
  2231. if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name)) {
  2232. pybind11_fail("Error during initialization: multiple incompatible "
  2233. "definitions with name \""
  2234. + std::string(name) + "\"");
  2235. }
  2236. scope.attr(name) = *this;
  2237. }
  2238. // Sets the current python exception to this exception object with the given message
  2239. void operator()(const char *message) { PyErr_SetString(m_ptr, message); }
  2240. };
  2241. PYBIND11_NAMESPACE_BEGIN(detail)
  2242. // Returns a reference to a function-local static exception object used in the simple
  2243. // register_exception approach below. (It would be simpler to have the static local variable
  2244. // directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
  2245. template <typename CppException>
  2246. exception<CppException> &get_exception_object() {
  2247. static exception<CppException> ex;
  2248. return ex;
  2249. }
  2250. // Helper function for register_exception and register_local_exception
  2251. template <typename CppException>
  2252. exception<CppException> &
  2253. register_exception_impl(handle scope, const char *name, handle base, bool isLocal) {
  2254. auto &ex = detail::get_exception_object<CppException>();
  2255. if (!ex) {
  2256. ex = exception<CppException>(scope, name, base);
  2257. }
  2258. auto register_func
  2259. = isLocal ? &register_local_exception_translator : &register_exception_translator;
  2260. register_func([](std::exception_ptr p) {
  2261. if (!p) {
  2262. return;
  2263. }
  2264. try {
  2265. std::rethrow_exception(p);
  2266. } catch (const CppException &e) {
  2267. detail::get_exception_object<CppException>()(e.what());
  2268. }
  2269. });
  2270. return ex;
  2271. }
  2272. PYBIND11_NAMESPACE_END(detail)
  2273. /**
  2274. * Registers a Python exception in `m` of the given `name` and installs a translator to
  2275. * translate the C++ exception to the created Python exception using the what() method.
  2276. * This is intended for simple exception translations; for more complex translation, register the
  2277. * exception object and translator directly.
  2278. */
  2279. template <typename CppException>
  2280. exception<CppException> &
  2281. register_exception(handle scope, const char *name, handle base = PyExc_Exception) {
  2282. return detail::register_exception_impl<CppException>(scope, name, base, false /* isLocal */);
  2283. }
  2284. /**
  2285. * Registers a Python exception in `m` of the given `name` and installs a translator to
  2286. * translate the C++ exception to the created Python exception using the what() method.
  2287. * This translator will only be used for exceptions that are thrown in this module and will be
  2288. * tried before global exception translators, including those registered with register_exception.
  2289. * This is intended for simple exception translations; for more complex translation, register the
  2290. * exception object and translator directly.
  2291. */
  2292. template <typename CppException>
  2293. exception<CppException> &
  2294. register_local_exception(handle scope, const char *name, handle base = PyExc_Exception) {
  2295. return detail::register_exception_impl<CppException>(scope, name, base, true /* isLocal */);
  2296. }
  2297. PYBIND11_NAMESPACE_BEGIN(detail)
  2298. PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) {
  2299. auto strings = tuple(args.size());
  2300. for (size_t i = 0; i < args.size(); ++i) {
  2301. strings[i] = str(args[i]);
  2302. }
  2303. auto sep = kwargs.contains("sep") ? kwargs["sep"] : str(" ");
  2304. auto line = sep.attr("join")(std::move(strings));
  2305. object file;
  2306. if (kwargs.contains("file")) {
  2307. file = kwargs["file"].cast<object>();
  2308. } else {
  2309. try {
  2310. file = module_::import("sys").attr("stdout");
  2311. } catch (const error_already_set &) {
  2312. /* If print() is called from code that is executed as
  2313. part of garbage collection during interpreter shutdown,
  2314. importing 'sys' can fail. Give up rather than crashing the
  2315. interpreter in this case. */
  2316. return;
  2317. }
  2318. }
  2319. auto write = file.attr("write");
  2320. write(std::move(line));
  2321. write(kwargs.contains("end") ? kwargs["end"] : str("\n"));
  2322. if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) {
  2323. file.attr("flush")();
  2324. }
  2325. }
  2326. PYBIND11_NAMESPACE_END(detail)
  2327. template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
  2328. void print(Args &&...args) {
  2329. auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
  2330. detail::print(c.args(), c.kwargs());
  2331. }
  2332. inline void
  2333. error_already_set::m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr) {
  2334. gil_scoped_acquire gil;
  2335. error_scope scope;
  2336. delete raw_ptr;
  2337. }
  2338. inline const char *error_already_set::what() const noexcept {
  2339. gil_scoped_acquire gil;
  2340. error_scope scope;
  2341. return m_fetched_error->error_string().c_str();
  2342. }
  2343. PYBIND11_NAMESPACE_BEGIN(detail)
  2344. inline function
  2345. get_type_override(const void *this_ptr, const type_info *this_type, const char *name) {
  2346. handle self = get_object_handle(this_ptr, this_type);
  2347. if (!self) {
  2348. return function();
  2349. }
  2350. handle type = type::handle_of(self);
  2351. auto key = std::make_pair(type.ptr(), name);
  2352. /* Cache functions that aren't overridden in Python to avoid
  2353. many costly Python dictionary lookups below */
  2354. auto &cache = get_internals().inactive_override_cache;
  2355. if (cache.find(key) != cache.end()) {
  2356. return function();
  2357. }
  2358. function override = getattr(self, name, function());
  2359. if (override.is_cpp_function()) {
  2360. cache.insert(std::move(key));
  2361. return function();
  2362. }
  2363. /* Don't call dispatch code if invoked from overridden function.
  2364. Unfortunately this doesn't work on PyPy. */
  2365. #if !defined(PYPY_VERSION)
  2366. # if PY_VERSION_HEX >= 0x03090000
  2367. PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
  2368. if (frame != nullptr) {
  2369. PyCodeObject *f_code = PyFrame_GetCode(frame);
  2370. // f_code is guaranteed to not be NULL
  2371. if ((std::string) str(f_code->co_name) == name && f_code->co_argcount > 0) {
  2372. PyObject *locals = PyEval_GetLocals();
  2373. if (locals != nullptr) {
  2374. PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code, "co_varnames");
  2375. PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
  2376. Py_DECREF(co_varnames);
  2377. PyObject *self_caller = dict_getitem(locals, self_arg);
  2378. if (self_caller == self.ptr()) {
  2379. Py_DECREF(f_code);
  2380. Py_DECREF(frame);
  2381. return function();
  2382. }
  2383. }
  2384. }
  2385. Py_DECREF(f_code);
  2386. Py_DECREF(frame);
  2387. }
  2388. # else
  2389. PyFrameObject *frame = PyThreadState_Get()->frame;
  2390. if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name
  2391. && frame->f_code->co_argcount > 0) {
  2392. PyFrame_FastToLocals(frame);
  2393. PyObject *self_caller
  2394. = dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
  2395. if (self_caller == self.ptr()) {
  2396. return function();
  2397. }
  2398. }
  2399. # endif
  2400. #else
  2401. /* PyPy currently doesn't provide a detailed cpyext emulation of
  2402. frame objects, so we have to emulate this using Python. This
  2403. is going to be slow..*/
  2404. dict d;
  2405. d["self"] = self;
  2406. d["name"] = pybind11::str(name);
  2407. PyObject *result
  2408. = PyRun_String("import inspect\n"
  2409. "frame = inspect.currentframe()\n"
  2410. "if frame is not None:\n"
  2411. " frame = frame.f_back\n"
  2412. " if frame is not None and str(frame.f_code.co_name) == name and "
  2413. "frame.f_code.co_argcount > 0:\n"
  2414. " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
  2415. " if self_caller == self:\n"
  2416. " self = None\n",
  2417. Py_file_input,
  2418. d.ptr(),
  2419. d.ptr());
  2420. if (result == nullptr)
  2421. throw error_already_set();
  2422. Py_DECREF(result);
  2423. if (d["self"].is_none())
  2424. return function();
  2425. #endif
  2426. return override;
  2427. }
  2428. PYBIND11_NAMESPACE_END(detail)
  2429. /** \rst
  2430. Try to retrieve a python method by the provided name from the instance pointed to by the
  2431. this_ptr.
  2432. :this_ptr: The pointer to the object the overridden method should be retrieved for. This should
  2433. be the first non-trampoline class encountered in the inheritance chain.
  2434. :name: The name of the overridden Python method to retrieve.
  2435. :return: The Python method by this name from the object or an empty function wrapper.
  2436. \endrst */
  2437. template <class T>
  2438. function get_override(const T *this_ptr, const char *name) {
  2439. auto *tinfo = detail::get_type_info(typeid(T));
  2440. return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
  2441. }
  2442. #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
  2443. do { \
  2444. pybind11::gil_scoped_acquire gil; \
  2445. pybind11::function override \
  2446. = pybind11::get_override(static_cast<const cname *>(this), name); \
  2447. if (override) { \
  2448. auto o = override(__VA_ARGS__); \
  2449. if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
  2450. static pybind11::detail::override_caster_t<ret_type> caster; \
  2451. return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
  2452. } \
  2453. return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
  2454. } \
  2455. } while (false)
  2456. /** \rst
  2457. Macro to populate the virtual method in the trampoline class. This macro tries to look up a
  2458. method named 'fn' from the Python side, deals with the :ref:`gil` and necessary argument
  2459. conversions to call this method and return the appropriate type.
  2460. See :ref:`overriding_virtuals` for more information. This macro should be used when the method
  2461. name in C is not the same as the method name in Python. For example with `__str__`.
  2462. .. code-block:: cpp
  2463. std::string toString() override {
  2464. PYBIND11_OVERRIDE_NAME(
  2465. std::string, // Return type (ret_type)
  2466. Animal, // Parent class (cname)
  2467. "__str__", // Name of method in Python (name)
  2468. toString, // Name of function in C++ (fn)
  2469. );
  2470. }
  2471. \endrst */
  2472. #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
  2473. do { \
  2474. PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
  2475. return cname::fn(__VA_ARGS__); \
  2476. } while (false)
  2477. /** \rst
  2478. Macro for pure virtual functions, this function is identical to
  2479. :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it throws if no override can be found.
  2480. \endrst */
  2481. #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
  2482. do { \
  2483. PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
  2484. pybind11::pybind11_fail( \
  2485. "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
  2486. } while (false)
  2487. /** \rst
  2488. Macro to populate the virtual method in the trampoline class. This macro tries to look up the
  2489. method from the Python side, deals with the :ref:`gil` and necessary argument conversions to
  2490. call this method and return the appropriate type. This macro should be used if the method name
  2491. in C and in Python are identical.
  2492. See :ref:`overriding_virtuals` for more information.
  2493. .. code-block:: cpp
  2494. class PyAnimal : public Animal {
  2495. public:
  2496. // Inherit the constructors
  2497. using Animal::Animal;
  2498. // Trampoline (need one for each virtual function)
  2499. std::string go(int n_times) override {
  2500. PYBIND11_OVERRIDE_PURE(
  2501. std::string, // Return type (ret_type)
  2502. Animal, // Parent class (cname)
  2503. go, // Name of function in C++ (must match Python name) (fn)
  2504. n_times // Argument(s) (...)
  2505. );
  2506. }
  2507. };
  2508. \endrst */
  2509. #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
  2510. PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
  2511. /** \rst
  2512. Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`,
  2513. except that it throws if no override can be found.
  2514. \endrst */
  2515. #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
  2516. PYBIND11_OVERRIDE_PURE_NAME( \
  2517. PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
  2518. // Deprecated versions
  2519. PYBIND11_DEPRECATED("get_type_overload has been deprecated")
  2520. inline function
  2521. get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
  2522. return detail::get_type_override(this_ptr, this_type, name);
  2523. }
  2524. template <class T>
  2525. inline function get_overload(const T *this_ptr, const char *name) {
  2526. return get_override(this_ptr, name);
  2527. }
  2528. #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
  2529. PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
  2530. #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
  2531. PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
  2532. #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
  2533. PYBIND11_OVERRIDE_PURE_NAME( \
  2534. PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
  2535. #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
  2536. PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
  2537. #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
  2538. PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
  2539. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
  2540. #if defined(__GNUC__) && __GNUC__ == 7
  2541. # pragma GCC diagnostic pop // -Wnoexcept-type
  2542. #endif