blob: 513ceed5dd81cc2763d8c609bd0832e7977416af [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
Baljak81da9882018-11-20 23:22:02 +010013#if defined(__INTEL_COMPILER)
14# pragma warning push
15# pragma warning disable 68 // integer conversion resulted in a change of sign
16# pragma warning disable 186 // pointless comparison of unsigned integer with zero
17# pragma warning disable 878 // incompatible exception specifications
18# pragma warning disable 1334 // the "template" keyword used for syntactic disambiguation may only be used within a template
19# pragma warning disable 1682 // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem)
20# pragma warning disable 1786 // function "strdup" was declared deprecated
21# pragma warning disable 1875 // offsetof applied to non-POD (Plain Old Data) types is nonstandard
22# pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
23#elif defined(_MSC_VER)
Wenzel Jakob48548ea2016-01-17 22:36:44 +010024# pragma warning(push)
Wenzel Jakob1ffce742016-08-25 01:43:33 +020025# pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
Wenzel Jakob48548ea2016-01-17 22:36:44 +010026# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
Wenzel Jakob1ffce742016-08-25 01:43:33 +020027# pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
Wenzel Jakob48548ea2016-01-17 22:36:44 +010028# pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
29# 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 +090030# pragma warning(disable: 4702) // warning C4702: unreachable code
Dean Moldovan2bab5792016-09-23 00:27:59 +020031# pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
Wenzel Jakob6d252962016-05-01 20:47:49 +020032#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +010033# pragma GCC diagnostic push
34# pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
35# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
36# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
Wenzel Jakobdeeab552016-05-15 23:54:34 +020037# pragma GCC diagnostic ignored "-Wstrict-aliasing"
38# pragma GCC diagnostic ignored "-Wattributes"
Jason Rhinelanderd15b2172017-05-09 14:46:15 -040039# if __GNUC__ >= 7
40# pragma GCC diagnostic ignored "-Wnoexcept-type"
41# endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +020042#endif
43
Wenzel Jakob48548ea2016-01-17 22:36:44 +010044#include "attr.h"
Alexander Stukowski9a110e62016-11-15 12:38:05 +010045#include "options.h"
Dean Moldovanf5806492017-08-14 00:35:53 +020046#include "detail/class.h"
Jason Rhinelander464d9892017-06-12 21:52:48 -040047#include "detail/init.h"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020048
Wenzel Jakoba1b71df2019-06-19 10:48:36 +020049#if defined(__GNUG__) && !defined(__clang__)
50# include <cxxabi.h>
51#endif
52
Jason Rhinelandera859dd62017-08-10 12:03:29 -040053NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
Wenzel Jakob38bd7112015-07-05 20:05:44 +020054
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020055/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020056class cpp_function : public function {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020057public:
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020058 cpp_function() { }
Ted Drain0a0758c2017-11-07 08:35:27 -080059 cpp_function(std::nullptr_t) { }
Wenzel Jakob38bd7112015-07-05 20:05:44 +020060
Wenzel Jakob5984baa2016-05-10 15:05:03 +010061 /// Construct a cpp_function from a vanilla function pointer
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050062 template <typename Return, typename... Args, typename... Extra>
63 cpp_function(Return (*f)(Args...), const Extra&... extra) {
Wenzel Jakob5984baa2016-05-10 15:05:03 +010064 initialize(f, f, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +020065 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020066
Wenzel Jakob5984baa2016-05-10 15:05:03 +010067 /// Construct a cpp_function from a lambda function (possibly with internal state)
Jason Rhinelanderb4bf5ed2017-05-10 01:51:08 -040068 template <typename Func, typename... Extra,
69 typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050070 cpp_function(Func &&f, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020071 initialize(std::forward<Func>(f),
Jason Rhinelanderb4bf5ed2017-05-10 01:51:08 -040072 (detail::function_signature_t<Func> *) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020073 }
74
Wenzel Jakob5984baa2016-05-10 15:05:03 +010075 /// Construct a cpp_function from a class method (non-const)
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050076 template <typename Return, typename Class, typename... Arg, typename... Extra>
77 cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020078 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050079 (Return (*) (Class *, Arg...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020080 }
81
Wenzel Jakob5984baa2016-05-10 15:05:03 +010082 /// Construct a cpp_function from a class method (const)
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050083 template <typename Return, typename Class, typename... Arg, typename... Extra>
84 cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020085 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050086 (Return (*)(const Class *, Arg ...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020087 }
88
Wenzel Jakob57082212015-09-04 23:42:12 +020089 /// Return the function name
Wenzel Jakob48548ea2016-01-17 22:36:44 +010090 object name() const { return attr("__name__"); }
Wenzel Jakob57082212015-09-04 23:42:12 +020091
Wenzel Jakobd561cb02016-01-17 22:36:41 +010092protected:
Wenzel Jakob382484a2016-09-10 15:28:37 +090093 /// Space optimization: don't inline this frequently instantiated fragment
94 PYBIND11_NOINLINE detail::function_record *make_function_record() {
95 return new detail::function_record();
96 }
97
Wenzel Jakobd561cb02016-01-17 22:36:41 +010098 /// Special internal constructor for functors, lambda functions, etc.
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050099 template <typename Func, typename Return, typename... Args, typename... Extra>
100 void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
Dean Moldovan56613942017-07-02 12:52:00 +0200101 using namespace detail;
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400102 struct capture { remove_reference_t<Func> f; };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200103
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100104 /* Store the function including any extra state it might have (e.g. a lambda capture object) */
Wenzel Jakob382484a2016-09-10 15:28:37 +0900105 auto rec = make_function_record();
Wenzel Jakob71867832015-07-29 17:43:52 +0200106
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100107 /* Store the capture object directly in the function record if there is enough space */
108 if (sizeof(capture) <= sizeof(rec->data)) {
Wenzel Jakob954b7932016-07-10 10:13:18 +0200109 /* Without these pragmas, GCC warns that there might not be
110 enough space to use the placement new operator. However, the
111 'if' statement above ensures that this is the case. */
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 push
114# pragma GCC diagnostic ignored "-Wplacement-new"
115#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100116 new ((capture *) &rec->data) capture { std::forward<Func>(f) };
Jason Rhinelander0b12f912016-07-07 16:26:04 -0400117#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -0400118# pragma GCC diagnostic pop
119#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100120 if (!std::is_trivially_destructible<Func>::value)
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400121 rec->free_data = [](function_record *r) { ((capture *) &r->data)->~capture(); };
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100122 } else {
123 rec->data[0] = new capture { std::forward<Func>(f) };
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400124 rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100125 }
Wenzel Jakob19208fe2015-10-13 17:37:25 +0200126
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100127 /* Type casters for the function arguments and return value */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400128 using cast_in = argument_loader<Args...>;
129 using cast_out = make_caster<
130 conditional_t<std::is_void<Return>::value, void_type, Return>
Dean Moldovan719c1732016-11-27 18:19:34 +0100131 >;
Wenzel Jakob71867832015-07-29 17:43:52 +0200132
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400133 static_assert(expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
Jason Rhinelander0f5ec0a2017-03-19 12:36:18 -0300134 "The number of argument annotations does not match the number of function arguments");
Jason Rhinelander2686da82017-01-21 23:42:14 -0500135
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100136 /* Dispatch code which converts function arguments and performs the actual function call */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400137 rec->impl = [](function_call &call) -> handle {
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100138 cast_in args_converter;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100139
140 /* Try to cast the function arguments into the C++ domain */
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500141 if (!args_converter.load_args(call))
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100142 return PYBIND11_TRY_NEXT_OVERLOAD;
143
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100144 /* Invoke call policy pre-call hook */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400145 process_attributes<Extra...>::precall(call);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100146
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100147 /* Get a pointer to the capture object */
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500148 auto data = (sizeof(capture) <= sizeof(call.func.data)
149 ? &call.func.data : call.func.data[0]);
150 capture *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100151
Jason Rhinelander546f6fc2017-01-20 00:59:26 -0500152 /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
Wenzel Jakobcbd16a82018-07-17 16:56:26 +0200153 return_value_policy policy = return_value_policy_override<Return>::policy(call.func.policy);
Dean Moldovand079f412016-11-20 05:31:02 +0100154
Dean Moldovan1ac19032017-03-16 11:22:26 +0100155 /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400156 using Guard = extract_guard_t<Extra...>;
Dean Moldovan1ac19032017-03-16 11:22:26 +0100157
Wenzel Jakob954b7932016-07-10 10:13:18 +0200158 /* Perform the function call */
Jason Rhinelander813d7e82017-05-14 15:57:26 -0400159 handle result = cast_out::cast(
160 std::move(args_converter).template call<Return, Guard>(cap->f), policy, call.parent);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100161
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100162 /* Invoke call policy post-call hook */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400163 process_attributes<Extra...>::postcall(call, result);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100164
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100165 return result;
Wenzel Jakob71867832015-07-29 17:43:52 +0200166 };
167
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100168 /* Process any user-provided function attributes */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400169 process_attributes<Extra...>::init(extra..., rec);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100170
171 /* Generate a readable signature describing the function's arguments and return value types */
Dean Moldovan56613942017-07-02 12:52:00 +0200172 static constexpr auto signature = _("(") + cast_in::arg_names + _(") -> ") + cast_out::name;
173 PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100174
175 /* Register the function with Python from generic (non-templated) code */
Dean Moldovan56613942017-07-02 12:52:00 +0200176 initialize_generic(rec, signature.text, types.data(), sizeof...(Args));
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100177
178 if (cast_in::has_args) rec->has_args = true;
179 if (cast_in::has_kwargs) rec->has_kwargs = true;
Wenzel Jakob954b7932016-07-10 10:13:18 +0200180
181 /* Stash some additional information used by an important optimization in 'functional.h' */
Jason Rhinelander1d7998e2017-02-17 06:56:41 -0500182 using FunctionType = Return (*)(Args...);
Wenzel Jakob954b7932016-07-10 10:13:18 +0200183 constexpr bool is_function_ptr =
184 std::is_convertible<Func, FunctionType>::value &&
185 sizeof(capture) == sizeof(void *);
186 if (is_function_ptr) {
187 rec->is_stateless = true;
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500188 rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
Wenzel Jakob954b7932016-07-10 10:13:18 +0200189 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200190 }
191
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100192 /// Register a function call with Python (generic non-templated code goes here)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100193 void initialize_generic(detail::function_record *rec, const char *text,
Dean Moldovanecced6c2016-07-31 20:03:18 +0200194 const std::type_info *const *types, size_t args) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100195
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100196 /* Create copies of all referenced C-style strings */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100197 rec->name = strdup(rec->name ? rec->name : "");
198 if (rec->doc) rec->doc = strdup(rec->doc);
199 for (auto &a: rec->args) {
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100200 if (a.name)
201 a.name = strdup(a.name);
202 if (a.descr)
203 a.descr = strdup(a.descr);
204 else if (a.value)
Dean Moldovan242b1462016-09-08 17:02:04 +0200205 a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100206 }
Wenzel Jakob954b7932016-07-10 10:13:18 +0200207
Jason Rhinelander464d9892017-06-12 21:52:48 -0400208 rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
209
Dean Moldovanb8c5dbd2017-08-24 02:46:07 +0200210#if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
211 if (rec->is_constructor && !rec->is_new_style_constructor) {
212 const auto class_name = std::string(((PyTypeObject *) rec->scope.ptr())->tp_name);
213 const auto func_name = std::string(rec->name);
214 PyErr_WarnEx(
215 PyExc_FutureWarning,
216 ("pybind11-bound class '" + class_name + "' is using an old-style "
217 "placement-new '" + func_name + "' which has been deprecated. See "
218 "the upgrade guide in pybind11's docs. This message is only visible "
219 "when compiled in debug mode.").c_str(), 0
220 );
221 }
222#endif
223
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100224 /* Generate a proper function signature */
225 std::string signature;
Dean Moldovan0aef6422017-08-31 14:38:23 +0200226 size_t type_index = 0, arg_index = 0;
227 for (auto *pc = text; *pc != '\0'; ++pc) {
228 const auto c = *pc;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100229
230 if (c == '{') {
Dean Moldovan0aef6422017-08-31 14:38:23 +0200231 // Write arg name for everything except *args and **kwargs.
232 if (*(pc + 1) == '*')
233 continue;
234
235 if (arg_index < rec->args.size() && rec->args[arg_index].name) {
236 signature += rec->args[arg_index].name;
237 } else if (arg_index == 0 && rec->is_method) {
238 signature += "self";
239 } else {
240 signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100241 }
Dean Moldovan0aef6422017-08-31 14:38:23 +0200242 signature += ": ";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100243 } else if (c == '}') {
Dean Moldovan0aef6422017-08-31 14:38:23 +0200244 // Write default value if available.
245 if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
Antony Lee0826b3c2017-11-26 20:00:35 -0800246 signature += " = ";
Dean Moldovan0aef6422017-08-31 14:38:23 +0200247 signature += rec->args[arg_index].descr;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100248 }
Dean Moldovan0aef6422017-08-31 14:38:23 +0200249 arg_index++;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100250 } else if (c == '%') {
251 const std::type_info *t = types[type_index++];
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100252 if (!t)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100253 pybind11_fail("Internal error while parsing type signature (1)");
Ivan Smirnov8f3e0452016-10-23 15:43:03 +0100254 if (auto tinfo = detail::get_type_info(*t)) {
Jason Rhinelander71178922017-11-07 12:33:05 -0400255 handle th((PyObject *) tinfo->type);
256 signature +=
257 th.attr("__module__").cast<std::string>() + "." +
258 th.attr("__qualname__").cast<std::string>(); // Python 3.3+, but we backport it to earlier versions
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200259 } else if (rec->is_new_style_constructor && arg_index == 0) {
260 // A new-style `__init__` takes `self` as `value_and_holder`.
261 // Rewrite it to the proper class type.
Jason Rhinelander71178922017-11-07 12:33:05 -0400262 signature +=
263 rec->scope.attr("__module__").cast<std::string>() + "." +
264 rec->scope.attr("__qualname__").cast<std::string>();
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100265 } else {
266 std::string tname(t->name());
267 detail::clean_type_id(tname);
268 signature += tname;
269 }
270 } else {
271 signature += c;
272 }
273 }
Dean Moldovan0aef6422017-08-31 14:38:23 +0200274 if (arg_index != args || types[type_index] != nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100275 pybind11_fail("Internal error while parsing type signature (2)");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100276
Wenzel Jakob57082212015-09-04 23:42:12 +0200277#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100278 if (strcmp(rec->name, "__next__") == 0) {
279 std::free(rec->name);
280 rec->name = strdup("next");
Wenzel Jakobd1bfc4e2016-05-16 18:52:46 +0200281 } else if (strcmp(rec->name, "__bool__") == 0) {
282 std::free(rec->name);
283 rec->name = strdup("__nonzero__");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100284 }
Wenzel Jakob57082212015-09-04 23:42:12 +0200285#endif
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100286 rec->signature = strdup(signature.c_str());
287 rec->args.shrink_to_fit();
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500288 rec->nargs = (std::uint16_t) args;
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200289
Jason Rhinelander0a90b2d2017-04-16 20:30:52 -0400290 if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr()))
291 rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
Wenzel Jakob57082212015-09-04 23:42:12 +0200292
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100293 detail::function_record *chain = nullptr, *chain_start = rec;
Jason Rhinelander6873c202016-10-24 21:58:22 -0400294 if (rec->sibling) {
295 if (PyCFunction_Check(rec->sibling.ptr())) {
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100296 auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
Jason Rhinelander6873c202016-10-24 21:58:22 -0400297 chain = (detail::function_record *) rec_capsule;
298 /* Never append a method to an overload chain of a parent class;
299 instead, hide the parent's overloads in this case */
Dean Moldovan36f0a152017-02-08 01:01:56 +0100300 if (!chain->scope.is(rec->scope))
Jason Rhinelander6873c202016-10-24 21:58:22 -0400301 chain = nullptr;
302 }
303 // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
304 else if (!rec->sibling.is_none() && rec->name[0] != '_')
305 pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
306 "\" with a function of the same name");
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200307 }
308
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100309 if (!chain) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100310 /* No existing overload was found, create a new function object */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100311 rec->def = new PyMethodDef();
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500312 std::memset(rec->def, 0, sizeof(PyMethodDef));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100313 rec->def->ml_name = rec->name;
Antony Leebaf6b992018-06-24 15:38:09 +0200314 rec->def->ml_meth = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(*dispatcher));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100315 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
Wenzel Jakoba6501792016-02-04 23:02:07 +0100316
Wenzel Jakobb16421e2017-03-22 22:04:00 +0100317 capsule rec_capsule(rec, [](void *ptr) {
318 destruct((detail::function_record *) ptr);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100319 });
Wenzel Jakoba6501792016-02-04 23:02:07 +0100320
321 object scope_module;
322 if (rec->scope) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200323 if (hasattr(rec->scope, "__module__")) {
324 scope_module = rec->scope.attr("__module__");
325 } else if (hasattr(rec->scope, "__name__")) {
326 scope_module = rec->scope.attr("__name__");
327 }
Wenzel Jakoba6501792016-02-04 23:02:07 +0100328 }
329
330 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200331 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100332 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200333 } else {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100334 /* Append at the end of the overload chain */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100335 m_ptr = rec->sibling.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200336 inc_ref();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100337 chain_start = chain;
Jason Rhinelanderd355f2f2017-04-16 22:31:13 -0400338 if (chain->is_method != rec->is_method)
339 pybind11_fail("overloading a method with both static and instance methods is not supported; "
340 #if defined(NDEBUG)
341 "compile in debug mode for more details"
342 #else
343 "error while attempting to bind " + std::string(rec->is_method ? "instance" : "static") + " method " +
344 std::string(pybind11::str(rec->scope.attr("__name__"))) + "." + std::string(rec->name) + signature
345 #endif
346 );
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100347 while (chain->next)
348 chain = chain->next;
349 chain->next = rec;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200350 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200351
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200352 std::string signatures;
Wenzel Jakob71867832015-07-29 17:43:52 +0200353 int index = 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100354 /* Create a nice pydoc rec including all signatures and
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100355 docstrings of the functions in the overload chain */
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100356 if (chain && options::show_function_signatures()) {
Sylvain Corlay0e04fdf2016-03-08 16:42:12 -0500357 // First a generic signature
358 signatures += rec->name;
359 signatures += "(*args, **kwargs)\n";
360 signatures += "Overloaded function.\n\n";
361 }
362 // Then specific overload signatures
Jason Rhinelander10d13042017-03-08 12:32:42 -0500363 bool first_user_def = true;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100364 for (auto it = chain_start; it != nullptr; it = it->next) {
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100365 if (options::show_function_signatures()) {
Jason Rhinelander10d13042017-03-08 12:32:42 -0500366 if (index > 0) signatures += "\n";
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100367 if (chain)
368 signatures += std::to_string(++index) + ". ";
369 signatures += rec->name;
370 signatures += it->signature;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100371 signatures += "\n";
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100372 }
373 if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
Jason Rhinelander10d13042017-03-08 12:32:42 -0500374 // If we're appending another docstring, and aren't printing function signatures, we
375 // need to append a newline first:
376 if (!options::show_function_signatures()) {
377 if (first_user_def) first_user_def = false;
378 else signatures += "\n";
379 }
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100380 if (options::show_function_signatures()) signatures += "\n";
Wenzel Jakob218b6ce2016-02-28 23:52:37 +0100381 signatures += it->doc;
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100382 if (options::show_function_signatures()) signatures += "\n";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100383 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200384 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100385
386 /* Install docstring */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200387 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
388 if (func->m_ml->ml_doc)
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500389 std::free(const_cast<char *>(func->m_ml->ml_doc));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200390 func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100391
Wenzel Jakob31fbf182016-11-20 05:27:05 +0100392 if (rec->is_method) {
393 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200394 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100395 pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200396 Py_DECREF(func);
397 }
398 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100399
400 /// When a cpp_function is GCed, release any memory allocated by pybind11
401 static void destruct(detail::function_record *rec) {
402 while (rec) {
403 detail::function_record *next = rec->next;
404 if (rec->free_data)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100405 rec->free_data(rec);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100406 std::free((char *) rec->name);
407 std::free((char *) rec->doc);
408 std::free((char *) rec->signature);
409 for (auto &arg: rec->args) {
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500410 std::free(const_cast<char *>(arg.name));
411 std::free(const_cast<char *>(arg.descr));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100412 arg.value.dec_ref();
413 }
414 if (rec->def) {
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500415 std::free(const_cast<char *>(rec->def->ml_doc));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100416 delete rec->def;
417 }
418 delete rec;
419 rec = next;
420 }
421 }
422
423 /// Main dispatch logic for calls to functions bound using pybind11
Jason Rhinelander2686da82017-01-21 23:42:14 -0500424 static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500425 using namespace detail;
426
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100427 /* Iterator over the list of potentially admissible overloads */
oremanje7761e32018-09-25 14:55:18 -0700428 const function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
429 *it = overloads;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100430
431 /* Need to know how many arguments + keyword arguments there are to pick the right overload */
Jason Rhinelander2686da82017-01-21 23:42:14 -0500432 const size_t n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100433
Jason Rhinelander2686da82017-01-21 23:42:14 -0500434 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100435 result = PYBIND11_TRY_NEXT_OVERLOAD;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500436
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200437 auto self_value_and_holder = value_and_holder();
438 if (overloads->is_constructor) {
439 const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
440 const auto pi = reinterpret_cast<instance *>(parent.ptr());
441 self_value_and_holder = pi->get_value_and_holder(tinfo, false);
442
443 if (!self_value_and_holder.type || !self_value_and_holder.inst) {
444 PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid `self` argument");
445 return nullptr;
446 }
447
448 // If this value is already registered it must mean __init__ is invoked multiple times;
449 // we really can't support that in C++, so just ignore the second __init__.
450 if (self_value_and_holder.instance_registered())
451 return none().release().ptr();
452 }
453
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100454 try {
Jason Rhinelandere5505892017-02-03 18:25:34 -0500455 // We do this in two passes: in the first pass, we load arguments with `convert=false`;
456 // in the second, we allow conversion (except for arguments with an explicit
457 // py::arg().noconvert()). This lets us prefer calls without conversion, with
458 // conversion as a fallback.
459 std::vector<function_call> second_pass;
460
461 // However, if there are no overloads, we can just skip the no-convert pass entirely
462 const bool overloaded = it != nullptr && it->next != nullptr;
463
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100464 for (; it != nullptr; it = it->next) {
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500465
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100466 /* For each overload:
Jason Rhinelander2686da82017-01-21 23:42:14 -0500467 1. Copy all positional arguments we were given, also checking to make sure that
468 named positional arguments weren't *also* specified via kwarg.
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100469 2. If we weren't given enough, try to make up the omitted ones by checking
Jason Rhinelander2686da82017-01-21 23:42:14 -0500470 whether they were provided by a kwarg matching the `py::arg("name")` name. If
471 so, use it (and remove it from kwargs; if not, see if the function binding
472 provided a default that we can use.
473 3. Ensure that either all keyword arguments were "consumed", or that the function
474 takes a kwargs argument to accept unconsumed kwargs.
475 4. Any positional arguments still left get put into a tuple (for args), and any
476 leftover kwargs get put into a dict.
477 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
478 extra tuple or dict at the end of the positional arguments.
479 6. Call the function call dispatcher (function_record::impl)
480
481 If one of these fail, move on to the next overload and keep trying until we get a
482 result other than PYBIND11_TRY_NEXT_OVERLOAD.
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100483 */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100484
oremanje7761e32018-09-25 14:55:18 -0700485 const function_record &func = *it;
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500486 size_t pos_args = func.nargs; // Number of positional arguments that we need
487 if (func.has_args) --pos_args; // (but don't count py::args
488 if (func.has_kwargs) --pos_args; // or py::kwargs)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100489
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500490 if (!func.has_args && n_args_in > pos_args)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500491 continue; // Too many arguments for this overload
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100492
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500493 if (n_args_in < pos_args && func.args.size() < pos_args)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500494 continue; // Not enough arguments given, and not enough defaults to fill in the blanks
495
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500496 function_call call(func, parent);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500497
Nathan9b3fb052019-07-18 01:01:50 -0600498 size_t args_to_copy = (std::min)(pos_args, n_args_in); // Protect std::min with parentheses
Jason Rhinelander2686da82017-01-21 23:42:14 -0500499 size_t args_copied = 0;
500
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200501 // 0. Inject new-style `self` argument
502 if (func.is_new_style_constructor) {
503 // The `value` may have been preallocated by an old-style `__init__`
504 // if it was a preceding candidate for overload resolution.
505 if (self_value_and_holder)
506 self_value_and_holder.type->dealloc(self_value_and_holder);
507
Dean Moldovan7939f4b2017-09-04 13:49:19 +0200508 call.init_self = PyTuple_GET_ITEM(args_in, 0);
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200509 call.args.push_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
510 call.args_convert.push_back(false);
511 ++args_copied;
512 }
513
Jason Rhinelander2686da82017-01-21 23:42:14 -0500514 // 1. Copy any position arguments given.
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400515 bool bad_arg = false;
Jason Rhinelander2686da82017-01-21 23:42:14 -0500516 for (; args_copied < args_to_copy; ++args_copied) {
oremanje7761e32018-09-25 14:55:18 -0700517 const argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400518 if (kwargs_in && arg_rec && arg_rec->name && PyDict_GetItemString(kwargs_in, arg_rec->name)) {
519 bad_arg = true;
Jason Rhinelandercaa13792017-02-23 19:54:53 -0500520 break;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100521 }
Jason Rhinelander2686da82017-01-21 23:42:14 -0500522
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400523 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
524 if (arg_rec && !arg_rec->none && arg.is_none()) {
525 bad_arg = true;
526 break;
527 }
528 call.args.push_back(arg);
529 call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100530 }
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400531 if (bad_arg)
Jason Rhinelandercaa13792017-02-23 19:54:53 -0500532 continue; // Maybe it was meant for another overload (issue #688)
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200533
Jason Rhinelander2686da82017-01-21 23:42:14 -0500534 // We'll need to copy this if we steal some kwargs for defaults
535 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
536
537 // 2. Check kwargs and, failing that, defaults that may help complete the list
538 if (args_copied < pos_args) {
539 bool copied_kwargs = false;
540
541 for (; args_copied < pos_args; ++args_copied) {
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500542 const auto &arg = func.args[args_copied];
Jason Rhinelander2686da82017-01-21 23:42:14 -0500543
544 handle value;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500545 if (kwargs_in && arg.name)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500546 value = PyDict_GetItemString(kwargs.ptr(), arg.name);
547
548 if (value) {
549 // Consume a kwargs value
550 if (!copied_kwargs) {
551 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
552 copied_kwargs = true;
553 }
554 PyDict_DelItemString(kwargs.ptr(), arg.name);
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100555 } else if (arg.value) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500556 value = arg.value;
557 }
558
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500559 if (value) {
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500560 call.args.push_back(value);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500561 call.args_convert.push_back(arg.convert);
562 }
Jason Rhinelander2686da82017-01-21 23:42:14 -0500563 else
564 break;
565 }
566
567 if (args_copied < pos_args)
568 continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments
569 }
570
571 // 3. Check everything was consumed (unless we have a kwargs arg)
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500572 if (kwargs && kwargs.size() > 0 && !func.has_kwargs)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500573 continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
574
575 // 4a. If we have a py::args argument, create a new tuple with leftovers
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500576 if (func.has_args) {
Jason Rhinelander48e1f9a2017-12-23 09:42:32 -0400577 tuple extra_args;
Jason Rhinelander2686da82017-01-21 23:42:14 -0500578 if (args_to_copy == 0) {
579 // We didn't copy out any position arguments from the args_in tuple, so we
580 // can reuse it directly without copying:
581 extra_args = reinterpret_borrow<tuple>(args_in);
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100582 } else if (args_copied >= n_args_in) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500583 extra_args = tuple(0);
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100584 } else {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500585 size_t args_size = n_args_in - args_copied;
586 extra_args = tuple(args_size);
587 for (size_t i = 0; i < args_size; ++i) {
Jason Rhinelander367d7232017-12-15 13:21:52 -0400588 extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500589 }
590 }
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500591 call.args.push_back(extra_args);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500592 call.args_convert.push_back(false);
Jason Rhinelander48e1f9a2017-12-23 09:42:32 -0400593 call.args_ref = std::move(extra_args);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500594 }
595
596 // 4b. If we have a py::kwargs, pass on any remaining kwargs
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500597 if (func.has_kwargs) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500598 if (!kwargs.ptr())
599 kwargs = dict(); // If we didn't get one, send an empty one
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500600 call.args.push_back(kwargs);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500601 call.args_convert.push_back(false);
Jason Rhinelander48e1f9a2017-12-23 09:42:32 -0400602 call.kwargs_ref = std::move(kwargs);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500603 }
604
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500605 // 5. Put everything in a vector. Not technically step 5, we've been building it
606 // in `call.args` all along.
607 #if !defined(NDEBUG)
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500608 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500609 pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
610 #endif
Jason Rhinelander2686da82017-01-21 23:42:14 -0500611
Jason Rhinelandere5505892017-02-03 18:25:34 -0500612 std::vector<bool> second_pass_convert;
613 if (overloaded) {
614 // We're in the first no-convert pass, so swap out the conversion flags for a
615 // set of all-false flags. If the call fails, we'll swap the flags back in for
616 // the conversion-allowed call below.
617 second_pass_convert.resize(func.nargs, false);
618 call.args_convert.swap(second_pass_convert);
619 }
620
Jason Rhinelander2686da82017-01-21 23:42:14 -0500621 // 6. Call the function.
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200622 try {
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200623 loader_life_support guard{};
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500624 result = func.impl(call);
Wenzel Jakob00062592016-07-01 16:07:35 +0200625 } catch (reference_cast_error &) {
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200626 result = PYBIND11_TRY_NEXT_OVERLOAD;
627 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100628
629 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
630 break;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500631
Jason Rhinelandere5505892017-02-03 18:25:34 -0500632 if (overloaded) {
633 // The (overloaded) call failed; if the call has at least one argument that
634 // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
635 // then add this call to the list of second pass overloads to try.
636 for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
637 if (second_pass_convert[i]) {
638 // Found one: swap the converting flags back in and store the call for
639 // the second pass.
640 call.args_convert.swap(second_pass_convert);
641 second_pass.push_back(std::move(call));
642 break;
643 }
644 }
645 }
646 }
647
648 if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
649 // The no-conversion pass finished without success, try again with conversion allowed
650 for (auto &call : second_pass) {
651 try {
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200652 loader_life_support guard{};
Jason Rhinelandere5505892017-02-03 18:25:34 -0500653 result = call.func.impl(call);
654 } catch (reference_cast_error &) {
655 result = PYBIND11_TRY_NEXT_OVERLOAD;
656 }
657
oremanje7761e32018-09-25 14:55:18 -0700658 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
659 // The error reporting logic below expects 'it' to be valid, as it would be
660 // if we'd encountered this failure in the first-pass loop.
661 if (!result)
662 it = &call.func;
Jason Rhinelandere5505892017-02-03 18:25:34 -0500663 break;
oremanje7761e32018-09-25 14:55:18 -0700664 }
Jason Rhinelandere5505892017-02-03 18:25:34 -0500665 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100666 }
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200667 } catch (error_already_set &e) {
668 e.restore();
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400669 return nullptr;
Jörg Kreuzberger69dc3802019-06-10 22:00:55 +0200670#if defined(__GNUG__) && !defined(__clang__)
671 } catch ( abi::__forced_unwind& ) {
672 throw;
673#endif
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100674 } catch (...) {
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400675 /* When an exception is caught, give each registered exception
676 translator a chance to translate it to a Python exception
677 in reverse order of registration.
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200678
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400679 A translator may choose to do one of the following:
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200680
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400681 - catch the exception and call PyErr_SetString or PyErr_SetObject
682 to set a standard (or custom) Python exception, or
683 - do nothing and let the exception fall through to the next translator, or
684 - delegate translation to the next translator by throwing a new type of exception. */
685
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200686 auto last_exception = std::current_exception();
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500687 auto &registered_exception_translators = get_internals().registered_exception_translators;
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400688 for (auto& translator : registered_exception_translators) {
689 try {
690 translator(last_exception);
691 } catch (...) {
692 last_exception = std::current_exception();
693 continue;
694 }
695 return nullptr;
696 }
697 PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100698 return nullptr;
699 }
700
Dean Moldovan2b4477e2017-09-09 20:21:34 +0200701 auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
702 if (msg.find("std::") != std::string::npos) {
703 msg += "\n\n"
704 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
705 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
706 "conversions are optional and require extra headers to be included\n"
707 "when compiling your pybind11 module.";
708 }
709 };
710
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100711 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
Wenzel Jakob382484a2016-09-10 15:28:37 +0900712 if (overloads->is_operator)
713 return handle(Py_NotImplemented).inc_ref().ptr();
714
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900715 std::string msg = std::string(overloads->name) + "(): incompatible " +
716 std::string(overloads->is_constructor ? "constructor" : "function") +
717 " arguments. The following argument types are supported:\n";
718
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100719 int ctr = 0;
oremanje7761e32018-09-25 14:55:18 -0700720 for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100721 msg += " "+ std::to_string(++ctr) + ". ";
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400722
723 bool wrote_sig = false;
724 if (overloads->is_constructor) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200725 // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400726 std::string sig = it2->signature;
Dean Moldovanecced6c2016-07-31 20:03:18 +0200727 size_t start = sig.find('(') + 7; // skip "(self: "
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400728 if (start < sig.size()) {
729 // End at the , for the next argument
730 size_t end = sig.find(", "), next = end + 2;
731 size_t ret = sig.rfind(" -> ");
732 // Or the ), if there is no comma:
733 if (end >= sig.size()) next = end = sig.find(')');
734 if (start < end && next < sig.size()) {
735 msg.append(sig, start, end - start);
736 msg += '(';
737 msg.append(sig, next, ret - next);
738 wrote_sig = true;
739 }
740 }
741 }
742 if (!wrote_sig) msg += it2->signature;
743
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100744 msg += "\n";
745 }
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900746 msg += "\nInvoked with: ";
Jason Rhinelander2686da82017-01-21 23:42:14 -0500747 auto args_ = reinterpret_borrow<tuple>(args_in);
Jason Rhinelander231e1672017-02-23 21:04:46 -0500748 bool some_args = false;
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200749 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
Jason Rhinelander231e1672017-02-23 21:04:46 -0500750 if (!some_args) some_args = true;
751 else msg += ", ";
Jason Rhinelander7146d622016-11-22 05:28:40 -0500752 msg += pybind11::repr(args_[ti]);
Andreas Bergmeier16d43942016-05-24 09:19:35 +0200753 }
Jason Rhinelander231e1672017-02-23 21:04:46 -0500754 if (kwargs_in) {
755 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
756 if (kwargs.size() > 0) {
757 if (some_args) msg += "; ";
758 msg += "kwargs: ";
759 bool first = true;
760 for (auto kwarg : kwargs) {
761 if (first) first = false;
762 else msg += ", ";
763 msg += pybind11::str("{}={!r}").format(kwarg.first, kwarg.second);
764 }
765 }
766 }
767
Dean Moldovan2b4477e2017-09-09 20:21:34 +0200768 append_note_if_missing_header_is_suspected(msg);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100769 PyErr_SetString(PyExc_TypeError, msg.c_str());
770 return nullptr;
771 } else if (!result) {
772 std::string msg = "Unable to convert function return value to a "
773 "Python type! The signature was\n\t";
774 msg += it->signature;
Dean Moldovan2b4477e2017-09-09 20:21:34 +0200775 append_note_if_missing_header_is_suspected(msg);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100776 PyErr_SetString(PyExc_TypeError, msg.c_str());
777 return nullptr;
778 } else {
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200779 if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
Jason Rhinelander464d9892017-06-12 21:52:48 -0400780 auto *pi = reinterpret_cast<instance *>(parent.ptr());
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200781 self_value_and_holder.type->init_instance(pi, nullptr);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100782 }
783 return result.ptr();
784 }
785 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200786};
787
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100788/// Wrapper for Python extension modules
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200789class module : public object {
790public:
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200791 PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200792
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100793 /// Create a new top-level Python module with the given name and docstring
Jason Rhinelander12d76602016-10-16 16:27:42 -0400794 explicit module(const char *name, const char *doc = nullptr) {
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100795 if (!options::show_user_defined_docstrings()) doc = nullptr;
Wenzel Jakob57082212015-09-04 23:42:12 +0200796#if PY_MAJOR_VERSION >= 3
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200797 PyModuleDef *def = new PyModuleDef();
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500798 std::memset(def, 0, sizeof(PyModuleDef));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200799 def->m_name = name;
800 def->m_doc = doc;
801 def->m_size = -1;
802 Py_INCREF(def);
803 m_ptr = PyModule_Create(def);
Wenzel Jakob57082212015-09-04 23:42:12 +0200804#else
805 m_ptr = Py_InitModule3(name, nullptr, doc);
806#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200807 if (m_ptr == nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100808 pybind11_fail("Internal error in module::module()");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200809 inc_ref();
810 }
811
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100812 /** \rst
813 Create Python binding for a new function within the module scope. ``Func``
814 can be a plain C++ function, a function pointer, or a lambda function. For
815 details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
816 \endrst */
Wenzel Jakob71867832015-07-29 17:43:52 +0200817 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100818 module &def(const char *name_, Func &&f, const Extra& ... extra) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200819 cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
820 sibling(getattr(*this, name_, none())), extra...);
Jason Rhinelander6873c202016-10-24 21:58:22 -0400821 // NB: allow overwriting here because cpp_function sets up a chain with the intention of
822 // overwriting (and has already checked internally that it isn't overwriting non-functions).
823 add_object(name_, func, true /* overwrite */);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200824 return *this;
825 }
826
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100827 /** \rst
828 Create and return a new Python submodule with the given name and docstring.
829 This also works recursively, i.e.
830
831 .. code-block:: cpp
832
833 py::module m("example", "pybind11 example plugin");
834 py::module m2 = m.def_submodule("sub", "A submodule of 'example'");
835 py::module m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
836 \endrst */
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200837 module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200838 std::string full_name = std::string(PyModule_GetName(m_ptr))
839 + std::string(".") + std::string(name);
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200840 auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100841 if (doc && options::show_user_defined_docstrings())
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200842 result.attr("__doc__") = pybind11::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200843 attr(name) = result;
844 return result;
845 }
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200846
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100847 /// Import and return a module or throws `error_already_set`.
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200848 static module import(const char *name) {
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100849 PyObject *obj = PyImport_ImportModule(name);
850 if (!obj)
esquires67a68f12016-12-01 05:35:34 -0500851 throw error_already_set();
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200852 return reinterpret_steal<module>(obj);
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200853 }
Jason Rhinelander6873c202016-10-24 21:58:22 -0400854
Gunnar Läthénc64e6b12017-09-12 08:05:05 +0200855 /// Reload the module or throws `error_already_set`.
856 void reload() {
857 PyObject *obj = PyImport_ReloadModule(ptr());
858 if (!obj)
859 throw error_already_set();
860 *this = reinterpret_steal<module>(obj);
861 }
862
Jason Rhinelander6873c202016-10-24 21:58:22 -0400863 // Adds an object to the module using the given name. Throws if an object with the given name
864 // already exists.
865 //
866 // overwrite should almost always be false: attempting to overwrite objects that pybind11 has
867 // established will, in most cases, break things.
Wenzel Jakobaa1b3162017-03-30 11:59:32 +0200868 PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
Jason Rhinelander6873c202016-10-24 21:58:22 -0400869 if (!overwrite && hasattr(*this, name))
870 pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
871 std::string(name) + "\"");
872
Wenzel Jakobaa1b3162017-03-30 11:59:32 +0200873 PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
Jason Rhinelander6873c202016-10-24 21:58:22 -0400874 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200875};
876
Dean Moldovan22c413b2017-03-30 00:20:42 +0200877/// \ingroup python_builtins
Dean Moldovan1d3c4bc2017-06-06 17:05:19 +0200878/// Return a dictionary representing the global variables in the current execution frame,
879/// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
880inline dict globals() {
881 PyObject *p = PyEval_GetGlobals();
882 return reinterpret_borrow<dict>(p ? p : module::import("__main__").attr("__dict__").ptr());
883}
Dean Moldovan22c413b2017-03-30 00:20:42 +0200884
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200885NAMESPACE_BEGIN(detail)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100886/// Generic support for creating new Python heap types
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100887class generic_type : public object {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400888 template <typename...> friend class class_;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200889public:
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100890 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100891protected:
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100892 void initialize(const type_record &rec) {
893 if (rec.scope && hasattr(rec.scope, rec.name))
894 pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
895 "\": an object with that name is already defined");
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200896
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400897 if (rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100898 pybind11_fail("generic_type: type \"" + std::string(rec.name) +
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200899 "\" is already registered!");
900
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100901 m_ptr = make_new_python_type(rec);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200902
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100903 /* Register supplemental type information in C++ dict */
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100904 auto *tinfo = new detail::type_info();
905 tinfo->type = (PyTypeObject *) m_ptr;
Jason Rhinelander1f8a1002017-04-21 19:01:30 -0400906 tinfo->cpptype = rec.type;
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100907 tinfo->type_size = rec.type_size;
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +0100908 tinfo->type_align = rec.type_align;
Dean Moldovan0d765f42017-03-21 01:15:20 +0100909 tinfo->operator_new = rec.operator_new;
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500910 tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
Jason Rhinelander353615f2017-07-25 00:53:23 -0400911 tinfo->init_instance = rec.init_instance;
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100912 tinfo->dealloc = rec.dealloc;
Jason Rhinelander1f8a1002017-04-21 19:01:30 -0400913 tinfo->simple_type = true;
914 tinfo->simple_ancestors = true;
Jason Rhinelander7437c692017-07-28 22:03:44 -0400915 tinfo->default_holder = rec.default_holder;
916 tinfo->module_local = rec.module_local;
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100917
918 auto &internals = get_internals();
919 auto tindex = std::type_index(*rec.type);
Ivan Smirnova6e6a8b2016-10-23 15:27:13 +0100920 tinfo->direct_conversions = &internals.direct_conversions[tindex];
Jason Rhinelander7437c692017-07-28 22:03:44 -0400921 if (rec.module_local)
922 registered_local_types_cpp()[tindex] = tinfo;
923 else
924 internals.registered_types_cpp[tindex] = tinfo;
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500925 internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo };
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100926
Jason Rhinelander1f8a1002017-04-21 19:01:30 -0400927 if (rec.bases.size() > 1 || rec.multiple_inheritance) {
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100928 mark_parents_nonsimple(tinfo->type);
Jason Rhinelander1f8a1002017-04-21 19:01:30 -0400929 tinfo->simple_ancestors = false;
930 }
931 else if (rec.bases.size() == 1) {
932 auto parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
933 tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
934 }
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400935
936 if (rec.module_local) {
937 // Stash the local typeinfo and loader so that external modules can access it.
938 tinfo->module_local_load = &type_caster_generic::local_load;
Dean Moldovan96997a42017-08-20 17:14:09 +0200939 setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400940 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200941 }
942
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900943 /// Helper function which tags all parents of a type using mult. inheritance
944 void mark_parents_nonsimple(PyTypeObject *value) {
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200945 auto t = reinterpret_borrow<tuple>(value->tp_bases);
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900946 for (handle h : t) {
947 auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
948 if (tinfo2)
949 tinfo2->simple_type = false;
950 mark_parents_nonsimple((PyTypeObject *) h.ptr());
951 }
952 }
953
Wenzel Jakob43398a82015-07-28 16:12:20 +0200954 void install_buffer_funcs(
955 buffer_info *(*get_buffer)(PyObject *, void *),
956 void *get_buffer_data) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200957 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100958 auto tinfo = detail::get_type_info(&type->ht_type);
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100959
960 if (!type->ht_type.tp_as_buffer)
961 pybind11_fail(
962 "To be able to register buffer protocol support for the type '" +
963 std::string(tinfo->type->tp_name) +
964 "' the associated class<>(..) invocation must "
965 "include the pybind11::buffer_protocol() annotation!");
966
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100967 tinfo->get_buffer = get_buffer;
968 tinfo->get_buffer_data = get_buffer_data;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200969 }
970
Ted Drain0a0758c2017-11-07 08:35:27 -0800971 // rec_func must be set for either fget or fset.
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100972 void def_property_static_impl(const char *name,
973 handle fget, handle fset,
Ted Drain0a0758c2017-11-07 08:35:27 -0800974 detail::function_record *rec_func) {
975 const auto is_static = rec_func && !(rec_func->is_method && rec_func->scope);
976 const auto has_doc = rec_func && rec_func->doc && pybind11::options::show_user_defined_docstrings();
Dean Moldovanc91f8bd2017-02-13 18:11:24 +0100977 auto property = handle((PyObject *) (is_static ? get_internals().static_property_type
978 : &PyProperty_Type));
979 attr(name) = property(fget.ptr() ? fget : none(),
980 fset.ptr() ? fset : none(),
981 /*deleter*/none(),
Ted Drain0a0758c2017-11-07 08:35:27 -0800982 pybind11::str(has_doc ? rec_func->doc : ""));
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100983 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200984};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400985
Dean Moldovan0d765f42017-03-21 01:15:20 +0100986/// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
987template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator new))>>
988void set_operator_new(type_record *r) { r->operator_new = &T::operator new; }
989
990template <typename> void set_operator_new(...) { }
991
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400992template <typename T, typename SFINAE = void> struct has_operator_delete : std::false_type { };
993template <typename T> struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
994 : std::true_type { };
995template <typename T, typename SFINAE = void> struct has_operator_delete_size : std::false_type { };
996template <typename T> struct has_operator_delete_size<T, void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>>
997 : std::true_type { };
Dean Moldovan0d765f42017-03-21 01:15:20 +0100998/// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
Jason Rhinelandera03408c2017-07-23 00:32:58 -0400999template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001000void call_operator_delete(T *p, size_t, size_t) { T::operator delete(p); }
Jason Rhinelandera03408c2017-07-23 00:32:58 -04001001template <typename T, enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> = 0>
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001002void call_operator_delete(T *p, size_t s, size_t) { T::operator delete(p, s); }
Dean Moldovan0d765f42017-03-21 01:15:20 +01001003
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001004inline void call_operator_delete(void *p, size_t s, size_t a) {
1005 (void)s; (void)a;
Jeremy Nimmer759221f2019-06-14 12:12:51 -04001006 #ifdef __cpp_aligned_new
1007 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1008 #ifdef __cpp_sized_deallocation
1009 ::operator delete(p, s, std::align_val_t(a));
1010 #else
1011 ::operator delete(p, std::align_val_t(a));
1012 #endif
1013 return;
1014 }
1015 #endif
1016 #ifdef __cpp_sized_deallocation
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001017 ::operator delete(p, s);
Jeremy Nimmer759221f2019-06-14 12:12:51 -04001018 #else
1019 ::operator delete(p);
1020 #endif
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001021}
Dean Moldovan0d765f42017-03-21 01:15:20 +01001022
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001023NAMESPACE_END(detail)
1024
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001025/// Given a pointer to a member function, cast it to its `Derived` version.
1026/// Forward everything else unchanged.
1027template <typename /*Derived*/, typename F>
1028auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) { return std::forward<F>(f); }
1029
1030template <typename Derived, typename Return, typename Class, typename... Args>
Jason Rhinelander76722922017-10-03 10:09:49 -03001031auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
1032 static_assert(detail::is_accessible_base_of<Class, Derived>::value,
1033 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1034 return pmf;
1035}
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001036
1037template <typename Derived, typename Return, typename Class, typename... Args>
Jason Rhinelander76722922017-10-03 10:09:49 -03001038auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
1039 static_assert(detail::is_accessible_base_of<Class, Derived>::value,
1040 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1041 return pmf;
1042}
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001043
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001044template <typename type_, typename... options>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001045class class_ : public detail::generic_type {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001046 template <typename T> using is_holder = detail::is_holder_type<type_, T>;
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001047 template <typename T> using is_subtype = detail::is_strict_base_of<type_, T>;
1048 template <typename T> using is_base = detail::is_strict_base_of<T, type_>;
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -05001049 // struct instead of using here to help MSVC:
1050 template <typename T> struct is_valid_class_option :
1051 detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001052
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001053public:
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001054 using type = type_;
Dean Moldovan82ece942017-03-29 11:55:18 +02001055 using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001056 constexpr static bool has_alias = !std::is_void<type_alias>::value;
Dean Moldovan82ece942017-03-29 11:55:18 +02001057 using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001058
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -05001059 static_assert(detail::all_of<is_valid_class_option<options>...>::value,
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001060 "Unknown/invalid class_ template parameters provided");
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001061
Jason Rhinelander42e5ddc2017-06-12 21:48:36 -04001062 static_assert(!has_alias || std::is_polymorphic<type>::value,
1063 "Cannot use an alias class with a non-polymorphic type");
1064
Dean Moldovanc7ac16b2016-10-28 03:08:15 +02001065 PYBIND11_OBJECT(class_, generic_type, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001066
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001067 template <typename... Extra>
1068 class_(handle scope, const char *name, const Extra &... extra) {
Jason Rhinelanderb9616262017-03-16 20:10:48 -03001069 using namespace detail;
1070
1071 // MI can only be specified via class_ template options, not constructor parameters
1072 static_assert(
1073 none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
1074 ( constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
1075 constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
1076 none_of<std::is_same<multiple_inheritance, Extra>...>::value), // no multiple_inheritance attr
1077 "Error: multiple inheritance bases must be specified via class_ template options");
1078
1079 type_record record;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001080 record.scope = scope;
1081 record.name = name;
1082 record.type = &typeid(type);
Jason Rhinelanderb9616262017-03-16 20:10:48 -03001083 record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001084 record.type_align = alignof(conditional_t<has_alias, type_alias, type>&);
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001085 record.holder_size = sizeof(holder_type);
Jason Rhinelander353615f2017-07-25 00:53:23 -04001086 record.init_instance = init_instance;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001087 record.dealloc = dealloc;
Trevor Laughlin63c2a972018-11-11 13:36:55 -05001088 record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001089
Dean Moldovan0d765f42017-03-21 01:15:20 +01001090 set_operator_new<type>(&record);
1091
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001092 /* Register base classes specified via template arguments to class_, if any */
Jason Rhinelander926e2cf2017-03-25 22:41:06 -03001093 PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
Jason Rhinelander6b52c832016-09-06 12:27:00 -04001094
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001095 /* Process optional arguments, if any */
Jason Rhinelanderb9616262017-03-16 20:10:48 -03001096 process_attributes<Extra...>::init(extra..., &record);
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001097
Jason Rhinelanderb9616262017-03-16 20:10:48 -03001098 generic_type::initialize(record);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001099
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001100 if (has_alias) {
Jason Rhinelander7437c692017-07-28 22:03:44 -04001101 auto &instances = record.module_local ? registered_local_types_cpp() : get_internals().registered_types_cpp;
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001102 instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
1103 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001104 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001105
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +09001106 template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001107 static void add_base(detail::type_record &rec) {
Jason Rhinelander21966962017-06-21 13:38:10 -04001108 rec.add_base(typeid(Base), [](void *src) -> void * {
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001109 return static_cast<Base *>(reinterpret_cast<type *>(src));
1110 });
1111 }
1112
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +09001113 template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001114 static void add_base(detail::type_record &) { }
1115
Wenzel Jakob71867832015-07-29 17:43:52 +02001116 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001117 class_ &def(const char *name_, Func&& f, const Extra&... extra) {
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001118 cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), name(name_), is_method(*this),
Dean Moldovan865e4302016-09-21 01:06:32 +02001119 sibling(getattr(*this, name_, none())), extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +02001120 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001121 return *this;
1122 }
1123
Wenzel Jakob71867832015-07-29 17:43:52 +02001124 template <typename Func, typename... Extra> class_ &
Jason Rhinelander139a0822017-03-12 17:59:07 -03001125 def_static(const char *name_, Func &&f, const Extra&... extra) {
1126 static_assert(!std::is_member_function_pointer<Func>::value,
1127 "def_static(...) called with a non-static member function pointer");
Dean Moldovan865e4302016-09-21 01:06:32 +02001128 cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
1129 sibling(getattr(*this, name_, none())), extra...);
Yannick Jadould23c8212019-06-11 10:59:57 +02001130 attr(cf.name()) = staticmethod(cf);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001131 return *this;
1132 }
1133
Wenzel Jakob71867832015-07-29 17:43:52 +02001134 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001135 class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001136 op.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001137 return *this;
1138 }
1139
Wenzel Jakob71867832015-07-29 17:43:52 +02001140 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001141 class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001142 op.execute_cast(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001143 return *this;
1144 }
1145
Wenzel Jakob71867832015-07-29 17:43:52 +02001146 template <typename... Args, typename... Extra>
Jason Rhinelanderc4e18002017-08-17 00:01:42 -04001147 class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001148 init.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001149 return *this;
1150 }
1151
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001152 template <typename... Args, typename... Extra>
Jason Rhinelanderc4e18002017-08-17 00:01:42 -04001153 class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001154 init.execute(*this, extra...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001155 return *this;
1156 }
1157
Jason Rhinelander464d9892017-06-12 21:52:48 -04001158 template <typename... Args, typename... Extra>
1159 class_ &def(detail::initimpl::factory<Args...> &&init, const Extra&... extra) {
1160 std::move(init).execute(*this, extra...);
1161 return *this;
1162 }
1163
Dean Moldovan1e5a7da2017-08-24 01:53:15 +02001164 template <typename... Args, typename... Extra>
1165 class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
1166 std::move(pf).execute(*this, extra...);
1167 return *this;
1168 }
1169
Wenzel Jakob71867832015-07-29 17:43:52 +02001170 template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob43398a82015-07-28 16:12:20 +02001171 struct capture { Func func; };
1172 capture *ptr = new capture { std::forward<Func>(func) };
1173 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Dean Moldovan5f07fac2017-01-03 11:52:05 +01001174 detail::make_caster<type> caster;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001175 if (!caster.load(obj, false))
1176 return nullptr;
Wenzel Jakob43398a82015-07-28 16:12:20 +02001177 return new buffer_info(((capture *) ptr)->func(caster));
1178 }, ptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001179 return *this;
1180 }
1181
Bruce Merryfe0cf8b2017-05-17 10:52:33 +02001182 template <typename Return, typename Class, typename... Args>
1183 class_ &def_buffer(Return (Class::*func)(Args...)) {
1184 return def_buffer([func] (type &obj) { return (obj.*func)(); });
1185 }
1186
1187 template <typename Return, typename Class, typename... Args>
1188 class_ &def_buffer(Return (Class::*func)(Args...) const) {
1189 return def_buffer([func] (const type &obj) { return (obj.*func)(); });
1190 }
1191
Wenzel Jakob71867832015-07-29 17:43:52 +02001192 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001193 class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
Roland Dreier1aa8dd12019-06-11 13:25:12 -07001194 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value, "def_readwrite() requires a class member (or base class member)");
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001195 cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this)),
1196 fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
Wenzel Jakob0b489582016-03-25 16:13:10 +01001197 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001198 return *this;
1199 }
1200
Wenzel Jakob71867832015-07-29 17:43:52 +02001201 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001202 class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
Roland Dreier1aa8dd12019-06-11 13:25:12 -07001203 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value, "def_readonly() requires a class member (or base class member)");
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001204 cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this));
Wenzel Jakob0b489582016-03-25 16:13:10 +01001205 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001206 return *this;
1207 }
1208
Wenzel Jakob71867832015-07-29 17:43:52 +02001209 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001210 class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001211 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
1212 fset([pm](object, const D &value) { *pm = value; }, scope(*this));
1213 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001214 return *this;
1215 }
1216
Wenzel Jakob71867832015-07-29 17:43:52 +02001217 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001218 class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001219 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
1220 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001221 return *this;
1222 }
1223
Dean Moldovan03f627e2016-11-01 11:44:57 +01001224 /// Uses return_value_policy::reference_internal by default
1225 template <typename Getter, typename... Extra>
1226 class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001227 return def_property_readonly(name, cpp_function(method_adaptor<type>(fget)),
1228 return_value_policy::reference_internal, extra...);
Dean Moldovan03f627e2016-11-01 11:44:57 +01001229 }
1230
1231 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001232 template <typename... Extra>
1233 class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
Ted Drain0a0758c2017-11-07 08:35:27 -08001234 return def_property(name, fget, nullptr, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001235 }
1236
Dean Moldovan03f627e2016-11-01 11:44:57 +01001237 /// Uses return_value_policy::reference by default
1238 template <typename Getter, typename... Extra>
1239 class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
1240 return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...);
1241 }
1242
1243 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001244 template <typename... Extra>
1245 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
Ted Drain0a0758c2017-11-07 08:35:27 -08001246 return def_property_static(name, fget, nullptr, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001247 }
1248
Dean Moldovan03f627e2016-11-01 11:44:57 +01001249 /// Uses return_value_policy::reference_internal by default
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001250 template <typename Getter, typename Setter, typename... Extra>
1251 class_ &def_property(const char *name, const Getter &fget, const Setter &fset, const Extra& ...extra) {
1252 return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
1253 }
Dean Moldovan03f627e2016-11-01 11:44:57 +01001254 template <typename Getter, typename... Extra>
1255 class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001256 return def_property(name, cpp_function(method_adaptor<type>(fget)), fset,
1257 return_value_policy::reference_internal, extra...);
Dean Moldovan03f627e2016-11-01 11:44:57 +01001258 }
1259
1260 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001261 template <typename... Extra>
1262 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001263 return def_property_static(name, fget, fset, is_method(*this), extra...);
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001264 }
1265
Dean Moldovan03f627e2016-11-01 11:44:57 +01001266 /// Uses return_value_policy::reference by default
1267 template <typename Getter, typename... Extra>
1268 class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1269 return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1270 }
1271
1272 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001273 template <typename... Extra>
1274 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
Jeff VanOss77ef03d2019-06-11 08:25:35 -04001275 static_assert( 0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
1276 "Argument annotations are not allowed for properties");
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001277 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
Ted Drain0a0758c2017-11-07 08:35:27 -08001278 auto *rec_active = rec_fget;
1279 if (rec_fget) {
1280 char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
1281 detail::process_attributes<Extra...>::init(extra..., rec_fget);
1282 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1283 free(doc_prev);
1284 rec_fget->doc = strdup(rec_fget->doc);
1285 }
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001286 }
1287 if (rec_fset) {
Ted Drain0a0758c2017-11-07 08:35:27 -08001288 char *doc_prev = rec_fset->doc;
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001289 detail::process_attributes<Extra...>::init(extra..., rec_fset);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001290 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1291 free(doc_prev);
1292 rec_fset->doc = strdup(rec_fset->doc);
1293 }
Ted Drain0a0758c2017-11-07 08:35:27 -08001294 if (! rec_active) rec_active = rec_fset;
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001295 }
Ted Drain0a0758c2017-11-07 08:35:27 -08001296 def_property_static_impl(name, fget, fset, rec_active);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001297 return *this;
1298 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001299
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001300private:
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001301 /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1302 template <typename T>
Jason Rhinelander353615f2017-07-25 00:53:23 -04001303 static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001304 const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001305 try {
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001306 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1307 v_h.value_ptr<type>()->shared_from_this());
Jason Rhinelanderb8ac4382017-05-19 13:34:55 -04001308 if (sh) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001309 new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001310 v_h.set_holder_constructed();
Dean Moldovanab90ec62016-12-07 02:36:44 +01001311 }
Jason Rhinelanderb8ac4382017-05-19 13:34:55 -04001312 } catch (const std::bad_weak_ptr &) {}
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001313
1314 if (!v_h.holder_constructed() && inst->owned) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001315 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001316 v_h.set_holder_constructed();
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001317 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001318 }
1319
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001320 static void init_holder_from_existing(const detail::value_and_holder &v_h,
1321 const holder_type *holder_ptr, std::true_type /*is_copy_constructible*/) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001322 new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001323 }
1324
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001325 static void init_holder_from_existing(const detail::value_and_holder &v_h,
1326 const holder_type *holder_ptr, std::false_type /*is_copy_constructible*/) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001327 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 +01001328 }
1329
1330 /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
Jason Rhinelander353615f2017-07-25 00:53:23 -04001331 static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001332 const holder_type *holder_ptr, const void * /* dummy -- not enable_shared_from_this<T>) */) {
Dean Moldovanec009a72017-01-31 17:05:44 +01001333 if (holder_ptr) {
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001334 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1335 v_h.set_holder_constructed();
Dean Moldovanec009a72017-01-31 17:05:44 +01001336 } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001337 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001338 v_h.set_holder_constructed();
Jason Rhinelanderc07ec312016-11-06 13:12:48 -05001339 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001340 }
1341
Jason Rhinelander353615f2017-07-25 00:53:23 -04001342 /// Performs instance initialization including constructing a holder and registering the known
1343 /// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes an
1344 /// optional pointer to an existing holder to use; if not specified and the instance is
1345 /// `.owned`, a new holder will be constructed to manage the value pointer.
1346 static void init_instance(detail::instance *inst, const void *holder_ptr) {
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001347 auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
Jason Rhinelandercca20a72017-07-29 03:56:01 -04001348 if (!v_h.instance_registered()) {
1349 register_instance(inst, v_h.value_ptr(), v_h.type);
1350 v_h.set_instance_registered();
1351 }
Jason Rhinelander353615f2017-07-25 00:53:23 -04001352 init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001353 }
1354
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001355 /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
Jason Rhinelander464d9892017-06-12 21:52:48 -04001356 static void dealloc(detail::value_and_holder &v_h) {
1357 if (v_h.holder_constructed()) {
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001358 v_h.holder<holder_type>().~holder_type();
Jason Rhinelander464d9892017-06-12 21:52:48 -04001359 v_h.set_holder_constructed(false);
1360 }
1361 else {
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001362 detail::call_operator_delete(v_h.value_ptr<type>(),
1363 v_h.type->type_size,
1364 v_h.type->type_align
1365 );
Jason Rhinelander464d9892017-06-12 21:52:48 -04001366 }
1367 v_h.value_ptr() = nullptr;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001368 }
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001369
1370 static detail::function_record *get_function_record(handle h) {
1371 h = detail::get_function(h);
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001372 return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
Dean Moldovanc7ac16b2016-10-28 03:08:15 +02001373 : nullptr;
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001374 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001375};
1376
Dean Moldovan68986792017-08-30 23:40:55 +02001377/// Binds an existing constructor taking arguments Args...
1378template <typename... Args> detail::initimpl::constructor<Args...> init() { return {}; }
1379/// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
1380/// when not inheriting on the Python side).
1381template <typename... Args> detail::initimpl::alias_constructor<Args...> init_alias() { return {}; }
1382
1383/// Binds a factory function as a constructor
1384template <typename Func, typename Ret = detail::initimpl::factory<Func>>
1385Ret init(Func &&f) { return {std::forward<Func>(f)}; }
1386
1387/// Dual-argument factory function: the first function is called when no alias is needed, the second
1388/// when an alias is needed (i.e. due to python-side inheritance). Arguments must be identical.
1389template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1390Ret init(CFunc &&c, AFunc &&a) {
1391 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1392}
1393
1394/// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
1395/// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
1396template <typename GetState, typename SetState>
1397detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
1398 return {std::forward<GetState>(g), std::forward<SetState>(s)};
Marcin Wojdyrfbab29c2017-09-04 18:37:16 +01001399}
Dean Moldovan68986792017-08-30 23:40:55 +02001400
Wenzel Jakobf4245182018-09-01 01:20:24 +02001401NAMESPACE_BEGIN(detail)
1402struct enum_base {
1403 enum_base(handle base, handle parent) : m_base(base), m_parent(parent) { }
1404
1405 PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
1406 m_base.attr("__entries") = dict();
1407 auto property = handle((PyObject *) &PyProperty_Type);
1408 auto static_property = handle((PyObject *) get_internals().static_property_type);
1409
1410 m_base.attr("__repr__") = cpp_function(
1411 [](handle arg) -> str {
1412 handle type = arg.get_type();
1413 object type_name = type.attr("__name__");
1414 dict entries = type.attr("__entries");
1415 for (const auto &kv : entries) {
1416 object other = kv.second[int_(0)];
1417 if (other.equal(arg))
1418 return pybind11::str("{}.{}").format(type_name, kv.first);
1419 }
1420 return pybind11::str("{}.???").format(type_name);
1421 }, is_method(m_base)
1422 );
1423
1424 m_base.attr("name") = property(cpp_function(
1425 [](handle arg) -> str {
1426 dict entries = arg.get_type().attr("__entries");
1427 for (const auto &kv : entries) {
1428 if (handle(kv.second[int_(0)]).equal(arg))
1429 return pybind11::str(kv.first);
1430 }
1431 return "???";
1432 }, is_method(m_base)
1433 ));
1434
1435 m_base.attr("__doc__") = static_property(cpp_function(
1436 [](handle arg) -> std::string {
1437 std::string docstring;
1438 dict entries = arg.attr("__entries");
1439 if (((PyTypeObject *) arg.ptr())->tp_doc)
1440 docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) + "\n\n";
1441 docstring += "Members:";
1442 for (const auto &kv : entries) {
1443 auto key = std::string(pybind11::str(kv.first));
1444 auto comment = kv.second[int_(1)];
1445 docstring += "\n\n " + key;
1446 if (!comment.is_none())
1447 docstring += " : " + (std::string) pybind11::str(comment);
1448 }
1449 return docstring;
1450 }
1451 ), none(), none(), "");
1452
1453 m_base.attr("__members__") = static_property(cpp_function(
1454 [](handle arg) -> dict {
1455 dict entries = arg.attr("__entries"), m;
1456 for (const auto &kv : entries)
1457 m[kv.first] = kv.second[int_(0)];
1458 return m;
1459 }), none(), none(), ""
1460 );
1461
Tarcísio Fischer54eb8192018-10-24 06:18:58 -03001462 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
Wenzel Jakobf4245182018-09-01 01:20:24 +02001463 m_base.attr(op) = cpp_function( \
1464 [](object a, object b) { \
1465 if (!a.get_type().is(b.get_type())) \
Tarcísio Fischer54eb8192018-10-24 06:18:58 -03001466 strict_behavior; \
Wenzel Jakobf4245182018-09-01 01:20:24 +02001467 return expr; \
1468 }, \
1469 is_method(m_base))
1470
1471 #define PYBIND11_ENUM_OP_CONV(op, expr) \
1472 m_base.attr(op) = cpp_function( \
1473 [](object a_, object b_) { \
1474 int_ a(a_), b(b_); \
1475 return expr; \
1476 }, \
1477 is_method(m_base))
1478
Sergei Izmailov09f08292019-09-19 19:23:27 +03001479 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
1480 m_base.attr(op) = cpp_function( \
1481 [](object a_, object b) { \
1482 int_ a(a_); \
1483 return expr; \
1484 }, \
1485 is_method(m_base))
1486
Wenzel Jakobf4245182018-09-01 01:20:24 +02001487 if (is_convertible) {
Sergei Izmailov09f08292019-09-19 19:23:27 +03001488 PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
1489 PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
Wenzel Jakobf4245182018-09-01 01:20:24 +02001490
1491 if (is_arithmetic) {
1492 PYBIND11_ENUM_OP_CONV("__lt__", a < b);
1493 PYBIND11_ENUM_OP_CONV("__gt__", a > b);
1494 PYBIND11_ENUM_OP_CONV("__le__", a <= b);
1495 PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
1496 PYBIND11_ENUM_OP_CONV("__and__", a & b);
1497 PYBIND11_ENUM_OP_CONV("__rand__", a & b);
1498 PYBIND11_ENUM_OP_CONV("__or__", a | b);
1499 PYBIND11_ENUM_OP_CONV("__ror__", a | b);
1500 PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
1501 PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
Lori A. Burnsf6c4c102019-09-04 16:16:21 -04001502 m_base.attr("__invert__") = cpp_function(
1503 [](object arg) { return ~(int_(arg)); }, is_method(m_base));
Wenzel Jakobf4245182018-09-01 01:20:24 +02001504 }
1505 } else {
Tarcísio Fischer54eb8192018-10-24 06:18:58 -03001506 PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
1507 PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
Wenzel Jakobf4245182018-09-01 01:20:24 +02001508
1509 if (is_arithmetic) {
Michał Wawrzyniec Urbańczyk978d4392018-11-03 13:20:08 +01001510 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
1511 PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
1512 PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
1513 PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
1514 PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
1515 #undef PYBIND11_THROW
Wenzel Jakobf4245182018-09-01 01:20:24 +02001516 }
1517 }
1518
Sergei Izmailov09f08292019-09-19 19:23:27 +03001519 #undef PYBIND11_ENUM_OP_CONV_LHS
Wenzel Jakobf4245182018-09-01 01:20:24 +02001520 #undef PYBIND11_ENUM_OP_CONV
1521 #undef PYBIND11_ENUM_OP_STRICT
1522
1523 object getstate = cpp_function(
1524 [](object arg) { return int_(arg); }, is_method(m_base));
1525
1526 m_base.attr("__getstate__") = getstate;
1527 m_base.attr("__hash__") = getstate;
1528 }
1529
1530 PYBIND11_NOINLINE void value(char const* name_, object value, const char *doc = nullptr) {
1531 dict entries = m_base.attr("__entries");
1532 str name(name_);
1533 if (entries.contains(name)) {
1534 std::string type_name = (std::string) str(m_base.attr("__name__"));
1535 throw value_error(type_name + ": element \"" + std::string(name_) + "\" already exists!");
1536 }
1537
1538 entries[name] = std::make_pair(value, doc);
1539 m_base.attr(name) = value;
1540 }
1541
1542 PYBIND11_NOINLINE void export_values() {
1543 dict entries = m_base.attr("__entries");
1544 for (const auto &kv : entries)
1545 m_parent.attr(kv.first) = kv.second[int_(0)];
1546 }
1547
1548 handle m_base;
1549 handle m_parent;
1550};
1551
1552NAMESPACE_END(detail)
1553
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001554/// Binds C++ enumerations and enumeration classes to Python
1555template <typename Type> class enum_ : public class_<Type> {
1556public:
Wenzel Jakobc8e9f3c2018-09-14 12:07:47 +02001557 using Base = class_<Type>;
1558 using Base::def;
1559 using Base::attr;
1560 using Base::def_property_readonly;
1561 using Base::def_property_readonly_static;
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001562 using Scalar = typename std::underlying_type<Type>::type;
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001563
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001564 template <typename... Extra>
1565 enum_(const handle &scope, const char *name, const Extra&... extra)
Wenzel Jakobf4245182018-09-01 01:20:24 +02001566 : class_<Type>(scope, name, extra...), m_base(*this, scope) {
Dean Moldovan82ece942017-03-29 11:55:18 +02001567 constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
Wenzel Jakobf4245182018-09-01 01:20:24 +02001568 constexpr bool is_convertible = std::is_convertible<Type, Scalar>::value;
1569 m_base.init(is_arithmetic, is_convertible);
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001570
Dean Moldovan68986792017-08-30 23:40:55 +02001571 def(init([](Scalar i) { return static_cast<Type>(i); }));
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001572 def("__int__", [](Type value) { return (Scalar) value; });
Wenzel Jakobe6fd2cd2017-04-28 14:46:52 +02001573 #if PY_MAJOR_VERSION < 3
1574 def("__long__", [](Type value) { return (Scalar) value; });
1575 #endif
Wenzel Jakobf3109d82019-09-21 18:09:35 +02001576 #if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 8)
Wenzel Jakob31680e62019-09-20 11:06:10 +02001577 def("__index__", [](Type value) { return (Scalar) value; });
1578 #endif
1579
Wenzel Jakobc8e9f3c2018-09-14 12:07:47 +02001580 cpp_function setstate(
1581 [](Type &value, Scalar arg) { value = static_cast<Type>(arg); },
1582 is_method(*this));
1583 attr("__setstate__") = setstate;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001584 }
1585
1586 /// Export enumeration entries into the parent scope
Matthieu Becaf936e12017-03-03 08:45:50 -08001587 enum_& export_values() {
Wenzel Jakobf4245182018-09-01 01:20:24 +02001588 m_base.export_values();
Wenzel Jakobe916d842016-11-04 16:51:14 +01001589 return *this;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001590 }
1591
1592 /// Add an enumeration entry
Wenzel Jakob6d190362017-11-16 22:24:36 +01001593 enum_& value(char const* name, Type value, const char *doc = nullptr) {
Wenzel Jakobf4245182018-09-01 01:20:24 +02001594 m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001595 return *this;
1596 }
Matthieu Becaf936e12017-03-03 08:45:50 -08001597
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001598private:
Wenzel Jakobf4245182018-09-01 01:20:24 +02001599 detail::enum_base m_base;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001600};
1601
1602NAMESPACE_BEGIN(detail)
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001603
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001604
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001605inline void keep_alive_impl(handle nurse, handle patient) {
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001606 if (!nurse || !patient)
Wenzel Jakob678d7872016-01-17 22:36:41 +01001607 pybind11_fail("Could not activate keep_alive!");
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001608
Ivan Smirnov984c7622016-08-29 02:38:47 +01001609 if (patient.is_none() || nurse.is_none())
Glen Walkerf45bb582016-08-16 17:50:43 +12001610 return; /* Nothing to keep alive or nothing to be kept alive by */
Wenzel Jakob9b880ba2016-04-25 03:25:13 +02001611
Bruce Merry9d698f72017-06-24 14:58:42 +02001612 auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
1613 if (!tinfo.empty()) {
1614 /* It's a pybind-registered type, so we can store the patient in the
1615 * internal list. */
1616 add_patient(nurse.ptr(), patient.ptr());
1617 }
1618 else {
1619 /* Fall back to clever approach based on weak references taken from
1620 * Boost.Python. This is not used for pybind-registered types because
1621 * the objects can be destroyed out-of-order in a GC pass. */
1622 cpp_function disable_lifesupport(
1623 [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001624
Bruce Merry9d698f72017-06-24 14:58:42 +02001625 weakref wr(nurse, disable_lifesupport);
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001626
Bruce Merry9d698f72017-06-24 14:58:42 +02001627 patient.inc_ref(); /* reference patient and leak the weak reference */
1628 (void) wr.release();
1629 }
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001630}
1631
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -05001632PYBIND11_NOINLINE inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
Dean Moldovan7939f4b2017-09-04 13:49:19 +02001633 auto get_arg = [&](size_t n) {
1634 if (n == 0)
1635 return ret;
1636 else if (n == 1 && call.init_self)
1637 return call.init_self;
1638 else if (n <= call.args.size())
1639 return call.args[n - 1];
1640 return handle();
1641 };
1642
1643 keep_alive_impl(get_arg(Nurse), get_arg(Patient));
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001644}
1645
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001646inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type) {
1647 auto res = get_internals().registered_types_py
Jason Rhinelander12be4cd2017-07-29 03:53:45 -04001648#ifdef __cpp_lib_unordered_map_try_emplace
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001649 .try_emplace(type);
1650#else
1651 .emplace(type, std::vector<detail::type_info *>());
1652#endif
1653 if (res.second) {
1654 // New cache entry created; set up a weak reference to automatically remove it if the type
1655 // gets destroyed:
1656 weakref((PyObject *) type, cpp_function([type](handle wr) {
1657 get_internals().registered_types_py.erase(type);
1658 wr.dec_ref();
1659 })).release();
1660 }
1661
1662 return res;
1663}
1664
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001665template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001666struct iterator_state {
1667 Iterator it;
1668 Sentinel end;
Dean Moldovancaedf742017-06-09 16:49:04 +02001669 bool first_or_done;
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001670};
Wenzel Jakobb2825952016-04-13 23:33:00 +02001671
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001672NAMESPACE_END(detail)
1673
Jason Rhinelander3d591e82017-03-18 13:34:21 -03001674/// Makes a python iterator from a first and past-the-end C++ InputIterator.
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001675template <return_value_policy Policy = return_value_policy::reference_internal,
1676 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001677 typename Sentinel,
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001678 typename ValueType = decltype(*std::declval<Iterator>()),
1679 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001680iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001681 typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001682
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001683 if (!detail::get_type_info(typeid(state), false)) {
Jason Rhinelander7437c692017-07-28 22:03:44 -04001684 class_<state>(handle(), "iterator", pybind11::module_local())
Wenzel Jakobb2825952016-04-13 23:33:00 +02001685 .def("__iter__", [](state &s) -> state& { return s; })
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001686 .def("__next__", [](state &s) -> ValueType {
Dean Moldovancaedf742017-06-09 16:49:04 +02001687 if (!s.first_or_done)
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001688 ++s.it;
1689 else
Dean Moldovancaedf742017-06-09 16:49:04 +02001690 s.first_or_done = false;
1691 if (s.it == s.end) {
1692 s.first_or_done = true;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001693 throw stop_iteration();
Dean Moldovancaedf742017-06-09 16:49:04 +02001694 }
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001695 return *s.it;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001696 }, std::forward<Extra>(extra)..., Policy);
Wenzel Jakobb2825952016-04-13 23:33:00 +02001697 }
1698
Dean Moldovancaedf742017-06-09 16:49:04 +02001699 return cast(state{first, last, true});
Wenzel Jakobb2825952016-04-13 23:33:00 +02001700}
Wenzel Jakob146397e2016-09-06 13:06:31 +09001701
Jason Rhinelander3d591e82017-03-18 13:34:21 -03001702/// Makes an python iterator over the keys (`.first`) of a iterator over pairs from a
1703/// first and past-the-end InputIterator.
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001704template <return_value_policy Policy = return_value_policy::reference_internal,
1705 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001706 typename Sentinel,
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001707 typename KeyType = decltype((*std::declval<Iterator>()).first),
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001708 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001709iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001710 typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001711
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001712 if (!detail::get_type_info(typeid(state), false)) {
Jason Rhinelander7437c692017-07-28 22:03:44 -04001713 class_<state>(handle(), "iterator", pybind11::module_local())
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001714 .def("__iter__", [](state &s) -> state& { return s; })
1715 .def("__next__", [](state &s) -> KeyType {
Dean Moldovancaedf742017-06-09 16:49:04 +02001716 if (!s.first_or_done)
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001717 ++s.it;
1718 else
Dean Moldovancaedf742017-06-09 16:49:04 +02001719 s.first_or_done = false;
1720 if (s.it == s.end) {
1721 s.first_or_done = true;
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001722 throw stop_iteration();
Dean Moldovancaedf742017-06-09 16:49:04 +02001723 }
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001724 return (*s.it).first;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001725 }, std::forward<Extra>(extra)..., Policy);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001726 }
1727
Dean Moldovancaedf742017-06-09 16:49:04 +02001728 return cast(state{first, last, true});
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001729}
Wenzel Jakobb2825952016-04-13 23:33:00 +02001730
Jason Rhinelander3d591e82017-03-18 13:34:21 -03001731/// Makes an iterator over values of an stl container or other container supporting
1732/// `std::begin()`/`std::end()`
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001733template <return_value_policy Policy = return_value_policy::reference_internal,
1734 typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
1735 return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
Wenzel Jakobbf0c7dc2016-04-18 10:52:12 +02001736}
1737
Jason Rhinelander3d591e82017-03-18 13:34:21 -03001738/// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
1739/// `std::begin()`/`std::end()`
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001740template <return_value_policy Policy = return_value_policy::reference_internal,
1741 typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
1742 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001743}
1744
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001745template <typename InputType, typename OutputType> void implicitly_convertible() {
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +02001746 struct set_flag {
1747 bool &flag;
1748 set_flag(bool &flag) : flag(flag) { flag = true; }
1749 ~set_flag() { flag = false; }
1750 };
Wenzel Jakob2ac50442016-01-17 22:36:35 +01001751 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +02001752 static bool currently_used = false;
1753 if (currently_used) // implicit conversions are non-reentrant
1754 return nullptr;
1755 set_flag flag_helper(currently_used);
Dean Moldovan5f07fac2017-01-03 11:52:05 +01001756 if (!detail::make_caster<InputType>().load(obj, false))
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001757 return nullptr;
1758 tuple args(1);
1759 args[0] = obj;
1760 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1761 if (result == nullptr)
1762 PyErr_Clear();
1763 return result;
1764 };
Ivan Smirnov8f3e0452016-10-23 15:43:03 +01001765
1766 if (auto tinfo = detail::get_type_info(typeid(OutputType)))
1767 tinfo->implicit_conversions.push_back(implicit_caster);
1768 else
Wenzel Jakob678d7872016-01-17 22:36:41 +01001769 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001770}
1771
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001772template <typename ExceptionTranslator>
1773void register_exception_translator(ExceptionTranslator&& translator) {
1774 detail::get_internals().registered_exception_translators.push_front(
1775 std::forward<ExceptionTranslator>(translator));
1776}
1777
Jason Rhinelander37b23832017-05-22 12:06:16 -04001778/**
1779 * Wrapper to generate a new Python exception type.
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001780 *
1781 * This should only be used with PyErr_SetString for now.
1782 * It is not (yet) possible to use as a py::base.
1783 * Template type argument is reserved for future use.
1784 */
1785template <typename type>
1786class exception : public object {
1787public:
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001788 exception() = default;
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001789 exception(handle scope, const char *name, PyObject *base = PyExc_Exception) {
1790 std::string full_name = scope.attr("__name__").cast<std::string>() +
1791 std::string(".") + name;
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -05001792 m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base, NULL);
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001793 if (hasattr(scope, name))
1794 pybind11_fail("Error during initialization: multiple incompatible "
1795 "definitions with name \"" + std::string(name) + "\"");
1796 scope.attr(name) = *this;
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001797 }
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001798
1799 // Sets the current python exception to this exception object with the given message
1800 void operator()(const char *message) {
1801 PyErr_SetString(m_ptr, message);
1802 }
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001803};
1804
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001805NAMESPACE_BEGIN(detail)
1806// Returns a reference to a function-local static exception object used in the simple
1807// register_exception approach below. (It would be simpler to have the static local variable
1808// directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
1809template <typename CppException>
1810exception<CppException> &get_exception_object() { static exception<CppException> ex; return ex; }
1811NAMESPACE_END(detail)
1812
Jason Rhinelander37b23832017-05-22 12:06:16 -04001813/**
1814 * Registers a Python exception in `m` of the given `name` and installs an exception translator to
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001815 * translate the C++ exception to the created Python exception using the exceptions what() method.
1816 * This is intended for simple exception translations; for more complex translation, register the
1817 * exception object and translator directly.
1818 */
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001819template <typename CppException>
1820exception<CppException> &register_exception(handle scope,
1821 const char *name,
1822 PyObject *base = PyExc_Exception) {
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001823 auto &ex = detail::get_exception_object<CppException>();
1824 if (!ex) ex = exception<CppException>(scope, name, base);
1825
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001826 register_exception_translator([](std::exception_ptr p) {
1827 if (!p) return;
1828 try {
1829 std::rethrow_exception(p);
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001830 } catch (const CppException &e) {
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001831 detail::get_exception_object<CppException>()(e.what());
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001832 }
1833 });
1834 return ex;
1835}
1836
Dean Moldovan67990d92016-08-29 18:03:34 +02001837NAMESPACE_BEGIN(detail)
1838PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
1839 auto strings = tuple(args.size());
1840 for (size_t i = 0; i < args.size(); ++i) {
Dean Moldovane18bc022016-10-25 22:12:39 +02001841 strings[i] = str(args[i]);
Dean Moldovan67990d92016-08-29 18:03:34 +02001842 }
Dean Moldovan865e4302016-09-21 01:06:32 +02001843 auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
Dean Moldovan242b1462016-09-08 17:02:04 +02001844 auto line = sep.attr("join")(strings);
Dean Moldovan67990d92016-08-29 18:03:34 +02001845
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001846 object file;
1847 if (kwargs.contains("file")) {
1848 file = kwargs["file"].cast<object>();
1849 } else {
1850 try {
1851 file = module::import("sys").attr("stdout");
esquires67a68f12016-12-01 05:35:34 -05001852 } catch (const error_already_set &) {
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001853 /* If print() is called from code that is executed as
1854 part of garbage collection during interpreter shutdown,
1855 importing 'sys' can fail. Give up rather than crashing the
1856 interpreter in this case. */
1857 return;
1858 }
1859 }
1860
Dean Moldovan242b1462016-09-08 17:02:04 +02001861 auto write = file.attr("write");
Dean Moldovan67990d92016-08-29 18:03:34 +02001862 write(line);
Dean Moldovan865e4302016-09-21 01:06:32 +02001863 write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
Dean Moldovan67990d92016-08-29 18:03:34 +02001864
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001865 if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
Dean Moldovan242b1462016-09-08 17:02:04 +02001866 file.attr("flush")();
Dean Moldovan67990d92016-08-29 18:03:34 +02001867}
1868NAMESPACE_END(detail)
1869
1870template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1871void print(Args &&...args) {
1872 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
1873 detail::print(c.args(), c.kwargs());
1874}
1875
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001876#if defined(WITH_THREAD) && !defined(PYPY_VERSION)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001877
1878/* The functions below essentially reproduce the PyGILState_* API using a RAII
1879 * pattern, but there are a few important differences:
1880 *
1881 * 1. When acquiring the GIL from an non-main thread during the finalization
1882 * phase, the GILState API blindly terminates the calling thread, which
1883 * is often not what is wanted. This API does not do this.
1884 *
1885 * 2. The gil_scoped_release function can optionally cut the relationship
1886 * of a PyThreadState and its associated thread, which allows moving it to
1887 * another thread (this is a fairly rare/advanced use case).
1888 *
1889 * 3. The reference count of an acquired thread state can be controlled. This
1890 * can be handy to prevent cases where callbacks issued from an external
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001891 * thread would otherwise constantly construct and destroy thread state data
1892 * structures.
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001893 *
1894 * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
1895 * example which uses features 2 and 3 to migrate the Python thread of
1896 * execution to another thread (to run the event loop on the original thread,
1897 * in this case).
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001898 */
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001899
1900class gil_scoped_acquire {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001901public:
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001902 PYBIND11_NOINLINE gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001903 auto const &internals = detail::get_internals();
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001904 tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001905
1906 if (!tstate) {
Borja Zarcoe2b884c2018-12-01 08:47:40 -05001907 /* Check if the GIL was acquired using the PyGILState_* API instead (e.g. if
1908 calling from a Python thread). Since we use a different key, this ensures
1909 we don't create a new thread state and deadlock in PyEval_AcquireThread
1910 below. Note we don't save this state with internals.tstate, since we don't
1911 create it we would fail to clear it (its reference count should be > 0). */
1912 tstate = PyGILState_GetThisThreadState();
1913 }
1914
1915 if (!tstate) {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001916 tstate = PyThreadState_New(internals.istate);
1917 #if !defined(NDEBUG)
1918 if (!tstate)
1919 pybind11_fail("scoped_acquire: could not create thread state!");
1920 #endif
1921 tstate->gilstate_counter = 0;
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001922 PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001923 } else {
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001924 release = detail::get_thread_state_unchecked() != tstate;
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001925 }
1926
1927 if (release) {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001928 /* Work around an annoying assertion in PyThreadState_Swap */
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001929 #if defined(Py_DEBUG)
1930 PyInterpreterState *interp = tstate->interp;
1931 tstate->interp = nullptr;
1932 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001933 PyEval_AcquireThread(tstate);
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001934 #if defined(Py_DEBUG)
1935 tstate->interp = interp;
1936 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001937 }
1938
1939 inc_ref();
1940 }
1941
1942 void inc_ref() {
1943 ++tstate->gilstate_counter;
1944 }
1945
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001946 PYBIND11_NOINLINE void dec_ref() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001947 --tstate->gilstate_counter;
1948 #if !defined(NDEBUG)
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001949 if (detail::get_thread_state_unchecked() != tstate)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001950 pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
1951 if (tstate->gilstate_counter < 0)
1952 pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
1953 #endif
1954 if (tstate->gilstate_counter == 0) {
1955 #if !defined(NDEBUG)
1956 if (!release)
1957 pybind11_fail("scoped_acquire::dec_ref(): internal error!");
1958 #endif
1959 PyThreadState_Clear(tstate);
1960 PyThreadState_DeleteCurrent();
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001961 PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001962 release = false;
1963 }
1964 }
1965
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001966 PYBIND11_NOINLINE ~gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001967 dec_ref();
1968 if (release)
1969 PyEval_SaveThread();
1970 }
1971private:
1972 PyThreadState *tstate = nullptr;
1973 bool release = true;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001974};
1975
1976class gil_scoped_release {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001977public:
Jason Rhinelander12d76602016-10-16 16:27:42 -04001978 explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
Dean Moldovan2d6116b2017-06-20 23:50:51 +02001979 // `get_internals()` must be called here unconditionally in order to initialize
1980 // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
1981 // initialization race could occur as multiple threads try `gil_scoped_acquire`.
1982 const auto &internals = detail::get_internals();
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001983 tstate = PyEval_SaveThread();
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001984 if (disassoc) {
Dean Moldovan2d6116b2017-06-20 23:50:51 +02001985 auto key = internals.tstate;
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001986 PYBIND11_TLS_DELETE_VALUE(key);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001987 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001988 }
1989 ~gil_scoped_release() {
1990 if (!tstate)
1991 return;
1992 PyEval_RestoreThread(tstate);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001993 if (disassoc) {
Boris Schäling20ee9352016-05-28 12:26:18 +02001994 auto key = detail::get_internals().tstate;
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001995 PYBIND11_TLS_REPLACE_VALUE(key, tstate);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001996 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001997 }
1998private:
1999 PyThreadState *tstate;
2000 bool disassoc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02002001};
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002002#elif defined(PYPY_VERSION)
2003class gil_scoped_acquire {
2004 PyGILState_STATE state;
2005public:
2006 gil_scoped_acquire() { state = PyGILState_Ensure(); }
2007 ~gil_scoped_acquire() { PyGILState_Release(state); }
2008};
2009
2010class gil_scoped_release {
2011 PyThreadState *state;
2012public:
2013 gil_scoped_release() { state = PyEval_SaveThread(); }
2014 ~gil_scoped_release() { PyEval_RestoreThread(state); }
2015};
Wenzel Jakob39e97e62016-04-25 03:26:15 +02002016#else
2017class gil_scoped_acquire { };
2018class gil_scoped_release { };
Felipe Lema2547ca42016-01-25 16:22:44 -03002019#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +02002020
Wenzel Jakob8d396fc2016-11-24 23:11:02 +01002021error_already_set::~error_already_set() {
martinRenou35045ee2019-05-03 14:32:28 +02002022 if (m_type) {
Wenzel Jakob8d396fc2016-11-24 23:11:02 +01002023 gil_scoped_acquire gil;
Wenzel Jakob8b90b1d2019-07-06 14:52:32 +02002024 error_scope scope;
martinRenou35045ee2019-05-03 14:32:28 +02002025 m_type.release().dec_ref();
2026 m_value.release().dec_ref();
2027 m_trace.release().dec_ref();
Wenzel Jakob8d396fc2016-11-24 23:11:02 +01002028 }
2029}
2030
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04002031inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002032 handle self = detail::get_object_handle(this_ptr, this_type);
2033 if (!self)
Wenzel Jakobac0fde92015-10-01 18:37:26 +02002034 return function();
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002035 handle type = self.get_type();
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002036 auto key = std::make_pair(type.ptr(), name);
2037
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02002038 /* Cache functions that aren't overloaded in Python to avoid
2039 many costly Python dictionary lookups below */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002040 auto &cache = detail::get_internals().inactive_overload_cache;
2041 if (cache.find(key) != cache.end())
2042 return function();
2043
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002044 function overload = getattr(self, name, function());
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002045 if (overload.is_cpp_function()) {
2046 cache.insert(key);
2047 return function();
2048 }
Wenzel Jakob27e8e102016-01-17 22:36:37 +01002049
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002050 /* Don't call dispatch code if invoked from overridden function.
2051 Unfortunately this doesn't work on PyPy. */
2052#if !defined(PYPY_VERSION)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002053 PyFrameObject *frame = PyThreadState_Get()->frame;
Dean Moldovane18bc022016-10-25 22:12:39 +02002054 if (frame && (std::string) str(frame->f_code->co_name) == name &&
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02002055 frame->f_code->co_argcount > 0) {
2056 PyFrame_FastToLocals(frame);
2057 PyObject *self_caller = PyDict_GetItem(
2058 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002059 if (self_caller == self.ptr())
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02002060 return function();
2061 }
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002062#else
2063 /* PyPy currently doesn't provide a detailed cpyext emulation of
2064 frame objects, so we have to emulate this using Python. This
2065 is going to be slow..*/
2066 dict d; d["self"] = self; d["name"] = pybind11::str(name);
2067 PyObject *result = PyRun_String(
2068 "import inspect\n"
2069 "frame = inspect.currentframe()\n"
2070 "if frame is not None:\n"
2071 " frame = frame.f_back\n"
2072 " if frame is not None and str(frame.f_code.co_name) == name and "
2073 "frame.f_code.co_argcount > 0:\n"
2074 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2075 " if self_caller == self:\n"
2076 " self = None\n",
2077 Py_file_input, d.ptr(), d.ptr());
2078 if (result == nullptr)
2079 throw error_already_set();
Dean Moldovan36f0a152017-02-08 01:01:56 +01002080 if (d["self"].is_none())
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002081 return function();
2082 Py_DECREF(result);
2083#endif
2084
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002085 return overload;
2086}
2087
Ivor Wanders2b045752019-06-10 16:12:28 -04002088/** \rst
2089 Try to retrieve a python method by the provided name from the instance pointed to by the this_ptr.
2090
2091 :this_ptr: The pointer to the object the overload should be retrieved for. This should be the first
2092 non-trampoline class encountered in the inheritance chain.
2093 :name: The name of the overloaded Python method to retrieve.
2094 :return: The Python method by this name from the object or an empty function wrapper.
2095 \endrst */
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04002096template <class T> function get_overload(const T *this_ptr, const char *name) {
Ivan Smirnov8f3e0452016-10-23 15:43:03 +01002097 auto tinfo = detail::get_type_info(typeid(T));
2098 return tinfo ? get_type_overload(this_ptr, tinfo, name) : function();
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04002099}
2100
Jason Rhinelander20978262016-08-29 18:16:46 -04002101#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02002102 pybind11::gil_scoped_acquire gil; \
Jason Rhinelander20978262016-08-29 18:16:46 -04002103 pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04002104 if (overload) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04002105 auto o = overload(__VA_ARGS__); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04002106 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04002107 static pybind11::detail::overload_caster_t<ret_type> caster; \
2108 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04002109 } \
2110 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2111 } \
2112 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002113
Ivor Wanders2b045752019-06-10 16:12:28 -04002114/** \rst
2115 Macro to populate the virtual method in the trampoline class. This macro tries to look up a method named 'fn'
2116 from the Python side, deals with the :ref:`gil` and necessary argument conversions to call this method and return
2117 the appropriate type. See :ref:`overriding_virtuals` for more information. This macro should be used when the method
2118 name in C is not the same as the method name in Python. For example with `__str__`.
2119
2120 .. code-block:: cpp
2121
2122 std::string toString() override {
2123 PYBIND11_OVERLOAD_NAME(
2124 std::string, // Return type (ret_type)
2125 Animal, // Parent class (cname)
2126 toString, // Name of function in C++ (name)
2127 "__str__", // Name of method in Python (fn)
2128 );
2129 }
2130\endrst */
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002131#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelandere88656a2018-02-27 22:33:41 -04002132 PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002133 return cname::fn(__VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002134
Ivor Wanders2b045752019-06-10 16:12:28 -04002135/** \rst
2136 Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERLOAD_NAME`, except that it
2137 throws if no overload can be found.
2138\endrst */
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002139#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelandere88656a2018-02-27 22:33:41 -04002140 PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
Jason Rhinelander9f41c8e2018-02-27 23:43:16 -04002141 pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\"");
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002142
Ivor Wanders2b045752019-06-10 16:12:28 -04002143/** \rst
2144 Macro to populate the virtual method in the trampoline class. This macro tries to look up the method
2145 from the Python side, deals with the :ref:`gil` and necessary argument conversions to call this method and return
2146 the appropriate type. This macro should be used if the method name in C and in Python are identical.
2147 See :ref:`overriding_virtuals` for more information.
2148
2149 .. code-block:: cpp
2150
2151 class PyAnimal : public Animal {
2152 public:
2153 // Inherit the constructors
2154 using Animal::Animal;
2155
2156 // Trampoline (need one for each virtual function)
2157 std::string go(int n_times) override {
2158 PYBIND11_OVERLOAD_PURE(
2159 std::string, // Return type (ret_type)
2160 Animal, // Parent class (cname)
2161 go, // Name of function in C++ (must match Python name) (fn)
2162 n_times // Argument(s) (...)
2163 );
2164 }
2165 };
2166\endrst */
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002167#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
Jason Rhinelandere88656a2018-02-27 22:33:41 -04002168 PYBIND11_OVERLOAD_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002169
Ivor Wanders2b045752019-06-10 16:12:28 -04002170/** \rst
2171 Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERLOAD`, except that it throws
2172 if no overload can be found.
2173\endrst */
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002174#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
Jason Rhinelandere88656a2018-02-27 22:33:41 -04002175 PYBIND11_OVERLOAD_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002176
Jason Rhinelandera859dd62017-08-10 12:03:29 -04002177NAMESPACE_END(PYBIND11_NAMESPACE)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02002178
Baljak81da9882018-11-20 23:22:02 +01002179#if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01002180# pragma warning(pop)
Wenzel Jakob6d252962016-05-01 20:47:49 +02002181#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01002182# pragma GCC diagnostic pop
Wenzel Jakob38bd7112015-07-05 20:05:44 +02002183#endif