pybind11.h 157 KB

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