1 /*
2 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
3
4 All rights reserved. Use of this source code is governed by a
5 BSD-style license that can be found in the LICENSE file.
6 */
7
8
9
10
11 #pragma once
12
13 #if defined(__INTEL_COMPILER)
14 # pragma warning push
15 # pragma warning disable 68
16 # pragma warning disable 186
17 # pragma warning disable 878
18 # pragma warning disable 1334
19 # pragma warning disable 1682
20 # pragma warning disable 1786
21 # pragma warning disable 1875
22 # pragma warning disable 2196
23 #elif defined(_MSC_VER)
24 # pragma warning(push)
25 # pragma warning(disable: 4100)
26 # pragma warning(disable: 4127)
27 # pragma warning(disable: 4512)
28 # pragma warning(disable: 4800)
29 # pragma warning(disable: 4996)
30 # pragma warning(disable: 4702)
31 # pragma warning(disable: 4522)
32 #elif defined(__GNUG__) && !defined(__clang__)
33 # pragma GCC diagnostic push
34 # pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
35 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
36 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
37 # pragma GCC diagnostic ignored "-Wstrict-aliasing"
38 # pragma GCC diagnostic ignored "-Wattributes"
39 # if __GNUC__ >= 7
40 # pragma GCC diagnostic ignored "-Wnoexcept-type"
41 # endif
42 #endif
43
44 #include "attr.h"
45 #include "options.h"
46 #include "detail/class.h"
47 #include "detail/init.h"
48
NAMESPACE_BEGIN(PYBIND11_NAMESPACE)49 NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
50
51
52 class cpp_function : public function {
53 public:
54 cpp_function() { }
55 cpp_function(std::nullptr_t) { }
56
57
58 template <typename Return, typename... Args, typename... Extra>
59 cpp_function(Return (*f)(Args...), const Extra&... extra) {
60 initialize(f, f, extra...);
61 }
62
63
64 template <typename Func, typename... Extra,
65 typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
66 cpp_function(Func &&f, const Extra&... extra) {
67 initialize(std::forward<Func>(f),
68 (detail::function_signature_t<Func> *) nullptr, extra...);
69 }
70
71
72 template <typename Return, typename Class, typename... Arg, typename... Extra>
73 cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
74 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
75 (Return (*) (Class *, Arg...)) nullptr, extra...);
76 }
77
78
79 template <typename Return, typename Class, typename... Arg, typename... Extra>
80 cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
81 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
82 (Return (*)(const Class *, Arg ...)) nullptr, extra...);
83 }
84
85
86 object name() const { return attr("__name__"); }
87
88 protected:
89
90 PYBIND11_NOINLINE detail::function_record *make_function_record() {
91 return new detail::function_record();
92 }
93
94
95 template <typename Func, typename Return, typename... Args, typename... Extra>
96 void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
97 using namespace detail;
98 struct capture { remove_reference_t<Func> f; };
99
100
101 auto rec = make_function_record();
102
103
104 if (sizeof(capture) <= sizeof(rec->data)) {
105
106 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
107 # pragma GCC diagnostic push
108 # pragma GCC diagnostic ignored "-Wplacement-new"
109 #endif
110 new ((capture *) &rec->data) capture { std::forward<Func>(f) };
111 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
112 # pragma GCC diagnostic pop
113 #endif
114 if (!std::is_trivially_destructible<Func>::value)
115 rec->free_data = [](function_record *r) { ((capture *) &r->data)->~capture(); };
116 } else {
117 rec->data[0] = new capture { std::forward<Func>(f) };
118 rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
119 }
120
121
122 using cast_in = argument_loader<Args...>;
123 using cast_out = make_caster<
124 conditional_t<std::is_void<Return>::value, void_type, Return>
125 >;
126
127 static_assert(expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
128 "The number of argument annotations does not match the number of function arguments");
129
130
131 rec->impl = [](function_call &call) -> handle {
132 cast_in args_converter;
133
134
135 if (!args_converter.load_args(call))
136 return PYBIND11_TRY_NEXT_OVERLOAD;
137
138
139 process_attributes<Extra...>::precall(call);
140
141
142 auto data = (sizeof(capture) <= sizeof(call.func.data)
143 ? &call.func.data : call.func.data[0]);
144 capture *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
145
146
147 return_value_policy policy = return_value_policy_override<Return>::policy(call.func.policy);
148
149
150 using Guard = extract_guard_t<Extra...>;
151
152
153 handle result = cast_out::cast(
154 std::move(args_converter).template call<Return, Guard>(cap->f), policy, call.parent);
155
156
157 process_attributes<Extra...>::postcall(call, result);
158
159 return result;
160 };
161
162
163 process_attributes<Extra...>::init(extra..., rec);
164
165
166 static constexpr auto signature = _("(") + cast_in::arg_names + _(") -> ") + cast_out::name;
167 PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
168
169
170 initialize_generic(rec, signature.text, types.data(), sizeof...(Args));
171
172 if (cast_in::has_args) rec->has_args = true;
173 if (cast_in::has_kwargs) rec->has_kwargs = true;
174
175
176 using FunctionType = Return (*)(Args...);
177 constexpr bool is_function_ptr =
178 std::is_convertible<Func, FunctionType>::value &&
179 sizeof(capture) == sizeof(void *);
180 if (is_function_ptr) {
181 rec->is_stateless = true;
182 rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
183 }
184 }
185
186
187 void initialize_generic(detail::function_record *rec, const char *text,
188 const std::type_info *const *types, size_t args) {
189
190
191 rec->name = strdup(rec->name ? rec->name : "");
192 if (rec->doc) rec->doc = strdup(rec->doc);
193 for (auto &a: rec->args) {
194 if (a.name)
195 a.name = strdup(a.name);
196 if (a.descr)
197 a.descr = strdup(a.descr);
198 else if (a.value)
199 a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
200 }
201
202 rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
203
204 #if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
205 if (rec->is_constructor && !rec->is_new_style_constructor) {
206 const auto class_name = std::string(((PyTypeObject *) rec->scope.ptr())->tp_name);
207 const auto func_name = std::string(rec->name);
208 PyErr_WarnEx(
209 PyExc_FutureWarning,
210 ("pybind11-bound class '" + class_name + "' is using an old-style "
211 "placement-new '" + func_name + "' which has been deprecated. See "
212 "the upgrade guide in pybind11's docs. This message is only visible "
213 "when compiled in debug mode.").c_str(), 0
214 );
215 }
216 #endif
217
218
219 std::string signature;
220 size_t type_index = 0, arg_index = 0;
221 for (auto *pc = text; *pc != '\0'; ++pc) {
222 const auto c = *pc;
223
224 if (c == '{') {
225
226 if (*(pc + 1) == '*')
227 continue;
228
229 if (arg_index < rec->args.size() && rec->args[arg_index].name) {
230 signature += rec->args[arg_index].name;
231 } else if (arg_index == 0 && rec->is_method) {
232 signature += "self";
233 } else {
234 signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
235 }
236 signature += ": ";
237 } else if (c == '}') {
238
239 if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
240 signature += " = ";
241 signature += rec->args[arg_index].descr;
242 }
243 arg_index++;
244 } else if (c == '%') {
245 const std::type_info *t = types[type_index++];
246 if (!t)
247 pybind11_fail("Internal error while parsing type signature (1)");
248 if (auto tinfo = detail::get_type_info(*t)) {
249 handle th((PyObject *) tinfo->type);
250 signature +=
251 th.attr("__module__").cast<std::string>() + "." +
252 th.attr("__qualname__").cast<std::string>();
253 } else if (rec->is_new_style_constructor && arg_index == 0) {
254
255
256 signature +=
257 rec->scope.attr("__module__").cast<std::string>() + "." +
258 rec->scope.attr("__qualname__").cast<std::string>();
259 } else {
260 std::string tname(t->name());
261 detail::clean_type_id(tname);
262 signature += tname;
263 }
264 } else {
265 signature += c;
266 }
267 }
268 if (arg_index != args || types[type_index] != nullptr)
269 pybind11_fail("Internal error while parsing type signature (2)");
270
271 #if PY_MAJOR_VERSION < 3
272 if (strcmp(rec->name, "__next__") == 0) {
273 std::free(rec->name);
274 rec->name = strdup("next");
275 } else if (strcmp(rec->name, "__bool__") == 0) {
276 std::free(rec->name);
277 rec->name = strdup("__nonzero__");
278 }
279 #endif
280 rec->signature = strdup(signature.c_str());
281 rec->args.shrink_to_fit();
282 rec->nargs = (std::uint16_t) args;
283
284 if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr()))
285 rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
286
287 detail::function_record *chain = nullptr, *chain_start = rec;
288 if (rec->sibling) {
289 if (PyCFunction_Check(rec->sibling.ptr())) {
290 auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
291 chain = (detail::function_record *) rec_capsule;
292
293 if (!chain->scope.is(rec->scope))
294 chain = nullptr;
295 }
296
297 else if (!rec->sibling.is_none() && rec->name[0] != '_')
298 pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
299 "\" with a function of the same name");
300 }
301
302 if (!chain) {
303
304 rec->def = new PyMethodDef();
305 std::memset(rec->def, 0, sizeof(PyMethodDef));
306 rec->def->ml_name = rec->name;
307 rec->def->ml_meth = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(*dispatcher));
308 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
309
310 capsule rec_capsule(rec, [](void *ptr) {
311 destruct((detail::function_record *) ptr);
312 });
313
314 object scope_module;
315 if (rec->scope) {
316 if (hasattr(rec->scope, "__module__")) {
317 scope_module = rec->scope.attr("__module__");
318 } else if (hasattr(rec->scope, "__name__")) {
319 scope_module = rec->scope.attr("__name__");
320 }
321 }
322
323 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
324 if (!m_ptr)
325 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
326 } else {
327
328 m_ptr = rec->sibling.ptr();
329 inc_ref();
330 chain_start = chain;
331 if (chain->is_method != rec->is_method)
332 pybind11_fail("overloading a method with both static and instance methods is not supported; "
333 #if defined(NDEBUG)
334 "compile in debug mode for more details"
335 #else
336 "error while attempting to bind " + std::string(rec->is_method ? "instance" : "static") + " method " +
337 std::string(pybind11::str(rec->scope.attr("__name__"))) + "." + std::string(rec->name) + signature
338 #endif
339 );
340 while (chain->next)
341 chain = chain->next;
342 chain->next = rec;
343 }
344
345 std::string signatures;
346 int index = 0;
347
348 if (chain && options::show_function_signatures()) {
349
350 signatures += rec->name;
351 signatures += "(*args, **kwargs)\n";
352 signatures += "Overloaded function.\n\n";
353 }
354
355 bool first_user_def = true;
356 for (auto it = chain_start; it != nullptr; it = it->next) {
357 if (options::show_function_signatures()) {
358 if (index > 0) signatures += "\n";
359 if (chain)
360 signatures += std::to_string(++index) + ". ";
361 signatures += rec->name;
362 signatures += it->signature;
363 signatures += "\n";
364 }
365 if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
366
367
368 if (!options::show_function_signatures()) {
369 if (first_user_def) first_user_def = false;
370 else signatures += "\n";
371 }
372 if (options::show_function_signatures()) signatures += "\n";
373 signatures += it->doc;
374 if (options::show_function_signatures()) signatures += "\n";
375 }
376 }
377
378
379 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
380 if (func->m_ml->ml_doc)
381 std::free(const_cast<char *>(func->m_ml->ml_doc));
382 func->m_ml->ml_doc = strdup(signatures.c_str());
383
384 if (rec->is_method) {
385 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
386 if (!m_ptr)
387 pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
388 Py_DECREF(func);
389 }
390 }
391
392
393 static void destruct(detail::function_record *rec) {
394 while (rec) {
395 detail::function_record *next = rec->next;
396 if (rec->free_data)
397 rec->free_data(rec);
398 std::free((char *) rec->name);
399 std::free((char *) rec->doc);
400 std::free((char *) rec->signature);
401 for (auto &arg: rec->args) {
402 std::free(const_cast<char *>(arg.name));
403 std::free(const_cast<char *>(arg.descr));
404 arg.value.dec_ref();
405 }
406 if (rec->def) {
407 std::free(const_cast<char *>(rec->def->ml_doc));
408 delete rec->def;
409 }
410 delete rec;
411 rec = next;
412 }
413 }
414
415
416 static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
417 using namespace detail;
418
419
420 const function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
421 *it = overloads;
422
423
424 const size_t n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
425
426 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
427 result = PYBIND11_TRY_NEXT_OVERLOAD;
428
429 auto self_value_and_holder = value_and_holder();
430 if (overloads->is_constructor) {
431 const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
432 const auto pi = reinterpret_cast<instance *>(parent.ptr());
433 self_value_and_holder = pi->get_value_and_holder(tinfo, false);
434
435 if (!self_value_and_holder.type || !self_value_and_holder.inst) {
436 PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid `self` argument");
437 return nullptr;
438 }
439
440
441
442 if (self_value_and_holder.instance_registered())
443 return none().release().ptr();
444 }
445
446 try {
447
448
449
450
451 std::vector<function_call> second_pass;
452
453
454 const bool overloaded = it != nullptr && it->next != nullptr;
455
456 for (; it != nullptr; it = it->next) {
457
458
459
460 const function_record &func = *it;
461 size_t pos_args = func.nargs;
462 if (func.has_args) --pos_args;
463 if (func.has_kwargs) --pos_args;
464
465 if (!func.has_args && n_args_in > pos_args)
466 continue;
467
468 if (n_args_in < pos_args && func.args.size() < pos_args)
469 continue;
470
471 function_call call(func, parent);
472
473 size_t args_to_copy = std::min(pos_args, n_args_in);
474 size_t args_copied = 0;
475
476
477 if (func.is_new_style_constructor) {
478
479
480 if (self_value_and_holder)
481 self_value_and_holder.type->dealloc(self_value_and_holder);
482
483 call.init_self = PyTuple_GET_ITEM(args_in, 0);
484 call.args.push_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
485 call.args_convert.push_back(false);
486 ++args_copied;
487 }
488
489
490 bool bad_arg = false;
491 for (; args_copied < args_to_copy; ++args_copied) {
492 const argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
493 if (kwargs_in && arg_rec && arg_rec->name && PyDict_GetItemString(kwargs_in, arg_rec->name)) {
494 bad_arg = true;
495 break;
496 }
497
498 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
499 if (arg_rec && !arg_rec->none && arg.is_none()) {
500 bad_arg = true;
501 break;
502 }
503 call.args.push_back(arg);
504 call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
505 }
506 if (bad_arg)
507 continue;
508
509
510 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
511
512
513 if (args_copied < pos_args) {
514 bool copied_kwargs = false;
515
516 for (; args_copied < pos_args; ++args_copied) {
517 const auto &arg = func.args[args_copied];
518
519 handle value;
520 if (kwargs_in && arg.name)
521 value = PyDict_GetItemString(kwargs.ptr(), arg.name);
522
523 if (value) {
524
525 if (!copied_kwargs) {
526 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
527 copied_kwargs = true;
528 }
529 PyDict_DelItemString(kwargs.ptr(), arg.name);
530 } else if (arg.value) {
531 value = arg.value;
532 }
533
534 if (value) {
535 call.args.push_back(value);
536 call.args_convert.push_back(arg.convert);
537 }
538 else
539 break;
540 }
541
542 if (args_copied < pos_args)
543 continue;
544 }
545
546
547 if (kwargs && kwargs.size() > 0 && !func.has_kwargs)
548 continue;
549
550
551 if (func.has_args) {
552 tuple extra_args;
553 if (args_to_copy == 0) {
554
555
556 extra_args = reinterpret_borrow<tuple>(args_in);
557 } else if (args_copied >= n_args_in) {
558 extra_args = tuple(0);
559 } else {
560 size_t args_size = n_args_in - args_copied;
561 extra_args = tuple(args_size);
562 for (size_t i = 0; i < args_size; ++i) {
563 extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i);
564 }
565 }
566 call.args.push_back(extra_args);
567 call.args_convert.push_back(false);
568 call.args_ref = std::move(extra_args);
569 }
570
571
572 if (func.has_kwargs) {
573 if (!kwargs.ptr())
574 kwargs = dict();
575 call.args.push_back(kwargs);
576 call.args_convert.push_back(false);
577 call.kwargs_ref = std::move(kwargs);
578 }
579
580
581
582 #if !defined(NDEBUG)
583 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
584 pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
585 #endif
586
587 std::vector<bool> second_pass_convert;
588 if (overloaded) {
589
590
591
592 second_pass_convert.resize(func.nargs, false);
593 call.args_convert.swap(second_pass_convert);
594 }
595
596
597 try {
598 loader_life_support guard{};
599 result = func.impl(call);
600 } catch (reference_cast_error &) {
601 result = PYBIND11_TRY_NEXT_OVERLOAD;
602 }
603
604 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
605 break;
606
607 if (overloaded) {
608
609
610
611 for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
612 if (second_pass_convert[i]) {
613
614
615 call.args_convert.swap(second_pass_convert);
616 second_pass.push_back(std::move(call));
617 break;
618 }
619 }
620 }
621 }
622
623 if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
624
625 for (auto &call : second_pass) {
626 try {
627 loader_life_support guard{};
628 result = call.func.impl(call);
629 } catch (reference_cast_error &) {
630 result = PYBIND11_TRY_NEXT_OVERLOAD;
631 }
632
633 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
634
635
636 if (!result)
637 it = &call.func;
638 break;
639 }
640 }
641 }
642 } catch (error_already_set &e) {
643 e.restore();
644 return nullptr;
645 } catch (...) {
646
647
648 auto last_exception = std::current_exception();
649 auto ®istered_exception_translators = get_internals().registered_exception_translators;
650 for (auto& translator : registered_exception_translators) {
651 try {
652 translator(last_exception);
653 } catch (...) {
654 last_exception = std::current_exception();
655 continue;
656 }
657 return nullptr;
658 }
659 PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
660 return nullptr;
661 }
662
663 auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
664 if (msg.find("std::") != std::string::npos) {
665 msg += "\n\n"
666 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
667 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
668 "conversions are optional and require extra headers to be included\n"
669 "when compiling your pybind11 module.";
670 }
671 };
672
673 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
674 if (overloads->is_operator)
675 return handle(Py_NotImplemented).inc_ref().ptr();
676
677 std::string msg = std::string(overloads->name) + "(): incompatible " +
678 std::string(overloads->is_constructor ? "constructor" : "function") +
679 " arguments. The following argument types are supported:\n";
680
681 int ctr = 0;
682 for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
683 msg += " "+ std::to_string(++ctr) + ". ";
684
685 bool wrote_sig = false;
686 if (overloads->is_constructor) {
687
688 std::string sig = it2->signature;
689 size_t start = sig.find('(') + 7;
690 if (start < sig.size()) {
691
692 size_t end = sig.find(", "), next = end + 2;
693 size_t ret = sig.rfind(" -> ");
694
695 if (end >= sig.size()) next = end = sig.find(')');
696 if (start < end && next < sig.size()) {
697 msg.append(sig, start, end - start);
698 msg += '(';
699 msg.append(sig, next, ret - next);
700 wrote_sig = true;
701 }
702 }
703 }
704 if (!wrote_sig) msg += it2->signature;
705
706 msg += "\n";
707 }
708 msg += "\nInvoked with: ";
709 auto args_ = reinterpret_borrow<tuple>(args_in);
710 bool some_args = false;
711 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
712 if (!some_args) some_args = true;
713 else msg += ", ";
714 msg += pybind11::repr(args_[ti]);
715 }
716 if (kwargs_in) {
717 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
718 if (kwargs.size() > 0) {
719 if (some_args) msg += "; ";
720 msg += "kwargs: ";
721 bool first = true;
722 for (auto kwarg : kwargs) {
723 if (first) first = false;
724 else msg += ", ";
725 msg += pybind11::str("{}={!r}").format(kwarg.first, kwarg.second);
726 }
727 }
728 }
729
730 append_note_if_missing_header_is_suspected(msg);
731 PyErr_SetString(PyExc_TypeError, msg.c_str());
732 return nullptr;
733 } else if (!result) {
734 std::string msg = "Unable to convert function return value to a "
735 "Python type! The signature was\n\t";
736 msg += it->signature;
737 append_note_if_missing_header_is_suspected(msg);
738 PyErr_SetString(PyExc_TypeError, msg.c_str());
739 return nullptr;
740 } else {
741 if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
742 auto *pi = reinterpret_cast<instance *>(parent.ptr());
743 self_value_and_holder.type->init_instance(pi, nullptr);
744 }
745 return result.ptr();
746 }
747 }
748 };
749
750
751 class module : public object {
752 public:
PYBIND11_OBJECT_DEFAULT(module,object,PyModule_Check)753 PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
754
755
756 explicit module(const char *name, const char *doc = nullptr) {
757 if (!options::show_user_defined_docstrings()) doc = nullptr;
758 #if PY_MAJOR_VERSION >= 3
759 PyModuleDef *def = new PyModuleDef();
760 std::memset(def, 0, sizeof(PyModuleDef));
761 def->m_name = name;
762 def->m_doc = doc;
763 def->m_size = -1;
764 Py_INCREF(def);
765 m_ptr = PyModule_Create(def);
766 #else
767 m_ptr = Py_InitModule3(name, nullptr, doc);
768 #endif
769 if (m_ptr == nullptr)
770 pybind11_fail("Internal error in module::module()");
771 inc_ref();
772 }
773
774
775 template <typename Func, typename... Extra>
def(const char * name_,Func && f,const Extra &...extra)776 module &def(const char *name_, Func &&f, const Extra& ... extra) {
777 cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
778 sibling(getattr(*this, name_, none())), extra...);
779
780
781 add_object(name_, func, true );
782 return *this;
783 }
784
785
786 module def_submodule(const char *name, const char *doc = nullptr) {
787 std::string full_name = std::string(PyModule_GetName(m_ptr))
788 + std::string(".") + std::string(name);
789 auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
790 if (doc && options::show_user_defined_docstrings())
791 result.attr("__doc__") = pybind11::str(doc);
792 attr(name) = result;
793 return result;
794 }
795
796
import(const char * name)797 static module import(const char *name) {
798 PyObject *obj = PyImport_ImportModule(name);
799 if (!obj)
800 throw error_already_set();
801 return reinterpret_steal<module>(obj);
802 }
803
804
reload()805 void reload() {
806 PyObject *obj = PyImport_ReloadModule(ptr());
807 if (!obj)
808 throw error_already_set();
809 *this = reinterpret_steal<module>(obj);
810 }
811
812
813
814
815
816
817 PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
818 if (!overwrite && hasattr(*this, name))
819 pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
820 std::string(name) + "\"");
821
822 PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() );
823 }
824 };
825
826
827
828
globals()829 inline dict globals() {
830 PyObject *p = PyEval_GetGlobals();
831 return reinterpret_borrow<dict>(p ? p : module::import("__main__").attr("__dict__").ptr());
832 }
833
NAMESPACE_BEGIN(detail)834 NAMESPACE_BEGIN(detail)
835
836 class generic_type : public object {
837 template <typename...> friend class class_;
838 public:
839 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
840 protected:
841 void initialize(const type_record &rec) {
842 if (rec.scope && hasattr(rec.scope, rec.name))
843 pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
844 "\": an object with that name is already defined");
845
846 if (rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
847 pybind11_fail("generic_type: type \"" + std::string(rec.name) +
848 "\" is already registered!");
849
850 m_ptr = make_new_python_type(rec);
851
852
853 auto *tinfo = new detail::type_info();
854 tinfo->type = (PyTypeObject *) m_ptr;
855 tinfo->cpptype = rec.type;
856 tinfo->type_size = rec.type_size;
857 tinfo->type_align = rec.type_align;
858 tinfo->operator_new = rec.operator_new;
859 tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
860 tinfo->init_instance = rec.init_instance;
861 tinfo->dealloc = rec.dealloc;
862 tinfo->simple_type = true;
863 tinfo->simple_ancestors = true;
864 tinfo->default_holder = rec.default_holder;
865 tinfo->module_local = rec.module_local;
866
867 auto &internals = get_internals();
868 auto tindex = std::type_index(*rec.type);
869 tinfo->direct_conversions = &internals.direct_conversions[tindex];
870 if (rec.module_local)
871 registered_local_types_cpp()[tindex] = tinfo;
872 else
873 internals.registered_types_cpp[tindex] = tinfo;
874 internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo };
875
876 if (rec.bases.size() > 1 || rec.multiple_inheritance) {
877 mark_parents_nonsimple(tinfo->type);
878 tinfo->simple_ancestors = false;
879 }
880 else if (rec.bases.size() == 1) {
881 auto parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
882 tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
883 }
884
885 if (rec.module_local) {
886
887 tinfo->module_local_load = &type_caster_generic::local_load;
888 setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
889 }
890 }
891
892
893 void mark_parents_nonsimple(PyTypeObject *value) {
894 auto t = reinterpret_borrow<tuple>(value->tp_bases);
895 for (handle h : t) {
896 auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
897 if (tinfo2)
898 tinfo2->simple_type = false;
899 mark_parents_nonsimple((PyTypeObject *) h.ptr());
900 }
901 }
902
903 void install_buffer_funcs(
904 buffer_info *(*get_buffer)(PyObject *, void *),
905 void *get_buffer_data) {
906 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
907 auto tinfo = detail::get_type_info(&type->ht_type);
908
909 if (!type->ht_type.tp_as_buffer)
910 pybind11_fail(
911 "To be able to register buffer protocol support for the type '" +
912 std::string(tinfo->type->tp_name) +
913 "' the associated class<>(..) invocation must "
914 "include the pybind11::buffer_protocol() annotation!");
915
916 tinfo->get_buffer = get_buffer;
917 tinfo->get_buffer_data = get_buffer_data;
918 }
919
920
921 void def_property_static_impl(const char *name,
922 handle fget, handle fset,
923 detail::function_record *rec_func) {
924 const auto is_static = rec_func && !(rec_func->is_method && rec_func->scope);
925 const auto has_doc = rec_func && rec_func->doc && pybind11::options::show_user_defined_docstrings();
926 auto property = handle((PyObject *) (is_static ? get_internals().static_property_type
927 : &PyProperty_Type));
928 attr(name) = property(fget.ptr() ? fget : none(),
929 fset.ptr() ? fset : none(),
930 none(),
931 pybind11::str(has_doc ? rec_func->doc : ""));
932 }
933 };
934
935
936 template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator new))>>
set_operator_new(type_record * r)937 void set_operator_new(type_record *r) { r->operator_new = &T::operator new; }
938
set_operator_new(...)939 template <typename> void set_operator_new(...) { }
940
941 template <typename T, typename SFINAE = void> struct has_operator_delete : std::false_type { };
942 template <typename T> struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
943 : std::true_type { };
944 template <typename T, typename SFINAE = void> struct has_operator_delete_size : std::false_type { };
945 template <typename T> struct has_operator_delete_size<T, void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>>
946 : std::true_type { };
947
948 template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
949 void call_operator_delete(T *p, size_t, size_t) { T::operator delete(p); }
950 template <typename T, enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> = 0>
951 void call_operator_delete(T *p, size_t s, size_t) { T::operator delete(p, s); }
952
953 inline void call_operator_delete(void *p, size_t s, size_t a) {
954 (void)s; (void)a;
955 #if defined(PYBIND11_CPP17)
956 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
957 ::operator delete(p, s, std::align_val_t(a));
958 else
959 ::operator delete(p, s);
960 #else
961 ::operator delete(p);
962 #endif
963 }
964
965 NAMESPACE_END(detail)
966
967
968
969 template <typename , typename F>
970 auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) { return std::forward<F>(f); }
971
972 template <typename Derived, typename Return, typename Class, typename... Args>
973 auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
974 static_assert(detail::is_accessible_base_of<Class, Derived>::value,
975 "Cannot bind an inaccessible base class method; use a lambda definition instead");
976 return pmf;
977 }
978
979 template <typename Derived, typename Return, typename Class, typename... Args>
980 auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
981 static_assert(detail::is_accessible_base_of<Class, Derived>::value,
982 "Cannot bind an inaccessible base class method; use a lambda definition instead");
983 return pmf;
984 }
985
986 template <typename type_, typename... options>
987 class class_ : public detail::generic_type {
988 template <typename T> using is_holder = detail::is_holder_type<type_, T>;
989 template <typename T> using is_subtype = detail::is_strict_base_of<type_, T>;
990 template <typename T> using is_base = detail::is_strict_base_of<T, type_>;
991
992 template <typename T> struct is_valid_class_option :
993 detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
994
995 public:
996 using type = type_;
997 using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
998 constexpr static bool has_alias = !std::is_void<type_alias>::value;
999 using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
1000
1001 static_assert(detail::all_of<is_valid_class_option<options>...>::value,
1002 "Unknown/invalid class_ template parameters provided");
1003
1004 static_assert(!has_alias || std::is_polymorphic<type>::value,
1005 "Cannot use an alias class with a non-polymorphic type");
1006
1007 PYBIND11_OBJECT(class_, generic_type, PyType_Check)
1008
1009 template <typename... Extra>
1010 class_(handle scope, const char *name, const Extra &... extra) {
1011 using namespace detail;
1012
1013
1014 static_assert(
1015 none_of<is_pyobject<Extra>...>::value ||
1016 ( constexpr_sum(is_pyobject<Extra>::value...) == 1 &&
1017 constexpr_sum(is_base<options>::value...) == 0 &&
1018 none_of<std::is_same<multiple_inheritance, Extra>...>::value),
1019 "Error: multiple inheritance bases must be specified via class_ template options");
1020
1021 type_record record;
1022 record.scope = scope;
1023 record.name = name;
1024 record.type = &typeid(type);
1025 record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
1026 record.type_align = alignof(conditional_t<has_alias, type_alias, type>&);
1027 record.holder_size = sizeof(holder_type);
1028 record.init_instance = init_instance;
1029 record.dealloc = dealloc;
1030 record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
1031
1032 set_operator_new<type>(&record);
1033
1034
1035 PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
1036
1037
1038 process_attributes<Extra...>::init(extra..., &record);
1039
1040 generic_type::initialize(record);
1041
1042 if (has_alias) {
1043 auto &instances = record.module_local ? registered_local_types_cpp() : get_internals().registered_types_cpp;
1044 instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
1045 }
1046 }
1047
1048 template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
1049 static void add_base(detail::type_record &rec) {
1050 rec.add_base(typeid(Base), [](void *src) -> void * {
1051 return static_cast<Base *>(reinterpret_cast<type *>(src));
1052 });
1053 }
1054
1055 template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
1056 static void add_base(detail::type_record &) { }
1057
1058 template <typename Func, typename... Extra>
1059 class_ &def(const char *name_, Func&& f, const Extra&... extra) {
1060 cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), name(name_), is_method(*this),
1061 sibling(getattr(*this, name_, none())), extra...);
1062 attr(cf.name()) = cf;
1063 return *this;
1064 }
1065
1066 template <typename Func, typename... Extra> class_ &
1067 def_static(const char *name_, Func &&f, const Extra&... extra) {
1068 static_assert(!std::is_member_function_pointer<Func>::value,
1069 "def_static(...) called with a non-static member function pointer");
1070 cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
1071 sibling(getattr(*this, name_, none())), extra...);
1072 attr(cf.name()) = cf;
1073 return *this;
1074 }
1075
1076 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
1077 class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
1078 op.execute(*this, extra...);
1079 return *this;
1080 }
1081
1082 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
1083 class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
1084 op.execute_cast(*this, extra...);
1085 return *this;
1086 }
1087
1088 template <typename... Args, typename... Extra>
1089 class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra&... extra) {
1090 init.execute(*this, extra...);
1091 return *this;
1092 }
1093
1094 template <typename... Args, typename... Extra>
1095 class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra&... extra) {
1096 init.execute(*this, extra...);
1097 return *this;
1098 }
1099
1100 template <typename... Args, typename... Extra>
1101 class_ &def(detail::initimpl::factory<Args...> &&init, const Extra&... extra) {
1102 std::move(init).execute(*this, extra...);
1103 return *this;
1104 }
1105
1106 template <typename... Args, typename... Extra>
1107 class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
1108 std::move(pf).execute(*this, extra...);
1109 return *this;
1110 }
1111
1112 template <typename Func> class_& def_buffer(Func &&func) {
1113 struct capture { Func func; };
1114 capture *ptr = new capture { std::forward<Func>(func) };
1115 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
1116 detail::make_caster<type> caster;
1117 if (!caster.load(obj, false))
1118 return nullptr;
1119 return new buffer_info(((capture *) ptr)->func(caster));
1120 }, ptr);
1121 return *this;
1122 }
1123
1124 template <typename Return, typename Class, typename... Args>
1125 class_ &def_buffer(Return (Class::*func)(Args...)) {
1126 return def_buffer([func] (type &obj) { return (obj.*func)(); });
1127 }
1128
1129 template <typename Return, typename Class, typename... Args>
1130 class_ &def_buffer(Return (Class::*func)(Args...) const) {
1131 return def_buffer([func] (const type &obj) { return (obj.*func)(); });
1132 }
1133
1134 template <typename C, typename D, typename... Extra>
1135 class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
1136 static_assert(std::is_base_of<C, type>::value, "def_readwrite() requires a class member (or base class member)");
1137 cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this)),
1138 fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
1139 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
1140 return *this;
1141 }
1142
1143 template <typename C, typename D, typename... Extra>
1144 class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
1145 static_assert(std::is_base_of<C, type>::value, "def_readonly() requires a class member (or base class member)");
1146 cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this));
1147 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
1148 return *this;
1149 }
1150
1151 template <typename D, typename... Extra>
1152 class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
1153 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
1154 fset([pm](object, const D &value) { *pm = value; }, scope(*this));
1155 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
1156 return *this;
1157 }
1158
1159 template <typename D, typename... Extra>
1160 class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
1161 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
1162 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
1163 return *this;
1164 }
1165
1166
1167 template <typename Getter, typename... Extra>
1168 class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
1169 return def_property_readonly(name, cpp_function(method_adaptor<type>(fget)),
1170 return_value_policy::reference_internal, extra...);
1171 }
1172
1173
1174 template <typename... Extra>
1175 class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
1176 return def_property(name, fget, nullptr, extra...);
1177 }
1178
1179
1180 template <typename Getter, typename... Extra>
1181 class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
1182 return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...);
1183 }
1184
1185
1186 template <typename... Extra>
1187 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
1188 return def_property_static(name, fget, nullptr, extra...);
1189 }
1190
1191
1192 template <typename Getter, typename Setter, typename... Extra>
1193 class_ &def_property(const char *name, const Getter &fget, const Setter &fset, const Extra& ...extra) {
1194 return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
1195 }
1196 template <typename Getter, typename... Extra>
1197 class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1198 return def_property(name, cpp_function(method_adaptor<type>(fget)), fset,
1199 return_value_policy::reference_internal, extra...);
1200 }
1201
1202
1203 template <typename... Extra>
1204 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1205 return def_property_static(name, fget, fset, is_method(*this), extra...);
1206 }
1207
1208
1209 template <typename Getter, typename... Extra>
1210 class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1211 return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1212 }
1213
1214
1215 template <typename... Extra>
1216 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1217 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1218 auto *rec_active = rec_fget;
1219 if (rec_fget) {
1220 char *doc_prev = rec_fget->doc;
1221 detail::process_attributes<Extra...>::init(extra..., rec_fget);
1222 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1223 free(doc_prev);
1224 rec_fget->doc = strdup(rec_fget->doc);
1225 }
1226 }
1227 if (rec_fset) {
1228 char *doc_prev = rec_fset->doc;
1229 detail::process_attributes<Extra...>::init(extra..., rec_fset);
1230 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1231 free(doc_prev);
1232 rec_fset->doc = strdup(rec_fset->doc);
1233 }
1234 if (! rec_active) rec_active = rec_fset;
1235 }
1236 def_property_static_impl(name, fget, fset, rec_active);
1237 return *this;
1238 }
1239
1240 private:
1241
1242 template <typename T>
1243 static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1244 const holder_type * , const std::enable_shared_from_this<T> * ) {
1245 try {
1246 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1247 v_h.value_ptr<type>()->shared_from_this());
1248 if (sh) {
1249 new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
1250 v_h.set_holder_constructed();
1251 }
1252 } catch (const std::bad_weak_ptr &) {}
1253
1254 if (!v_h.holder_constructed() && inst->owned) {
1255 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1256 v_h.set_holder_constructed();
1257 }
1258 }
1259
1260 static void init_holder_from_existing(const detail::value_and_holder &v_h,
1261 const holder_type *holder_ptr, std::true_type ) {
1262 new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1263 }
1264
1265 static void init_holder_from_existing(const detail::value_and_holder &v_h,
1266 const holder_type *holder_ptr, std::false_type ) {
1267 new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1268 }
1269
1270
1271 static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1272 const holder_type *holder_ptr, const void * ) {
1273 if (holder_ptr) {
1274 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1275 v_h.set_holder_constructed();
1276 } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
1277 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1278 v_h.set_holder_constructed();
1279 }
1280 }
1281
1282
1283
1284
1285
1286 static void init_instance(detail::instance *inst, const void *holder_ptr) {
1287 auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
1288 if (!v_h.instance_registered()) {
1289 register_instance(inst, v_h.value_ptr(), v_h.type);
1290 v_h.set_instance_registered();
1291 }
1292 init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
1293 }
1294
1295
1296 static void dealloc(detail::value_and_holder &v_h) {
1297 if (v_h.holder_constructed()) {
1298 v_h.holder<holder_type>().~holder_type();
1299 v_h.set_holder_constructed(false);
1300 }
1301 else {
1302 detail::call_operator_delete(v_h.value_ptr<type>(),
1303 v_h.type->type_size,
1304 v_h.type->type_align
1305 );
1306 }
1307 v_h.value_ptr() = nullptr;
1308 }
1309
1310 static detail::function_record *get_function_record(handle h) {
1311 h = detail::get_function(h);
1312 return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
1313 : nullptr;
1314 }
1315 };
1316
1317
1318 template <typename... Args> detail::initimpl::constructor<Args...> init() { return {}; }
1319
1320
1321 template <typename... Args> detail::initimpl::alias_constructor<Args...> init_alias() { return {}; }
1322
1323
1324 template <typename Func, typename Ret = detail::initimpl::factory<Func>>
1325 Ret init(Func &&f) { return {std::forward<Func>(f)}; }
1326
1327
1328
1329 template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1330 Ret init(CFunc &&c, AFunc &&a) {
1331 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1332 }
1333
1334
1335
1336 template <typename GetState, typename SetState>
1337 detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
1338 return {std::forward<GetState>(g), std::forward<SetState>(s)};
1339 }
1340
1341 NAMESPACE_BEGIN(detail)
1342 struct enum_base {
1343 enum_base(handle base, handle parent) : m_base(base), m_parent(parent) { }
1344
1345 PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
1346 m_base.attr("__entries") = dict();
1347 auto property = handle((PyObject *) &PyProperty_Type);
1348 auto static_property = handle((PyObject *) get_internals().static_property_type);
1349
1350 m_base.attr("__repr__") = cpp_function(
1351 [](handle arg) -> str {
1352 handle type = arg.get_type();
1353 object type_name = type.attr("__name__");
1354 dict entries = type.attr("__entries");
1355 for (const auto &kv : entries) {
1356 object other = kv.second[int_(0)];
1357 if (other.equal(arg))
1358 return pybind11::str("{}.{}").format(type_name, kv.first);
1359 }
1360 return pybind11::str("{}.???").format(type_name);
1361 }, is_method(m_base)
1362 );
1363
1364 m_base.attr("name") = property(cpp_function(
1365 [](handle arg) -> str {
1366 dict entries = arg.get_type().attr("__entries");
1367 for (const auto &kv : entries) {
1368 if (handle(kv.second[int_(0)]).equal(arg))
1369 return pybind11::str(kv.first);
1370 }
1371 return "???";
1372 }, is_method(m_base)
1373 ));
1374
1375 m_base.attr("__doc__") = static_property(cpp_function(
1376 [](handle arg) -> std::string {
1377 std::string docstring;
1378 dict entries = arg.attr("__entries");
1379 if (((PyTypeObject *) arg.ptr())->tp_doc)
1380 docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) + "\n\n";
1381 docstring += "Members:";
1382 for (const auto &kv : entries) {
1383 auto key = std::string(pybind11::str(kv.first));
1384 auto comment = kv.second[int_(1)];
1385 docstring += "\n\n " + key;
1386 if (!comment.is_none())
1387 docstring += " : " + (std::string) pybind11::str(comment);
1388 }
1389 return docstring;
1390 }
1391 ), none(), none(), "");
1392
1393 m_base.attr("__members__") = static_property(cpp_function(
1394 [](handle arg) -> dict {
1395 dict entries = arg.attr("__entries"), m;
1396 for (const auto &kv : entries)
1397 m[kv.first] = kv.second[int_(0)];
1398 return m;
1399 }), none(), none(), ""
1400 );
1401
1402 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
1403 m_base.attr(op) = cpp_function( \
1404 [](object a, object b) { \
1405 if (!a.get_type().is(b.get_type())) \
1406 strict_behavior; \
1407 return expr; \
1408 }, \
1409 is_method(m_base))
1410
1411 #define PYBIND11_ENUM_OP_CONV(op, expr) \
1412 m_base.attr(op) = cpp_function( \
1413 [](object a_, object b_) { \
1414 int_ a(a_), b(b_); \
1415 return expr; \
1416 }, \
1417 is_method(m_base))
1418
1419 if (is_convertible) {
1420 PYBIND11_ENUM_OP_CONV("__eq__", !b.is_none() && a.equal(b));
1421 PYBIND11_ENUM_OP_CONV("__ne__", b.is_none() || !a.equal(b));
1422
1423 if (is_arithmetic) {
1424 PYBIND11_ENUM_OP_CONV("__lt__", a < b);
1425 PYBIND11_ENUM_OP_CONV("__gt__", a > b);
1426 PYBIND11_ENUM_OP_CONV("__le__", a <= b);
1427 PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
1428 PYBIND11_ENUM_OP_CONV("__and__", a & b);
1429 PYBIND11_ENUM_OP_CONV("__rand__", a & b);
1430 PYBIND11_ENUM_OP_CONV("__or__", a | b);
1431 PYBIND11_ENUM_OP_CONV("__ror__", a | b);
1432 PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
1433 PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
1434 }
1435 } else {
1436 PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
1437 PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
1438
1439 if (is_arithmetic) {
1440 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
1441 PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
1442 PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
1443 PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
1444 PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
1445 #undef PYBIND11_THROW
1446 }
1447 }
1448
1449 #undef PYBIND11_ENUM_OP_CONV
1450 #undef PYBIND11_ENUM_OP_STRICT
1451
1452 object getstate = cpp_function(
1453 [](object arg) { return int_(arg); }, is_method(m_base));
1454
1455 m_base.attr("__getstate__") = getstate;
1456 m_base.attr("__hash__") = getstate;
1457 }
1458
1459 PYBIND11_NOINLINE void value(char const* name_, object value, const char *doc = nullptr) {
1460 dict entries = m_base.attr("__entries");
1461 str name(name_);
1462 if (entries.contains(name)) {
1463 std::string type_name = (std::string) str(m_base.attr("__name__"));
1464 throw value_error(type_name + ": element \"" + std::string(name_) + "\" already exists!");
1465 }
1466
1467 entries[name] = std::make_pair(value, doc);
1468 m_base.attr(name) = value;
1469 }
1470
1471 PYBIND11_NOINLINE void export_values() {
1472 dict entries = m_base.attr("__entries");
1473 for (const auto &kv : entries)
1474 m_parent.attr(kv.first) = kv.second[int_(0)];
1475 }
1476
1477 handle m_base;
1478 handle m_parent;
1479 };
1480
1481 NAMESPACE_END(detail)
1482
1483
1484 template <typename Type> class enum_ : public class_<Type> {
1485 public:
1486 using Base = class_<Type>;
1487 using Base::def;
1488 using Base::attr;
1489 using Base::def_property_readonly;
1490 using Base::def_property_readonly_static;
1491 using Scalar = typename std::underlying_type<Type>::type;
1492
1493 template <typename... Extra>
1494 enum_(const handle &scope, const char *name, const Extra&... extra)
1495 : class_<Type>(scope, name, extra...), m_base(*this, scope) {
1496 constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
1497 constexpr bool is_convertible = std::is_convertible<Type, Scalar>::value;
1498 m_base.init(is_arithmetic, is_convertible);
1499
1500 def(init([](Scalar i) { return static_cast<Type>(i); }));
1501 def("__int__", [](Type value) { return (Scalar) value; });
1502 #if PY_MAJOR_VERSION < 3
1503 def("__long__", [](Type value) { return (Scalar) value; });
1504 #endif
1505 cpp_function setstate(
1506 [](Type &value, Scalar arg) { value = static_cast<Type>(arg); },
1507 is_method(*this));
1508 attr("__setstate__") = setstate;
1509 }
1510
1511
1512 enum_& export_values() {
1513 m_base.export_values();
1514 return *this;
1515 }
1516
1517
1518 enum_& value(char const* name, Type value, const char *doc = nullptr) {
1519 m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
1520 return *this;
1521 }
1522
1523 private:
1524 detail::enum_base m_base;
1525 };
1526
1527 NAMESPACE_BEGIN(detail)
1528
1529
1530 inline void keep_alive_impl(handle nurse, handle patient) {
1531 if (!nurse || !patient)
1532 pybind11_fail("Could not activate keep_alive!");
1533
1534 if (patient.is_none() || nurse.is_none())
1535 return;
1536
1537 auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
1538 if (!tinfo.empty()) {
1539
1540 add_patient(nurse.ptr(), patient.ptr());
1541 }
1542 else {
1543
1544 cpp_function disable_lifesupport(
1545 [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
1546
1547 weakref wr(nurse, disable_lifesupport);
1548
1549 patient.inc_ref();
1550 (void) wr.release();
1551 }
1552 }
1553
1554 PYBIND11_NOINLINE inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
1555 auto get_arg = [&](size_t n) {
1556 if (n == 0)
1557 return ret;
1558 else if (n == 1 && call.init_self)
1559 return call.init_self;
1560 else if (n <= call.args.size())
1561 return call.args[n - 1];
1562 return handle();
1563 };
1564
1565 keep_alive_impl(get_arg(Nurse), get_arg(Patient));
1566 }
1567
1568 inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type) {
1569 auto res = get_internals().registered_types_py
1570 #ifdef __cpp_lib_unordered_map_try_emplace
1571 .try_emplace(type);
1572 #else
1573 .emplace(type, std::vector<detail::type_info *>());
1574 #endif
1575 if (res.second) {
1576
1577
1578 weakref((PyObject *) type, cpp_function([type](handle wr) {
1579 get_internals().registered_types_py.erase(type);
1580 wr.dec_ref();
1581 })).release();
1582 }
1583
1584 return res;
1585 }
1586
1587 template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
1588 struct iterator_state {
1589 Iterator it;
1590 Sentinel end;
1591 bool first_or_done;
1592 };
1593
1594 NAMESPACE_END(detail)
1595
1596
1597 template <return_value_policy Policy = return_value_policy::reference_internal,
1598 typename Iterator,
1599 typename Sentinel,
1600 typename ValueType = decltype(*std::declval<Iterator>()),
1601 typename... Extra>
1602 iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1603 typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
1604
1605 if (!detail::get_type_info(typeid(state), false)) {
1606 class_<state>(handle(), "iterator", pybind11::module_local())
1607 .def("__iter__", [](state &s) -> state& { return s; })
1608 .def("__next__", [](state &s) -> ValueType {
1609 if (!s.first_or_done)
1610 ++s.it;
1611 else
1612 s.first_or_done = false;
1613 if (s.it == s.end) {
1614 s.first_or_done = true;
1615 throw stop_iteration();
1616 }
1617 return *s.it;
1618 }, std::forward<Extra>(extra)..., Policy);
1619 }
1620
1621 return cast(state{first, last, true});
1622 }
1623
1624
1625
1626 template <return_value_policy Policy = return_value_policy::reference_internal,
1627 typename Iterator,
1628 typename Sentinel,
1629 typename KeyType = decltype((*std::declval<Iterator>()).first),
1630 typename... Extra>
1631 iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1632 typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
1633
1634 if (!detail::get_type_info(typeid(state), false)) {
1635 class_<state>(handle(), "iterator", pybind11::module_local())
1636 .def("__iter__", [](state &s) -> state& { return s; })
1637 .def("__next__", [](state &s) -> KeyType {
1638 if (!s.first_or_done)
1639 ++s.it;
1640 else
1641 s.first_or_done = false;
1642 if (s.it == s.end) {
1643 s.first_or_done = true;
1644 throw stop_iteration();
1645 }
1646 return (*s.it).first;
1647 }, std::forward<Extra>(extra)..., Policy);
1648 }
1649
1650 return cast(state{first, last, true});
1651 }
1652
1653
1654
1655 template <return_value_policy Policy = return_value_policy::reference_internal,
1656 typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
1657 return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
1658 }
1659
1660
1661
1662 template <return_value_policy Policy = return_value_policy::reference_internal,
1663 typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
1664 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
1665 }
1666
1667 template <typename InputType, typename OutputType> void implicitly_convertible() {
1668 struct set_flag {
1669 bool &flag;
1670 set_flag(bool &flag) : flag(flag) { flag = true; }
1671 ~set_flag() { flag = false; }
1672 };
1673 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
1674 static bool currently_used = false;
1675 if (currently_used)
1676 return nullptr;
1677 set_flag flag_helper(currently_used);
1678 if (!detail::make_caster<InputType>().load(obj, false))
1679 return nullptr;
1680 tuple args(1);
1681 args[0] = obj;
1682 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1683 if (result == nullptr)
1684 PyErr_Clear();
1685 return result;
1686 };
1687
1688 if (auto tinfo = detail::get_type_info(typeid(OutputType)))
1689 tinfo->implicit_conversions.push_back(implicit_caster);
1690 else
1691 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
1692 }
1693
1694 template <typename ExceptionTranslator>
1695 void register_exception_translator(ExceptionTranslator&& translator) {
1696 detail::get_internals().registered_exception_translators.push_front(
1697 std::forward<ExceptionTranslator>(translator));
1698 }
1699
1700
1701 template <typename type>
1702 class exception : public object {
1703 public:
1704 exception() = default;
1705 exception(handle scope, const char *name, PyObject *base = PyExc_Exception) {
1706 std::string full_name = scope.attr("__name__").cast<std::string>() +
1707 std::string(".") + name;
1708 m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base, NULL);
1709 if (hasattr(scope, name))
1710 pybind11_fail("Error during initialization: multiple incompatible "
1711 "definitions with name \"" + std::string(name) + "\"");
1712 scope.attr(name) = *this;
1713 }
1714
1715
1716 void operator()(const char *message) {
1717 PyErr_SetString(m_ptr, message);
1718 }
1719 };
1720
1721 NAMESPACE_BEGIN(detail)
1722
1723
1724
1725 template <typename CppException>
1726 exception<CppException> &get_exception_object() { static exception<CppException> ex; return ex; }
1727 NAMESPACE_END(detail)
1728
1729
1730 template <typename CppException>
1731 exception<CppException> ®ister_exception(handle scope,
1732 const char *name,
1733 PyObject *base = PyExc_Exception) {
1734 auto &ex = detail::get_exception_object<CppException>();
1735 if (!ex) ex = exception<CppException>(scope, name, base);
1736
1737 register_exception_translator([](std::exception_ptr p) {
1738 if (!p) return;
1739 try {
1740 std::rethrow_exception(p);
1741 } catch (const CppException &e) {
1742 detail::get_exception_object<CppException>()(e.what());
1743 }
1744 });
1745 return ex;
1746 }
1747
1748 NAMESPACE_BEGIN(detail)
1749 PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
1750 auto strings = tuple(args.size());
1751 for (size_t i = 0; i < args.size(); ++i) {
1752 strings[i] = str(args[i]);
1753 }
1754 auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
1755 auto line = sep.attr("join")(strings);
1756
1757 object file;
1758 if (kwargs.contains("file")) {
1759 file = kwargs["file"].cast<object>();
1760 } else {
1761 try {
1762 file = module::import("sys").attr("stdout");
1763 } catch (const error_already_set &) {
1764
1765 return;
1766 }
1767 }
1768
1769 auto write = file.attr("write");
1770 write(line);
1771 write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
1772
1773 if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
1774 file.attr("flush")();
1775 }
1776 NAMESPACE_END(detail)
1777
1778 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1779 void print(Args &&...args) {
1780 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
1781 detail::print(c.args(), c.kwargs());
1782 }
1783
1784 #if defined(WITH_THREAD) && !defined(PYPY_VERSION)
1785
1786
1787
1788 class gil_scoped_acquire {
1789 public:
1790 PYBIND11_NOINLINE gil_scoped_acquire() {
1791 auto const &internals = detail::get_internals();
1792 tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
1793
1794 if (!tstate) {
1795
1796 tstate = PyGILState_GetThisThreadState();
1797 }
1798
1799 if (!tstate) {
1800 tstate = PyThreadState_New(internals.istate);
1801 #if !defined(NDEBUG)
1802 if (!tstate)
1803 pybind11_fail("scoped_acquire: could not create thread state!");
1804 #endif
1805 tstate->gilstate_counter = 0;
1806 PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
1807 } else {
1808 release = detail::get_thread_state_unchecked() != tstate;
1809 }
1810
1811 if (release) {
1812
1813 #if defined(Py_DEBUG)
1814 PyInterpreterState *interp = tstate->interp;
1815 tstate->interp = nullptr;
1816 #endif
1817 PyEval_AcquireThread(tstate);
1818 #if defined(Py_DEBUG)
1819 tstate->interp = interp;
1820 #endif
1821 }
1822
1823 inc_ref();
1824 }
1825
1826 void inc_ref() {
1827 ++tstate->gilstate_counter;
1828 }
1829
1830 PYBIND11_NOINLINE void dec_ref() {
1831 --tstate->gilstate_counter;
1832 #if !defined(NDEBUG)
1833 if (detail::get_thread_state_unchecked() != tstate)
1834 pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
1835 if (tstate->gilstate_counter < 0)
1836 pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
1837 #endif
1838 if (tstate->gilstate_counter == 0) {
1839 #if !defined(NDEBUG)
1840 if (!release)
1841 pybind11_fail("scoped_acquire::dec_ref(): internal error!");
1842 #endif
1843 PyThreadState_Clear(tstate);
1844 PyThreadState_DeleteCurrent();
1845 PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
1846 release = false;
1847 }
1848 }
1849
1850 PYBIND11_NOINLINE ~gil_scoped_acquire() {
1851 dec_ref();
1852 if (release)
1853 PyEval_SaveThread();
1854 }
1855 private:
1856 PyThreadState *tstate = nullptr;
1857 bool release = true;
1858 };
1859
1860 class gil_scoped_release {
1861 public:
1862 explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
1863
1864
1865
1866 const auto &internals = detail::get_internals();
1867 tstate = PyEval_SaveThread();
1868 if (disassoc) {
1869 auto key = internals.tstate;
1870 PYBIND11_TLS_DELETE_VALUE(key);
1871 }
1872 }
1873 ~gil_scoped_release() {
1874 if (!tstate)
1875 return;
1876 PyEval_RestoreThread(tstate);
1877 if (disassoc) {
1878 auto key = detail::get_internals().tstate;
1879 PYBIND11_TLS_REPLACE_VALUE(key, tstate);
1880 }
1881 }
1882 private:
1883 PyThreadState *tstate;
1884 bool disassoc;
1885 };
1886 #elif defined(PYPY_VERSION)
1887 class gil_scoped_acquire {
1888 PyGILState_STATE state;
1889 public:
1890 gil_scoped_acquire() { state = PyGILState_Ensure(); }
1891 ~gil_scoped_acquire() { PyGILState_Release(state); }
1892 };
1893
1894 class gil_scoped_release {
1895 PyThreadState *state;
1896 public:
1897 gil_scoped_release() { state = PyEval_SaveThread(); }
1898 ~gil_scoped_release() { PyEval_RestoreThread(state); }
1899 };
1900 #else
1901 class gil_scoped_acquire { };
1902 class gil_scoped_release { };
1903 #endif
1904
1905 error_already_set::~error_already_set() {
1906 if (type) {
1907 error_scope scope;
1908 gil_scoped_acquire gil;
1909 type.release().dec_ref();
1910 value.release().dec_ref();
1911 trace.release().dec_ref();
1912 }
1913 }
1914
1915 inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
1916 handle self = detail::get_object_handle(this_ptr, this_type);
1917 if (!self)
1918 return function();
1919 handle type = self.get_type();
1920 auto key = std::make_pair(type.ptr(), name);
1921
1922
1923 auto &cache = detail::get_internals().inactive_overload_cache;
1924 if (cache.find(key) != cache.end())
1925 return function();
1926
1927 function overload = getattr(self, name, function());
1928 if (overload.is_cpp_function()) {
1929 cache.insert(key);
1930 return function();
1931 }
1932
1933
1934 #if !defined(PYPY_VERSION)
1935 PyFrameObject *frame = PyThreadState_Get()->frame;
1936 if (frame && (std::string) str(frame->f_code->co_name) == name &&
1937 frame->f_code->co_argcount > 0) {
1938 PyFrame_FastToLocals(frame);
1939 PyObject *self_caller = PyDict_GetItem(
1940 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
1941 if (self_caller == self.ptr())
1942 return function();
1943 }
1944 #else
1945
1946 dict d; d["self"] = self; d["name"] = pybind11::str(name);
1947 PyObject *result = PyRun_String(
1948 "import inspect\n"
1949 "frame = inspect.currentframe()\n"
1950 "if frame is not None:\n"
1951 " frame = frame.f_back\n"
1952 " if frame is not None and str(frame.f_code.co_name) == name and "
1953 "frame.f_code.co_argcount > 0:\n"
1954 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
1955 " if self_caller == self:\n"
1956 " self = None\n",
1957 Py_file_input, d.ptr(), d.ptr());
1958 if (result == nullptr)
1959 throw error_already_set();
1960 if (d["self"].is_none())
1961 return function();
1962 Py_DECREF(result);
1963 #endif
1964
1965 return overload;
1966 }
1967
1968 template <class T> function get_overload(const T *this_ptr, const char *name) {
1969 auto tinfo = detail::get_type_info(typeid(T));
1970 return tinfo ? get_type_overload(this_ptr, tinfo, name) : function();
1971 }
1972
1973 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
1974 pybind11::gil_scoped_acquire gil; \
1975 pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
1976 if (overload) { \
1977 auto o = overload(__VA_ARGS__); \
1978 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
1979 static pybind11::detail::overload_caster_t<ret_type> caster; \
1980 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
1981 } \
1982 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
1983 } \
1984 }
1985
1986 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
1987 PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
1988 return cname::fn(__VA_ARGS__)
1989
1990 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
1991 PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
1992 pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\"");
1993
1994 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
1995 PYBIND11_OVERLOAD_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
1996
1997 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
1998 PYBIND11_OVERLOAD_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
1999
2000 NAMESPACE_END(PYBIND11_NAMESPACE)
2001
2002 #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
2003 # pragma warning(pop)
2004 #elif defined(__GNUG__) && !defined(__clang__)
2005 # pragma GCC diagnostic pop
2006 #endif
2007