blob: 84577e97517275b727324361bc436f63748870b6 [file] [log] [blame]
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001/*
Wenzel Jakob48548ea2016-01-17 22:36:44 +01002 pybind11/pybind11.h: Main header file of the C++11 python
3 binding generator library
Wenzel Jakob38bd7112015-07-05 20:05:44 +02004
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +02005 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakob38bd7112015-07-05 20:05:44 +02006
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
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020011#pragma once
Wenzel Jakob38bd7112015-07-05 20:05:44 +020012
13#if defined(_MSC_VER)
Wenzel Jakob48548ea2016-01-17 22:36:44 +010014# pragma warning(push)
Wenzel Jakob1ffce742016-08-25 01:43:33 +020015# pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
Wenzel Jakob48548ea2016-01-17 22:36:44 +010016# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
Wenzel Jakob1ffce742016-08-25 01:43:33 +020017# pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
Wenzel Jakob48548ea2016-01-17 22:36:44 +010018# 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
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +090020# pragma warning(disable: 4702) // warning C4702: unreachable code
Dean Moldovan2bab5792016-09-23 00:27:59 +020021# pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
Wenzel Jakob1ffce742016-08-25 01:43:33 +020022#elif defined(__INTEL_COMPILER)
Ben Pritchard33f34302016-02-18 15:25:51 -050023# pragma warning(push)
Dean Moldovan706a7d92017-07-04 01:27:18 +020024# pragma warning(disable: 68) // integer conversion resulted in a change of sign
Wenzel Jakob1ffce742016-08-25 01:43:33 +020025# pragma warning(disable: 186) // pointless comparison of unsigned integer with zero
Dean Moldovan706a7d92017-07-04 01:27:18 +020026# pragma warning(disable: 878) // incompatible exception specifications
Wenzel Jakob1ffce742016-08-25 01:43:33 +020027# pragma warning(disable: 1334) // the "template" keyword used for syntactic disambiguation may only be used within a template
Dean Moldovan706a7d92017-07-04 01:27:18 +020028# pragma warning(disable: 1682) // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem)
29# pragma warning(disable: 1875) // offsetof applied to non-POD (Plain Old Data) types is nonstandard
Wenzel Jakob1ffce742016-08-25 01:43:33 +020030# pragma warning(disable: 2196) // warning #2196: routine is both "inline" and "noinline"
Wenzel Jakob6d252962016-05-01 20:47:49 +020031#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +010032# pragma GCC diagnostic push
33# pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
34# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
35# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
Wenzel Jakobdeeab552016-05-15 23:54:34 +020036# pragma GCC diagnostic ignored "-Wstrict-aliasing"
37# pragma GCC diagnostic ignored "-Wattributes"
Jason Rhinelanderd15b2172017-05-09 14:46:15 -040038# if __GNUC__ >= 7
39# pragma GCC diagnostic ignored "-Wnoexcept-type"
40# endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +020041#endif
42
Wenzel Jakob48548ea2016-01-17 22:36:44 +010043#include "attr.h"
Alexander Stukowski9a110e62016-11-15 12:38:05 +010044#include "options.h"
Dean Moldovanf5806492017-08-14 00:35:53 +020045#include "detail/class.h"
Jason Rhinelander464d9892017-06-12 21:52:48 -040046#include "detail/init.h"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020047
Jason Rhinelandera859dd62017-08-10 12:03:29 -040048NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
Wenzel Jakob38bd7112015-07-05 20:05:44 +020049
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020050/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020051class cpp_function : public function {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020052public:
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020053 cpp_function() { }
Ted Drain0a0758c2017-11-07 08:35:27 -080054 cpp_function(std::nullptr_t) { }
Wenzel Jakob38bd7112015-07-05 20:05:44 +020055
Wenzel Jakob5984baa2016-05-10 15:05:03 +010056 /// Construct a cpp_function from a vanilla function pointer
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050057 template <typename Return, typename... Args, typename... Extra>
58 cpp_function(Return (*f)(Args...), const Extra&... extra) {
Wenzel Jakob5984baa2016-05-10 15:05:03 +010059 initialize(f, f, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +020060 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020061
Wenzel Jakob5984baa2016-05-10 15:05:03 +010062 /// Construct a cpp_function from a lambda function (possibly with internal state)
Jason Rhinelanderb4bf5ed2017-05-10 01:51:08 -040063 template <typename Func, typename... Extra,
64 typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050065 cpp_function(Func &&f, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020066 initialize(std::forward<Func>(f),
Jason Rhinelanderb4bf5ed2017-05-10 01:51:08 -040067 (detail::function_signature_t<Func> *) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020068 }
69
Wenzel Jakob5984baa2016-05-10 15:05:03 +010070 /// Construct a cpp_function from a class method (non-const)
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050071 template <typename Return, typename Class, typename... Arg, typename... Extra>
72 cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020073 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050074 (Return (*) (Class *, Arg...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020075 }
76
Wenzel Jakob5984baa2016-05-10 15:05:03 +010077 /// Construct a cpp_function from a class method (const)
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050078 template <typename Return, typename Class, typename... Arg, typename... Extra>
79 cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020080 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050081 (Return (*)(const Class *, Arg ...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020082 }
83
Wenzel Jakob57082212015-09-04 23:42:12 +020084 /// Return the function name
Wenzel Jakob48548ea2016-01-17 22:36:44 +010085 object name() const { return attr("__name__"); }
Wenzel Jakob57082212015-09-04 23:42:12 +020086
Wenzel Jakobd561cb02016-01-17 22:36:41 +010087protected:
Wenzel Jakob382484a2016-09-10 15:28:37 +090088 /// Space optimization: don't inline this frequently instantiated fragment
89 PYBIND11_NOINLINE detail::function_record *make_function_record() {
90 return new detail::function_record();
91 }
92
Wenzel Jakobd561cb02016-01-17 22:36:41 +010093 /// Special internal constructor for functors, lambda functions, etc.
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050094 template <typename Func, typename Return, typename... Args, typename... Extra>
95 void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
Dean Moldovan56613942017-07-02 12:52:00 +020096 using namespace detail;
Jason Rhinelander657a51e2018-01-12 12:06:46 -040097 struct capture { remove_reference_t<Func> f; };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020098
Wenzel Jakobd561cb02016-01-17 22:36:41 +010099 /* Store the function including any extra state it might have (e.g. a lambda capture object) */
Wenzel Jakob382484a2016-09-10 15:28:37 +0900100 auto rec = make_function_record();
Wenzel Jakob71867832015-07-29 17:43:52 +0200101
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100102 /* Store the capture object directly in the function record if there is enough space */
103 if (sizeof(capture) <= sizeof(rec->data)) {
Wenzel Jakob954b7932016-07-10 10:13:18 +0200104 /* Without these pragmas, GCC warns that there might not be
105 enough space to use the placement new operator. However, the
106 'if' statement above ensures that this is the case. */
Jason Rhinelander0b12f912016-07-07 16:26:04 -0400107#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -0400108# pragma GCC diagnostic push
109# pragma GCC diagnostic ignored "-Wplacement-new"
110#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100111 new ((capture *) &rec->data) capture { std::forward<Func>(f) };
Jason Rhinelander0b12f912016-07-07 16:26:04 -0400112#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -0400113# pragma GCC diagnostic pop
114#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100115 if (!std::is_trivially_destructible<Func>::value)
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400116 rec->free_data = [](function_record *r) { ((capture *) &r->data)->~capture(); };
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100117 } else {
118 rec->data[0] = new capture { std::forward<Func>(f) };
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400119 rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100120 }
Wenzel Jakob19208fe2015-10-13 17:37:25 +0200121
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100122 /* Type casters for the function arguments and return value */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400123 using cast_in = argument_loader<Args...>;
124 using cast_out = make_caster<
125 conditional_t<std::is_void<Return>::value, void_type, Return>
Dean Moldovan719c1732016-11-27 18:19:34 +0100126 >;
Wenzel Jakob71867832015-07-29 17:43:52 +0200127
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400128 static_assert(expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
Jason Rhinelander0f5ec0a2017-03-19 12:36:18 -0300129 "The number of argument annotations does not match the number of function arguments");
Jason Rhinelander2686da82017-01-21 23:42:14 -0500130
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100131 /* Dispatch code which converts function arguments and performs the actual function call */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400132 rec->impl = [](function_call &call) -> handle {
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100133 cast_in args_converter;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100134
135 /* Try to cast the function arguments into the C++ domain */
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500136 if (!args_converter.load_args(call))
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100137 return PYBIND11_TRY_NEXT_OVERLOAD;
138
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100139 /* Invoke call policy pre-call hook */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400140 process_attributes<Extra...>::precall(call);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100141
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100142 /* Get a pointer to the capture object */
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500143 auto data = (sizeof(capture) <= sizeof(call.func.data)
144 ? &call.func.data : call.func.data[0]);
145 capture *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100146
Jason Rhinelander546f6fc2017-01-20 00:59:26 -0500147 /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
Wenzel Jakobcbd16a82018-07-17 16:56:26 +0200148 return_value_policy policy = return_value_policy_override<Return>::policy(call.func.policy);
Dean Moldovand079f412016-11-20 05:31:02 +0100149
Dean Moldovan1ac19032017-03-16 11:22:26 +0100150 /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400151 using Guard = extract_guard_t<Extra...>;
Dean Moldovan1ac19032017-03-16 11:22:26 +0100152
Wenzel Jakob954b7932016-07-10 10:13:18 +0200153 /* Perform the function call */
Jason Rhinelander813d7e82017-05-14 15:57:26 -0400154 handle result = cast_out::cast(
155 std::move(args_converter).template call<Return, Guard>(cap->f), policy, call.parent);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100156
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100157 /* Invoke call policy post-call hook */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400158 process_attributes<Extra...>::postcall(call, result);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100159
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100160 return result;
Wenzel Jakob71867832015-07-29 17:43:52 +0200161 };
162
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100163 /* Process any user-provided function attributes */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400164 process_attributes<Extra...>::init(extra..., rec);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100165
166 /* Generate a readable signature describing the function's arguments and return value types */
Dean Moldovan56613942017-07-02 12:52:00 +0200167 static constexpr auto signature = _("(") + cast_in::arg_names + _(") -> ") + cast_out::name;
168 PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100169
170 /* Register the function with Python from generic (non-templated) code */
Dean Moldovan56613942017-07-02 12:52:00 +0200171 initialize_generic(rec, signature.text, types.data(), sizeof...(Args));
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100172
173 if (cast_in::has_args) rec->has_args = true;
174 if (cast_in::has_kwargs) rec->has_kwargs = true;
Wenzel Jakob954b7932016-07-10 10:13:18 +0200175
176 /* Stash some additional information used by an important optimization in 'functional.h' */
Jason Rhinelander1d7998e2017-02-17 06:56:41 -0500177 using FunctionType = Return (*)(Args...);
Wenzel Jakob954b7932016-07-10 10:13:18 +0200178 constexpr bool is_function_ptr =
179 std::is_convertible<Func, FunctionType>::value &&
180 sizeof(capture) == sizeof(void *);
181 if (is_function_ptr) {
182 rec->is_stateless = true;
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500183 rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
Wenzel Jakob954b7932016-07-10 10:13:18 +0200184 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200185 }
186
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100187 /// Register a function call with Python (generic non-templated code goes here)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100188 void initialize_generic(detail::function_record *rec, const char *text,
Dean Moldovanecced6c2016-07-31 20:03:18 +0200189 const std::type_info *const *types, size_t args) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100190
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100191 /* Create copies of all referenced C-style strings */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100192 rec->name = strdup(rec->name ? rec->name : "");
193 if (rec->doc) rec->doc = strdup(rec->doc);
194 for (auto &a: rec->args) {
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100195 if (a.name)
196 a.name = strdup(a.name);
197 if (a.descr)
198 a.descr = strdup(a.descr);
199 else if (a.value)
Dean Moldovan242b1462016-09-08 17:02:04 +0200200 a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100201 }
Wenzel Jakob954b7932016-07-10 10:13:18 +0200202
Jason Rhinelander464d9892017-06-12 21:52:48 -0400203 rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
204
Dean Moldovanb8c5dbd2017-08-24 02:46:07 +0200205#if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
206 if (rec->is_constructor && !rec->is_new_style_constructor) {
207 const auto class_name = std::string(((PyTypeObject *) rec->scope.ptr())->tp_name);
208 const auto func_name = std::string(rec->name);
209 PyErr_WarnEx(
210 PyExc_FutureWarning,
211 ("pybind11-bound class '" + class_name + "' is using an old-style "
212 "placement-new '" + func_name + "' which has been deprecated. See "
213 "the upgrade guide in pybind11's docs. This message is only visible "
214 "when compiled in debug mode.").c_str(), 0
215 );
216 }
217#endif
218
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100219 /* Generate a proper function signature */
220 std::string signature;
Dean Moldovan0aef6422017-08-31 14:38:23 +0200221 size_t type_index = 0, arg_index = 0;
222 for (auto *pc = text; *pc != '\0'; ++pc) {
223 const auto c = *pc;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100224
225 if (c == '{') {
Dean Moldovan0aef6422017-08-31 14:38:23 +0200226 // Write arg name for everything except *args and **kwargs.
227 if (*(pc + 1) == '*')
228 continue;
229
230 if (arg_index < rec->args.size() && rec->args[arg_index].name) {
231 signature += rec->args[arg_index].name;
232 } else if (arg_index == 0 && rec->is_method) {
233 signature += "self";
234 } else {
235 signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100236 }
Dean Moldovan0aef6422017-08-31 14:38:23 +0200237 signature += ": ";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100238 } else if (c == '}') {
Dean Moldovan0aef6422017-08-31 14:38:23 +0200239 // Write default value if available.
240 if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
Antony Lee0826b3c2017-11-26 20:00:35 -0800241 signature += " = ";
Dean Moldovan0aef6422017-08-31 14:38:23 +0200242 signature += rec->args[arg_index].descr;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100243 }
Dean Moldovan0aef6422017-08-31 14:38:23 +0200244 arg_index++;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100245 } else if (c == '%') {
246 const std::type_info *t = types[type_index++];
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100247 if (!t)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100248 pybind11_fail("Internal error while parsing type signature (1)");
Ivan Smirnov8f3e0452016-10-23 15:43:03 +0100249 if (auto tinfo = detail::get_type_info(*t)) {
Jason Rhinelander71178922017-11-07 12:33:05 -0400250 handle th((PyObject *) tinfo->type);
251 signature +=
252 th.attr("__module__").cast<std::string>() + "." +
253 th.attr("__qualname__").cast<std::string>(); // Python 3.3+, but we backport it to earlier versions
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200254 } else if (rec->is_new_style_constructor && arg_index == 0) {
255 // A new-style `__init__` takes `self` as `value_and_holder`.
256 // Rewrite it to the proper class type.
Jason Rhinelander71178922017-11-07 12:33:05 -0400257 signature +=
258 rec->scope.attr("__module__").cast<std::string>() + "." +
259 rec->scope.attr("__qualname__").cast<std::string>();
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100260 } else {
261 std::string tname(t->name());
262 detail::clean_type_id(tname);
263 signature += tname;
264 }
265 } else {
266 signature += c;
267 }
268 }
Dean Moldovan0aef6422017-08-31 14:38:23 +0200269 if (arg_index != args || types[type_index] != nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100270 pybind11_fail("Internal error while parsing type signature (2)");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100271
Wenzel Jakob57082212015-09-04 23:42:12 +0200272#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100273 if (strcmp(rec->name, "__next__") == 0) {
274 std::free(rec->name);
275 rec->name = strdup("next");
Wenzel Jakobd1bfc4e2016-05-16 18:52:46 +0200276 } else if (strcmp(rec->name, "__bool__") == 0) {
277 std::free(rec->name);
278 rec->name = strdup("__nonzero__");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100279 }
Wenzel Jakob57082212015-09-04 23:42:12 +0200280#endif
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100281 rec->signature = strdup(signature.c_str());
282 rec->args.shrink_to_fit();
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500283 rec->nargs = (std::uint16_t) args;
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200284
Jason Rhinelander0a90b2d2017-04-16 20:30:52 -0400285 if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr()))
286 rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
Wenzel Jakob57082212015-09-04 23:42:12 +0200287
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100288 detail::function_record *chain = nullptr, *chain_start = rec;
Jason Rhinelander6873c202016-10-24 21:58:22 -0400289 if (rec->sibling) {
290 if (PyCFunction_Check(rec->sibling.ptr())) {
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100291 auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
Jason Rhinelander6873c202016-10-24 21:58:22 -0400292 chain = (detail::function_record *) rec_capsule;
293 /* Never append a method to an overload chain of a parent class;
294 instead, hide the parent's overloads in this case */
Dean Moldovan36f0a152017-02-08 01:01:56 +0100295 if (!chain->scope.is(rec->scope))
Jason Rhinelander6873c202016-10-24 21:58:22 -0400296 chain = nullptr;
297 }
298 // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
299 else if (!rec->sibling.is_none() && rec->name[0] != '_')
300 pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
301 "\" with a function of the same name");
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200302 }
303
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100304 if (!chain) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100305 /* No existing overload was found, create a new function object */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100306 rec->def = new PyMethodDef();
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500307 std::memset(rec->def, 0, sizeof(PyMethodDef));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100308 rec->def->ml_name = rec->name;
Antony Leebaf6b992018-06-24 15:38:09 +0200309 rec->def->ml_meth = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(*dispatcher));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100310 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
Wenzel Jakoba6501792016-02-04 23:02:07 +0100311
Wenzel Jakobb16421e2017-03-22 22:04:00 +0100312 capsule rec_capsule(rec, [](void *ptr) {
313 destruct((detail::function_record *) ptr);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100314 });
Wenzel Jakoba6501792016-02-04 23:02:07 +0100315
316 object scope_module;
317 if (rec->scope) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200318 if (hasattr(rec->scope, "__module__")) {
319 scope_module = rec->scope.attr("__module__");
320 } else if (hasattr(rec->scope, "__name__")) {
321 scope_module = rec->scope.attr("__name__");
322 }
Wenzel Jakoba6501792016-02-04 23:02:07 +0100323 }
324
325 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200326 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100327 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200328 } else {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100329 /* Append at the end of the overload chain */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100330 m_ptr = rec->sibling.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200331 inc_ref();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100332 chain_start = chain;
Jason Rhinelanderd355f2f2017-04-16 22:31:13 -0400333 if (chain->is_method != rec->is_method)
334 pybind11_fail("overloading a method with both static and instance methods is not supported; "
335 #if defined(NDEBUG)
336 "compile in debug mode for more details"
337 #else
338 "error while attempting to bind " + std::string(rec->is_method ? "instance" : "static") + " method " +
339 std::string(pybind11::str(rec->scope.attr("__name__"))) + "." + std::string(rec->name) + signature
340 #endif
341 );
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100342 while (chain->next)
343 chain = chain->next;
344 chain->next = rec;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200345 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200346
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200347 std::string signatures;
Wenzel Jakob71867832015-07-29 17:43:52 +0200348 int index = 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100349 /* Create a nice pydoc rec including all signatures and
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100350 docstrings of the functions in the overload chain */
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100351 if (chain && options::show_function_signatures()) {
Sylvain Corlay0e04fdf2016-03-08 16:42:12 -0500352 // First a generic signature
353 signatures += rec->name;
354 signatures += "(*args, **kwargs)\n";
355 signatures += "Overloaded function.\n\n";
356 }
357 // Then specific overload signatures
Jason Rhinelander10d13042017-03-08 12:32:42 -0500358 bool first_user_def = true;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100359 for (auto it = chain_start; it != nullptr; it = it->next) {
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100360 if (options::show_function_signatures()) {
Jason Rhinelander10d13042017-03-08 12:32:42 -0500361 if (index > 0) signatures += "\n";
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100362 if (chain)
363 signatures += std::to_string(++index) + ". ";
364 signatures += rec->name;
365 signatures += it->signature;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100366 signatures += "\n";
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100367 }
368 if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
Jason Rhinelander10d13042017-03-08 12:32:42 -0500369 // If we're appending another docstring, and aren't printing function signatures, we
370 // need to append a newline first:
371 if (!options::show_function_signatures()) {
372 if (first_user_def) first_user_def = false;
373 else signatures += "\n";
374 }
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100375 if (options::show_function_signatures()) signatures += "\n";
Wenzel Jakob218b6ce2016-02-28 23:52:37 +0100376 signatures += it->doc;
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100377 if (options::show_function_signatures()) signatures += "\n";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100378 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200379 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100380
381 /* Install docstring */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200382 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
383 if (func->m_ml->ml_doc)
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500384 std::free(const_cast<char *>(func->m_ml->ml_doc));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200385 func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100386
Wenzel Jakob31fbf182016-11-20 05:27:05 +0100387 if (rec->is_method) {
388 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200389 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100390 pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200391 Py_DECREF(func);
392 }
393 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100394
395 /// When a cpp_function is GCed, release any memory allocated by pybind11
396 static void destruct(detail::function_record *rec) {
397 while (rec) {
398 detail::function_record *next = rec->next;
399 if (rec->free_data)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100400 rec->free_data(rec);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100401 std::free((char *) rec->name);
402 std::free((char *) rec->doc);
403 std::free((char *) rec->signature);
404 for (auto &arg: rec->args) {
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500405 std::free(const_cast<char *>(arg.name));
406 std::free(const_cast<char *>(arg.descr));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100407 arg.value.dec_ref();
408 }
409 if (rec->def) {
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500410 std::free(const_cast<char *>(rec->def->ml_doc));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100411 delete rec->def;
412 }
413 delete rec;
414 rec = next;
415 }
416 }
417
418 /// Main dispatch logic for calls to functions bound using pybind11
Jason Rhinelander2686da82017-01-21 23:42:14 -0500419 static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500420 using namespace detail;
421
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100422 /* Iterator over the list of potentially admissible overloads */
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500423 function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
424 *it = overloads;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100425
426 /* Need to know how many arguments + keyword arguments there are to pick the right overload */
Jason Rhinelander2686da82017-01-21 23:42:14 -0500427 const size_t n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100428
Jason Rhinelander2686da82017-01-21 23:42:14 -0500429 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100430 result = PYBIND11_TRY_NEXT_OVERLOAD;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500431
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200432 auto self_value_and_holder = value_and_holder();
433 if (overloads->is_constructor) {
434 const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
435 const auto pi = reinterpret_cast<instance *>(parent.ptr());
436 self_value_and_holder = pi->get_value_and_holder(tinfo, false);
437
438 if (!self_value_and_holder.type || !self_value_and_holder.inst) {
439 PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid `self` argument");
440 return nullptr;
441 }
442
443 // If this value is already registered it must mean __init__ is invoked multiple times;
444 // we really can't support that in C++, so just ignore the second __init__.
445 if (self_value_and_holder.instance_registered())
446 return none().release().ptr();
447 }
448
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100449 try {
Jason Rhinelandere5505892017-02-03 18:25:34 -0500450 // We do this in two passes: in the first pass, we load arguments with `convert=false`;
451 // in the second, we allow conversion (except for arguments with an explicit
452 // py::arg().noconvert()). This lets us prefer calls without conversion, with
453 // conversion as a fallback.
454 std::vector<function_call> second_pass;
455
456 // However, if there are no overloads, we can just skip the no-convert pass entirely
457 const bool overloaded = it != nullptr && it->next != nullptr;
458
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100459 for (; it != nullptr; it = it->next) {
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500460
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100461 /* For each overload:
Jason Rhinelander2686da82017-01-21 23:42:14 -0500462 1. Copy all positional arguments we were given, also checking to make sure that
463 named positional arguments weren't *also* specified via kwarg.
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100464 2. If we weren't given enough, try to make up the omitted ones by checking
Jason Rhinelander2686da82017-01-21 23:42:14 -0500465 whether they were provided by a kwarg matching the `py::arg("name")` name. If
466 so, use it (and remove it from kwargs; if not, see if the function binding
467 provided a default that we can use.
468 3. Ensure that either all keyword arguments were "consumed", or that the function
469 takes a kwargs argument to accept unconsumed kwargs.
470 4. Any positional arguments still left get put into a tuple (for args), and any
471 leftover kwargs get put into a dict.
472 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
473 extra tuple or dict at the end of the positional arguments.
474 6. Call the function call dispatcher (function_record::impl)
475
476 If one of these fail, move on to the next overload and keep trying until we get a
477 result other than PYBIND11_TRY_NEXT_OVERLOAD.
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100478 */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100479
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500480 function_record &func = *it;
481 size_t pos_args = func.nargs; // Number of positional arguments that we need
482 if (func.has_args) --pos_args; // (but don't count py::args
483 if (func.has_kwargs) --pos_args; // or py::kwargs)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100484
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500485 if (!func.has_args && n_args_in > pos_args)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500486 continue; // Too many arguments for this overload
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100487
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500488 if (n_args_in < pos_args && func.args.size() < pos_args)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500489 continue; // Not enough arguments given, and not enough defaults to fill in the blanks
490
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500491 function_call call(func, parent);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500492
493 size_t args_to_copy = std::min(pos_args, n_args_in);
494 size_t args_copied = 0;
495
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200496 // 0. Inject new-style `self` argument
497 if (func.is_new_style_constructor) {
498 // The `value` may have been preallocated by an old-style `__init__`
499 // if it was a preceding candidate for overload resolution.
500 if (self_value_and_holder)
501 self_value_and_holder.type->dealloc(self_value_and_holder);
502
Dean Moldovan7939f4b2017-09-04 13:49:19 +0200503 call.init_self = PyTuple_GET_ITEM(args_in, 0);
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200504 call.args.push_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
505 call.args_convert.push_back(false);
506 ++args_copied;
507 }
508
Jason Rhinelander2686da82017-01-21 23:42:14 -0500509 // 1. Copy any position arguments given.
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400510 bool bad_arg = false;
Jason Rhinelander2686da82017-01-21 23:42:14 -0500511 for (; args_copied < args_to_copy; ++args_copied) {
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400512 argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
513 if (kwargs_in && arg_rec && arg_rec->name && PyDict_GetItemString(kwargs_in, arg_rec->name)) {
514 bad_arg = true;
Jason Rhinelandercaa13792017-02-23 19:54:53 -0500515 break;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100516 }
Jason Rhinelander2686da82017-01-21 23:42:14 -0500517
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400518 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
519 if (arg_rec && !arg_rec->none && arg.is_none()) {
520 bad_arg = true;
521 break;
522 }
523 call.args.push_back(arg);
524 call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100525 }
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400526 if (bad_arg)
Jason Rhinelandercaa13792017-02-23 19:54:53 -0500527 continue; // Maybe it was meant for another overload (issue #688)
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200528
Jason Rhinelander2686da82017-01-21 23:42:14 -0500529 // We'll need to copy this if we steal some kwargs for defaults
530 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
531
532 // 2. Check kwargs and, failing that, defaults that may help complete the list
533 if (args_copied < pos_args) {
534 bool copied_kwargs = false;
535
536 for (; args_copied < pos_args; ++args_copied) {
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500537 const auto &arg = func.args[args_copied];
Jason Rhinelander2686da82017-01-21 23:42:14 -0500538
539 handle value;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500540 if (kwargs_in && arg.name)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500541 value = PyDict_GetItemString(kwargs.ptr(), arg.name);
542
543 if (value) {
544 // Consume a kwargs value
545 if (!copied_kwargs) {
546 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
547 copied_kwargs = true;
548 }
549 PyDict_DelItemString(kwargs.ptr(), arg.name);
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100550 } else if (arg.value) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500551 value = arg.value;
552 }
553
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500554 if (value) {
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500555 call.args.push_back(value);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500556 call.args_convert.push_back(arg.convert);
557 }
Jason Rhinelander2686da82017-01-21 23:42:14 -0500558 else
559 break;
560 }
561
562 if (args_copied < pos_args)
563 continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments
564 }
565
566 // 3. Check everything was consumed (unless we have a kwargs arg)
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500567 if (kwargs && kwargs.size() > 0 && !func.has_kwargs)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500568 continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
569
570 // 4a. If we have a py::args argument, create a new tuple with leftovers
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500571 if (func.has_args) {
Jason Rhinelander48e1f9a2017-12-23 09:42:32 -0400572 tuple extra_args;
Jason Rhinelander2686da82017-01-21 23:42:14 -0500573 if (args_to_copy == 0) {
574 // We didn't copy out any position arguments from the args_in tuple, so we
575 // can reuse it directly without copying:
576 extra_args = reinterpret_borrow<tuple>(args_in);
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100577 } else if (args_copied >= n_args_in) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500578 extra_args = tuple(0);
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100579 } else {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500580 size_t args_size = n_args_in - args_copied;
581 extra_args = tuple(args_size);
582 for (size_t i = 0; i < args_size; ++i) {
Jason Rhinelander367d7232017-12-15 13:21:52 -0400583 extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500584 }
585 }
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500586 call.args.push_back(extra_args);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500587 call.args_convert.push_back(false);
Jason Rhinelander48e1f9a2017-12-23 09:42:32 -0400588 call.args_ref = std::move(extra_args);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500589 }
590
591 // 4b. If we have a py::kwargs, pass on any remaining kwargs
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500592 if (func.has_kwargs) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500593 if (!kwargs.ptr())
594 kwargs = dict(); // If we didn't get one, send an empty one
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500595 call.args.push_back(kwargs);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500596 call.args_convert.push_back(false);
Jason Rhinelander48e1f9a2017-12-23 09:42:32 -0400597 call.kwargs_ref = std::move(kwargs);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500598 }
599
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500600 // 5. Put everything in a vector. Not technically step 5, we've been building it
601 // in `call.args` all along.
602 #if !defined(NDEBUG)
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500603 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500604 pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
605 #endif
Jason Rhinelander2686da82017-01-21 23:42:14 -0500606
Jason Rhinelandere5505892017-02-03 18:25:34 -0500607 std::vector<bool> second_pass_convert;
608 if (overloaded) {
609 // We're in the first no-convert pass, so swap out the conversion flags for a
610 // set of all-false flags. If the call fails, we'll swap the flags back in for
611 // the conversion-allowed call below.
612 second_pass_convert.resize(func.nargs, false);
613 call.args_convert.swap(second_pass_convert);
614 }
615
Jason Rhinelander2686da82017-01-21 23:42:14 -0500616 // 6. Call the function.
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200617 try {
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200618 loader_life_support guard{};
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500619 result = func.impl(call);
Wenzel Jakob00062592016-07-01 16:07:35 +0200620 } catch (reference_cast_error &) {
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200621 result = PYBIND11_TRY_NEXT_OVERLOAD;
622 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100623
624 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
625 break;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500626
Jason Rhinelandere5505892017-02-03 18:25:34 -0500627 if (overloaded) {
628 // The (overloaded) call failed; if the call has at least one argument that
629 // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
630 // then add this call to the list of second pass overloads to try.
631 for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
632 if (second_pass_convert[i]) {
633 // Found one: swap the converting flags back in and store the call for
634 // the second pass.
635 call.args_convert.swap(second_pass_convert);
636 second_pass.push_back(std::move(call));
637 break;
638 }
639 }
640 }
641 }
642
643 if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
644 // The no-conversion pass finished without success, try again with conversion allowed
645 for (auto &call : second_pass) {
646 try {
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200647 loader_life_support guard{};
Jason Rhinelandere5505892017-02-03 18:25:34 -0500648 result = call.func.impl(call);
649 } catch (reference_cast_error &) {
650 result = PYBIND11_TRY_NEXT_OVERLOAD;
651 }
652
653 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
654 break;
655 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100656 }
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200657 } catch (error_already_set &e) {
658 e.restore();
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400659 return nullptr;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100660 } catch (...) {
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400661 /* When an exception is caught, give each registered exception
662 translator a chance to translate it to a Python exception
663 in reverse order of registration.
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200664
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400665 A translator may choose to do one of the following:
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200666
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400667 - catch the exception and call PyErr_SetString or PyErr_SetObject
668 to set a standard (or custom) Python exception, or
669 - do nothing and let the exception fall through to the next translator, or
670 - delegate translation to the next translator by throwing a new type of exception. */
671
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200672 auto last_exception = std::current_exception();
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500673 auto &registered_exception_translators = get_internals().registered_exception_translators;
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400674 for (auto& translator : registered_exception_translators) {
675 try {
676 translator(last_exception);
677 } catch (...) {
678 last_exception = std::current_exception();
679 continue;
680 }
681 return nullptr;
682 }
683 PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100684 return nullptr;
685 }
686
Dean Moldovan2b4477e2017-09-09 20:21:34 +0200687 auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
688 if (msg.find("std::") != std::string::npos) {
689 msg += "\n\n"
690 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
691 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
692 "conversions are optional and require extra headers to be included\n"
693 "when compiling your pybind11 module.";
694 }
695 };
696
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100697 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
Wenzel Jakob382484a2016-09-10 15:28:37 +0900698 if (overloads->is_operator)
699 return handle(Py_NotImplemented).inc_ref().ptr();
700
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900701 std::string msg = std::string(overloads->name) + "(): incompatible " +
702 std::string(overloads->is_constructor ? "constructor" : "function") +
703 " arguments. The following argument types are supported:\n";
704
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100705 int ctr = 0;
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500706 for (function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100707 msg += " "+ std::to_string(++ctr) + ". ";
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400708
709 bool wrote_sig = false;
710 if (overloads->is_constructor) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200711 // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400712 std::string sig = it2->signature;
Dean Moldovanecced6c2016-07-31 20:03:18 +0200713 size_t start = sig.find('(') + 7; // skip "(self: "
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400714 if (start < sig.size()) {
715 // End at the , for the next argument
716 size_t end = sig.find(", "), next = end + 2;
717 size_t ret = sig.rfind(" -> ");
718 // Or the ), if there is no comma:
719 if (end >= sig.size()) next = end = sig.find(')');
720 if (start < end && next < sig.size()) {
721 msg.append(sig, start, end - start);
722 msg += '(';
723 msg.append(sig, next, ret - next);
724 wrote_sig = true;
725 }
726 }
727 }
728 if (!wrote_sig) msg += it2->signature;
729
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100730 msg += "\n";
731 }
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900732 msg += "\nInvoked with: ";
Jason Rhinelander2686da82017-01-21 23:42:14 -0500733 auto args_ = reinterpret_borrow<tuple>(args_in);
Jason Rhinelander231e1672017-02-23 21:04:46 -0500734 bool some_args = false;
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200735 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
Jason Rhinelander231e1672017-02-23 21:04:46 -0500736 if (!some_args) some_args = true;
737 else msg += ", ";
Jason Rhinelander7146d622016-11-22 05:28:40 -0500738 msg += pybind11::repr(args_[ti]);
Andreas Bergmeier16d43942016-05-24 09:19:35 +0200739 }
Jason Rhinelander231e1672017-02-23 21:04:46 -0500740 if (kwargs_in) {
741 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
742 if (kwargs.size() > 0) {
743 if (some_args) msg += "; ";
744 msg += "kwargs: ";
745 bool first = true;
746 for (auto kwarg : kwargs) {
747 if (first) first = false;
748 else msg += ", ";
749 msg += pybind11::str("{}={!r}").format(kwarg.first, kwarg.second);
750 }
751 }
752 }
753
Dean Moldovan2b4477e2017-09-09 20:21:34 +0200754 append_note_if_missing_header_is_suspected(msg);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100755 PyErr_SetString(PyExc_TypeError, msg.c_str());
756 return nullptr;
757 } else if (!result) {
758 std::string msg = "Unable to convert function return value to a "
759 "Python type! The signature was\n\t";
760 msg += it->signature;
Dean Moldovan2b4477e2017-09-09 20:21:34 +0200761 append_note_if_missing_header_is_suspected(msg);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100762 PyErr_SetString(PyExc_TypeError, msg.c_str());
763 return nullptr;
764 } else {
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200765 if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
Jason Rhinelander464d9892017-06-12 21:52:48 -0400766 auto *pi = reinterpret_cast<instance *>(parent.ptr());
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200767 self_value_and_holder.type->init_instance(pi, nullptr);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100768 }
769 return result.ptr();
770 }
771 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200772};
773
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100774/// Wrapper for Python extension modules
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200775class module : public object {
776public:
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200777 PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200778
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100779 /// Create a new top-level Python module with the given name and docstring
Jason Rhinelander12d76602016-10-16 16:27:42 -0400780 explicit module(const char *name, const char *doc = nullptr) {
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100781 if (!options::show_user_defined_docstrings()) doc = nullptr;
Wenzel Jakob57082212015-09-04 23:42:12 +0200782#if PY_MAJOR_VERSION >= 3
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200783 PyModuleDef *def = new PyModuleDef();
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500784 std::memset(def, 0, sizeof(PyModuleDef));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200785 def->m_name = name;
786 def->m_doc = doc;
787 def->m_size = -1;
788 Py_INCREF(def);
789 m_ptr = PyModule_Create(def);
Wenzel Jakob57082212015-09-04 23:42:12 +0200790#else
791 m_ptr = Py_InitModule3(name, nullptr, doc);
792#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200793 if (m_ptr == nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100794 pybind11_fail("Internal error in module::module()");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200795 inc_ref();
796 }
797
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100798 /** \rst
799 Create Python binding for a new function within the module scope. ``Func``
800 can be a plain C++ function, a function pointer, or a lambda function. For
801 details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
802 \endrst */
Wenzel Jakob71867832015-07-29 17:43:52 +0200803 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100804 module &def(const char *name_, Func &&f, const Extra& ... extra) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200805 cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
806 sibling(getattr(*this, name_, none())), extra...);
Jason Rhinelander6873c202016-10-24 21:58:22 -0400807 // NB: allow overwriting here because cpp_function sets up a chain with the intention of
808 // overwriting (and has already checked internally that it isn't overwriting non-functions).
809 add_object(name_, func, true /* overwrite */);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200810 return *this;
811 }
812
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100813 /** \rst
814 Create and return a new Python submodule with the given name and docstring.
815 This also works recursively, i.e.
816
817 .. code-block:: cpp
818
819 py::module m("example", "pybind11 example plugin");
820 py::module m2 = m.def_submodule("sub", "A submodule of 'example'");
821 py::module m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
822 \endrst */
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200823 module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200824 std::string full_name = std::string(PyModule_GetName(m_ptr))
825 + std::string(".") + std::string(name);
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200826 auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100827 if (doc && options::show_user_defined_docstrings())
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200828 result.attr("__doc__") = pybind11::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200829 attr(name) = result;
830 return result;
831 }
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200832
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100833 /// Import and return a module or throws `error_already_set`.
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200834 static module import(const char *name) {
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100835 PyObject *obj = PyImport_ImportModule(name);
836 if (!obj)
esquires67a68f12016-12-01 05:35:34 -0500837 throw error_already_set();
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200838 return reinterpret_steal<module>(obj);
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200839 }
Jason Rhinelander6873c202016-10-24 21:58:22 -0400840
Gunnar Läthénc64e6b12017-09-12 08:05:05 +0200841 /// Reload the module or throws `error_already_set`.
842 void reload() {
843 PyObject *obj = PyImport_ReloadModule(ptr());
844 if (!obj)
845 throw error_already_set();
846 *this = reinterpret_steal<module>(obj);
847 }
848
Jason Rhinelander6873c202016-10-24 21:58:22 -0400849 // Adds an object to the module using the given name. Throws if an object with the given name
850 // already exists.
851 //
852 // overwrite should almost always be false: attempting to overwrite objects that pybind11 has
853 // established will, in most cases, break things.
Wenzel Jakobaa1b3162017-03-30 11:59:32 +0200854 PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
Jason Rhinelander6873c202016-10-24 21:58:22 -0400855 if (!overwrite && hasattr(*this, name))
856 pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
857 std::string(name) + "\"");
858
Wenzel Jakobaa1b3162017-03-30 11:59:32 +0200859 PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
Jason Rhinelander6873c202016-10-24 21:58:22 -0400860 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200861};
862
Dean Moldovan22c413b2017-03-30 00:20:42 +0200863/// \ingroup python_builtins
Dean Moldovan1d3c4bc2017-06-06 17:05:19 +0200864/// Return a dictionary representing the global variables in the current execution frame,
865/// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
866inline dict globals() {
867 PyObject *p = PyEval_GetGlobals();
868 return reinterpret_borrow<dict>(p ? p : module::import("__main__").attr("__dict__").ptr());
869}
Dean Moldovan22c413b2017-03-30 00:20:42 +0200870
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200871NAMESPACE_BEGIN(detail)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100872/// Generic support for creating new Python heap types
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100873class generic_type : public object {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400874 template <typename...> friend class class_;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200875public:
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100876 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100877protected:
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100878 void initialize(const type_record &rec) {
879 if (rec.scope && hasattr(rec.scope, rec.name))
880 pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
881 "\": an object with that name is already defined");
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200882
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400883 if (rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100884 pybind11_fail("generic_type: type \"" + std::string(rec.name) +
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200885 "\" is already registered!");
886
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100887 m_ptr = make_new_python_type(rec);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200888
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100889 /* Register supplemental type information in C++ dict */
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100890 auto *tinfo = new detail::type_info();
891 tinfo->type = (PyTypeObject *) m_ptr;
Jason Rhinelander1f8a1002017-04-21 19:01:30 -0400892 tinfo->cpptype = rec.type;
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100893 tinfo->type_size = rec.type_size;
Dean Moldovan0d765f42017-03-21 01:15:20 +0100894 tinfo->operator_new = rec.operator_new;
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500895 tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
Jason Rhinelander353615f2017-07-25 00:53:23 -0400896 tinfo->init_instance = rec.init_instance;
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100897 tinfo->dealloc = rec.dealloc;
Jason Rhinelander1f8a1002017-04-21 19:01:30 -0400898 tinfo->simple_type = true;
899 tinfo->simple_ancestors = true;
Jason Rhinelander7437c692017-07-28 22:03:44 -0400900 tinfo->default_holder = rec.default_holder;
901 tinfo->module_local = rec.module_local;
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100902
903 auto &internals = get_internals();
904 auto tindex = std::type_index(*rec.type);
Ivan Smirnova6e6a8b2016-10-23 15:27:13 +0100905 tinfo->direct_conversions = &internals.direct_conversions[tindex];
Jason Rhinelander7437c692017-07-28 22:03:44 -0400906 if (rec.module_local)
907 registered_local_types_cpp()[tindex] = tinfo;
908 else
909 internals.registered_types_cpp[tindex] = tinfo;
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500910 internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo };
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100911
Jason Rhinelander1f8a1002017-04-21 19:01:30 -0400912 if (rec.bases.size() > 1 || rec.multiple_inheritance) {
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100913 mark_parents_nonsimple(tinfo->type);
Jason Rhinelander1f8a1002017-04-21 19:01:30 -0400914 tinfo->simple_ancestors = false;
915 }
916 else if (rec.bases.size() == 1) {
917 auto parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
918 tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
919 }
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400920
921 if (rec.module_local) {
922 // Stash the local typeinfo and loader so that external modules can access it.
923 tinfo->module_local_load = &type_caster_generic::local_load;
Dean Moldovan96997a42017-08-20 17:14:09 +0200924 setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400925 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200926 }
927
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900928 /// Helper function which tags all parents of a type using mult. inheritance
929 void mark_parents_nonsimple(PyTypeObject *value) {
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200930 auto t = reinterpret_borrow<tuple>(value->tp_bases);
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900931 for (handle h : t) {
932 auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
933 if (tinfo2)
934 tinfo2->simple_type = false;
935 mark_parents_nonsimple((PyTypeObject *) h.ptr());
936 }
937 }
938
Wenzel Jakob43398a82015-07-28 16:12:20 +0200939 void install_buffer_funcs(
940 buffer_info *(*get_buffer)(PyObject *, void *),
941 void *get_buffer_data) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200942 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100943 auto tinfo = detail::get_type_info(&type->ht_type);
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100944
945 if (!type->ht_type.tp_as_buffer)
946 pybind11_fail(
947 "To be able to register buffer protocol support for the type '" +
948 std::string(tinfo->type->tp_name) +
949 "' the associated class<>(..) invocation must "
950 "include the pybind11::buffer_protocol() annotation!");
951
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100952 tinfo->get_buffer = get_buffer;
953 tinfo->get_buffer_data = get_buffer_data;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200954 }
955
Ted Drain0a0758c2017-11-07 08:35:27 -0800956 // rec_func must be set for either fget or fset.
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100957 void def_property_static_impl(const char *name,
958 handle fget, handle fset,
Ted Drain0a0758c2017-11-07 08:35:27 -0800959 detail::function_record *rec_func) {
960 const auto is_static = rec_func && !(rec_func->is_method && rec_func->scope);
961 const auto has_doc = rec_func && rec_func->doc && pybind11::options::show_user_defined_docstrings();
Dean Moldovanc91f8bd2017-02-13 18:11:24 +0100962 auto property = handle((PyObject *) (is_static ? get_internals().static_property_type
963 : &PyProperty_Type));
964 attr(name) = property(fget.ptr() ? fget : none(),
965 fset.ptr() ? fset : none(),
966 /*deleter*/none(),
Ted Drain0a0758c2017-11-07 08:35:27 -0800967 pybind11::str(has_doc ? rec_func->doc : ""));
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100968 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200969};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400970
Dean Moldovan0d765f42017-03-21 01:15:20 +0100971/// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
972template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator new))>>
973void set_operator_new(type_record *r) { r->operator_new = &T::operator new; }
974
975template <typename> void set_operator_new(...) { }
976
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400977template <typename T, typename SFINAE = void> struct has_operator_delete : std::false_type { };
978template <typename T> struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
979 : std::true_type { };
980template <typename T, typename SFINAE = void> struct has_operator_delete_size : std::false_type { };
981template <typename T> struct has_operator_delete_size<T, void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>>
982 : std::true_type { };
Dean Moldovan0d765f42017-03-21 01:15:20 +0100983/// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400984template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
985void call_operator_delete(T *p, size_t) { T::operator delete(p); }
986template <typename T, enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> = 0>
987void call_operator_delete(T *p, size_t s) { T::operator delete(p, s); }
Dean Moldovan0d765f42017-03-21 01:15:20 +0100988
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400989inline void call_operator_delete(void *p, size_t) { ::operator delete(p); }
Dean Moldovan0d765f42017-03-21 01:15:20 +0100990
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200991NAMESPACE_END(detail)
992
Jason Rhinelander23bf8942017-05-16 11:07:28 -0400993/// Given a pointer to a member function, cast it to its `Derived` version.
994/// Forward everything else unchanged.
995template <typename /*Derived*/, typename F>
996auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) { return std::forward<F>(f); }
997
998template <typename Derived, typename Return, typename Class, typename... Args>
Jason Rhinelander76722922017-10-03 10:09:49 -0300999auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
1000 static_assert(detail::is_accessible_base_of<Class, Derived>::value,
1001 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1002 return pmf;
1003}
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001004
1005template <typename Derived, typename Return, typename Class, typename... Args>
Jason Rhinelander76722922017-10-03 10:09:49 -03001006auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
1007 static_assert(detail::is_accessible_base_of<Class, Derived>::value,
1008 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1009 return pmf;
1010}
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001011
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001012template <typename type_, typename... options>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001013class class_ : public detail::generic_type {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001014 template <typename T> using is_holder = detail::is_holder_type<type_, T>;
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001015 template <typename T> using is_subtype = detail::is_strict_base_of<type_, T>;
1016 template <typename T> using is_base = detail::is_strict_base_of<T, type_>;
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -05001017 // struct instead of using here to help MSVC:
1018 template <typename T> struct is_valid_class_option :
1019 detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001020
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001021public:
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001022 using type = type_;
Dean Moldovan82ece942017-03-29 11:55:18 +02001023 using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001024 constexpr static bool has_alias = !std::is_void<type_alias>::value;
Dean Moldovan82ece942017-03-29 11:55:18 +02001025 using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001026
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -05001027 static_assert(detail::all_of<is_valid_class_option<options>...>::value,
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001028 "Unknown/invalid class_ template parameters provided");
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001029
Jason Rhinelander42e5ddc2017-06-12 21:48:36 -04001030 static_assert(!has_alias || std::is_polymorphic<type>::value,
1031 "Cannot use an alias class with a non-polymorphic type");
1032
Dean Moldovanc7ac16b2016-10-28 03:08:15 +02001033 PYBIND11_OBJECT(class_, generic_type, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001034
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001035 template <typename... Extra>
1036 class_(handle scope, const char *name, const Extra &... extra) {
Jason Rhinelanderb9616262017-03-16 20:10:48 -03001037 using namespace detail;
1038
1039 // MI can only be specified via class_ template options, not constructor parameters
1040 static_assert(
1041 none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
1042 ( constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
1043 constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
1044 none_of<std::is_same<multiple_inheritance, Extra>...>::value), // no multiple_inheritance attr
1045 "Error: multiple inheritance bases must be specified via class_ template options");
1046
1047 type_record record;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001048 record.scope = scope;
1049 record.name = name;
1050 record.type = &typeid(type);
Jason Rhinelanderb9616262017-03-16 20:10:48 -03001051 record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001052 record.holder_size = sizeof(holder_type);
Jason Rhinelander353615f2017-07-25 00:53:23 -04001053 record.init_instance = init_instance;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001054 record.dealloc = dealloc;
Pim Schellartcc88aae2017-01-31 10:52:11 -05001055 record.default_holder = std::is_same<holder_type, std::unique_ptr<type>>::value;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001056
Dean Moldovan0d765f42017-03-21 01:15:20 +01001057 set_operator_new<type>(&record);
1058
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001059 /* Register base classes specified via template arguments to class_, if any */
Jason Rhinelander926e2cf2017-03-25 22:41:06 -03001060 PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
Jason Rhinelander6b52c832016-09-06 12:27:00 -04001061
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001062 /* Process optional arguments, if any */
Jason Rhinelanderb9616262017-03-16 20:10:48 -03001063 process_attributes<Extra...>::init(extra..., &record);
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001064
Jason Rhinelanderb9616262017-03-16 20:10:48 -03001065 generic_type::initialize(record);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001066
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001067 if (has_alias) {
Jason Rhinelander7437c692017-07-28 22:03:44 -04001068 auto &instances = record.module_local ? registered_local_types_cpp() : get_internals().registered_types_cpp;
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001069 instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
1070 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001071 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001072
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +09001073 template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001074 static void add_base(detail::type_record &rec) {
Jason Rhinelander21966962017-06-21 13:38:10 -04001075 rec.add_base(typeid(Base), [](void *src) -> void * {
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001076 return static_cast<Base *>(reinterpret_cast<type *>(src));
1077 });
1078 }
1079
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +09001080 template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001081 static void add_base(detail::type_record &) { }
1082
Wenzel Jakob71867832015-07-29 17:43:52 +02001083 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001084 class_ &def(const char *name_, Func&& f, const Extra&... extra) {
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001085 cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), name(name_), is_method(*this),
Dean Moldovan865e4302016-09-21 01:06:32 +02001086 sibling(getattr(*this, name_, none())), extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +02001087 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001088 return *this;
1089 }
1090
Wenzel Jakob71867832015-07-29 17:43:52 +02001091 template <typename Func, typename... Extra> class_ &
Jason Rhinelander139a0822017-03-12 17:59:07 -03001092 def_static(const char *name_, Func &&f, const Extra&... extra) {
1093 static_assert(!std::is_member_function_pointer<Func>::value,
1094 "def_static(...) called with a non-static member function pointer");
Dean Moldovan865e4302016-09-21 01:06:32 +02001095 cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
1096 sibling(getattr(*this, name_, none())), extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +02001097 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001098 return *this;
1099 }
1100
Wenzel Jakob71867832015-07-29 17:43:52 +02001101 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001102 class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001103 op.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001104 return *this;
1105 }
1106
Wenzel Jakob71867832015-07-29 17:43:52 +02001107 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001108 class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001109 op.execute_cast(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001110 return *this;
1111 }
1112
Wenzel Jakob71867832015-07-29 17:43:52 +02001113 template <typename... Args, typename... Extra>
Jason Rhinelanderc4e18002017-08-17 00:01:42 -04001114 class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001115 init.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001116 return *this;
1117 }
1118
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001119 template <typename... Args, typename... Extra>
Jason Rhinelanderc4e18002017-08-17 00:01:42 -04001120 class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001121 init.execute(*this, extra...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001122 return *this;
1123 }
1124
Jason Rhinelander464d9892017-06-12 21:52:48 -04001125 template <typename... Args, typename... Extra>
1126 class_ &def(detail::initimpl::factory<Args...> &&init, const Extra&... extra) {
1127 std::move(init).execute(*this, extra...);
1128 return *this;
1129 }
1130
Dean Moldovan1e5a7da2017-08-24 01:53:15 +02001131 template <typename... Args, typename... Extra>
1132 class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
1133 std::move(pf).execute(*this, extra...);
1134 return *this;
1135 }
1136
Wenzel Jakob71867832015-07-29 17:43:52 +02001137 template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob43398a82015-07-28 16:12:20 +02001138 struct capture { Func func; };
1139 capture *ptr = new capture { std::forward<Func>(func) };
1140 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Dean Moldovan5f07fac2017-01-03 11:52:05 +01001141 detail::make_caster<type> caster;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001142 if (!caster.load(obj, false))
1143 return nullptr;
Wenzel Jakob43398a82015-07-28 16:12:20 +02001144 return new buffer_info(((capture *) ptr)->func(caster));
1145 }, ptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001146 return *this;
1147 }
1148
Bruce Merryfe0cf8b2017-05-17 10:52:33 +02001149 template <typename Return, typename Class, typename... Args>
1150 class_ &def_buffer(Return (Class::*func)(Args...)) {
1151 return def_buffer([func] (type &obj) { return (obj.*func)(); });
1152 }
1153
1154 template <typename Return, typename Class, typename... Args>
1155 class_ &def_buffer(Return (Class::*func)(Args...) const) {
1156 return def_buffer([func] (const type &obj) { return (obj.*func)(); });
1157 }
1158
Wenzel Jakob71867832015-07-29 17:43:52 +02001159 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001160 class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001161 static_assert(std::is_base_of<C, type>::value, "def_readwrite() requires a class member (or base class member)");
1162 cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this)),
1163 fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
Wenzel Jakob0b489582016-03-25 16:13:10 +01001164 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001165 return *this;
1166 }
1167
Wenzel Jakob71867832015-07-29 17:43:52 +02001168 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001169 class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001170 static_assert(std::is_base_of<C, type>::value, "def_readonly() requires a class member (or base class member)");
1171 cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this));
Wenzel Jakob0b489582016-03-25 16:13:10 +01001172 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001173 return *this;
1174 }
1175
Wenzel Jakob71867832015-07-29 17:43:52 +02001176 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001177 class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001178 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
1179 fset([pm](object, const D &value) { *pm = value; }, scope(*this));
1180 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001181 return *this;
1182 }
1183
Wenzel Jakob71867832015-07-29 17:43:52 +02001184 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001185 class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001186 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
1187 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001188 return *this;
1189 }
1190
Dean Moldovan03f627e2016-11-01 11:44:57 +01001191 /// Uses return_value_policy::reference_internal by default
1192 template <typename Getter, typename... Extra>
1193 class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001194 return def_property_readonly(name, cpp_function(method_adaptor<type>(fget)),
1195 return_value_policy::reference_internal, extra...);
Dean Moldovan03f627e2016-11-01 11:44:57 +01001196 }
1197
1198 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001199 template <typename... Extra>
1200 class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
Ted Drain0a0758c2017-11-07 08:35:27 -08001201 return def_property(name, fget, nullptr, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001202 }
1203
Dean Moldovan03f627e2016-11-01 11:44:57 +01001204 /// Uses return_value_policy::reference by default
1205 template <typename Getter, typename... Extra>
1206 class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
1207 return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...);
1208 }
1209
1210 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001211 template <typename... Extra>
1212 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
Ted Drain0a0758c2017-11-07 08:35:27 -08001213 return def_property_static(name, fget, nullptr, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001214 }
1215
Dean Moldovan03f627e2016-11-01 11:44:57 +01001216 /// Uses return_value_policy::reference_internal by default
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001217 template <typename Getter, typename Setter, typename... Extra>
1218 class_ &def_property(const char *name, const Getter &fget, const Setter &fset, const Extra& ...extra) {
1219 return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
1220 }
Dean Moldovan03f627e2016-11-01 11:44:57 +01001221 template <typename Getter, typename... Extra>
1222 class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001223 return def_property(name, cpp_function(method_adaptor<type>(fget)), fset,
1224 return_value_policy::reference_internal, extra...);
Dean Moldovan03f627e2016-11-01 11:44:57 +01001225 }
1226
1227 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001228 template <typename... Extra>
1229 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001230 return def_property_static(name, fget, fset, is_method(*this), extra...);
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001231 }
1232
Dean Moldovan03f627e2016-11-01 11:44:57 +01001233 /// Uses return_value_policy::reference by default
1234 template <typename Getter, typename... Extra>
1235 class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1236 return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1237 }
1238
1239 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001240 template <typename... Extra>
1241 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1242 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
Ted Drain0a0758c2017-11-07 08:35:27 -08001243 auto *rec_active = rec_fget;
1244 if (rec_fget) {
1245 char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
1246 detail::process_attributes<Extra...>::init(extra..., rec_fget);
1247 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1248 free(doc_prev);
1249 rec_fget->doc = strdup(rec_fget->doc);
1250 }
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001251 }
1252 if (rec_fset) {
Ted Drain0a0758c2017-11-07 08:35:27 -08001253 char *doc_prev = rec_fset->doc;
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001254 detail::process_attributes<Extra...>::init(extra..., rec_fset);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001255 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1256 free(doc_prev);
1257 rec_fset->doc = strdup(rec_fset->doc);
1258 }
Ted Drain0a0758c2017-11-07 08:35:27 -08001259 if (! rec_active) rec_active = rec_fset;
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001260 }
Ted Drain0a0758c2017-11-07 08:35:27 -08001261 def_property_static_impl(name, fget, fset, rec_active);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001262 return *this;
1263 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001264
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001265private:
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001266 /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1267 template <typename T>
Jason Rhinelander353615f2017-07-25 00:53:23 -04001268 static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001269 const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001270 try {
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001271 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1272 v_h.value_ptr<type>()->shared_from_this());
Jason Rhinelanderb8ac4382017-05-19 13:34:55 -04001273 if (sh) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001274 new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001275 v_h.set_holder_constructed();
Dean Moldovanab90ec62016-12-07 02:36:44 +01001276 }
Jason Rhinelanderb8ac4382017-05-19 13:34:55 -04001277 } catch (const std::bad_weak_ptr &) {}
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001278
1279 if (!v_h.holder_constructed() && inst->owned) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001280 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001281 v_h.set_holder_constructed();
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001282 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001283 }
1284
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001285 static void init_holder_from_existing(const detail::value_and_holder &v_h,
1286 const holder_type *holder_ptr, std::true_type /*is_copy_constructible*/) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001287 new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001288 }
1289
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001290 static void init_holder_from_existing(const detail::value_and_holder &v_h,
1291 const holder_type *holder_ptr, std::false_type /*is_copy_constructible*/) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001292 new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
Dean Moldovanec009a72017-01-31 17:05:44 +01001293 }
1294
1295 /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
Jason Rhinelander353615f2017-07-25 00:53:23 -04001296 static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001297 const holder_type *holder_ptr, const void * /* dummy -- not enable_shared_from_this<T>) */) {
Dean Moldovanec009a72017-01-31 17:05:44 +01001298 if (holder_ptr) {
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001299 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1300 v_h.set_holder_constructed();
Dean Moldovanec009a72017-01-31 17:05:44 +01001301 } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001302 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001303 v_h.set_holder_constructed();
Jason Rhinelanderc07ec312016-11-06 13:12:48 -05001304 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001305 }
1306
Jason Rhinelander353615f2017-07-25 00:53:23 -04001307 /// Performs instance initialization including constructing a holder and registering the known
1308 /// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes an
1309 /// optional pointer to an existing holder to use; if not specified and the instance is
1310 /// `.owned`, a new holder will be constructed to manage the value pointer.
1311 static void init_instance(detail::instance *inst, const void *holder_ptr) {
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001312 auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
Jason Rhinelandercca20a72017-07-29 03:56:01 -04001313 if (!v_h.instance_registered()) {
1314 register_instance(inst, v_h.value_ptr(), v_h.type);
1315 v_h.set_instance_registered();
1316 }
Jason Rhinelander353615f2017-07-25 00:53:23 -04001317 init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001318 }
1319
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001320 /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
Jason Rhinelander464d9892017-06-12 21:52:48 -04001321 static void dealloc(detail::value_and_holder &v_h) {
1322 if (v_h.holder_constructed()) {
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001323 v_h.holder<holder_type>().~holder_type();
Jason Rhinelander464d9892017-06-12 21:52:48 -04001324 v_h.set_holder_constructed(false);
1325 }
1326 else {
Jason Rhinelandera03408c2017-07-23 00:32:58 -04001327 detail::call_operator_delete(v_h.value_ptr<type>(), v_h.type->type_size);
Jason Rhinelander464d9892017-06-12 21:52:48 -04001328 }
1329 v_h.value_ptr() = nullptr;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001330 }
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001331
1332 static detail::function_record *get_function_record(handle h) {
1333 h = detail::get_function(h);
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001334 return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
Dean Moldovanc7ac16b2016-10-28 03:08:15 +02001335 : nullptr;
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001336 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001337};
1338
Dean Moldovan68986792017-08-30 23:40:55 +02001339/// Binds an existing constructor taking arguments Args...
1340template <typename... Args> detail::initimpl::constructor<Args...> init() { return {}; }
1341/// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
1342/// when not inheriting on the Python side).
1343template <typename... Args> detail::initimpl::alias_constructor<Args...> init_alias() { return {}; }
1344
1345/// Binds a factory function as a constructor
1346template <typename Func, typename Ret = detail::initimpl::factory<Func>>
1347Ret init(Func &&f) { return {std::forward<Func>(f)}; }
1348
1349/// Dual-argument factory function: the first function is called when no alias is needed, the second
1350/// when an alias is needed (i.e. due to python-side inheritance). Arguments must be identical.
1351template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1352Ret init(CFunc &&c, AFunc &&a) {
1353 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1354}
1355
1356/// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
1357/// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
1358template <typename GetState, typename SetState>
1359detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
1360 return {std::forward<GetState>(g), std::forward<SetState>(s)};
Marcin Wojdyrfbab29c2017-09-04 18:37:16 +01001361}
Dean Moldovan68986792017-08-30 23:40:55 +02001362
Wenzel Jakobf4245182018-09-01 01:20:24 +02001363NAMESPACE_BEGIN(detail)
1364struct enum_base {
1365 enum_base(handle base, handle parent) : m_base(base), m_parent(parent) { }
1366
1367 PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
1368 m_base.attr("__entries") = dict();
1369 auto property = handle((PyObject *) &PyProperty_Type);
1370 auto static_property = handle((PyObject *) get_internals().static_property_type);
1371
1372 m_base.attr("__repr__") = cpp_function(
1373 [](handle arg) -> str {
1374 handle type = arg.get_type();
1375 object type_name = type.attr("__name__");
1376 dict entries = type.attr("__entries");
1377 for (const auto &kv : entries) {
1378 object other = kv.second[int_(0)];
1379 if (other.equal(arg))
1380 return pybind11::str("{}.{}").format(type_name, kv.first);
1381 }
1382 return pybind11::str("{}.???").format(type_name);
1383 }, is_method(m_base)
1384 );
1385
1386 m_base.attr("name") = property(cpp_function(
1387 [](handle arg) -> str {
1388 dict entries = arg.get_type().attr("__entries");
1389 for (const auto &kv : entries) {
1390 if (handle(kv.second[int_(0)]).equal(arg))
1391 return pybind11::str(kv.first);
1392 }
1393 return "???";
1394 }, is_method(m_base)
1395 ));
1396
1397 m_base.attr("__doc__") = static_property(cpp_function(
1398 [](handle arg) -> std::string {
1399 std::string docstring;
1400 dict entries = arg.attr("__entries");
1401 if (((PyTypeObject *) arg.ptr())->tp_doc)
1402 docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) + "\n\n";
1403 docstring += "Members:";
1404 for (const auto &kv : entries) {
1405 auto key = std::string(pybind11::str(kv.first));
1406 auto comment = kv.second[int_(1)];
1407 docstring += "\n\n " + key;
1408 if (!comment.is_none())
1409 docstring += " : " + (std::string) pybind11::str(comment);
1410 }
1411 return docstring;
1412 }
1413 ), none(), none(), "");
1414
1415 m_base.attr("__members__") = static_property(cpp_function(
1416 [](handle arg) -> dict {
1417 dict entries = arg.attr("__entries"), m;
1418 for (const auto &kv : entries)
1419 m[kv.first] = kv.second[int_(0)];
1420 return m;
1421 }), none(), none(), ""
1422 );
1423
1424 #define PYBIND11_ENUM_OP_STRICT(op, expr) \
1425 m_base.attr(op) = cpp_function( \
1426 [](object a, object b) { \
1427 if (!a.get_type().is(b.get_type())) \
1428 throw type_error("Expected an enumeration of matching type!"); \
1429 return expr; \
1430 }, \
1431 is_method(m_base))
1432
1433 #define PYBIND11_ENUM_OP_CONV(op, expr) \
1434 m_base.attr(op) = cpp_function( \
1435 [](object a_, object b_) { \
1436 int_ a(a_), b(b_); \
1437 return expr; \
1438 }, \
1439 is_method(m_base))
1440
1441 if (is_convertible) {
1442 PYBIND11_ENUM_OP_CONV("__eq__", !b.is_none() && a.equal(b));
1443 PYBIND11_ENUM_OP_CONV("__ne__", b.is_none() || !a.equal(b));
1444
1445 if (is_arithmetic) {
1446 PYBIND11_ENUM_OP_CONV("__lt__", a < b);
1447 PYBIND11_ENUM_OP_CONV("__gt__", a > b);
1448 PYBIND11_ENUM_OP_CONV("__le__", a <= b);
1449 PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
1450 PYBIND11_ENUM_OP_CONV("__and__", a & b);
1451 PYBIND11_ENUM_OP_CONV("__rand__", a & b);
1452 PYBIND11_ENUM_OP_CONV("__or__", a | b);
1453 PYBIND11_ENUM_OP_CONV("__ror__", a | b);
1454 PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
1455 PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
1456 }
1457 } else {
1458 PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)));
1459 PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)));
1460
1461 if (is_arithmetic) {
1462 PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b));
1463 PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b));
1464 PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b));
1465 PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b));
1466 }
1467 }
1468
1469 #undef PYBIND11_ENUM_OP_CONV
1470 #undef PYBIND11_ENUM_OP_STRICT
1471
1472 object getstate = cpp_function(
1473 [](object arg) { return int_(arg); }, is_method(m_base));
1474
1475 m_base.attr("__getstate__") = getstate;
1476 m_base.attr("__hash__") = getstate;
1477 }
1478
1479 PYBIND11_NOINLINE void value(char const* name_, object value, const char *doc = nullptr) {
1480 dict entries = m_base.attr("__entries");
1481 str name(name_);
1482 if (entries.contains(name)) {
1483 std::string type_name = (std::string) str(m_base.attr("__name__"));
1484 throw value_error(type_name + ": element \"" + std::string(name_) + "\" already exists!");
1485 }
1486
1487 entries[name] = std::make_pair(value, doc);
1488 m_base.attr(name) = value;
1489 }
1490
1491 PYBIND11_NOINLINE void export_values() {
1492 dict entries = m_base.attr("__entries");
1493 for (const auto &kv : entries)
1494 m_parent.attr(kv.first) = kv.second[int_(0)];
1495 }
1496
1497 handle m_base;
1498 handle m_parent;
1499};
1500
1501NAMESPACE_END(detail)
1502
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001503/// Binds C++ enumerations and enumeration classes to Python
1504template <typename Type> class enum_ : public class_<Type> {
1505public:
Wenzel Jakobc8e9f3c2018-09-14 12:07:47 +02001506 using Base = class_<Type>;
1507 using Base::def;
1508 using Base::attr;
1509 using Base::def_property_readonly;
1510 using Base::def_property_readonly_static;
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001511 using Scalar = typename std::underlying_type<Type>::type;
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001512
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001513 template <typename... Extra>
1514 enum_(const handle &scope, const char *name, const Extra&... extra)
Wenzel Jakobf4245182018-09-01 01:20:24 +02001515 : class_<Type>(scope, name, extra...), m_base(*this, scope) {
Dean Moldovan82ece942017-03-29 11:55:18 +02001516 constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
Wenzel Jakobf4245182018-09-01 01:20:24 +02001517 constexpr bool is_convertible = std::is_convertible<Type, Scalar>::value;
1518 m_base.init(is_arithmetic, is_convertible);
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001519
Dean Moldovan68986792017-08-30 23:40:55 +02001520 def(init([](Scalar i) { return static_cast<Type>(i); }));
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001521 def("__int__", [](Type value) { return (Scalar) value; });
Wenzel Jakobe6fd2cd2017-04-28 14:46:52 +02001522 #if PY_MAJOR_VERSION < 3
1523 def("__long__", [](Type value) { return (Scalar) value; });
1524 #endif
Wenzel Jakobc8e9f3c2018-09-14 12:07:47 +02001525 cpp_function setstate(
1526 [](Type &value, Scalar arg) { value = static_cast<Type>(arg); },
1527 is_method(*this));
1528 attr("__setstate__") = setstate;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001529 }
1530
1531 /// Export enumeration entries into the parent scope
Matthieu Becaf936e12017-03-03 08:45:50 -08001532 enum_& export_values() {
Wenzel Jakobf4245182018-09-01 01:20:24 +02001533 m_base.export_values();
Wenzel Jakobe916d842016-11-04 16:51:14 +01001534 return *this;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001535 }
1536
1537 /// Add an enumeration entry
Wenzel Jakob6d190362017-11-16 22:24:36 +01001538 enum_& value(char const* name, Type value, const char *doc = nullptr) {
Wenzel Jakobf4245182018-09-01 01:20:24 +02001539 m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001540 return *this;
1541 }
Matthieu Becaf936e12017-03-03 08:45:50 -08001542
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001543private:
Wenzel Jakobf4245182018-09-01 01:20:24 +02001544 detail::enum_base m_base;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001545};
1546
1547NAMESPACE_BEGIN(detail)
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001548
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001549
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001550inline void keep_alive_impl(handle nurse, handle patient) {
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001551 if (!nurse || !patient)
Wenzel Jakob678d7872016-01-17 22:36:41 +01001552 pybind11_fail("Could not activate keep_alive!");
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001553
Ivan Smirnov984c7622016-08-29 02:38:47 +01001554 if (patient.is_none() || nurse.is_none())
Glen Walkerf45bb582016-08-16 17:50:43 +12001555 return; /* Nothing to keep alive or nothing to be kept alive by */
Wenzel Jakob9b880ba2016-04-25 03:25:13 +02001556
Bruce Merry9d698f72017-06-24 14:58:42 +02001557 auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
1558 if (!tinfo.empty()) {
1559 /* It's a pybind-registered type, so we can store the patient in the
1560 * internal list. */
1561 add_patient(nurse.ptr(), patient.ptr());
1562 }
1563 else {
1564 /* Fall back to clever approach based on weak references taken from
1565 * Boost.Python. This is not used for pybind-registered types because
1566 * the objects can be destroyed out-of-order in a GC pass. */
1567 cpp_function disable_lifesupport(
1568 [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001569
Bruce Merry9d698f72017-06-24 14:58:42 +02001570 weakref wr(nurse, disable_lifesupport);
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001571
Bruce Merry9d698f72017-06-24 14:58:42 +02001572 patient.inc_ref(); /* reference patient and leak the weak reference */
1573 (void) wr.release();
1574 }
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001575}
1576
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -05001577PYBIND11_NOINLINE inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
Dean Moldovan7939f4b2017-09-04 13:49:19 +02001578 auto get_arg = [&](size_t n) {
1579 if (n == 0)
1580 return ret;
1581 else if (n == 1 && call.init_self)
1582 return call.init_self;
1583 else if (n <= call.args.size())
1584 return call.args[n - 1];
1585 return handle();
1586 };
1587
1588 keep_alive_impl(get_arg(Nurse), get_arg(Patient));
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001589}
1590
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001591inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type) {
1592 auto res = get_internals().registered_types_py
Jason Rhinelander12be4cd2017-07-29 03:53:45 -04001593#ifdef __cpp_lib_unordered_map_try_emplace
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001594 .try_emplace(type);
1595#else
1596 .emplace(type, std::vector<detail::type_info *>());
1597#endif
1598 if (res.second) {
1599 // New cache entry created; set up a weak reference to automatically remove it if the type
1600 // gets destroyed:
1601 weakref((PyObject *) type, cpp_function([type](handle wr) {
1602 get_internals().registered_types_py.erase(type);
1603 wr.dec_ref();
1604 })).release();
1605 }
1606
1607 return res;
1608}
1609
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001610template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001611struct iterator_state {
1612 Iterator it;
1613 Sentinel end;
Dean Moldovancaedf742017-06-09 16:49:04 +02001614 bool first_or_done;
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001615};
Wenzel Jakobb2825952016-04-13 23:33:00 +02001616
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001617NAMESPACE_END(detail)
1618
Jason Rhinelander3d591e82017-03-18 13:34:21 -03001619/// Makes a python iterator from a first and past-the-end C++ InputIterator.
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001620template <return_value_policy Policy = return_value_policy::reference_internal,
1621 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001622 typename Sentinel,
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001623 typename ValueType = decltype(*std::declval<Iterator>()),
1624 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001625iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001626 typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001627
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001628 if (!detail::get_type_info(typeid(state), false)) {
Jason Rhinelander7437c692017-07-28 22:03:44 -04001629 class_<state>(handle(), "iterator", pybind11::module_local())
Wenzel Jakobb2825952016-04-13 23:33:00 +02001630 .def("__iter__", [](state &s) -> state& { return s; })
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001631 .def("__next__", [](state &s) -> ValueType {
Dean Moldovancaedf742017-06-09 16:49:04 +02001632 if (!s.first_or_done)
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001633 ++s.it;
1634 else
Dean Moldovancaedf742017-06-09 16:49:04 +02001635 s.first_or_done = false;
1636 if (s.it == s.end) {
1637 s.first_or_done = true;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001638 throw stop_iteration();
Dean Moldovancaedf742017-06-09 16:49:04 +02001639 }
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001640 return *s.it;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001641 }, std::forward<Extra>(extra)..., Policy);
Wenzel Jakobb2825952016-04-13 23:33:00 +02001642 }
1643
Dean Moldovancaedf742017-06-09 16:49:04 +02001644 return cast(state{first, last, true});
Wenzel Jakobb2825952016-04-13 23:33:00 +02001645}
Wenzel Jakob146397e2016-09-06 13:06:31 +09001646
Jason Rhinelander3d591e82017-03-18 13:34:21 -03001647/// Makes an python iterator over the keys (`.first`) of a iterator over pairs from a
1648/// first and past-the-end InputIterator.
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001649template <return_value_policy Policy = return_value_policy::reference_internal,
1650 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001651 typename Sentinel,
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001652 typename KeyType = decltype((*std::declval<Iterator>()).first),
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001653 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001654iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001655 typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001656
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001657 if (!detail::get_type_info(typeid(state), false)) {
Jason Rhinelander7437c692017-07-28 22:03:44 -04001658 class_<state>(handle(), "iterator", pybind11::module_local())
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001659 .def("__iter__", [](state &s) -> state& { return s; })
1660 .def("__next__", [](state &s) -> KeyType {
Dean Moldovancaedf742017-06-09 16:49:04 +02001661 if (!s.first_or_done)
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001662 ++s.it;
1663 else
Dean Moldovancaedf742017-06-09 16:49:04 +02001664 s.first_or_done = false;
1665 if (s.it == s.end) {
1666 s.first_or_done = true;
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001667 throw stop_iteration();
Dean Moldovancaedf742017-06-09 16:49:04 +02001668 }
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001669 return (*s.it).first;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001670 }, std::forward<Extra>(extra)..., Policy);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001671 }
1672
Dean Moldovancaedf742017-06-09 16:49:04 +02001673 return cast(state{first, last, true});
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001674}
Wenzel Jakobb2825952016-04-13 23:33:00 +02001675
Jason Rhinelander3d591e82017-03-18 13:34:21 -03001676/// Makes an iterator over values of an stl container or other container supporting
1677/// `std::begin()`/`std::end()`
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001678template <return_value_policy Policy = return_value_policy::reference_internal,
1679 typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
1680 return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
Wenzel Jakobbf0c7dc2016-04-18 10:52:12 +02001681}
1682
Jason Rhinelander3d591e82017-03-18 13:34:21 -03001683/// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
1684/// `std::begin()`/`std::end()`
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001685template <return_value_policy Policy = return_value_policy::reference_internal,
1686 typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
1687 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001688}
1689
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001690template <typename InputType, typename OutputType> void implicitly_convertible() {
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +02001691 struct set_flag {
1692 bool &flag;
1693 set_flag(bool &flag) : flag(flag) { flag = true; }
1694 ~set_flag() { flag = false; }
1695 };
Wenzel Jakob2ac50442016-01-17 22:36:35 +01001696 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +02001697 static bool currently_used = false;
1698 if (currently_used) // implicit conversions are non-reentrant
1699 return nullptr;
1700 set_flag flag_helper(currently_used);
Dean Moldovan5f07fac2017-01-03 11:52:05 +01001701 if (!detail::make_caster<InputType>().load(obj, false))
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001702 return nullptr;
1703 tuple args(1);
1704 args[0] = obj;
1705 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1706 if (result == nullptr)
1707 PyErr_Clear();
1708 return result;
1709 };
Ivan Smirnov8f3e0452016-10-23 15:43:03 +01001710
1711 if (auto tinfo = detail::get_type_info(typeid(OutputType)))
1712 tinfo->implicit_conversions.push_back(implicit_caster);
1713 else
Wenzel Jakob678d7872016-01-17 22:36:41 +01001714 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001715}
1716
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001717template <typename ExceptionTranslator>
1718void register_exception_translator(ExceptionTranslator&& translator) {
1719 detail::get_internals().registered_exception_translators.push_front(
1720 std::forward<ExceptionTranslator>(translator));
1721}
1722
Jason Rhinelander37b23832017-05-22 12:06:16 -04001723/**
1724 * Wrapper to generate a new Python exception type.
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001725 *
1726 * This should only be used with PyErr_SetString for now.
1727 * It is not (yet) possible to use as a py::base.
1728 * Template type argument is reserved for future use.
1729 */
1730template <typename type>
1731class exception : public object {
1732public:
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001733 exception() = default;
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001734 exception(handle scope, const char *name, PyObject *base = PyExc_Exception) {
1735 std::string full_name = scope.attr("__name__").cast<std::string>() +
1736 std::string(".") + name;
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -05001737 m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base, NULL);
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001738 if (hasattr(scope, name))
1739 pybind11_fail("Error during initialization: multiple incompatible "
1740 "definitions with name \"" + std::string(name) + "\"");
1741 scope.attr(name) = *this;
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001742 }
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001743
1744 // Sets the current python exception to this exception object with the given message
1745 void operator()(const char *message) {
1746 PyErr_SetString(m_ptr, message);
1747 }
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001748};
1749
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001750NAMESPACE_BEGIN(detail)
1751// Returns a reference to a function-local static exception object used in the simple
1752// register_exception approach below. (It would be simpler to have the static local variable
1753// directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
1754template <typename CppException>
1755exception<CppException> &get_exception_object() { static exception<CppException> ex; return ex; }
1756NAMESPACE_END(detail)
1757
Jason Rhinelander37b23832017-05-22 12:06:16 -04001758/**
1759 * Registers a Python exception in `m` of the given `name` and installs an exception translator to
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001760 * translate the C++ exception to the created Python exception using the exceptions what() method.
1761 * This is intended for simple exception translations; for more complex translation, register the
1762 * exception object and translator directly.
1763 */
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001764template <typename CppException>
1765exception<CppException> &register_exception(handle scope,
1766 const char *name,
1767 PyObject *base = PyExc_Exception) {
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001768 auto &ex = detail::get_exception_object<CppException>();
1769 if (!ex) ex = exception<CppException>(scope, name, base);
1770
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001771 register_exception_translator([](std::exception_ptr p) {
1772 if (!p) return;
1773 try {
1774 std::rethrow_exception(p);
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001775 } catch (const CppException &e) {
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001776 detail::get_exception_object<CppException>()(e.what());
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001777 }
1778 });
1779 return ex;
1780}
1781
Dean Moldovan67990d92016-08-29 18:03:34 +02001782NAMESPACE_BEGIN(detail)
1783PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
1784 auto strings = tuple(args.size());
1785 for (size_t i = 0; i < args.size(); ++i) {
Dean Moldovane18bc022016-10-25 22:12:39 +02001786 strings[i] = str(args[i]);
Dean Moldovan67990d92016-08-29 18:03:34 +02001787 }
Dean Moldovan865e4302016-09-21 01:06:32 +02001788 auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
Dean Moldovan242b1462016-09-08 17:02:04 +02001789 auto line = sep.attr("join")(strings);
Dean Moldovan67990d92016-08-29 18:03:34 +02001790
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001791 object file;
1792 if (kwargs.contains("file")) {
1793 file = kwargs["file"].cast<object>();
1794 } else {
1795 try {
1796 file = module::import("sys").attr("stdout");
esquires67a68f12016-12-01 05:35:34 -05001797 } catch (const error_already_set &) {
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001798 /* If print() is called from code that is executed as
1799 part of garbage collection during interpreter shutdown,
1800 importing 'sys' can fail. Give up rather than crashing the
1801 interpreter in this case. */
1802 return;
1803 }
1804 }
1805
Dean Moldovan242b1462016-09-08 17:02:04 +02001806 auto write = file.attr("write");
Dean Moldovan67990d92016-08-29 18:03:34 +02001807 write(line);
Dean Moldovan865e4302016-09-21 01:06:32 +02001808 write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
Dean Moldovan67990d92016-08-29 18:03:34 +02001809
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001810 if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
Dean Moldovan242b1462016-09-08 17:02:04 +02001811 file.attr("flush")();
Dean Moldovan67990d92016-08-29 18:03:34 +02001812}
1813NAMESPACE_END(detail)
1814
1815template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1816void print(Args &&...args) {
1817 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
1818 detail::print(c.args(), c.kwargs());
1819}
1820
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001821#if defined(WITH_THREAD) && !defined(PYPY_VERSION)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001822
1823/* The functions below essentially reproduce the PyGILState_* API using a RAII
1824 * pattern, but there are a few important differences:
1825 *
1826 * 1. When acquiring the GIL from an non-main thread during the finalization
1827 * phase, the GILState API blindly terminates the calling thread, which
1828 * is often not what is wanted. This API does not do this.
1829 *
1830 * 2. The gil_scoped_release function can optionally cut the relationship
1831 * of a PyThreadState and its associated thread, which allows moving it to
1832 * another thread (this is a fairly rare/advanced use case).
1833 *
1834 * 3. The reference count of an acquired thread state can be controlled. This
1835 * can be handy to prevent cases where callbacks issued from an external
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001836 * thread would otherwise constantly construct and destroy thread state data
1837 * structures.
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001838 *
1839 * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
1840 * example which uses features 2 and 3 to migrate the Python thread of
1841 * execution to another thread (to run the event loop on the original thread,
1842 * in this case).
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001843 */
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001844
1845class gil_scoped_acquire {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001846public:
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001847 PYBIND11_NOINLINE gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001848 auto const &internals = detail::get_internals();
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001849 tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001850
1851 if (!tstate) {
1852 tstate = PyThreadState_New(internals.istate);
1853 #if !defined(NDEBUG)
1854 if (!tstate)
1855 pybind11_fail("scoped_acquire: could not create thread state!");
1856 #endif
1857 tstate->gilstate_counter = 0;
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001858 PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001859 } else {
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001860 release = detail::get_thread_state_unchecked() != tstate;
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001861 }
1862
1863 if (release) {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001864 /* Work around an annoying assertion in PyThreadState_Swap */
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001865 #if defined(Py_DEBUG)
1866 PyInterpreterState *interp = tstate->interp;
1867 tstate->interp = nullptr;
1868 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001869 PyEval_AcquireThread(tstate);
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001870 #if defined(Py_DEBUG)
1871 tstate->interp = interp;
1872 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001873 }
1874
1875 inc_ref();
1876 }
1877
1878 void inc_ref() {
1879 ++tstate->gilstate_counter;
1880 }
1881
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001882 PYBIND11_NOINLINE void dec_ref() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001883 --tstate->gilstate_counter;
1884 #if !defined(NDEBUG)
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001885 if (detail::get_thread_state_unchecked() != tstate)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001886 pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
1887 if (tstate->gilstate_counter < 0)
1888 pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
1889 #endif
1890 if (tstate->gilstate_counter == 0) {
1891 #if !defined(NDEBUG)
1892 if (!release)
1893 pybind11_fail("scoped_acquire::dec_ref(): internal error!");
1894 #endif
1895 PyThreadState_Clear(tstate);
1896 PyThreadState_DeleteCurrent();
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001897 PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001898 release = false;
1899 }
1900 }
1901
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001902 PYBIND11_NOINLINE ~gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001903 dec_ref();
1904 if (release)
1905 PyEval_SaveThread();
1906 }
1907private:
1908 PyThreadState *tstate = nullptr;
1909 bool release = true;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001910};
1911
1912class gil_scoped_release {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001913public:
Jason Rhinelander12d76602016-10-16 16:27:42 -04001914 explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
Dean Moldovan2d6116b2017-06-20 23:50:51 +02001915 // `get_internals()` must be called here unconditionally in order to initialize
1916 // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
1917 // initialization race could occur as multiple threads try `gil_scoped_acquire`.
1918 const auto &internals = detail::get_internals();
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001919 tstate = PyEval_SaveThread();
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001920 if (disassoc) {
Dean Moldovan2d6116b2017-06-20 23:50:51 +02001921 auto key = internals.tstate;
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001922 PYBIND11_TLS_DELETE_VALUE(key);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001923 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001924 }
1925 ~gil_scoped_release() {
1926 if (!tstate)
1927 return;
1928 PyEval_RestoreThread(tstate);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001929 if (disassoc) {
Boris Schäling20ee9352016-05-28 12:26:18 +02001930 auto key = detail::get_internals().tstate;
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001931 PYBIND11_TLS_REPLACE_VALUE(key, tstate);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001932 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001933 }
1934private:
1935 PyThreadState *tstate;
1936 bool disassoc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001937};
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001938#elif defined(PYPY_VERSION)
1939class gil_scoped_acquire {
1940 PyGILState_STATE state;
1941public:
1942 gil_scoped_acquire() { state = PyGILState_Ensure(); }
1943 ~gil_scoped_acquire() { PyGILState_Release(state); }
1944};
1945
1946class gil_scoped_release {
1947 PyThreadState *state;
1948public:
1949 gil_scoped_release() { state = PyEval_SaveThread(); }
1950 ~gil_scoped_release() { PyEval_RestoreThread(state); }
1951};
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001952#else
1953class gil_scoped_acquire { };
1954class gil_scoped_release { };
Felipe Lema2547ca42016-01-25 16:22:44 -03001955#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001956
Wenzel Jakob8d396fc2016-11-24 23:11:02 +01001957error_already_set::~error_already_set() {
Jason Rhinelander1682b672017-07-20 23:14:33 -04001958 if (type) {
Antony Lee58e551c2018-04-16 19:08:45 -07001959 error_scope scope;
Wenzel Jakob8d396fc2016-11-24 23:11:02 +01001960 gil_scoped_acquire gil;
Jason Rhinelander1682b672017-07-20 23:14:33 -04001961 type.release().dec_ref();
1962 value.release().dec_ref();
1963 trace.release().dec_ref();
Wenzel Jakob8d396fc2016-11-24 23:11:02 +01001964 }
1965}
1966
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04001967inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001968 handle self = detail::get_object_handle(this_ptr, this_type);
1969 if (!self)
Wenzel Jakobac0fde92015-10-01 18:37:26 +02001970 return function();
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001971 handle type = self.get_type();
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001972 auto key = std::make_pair(type.ptr(), name);
1973
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001974 /* Cache functions that aren't overloaded in Python to avoid
1975 many costly Python dictionary lookups below */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001976 auto &cache = detail::get_internals().inactive_overload_cache;
1977 if (cache.find(key) != cache.end())
1978 return function();
1979
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001980 function overload = getattr(self, name, function());
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001981 if (overload.is_cpp_function()) {
1982 cache.insert(key);
1983 return function();
1984 }
Wenzel Jakob27e8e102016-01-17 22:36:37 +01001985
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001986 /* Don't call dispatch code if invoked from overridden function.
1987 Unfortunately this doesn't work on PyPy. */
1988#if !defined(PYPY_VERSION)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001989 PyFrameObject *frame = PyThreadState_Get()->frame;
Dean Moldovane18bc022016-10-25 22:12:39 +02001990 if (frame && (std::string) str(frame->f_code->co_name) == name &&
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001991 frame->f_code->co_argcount > 0) {
1992 PyFrame_FastToLocals(frame);
1993 PyObject *self_caller = PyDict_GetItem(
1994 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001995 if (self_caller == self.ptr())
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001996 return function();
1997 }
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001998#else
1999 /* PyPy currently doesn't provide a detailed cpyext emulation of
2000 frame objects, so we have to emulate this using Python. This
2001 is going to be slow..*/
2002 dict d; d["self"] = self; d["name"] = pybind11::str(name);
2003 PyObject *result = PyRun_String(
2004 "import inspect\n"
2005 "frame = inspect.currentframe()\n"
2006 "if frame is not None:\n"
2007 " frame = frame.f_back\n"
2008 " if frame is not None and str(frame.f_code.co_name) == name and "
2009 "frame.f_code.co_argcount > 0:\n"
2010 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2011 " if self_caller == self:\n"
2012 " self = None\n",
2013 Py_file_input, d.ptr(), d.ptr());
2014 if (result == nullptr)
2015 throw error_already_set();
Dean Moldovan36f0a152017-02-08 01:01:56 +01002016 if (d["self"].is_none())
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002017 return function();
2018 Py_DECREF(result);
2019#endif
2020
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002021 return overload;
2022}
2023
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04002024template <class T> function get_overload(const T *this_ptr, const char *name) {
Ivan Smirnov8f3e0452016-10-23 15:43:03 +01002025 auto tinfo = detail::get_type_info(typeid(T));
2026 return tinfo ? get_type_overload(this_ptr, tinfo, name) : function();
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04002027}
2028
Jason Rhinelander20978262016-08-29 18:16:46 -04002029#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02002030 pybind11::gil_scoped_acquire gil; \
Jason Rhinelander20978262016-08-29 18:16:46 -04002031 pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04002032 if (overload) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04002033 auto o = overload(__VA_ARGS__); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04002034 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04002035 static pybind11::detail::overload_caster_t<ret_type> caster; \
2036 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04002037 } \
2038 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2039 } \
2040 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002041
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002042#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelandere88656a2018-02-27 22:33:41 -04002043 PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002044 return cname::fn(__VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002045
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002046#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelandere88656a2018-02-27 22:33:41 -04002047 PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
Jason Rhinelander9f41c8e2018-02-27 23:43:16 -04002048 pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\"");
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002049
2050#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
Jason Rhinelandere88656a2018-02-27 22:33:41 -04002051 PYBIND11_OVERLOAD_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002052
2053#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
Jason Rhinelandere88656a2018-02-27 22:33:41 -04002054 PYBIND11_OVERLOAD_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002055
Jason Rhinelandera859dd62017-08-10 12:03:29 -04002056NAMESPACE_END(PYBIND11_NAMESPACE)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02002057
2058#if defined(_MSC_VER)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01002059# pragma warning(pop)
Wenzel Jakob1ffce742016-08-25 01:43:33 +02002060#elif defined(__INTEL_COMPILER)
2061/* Leave ignored warnings on */
Wenzel Jakob6d252962016-05-01 20:47:49 +02002062#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01002063# pragma GCC diagnostic pop
Wenzel Jakob38bd7112015-07-05 20:05:44 +02002064#endif