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