pybind11.h 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094
  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. #if defined(__INTEL_COMPILER)
  10. # pragma warning push
  11. # pragma warning disable 68 // integer conversion resulted in a change of sign
  12. # pragma warning disable 186 // pointless comparison of unsigned integer with zero
  13. # pragma warning disable 878 // incompatible exception specifications
  14. # pragma warning disable 1334 // the "template" keyword used for syntactic disambiguation may only be used within a template
  15. # pragma warning disable 1682 // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem)
  16. # pragma warning disable 1786 // function "strdup" was declared deprecated
  17. # pragma warning disable 1875 // offsetof applied to non-POD (Plain Old Data) types is nonstandard
  18. # pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
  19. #elif defined(_MSC_VER)
  20. # pragma warning(push)
  21. # pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
  22. # pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
  23. # pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
  24. # pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
  25. # pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
  26. # pragma warning(disable: 4702) // warning C4702: unreachable code
  27. # pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
  28. #elif defined(__GNUG__) && !defined(__clang__)
  29. # pragma GCC diagnostic push
  30. # pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
  31. # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
  32. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  33. # pragma GCC diagnostic ignored "-Wstrict-aliasing"
  34. # pragma GCC diagnostic ignored "-Wattributes"
  35. # if __GNUC__ >= 7
  36. # pragma GCC diagnostic ignored "-Wnoexcept-type"
  37. # endif
  38. #endif
  39. #include "attr.h"
  40. #include "options.h"
  41. #include "detail/class.h"
  42. #include "detail/init.h"
  43. NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  44. /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
  45. class cpp_function : public function {
  46. public:
  47. cpp_function() { }
  48. cpp_function(std::nullptr_t) { }
  49. /// Construct a cpp_function from a vanilla function pointer
  50. template <typename Return, typename... Args, typename... Extra>
  51. cpp_function(Return (*f)(Args...), const Extra&... extra) {
  52. initialize(f, f, extra...);
  53. }
  54. /// Construct a cpp_function from a lambda function (possibly with internal state)
  55. template <typename Func, typename... Extra,
  56. typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
  57. cpp_function(Func &&f, const Extra&... extra) {
  58. initialize(std::forward<Func>(f),
  59. (detail::function_signature_t<Func> *) nullptr, extra...);
  60. }
  61. /// Construct a cpp_function from a class method (non-const)
  62. template <typename Return, typename Class, typename... Arg, typename... Extra>
  63. cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
  64. initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
  65. (Return (*) (Class *, Arg...)) nullptr, extra...);
  66. }
  67. /// Construct a cpp_function from a class method (const)
  68. template <typename Return, typename Class, typename... Arg, typename... Extra>
  69. cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
  70. initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
  71. (Return (*)(const Class *, Arg ...)) nullptr, extra...);
  72. }
  73. /// Return the function name
  74. object name() const { return attr("__name__"); }
  75. protected:
  76. /// Space optimization: don't inline this frequently instantiated fragment
  77. PYBIND11_NOINLINE detail::function_record *make_function_record() {
  78. return new detail::function_record();
  79. }
  80. /// Special internal constructor for functors, lambda functions, etc.
  81. template <typename Func, typename Return, typename... Args, typename... Extra>
  82. void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
  83. using namespace detail;
  84. struct capture { remove_reference_t<Func> f; };
  85. /* Store the function including any extra state it might have (e.g. a lambda capture object) */
  86. auto rec = make_function_record();
  87. /* Store the capture object directly in the function record if there is enough space */
  88. if (sizeof(capture) <= sizeof(rec->data)) {
  89. /* Without these pragmas, GCC warns that there might not be
  90. enough space to use the placement new operator. However, the
  91. 'if' statement above ensures that this is the case. */
  92. #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
  93. # pragma GCC diagnostic push
  94. # pragma GCC diagnostic ignored "-Wplacement-new"
  95. #endif
  96. new ((capture *) &rec->data) capture { std::forward<Func>(f) };
  97. #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
  98. # pragma GCC diagnostic pop
  99. #endif
  100. if (!std::is_trivially_destructible<Func>::value)
  101. rec->free_data = [](function_record *r) { ((capture *) &r->data)->~capture(); };
  102. } else {
  103. rec->data[0] = new capture { std::forward<Func>(f) };
  104. rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
  105. }
  106. /* Type casters for the function arguments and return value */
  107. using cast_in = argument_loader<Args...>;
  108. using cast_out = make_caster<
  109. conditional_t<std::is_void<Return>::value, void_type, Return>
  110. >;
  111. static_assert(expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
  112. "The number of argument annotations does not match the number of function arguments");
  113. /* Dispatch code which converts function arguments and performs the actual function call */
  114. rec->impl = [](function_call &call) -> handle {
  115. cast_in args_converter;
  116. /* Try to cast the function arguments into the C++ domain */
  117. if (!args_converter.load_args(call))
  118. return PYBIND11_TRY_NEXT_OVERLOAD;
  119. /* Invoke call policy pre-call hook */
  120. process_attributes<Extra...>::precall(call);
  121. /* Get a pointer to the capture object */
  122. auto data = (sizeof(capture) <= sizeof(call.func.data)
  123. ? &call.func.data : call.func.data[0]);
  124. capture *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
  125. /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
  126. return_value_policy policy = return_value_policy_override<Return>::policy(call.func.policy);
  127. /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
  128. using Guard = extract_guard_t<Extra...>;
  129. /* Perform the function call */
  130. handle result = cast_out::cast(
  131. std::move(args_converter).template call<Return, Guard>(cap->f), policy, call.parent);
  132. /* Invoke call policy post-call hook */
  133. process_attributes<Extra...>::postcall(call, result);
  134. return result;
  135. };
  136. /* Process any user-provided function attributes */
  137. process_attributes<Extra...>::init(extra..., rec);
  138. /* Generate a readable signature describing the function's arguments and return value types */
  139. static constexpr auto signature = _("(") + cast_in::arg_names + _(") -> ") + cast_out::name;
  140. PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
  141. /* Register the function with Python from generic (non-templated) code */
  142. initialize_generic(rec, signature.text, types.data(), sizeof...(Args));
  143. if (cast_in::has_args) rec->has_args = true;
  144. if (cast_in::has_kwargs) rec->has_kwargs = true;
  145. /* Stash some additional information used by an important optimization in 'functional.h' */
  146. using FunctionType = Return (*)(Args...);
  147. constexpr bool is_function_ptr =
  148. std::is_convertible<Func, FunctionType>::value &&
  149. sizeof(capture) == sizeof(void *);
  150. if (is_function_ptr) {
  151. rec->is_stateless = true;
  152. rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
  153. }
  154. }
  155. /// Register a function call with Python (generic non-templated code goes here)
  156. void initialize_generic(detail::function_record *rec, const char *text,
  157. const std::type_info *const *types, size_t args) {
  158. /* Create copies of all referenced C-style strings */
  159. rec->name = strdup(rec->name ? rec->name : "");
  160. if (rec->doc) rec->doc = strdup(rec->doc);
  161. for (auto &a: rec->args) {
  162. if (a.name)
  163. a.name = strdup(a.name);
  164. if (a.descr)
  165. a.descr = strdup(a.descr);
  166. else if (a.value)
  167. a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
  168. }
  169. rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
  170. #if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
  171. if (rec->is_constructor && !rec->is_new_style_constructor) {
  172. const auto class_name = std::string(((PyTypeObject *) rec->scope.ptr())->tp_name);
  173. const auto func_name = std::string(rec->name);
  174. PyErr_WarnEx(
  175. PyExc_FutureWarning,
  176. ("pybind11-bound class '" + class_name + "' is using an old-style "
  177. "placement-new '" + func_name + "' which has been deprecated. See "
  178. "the upgrade guide in pybind11's docs. This message is only visible "
  179. "when compiled in debug mode.").c_str(), 0
  180. );
  181. }
  182. #endif
  183. /* Generate a proper function signature */
  184. std::string signature;
  185. size_t type_index = 0, arg_index = 0;
  186. for (auto *pc = text; *pc != '\0'; ++pc) {
  187. const auto c = *pc;
  188. if (c == '{') {
  189. // Write arg name for everything except *args and **kwargs.
  190. if (*(pc + 1) == '*')
  191. continue;
  192. if (arg_index < rec->args.size() && rec->args[arg_index].name) {
  193. signature += rec->args[arg_index].name;
  194. } else if (arg_index == 0 && rec->is_method) {
  195. signature += "self";
  196. } else {
  197. signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
  198. }
  199. signature += ": ";
  200. } else if (c == '}') {
  201. // Write default value if available.
  202. if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
  203. signature += " = ";
  204. signature += rec->args[arg_index].descr;
  205. }
  206. arg_index++;
  207. } else if (c == '%') {
  208. const std::type_info *t = types[type_index++];
  209. if (!t)
  210. pybind11_fail("Internal error while parsing type signature (1)");
  211. if (auto tinfo = detail::get_type_info(*t)) {
  212. handle th((PyObject *) tinfo->type);
  213. signature +=
  214. th.attr("__module__").cast<std::string>() + "." +
  215. th.attr("__qualname__").cast<std::string>(); // Python 3.3+, but we backport it to earlier versions
  216. } else if (rec->is_new_style_constructor && arg_index == 0) {
  217. // A new-style `__init__` takes `self` as `value_and_holder`.
  218. // Rewrite it to the proper class type.
  219. signature +=
  220. rec->scope.attr("__module__").cast<std::string>() + "." +
  221. rec->scope.attr("__qualname__").cast<std::string>();
  222. } else {
  223. std::string tname(t->name());
  224. detail::clean_type_id(tname);
  225. signature += tname;
  226. }
  227. } else {
  228. signature += c;
  229. }
  230. }
  231. if (arg_index != args || types[type_index] != nullptr)
  232. pybind11_fail("Internal error while parsing type signature (2)");
  233. #if PY_MAJOR_VERSION < 3
  234. if (strcmp(rec->name, "__next__") == 0) {
  235. std::free(rec->name);
  236. rec->name = strdup("next");
  237. } else if (strcmp(rec->name, "__bool__") == 0) {
  238. std::free(rec->name);
  239. rec->name = strdup("__nonzero__");
  240. }
  241. #endif
  242. rec->signature = strdup(signature.c_str());
  243. rec->args.shrink_to_fit();
  244. rec->nargs = (std::uint16_t) args;
  245. if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr()))
  246. rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
  247. detail::function_record *chain = nullptr, *chain_start = rec;
  248. if (rec->sibling) {
  249. if (PyCFunction_Check(rec->sibling.ptr())) {
  250. auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
  251. chain = (detail::function_record *) rec_capsule;
  252. /* Never append a method to an overload chain of a parent class;
  253. instead, hide the parent's overloads in this case */
  254. if (!chain->scope.is(rec->scope))
  255. chain = nullptr;
  256. }
  257. // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
  258. else if (!rec->sibling.is_none() && rec->name[0] != '_')
  259. pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
  260. "\" with a function of the same name");
  261. }
  262. if (!chain) {
  263. /* No existing overload was found, create a new function object */
  264. rec->def = new PyMethodDef();
  265. std::memset(rec->def, 0, sizeof(PyMethodDef));
  266. rec->def->ml_name = rec->name;
  267. rec->def->ml_meth = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(*dispatcher));
  268. rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
  269. capsule rec_capsule(rec, [](void *ptr) {
  270. destruct((detail::function_record *) ptr);
  271. });
  272. object scope_module;
  273. if (rec->scope) {
  274. if (hasattr(rec->scope, "__module__")) {
  275. scope_module = rec->scope.attr("__module__");
  276. } else if (hasattr(rec->scope, "__name__")) {
  277. scope_module = rec->scope.attr("__name__");
  278. }
  279. }
  280. m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
  281. if (!m_ptr)
  282. pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
  283. } else {
  284. /* Append at the end of the overload chain */
  285. m_ptr = rec->sibling.ptr();
  286. inc_ref();
  287. chain_start = chain;
  288. if (chain->is_method != rec->is_method)
  289. pybind11_fail("overloading a method with both static and instance methods is not supported; "
  290. #if defined(NDEBUG)
  291. "compile in debug mode for more details"
  292. #else
  293. "error while attempting to bind " + std::string(rec->is_method ? "instance" : "static") + " method " +
  294. std::string(pybind11::str(rec->scope.attr("__name__"))) + "." + std::string(rec->name) + signature
  295. #endif
  296. );
  297. while (chain->next)
  298. chain = chain->next;
  299. chain->next = rec;
  300. }
  301. std::string signatures;
  302. int index = 0;
  303. /* Create a nice pydoc rec including all signatures and
  304. docstrings of the functions in the overload chain */
  305. if (chain && options::show_function_signatures()) {
  306. // First a generic signature
  307. signatures += rec->name;
  308. signatures += "(*args, **kwargs)\n";
  309. signatures += "Overloaded function.\n\n";
  310. }
  311. // Then specific overload signatures
  312. bool first_user_def = true;
  313. for (auto it = chain_start; it != nullptr; it = it->next) {
  314. if (options::show_function_signatures()) {
  315. if (index > 0) signatures += "\n";
  316. if (chain)
  317. signatures += std::to_string(++index) + ". ";
  318. signatures += rec->name;
  319. signatures += it->signature;
  320. signatures += "\n";
  321. }
  322. if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
  323. // If we're appending another docstring, and aren't printing function signatures, we
  324. // need to append a newline first:
  325. if (!options::show_function_signatures()) {
  326. if (first_user_def) first_user_def = false;
  327. else signatures += "\n";
  328. }
  329. if (options::show_function_signatures()) signatures += "\n";
  330. signatures += it->doc;
  331. if (options::show_function_signatures()) signatures += "\n";
  332. }
  333. }
  334. /* Install docstring */
  335. PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
  336. if (func->m_ml->ml_doc)
  337. std::free(const_cast<char *>(func->m_ml->ml_doc));
  338. func->m_ml->ml_doc = strdup(signatures.c_str());
  339. if (rec->is_method) {
  340. m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
  341. if (!m_ptr)
  342. pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
  343. Py_DECREF(func);
  344. }
  345. }
  346. /// When a cpp_function is GCed, release any memory allocated by pybind11
  347. static void destruct(detail::function_record *rec) {
  348. while (rec) {
  349. detail::function_record *next = rec->next;
  350. if (rec->free_data)
  351. rec->free_data(rec);
  352. std::free((char *) rec->name);
  353. std::free((char *) rec->doc);
  354. std::free((char *) rec->signature);
  355. for (auto &arg: rec->args) {
  356. std::free(const_cast<char *>(arg.name));
  357. std::free(const_cast<char *>(arg.descr));
  358. arg.value.dec_ref();
  359. }
  360. if (rec->def) {
  361. std::free(const_cast<char *>(rec->def->ml_doc));
  362. delete rec->def;
  363. }
  364. delete rec;
  365. rec = next;
  366. }
  367. }
  368. /// Main dispatch logic for calls to functions bound using pybind11
  369. static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
  370. using namespace detail;
  371. /* Iterator over the list of potentially admissible overloads */
  372. const function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
  373. *it = overloads;
  374. /* Need to know how many arguments + keyword arguments there are to pick the right overload */
  375. const size_t n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
  376. handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
  377. result = PYBIND11_TRY_NEXT_OVERLOAD;
  378. auto self_value_and_holder = value_and_holder();
  379. if (overloads->is_constructor) {
  380. const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
  381. const auto pi = reinterpret_cast<instance *>(parent.ptr());
  382. self_value_and_holder = pi->get_value_and_holder(tinfo, false);
  383. if (!self_value_and_holder.type || !self_value_and_holder.inst) {
  384. PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid `self` argument");
  385. return nullptr;
  386. }
  387. // If this value is already registered it must mean __init__ is invoked multiple times;
  388. // we really can't support that in C++, so just ignore the second __init__.
  389. if (self_value_and_holder.instance_registered())
  390. return none().release().ptr();
  391. }
  392. try {
  393. // We do this in two passes: in the first pass, we load arguments with `convert=false`;
  394. // in the second, we allow conversion (except for arguments with an explicit
  395. // py::arg().noconvert()). This lets us prefer calls without conversion, with
  396. // conversion as a fallback.
  397. std::vector<function_call> second_pass;
  398. // However, if there are no overloads, we can just skip the no-convert pass entirely
  399. const bool overloaded = it != nullptr && it->next != nullptr;
  400. for (; it != nullptr; it = it->next) {
  401. /* For each overload:
  402. 1. Copy all positional arguments we were given, also checking to make sure that
  403. named positional arguments weren't *also* specified via kwarg.
  404. 2. If we weren't given enough, try to make up the omitted ones by checking
  405. whether they were provided by a kwarg matching the `py::arg("name")` name. If
  406. so, use it (and remove it from kwargs; if not, see if the function binding
  407. provided a default that we can use.
  408. 3. Ensure that either all keyword arguments were "consumed", or that the function
  409. takes a kwargs argument to accept unconsumed kwargs.
  410. 4. Any positional arguments still left get put into a tuple (for args), and any
  411. leftover kwargs get put into a dict.
  412. 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
  413. extra tuple or dict at the end of the positional arguments.
  414. 6. Call the function call dispatcher (function_record::impl)
  415. If one of these fail, move on to the next overload and keep trying until we get a
  416. result other than PYBIND11_TRY_NEXT_OVERLOAD.
  417. */
  418. const function_record &func = *it;
  419. size_t pos_args = func.nargs; // Number of positional arguments that we need
  420. if (func.has_args) --pos_args; // (but don't count py::args
  421. if (func.has_kwargs) --pos_args; // or py::kwargs)
  422. if (!func.has_args && n_args_in > pos_args)
  423. continue; // Too many arguments for this overload
  424. if (n_args_in < pos_args && func.args.size() < pos_args)
  425. continue; // Not enough arguments given, and not enough defaults to fill in the blanks
  426. function_call call(func, parent);
  427. size_t args_to_copy = std::min(pos_args, n_args_in);
  428. size_t args_copied = 0;
  429. // 0. Inject new-style `self` argument
  430. if (func.is_new_style_constructor) {
  431. // The `value` may have been preallocated by an old-style `__init__`
  432. // if it was a preceding candidate for overload resolution.
  433. if (self_value_and_holder)
  434. self_value_and_holder.type->dealloc(self_value_and_holder);
  435. call.init_self = PyTuple_GET_ITEM(args_in, 0);
  436. call.args.push_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
  437. call.args_convert.push_back(false);
  438. ++args_copied;
  439. }
  440. // 1. Copy any position arguments given.
  441. bool bad_arg = false;
  442. for (; args_copied < args_to_copy; ++args_copied) {
  443. const argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
  444. if (kwargs_in && arg_rec && arg_rec->name && PyDict_GetItemString(kwargs_in, arg_rec->name)) {
  445. bad_arg = true;
  446. break;
  447. }
  448. handle arg(PyTuple_GET_ITEM(args_in, args_copied));
  449. if (arg_rec && !arg_rec->none && arg.is_none()) {
  450. bad_arg = true;
  451. break;
  452. }
  453. call.args.push_back(arg);
  454. call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
  455. }
  456. if (bad_arg)
  457. continue; // Maybe it was meant for another overload (issue #688)
  458. // We'll need to copy this if we steal some kwargs for defaults
  459. dict kwargs = reinterpret_borrow<dict>(kwargs_in);
  460. // 2. Check kwargs and, failing that, defaults that may help complete the list
  461. if (args_copied < pos_args) {
  462. bool copied_kwargs = false;
  463. for (; args_copied < pos_args; ++args_copied) {
  464. const auto &arg = func.args[args_copied];
  465. handle value;
  466. if (kwargs_in && arg.name)
  467. value = PyDict_GetItemString(kwargs.ptr(), arg.name);
  468. if (value) {
  469. // Consume a kwargs value
  470. if (!copied_kwargs) {
  471. kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
  472. copied_kwargs = true;
  473. }
  474. PyDict_DelItemString(kwargs.ptr(), arg.name);
  475. } else if (arg.value) {
  476. value = arg.value;
  477. }
  478. if (value) {
  479. call.args.push_back(value);
  480. call.args_convert.push_back(arg.convert);
  481. }
  482. else
  483. break;
  484. }
  485. if (args_copied < pos_args)
  486. continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments
  487. }
  488. // 3. Check everything was consumed (unless we have a kwargs arg)
  489. if (kwargs && kwargs.size() > 0 && !func.has_kwargs)
  490. continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
  491. // 4a. If we have a py::args argument, create a new tuple with leftovers
  492. if (func.has_args) {
  493. tuple extra_args;
  494. if (args_to_copy == 0) {
  495. // We didn't copy out any position arguments from the args_in tuple, so we
  496. // can reuse it directly without copying:
  497. extra_args = reinterpret_borrow<tuple>(args_in);
  498. } else if (args_copied >= n_args_in) {
  499. extra_args = tuple(0);
  500. } else {
  501. size_t args_size = n_args_in - args_copied;
  502. extra_args = tuple(args_size);
  503. for (size_t i = 0; i < args_size; ++i) {
  504. extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i);
  505. }
  506. }
  507. call.args.push_back(extra_args);
  508. call.args_convert.push_back(false);
  509. call.args_ref = std::move(extra_args);
  510. }
  511. // 4b. If we have a py::kwargs, pass on any remaining kwargs
  512. if (func.has_kwargs) {
  513. if (!kwargs.ptr())
  514. kwargs = dict(); // If we didn't get one, send an empty one
  515. call.args.push_back(kwargs);
  516. call.args_convert.push_back(false);
  517. call.kwargs_ref = std::move(kwargs);
  518. }
  519. // 5. Put everything in a vector. Not technically step 5, we've been building it
  520. // in `call.args` all along.
  521. #if !defined(NDEBUG)
  522. if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
  523. pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
  524. #endif
  525. std::vector<bool> second_pass_convert;
  526. if (overloaded) {
  527. // We're in the first no-convert pass, so swap out the conversion flags for a
  528. // set of all-false flags. If the call fails, we'll swap the flags back in for
  529. // the conversion-allowed call below.
  530. second_pass_convert.resize(func.nargs, false);
  531. call.args_convert.swap(second_pass_convert);
  532. }
  533. // 6. Call the function.
  534. try {
  535. loader_life_support guard{};
  536. result = func.impl(call);
  537. } catch (reference_cast_error &) {
  538. result = PYBIND11_TRY_NEXT_OVERLOAD;
  539. }
  540. if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
  541. break;
  542. if (overloaded) {
  543. // The (overloaded) call failed; if the call has at least one argument that
  544. // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
  545. // then add this call to the list of second pass overloads to try.
  546. for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
  547. if (second_pass_convert[i]) {
  548. // Found one: swap the converting flags back in and store the call for
  549. // the second pass.
  550. call.args_convert.swap(second_pass_convert);
  551. second_pass.push_back(std::move(call));
  552. break;
  553. }
  554. }
  555. }
  556. }
  557. if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
  558. // The no-conversion pass finished without success, try again with conversion allowed
  559. for (auto &call : second_pass) {
  560. try {
  561. loader_life_support guard{};
  562. result = call.func.impl(call);
  563. } catch (reference_cast_error &) {
  564. result = PYBIND11_TRY_NEXT_OVERLOAD;
  565. }
  566. if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
  567. // The error reporting logic below expects 'it' to be valid, as it would be
  568. // if we'd encountered this failure in the first-pass loop.
  569. if (!result)
  570. it = &call.func;
  571. break;
  572. }
  573. }
  574. }
  575. } catch (error_already_set &e) {
  576. e.restore();
  577. return nullptr;
  578. } catch (...) {
  579. /* When an exception is caught, give each registered exception
  580. translator a chance to translate it to a Python exception
  581. in reverse order of registration.
  582. A translator may choose to do one of the following:
  583. - catch the exception and call PyErr_SetString or PyErr_SetObject
  584. to set a standard (or custom) Python exception, or
  585. - do nothing and let the exception fall through to the next translator, or
  586. - delegate translation to the next translator by throwing a new type of exception. */
  587. auto last_exception = std::current_exception();
  588. auto &registered_exception_translators = get_internals().registered_exception_translators;
  589. for (auto& translator : registered_exception_translators) {
  590. try {
  591. translator(last_exception);
  592. } catch (...) {
  593. last_exception = std::current_exception();
  594. continue;
  595. }
  596. return nullptr;
  597. }
  598. PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
  599. return nullptr;
  600. }
  601. auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
  602. if (msg.find("std::") != std::string::npos) {
  603. msg += "\n\n"
  604. "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
  605. "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
  606. "conversions are optional and require extra headers to be included\n"
  607. "when compiling your pybind11 module.";
  608. }
  609. };
  610. if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
  611. if (overloads->is_operator)
  612. return handle(Py_NotImplemented).inc_ref().ptr();
  613. std::string msg = std::string(overloads->name) + "(): incompatible " +
  614. std::string(overloads->is_constructor ? "constructor" : "function") +
  615. " arguments. The following argument types are supported:\n";
  616. int ctr = 0;
  617. for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
  618. msg += " "+ std::to_string(++ctr) + ". ";
  619. bool wrote_sig = false;
  620. if (overloads->is_constructor) {
  621. // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
  622. std::string sig = it2->signature;
  623. size_t start = sig.find('(') + 7; // skip "(self: "
  624. if (start < sig.size()) {
  625. // End at the , for the next argument
  626. size_t end = sig.find(", "), next = end + 2;
  627. size_t ret = sig.rfind(" -> ");
  628. // Or the ), if there is no comma:
  629. if (end >= sig.size()) next = end = sig.find(')');
  630. if (start < end && next < sig.size()) {
  631. msg.append(sig, start, end - start);
  632. msg += '(';
  633. msg.append(sig, next, ret - next);
  634. wrote_sig = true;
  635. }
  636. }
  637. }
  638. if (!wrote_sig) msg += it2->signature;
  639. msg += "\n";
  640. }
  641. msg += "\nInvoked with: ";
  642. auto args_ = reinterpret_borrow<tuple>(args_in);
  643. bool some_args = false;
  644. for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
  645. if (!some_args) some_args = true;
  646. else msg += ", ";
  647. msg += pybind11::repr(args_[ti]);
  648. }
  649. if (kwargs_in) {
  650. auto kwargs = reinterpret_borrow<dict>(kwargs_in);
  651. if (kwargs.size() > 0) {
  652. if (some_args) msg += "; ";
  653. msg += "kwargs: ";
  654. bool first = true;
  655. for (auto kwarg : kwargs) {
  656. if (first) first = false;
  657. else msg += ", ";
  658. msg += pybind11::str("{}={!r}").format(kwarg.first, kwarg.second);
  659. }
  660. }
  661. }
  662. append_note_if_missing_header_is_suspected(msg);
  663. PyErr_SetString(PyExc_TypeError, msg.c_str());
  664. return nullptr;
  665. } else if (!result) {
  666. std::string msg = "Unable to convert function return value to a "
  667. "Python type! The signature was\n\t";
  668. msg += it->signature;
  669. append_note_if_missing_header_is_suspected(msg);
  670. PyErr_SetString(PyExc_TypeError, msg.c_str());
  671. return nullptr;
  672. } else {
  673. if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
  674. auto *pi = reinterpret_cast<instance *>(parent.ptr());
  675. self_value_and_holder.type->init_instance(pi, nullptr);
  676. }
  677. return result.ptr();
  678. }
  679. }
  680. };
  681. /// Wrapper for Python extension modules
  682. class module : public object {
  683. public:
  684. PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
  685. /// Create a new top-level Python module with the given name and docstring
  686. explicit module(const char *name, const char *doc = nullptr) {
  687. if (!options::show_user_defined_docstrings()) doc = nullptr;
  688. #if PY_MAJOR_VERSION >= 3
  689. PyModuleDef *def = new PyModuleDef();
  690. std::memset(def, 0, sizeof(PyModuleDef));
  691. def->m_name = name;
  692. def->m_doc = doc;
  693. def->m_size = -1;
  694. Py_INCREF(def);
  695. m_ptr = PyModule_Create(def);
  696. #else
  697. m_ptr = Py_InitModule3(name, nullptr, doc);
  698. #endif
  699. if (m_ptr == nullptr)
  700. pybind11_fail("Internal error in module::module()");
  701. inc_ref();
  702. }
  703. /** \rst
  704. Create Python binding for a new function within the module scope. ``Func``
  705. can be a plain C++ function, a function pointer, or a lambda function. For
  706. details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
  707. \endrst */
  708. template <typename Func, typename... Extra>
  709. module &def(const char *name_, Func &&f, const Extra& ... extra) {
  710. cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
  711. sibling(getattr(*this, name_, none())), extra...);
  712. // NB: allow overwriting here because cpp_function sets up a chain with the intention of
  713. // overwriting (and has already checked internally that it isn't overwriting non-functions).
  714. add_object(name_, func, true /* overwrite */);
  715. return *this;
  716. }
  717. /** \rst
  718. Create and return a new Python submodule with the given name and docstring.
  719. This also works recursively, i.e.
  720. .. code-block:: cpp
  721. py::module m("example", "pybind11 example plugin");
  722. py::module m2 = m.def_submodule("sub", "A submodule of 'example'");
  723. py::module m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
  724. \endrst */
  725. module def_submodule(const char *name, const char *doc = nullptr) {
  726. std::string full_name = std::string(PyModule_GetName(m_ptr))
  727. + std::string(".") + std::string(name);
  728. auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
  729. if (doc && options::show_user_defined_docstrings())
  730. result.attr("__doc__") = pybind11::str(doc);
  731. attr(name) = result;
  732. return result;
  733. }
  734. /// Import and return a module or throws `error_already_set`.
  735. static module import(const char *name) {
  736. PyObject *obj = PyImport_ImportModule(name);
  737. if (!obj)
  738. throw error_already_set();
  739. return reinterpret_steal<module>(obj);
  740. }
  741. /// Reload the module or throws `error_already_set`.
  742. void reload() {
  743. PyObject *obj = PyImport_ReloadModule(ptr());
  744. if (!obj)
  745. throw error_already_set();
  746. *this = reinterpret_steal<module>(obj);
  747. }
  748. // Adds an object to the module using the given name. Throws if an object with the given name
  749. // already exists.
  750. //
  751. // overwrite should almost always be false: attempting to overwrite objects that pybind11 has
  752. // established will, in most cases, break things.
  753. PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
  754. if (!overwrite && hasattr(*this, name))
  755. pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
  756. std::string(name) + "\"");
  757. PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
  758. }
  759. };
  760. /// \ingroup python_builtins
  761. /// Return a dictionary representing the global variables in the current execution frame,
  762. /// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
  763. inline dict globals() {
  764. PyObject *p = PyEval_GetGlobals();
  765. return reinterpret_borrow<dict>(p ? p : module::import("__main__").attr("__dict__").ptr());
  766. }
  767. NAMESPACE_BEGIN(detail)
  768. /// Generic support for creating new Python heap types
  769. class generic_type : public object {
  770. template <typename...> friend class class_;
  771. public:
  772. PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
  773. protected:
  774. void initialize(const type_record &rec) {
  775. if (rec.scope && hasattr(rec.scope, rec.name))
  776. pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
  777. "\": an object with that name is already defined");
  778. if (rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
  779. pybind11_fail("generic_type: type \"" + std::string(rec.name) +
  780. "\" is already registered!");
  781. m_ptr = make_new_python_type(rec);
  782. /* Register supplemental type information in C++ dict */
  783. auto *tinfo = new detail::type_info();
  784. tinfo->type = (PyTypeObject *) m_ptr;
  785. tinfo->cpptype = rec.type;
  786. tinfo->type_size = rec.type_size;
  787. tinfo->type_align = rec.type_align;
  788. tinfo->operator_new = rec.operator_new;
  789. tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
  790. tinfo->init_instance = rec.init_instance;
  791. tinfo->dealloc = rec.dealloc;
  792. tinfo->simple_type = true;
  793. tinfo->simple_ancestors = true;
  794. tinfo->default_holder = rec.default_holder;
  795. tinfo->module_local = rec.module_local;
  796. auto &internals = get_internals();
  797. auto tindex = std::type_index(*rec.type);
  798. tinfo->direct_conversions = &internals.direct_conversions[tindex];
  799. if (rec.module_local)
  800. registered_local_types_cpp()[tindex] = tinfo;
  801. else
  802. internals.registered_types_cpp[tindex] = tinfo;
  803. internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo };
  804. if (rec.bases.size() > 1 || rec.multiple_inheritance) {
  805. mark_parents_nonsimple(tinfo->type);
  806. tinfo->simple_ancestors = false;
  807. }
  808. else if (rec.bases.size() == 1) {
  809. auto parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
  810. tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
  811. }
  812. if (rec.module_local) {
  813. // Stash the local typeinfo and loader so that external modules can access it.
  814. tinfo->module_local_load = &type_caster_generic::local_load;
  815. setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
  816. }
  817. }
  818. /// Helper function which tags all parents of a type using mult. inheritance
  819. void mark_parents_nonsimple(PyTypeObject *value) {
  820. auto t = reinterpret_borrow<tuple>(value->tp_bases);
  821. for (handle h : t) {
  822. auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
  823. if (tinfo2)
  824. tinfo2->simple_type = false;
  825. mark_parents_nonsimple((PyTypeObject *) h.ptr());
  826. }
  827. }
  828. void install_buffer_funcs(
  829. buffer_info *(*get_buffer)(PyObject *, void *),
  830. void *get_buffer_data) {
  831. PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
  832. auto tinfo = detail::get_type_info(&type->ht_type);
  833. if (!type->ht_type.tp_as_buffer)
  834. pybind11_fail(
  835. "To be able to register buffer protocol support for the type '" +
  836. std::string(tinfo->type->tp_name) +
  837. "' the associated class<>(..) invocation must "
  838. "include the pybind11::buffer_protocol() annotation!");
  839. tinfo->get_buffer = get_buffer;
  840. tinfo->get_buffer_data = get_buffer_data;
  841. }
  842. // rec_func must be set for either fget or fset.
  843. void def_property_static_impl(const char *name,
  844. handle fget, handle fset,
  845. detail::function_record *rec_func) {
  846. const auto is_static = rec_func && !(rec_func->is_method && rec_func->scope);
  847. const auto has_doc = rec_func && rec_func->doc && pybind11::options::show_user_defined_docstrings();
  848. auto property = handle((PyObject *) (is_static ? get_internals().static_property_type
  849. : &PyProperty_Type));
  850. attr(name) = property(fget.ptr() ? fget : none(),
  851. fset.ptr() ? fset : none(),
  852. /*deleter*/none(),
  853. pybind11::str(has_doc ? rec_func->doc : ""));
  854. }
  855. };
  856. /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
  857. template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator new))>>
  858. void set_operator_new(type_record *r) { r->operator_new = &T::operator new; }
  859. template <typename> void set_operator_new(...) { }
  860. template <typename T, typename SFINAE = void> struct has_operator_delete : std::false_type { };
  861. template <typename T> struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
  862. : std::true_type { };
  863. template <typename T, typename SFINAE = void> struct has_operator_delete_size : std::false_type { };
  864. template <typename T> struct has_operator_delete_size<T, void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>>
  865. : std::true_type { };
  866. /// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
  867. template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
  868. void call_operator_delete(T *p, size_t, size_t) { T::operator delete(p); }
  869. template <typename T, enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> = 0>
  870. void call_operator_delete(T *p, size_t s, size_t) { T::operator delete(p, s); }
  871. inline void call_operator_delete(void *p, size_t s, size_t a) {
  872. (void)s; (void)a;
  873. #if defined(PYBIND11_CPP17)
  874. if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
  875. ::operator delete(p, s, std::align_val_t(a));
  876. else
  877. ::operator delete(p, s);
  878. #else
  879. ::operator delete(p);
  880. #endif
  881. }
  882. NAMESPACE_END(detail)
  883. /// Given a pointer to a member function, cast it to its `Derived` version.
  884. /// Forward everything else unchanged.
  885. template <typename /*Derived*/, typename F>
  886. auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) { return std::forward<F>(f); }
  887. template <typename Derived, typename Return, typename Class, typename... Args>
  888. auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
  889. static_assert(detail::is_accessible_base_of<Class, Derived>::value,
  890. "Cannot bind an inaccessible base class method; use a lambda definition instead");
  891. return pmf;
  892. }
  893. template <typename Derived, typename Return, typename Class, typename... Args>
  894. auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
  895. static_assert(detail::is_accessible_base_of<Class, Derived>::value,
  896. "Cannot bind an inaccessible base class method; use a lambda definition instead");
  897. return pmf;
  898. }
  899. template <typename type_, typename... options>
  900. class class_ : public detail::generic_type {
  901. template <typename T> using is_holder = detail::is_holder_type<type_, T>;
  902. template <typename T> using is_subtype = detail::is_strict_base_of<type_, T>;
  903. template <typename T> using is_base = detail::is_strict_base_of<T, type_>;
  904. // struct instead of using here to help MSVC:
  905. template <typename T> struct is_valid_class_option :
  906. detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
  907. public:
  908. using type = type_;
  909. using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
  910. constexpr static bool has_alias = !std::is_void<type_alias>::value;
  911. using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
  912. static_assert(detail::all_of<is_valid_class_option<options>...>::value,
  913. "Unknown/invalid class_ template parameters provided");
  914. static_assert(!has_alias || std::is_polymorphic<type>::value,
  915. "Cannot use an alias class with a non-polymorphic type");
  916. PYBIND11_OBJECT(class_, generic_type, PyType_Check)
  917. template <typename... Extra>
  918. class_(handle scope, const char *name, const Extra &... extra) {
  919. using namespace detail;
  920. // MI can only be specified via class_ template options, not constructor parameters
  921. static_assert(
  922. none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
  923. ( constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
  924. constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
  925. none_of<std::is_same<multiple_inheritance, Extra>...>::value), // no multiple_inheritance attr
  926. "Error: multiple inheritance bases must be specified via class_ template options");
  927. type_record record;
  928. record.scope = scope;
  929. record.name = name;
  930. record.type = &typeid(type);
  931. record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
  932. record.type_align = alignof(conditional_t<has_alias, type_alias, type>&);
  933. record.holder_size = sizeof(holder_type);
  934. record.init_instance = init_instance;
  935. record.dealloc = dealloc;
  936. record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
  937. set_operator_new<type>(&record);
  938. /* Register base classes specified via template arguments to class_, if any */
  939. PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
  940. /* Process optional arguments, if any */
  941. process_attributes<Extra...>::init(extra..., &record);
  942. generic_type::initialize(record);
  943. if (has_alias) {
  944. auto &instances = record.module_local ? registered_local_types_cpp() : get_internals().registered_types_cpp;
  945. instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
  946. }
  947. }
  948. template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
  949. static void add_base(detail::type_record &rec) {
  950. rec.add_base(typeid(Base), [](void *src) -> void * {
  951. return static_cast<Base *>(reinterpret_cast<type *>(src));
  952. });
  953. }
  954. template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
  955. static void add_base(detail::type_record &) { }
  956. template <typename Func, typename... Extra>
  957. class_ &def(const char *name_, Func&& f, const Extra&... extra) {
  958. cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), name(name_), is_method(*this),
  959. sibling(getattr(*this, name_, none())), extra...);
  960. attr(cf.name()) = cf;
  961. return *this;
  962. }
  963. template <typename Func, typename... Extra> class_ &
  964. def_static(const char *name_, Func &&f, const Extra&... extra) {
  965. static_assert(!std::is_member_function_pointer<Func>::value,
  966. "def_static(...) called with a non-static member function pointer");
  967. cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
  968. sibling(getattr(*this, name_, none())), extra...);
  969. attr(cf.name()) = cf;
  970. return *this;
  971. }
  972. template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
  973. class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
  974. op.execute(*this, extra...);
  975. return *this;
  976. }
  977. template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
  978. class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
  979. op.execute_cast(*this, extra...);
  980. return *this;
  981. }
  982. template <typename... Args, typename... Extra>
  983. class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra&... extra) {
  984. init.execute(*this, extra...);
  985. return *this;
  986. }
  987. template <typename... Args, typename... Extra>
  988. class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra&... extra) {
  989. init.execute(*this, extra...);
  990. return *this;
  991. }
  992. template <typename... Args, typename... Extra>
  993. class_ &def(detail::initimpl::factory<Args...> &&init, const Extra&... extra) {
  994. std::move(init).execute(*this, extra...);
  995. return *this;
  996. }
  997. template <typename... Args, typename... Extra>
  998. class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
  999. std::move(pf).execute(*this, extra...);
  1000. return *this;
  1001. }
  1002. template <typename Func> class_& def_buffer(Func &&func) {
  1003. struct capture { Func func; };
  1004. capture *ptr = new capture { std::forward<Func>(func) };
  1005. install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
  1006. detail::make_caster<type> caster;
  1007. if (!caster.load(obj, false))
  1008. return nullptr;
  1009. return new buffer_info(((capture *) ptr)->func(caster));
  1010. }, ptr);
  1011. return *this;
  1012. }
  1013. template <typename Return, typename Class, typename... Args>
  1014. class_ &def_buffer(Return (Class::*func)(Args...)) {
  1015. return def_buffer([func] (type &obj) { return (obj.*func)(); });
  1016. }
  1017. template <typename Return, typename Class, typename... Args>
  1018. class_ &def_buffer(Return (Class::*func)(Args...) const) {
  1019. return def_buffer([func] (const type &obj) { return (obj.*func)(); });
  1020. }
  1021. template <typename C, typename D, typename... Extra>
  1022. class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
  1023. static_assert(std::is_base_of<C, type>::value, "def_readwrite() requires a class member (or base class member)");
  1024. cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this)),
  1025. fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
  1026. def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
  1027. return *this;
  1028. }
  1029. template <typename C, typename D, typename... Extra>
  1030. class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
  1031. static_assert(std::is_base_of<C, type>::value, "def_readonly() requires a class member (or base class member)");
  1032. cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this));
  1033. def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
  1034. return *this;
  1035. }
  1036. template <typename D, typename... Extra>
  1037. class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
  1038. cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
  1039. fset([pm](object, const D &value) { *pm = value; }, scope(*this));
  1040. def_property_static(name, fget, fset, return_value_policy::reference, extra...);
  1041. return *this;
  1042. }
  1043. template <typename D, typename... Extra>
  1044. class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
  1045. cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
  1046. def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
  1047. return *this;
  1048. }
  1049. /// Uses return_value_policy::reference_internal by default
  1050. template <typename Getter, typename... Extra>
  1051. class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
  1052. return def_property_readonly(name, cpp_function(method_adaptor<type>(fget)),
  1053. return_value_policy::reference_internal, extra...);
  1054. }
  1055. /// Uses cpp_function's return_value_policy by default
  1056. template <typename... Extra>
  1057. class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
  1058. return def_property(name, fget, nullptr, extra...);
  1059. }
  1060. /// Uses return_value_policy::reference by default
  1061. template <typename Getter, typename... Extra>
  1062. class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
  1063. return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...);
  1064. }
  1065. /// Uses cpp_function's return_value_policy by default
  1066. template <typename... Extra>
  1067. class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
  1068. return def_property_static(name, fget, nullptr, extra...);
  1069. }
  1070. /// Uses return_value_policy::reference_internal by default
  1071. template <typename Getter, typename Setter, typename... Extra>
  1072. class_ &def_property(const char *name, const Getter &fget, const Setter &fset, const Extra& ...extra) {
  1073. return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
  1074. }
  1075. template <typename Getter, typename... Extra>
  1076. class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
  1077. return def_property(name, cpp_function(method_adaptor<type>(fget)), fset,
  1078. return_value_policy::reference_internal, extra...);
  1079. }
  1080. /// Uses cpp_function's return_value_policy by default
  1081. template <typename... Extra>
  1082. class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
  1083. return def_property_static(name, fget, fset, is_method(*this), extra...);
  1084. }
  1085. /// Uses return_value_policy::reference by default
  1086. template <typename Getter, typename... Extra>
  1087. class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
  1088. return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
  1089. }
  1090. /// Uses cpp_function's return_value_policy by default
  1091. template <typename... Extra>
  1092. class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
  1093. auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
  1094. auto *rec_active = rec_fget;
  1095. if (rec_fget) {
  1096. char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
  1097. detail::process_attributes<Extra...>::init(extra..., rec_fget);
  1098. if (rec_fget->doc && rec_fget->doc != doc_prev) {
  1099. free(doc_prev);
  1100. rec_fget->doc = strdup(rec_fget->doc);
  1101. }
  1102. }
  1103. if (rec_fset) {
  1104. char *doc_prev = rec_fset->doc;
  1105. detail::process_attributes<Extra...>::init(extra..., rec_fset);
  1106. if (rec_fset->doc && rec_fset->doc != doc_prev) {
  1107. free(doc_prev);
  1108. rec_fset->doc = strdup(rec_fset->doc);
  1109. }
  1110. if (! rec_active) rec_active = rec_fset;
  1111. }
  1112. def_property_static_impl(name, fget, fset, rec_active);
  1113. return *this;
  1114. }
  1115. private:
  1116. /// Initialize holder object, variant 1: object derives from enable_shared_from_this
  1117. template <typename T>
  1118. static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
  1119. const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
  1120. try {
  1121. auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
  1122. v_h.value_ptr<type>()->shared_from_this());
  1123. if (sh) {
  1124. new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
  1125. v_h.set_holder_constructed();
  1126. }
  1127. } catch (const std::bad_weak_ptr &) {}
  1128. if (!v_h.holder_constructed() && inst->owned) {
  1129. new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
  1130. v_h.set_holder_constructed();
  1131. }
  1132. }
  1133. static void init_holder_from_existing(const detail::value_and_holder &v_h,
  1134. const holder_type *holder_ptr, std::true_type /*is_copy_constructible*/) {
  1135. new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
  1136. }
  1137. static void init_holder_from_existing(const detail::value_and_holder &v_h,
  1138. const holder_type *holder_ptr, std::false_type /*is_copy_constructible*/) {
  1139. new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
  1140. }
  1141. /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
  1142. static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
  1143. const holder_type *holder_ptr, const void * /* dummy -- not enable_shared_from_this<T>) */) {
  1144. if (holder_ptr) {
  1145. init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
  1146. v_h.set_holder_constructed();
  1147. } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
  1148. new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
  1149. v_h.set_holder_constructed();
  1150. }
  1151. }
  1152. /// Performs instance initialization including constructing a holder and registering the known
  1153. /// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes an
  1154. /// optional pointer to an existing holder to use; if not specified and the instance is
  1155. /// `.owned`, a new holder will be constructed to manage the value pointer.
  1156. static void init_instance(detail::instance *inst, const void *holder_ptr) {
  1157. auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
  1158. if (!v_h.instance_registered()) {
  1159. register_instance(inst, v_h.value_ptr(), v_h.type);
  1160. v_h.set_instance_registered();
  1161. }
  1162. init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
  1163. }
  1164. /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
  1165. static void dealloc(detail::value_and_holder &v_h) {
  1166. if (v_h.holder_constructed()) {
  1167. v_h.holder<holder_type>().~holder_type();
  1168. v_h.set_holder_constructed(false);
  1169. }
  1170. else {
  1171. detail::call_operator_delete(v_h.value_ptr<type>(),
  1172. v_h.type->type_size,
  1173. v_h.type->type_align
  1174. );
  1175. }
  1176. v_h.value_ptr() = nullptr;
  1177. }
  1178. static detail::function_record *get_function_record(handle h) {
  1179. h = detail::get_function(h);
  1180. return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
  1181. : nullptr;
  1182. }
  1183. };
  1184. /// Binds an existing constructor taking arguments Args...
  1185. template <typename... Args> detail::initimpl::constructor<Args...> init() { return {}; }
  1186. /// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
  1187. /// when not inheriting on the Python side).
  1188. template <typename... Args> detail::initimpl::alias_constructor<Args...> init_alias() { return {}; }
  1189. /// Binds a factory function as a constructor
  1190. template <typename Func, typename Ret = detail::initimpl::factory<Func>>
  1191. Ret init(Func &&f) { return {std::forward<Func>(f)}; }
  1192. /// Dual-argument factory function: the first function is called when no alias is needed, the second
  1193. /// when an alias is needed (i.e. due to python-side inheritance). Arguments must be identical.
  1194. template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
  1195. Ret init(CFunc &&c, AFunc &&a) {
  1196. return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
  1197. }
  1198. /// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
  1199. /// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
  1200. template <typename GetState, typename SetState>
  1201. detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
  1202. return {std::forward<GetState>(g), std::forward<SetState>(s)};
  1203. }
  1204. NAMESPACE_BEGIN(detail)
  1205. struct enum_base {
  1206. enum_base(handle base, handle parent) : m_base(base), m_parent(parent) { }
  1207. PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
  1208. m_base.attr("__entries") = dict();
  1209. auto property = handle((PyObject *) &PyProperty_Type);
  1210. auto static_property = handle((PyObject *) get_internals().static_property_type);
  1211. m_base.attr("__repr__") = cpp_function(
  1212. [](handle arg) -> str {
  1213. handle type = arg.get_type();
  1214. object type_name = type.attr("__name__");
  1215. dict entries = type.attr("__entries");
  1216. for (const auto &kv : entries) {
  1217. object other = kv.second[int_(0)];
  1218. if (other.equal(arg))
  1219. return pybind11::str("{}.{}").format(type_name, kv.first);
  1220. }
  1221. return pybind11::str("{}.???").format(type_name);
  1222. }, is_method(m_base)
  1223. );
  1224. m_base.attr("name") = property(cpp_function(
  1225. [](handle arg) -> str {
  1226. dict entries = arg.get_type().attr("__entries");
  1227. for (const auto &kv : entries) {
  1228. if (handle(kv.second[int_(0)]).equal(arg))
  1229. return pybind11::str(kv.first);
  1230. }
  1231. return "???";
  1232. }, is_method(m_base)
  1233. ));
  1234. m_base.attr("__doc__") = static_property(cpp_function(
  1235. [](handle arg) -> std::string {
  1236. std::string docstring;
  1237. dict entries = arg.attr("__entries");
  1238. if (((PyTypeObject *) arg.ptr())->tp_doc)
  1239. docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) + "\n\n";
  1240. docstring += "Members:";
  1241. for (const auto &kv : entries) {
  1242. auto key = std::string(pybind11::str(kv.first));
  1243. auto comment = kv.second[int_(1)];
  1244. docstring += "\n\n " + key;
  1245. if (!comment.is_none())
  1246. docstring += " : " + (std::string) pybind11::str(comment);
  1247. }
  1248. return docstring;
  1249. }
  1250. ), none(), none(), "");
  1251. m_base.attr("__members__") = static_property(cpp_function(
  1252. [](handle arg) -> dict {
  1253. dict entries = arg.attr("__entries"), m;
  1254. for (const auto &kv : entries)
  1255. m[kv.first] = kv.second[int_(0)];
  1256. return m;
  1257. }), none(), none(), ""
  1258. );
  1259. #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
  1260. m_base.attr(op) = cpp_function( \
  1261. [](object a, object b) { \
  1262. if (!a.get_type().is(b.get_type())) \
  1263. strict_behavior; \
  1264. return expr; \
  1265. }, \
  1266. is_method(m_base))
  1267. #define PYBIND11_ENUM_OP_CONV(op, expr) \
  1268. m_base.attr(op) = cpp_function( \
  1269. [](object a_, object b_) { \
  1270. int_ a(a_), b(b_); \
  1271. return expr; \
  1272. }, \
  1273. is_method(m_base))
  1274. if (is_convertible) {
  1275. PYBIND11_ENUM_OP_CONV("__eq__", !b.is_none() && a.equal(b));
  1276. PYBIND11_ENUM_OP_CONV("__ne__", b.is_none() || !a.equal(b));
  1277. if (is_arithmetic) {
  1278. PYBIND11_ENUM_OP_CONV("__lt__", a < b);
  1279. PYBIND11_ENUM_OP_CONV("__gt__", a > b);
  1280. PYBIND11_ENUM_OP_CONV("__le__", a <= b);
  1281. PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
  1282. PYBIND11_ENUM_OP_CONV("__and__", a & b);
  1283. PYBIND11_ENUM_OP_CONV("__rand__", a & b);
  1284. PYBIND11_ENUM_OP_CONV("__or__", a | b);
  1285. PYBIND11_ENUM_OP_CONV("__ror__", a | b);
  1286. PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
  1287. PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
  1288. }
  1289. } else {
  1290. PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
  1291. PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
  1292. if (is_arithmetic) {
  1293. #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
  1294. PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
  1295. PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
  1296. PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
  1297. PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
  1298. #undef PYBIND11_THROW
  1299. }
  1300. }
  1301. #undef PYBIND11_ENUM_OP_CONV
  1302. #undef PYBIND11_ENUM_OP_STRICT
  1303. object getstate = cpp_function(
  1304. [](object arg) { return int_(arg); }, is_method(m_base));
  1305. m_base.attr("__getstate__") = getstate;
  1306. m_base.attr("__hash__") = getstate;
  1307. }
  1308. PYBIND11_NOINLINE void value(char const* name_, object value, const char *doc = nullptr) {
  1309. dict entries = m_base.attr("__entries");
  1310. str name(name_);
  1311. if (entries.contains(name)) {
  1312. std::string type_name = (std::string) str(m_base.attr("__name__"));
  1313. throw value_error(type_name + ": element \"" + std::string(name_) + "\" already exists!");
  1314. }
  1315. entries[name] = std::make_pair(value, doc);
  1316. m_base.attr(name) = value;
  1317. }
  1318. PYBIND11_NOINLINE void export_values() {
  1319. dict entries = m_base.attr("__entries");
  1320. for (const auto &kv : entries)
  1321. m_parent.attr(kv.first) = kv.second[int_(0)];
  1322. }
  1323. handle m_base;
  1324. handle m_parent;
  1325. };
  1326. NAMESPACE_END(detail)
  1327. /// Binds C++ enumerations and enumeration classes to Python
  1328. template <typename Type> class enum_ : public class_<Type> {
  1329. public:
  1330. using Base = class_<Type>;
  1331. using Base::def;
  1332. using Base::attr;
  1333. using Base::def_property_readonly;
  1334. using Base::def_property_readonly_static;
  1335. using Scalar = typename std::underlying_type<Type>::type;
  1336. template <typename... Extra>
  1337. enum_(const handle &scope, const char *name, const Extra&... extra)
  1338. : class_<Type>(scope, name, extra...), m_base(*this, scope) {
  1339. constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
  1340. constexpr bool is_convertible = std::is_convertible<Type, Scalar>::value;
  1341. m_base.init(is_arithmetic, is_convertible);
  1342. def(init([](Scalar i) { return static_cast<Type>(i); }));
  1343. def("__int__", [](Type value) { return (Scalar) value; });
  1344. #if PY_MAJOR_VERSION < 3
  1345. def("__long__", [](Type value) { return (Scalar) value; });
  1346. #endif
  1347. cpp_function setstate(
  1348. [](Type &value, Scalar arg) { value = static_cast<Type>(arg); },
  1349. is_method(*this));
  1350. attr("__setstate__") = setstate;
  1351. }
  1352. /// Export enumeration entries into the parent scope
  1353. enum_& export_values() {
  1354. m_base.export_values();
  1355. return *this;
  1356. }
  1357. /// Add an enumeration entry
  1358. enum_& value(char const* name, Type value, const char *doc = nullptr) {
  1359. m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
  1360. return *this;
  1361. }
  1362. private:
  1363. detail::enum_base m_base;
  1364. };
  1365. NAMESPACE_BEGIN(detail)
  1366. inline void keep_alive_impl(handle nurse, handle patient) {
  1367. if (!nurse || !patient)
  1368. pybind11_fail("Could not activate keep_alive!");
  1369. if (patient.is_none() || nurse.is_none())
  1370. return; /* Nothing to keep alive or nothing to be kept alive by */
  1371. auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
  1372. if (!tinfo.empty()) {
  1373. /* It's a pybind-registered type, so we can store the patient in the
  1374. * internal list. */
  1375. add_patient(nurse.ptr(), patient.ptr());
  1376. }
  1377. else {
  1378. /* Fall back to clever approach based on weak references taken from
  1379. * Boost.Python. This is not used for pybind-registered types because
  1380. * the objects can be destroyed out-of-order in a GC pass. */
  1381. cpp_function disable_lifesupport(
  1382. [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
  1383. weakref wr(nurse, disable_lifesupport);
  1384. patient.inc_ref(); /* reference patient and leak the weak reference */
  1385. (void) wr.release();
  1386. }
  1387. }
  1388. PYBIND11_NOINLINE inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
  1389. auto get_arg = [&](size_t n) {
  1390. if (n == 0)
  1391. return ret;
  1392. else if (n == 1 && call.init_self)
  1393. return call.init_self;
  1394. else if (n <= call.args.size())
  1395. return call.args[n - 1];
  1396. return handle();
  1397. };
  1398. keep_alive_impl(get_arg(Nurse), get_arg(Patient));
  1399. }
  1400. inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type) {
  1401. auto res = get_internals().registered_types_py
  1402. #ifdef __cpp_lib_unordered_map_try_emplace
  1403. .try_emplace(type);
  1404. #else
  1405. .emplace(type, std::vector<detail::type_info *>());
  1406. #endif
  1407. if (res.second) {
  1408. // New cache entry created; set up a weak reference to automatically remove it if the type
  1409. // gets destroyed:
  1410. weakref((PyObject *) type, cpp_function([type](handle wr) {
  1411. get_internals().registered_types_py.erase(type);
  1412. wr.dec_ref();
  1413. })).release();
  1414. }
  1415. return res;
  1416. }
  1417. template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
  1418. struct iterator_state {
  1419. Iterator it;
  1420. Sentinel end;
  1421. bool first_or_done;
  1422. };
  1423. NAMESPACE_END(detail)
  1424. /// Makes a python iterator from a first and past-the-end C++ InputIterator.
  1425. template <return_value_policy Policy = return_value_policy::reference_internal,
  1426. typename Iterator,
  1427. typename Sentinel,
  1428. typename ValueType = decltype(*std::declval<Iterator>()),
  1429. typename... Extra>
  1430. iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
  1431. typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
  1432. if (!detail::get_type_info(typeid(state), false)) {
  1433. class_<state>(handle(), "iterator", pybind11::module_local())
  1434. .def("__iter__", [](state &s) -> state& { return s; })
  1435. .def("__next__", [](state &s) -> ValueType {
  1436. if (!s.first_or_done)
  1437. ++s.it;
  1438. else
  1439. s.first_or_done = false;
  1440. if (s.it == s.end) {
  1441. s.first_or_done = true;
  1442. throw stop_iteration();
  1443. }
  1444. return *s.it;
  1445. }, std::forward<Extra>(extra)..., Policy);
  1446. }
  1447. return cast(state{first, last, true});
  1448. }
  1449. /// Makes an python iterator over the keys (`.first`) of a iterator over pairs from a
  1450. /// first and past-the-end InputIterator.
  1451. template <return_value_policy Policy = return_value_policy::reference_internal,
  1452. typename Iterator,
  1453. typename Sentinel,
  1454. typename KeyType = decltype((*std::declval<Iterator>()).first),
  1455. typename... Extra>
  1456. iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
  1457. typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
  1458. if (!detail::get_type_info(typeid(state), false)) {
  1459. class_<state>(handle(), "iterator", pybind11::module_local())
  1460. .def("__iter__", [](state &s) -> state& { return s; })
  1461. .def("__next__", [](state &s) -> KeyType {
  1462. if (!s.first_or_done)
  1463. ++s.it;
  1464. else
  1465. s.first_or_done = false;
  1466. if (s.it == s.end) {
  1467. s.first_or_done = true;
  1468. throw stop_iteration();
  1469. }
  1470. return (*s.it).first;
  1471. }, std::forward<Extra>(extra)..., Policy);
  1472. }
  1473. return cast(state{first, last, true});
  1474. }
  1475. /// Makes an iterator over values of an stl container or other container supporting
  1476. /// `std::begin()`/`std::end()`
  1477. template <return_value_policy Policy = return_value_policy::reference_internal,
  1478. typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
  1479. return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
  1480. }
  1481. /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
  1482. /// `std::begin()`/`std::end()`
  1483. template <return_value_policy Policy = return_value_policy::reference_internal,
  1484. typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
  1485. return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
  1486. }
  1487. template <typename InputType, typename OutputType> void implicitly_convertible() {
  1488. struct set_flag {
  1489. bool &flag;
  1490. set_flag(bool &flag) : flag(flag) { flag = true; }
  1491. ~set_flag() { flag = false; }
  1492. };
  1493. auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
  1494. static bool currently_used = false;
  1495. if (currently_used) // implicit conversions are non-reentrant
  1496. return nullptr;
  1497. set_flag flag_helper(currently_used);
  1498. if (!detail::make_caster<InputType>().load(obj, false))
  1499. return nullptr;
  1500. tuple args(1);
  1501. args[0] = obj;
  1502. PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
  1503. if (result == nullptr)
  1504. PyErr_Clear();
  1505. return result;
  1506. };
  1507. if (auto tinfo = detail::get_type_info(typeid(OutputType)))
  1508. tinfo->implicit_conversions.push_back(implicit_caster);
  1509. else
  1510. pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
  1511. }
  1512. template <typename ExceptionTranslator>
  1513. void register_exception_translator(ExceptionTranslator&& translator) {
  1514. detail::get_internals().registered_exception_translators.push_front(
  1515. std::forward<ExceptionTranslator>(translator));
  1516. }
  1517. /**
  1518. * Wrapper to generate a new Python exception type.
  1519. *
  1520. * This should only be used with PyErr_SetString for now.
  1521. * It is not (yet) possible to use as a py::base.
  1522. * Template type argument is reserved for future use.
  1523. */
  1524. template <typename type>
  1525. class exception : public object {
  1526. public:
  1527. exception() = default;
  1528. exception(handle scope, const char *name, PyObject *base = PyExc_Exception) {
  1529. std::string full_name = scope.attr("__name__").cast<std::string>() +
  1530. std::string(".") + name;
  1531. m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base, NULL);
  1532. if (hasattr(scope, name))
  1533. pybind11_fail("Error during initialization: multiple incompatible "
  1534. "definitions with name \"" + std::string(name) + "\"");
  1535. scope.attr(name) = *this;
  1536. }
  1537. // Sets the current python exception to this exception object with the given message
  1538. void operator()(const char *message) {
  1539. PyErr_SetString(m_ptr, message);
  1540. }
  1541. };
  1542. NAMESPACE_BEGIN(detail)
  1543. // Returns a reference to a function-local static exception object used in the simple
  1544. // register_exception approach below. (It would be simpler to have the static local variable
  1545. // directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
  1546. template <typename CppException>
  1547. exception<CppException> &get_exception_object() { static exception<CppException> ex; return ex; }
  1548. NAMESPACE_END(detail)
  1549. /**
  1550. * Registers a Python exception in `m` of the given `name` and installs an exception translator to
  1551. * translate the C++ exception to the created Python exception using the exceptions what() method.
  1552. * This is intended for simple exception translations; for more complex translation, register the
  1553. * exception object and translator directly.
  1554. */
  1555. template <typename CppException>
  1556. exception<CppException> &register_exception(handle scope,
  1557. const char *name,
  1558. PyObject *base = PyExc_Exception) {
  1559. auto &ex = detail::get_exception_object<CppException>();
  1560. if (!ex) ex = exception<CppException>(scope, name, base);
  1561. register_exception_translator([](std::exception_ptr p) {
  1562. if (!p) return;
  1563. try {
  1564. std::rethrow_exception(p);
  1565. } catch (const CppException &e) {
  1566. detail::get_exception_object<CppException>()(e.what());
  1567. }
  1568. });
  1569. return ex;
  1570. }
  1571. NAMESPACE_BEGIN(detail)
  1572. PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
  1573. auto strings = tuple(args.size());
  1574. for (size_t i = 0; i < args.size(); ++i) {
  1575. strings[i] = str(args[i]);
  1576. }
  1577. auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
  1578. auto line = sep.attr("join")(strings);
  1579. object file;
  1580. if (kwargs.contains("file")) {
  1581. file = kwargs["file"].cast<object>();
  1582. } else {
  1583. try {
  1584. file = module::import("sys").attr("stdout");
  1585. } catch (const error_already_set &) {
  1586. /* If print() is called from code that is executed as
  1587. part of garbage collection during interpreter shutdown,
  1588. importing 'sys' can fail. Give up rather than crashing the
  1589. interpreter in this case. */
  1590. return;
  1591. }
  1592. }
  1593. auto write = file.attr("write");
  1594. write(line);
  1595. write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
  1596. if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
  1597. file.attr("flush")();
  1598. }
  1599. NAMESPACE_END(detail)
  1600. template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
  1601. void print(Args &&...args) {
  1602. auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
  1603. detail::print(c.args(), c.kwargs());
  1604. }
  1605. #if defined(WITH_THREAD) && !defined(PYPY_VERSION)
  1606. /* The functions below essentially reproduce the PyGILState_* API using a RAII
  1607. * pattern, but there are a few important differences:
  1608. *
  1609. * 1. When acquiring the GIL from an non-main thread during the finalization
  1610. * phase, the GILState API blindly terminates the calling thread, which
  1611. * is often not what is wanted. This API does not do this.
  1612. *
  1613. * 2. The gil_scoped_release function can optionally cut the relationship
  1614. * of a PyThreadState and its associated thread, which allows moving it to
  1615. * another thread (this is a fairly rare/advanced use case).
  1616. *
  1617. * 3. The reference count of an acquired thread state can be controlled. This
  1618. * can be handy to prevent cases where callbacks issued from an external
  1619. * thread would otherwise constantly construct and destroy thread state data
  1620. * structures.
  1621. *
  1622. * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
  1623. * example which uses features 2 and 3 to migrate the Python thread of
  1624. * execution to another thread (to run the event loop on the original thread,
  1625. * in this case).
  1626. */
  1627. class gil_scoped_acquire {
  1628. public:
  1629. PYBIND11_NOINLINE gil_scoped_acquire() {
  1630. auto const &internals = detail::get_internals();
  1631. tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
  1632. if (!tstate) {
  1633. /* Check if the GIL was acquired using the PyGILState_* API instead (e.g. if
  1634. calling from a Python thread). Since we use a different key, this ensures
  1635. we don't create a new thread state and deadlock in PyEval_AcquireThread
  1636. below. Note we don't save this state with internals.tstate, since we don't
  1637. create it we would fail to clear it (its reference count should be > 0). */
  1638. tstate = PyGILState_GetThisThreadState();
  1639. }
  1640. if (!tstate) {
  1641. tstate = PyThreadState_New(internals.istate);
  1642. #if !defined(NDEBUG)
  1643. if (!tstate)
  1644. pybind11_fail("scoped_acquire: could not create thread state!");
  1645. #endif
  1646. tstate->gilstate_counter = 0;
  1647. PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
  1648. } else {
  1649. release = detail::get_thread_state_unchecked() != tstate;
  1650. }
  1651. if (release) {
  1652. /* Work around an annoying assertion in PyThreadState_Swap */
  1653. #if defined(Py_DEBUG)
  1654. PyInterpreterState *interp = tstate->interp;
  1655. tstate->interp = nullptr;
  1656. #endif
  1657. PyEval_AcquireThread(tstate);
  1658. #if defined(Py_DEBUG)
  1659. tstate->interp = interp;
  1660. #endif
  1661. }
  1662. inc_ref();
  1663. }
  1664. void inc_ref() {
  1665. ++tstate->gilstate_counter;
  1666. }
  1667. PYBIND11_NOINLINE void dec_ref() {
  1668. --tstate->gilstate_counter;
  1669. #if !defined(NDEBUG)
  1670. if (detail::get_thread_state_unchecked() != tstate)
  1671. pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
  1672. if (tstate->gilstate_counter < 0)
  1673. pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
  1674. #endif
  1675. if (tstate->gilstate_counter == 0) {
  1676. #if !defined(NDEBUG)
  1677. if (!release)
  1678. pybind11_fail("scoped_acquire::dec_ref(): internal error!");
  1679. #endif
  1680. PyThreadState_Clear(tstate);
  1681. PyThreadState_DeleteCurrent();
  1682. PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
  1683. release = false;
  1684. }
  1685. }
  1686. PYBIND11_NOINLINE ~gil_scoped_acquire() {
  1687. dec_ref();
  1688. if (release)
  1689. PyEval_SaveThread();
  1690. }
  1691. private:
  1692. PyThreadState *tstate = nullptr;
  1693. bool release = true;
  1694. };
  1695. class gil_scoped_release {
  1696. public:
  1697. explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
  1698. // `get_internals()` must be called here unconditionally in order to initialize
  1699. // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
  1700. // initialization race could occur as multiple threads try `gil_scoped_acquire`.
  1701. const auto &internals = detail::get_internals();
  1702. tstate = PyEval_SaveThread();
  1703. if (disassoc) {
  1704. auto key = internals.tstate;
  1705. PYBIND11_TLS_DELETE_VALUE(key);
  1706. }
  1707. }
  1708. ~gil_scoped_release() {
  1709. if (!tstate)
  1710. return;
  1711. PyEval_RestoreThread(tstate);
  1712. if (disassoc) {
  1713. auto key = detail::get_internals().tstate;
  1714. PYBIND11_TLS_REPLACE_VALUE(key, tstate);
  1715. }
  1716. }
  1717. private:
  1718. PyThreadState *tstate;
  1719. bool disassoc;
  1720. };
  1721. #elif defined(PYPY_VERSION)
  1722. class gil_scoped_acquire {
  1723. PyGILState_STATE state;
  1724. public:
  1725. gil_scoped_acquire() { state = PyGILState_Ensure(); }
  1726. ~gil_scoped_acquire() { PyGILState_Release(state); }
  1727. };
  1728. class gil_scoped_release {
  1729. PyThreadState *state;
  1730. public:
  1731. gil_scoped_release() { state = PyEval_SaveThread(); }
  1732. ~gil_scoped_release() { PyEval_RestoreThread(state); }
  1733. };
  1734. #else
  1735. class gil_scoped_acquire { };
  1736. class gil_scoped_release { };
  1737. #endif
  1738. error_already_set::~error_already_set() {
  1739. if (type) {
  1740. error_scope scope;
  1741. gil_scoped_acquire gil;
  1742. type.release().dec_ref();
  1743. value.release().dec_ref();
  1744. trace.release().dec_ref();
  1745. }
  1746. }
  1747. inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
  1748. handle self = detail::get_object_handle(this_ptr, this_type);
  1749. if (!self)
  1750. return function();
  1751. handle type = self.get_type();
  1752. auto key = std::make_pair(type.ptr(), name);
  1753. /* Cache functions that aren't overloaded in Python to avoid
  1754. many costly Python dictionary lookups below */
  1755. auto &cache = detail::get_internals().inactive_overload_cache;
  1756. if (cache.find(key) != cache.end())
  1757. return function();
  1758. function overload = getattr(self, name, function());
  1759. if (overload.is_cpp_function()) {
  1760. cache.insert(key);
  1761. return function();
  1762. }
  1763. /* Don't call dispatch code if invoked from overridden function.
  1764. Unfortunately this doesn't work on PyPy. */
  1765. #if !defined(PYPY_VERSION)
  1766. PyFrameObject *frame = PyThreadState_Get()->frame;
  1767. if (frame && (std::string) str(frame->f_code->co_name) == name &&
  1768. frame->f_code->co_argcount > 0) {
  1769. PyFrame_FastToLocals(frame);
  1770. PyObject *self_caller = PyDict_GetItem(
  1771. frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
  1772. if (self_caller == self.ptr())
  1773. return function();
  1774. }
  1775. #else
  1776. /* PyPy currently doesn't provide a detailed cpyext emulation of
  1777. frame objects, so we have to emulate this using Python. This
  1778. is going to be slow..*/
  1779. dict d; d["self"] = self; d["name"] = pybind11::str(name);
  1780. PyObject *result = PyRun_String(
  1781. "import inspect\n"
  1782. "frame = inspect.currentframe()\n"
  1783. "if frame is not None:\n"
  1784. " frame = frame.f_back\n"
  1785. " if frame is not None and str(frame.f_code.co_name) == name and "
  1786. "frame.f_code.co_argcount > 0:\n"
  1787. " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
  1788. " if self_caller == self:\n"
  1789. " self = None\n",
  1790. Py_file_input, d.ptr(), d.ptr());
  1791. if (result == nullptr)
  1792. throw error_already_set();
  1793. if (d["self"].is_none())
  1794. return function();
  1795. Py_DECREF(result);
  1796. #endif
  1797. return overload;
  1798. }
  1799. template <class T> function get_overload(const T *this_ptr, const char *name) {
  1800. auto tinfo = detail::get_type_info(typeid(T));
  1801. return tinfo ? get_type_overload(this_ptr, tinfo, name) : function();
  1802. }
  1803. #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
  1804. pybind11::gil_scoped_acquire gil; \
  1805. pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
  1806. if (overload) { \
  1807. auto o = overload(__VA_ARGS__); \
  1808. if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
  1809. static pybind11::detail::overload_caster_t<ret_type> caster; \
  1810. return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
  1811. } \
  1812. else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
  1813. } \
  1814. }
  1815. #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
  1816. PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
  1817. return cname::fn(__VA_ARGS__)
  1818. #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
  1819. PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
  1820. pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\"");
  1821. #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
  1822. PYBIND11_OVERLOAD_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
  1823. #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
  1824. PYBIND11_OVERLOAD_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
  1825. NAMESPACE_END(PYBIND11_NAMESPACE)
  1826. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  1827. # pragma warning(pop)
  1828. #elif defined(__GNUG__) && !defined(__clang__)
  1829. # pragma GCC diagnostic pop
  1830. #endif