pybind11.h 128 KB

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