pybind11.h 127 KB

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