pybind11.h 157 KB

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