blob: ee28705245eda48a8028661349a1596a4f6ab3a0 [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
Yannick Jadoulf980d762020-07-09 00:14:41 +020053PYBIND11_NAMESPACE_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
Clemens Sielaff63df87f2020-06-10 04:35:10 -070075 /// Construct a cpp_function from a class method (non-const, no ref-qualifier)
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) {
Robert Haschkef2226ae2020-07-07 15:56:07 +020078 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050079 (Return (*) (Class *, Arg...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020080 }
81
Clemens Sielaff63df87f2020-06-10 04:35:10 -070082 /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier)
83 /// A copy of the overload for non-const functions without explicit ref-qualifier
84 /// but with an added `&`.
85 template <typename Return, typename Class, typename... Arg, typename... Extra>
86 cpp_function(Return (Class::*f)(Arg...)&, const Extra&... extra) {
87 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
88 (Return (*) (Class *, Arg...)) nullptr, extra...);
89 }
90
91 /// Construct a cpp_function from a class method (const, no ref-qualifier)
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050092 template <typename Return, typename Class, typename... Arg, typename... Extra>
93 cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
Robert Haschkef2226ae2020-07-07 15:56:07 +020094 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050095 (Return (*)(const Class *, Arg ...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020096 }
97
Clemens Sielaff63df87f2020-06-10 04:35:10 -070098 /// Construct a cpp_function from a class method (const, lvalue ref-qualifier)
99 /// A copy of the overload for const functions without explicit ref-qualifier
100 /// but with an added `&`.
101 template <typename Return, typename Class, typename... Arg, typename... Extra>
102 cpp_function(Return (Class::*f)(Arg...) const&, const Extra&... extra) {
103 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
104 (Return (*)(const Class *, Arg ...)) nullptr, extra...);
105 }
106
Wenzel Jakob57082212015-09-04 23:42:12 +0200107 /// Return the function name
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100108 object name() const { return attr("__name__"); }
Wenzel Jakob57082212015-09-04 23:42:12 +0200109
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100110protected:
Wenzel Jakob382484a2016-09-10 15:28:37 +0900111 /// Space optimization: don't inline this frequently instantiated fragment
112 PYBIND11_NOINLINE detail::function_record *make_function_record() {
113 return new detail::function_record();
114 }
115
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100116 /// Special internal constructor for functors, lambda functions, etc.
Jason Rhinelander1d7998e2017-02-17 06:56:41 -0500117 template <typename Func, typename Return, typename... Args, typename... Extra>
118 void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
Dean Moldovan56613942017-07-02 12:52:00 +0200119 using namespace detail;
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400120 struct capture { remove_reference_t<Func> f; };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200121
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100122 /* Store the function including any extra state it might have (e.g. a lambda capture object) */
Wenzel Jakob382484a2016-09-10 15:28:37 +0900123 auto rec = make_function_record();
Wenzel Jakob71867832015-07-29 17:43:52 +0200124
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100125 /* Store the capture object directly in the function record if there is enough space */
126 if (sizeof(capture) <= sizeof(rec->data)) {
Wenzel Jakob954b7932016-07-10 10:13:18 +0200127 /* Without these pragmas, GCC warns that there might not be
128 enough space to use the placement new operator. However, the
129 'if' statement above ensures that this is the case. */
Jason Rhinelander0b12f912016-07-07 16:26:04 -0400130#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -0400131# pragma GCC diagnostic push
132# pragma GCC diagnostic ignored "-Wplacement-new"
133#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100134 new ((capture *) &rec->data) capture { std::forward<Func>(f) };
Jason Rhinelander0b12f912016-07-07 16:26:04 -0400135#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -0400136# pragma GCC diagnostic pop
137#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100138 if (!std::is_trivially_destructible<Func>::value)
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400139 rec->free_data = [](function_record *r) { ((capture *) &r->data)->~capture(); };
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100140 } else {
141 rec->data[0] = new capture { std::forward<Func>(f) };
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400142 rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100143 }
Wenzel Jakob19208fe2015-10-13 17:37:25 +0200144
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100145 /* Type casters for the function arguments and return value */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400146 using cast_in = argument_loader<Args...>;
147 using cast_out = make_caster<
148 conditional_t<std::is_void<Return>::value, void_type, Return>
Dean Moldovan719c1732016-11-27 18:19:34 +0100149 >;
Wenzel Jakob71867832015-07-29 17:43:52 +0200150
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400151 static_assert(expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
Jason Rhinelander0f5ec0a2017-03-19 12:36:18 -0300152 "The number of argument annotations does not match the number of function arguments");
Jason Rhinelander2686da82017-01-21 23:42:14 -0500153
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100154 /* Dispatch code which converts function arguments and performs the actual function call */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400155 rec->impl = [](function_call &call) -> handle {
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100156 cast_in args_converter;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100157
158 /* Try to cast the function arguments into the C++ domain */
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500159 if (!args_converter.load_args(call))
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100160 return PYBIND11_TRY_NEXT_OVERLOAD;
161
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100162 /* Invoke call policy pre-call hook */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400163 process_attributes<Extra...>::precall(call);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100164
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100165 /* Get a pointer to the capture object */
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500166 auto data = (sizeof(capture) <= sizeof(call.func.data)
167 ? &call.func.data : call.func.data[0]);
168 capture *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100169
Jason Rhinelander546f6fc2017-01-20 00:59:26 -0500170 /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
Wenzel Jakobcbd16a82018-07-17 16:56:26 +0200171 return_value_policy policy = return_value_policy_override<Return>::policy(call.func.policy);
Dean Moldovand079f412016-11-20 05:31:02 +0100172
Dean Moldovan1ac19032017-03-16 11:22:26 +0100173 /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400174 using Guard = extract_guard_t<Extra...>;
Dean Moldovan1ac19032017-03-16 11:22:26 +0100175
Wenzel Jakob954b7932016-07-10 10:13:18 +0200176 /* Perform the function call */
Jason Rhinelander813d7e82017-05-14 15:57:26 -0400177 handle result = cast_out::cast(
178 std::move(args_converter).template call<Return, Guard>(cap->f), policy, call.parent);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100179
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100180 /* Invoke call policy post-call hook */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400181 process_attributes<Extra...>::postcall(call, result);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100182
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100183 return result;
Wenzel Jakob71867832015-07-29 17:43:52 +0200184 };
185
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100186 /* Process any user-provided function attributes */
Jason Rhinelander657a51e2018-01-12 12:06:46 -0400187 process_attributes<Extra...>::init(extra..., rec);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100188
Jason Rhinelanderbe0d8042017-12-23 18:56:07 -0400189 {
Sebastian Koslowskia86ac532020-04-14 13:04:25 +0200190 constexpr bool has_kwonly_args = any_of<std::is_same<kwonly, Extra>...>::value,
Jason Rhinelanderbe0d8042017-12-23 18:56:07 -0400191 has_args = any_of<std::is_same<args, Args>...>::value,
192 has_arg_annotations = any_of<is_keyword<Extra>...>::value;
Sebastian Koslowskia86ac532020-04-14 13:04:25 +0200193 static_assert(has_arg_annotations || !has_kwonly_args, "py::kwonly requires the use of argument annotations");
194 static_assert(!(has_args && has_kwonly_args), "py::kwonly cannot be combined with a py::args argument");
Jason Rhinelanderbe0d8042017-12-23 18:56:07 -0400195 }
196
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100197 /* Generate a readable signature describing the function's arguments and return value types */
Dean Moldovan56613942017-07-02 12:52:00 +0200198 static constexpr auto signature = _("(") + cast_in::arg_names + _(") -> ") + cast_out::name;
199 PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100200
201 /* Register the function with Python from generic (non-templated) code */
Dean Moldovan56613942017-07-02 12:52:00 +0200202 initialize_generic(rec, signature.text, types.data(), sizeof...(Args));
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100203
204 if (cast_in::has_args) rec->has_args = true;
205 if (cast_in::has_kwargs) rec->has_kwargs = true;
Wenzel Jakob954b7932016-07-10 10:13:18 +0200206
207 /* Stash some additional information used by an important optimization in 'functional.h' */
Jason Rhinelander1d7998e2017-02-17 06:56:41 -0500208 using FunctionType = Return (*)(Args...);
Wenzel Jakob954b7932016-07-10 10:13:18 +0200209 constexpr bool is_function_ptr =
210 std::is_convertible<Func, FunctionType>::value &&
211 sizeof(capture) == sizeof(void *);
212 if (is_function_ptr) {
213 rec->is_stateless = true;
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500214 rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
Wenzel Jakob954b7932016-07-10 10:13:18 +0200215 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200216 }
217
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100218 /// Register a function call with Python (generic non-templated code goes here)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100219 void initialize_generic(detail::function_record *rec, const char *text,
Dean Moldovanecced6c2016-07-31 20:03:18 +0200220 const std::type_info *const *types, size_t args) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100221
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100222 /* Create copies of all referenced C-style strings */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100223 rec->name = strdup(rec->name ? rec->name : "");
224 if (rec->doc) rec->doc = strdup(rec->doc);
225 for (auto &a: rec->args) {
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100226 if (a.name)
227 a.name = strdup(a.name);
228 if (a.descr)
229 a.descr = strdup(a.descr);
230 else if (a.value)
Dean Moldovan242b1462016-09-08 17:02:04 +0200231 a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100232 }
Wenzel Jakob954b7932016-07-10 10:13:18 +0200233
Jason Rhinelander464d9892017-06-12 21:52:48 -0400234 rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
235
Dean Moldovanb8c5dbd2017-08-24 02:46:07 +0200236#if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
237 if (rec->is_constructor && !rec->is_new_style_constructor) {
238 const auto class_name = std::string(((PyTypeObject *) rec->scope.ptr())->tp_name);
239 const auto func_name = std::string(rec->name);
240 PyErr_WarnEx(
241 PyExc_FutureWarning,
242 ("pybind11-bound class '" + class_name + "' is using an old-style "
243 "placement-new '" + func_name + "' which has been deprecated. See "
244 "the upgrade guide in pybind11's docs. This message is only visible "
245 "when compiled in debug mode.").c_str(), 0
246 );
247 }
248#endif
249
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100250 /* Generate a proper function signature */
251 std::string signature;
Dean Moldovan0aef6422017-08-31 14:38:23 +0200252 size_t type_index = 0, arg_index = 0;
253 for (auto *pc = text; *pc != '\0'; ++pc) {
254 const auto c = *pc;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100255
256 if (c == '{') {
Dean Moldovan0aef6422017-08-31 14:38:23 +0200257 // Write arg name for everything except *args and **kwargs.
258 if (*(pc + 1) == '*')
259 continue;
260
261 if (arg_index < rec->args.size() && rec->args[arg_index].name) {
262 signature += rec->args[arg_index].name;
263 } else if (arg_index == 0 && rec->is_method) {
264 signature += "self";
265 } else {
266 signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100267 }
Dean Moldovan0aef6422017-08-31 14:38:23 +0200268 signature += ": ";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100269 } else if (c == '}') {
Dean Moldovan0aef6422017-08-31 14:38:23 +0200270 // Write default value if available.
271 if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
Antony Lee0826b3c2017-11-26 20:00:35 -0800272 signature += " = ";
Dean Moldovan0aef6422017-08-31 14:38:23 +0200273 signature += rec->args[arg_index].descr;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100274 }
Dean Moldovan0aef6422017-08-31 14:38:23 +0200275 arg_index++;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100276 } else if (c == '%') {
277 const std::type_info *t = types[type_index++];
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100278 if (!t)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100279 pybind11_fail("Internal error while parsing type signature (1)");
Ivan Smirnov8f3e0452016-10-23 15:43:03 +0100280 if (auto tinfo = detail::get_type_info(*t)) {
Jason Rhinelander71178922017-11-07 12:33:05 -0400281 handle th((PyObject *) tinfo->type);
282 signature +=
283 th.attr("__module__").cast<std::string>() + "." +
284 th.attr("__qualname__").cast<std::string>(); // Python 3.3+, but we backport it to earlier versions
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200285 } else if (rec->is_new_style_constructor && arg_index == 0) {
286 // A new-style `__init__` takes `self` as `value_and_holder`.
287 // Rewrite it to the proper class type.
Jason Rhinelander71178922017-11-07 12:33:05 -0400288 signature +=
289 rec->scope.attr("__module__").cast<std::string>() + "." +
290 rec->scope.attr("__qualname__").cast<std::string>();
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100291 } else {
292 std::string tname(t->name());
293 detail::clean_type_id(tname);
294 signature += tname;
295 }
296 } else {
297 signature += c;
298 }
299 }
Dean Moldovan0aef6422017-08-31 14:38:23 +0200300 if (arg_index != args || types[type_index] != nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100301 pybind11_fail("Internal error while parsing type signature (2)");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100302
Wenzel Jakob57082212015-09-04 23:42:12 +0200303#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100304 if (strcmp(rec->name, "__next__") == 0) {
305 std::free(rec->name);
306 rec->name = strdup("next");
Wenzel Jakobd1bfc4e2016-05-16 18:52:46 +0200307 } else if (strcmp(rec->name, "__bool__") == 0) {
308 std::free(rec->name);
309 rec->name = strdup("__nonzero__");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100310 }
Wenzel Jakob57082212015-09-04 23:42:12 +0200311#endif
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100312 rec->signature = strdup(signature.c_str());
313 rec->args.shrink_to_fit();
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500314 rec->nargs = (std::uint16_t) args;
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200315
Jason Rhinelander0a90b2d2017-04-16 20:30:52 -0400316 if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr()))
317 rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
Wenzel Jakob57082212015-09-04 23:42:12 +0200318
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100319 detail::function_record *chain = nullptr, *chain_start = rec;
Jason Rhinelander6873c202016-10-24 21:58:22 -0400320 if (rec->sibling) {
321 if (PyCFunction_Check(rec->sibling.ptr())) {
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100322 auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
Jason Rhinelander6873c202016-10-24 21:58:22 -0400323 chain = (detail::function_record *) rec_capsule;
324 /* Never append a method to an overload chain of a parent class;
325 instead, hide the parent's overloads in this case */
Dean Moldovan36f0a152017-02-08 01:01:56 +0100326 if (!chain->scope.is(rec->scope))
Jason Rhinelander6873c202016-10-24 21:58:22 -0400327 chain = nullptr;
328 }
329 // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
330 else if (!rec->sibling.is_none() && rec->name[0] != '_')
331 pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
332 "\" with a function of the same name");
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200333 }
334
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100335 if (!chain) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100336 /* No existing overload was found, create a new function object */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100337 rec->def = new PyMethodDef();
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500338 std::memset(rec->def, 0, sizeof(PyMethodDef));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100339 rec->def->ml_name = rec->name;
Antony Leebaf6b992018-06-24 15:38:09 +0200340 rec->def->ml_meth = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(*dispatcher));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100341 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
Wenzel Jakoba6501792016-02-04 23:02:07 +0100342
Wenzel Jakobb16421e2017-03-22 22:04:00 +0100343 capsule rec_capsule(rec, [](void *ptr) {
344 destruct((detail::function_record *) ptr);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100345 });
Wenzel Jakoba6501792016-02-04 23:02:07 +0100346
347 object scope_module;
348 if (rec->scope) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200349 if (hasattr(rec->scope, "__module__")) {
350 scope_module = rec->scope.attr("__module__");
351 } else if (hasattr(rec->scope, "__name__")) {
352 scope_module = rec->scope.attr("__name__");
353 }
Wenzel Jakoba6501792016-02-04 23:02:07 +0100354 }
355
356 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200357 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100358 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200359 } else {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100360 /* Append at the end of the overload chain */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100361 m_ptr = rec->sibling.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200362 inc_ref();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100363 chain_start = chain;
Jason Rhinelanderd355f2f2017-04-16 22:31:13 -0400364 if (chain->is_method != rec->is_method)
365 pybind11_fail("overloading a method with both static and instance methods is not supported; "
366 #if defined(NDEBUG)
367 "compile in debug mode for more details"
368 #else
369 "error while attempting to bind " + std::string(rec->is_method ? "instance" : "static") + " method " +
370 std::string(pybind11::str(rec->scope.attr("__name__"))) + "." + std::string(rec->name) + signature
371 #endif
372 );
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100373 while (chain->next)
374 chain = chain->next;
375 chain->next = rec;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200376 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200377
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200378 std::string signatures;
Wenzel Jakob71867832015-07-29 17:43:52 +0200379 int index = 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100380 /* Create a nice pydoc rec including all signatures and
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100381 docstrings of the functions in the overload chain */
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100382 if (chain && options::show_function_signatures()) {
Sylvain Corlay0e04fdf2016-03-08 16:42:12 -0500383 // First a generic signature
384 signatures += rec->name;
385 signatures += "(*args, **kwargs)\n";
386 signatures += "Overloaded function.\n\n";
387 }
388 // Then specific overload signatures
Jason Rhinelander10d13042017-03-08 12:32:42 -0500389 bool first_user_def = true;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100390 for (auto it = chain_start; it != nullptr; it = it->next) {
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100391 if (options::show_function_signatures()) {
Jason Rhinelander10d13042017-03-08 12:32:42 -0500392 if (index > 0) signatures += "\n";
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100393 if (chain)
394 signatures += std::to_string(++index) + ". ";
395 signatures += rec->name;
396 signatures += it->signature;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100397 signatures += "\n";
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100398 }
399 if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
Jason Rhinelander10d13042017-03-08 12:32:42 -0500400 // If we're appending another docstring, and aren't printing function signatures, we
401 // need to append a newline first:
402 if (!options::show_function_signatures()) {
403 if (first_user_def) first_user_def = false;
404 else signatures += "\n";
405 }
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100406 if (options::show_function_signatures()) signatures += "\n";
Wenzel Jakob218b6ce2016-02-28 23:52:37 +0100407 signatures += it->doc;
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100408 if (options::show_function_signatures()) signatures += "\n";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100409 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200410 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100411
412 /* Install docstring */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200413 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
414 if (func->m_ml->ml_doc)
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500415 std::free(const_cast<char *>(func->m_ml->ml_doc));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200416 func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100417
Wenzel Jakob31fbf182016-11-20 05:27:05 +0100418 if (rec->is_method) {
419 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200420 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100421 pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200422 Py_DECREF(func);
423 }
424 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100425
426 /// When a cpp_function is GCed, release any memory allocated by pybind11
427 static void destruct(detail::function_record *rec) {
428 while (rec) {
429 detail::function_record *next = rec->next;
430 if (rec->free_data)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100431 rec->free_data(rec);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100432 std::free((char *) rec->name);
433 std::free((char *) rec->doc);
434 std::free((char *) rec->signature);
435 for (auto &arg: rec->args) {
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500436 std::free(const_cast<char *>(arg.name));
437 std::free(const_cast<char *>(arg.descr));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100438 arg.value.dec_ref();
439 }
440 if (rec->def) {
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500441 std::free(const_cast<char *>(rec->def->ml_doc));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100442 delete rec->def;
443 }
444 delete rec;
445 rec = next;
446 }
447 }
448
449 /// Main dispatch logic for calls to functions bound using pybind11
Jason Rhinelander2686da82017-01-21 23:42:14 -0500450 static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500451 using namespace detail;
452
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100453 /* Iterator over the list of potentially admissible overloads */
oremanje7761e32018-09-25 14:55:18 -0700454 const function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
455 *it = overloads;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100456
457 /* Need to know how many arguments + keyword arguments there are to pick the right overload */
Jason Rhinelander2686da82017-01-21 23:42:14 -0500458 const size_t n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100459
Jason Rhinelander2686da82017-01-21 23:42:14 -0500460 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100461 result = PYBIND11_TRY_NEXT_OVERLOAD;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500462
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200463 auto self_value_and_holder = value_and_holder();
464 if (overloads->is_constructor) {
465 const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
466 const auto pi = reinterpret_cast<instance *>(parent.ptr());
467 self_value_and_holder = pi->get_value_and_holder(tinfo, false);
468
469 if (!self_value_and_holder.type || !self_value_and_holder.inst) {
470 PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid `self` argument");
471 return nullptr;
472 }
473
474 // If this value is already registered it must mean __init__ is invoked multiple times;
475 // we really can't support that in C++, so just ignore the second __init__.
476 if (self_value_and_holder.instance_registered())
477 return none().release().ptr();
478 }
479
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100480 try {
Jason Rhinelandere5505892017-02-03 18:25:34 -0500481 // We do this in two passes: in the first pass, we load arguments with `convert=false`;
482 // in the second, we allow conversion (except for arguments with an explicit
483 // py::arg().noconvert()). This lets us prefer calls without conversion, with
484 // conversion as a fallback.
485 std::vector<function_call> second_pass;
486
487 // However, if there are no overloads, we can just skip the no-convert pass entirely
488 const bool overloaded = it != nullptr && it->next != nullptr;
489
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100490 for (; it != nullptr; it = it->next) {
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500491
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100492 /* For each overload:
Jason Rhinelander2686da82017-01-21 23:42:14 -0500493 1. Copy all positional arguments we were given, also checking to make sure that
494 named positional arguments weren't *also* specified via kwarg.
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100495 2. If we weren't given enough, try to make up the omitted ones by checking
Jason Rhinelander2686da82017-01-21 23:42:14 -0500496 whether they were provided by a kwarg matching the `py::arg("name")` name. If
497 so, use it (and remove it from kwargs; if not, see if the function binding
498 provided a default that we can use.
499 3. Ensure that either all keyword arguments were "consumed", or that the function
500 takes a kwargs argument to accept unconsumed kwargs.
501 4. Any positional arguments still left get put into a tuple (for args), and any
502 leftover kwargs get put into a dict.
503 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
504 extra tuple or dict at the end of the positional arguments.
505 6. Call the function call dispatcher (function_record::impl)
506
507 If one of these fail, move on to the next overload and keep trying until we get a
508 result other than PYBIND11_TRY_NEXT_OVERLOAD.
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100509 */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100510
oremanje7761e32018-09-25 14:55:18 -0700511 const function_record &func = *it;
Jason Rhinelanderbe0d8042017-12-23 18:56:07 -0400512 size_t num_args = func.nargs; // Number of positional arguments that we need
513 if (func.has_args) --num_args; // (but don't count py::args
514 if (func.has_kwargs) --num_args; // or py::kwargs)
515 size_t pos_args = num_args - func.nargs_kwonly;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100516
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500517 if (!func.has_args && n_args_in > pos_args)
Jason Rhinelanderbe0d8042017-12-23 18:56:07 -0400518 continue; // Too many positional arguments for this overload
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100519
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500520 if (n_args_in < pos_args && func.args.size() < pos_args)
Jason Rhinelanderbe0d8042017-12-23 18:56:07 -0400521 continue; // Not enough positional arguments given, and not enough defaults to fill in the blanks
Jason Rhinelander2686da82017-01-21 23:42:14 -0500522
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500523 function_call call(func, parent);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500524
Nathan9b3fb052019-07-18 01:01:50 -0600525 size_t args_to_copy = (std::min)(pos_args, n_args_in); // Protect std::min with parentheses
Jason Rhinelander2686da82017-01-21 23:42:14 -0500526 size_t args_copied = 0;
527
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200528 // 0. Inject new-style `self` argument
529 if (func.is_new_style_constructor) {
530 // The `value` may have been preallocated by an old-style `__init__`
531 // if it was a preceding candidate for overload resolution.
532 if (self_value_and_holder)
533 self_value_and_holder.type->dealloc(self_value_and_holder);
534
Dean Moldovan7939f4b2017-09-04 13:49:19 +0200535 call.init_self = PyTuple_GET_ITEM(args_in, 0);
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200536 call.args.push_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
537 call.args_convert.push_back(false);
538 ++args_copied;
539 }
540
Jason Rhinelander2686da82017-01-21 23:42:14 -0500541 // 1. Copy any position arguments given.
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400542 bool bad_arg = false;
Jason Rhinelander2686da82017-01-21 23:42:14 -0500543 for (; args_copied < args_to_copy; ++args_copied) {
oremanje7761e32018-09-25 14:55:18 -0700544 const argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400545 if (kwargs_in && arg_rec && arg_rec->name && PyDict_GetItemString(kwargs_in, arg_rec->name)) {
546 bad_arg = true;
Jason Rhinelandercaa13792017-02-23 19:54:53 -0500547 break;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100548 }
Jason Rhinelander2686da82017-01-21 23:42:14 -0500549
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400550 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
551 if (arg_rec && !arg_rec->none && arg.is_none()) {
552 bad_arg = true;
553 break;
554 }
555 call.args.push_back(arg);
556 call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100557 }
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400558 if (bad_arg)
Jason Rhinelandercaa13792017-02-23 19:54:53 -0500559 continue; // Maybe it was meant for another overload (issue #688)
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200560
Jason Rhinelander2686da82017-01-21 23:42:14 -0500561 // We'll need to copy this if we steal some kwargs for defaults
562 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
563
564 // 2. Check kwargs and, failing that, defaults that may help complete the list
Jason Rhinelanderbe0d8042017-12-23 18:56:07 -0400565 if (args_copied < num_args) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500566 bool copied_kwargs = false;
567
Jason Rhinelanderbe0d8042017-12-23 18:56:07 -0400568 for (; args_copied < num_args; ++args_copied) {
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500569 const auto &arg = func.args[args_copied];
Jason Rhinelander2686da82017-01-21 23:42:14 -0500570
571 handle value;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500572 if (kwargs_in && arg.name)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500573 value = PyDict_GetItemString(kwargs.ptr(), arg.name);
574
575 if (value) {
576 // Consume a kwargs value
577 if (!copied_kwargs) {
578 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
579 copied_kwargs = true;
580 }
581 PyDict_DelItemString(kwargs.ptr(), arg.name);
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100582 } else if (arg.value) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500583 value = arg.value;
584 }
585
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500586 if (value) {
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500587 call.args.push_back(value);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500588 call.args_convert.push_back(arg.convert);
589 }
Jason Rhinelander2686da82017-01-21 23:42:14 -0500590 else
591 break;
592 }
593
Jason Rhinelanderbe0d8042017-12-23 18:56:07 -0400594 if (args_copied < num_args)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500595 continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments
596 }
597
598 // 3. Check everything was consumed (unless we have a kwargs arg)
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500599 if (kwargs && kwargs.size() > 0 && !func.has_kwargs)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500600 continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
601
602 // 4a. If we have a py::args argument, create a new tuple with leftovers
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500603 if (func.has_args) {
Jason Rhinelander48e1f9a2017-12-23 09:42:32 -0400604 tuple extra_args;
Jason Rhinelander2686da82017-01-21 23:42:14 -0500605 if (args_to_copy == 0) {
606 // We didn't copy out any position arguments from the args_in tuple, so we
607 // can reuse it directly without copying:
608 extra_args = reinterpret_borrow<tuple>(args_in);
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100609 } else if (args_copied >= n_args_in) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500610 extra_args = tuple(0);
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100611 } else {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500612 size_t args_size = n_args_in - args_copied;
613 extra_args = tuple(args_size);
614 for (size_t i = 0; i < args_size; ++i) {
Jason Rhinelander367d7232017-12-15 13:21:52 -0400615 extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500616 }
617 }
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500618 call.args.push_back(extra_args);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500619 call.args_convert.push_back(false);
Jason Rhinelander48e1f9a2017-12-23 09:42:32 -0400620 call.args_ref = std::move(extra_args);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500621 }
622
623 // 4b. If we have a py::kwargs, pass on any remaining kwargs
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500624 if (func.has_kwargs) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500625 if (!kwargs.ptr())
626 kwargs = dict(); // If we didn't get one, send an empty one
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500627 call.args.push_back(kwargs);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500628 call.args_convert.push_back(false);
Jason Rhinelander48e1f9a2017-12-23 09:42:32 -0400629 call.kwargs_ref = std::move(kwargs);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500630 }
631
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500632 // 5. Put everything in a vector. Not technically step 5, we've been building it
633 // in `call.args` all along.
634 #if !defined(NDEBUG)
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500635 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500636 pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
637 #endif
Jason Rhinelander2686da82017-01-21 23:42:14 -0500638
Jason Rhinelandere5505892017-02-03 18:25:34 -0500639 std::vector<bool> second_pass_convert;
640 if (overloaded) {
641 // We're in the first no-convert pass, so swap out the conversion flags for a
642 // set of all-false flags. If the call fails, we'll swap the flags back in for
643 // the conversion-allowed call below.
644 second_pass_convert.resize(func.nargs, false);
645 call.args_convert.swap(second_pass_convert);
646 }
647
Jason Rhinelander2686da82017-01-21 23:42:14 -0500648 // 6. Call the function.
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200649 try {
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200650 loader_life_support guard{};
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500651 result = func.impl(call);
Wenzel Jakob00062592016-07-01 16:07:35 +0200652 } catch (reference_cast_error &) {
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200653 result = PYBIND11_TRY_NEXT_OVERLOAD;
654 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100655
656 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
657 break;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500658
Jason Rhinelandere5505892017-02-03 18:25:34 -0500659 if (overloaded) {
660 // The (overloaded) call failed; if the call has at least one argument that
661 // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
662 // then add this call to the list of second pass overloads to try.
663 for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
664 if (second_pass_convert[i]) {
665 // Found one: swap the converting flags back in and store the call for
666 // the second pass.
667 call.args_convert.swap(second_pass_convert);
668 second_pass.push_back(std::move(call));
669 break;
670 }
671 }
672 }
673 }
674
675 if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
676 // The no-conversion pass finished without success, try again with conversion allowed
677 for (auto &call : second_pass) {
678 try {
Dean Moldovanaf2dda32017-06-26 20:34:06 +0200679 loader_life_support guard{};
Jason Rhinelandere5505892017-02-03 18:25:34 -0500680 result = call.func.impl(call);
681 } catch (reference_cast_error &) {
682 result = PYBIND11_TRY_NEXT_OVERLOAD;
683 }
684
oremanje7761e32018-09-25 14:55:18 -0700685 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
686 // The error reporting logic below expects 'it' to be valid, as it would be
687 // if we'd encountered this failure in the first-pass loop.
688 if (!result)
689 it = &call.func;
Jason Rhinelandere5505892017-02-03 18:25:34 -0500690 break;
oremanje7761e32018-09-25 14:55:18 -0700691 }
Jason Rhinelandere5505892017-02-03 18:25:34 -0500692 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100693 }
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200694 } catch (error_already_set &e) {
695 e.restore();
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400696 return nullptr;
Jörg Kreuzberger69dc3802019-06-10 22:00:55 +0200697#if defined(__GNUG__) && !defined(__clang__)
698 } catch ( abi::__forced_unwind& ) {
699 throw;
700#endif
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100701 } catch (...) {
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400702 /* When an exception is caught, give each registered exception
703 translator a chance to translate it to a Python exception
704 in reverse order of registration.
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200705
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400706 A translator may choose to do one of the following:
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200707
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400708 - catch the exception and call PyErr_SetString or PyErr_SetObject
709 to set a standard (or custom) Python exception, or
710 - do nothing and let the exception fall through to the next translator, or
711 - delegate translation to the next translator by throwing a new type of exception. */
712
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200713 auto last_exception = std::current_exception();
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500714 auto &registered_exception_translators = get_internals().registered_exception_translators;
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400715 for (auto& translator : registered_exception_translators) {
716 try {
717 translator(last_exception);
718 } catch (...) {
719 last_exception = std::current_exception();
720 continue;
721 }
722 return nullptr;
723 }
724 PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100725 return nullptr;
726 }
727
Dean Moldovan2b4477e2017-09-09 20:21:34 +0200728 auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
729 if (msg.find("std::") != std::string::npos) {
730 msg += "\n\n"
731 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
732 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
733 "conversions are optional and require extra headers to be included\n"
734 "when compiling your pybind11 module.";
735 }
736 };
737
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100738 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
Wenzel Jakob382484a2016-09-10 15:28:37 +0900739 if (overloads->is_operator)
740 return handle(Py_NotImplemented).inc_ref().ptr();
741
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900742 std::string msg = std::string(overloads->name) + "(): incompatible " +
743 std::string(overloads->is_constructor ? "constructor" : "function") +
744 " arguments. The following argument types are supported:\n";
745
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100746 int ctr = 0;
oremanje7761e32018-09-25 14:55:18 -0700747 for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100748 msg += " "+ std::to_string(++ctr) + ". ";
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400749
750 bool wrote_sig = false;
751 if (overloads->is_constructor) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200752 // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400753 std::string sig = it2->signature;
Dean Moldovanecced6c2016-07-31 20:03:18 +0200754 size_t start = sig.find('(') + 7; // skip "(self: "
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400755 if (start < sig.size()) {
756 // End at the , for the next argument
757 size_t end = sig.find(", "), next = end + 2;
758 size_t ret = sig.rfind(" -> ");
759 // Or the ), if there is no comma:
760 if (end >= sig.size()) next = end = sig.find(')');
761 if (start < end && next < sig.size()) {
762 msg.append(sig, start, end - start);
763 msg += '(';
764 msg.append(sig, next, ret - next);
765 wrote_sig = true;
766 }
767 }
768 }
769 if (!wrote_sig) msg += it2->signature;
770
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100771 msg += "\n";
772 }
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900773 msg += "\nInvoked with: ";
Jason Rhinelander2686da82017-01-21 23:42:14 -0500774 auto args_ = reinterpret_borrow<tuple>(args_in);
Jason Rhinelander231e1672017-02-23 21:04:46 -0500775 bool some_args = false;
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200776 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
Jason Rhinelander231e1672017-02-23 21:04:46 -0500777 if (!some_args) some_args = true;
778 else msg += ", ";
Jason Rhinelander7146d622016-11-22 05:28:40 -0500779 msg += pybind11::repr(args_[ti]);
Andreas Bergmeier16d43942016-05-24 09:19:35 +0200780 }
Jason Rhinelander231e1672017-02-23 21:04:46 -0500781 if (kwargs_in) {
782 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
783 if (kwargs.size() > 0) {
784 if (some_args) msg += "; ";
785 msg += "kwargs: ";
786 bool first = true;
787 for (auto kwarg : kwargs) {
788 if (first) first = false;
789 else msg += ", ";
790 msg += pybind11::str("{}={!r}").format(kwarg.first, kwarg.second);
791 }
792 }
793 }
794
Dean Moldovan2b4477e2017-09-09 20:21:34 +0200795 append_note_if_missing_header_is_suspected(msg);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100796 PyErr_SetString(PyExc_TypeError, msg.c_str());
797 return nullptr;
798 } else if (!result) {
799 std::string msg = "Unable to convert function return value to a "
800 "Python type! The signature was\n\t";
801 msg += it->signature;
Dean Moldovan2b4477e2017-09-09 20:21:34 +0200802 append_note_if_missing_header_is_suspected(msg);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100803 PyErr_SetString(PyExc_TypeError, msg.c_str());
804 return nullptr;
805 } else {
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200806 if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
Jason Rhinelander464d9892017-06-12 21:52:48 -0400807 auto *pi = reinterpret_cast<instance *>(parent.ptr());
Dean Moldovan39fd6a92017-08-17 02:01:32 +0200808 self_value_and_holder.type->init_instance(pi, nullptr);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100809 }
810 return result.ptr();
811 }
812 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200813};
814
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100815/// Wrapper for Python extension modules
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200816class module : public object {
817public:
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200818 PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200819
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100820 /// Create a new top-level Python module with the given name and docstring
Jason Rhinelander12d76602016-10-16 16:27:42 -0400821 explicit module(const char *name, const char *doc = nullptr) {
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100822 if (!options::show_user_defined_docstrings()) doc = nullptr;
Wenzel Jakob57082212015-09-04 23:42:12 +0200823#if PY_MAJOR_VERSION >= 3
Wenzel Jakobfb910ae2019-12-11 21:26:46 +0100824 PyModuleDef *def = new PyModuleDef();
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500825 std::memset(def, 0, sizeof(PyModuleDef));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200826 def->m_name = name;
827 def->m_doc = doc;
828 def->m_size = -1;
829 Py_INCREF(def);
830 m_ptr = PyModule_Create(def);
Wenzel Jakob57082212015-09-04 23:42:12 +0200831#else
832 m_ptr = Py_InitModule3(name, nullptr, doc);
833#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200834 if (m_ptr == nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100835 pybind11_fail("Internal error in module::module()");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200836 inc_ref();
837 }
838
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100839 /** \rst
840 Create Python binding for a new function within the module scope. ``Func``
841 can be a plain C++ function, a function pointer, or a lambda function. For
842 details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
843 \endrst */
Wenzel Jakob71867832015-07-29 17:43:52 +0200844 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100845 module &def(const char *name_, Func &&f, const Extra& ... extra) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200846 cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
847 sibling(getattr(*this, name_, none())), extra...);
Jason Rhinelander6873c202016-10-24 21:58:22 -0400848 // NB: allow overwriting here because cpp_function sets up a chain with the intention of
849 // overwriting (and has already checked internally that it isn't overwriting non-functions).
850 add_object(name_, func, true /* overwrite */);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200851 return *this;
852 }
853
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100854 /** \rst
855 Create and return a new Python submodule with the given name and docstring.
856 This also works recursively, i.e.
857
858 .. code-block:: cpp
859
860 py::module m("example", "pybind11 example plugin");
861 py::module m2 = m.def_submodule("sub", "A submodule of 'example'");
862 py::module m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
863 \endrst */
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200864 module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200865 std::string full_name = std::string(PyModule_GetName(m_ptr))
866 + std::string(".") + std::string(name);
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200867 auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100868 if (doc && options::show_user_defined_docstrings())
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200869 result.attr("__doc__") = pybind11::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200870 attr(name) = result;
871 return result;
872 }
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200873
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100874 /// Import and return a module or throws `error_already_set`.
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200875 static module import(const char *name) {
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100876 PyObject *obj = PyImport_ImportModule(name);
877 if (!obj)
esquires67a68f12016-12-01 05:35:34 -0500878 throw error_already_set();
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200879 return reinterpret_steal<module>(obj);
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200880 }
Jason Rhinelander6873c202016-10-24 21:58:22 -0400881
Gunnar Läthénc64e6b12017-09-12 08:05:05 +0200882 /// Reload the module or throws `error_already_set`.
883 void reload() {
884 PyObject *obj = PyImport_ReloadModule(ptr());
885 if (!obj)
886 throw error_already_set();
887 *this = reinterpret_steal<module>(obj);
888 }
889
Jason Rhinelander6873c202016-10-24 21:58:22 -0400890 // Adds an object to the module using the given name. Throws if an object with the given name
891 // already exists.
892 //
893 // overwrite should almost always be false: attempting to overwrite objects that pybind11 has
894 // established will, in most cases, break things.
Wenzel Jakobaa1b3162017-03-30 11:59:32 +0200895 PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
Jason Rhinelander6873c202016-10-24 21:58:22 -0400896 if (!overwrite && hasattr(*this, name))
897 pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
898 std::string(name) + "\"");
899
Wenzel Jakobaa1b3162017-03-30 11:59:32 +0200900 PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
Jason Rhinelander6873c202016-10-24 21:58:22 -0400901 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200902};
903
Dean Moldovan22c413b2017-03-30 00:20:42 +0200904/// \ingroup python_builtins
Dean Moldovan1d3c4bc2017-06-06 17:05:19 +0200905/// Return a dictionary representing the global variables in the current execution frame,
906/// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
907inline dict globals() {
908 PyObject *p = PyEval_GetGlobals();
909 return reinterpret_borrow<dict>(p ? p : module::import("__main__").attr("__dict__").ptr());
910}
Dean Moldovan22c413b2017-03-30 00:20:42 +0200911
Yannick Jadoulf980d762020-07-09 00:14:41 +0200912PYBIND11_NAMESPACE_BEGIN(detail)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100913/// Generic support for creating new Python heap types
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100914class generic_type : public object {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400915 template <typename...> friend class class_;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200916public:
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100917 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100918protected:
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100919 void initialize(const type_record &rec) {
920 if (rec.scope && hasattr(rec.scope, rec.name))
921 pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
922 "\": an object with that name is already defined");
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200923
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400924 if (rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100925 pybind11_fail("generic_type: type \"" + std::string(rec.name) +
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200926 "\" is already registered!");
927
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100928 m_ptr = make_new_python_type(rec);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200929
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100930 /* Register supplemental type information in C++ dict */
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100931 auto *tinfo = new detail::type_info();
932 tinfo->type = (PyTypeObject *) m_ptr;
Jason Rhinelander1f8a1002017-04-21 19:01:30 -0400933 tinfo->cpptype = rec.type;
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100934 tinfo->type_size = rec.type_size;
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +0100935 tinfo->type_align = rec.type_align;
Dean Moldovan0d765f42017-03-21 01:15:20 +0100936 tinfo->operator_new = rec.operator_new;
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500937 tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
Jason Rhinelander353615f2017-07-25 00:53:23 -0400938 tinfo->init_instance = rec.init_instance;
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100939 tinfo->dealloc = rec.dealloc;
Jason Rhinelander1f8a1002017-04-21 19:01:30 -0400940 tinfo->simple_type = true;
941 tinfo->simple_ancestors = true;
Jason Rhinelander7437c692017-07-28 22:03:44 -0400942 tinfo->default_holder = rec.default_holder;
943 tinfo->module_local = rec.module_local;
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100944
945 auto &internals = get_internals();
946 auto tindex = std::type_index(*rec.type);
Ivan Smirnova6e6a8b2016-10-23 15:27:13 +0100947 tinfo->direct_conversions = &internals.direct_conversions[tindex];
Jason Rhinelander7437c692017-07-28 22:03:44 -0400948 if (rec.module_local)
949 registered_local_types_cpp()[tindex] = tinfo;
950 else
951 internals.registered_types_cpp[tindex] = tinfo;
Jason Rhinelandere45c2112017-02-22 21:36:09 -0500952 internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo };
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100953
Jason Rhinelander1f8a1002017-04-21 19:01:30 -0400954 if (rec.bases.size() > 1 || rec.multiple_inheritance) {
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100955 mark_parents_nonsimple(tinfo->type);
Jason Rhinelander1f8a1002017-04-21 19:01:30 -0400956 tinfo->simple_ancestors = false;
957 }
958 else if (rec.bases.size() == 1) {
959 auto parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
960 tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
961 }
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400962
963 if (rec.module_local) {
964 // Stash the local typeinfo and loader so that external modules can access it.
965 tinfo->module_local_load = &type_caster_generic::local_load;
Dean Moldovan96997a42017-08-20 17:14:09 +0200966 setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
Jason Rhinelander5e14aa62017-08-17 11:38:05 -0400967 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200968 }
969
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900970 /// Helper function which tags all parents of a type using mult. inheritance
971 void mark_parents_nonsimple(PyTypeObject *value) {
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200972 auto t = reinterpret_borrow<tuple>(value->tp_bases);
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900973 for (handle h : t) {
974 auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
975 if (tinfo2)
976 tinfo2->simple_type = false;
977 mark_parents_nonsimple((PyTypeObject *) h.ptr());
978 }
979 }
980
Wenzel Jakob43398a82015-07-28 16:12:20 +0200981 void install_buffer_funcs(
982 buffer_info *(*get_buffer)(PyObject *, void *),
983 void *get_buffer_data) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200984 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100985 auto tinfo = detail::get_type_info(&type->ht_type);
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100986
987 if (!type->ht_type.tp_as_buffer)
988 pybind11_fail(
989 "To be able to register buffer protocol support for the type '" +
990 std::string(tinfo->type->tp_name) +
991 "' the associated class<>(..) invocation must "
992 "include the pybind11::buffer_protocol() annotation!");
993
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100994 tinfo->get_buffer = get_buffer;
995 tinfo->get_buffer_data = get_buffer_data;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200996 }
997
Ted Drain0a0758c2017-11-07 08:35:27 -0800998 // rec_func must be set for either fget or fset.
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100999 void def_property_static_impl(const char *name,
1000 handle fget, handle fset,
Ted Drain0a0758c2017-11-07 08:35:27 -08001001 detail::function_record *rec_func) {
1002 const auto is_static = rec_func && !(rec_func->is_method && rec_func->scope);
1003 const auto has_doc = rec_func && rec_func->doc && pybind11::options::show_user_defined_docstrings();
Dean Moldovanc91f8bd2017-02-13 18:11:24 +01001004 auto property = handle((PyObject *) (is_static ? get_internals().static_property_type
1005 : &PyProperty_Type));
1006 attr(name) = property(fget.ptr() ? fget : none(),
1007 fset.ptr() ? fset : none(),
1008 /*deleter*/none(),
Ted Drain0a0758c2017-11-07 08:35:27 -08001009 pybind11::str(has_doc ? rec_func->doc : ""));
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001010 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001011};
Jason Rhinelander6b52c832016-09-06 12:27:00 -04001012
Dean Moldovan0d765f42017-03-21 01:15:20 +01001013/// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
1014template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator new))>>
1015void set_operator_new(type_record *r) { r->operator_new = &T::operator new; }
1016
1017template <typename> void set_operator_new(...) { }
1018
Jason Rhinelandera03408c2017-07-23 00:32:58 -04001019template <typename T, typename SFINAE = void> struct has_operator_delete : std::false_type { };
1020template <typename T> struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
1021 : std::true_type { };
1022template <typename T, typename SFINAE = void> struct has_operator_delete_size : std::false_type { };
1023template <typename T> struct has_operator_delete_size<T, void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>>
1024 : std::true_type { };
Dean Moldovan0d765f42017-03-21 01:15:20 +01001025/// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
Jason Rhinelandera03408c2017-07-23 00:32:58 -04001026template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001027void call_operator_delete(T *p, size_t, size_t) { T::operator delete(p); }
Jason Rhinelandera03408c2017-07-23 00:32:58 -04001028template <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 +01001029void call_operator_delete(T *p, size_t s, size_t) { T::operator delete(p, s); }
Dean Moldovan0d765f42017-03-21 01:15:20 +01001030
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001031inline void call_operator_delete(void *p, size_t s, size_t a) {
1032 (void)s; (void)a;
Francesco Biscanibd241552019-11-16 01:18:24 +01001033 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
Jeremy Nimmer759221f2019-06-14 12:12:51 -04001034 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1035 #ifdef __cpp_sized_deallocation
1036 ::operator delete(p, s, std::align_val_t(a));
1037 #else
1038 ::operator delete(p, std::align_val_t(a));
1039 #endif
1040 return;
1041 }
1042 #endif
1043 #ifdef __cpp_sized_deallocation
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001044 ::operator delete(p, s);
Jeremy Nimmer759221f2019-06-14 12:12:51 -04001045 #else
1046 ::operator delete(p);
1047 #endif
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001048}
Dean Moldovan0d765f42017-03-21 01:15:20 +01001049
Yannick Jadoulf980d762020-07-09 00:14:41 +02001050PYBIND11_NAMESPACE_END(detail)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001051
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001052/// Given a pointer to a member function, cast it to its `Derived` version.
1053/// Forward everything else unchanged.
1054template <typename /*Derived*/, typename F>
1055auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) { return std::forward<F>(f); }
1056
1057template <typename Derived, typename Return, typename Class, typename... Args>
Jason Rhinelander76722922017-10-03 10:09:49 -03001058auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
1059 static_assert(detail::is_accessible_base_of<Class, Derived>::value,
1060 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1061 return pmf;
1062}
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001063
1064template <typename Derived, typename Return, typename Class, typename... Args>
Jason Rhinelander76722922017-10-03 10:09:49 -03001065auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
1066 static_assert(detail::is_accessible_base_of<Class, Derived>::value,
1067 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1068 return pmf;
1069}
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001070
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001071template <typename type_, typename... options>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001072class class_ : public detail::generic_type {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001073 template <typename T> using is_holder = detail::is_holder_type<type_, T>;
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001074 template <typename T> using is_subtype = detail::is_strict_base_of<type_, T>;
1075 template <typename T> using is_base = detail::is_strict_base_of<T, type_>;
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -05001076 // struct instead of using here to help MSVC:
1077 template <typename T> struct is_valid_class_option :
1078 detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001079
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001080public:
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001081 using type = type_;
Dean Moldovan82ece942017-03-29 11:55:18 +02001082 using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001083 constexpr static bool has_alias = !std::is_void<type_alias>::value;
Dean Moldovan82ece942017-03-29 11:55:18 +02001084 using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001085
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -05001086 static_assert(detail::all_of<is_valid_class_option<options>...>::value,
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001087 "Unknown/invalid class_ template parameters provided");
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001088
Jason Rhinelander42e5ddc2017-06-12 21:48:36 -04001089 static_assert(!has_alias || std::is_polymorphic<type>::value,
1090 "Cannot use an alias class with a non-polymorphic type");
1091
Dean Moldovanc7ac16b2016-10-28 03:08:15 +02001092 PYBIND11_OBJECT(class_, generic_type, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001093
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001094 template <typename... Extra>
1095 class_(handle scope, const char *name, const Extra &... extra) {
Jason Rhinelanderb9616262017-03-16 20:10:48 -03001096 using namespace detail;
1097
1098 // MI can only be specified via class_ template options, not constructor parameters
1099 static_assert(
1100 none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
1101 ( constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
1102 constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
1103 none_of<std::is_same<multiple_inheritance, Extra>...>::value), // no multiple_inheritance attr
1104 "Error: multiple inheritance bases must be specified via class_ template options");
1105
1106 type_record record;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001107 record.scope = scope;
1108 record.name = name;
1109 record.type = &typeid(type);
Jason Rhinelanderb9616262017-03-16 20:10:48 -03001110 record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001111 record.type_align = alignof(conditional_t<has_alias, type_alias, type>&);
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001112 record.holder_size = sizeof(holder_type);
Jason Rhinelander353615f2017-07-25 00:53:23 -04001113 record.init_instance = init_instance;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001114 record.dealloc = dealloc;
Trevor Laughlin63c2a972018-11-11 13:36:55 -05001115 record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001116
Dean Moldovan0d765f42017-03-21 01:15:20 +01001117 set_operator_new<type>(&record);
1118
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001119 /* Register base classes specified via template arguments to class_, if any */
Jason Rhinelander926e2cf2017-03-25 22:41:06 -03001120 PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
Jason Rhinelander6b52c832016-09-06 12:27:00 -04001121
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001122 /* Process optional arguments, if any */
Jason Rhinelanderb9616262017-03-16 20:10:48 -03001123 process_attributes<Extra...>::init(extra..., &record);
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001124
Jason Rhinelanderb9616262017-03-16 20:10:48 -03001125 generic_type::initialize(record);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001126
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001127 if (has_alias) {
Jason Rhinelander7437c692017-07-28 22:03:44 -04001128 auto &instances = record.module_local ? registered_local_types_cpp() : get_internals().registered_types_cpp;
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001129 instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
1130 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001131 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001132
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +09001133 template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001134 static void add_base(detail::type_record &rec) {
Jason Rhinelander21966962017-06-21 13:38:10 -04001135 rec.add_base(typeid(Base), [](void *src) -> void * {
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001136 return static_cast<Base *>(reinterpret_cast<type *>(src));
1137 });
1138 }
1139
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +09001140 template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001141 static void add_base(detail::type_record &) { }
1142
Wenzel Jakob71867832015-07-29 17:43:52 +02001143 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001144 class_ &def(const char *name_, Func&& f, const Extra&... extra) {
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001145 cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), name(name_), is_method(*this),
Dean Moldovan865e4302016-09-21 01:06:32 +02001146 sibling(getattr(*this, name_, none())), extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +02001147 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001148 return *this;
1149 }
1150
Wenzel Jakob71867832015-07-29 17:43:52 +02001151 template <typename Func, typename... Extra> class_ &
Jason Rhinelander139a0822017-03-12 17:59:07 -03001152 def_static(const char *name_, Func &&f, const Extra&... extra) {
1153 static_assert(!std::is_member_function_pointer<Func>::value,
1154 "def_static(...) called with a non-static member function pointer");
Dean Moldovan865e4302016-09-21 01:06:32 +02001155 cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
1156 sibling(getattr(*this, name_, none())), extra...);
Yannick Jadould23c8212019-06-11 10:59:57 +02001157 attr(cf.name()) = staticmethod(cf);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001158 return *this;
1159 }
1160
Wenzel Jakob71867832015-07-29 17:43:52 +02001161 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001162 class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001163 op.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001164 return *this;
1165 }
1166
Wenzel Jakob71867832015-07-29 17:43:52 +02001167 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001168 class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001169 op.execute_cast(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001170 return *this;
1171 }
1172
Wenzel Jakob71867832015-07-29 17:43:52 +02001173 template <typename... Args, typename... Extra>
Jason Rhinelanderc4e18002017-08-17 00:01:42 -04001174 class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001175 init.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001176 return *this;
1177 }
1178
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001179 template <typename... Args, typename... Extra>
Jason Rhinelanderc4e18002017-08-17 00:01:42 -04001180 class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001181 init.execute(*this, extra...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001182 return *this;
1183 }
1184
Jason Rhinelander464d9892017-06-12 21:52:48 -04001185 template <typename... Args, typename... Extra>
1186 class_ &def(detail::initimpl::factory<Args...> &&init, const Extra&... extra) {
1187 std::move(init).execute(*this, extra...);
1188 return *this;
1189 }
1190
Dean Moldovan1e5a7da2017-08-24 01:53:15 +02001191 template <typename... Args, typename... Extra>
1192 class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
1193 std::move(pf).execute(*this, extra...);
1194 return *this;
1195 }
1196
Wenzel Jakob71867832015-07-29 17:43:52 +02001197 template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob43398a82015-07-28 16:12:20 +02001198 struct capture { Func func; };
1199 capture *ptr = new capture { std::forward<Func>(func) };
1200 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Dean Moldovan5f07fac2017-01-03 11:52:05 +01001201 detail::make_caster<type> caster;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001202 if (!caster.load(obj, false))
1203 return nullptr;
Wenzel Jakob43398a82015-07-28 16:12:20 +02001204 return new buffer_info(((capture *) ptr)->func(caster));
1205 }, ptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001206 return *this;
1207 }
1208
Bruce Merryfe0cf8b2017-05-17 10:52:33 +02001209 template <typename Return, typename Class, typename... Args>
1210 class_ &def_buffer(Return (Class::*func)(Args...)) {
1211 return def_buffer([func] (type &obj) { return (obj.*func)(); });
1212 }
1213
1214 template <typename Return, typename Class, typename... Args>
1215 class_ &def_buffer(Return (Class::*func)(Args...) const) {
1216 return def_buffer([func] (const type &obj) { return (obj.*func)(); });
1217 }
1218
Wenzel Jakob71867832015-07-29 17:43:52 +02001219 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001220 class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
Roland Dreier1aa8dd12019-06-11 13:25:12 -07001221 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 -04001222 cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this)),
1223 fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
Wenzel Jakob0b489582016-03-25 16:13:10 +01001224 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001225 return *this;
1226 }
1227
Wenzel Jakob71867832015-07-29 17:43:52 +02001228 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001229 class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
Roland Dreier1aa8dd12019-06-11 13:25:12 -07001230 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 -04001231 cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this));
Wenzel Jakob0b489582016-03-25 16:13:10 +01001232 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001233 return *this;
1234 }
1235
Wenzel Jakob71867832015-07-29 17:43:52 +02001236 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001237 class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001238 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
1239 fset([pm](object, const D &value) { *pm = value; }, scope(*this));
1240 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001241 return *this;
1242 }
1243
Wenzel Jakob71867832015-07-29 17:43:52 +02001244 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001245 class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001246 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
1247 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001248 return *this;
1249 }
1250
Dean Moldovan03f627e2016-11-01 11:44:57 +01001251 /// Uses return_value_policy::reference_internal by default
1252 template <typename Getter, typename... Extra>
1253 class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001254 return def_property_readonly(name, cpp_function(method_adaptor<type>(fget)),
1255 return_value_policy::reference_internal, extra...);
Dean Moldovan03f627e2016-11-01 11:44:57 +01001256 }
1257
1258 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001259 template <typename... Extra>
1260 class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
Ted Drain0a0758c2017-11-07 08:35:27 -08001261 return def_property(name, fget, nullptr, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001262 }
1263
Dean Moldovan03f627e2016-11-01 11:44:57 +01001264 /// Uses return_value_policy::reference by default
1265 template <typename Getter, typename... Extra>
1266 class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
1267 return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...);
1268 }
1269
1270 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001271 template <typename... Extra>
1272 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
Ted Drain0a0758c2017-11-07 08:35:27 -08001273 return def_property_static(name, fget, nullptr, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001274 }
1275
Dean Moldovan03f627e2016-11-01 11:44:57 +01001276 /// Uses return_value_policy::reference_internal by default
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001277 template <typename Getter, typename Setter, typename... Extra>
1278 class_ &def_property(const char *name, const Getter &fget, const Setter &fset, const Extra& ...extra) {
1279 return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
1280 }
Dean Moldovan03f627e2016-11-01 11:44:57 +01001281 template <typename Getter, typename... Extra>
1282 class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
Jason Rhinelander23bf8942017-05-16 11:07:28 -04001283 return def_property(name, cpp_function(method_adaptor<type>(fget)), fset,
1284 return_value_policy::reference_internal, extra...);
Dean Moldovan03f627e2016-11-01 11:44:57 +01001285 }
1286
1287 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001288 template <typename... Extra>
1289 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001290 return def_property_static(name, fget, fset, is_method(*this), extra...);
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001291 }
1292
Dean Moldovan03f627e2016-11-01 11:44:57 +01001293 /// Uses return_value_policy::reference by default
1294 template <typename Getter, typename... Extra>
1295 class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1296 return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1297 }
1298
1299 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001300 template <typename... Extra>
1301 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 -04001302 static_assert( 0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
1303 "Argument annotations are not allowed for properties");
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001304 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
Ted Drain0a0758c2017-11-07 08:35:27 -08001305 auto *rec_active = rec_fget;
1306 if (rec_fget) {
1307 char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
1308 detail::process_attributes<Extra...>::init(extra..., rec_fget);
1309 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1310 free(doc_prev);
1311 rec_fget->doc = strdup(rec_fget->doc);
1312 }
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001313 }
1314 if (rec_fset) {
Ted Drain0a0758c2017-11-07 08:35:27 -08001315 char *doc_prev = rec_fset->doc;
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001316 detail::process_attributes<Extra...>::init(extra..., rec_fset);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001317 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1318 free(doc_prev);
1319 rec_fset->doc = strdup(rec_fset->doc);
1320 }
Ted Drain0a0758c2017-11-07 08:35:27 -08001321 if (! rec_active) rec_active = rec_fset;
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001322 }
Ted Drain0a0758c2017-11-07 08:35:27 -08001323 def_property_static_impl(name, fget, fset, rec_active);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001324 return *this;
1325 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001326
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001327private:
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001328 /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1329 template <typename T>
Jason Rhinelander353615f2017-07-25 00:53:23 -04001330 static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001331 const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001332 try {
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001333 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1334 v_h.value_ptr<type>()->shared_from_this());
Jason Rhinelanderb8ac4382017-05-19 13:34:55 -04001335 if (sh) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001336 new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001337 v_h.set_holder_constructed();
Dean Moldovanab90ec62016-12-07 02:36:44 +01001338 }
Jason Rhinelanderb8ac4382017-05-19 13:34:55 -04001339 } catch (const std::bad_weak_ptr &) {}
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001340
1341 if (!v_h.holder_constructed() && inst->owned) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001342 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001343 v_h.set_holder_constructed();
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001344 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001345 }
1346
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001347 static void init_holder_from_existing(const detail::value_and_holder &v_h,
1348 const holder_type *holder_ptr, std::true_type /*is_copy_constructible*/) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001349 new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001350 }
1351
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001352 static void init_holder_from_existing(const detail::value_and_holder &v_h,
1353 const holder_type *holder_ptr, std::false_type /*is_copy_constructible*/) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001354 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 +01001355 }
1356
1357 /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
Jason Rhinelander353615f2017-07-25 00:53:23 -04001358 static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001359 const holder_type *holder_ptr, const void * /* dummy -- not enable_shared_from_this<T>) */) {
Dean Moldovanec009a72017-01-31 17:05:44 +01001360 if (holder_ptr) {
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001361 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1362 v_h.set_holder_constructed();
Dean Moldovanec009a72017-01-31 17:05:44 +01001363 } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
Khachajantc Michaele3cb2a62018-06-20 18:33:50 +03001364 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001365 v_h.set_holder_constructed();
Jason Rhinelanderc07ec312016-11-06 13:12:48 -05001366 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001367 }
1368
Jason Rhinelander353615f2017-07-25 00:53:23 -04001369 /// Performs instance initialization including constructing a holder and registering the known
1370 /// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes an
1371 /// optional pointer to an existing holder to use; if not specified and the instance is
1372 /// `.owned`, a new holder will be constructed to manage the value pointer.
1373 static void init_instance(detail::instance *inst, const void *holder_ptr) {
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001374 auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
Jason Rhinelandercca20a72017-07-29 03:56:01 -04001375 if (!v_h.instance_registered()) {
1376 register_instance(inst, v_h.value_ptr(), v_h.type);
1377 v_h.set_instance_registered();
1378 }
Jason Rhinelander353615f2017-07-25 00:53:23 -04001379 init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001380 }
1381
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001382 /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
Jason Rhinelander464d9892017-06-12 21:52:48 -04001383 static void dealloc(detail::value_and_holder &v_h) {
1384 if (v_h.holder_constructed()) {
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001385 v_h.holder<holder_type>().~holder_type();
Jason Rhinelander464d9892017-06-12 21:52:48 -04001386 v_h.set_holder_constructed(false);
1387 }
1388 else {
Wenzel Jakobe2eca4f2018-11-09 20:14:53 +01001389 detail::call_operator_delete(v_h.value_ptr<type>(),
1390 v_h.type->type_size,
1391 v_h.type->type_align
1392 );
Jason Rhinelander464d9892017-06-12 21:52:48 -04001393 }
1394 v_h.value_ptr() = nullptr;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001395 }
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001396
1397 static detail::function_record *get_function_record(handle h) {
1398 h = detail::get_function(h);
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001399 return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
Dean Moldovanc7ac16b2016-10-28 03:08:15 +02001400 : nullptr;
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001401 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001402};
1403
Dean Moldovan68986792017-08-30 23:40:55 +02001404/// Binds an existing constructor taking arguments Args...
1405template <typename... Args> detail::initimpl::constructor<Args...> init() { return {}; }
1406/// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
1407/// when not inheriting on the Python side).
1408template <typename... Args> detail::initimpl::alias_constructor<Args...> init_alias() { return {}; }
1409
1410/// Binds a factory function as a constructor
1411template <typename Func, typename Ret = detail::initimpl::factory<Func>>
1412Ret init(Func &&f) { return {std::forward<Func>(f)}; }
1413
1414/// Dual-argument factory function: the first function is called when no alias is needed, the second
1415/// when an alias is needed (i.e. due to python-side inheritance). Arguments must be identical.
1416template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1417Ret init(CFunc &&c, AFunc &&a) {
1418 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1419}
1420
1421/// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
1422/// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
1423template <typename GetState, typename SetState>
1424detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
1425 return {std::forward<GetState>(g), std::forward<SetState>(s)};
Marcin Wojdyrfbab29c2017-09-04 18:37:16 +01001426}
Dean Moldovan68986792017-08-30 23:40:55 +02001427
Yannick Jadoulf980d762020-07-09 00:14:41 +02001428PYBIND11_NAMESPACE_BEGIN(detail)
Wenzel Jakobf4245182018-09-01 01:20:24 +02001429struct enum_base {
1430 enum_base(handle base, handle parent) : m_base(base), m_parent(parent) { }
1431
1432 PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
1433 m_base.attr("__entries") = dict();
1434 auto property = handle((PyObject *) &PyProperty_Type);
1435 auto static_property = handle((PyObject *) get_internals().static_property_type);
1436
1437 m_base.attr("__repr__") = cpp_function(
1438 [](handle arg) -> str {
1439 handle type = arg.get_type();
1440 object type_name = type.attr("__name__");
1441 dict entries = type.attr("__entries");
1442 for (const auto &kv : entries) {
1443 object other = kv.second[int_(0)];
1444 if (other.equal(arg))
1445 return pybind11::str("{}.{}").format(type_name, kv.first);
1446 }
1447 return pybind11::str("{}.???").format(type_name);
Yannick Jadoul805c5862020-01-25 23:38:01 +01001448 }, name("__repr__"), is_method(m_base)
Wenzel Jakobf4245182018-09-01 01:20:24 +02001449 );
1450
1451 m_base.attr("name") = property(cpp_function(
1452 [](handle arg) -> str {
1453 dict entries = arg.get_type().attr("__entries");
1454 for (const auto &kv : entries) {
1455 if (handle(kv.second[int_(0)]).equal(arg))
1456 return pybind11::str(kv.first);
1457 }
1458 return "???";
Yannick Jadoul805c5862020-01-25 23:38:01 +01001459 }, name("name"), is_method(m_base)
Wenzel Jakobf4245182018-09-01 01:20:24 +02001460 ));
1461
1462 m_base.attr("__doc__") = static_property(cpp_function(
1463 [](handle arg) -> std::string {
1464 std::string docstring;
1465 dict entries = arg.attr("__entries");
1466 if (((PyTypeObject *) arg.ptr())->tp_doc)
1467 docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) + "\n\n";
1468 docstring += "Members:";
1469 for (const auto &kv : entries) {
1470 auto key = std::string(pybind11::str(kv.first));
1471 auto comment = kv.second[int_(1)];
1472 docstring += "\n\n " + key;
1473 if (!comment.is_none())
1474 docstring += " : " + (std::string) pybind11::str(comment);
1475 }
1476 return docstring;
Yannick Jadoul805c5862020-01-25 23:38:01 +01001477 }, name("__doc__")
Wenzel Jakobf4245182018-09-01 01:20:24 +02001478 ), none(), none(), "");
1479
1480 m_base.attr("__members__") = static_property(cpp_function(
1481 [](handle arg) -> dict {
1482 dict entries = arg.attr("__entries"), m;
1483 for (const auto &kv : entries)
1484 m[kv.first] = kv.second[int_(0)];
1485 return m;
Yannick Jadoul805c5862020-01-25 23:38:01 +01001486 }, name("__members__")), none(), none(), ""
Wenzel Jakobf4245182018-09-01 01:20:24 +02001487 );
1488
Tarcísio Fischer54eb8192018-10-24 06:18:58 -03001489 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
Wenzel Jakobf4245182018-09-01 01:20:24 +02001490 m_base.attr(op) = cpp_function( \
1491 [](object a, object b) { \
1492 if (!a.get_type().is(b.get_type())) \
Tarcísio Fischer54eb8192018-10-24 06:18:58 -03001493 strict_behavior; \
Wenzel Jakobf4245182018-09-01 01:20:24 +02001494 return expr; \
1495 }, \
Yannick Jadoul805c5862020-01-25 23:38:01 +01001496 name(op), is_method(m_base))
Wenzel Jakobf4245182018-09-01 01:20:24 +02001497
1498 #define PYBIND11_ENUM_OP_CONV(op, expr) \
1499 m_base.attr(op) = cpp_function( \
1500 [](object a_, object b_) { \
1501 int_ a(a_), b(b_); \
1502 return expr; \
1503 }, \
Yannick Jadoul805c5862020-01-25 23:38:01 +01001504 name(op), is_method(m_base))
Wenzel Jakobf4245182018-09-01 01:20:24 +02001505
Sergei Izmailov09f08292019-09-19 19:23:27 +03001506 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
1507 m_base.attr(op) = cpp_function( \
1508 [](object a_, object b) { \
1509 int_ a(a_); \
1510 return expr; \
1511 }, \
Yannick Jadoul805c5862020-01-25 23:38:01 +01001512 name(op), is_method(m_base))
Sergei Izmailov09f08292019-09-19 19:23:27 +03001513
Wenzel Jakobf4245182018-09-01 01:20:24 +02001514 if (is_convertible) {
Sergei Izmailov09f08292019-09-19 19:23:27 +03001515 PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
1516 PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
Wenzel Jakobf4245182018-09-01 01:20:24 +02001517
1518 if (is_arithmetic) {
1519 PYBIND11_ENUM_OP_CONV("__lt__", a < b);
1520 PYBIND11_ENUM_OP_CONV("__gt__", a > b);
1521 PYBIND11_ENUM_OP_CONV("__le__", a <= b);
1522 PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
1523 PYBIND11_ENUM_OP_CONV("__and__", a & b);
1524 PYBIND11_ENUM_OP_CONV("__rand__", a & b);
1525 PYBIND11_ENUM_OP_CONV("__or__", a | b);
1526 PYBIND11_ENUM_OP_CONV("__ror__", a | b);
1527 PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
1528 PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
Lori A. Burnsf6c4c102019-09-04 16:16:21 -04001529 m_base.attr("__invert__") = cpp_function(
Yannick Jadoul805c5862020-01-25 23:38:01 +01001530 [](object arg) { return ~(int_(arg)); }, name("__invert__"), is_method(m_base));
Wenzel Jakobf4245182018-09-01 01:20:24 +02001531 }
1532 } else {
Tarcísio Fischer54eb8192018-10-24 06:18:58 -03001533 PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
1534 PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
Wenzel Jakobf4245182018-09-01 01:20:24 +02001535
1536 if (is_arithmetic) {
Michał Wawrzyniec Urbańczyk978d4392018-11-03 13:20:08 +01001537 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
1538 PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
1539 PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
1540 PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
1541 PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
1542 #undef PYBIND11_THROW
Wenzel Jakobf4245182018-09-01 01:20:24 +02001543 }
1544 }
1545
Sergei Izmailov09f08292019-09-19 19:23:27 +03001546 #undef PYBIND11_ENUM_OP_CONV_LHS
Wenzel Jakobf4245182018-09-01 01:20:24 +02001547 #undef PYBIND11_ENUM_OP_CONV
1548 #undef PYBIND11_ENUM_OP_STRICT
1549
Yannick Jadoul805c5862020-01-25 23:38:01 +01001550 m_base.attr("__getstate__") = cpp_function(
1551 [](object arg) { return int_(arg); }, name("__getstate__"), is_method(m_base));
Wenzel Jakobf4245182018-09-01 01:20:24 +02001552
Yannick Jadoul805c5862020-01-25 23:38:01 +01001553 m_base.attr("__hash__") = cpp_function(
1554 [](object arg) { return int_(arg); }, name("__hash__"), is_method(m_base));
Wenzel Jakobf4245182018-09-01 01:20:24 +02001555 }
1556
1557 PYBIND11_NOINLINE void value(char const* name_, object value, const char *doc = nullptr) {
1558 dict entries = m_base.attr("__entries");
1559 str name(name_);
1560 if (entries.contains(name)) {
1561 std::string type_name = (std::string) str(m_base.attr("__name__"));
1562 throw value_error(type_name + ": element \"" + std::string(name_) + "\" already exists!");
1563 }
1564
1565 entries[name] = std::make_pair(value, doc);
1566 m_base.attr(name) = value;
1567 }
1568
1569 PYBIND11_NOINLINE void export_values() {
1570 dict entries = m_base.attr("__entries");
1571 for (const auto &kv : entries)
1572 m_parent.attr(kv.first) = kv.second[int_(0)];
1573 }
1574
1575 handle m_base;
1576 handle m_parent;
1577};
1578
Yannick Jadoulf980d762020-07-09 00:14:41 +02001579PYBIND11_NAMESPACE_END(detail)
Wenzel Jakobf4245182018-09-01 01:20:24 +02001580
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001581/// Binds C++ enumerations and enumeration classes to Python
1582template <typename Type> class enum_ : public class_<Type> {
1583public:
Wenzel Jakobc8e9f3c2018-09-14 12:07:47 +02001584 using Base = class_<Type>;
1585 using Base::def;
1586 using Base::attr;
1587 using Base::def_property_readonly;
1588 using Base::def_property_readonly_static;
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001589 using Scalar = typename std::underlying_type<Type>::type;
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001590
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001591 template <typename... Extra>
1592 enum_(const handle &scope, const char *name, const Extra&... extra)
Wenzel Jakobf4245182018-09-01 01:20:24 +02001593 : class_<Type>(scope, name, extra...), m_base(*this, scope) {
Dean Moldovan82ece942017-03-29 11:55:18 +02001594 constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
Wenzel Jakobf4245182018-09-01 01:20:24 +02001595 constexpr bool is_convertible = std::is_convertible<Type, Scalar>::value;
1596 m_base.init(is_arithmetic, is_convertible);
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001597
Dean Moldovan68986792017-08-30 23:40:55 +02001598 def(init([](Scalar i) { return static_cast<Type>(i); }));
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001599 def("__int__", [](Type value) { return (Scalar) value; });
Wenzel Jakobe6fd2cd2017-04-28 14:46:52 +02001600 #if PY_MAJOR_VERSION < 3
1601 def("__long__", [](Type value) { return (Scalar) value; });
1602 #endif
Wenzel Jakobf3109d82019-09-21 18:09:35 +02001603 #if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 8)
Wenzel Jakob31680e62019-09-20 11:06:10 +02001604 def("__index__", [](Type value) { return (Scalar) value; });
1605 #endif
1606
Yannick Jadoul805c5862020-01-25 23:38:01 +01001607 attr("__setstate__") = cpp_function(
1608 [](detail::value_and_holder &v_h, Scalar arg) {
1609 detail::initimpl::setstate<Base>(v_h, static_cast<Type>(arg),
1610 Py_TYPE(v_h.inst) != v_h.type->type); },
1611 detail::is_new_style_constructor(),
1612 pybind11::name("__setstate__"), is_method(*this));
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001613 }
1614
1615 /// Export enumeration entries into the parent scope
Matthieu Becaf936e12017-03-03 08:45:50 -08001616 enum_& export_values() {
Wenzel Jakobf4245182018-09-01 01:20:24 +02001617 m_base.export_values();
Wenzel Jakobe916d842016-11-04 16:51:14 +01001618 return *this;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001619 }
1620
1621 /// Add an enumeration entry
Wenzel Jakob6d190362017-11-16 22:24:36 +01001622 enum_& value(char const* name, Type value, const char *doc = nullptr) {
Wenzel Jakobf4245182018-09-01 01:20:24 +02001623 m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001624 return *this;
1625 }
Matthieu Becaf936e12017-03-03 08:45:50 -08001626
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001627private:
Wenzel Jakobf4245182018-09-01 01:20:24 +02001628 detail::enum_base m_base;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001629};
1630
Yannick Jadoulf980d762020-07-09 00:14:41 +02001631PYBIND11_NAMESPACE_BEGIN(detail)
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001632
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001633
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001634inline void keep_alive_impl(handle nurse, handle patient) {
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001635 if (!nurse || !patient)
Wenzel Jakob678d7872016-01-17 22:36:41 +01001636 pybind11_fail("Could not activate keep_alive!");
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001637
Ivan Smirnov984c7622016-08-29 02:38:47 +01001638 if (patient.is_none() || nurse.is_none())
Glen Walkerf45bb582016-08-16 17:50:43 +12001639 return; /* Nothing to keep alive or nothing to be kept alive by */
Wenzel Jakob9b880ba2016-04-25 03:25:13 +02001640
Bruce Merry9d698f72017-06-24 14:58:42 +02001641 auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
1642 if (!tinfo.empty()) {
1643 /* It's a pybind-registered type, so we can store the patient in the
1644 * internal list. */
1645 add_patient(nurse.ptr(), patient.ptr());
1646 }
1647 else {
1648 /* Fall back to clever approach based on weak references taken from
1649 * Boost.Python. This is not used for pybind-registered types because
1650 * the objects can be destroyed out-of-order in a GC pass. */
1651 cpp_function disable_lifesupport(
1652 [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001653
Bruce Merry9d698f72017-06-24 14:58:42 +02001654 weakref wr(nurse, disable_lifesupport);
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001655
Bruce Merry9d698f72017-06-24 14:58:42 +02001656 patient.inc_ref(); /* reference patient and leak the weak reference */
1657 (void) wr.release();
1658 }
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001659}
1660
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -05001661PYBIND11_NOINLINE inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
Dean Moldovan7939f4b2017-09-04 13:49:19 +02001662 auto get_arg = [&](size_t n) {
1663 if (n == 0)
1664 return ret;
1665 else if (n == 1 && call.init_self)
1666 return call.init_self;
1667 else if (n <= call.args.size())
1668 return call.args[n - 1];
1669 return handle();
1670 };
1671
1672 keep_alive_impl(get_arg(Nurse), get_arg(Patient));
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001673}
1674
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001675inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type) {
1676 auto res = get_internals().registered_types_py
Jason Rhinelander12be4cd2017-07-29 03:53:45 -04001677#ifdef __cpp_lib_unordered_map_try_emplace
Jason Rhinelandere45c2112017-02-22 21:36:09 -05001678 .try_emplace(type);
1679#else
1680 .emplace(type, std::vector<detail::type_info *>());
1681#endif
1682 if (res.second) {
1683 // New cache entry created; set up a weak reference to automatically remove it if the type
1684 // gets destroyed:
1685 weakref((PyObject *) type, cpp_function([type](handle wr) {
1686 get_internals().registered_types_py.erase(type);
1687 wr.dec_ref();
1688 })).release();
1689 }
1690
1691 return res;
1692}
1693
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001694template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001695struct iterator_state {
1696 Iterator it;
1697 Sentinel end;
Dean Moldovancaedf742017-06-09 16:49:04 +02001698 bool first_or_done;
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001699};
Wenzel Jakobb2825952016-04-13 23:33:00 +02001700
Yannick Jadoulf980d762020-07-09 00:14:41 +02001701PYBIND11_NAMESPACE_END(detail)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001702
Jason Rhinelander3d591e82017-03-18 13:34:21 -03001703/// Makes a python iterator from a first and past-the-end C++ 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,
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001707 typename ValueType = decltype(*std::declval<Iterator>()),
1708 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001709iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001710 typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001711
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())
Wenzel Jakobb2825952016-04-13 23:33:00 +02001714 .def("__iter__", [](state &s) -> state& { return s; })
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001715 .def("__next__", [](state &s) -> ValueType {
Dean Moldovancaedf742017-06-09 16:49:04 +02001716 if (!s.first_or_done)
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001717 ++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;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001722 throw stop_iteration();
Dean Moldovancaedf742017-06-09 16:49:04 +02001723 }
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001724 return *s.it;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001725 }, std::forward<Extra>(extra)..., Policy);
Wenzel Jakobb2825952016-04-13 23:33:00 +02001726 }
1727
Dean Moldovancaedf742017-06-09 16:49:04 +02001728 return cast(state{first, last, true});
Wenzel Jakobb2825952016-04-13 23:33:00 +02001729}
Wenzel Jakob146397e2016-09-06 13:06:31 +09001730
Jason Rhinelander3d591e82017-03-18 13:34:21 -03001731/// Makes an python iterator over the keys (`.first`) of a iterator over pairs from a
1732/// first and past-the-end InputIterator.
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001733template <return_value_policy Policy = return_value_policy::reference_internal,
1734 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001735 typename Sentinel,
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001736 typename KeyType = decltype((*std::declval<Iterator>()).first),
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001737 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001738iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001739 typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001740
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001741 if (!detail::get_type_info(typeid(state), false)) {
Jason Rhinelander7437c692017-07-28 22:03:44 -04001742 class_<state>(handle(), "iterator", pybind11::module_local())
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001743 .def("__iter__", [](state &s) -> state& { return s; })
1744 .def("__next__", [](state &s) -> KeyType {
Dean Moldovancaedf742017-06-09 16:49:04 +02001745 if (!s.first_or_done)
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001746 ++s.it;
1747 else
Dean Moldovancaedf742017-06-09 16:49:04 +02001748 s.first_or_done = false;
1749 if (s.it == s.end) {
1750 s.first_or_done = true;
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001751 throw stop_iteration();
Dean Moldovancaedf742017-06-09 16:49:04 +02001752 }
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001753 return (*s.it).first;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001754 }, std::forward<Extra>(extra)..., Policy);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001755 }
1756
Dean Moldovancaedf742017-06-09 16:49:04 +02001757 return cast(state{first, last, true});
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001758}
Wenzel Jakobb2825952016-04-13 23:33:00 +02001759
Jason Rhinelander3d591e82017-03-18 13:34:21 -03001760/// Makes an iterator over values of an stl container or other container supporting
1761/// `std::begin()`/`std::end()`
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001762template <return_value_policy Policy = return_value_policy::reference_internal,
1763 typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
1764 return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
Wenzel Jakobbf0c7dc2016-04-18 10:52:12 +02001765}
1766
Jason Rhinelander3d591e82017-03-18 13:34:21 -03001767/// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
1768/// `std::begin()`/`std::end()`
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001769template <return_value_policy Policy = return_value_policy::reference_internal,
1770 typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
1771 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001772}
1773
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001774template <typename InputType, typename OutputType> void implicitly_convertible() {
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +02001775 struct set_flag {
1776 bool &flag;
1777 set_flag(bool &flag) : flag(flag) { flag = true; }
1778 ~set_flag() { flag = false; }
1779 };
Wenzel Jakob2ac50442016-01-17 22:36:35 +01001780 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
Wenzel Jakob8ed5b8a2017-08-28 16:34:06 +02001781 static bool currently_used = false;
1782 if (currently_used) // implicit conversions are non-reentrant
1783 return nullptr;
1784 set_flag flag_helper(currently_used);
Dean Moldovan5f07fac2017-01-03 11:52:05 +01001785 if (!detail::make_caster<InputType>().load(obj, false))
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001786 return nullptr;
1787 tuple args(1);
1788 args[0] = obj;
1789 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1790 if (result == nullptr)
1791 PyErr_Clear();
1792 return result;
1793 };
Ivan Smirnov8f3e0452016-10-23 15:43:03 +01001794
1795 if (auto tinfo = detail::get_type_info(typeid(OutputType)))
1796 tinfo->implicit_conversions.push_back(implicit_caster);
1797 else
Wenzel Jakob678d7872016-01-17 22:36:41 +01001798 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001799}
1800
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001801template <typename ExceptionTranslator>
1802void register_exception_translator(ExceptionTranslator&& translator) {
1803 detail::get_internals().registered_exception_translators.push_front(
1804 std::forward<ExceptionTranslator>(translator));
1805}
1806
Jason Rhinelander37b23832017-05-22 12:06:16 -04001807/**
1808 * Wrapper to generate a new Python exception type.
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001809 *
1810 * This should only be used with PyErr_SetString for now.
1811 * It is not (yet) possible to use as a py::base.
1812 * Template type argument is reserved for future use.
1813 */
1814template <typename type>
1815class exception : public object {
1816public:
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001817 exception() = default;
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001818 exception(handle scope, const char *name, PyObject *base = PyExc_Exception) {
1819 std::string full_name = scope.attr("__name__").cast<std::string>() +
1820 std::string(".") + name;
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -05001821 m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base, NULL);
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001822 if (hasattr(scope, name))
1823 pybind11_fail("Error during initialization: multiple incompatible "
1824 "definitions with name \"" + std::string(name) + "\"");
1825 scope.attr(name) = *this;
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001826 }
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001827
1828 // Sets the current python exception to this exception object with the given message
1829 void operator()(const char *message) {
1830 PyErr_SetString(m_ptr, message);
1831 }
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001832};
1833
Yannick Jadoulf980d762020-07-09 00:14:41 +02001834PYBIND11_NAMESPACE_BEGIN(detail)
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001835// Returns a reference to a function-local static exception object used in the simple
1836// register_exception approach below. (It would be simpler to have the static local variable
1837// directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
1838template <typename CppException>
1839exception<CppException> &get_exception_object() { static exception<CppException> ex; return ex; }
Yannick Jadoulf980d762020-07-09 00:14:41 +02001840PYBIND11_NAMESPACE_END(detail)
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001841
Jason Rhinelander37b23832017-05-22 12:06:16 -04001842/**
1843 * Registers a Python exception in `m` of the given `name` and installs an exception translator to
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001844 * translate the C++ exception to the created Python exception using the exceptions what() method.
1845 * This is intended for simple exception translations; for more complex translation, register the
1846 * exception object and translator directly.
1847 */
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001848template <typename CppException>
1849exception<CppException> &register_exception(handle scope,
1850 const char *name,
1851 PyObject *base = PyExc_Exception) {
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001852 auto &ex = detail::get_exception_object<CppException>();
1853 if (!ex) ex = exception<CppException>(scope, name, base);
1854
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001855 register_exception_translator([](std::exception_ptr p) {
1856 if (!p) return;
1857 try {
1858 std::rethrow_exception(p);
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001859 } catch (const CppException &e) {
Jason Rhinelander6862cb92018-04-05 11:04:15 -03001860 detail::get_exception_object<CppException>()(e.what());
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001861 }
1862 });
1863 return ex;
1864}
1865
Yannick Jadoulf980d762020-07-09 00:14:41 +02001866PYBIND11_NAMESPACE_BEGIN(detail)
Dean Moldovan67990d92016-08-29 18:03:34 +02001867PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
1868 auto strings = tuple(args.size());
1869 for (size_t i = 0; i < args.size(); ++i) {
Dean Moldovane18bc022016-10-25 22:12:39 +02001870 strings[i] = str(args[i]);
Dean Moldovan67990d92016-08-29 18:03:34 +02001871 }
Dean Moldovan865e4302016-09-21 01:06:32 +02001872 auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
Dean Moldovan242b1462016-09-08 17:02:04 +02001873 auto line = sep.attr("join")(strings);
Dean Moldovan67990d92016-08-29 18:03:34 +02001874
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001875 object file;
1876 if (kwargs.contains("file")) {
1877 file = kwargs["file"].cast<object>();
1878 } else {
1879 try {
1880 file = module::import("sys").attr("stdout");
esquires67a68f12016-12-01 05:35:34 -05001881 } catch (const error_already_set &) {
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001882 /* If print() is called from code that is executed as
1883 part of garbage collection during interpreter shutdown,
1884 importing 'sys' can fail. Give up rather than crashing the
1885 interpreter in this case. */
1886 return;
1887 }
1888 }
1889
Dean Moldovan242b1462016-09-08 17:02:04 +02001890 auto write = file.attr("write");
Dean Moldovan67990d92016-08-29 18:03:34 +02001891 write(line);
Dean Moldovan865e4302016-09-21 01:06:32 +02001892 write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
Dean Moldovan67990d92016-08-29 18:03:34 +02001893
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001894 if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
Dean Moldovan242b1462016-09-08 17:02:04 +02001895 file.attr("flush")();
Dean Moldovan67990d92016-08-29 18:03:34 +02001896}
Yannick Jadoulf980d762020-07-09 00:14:41 +02001897PYBIND11_NAMESPACE_END(detail)
Dean Moldovan67990d92016-08-29 18:03:34 +02001898
1899template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1900void print(Args &&...args) {
1901 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
1902 detail::print(c.args(), c.kwargs());
1903}
1904
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001905#if defined(WITH_THREAD) && !defined(PYPY_VERSION)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001906
1907/* The functions below essentially reproduce the PyGILState_* API using a RAII
1908 * pattern, but there are a few important differences:
1909 *
1910 * 1. When acquiring the GIL from an non-main thread during the finalization
1911 * phase, the GILState API blindly terminates the calling thread, which
1912 * is often not what is wanted. This API does not do this.
1913 *
1914 * 2. The gil_scoped_release function can optionally cut the relationship
1915 * of a PyThreadState and its associated thread, which allows moving it to
1916 * another thread (this is a fairly rare/advanced use case).
1917 *
1918 * 3. The reference count of an acquired thread state can be controlled. This
1919 * can be handy to prevent cases where callbacks issued from an external
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001920 * thread would otherwise constantly construct and destroy thread state data
1921 * structures.
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001922 *
1923 * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
1924 * example which uses features 2 and 3 to migrate the Python thread of
1925 * execution to another thread (to run the event loop on the original thread,
1926 * in this case).
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001927 */
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001928
1929class gil_scoped_acquire {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001930public:
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001931 PYBIND11_NOINLINE gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001932 auto const &internals = detail::get_internals();
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001933 tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001934
1935 if (!tstate) {
Borja Zarcoe2b884c2018-12-01 08:47:40 -05001936 /* Check if the GIL was acquired using the PyGILState_* API instead (e.g. if
1937 calling from a Python thread). Since we use a different key, this ensures
1938 we don't create a new thread state and deadlock in PyEval_AcquireThread
1939 below. Note we don't save this state with internals.tstate, since we don't
1940 create it we would fail to clear it (its reference count should be > 0). */
1941 tstate = PyGILState_GetThisThreadState();
1942 }
1943
1944 if (!tstate) {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001945 tstate = PyThreadState_New(internals.istate);
1946 #if !defined(NDEBUG)
1947 if (!tstate)
1948 pybind11_fail("scoped_acquire: could not create thread state!");
1949 #endif
1950 tstate->gilstate_counter = 0;
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001951 PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001952 } else {
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001953 release = detail::get_thread_state_unchecked() != tstate;
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001954 }
1955
1956 if (release) {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001957 /* Work around an annoying assertion in PyThreadState_Swap */
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001958 #if defined(Py_DEBUG)
1959 PyInterpreterState *interp = tstate->interp;
1960 tstate->interp = nullptr;
1961 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001962 PyEval_AcquireThread(tstate);
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001963 #if defined(Py_DEBUG)
1964 tstate->interp = interp;
1965 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001966 }
1967
1968 inc_ref();
1969 }
1970
1971 void inc_ref() {
1972 ++tstate->gilstate_counter;
1973 }
1974
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001975 PYBIND11_NOINLINE void dec_ref() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001976 --tstate->gilstate_counter;
1977 #if !defined(NDEBUG)
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001978 if (detail::get_thread_state_unchecked() != tstate)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001979 pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
1980 if (tstate->gilstate_counter < 0)
1981 pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
1982 #endif
1983 if (tstate->gilstate_counter == 0) {
1984 #if !defined(NDEBUG)
1985 if (!release)
1986 pybind11_fail("scoped_acquire::dec_ref(): internal error!");
1987 #endif
1988 PyThreadState_Clear(tstate);
1989 PyThreadState_DeleteCurrent();
Yannick Jadoulb4719a62018-07-17 16:55:52 +02001990 PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001991 release = false;
1992 }
1993 }
1994
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001995 PYBIND11_NOINLINE ~gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001996 dec_ref();
1997 if (release)
1998 PyEval_SaveThread();
1999 }
2000private:
2001 PyThreadState *tstate = nullptr;
2002 bool release = true;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02002003};
2004
2005class gil_scoped_release {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02002006public:
Jason Rhinelander12d76602016-10-16 16:27:42 -04002007 explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
Dean Moldovan2d6116b2017-06-20 23:50:51 +02002008 // `get_internals()` must be called here unconditionally in order to initialize
2009 // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
2010 // initialization race could occur as multiple threads try `gil_scoped_acquire`.
2011 const auto &internals = detail::get_internals();
Wenzel Jakob39e97e62016-04-25 03:26:15 +02002012 tstate = PyEval_SaveThread();
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02002013 if (disassoc) {
Dean Moldovan2d6116b2017-06-20 23:50:51 +02002014 auto key = internals.tstate;
Yannick Jadoulb4719a62018-07-17 16:55:52 +02002015 PYBIND11_TLS_DELETE_VALUE(key);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02002016 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02002017 }
2018 ~gil_scoped_release() {
2019 if (!tstate)
2020 return;
2021 PyEval_RestoreThread(tstate);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02002022 if (disassoc) {
Boris Schäling20ee9352016-05-28 12:26:18 +02002023 auto key = detail::get_internals().tstate;
Yannick Jadoulb4719a62018-07-17 16:55:52 +02002024 PYBIND11_TLS_REPLACE_VALUE(key, tstate);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02002025 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02002026 }
2027private:
2028 PyThreadState *tstate;
2029 bool disassoc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02002030};
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002031#elif defined(PYPY_VERSION)
2032class gil_scoped_acquire {
2033 PyGILState_STATE state;
2034public:
2035 gil_scoped_acquire() { state = PyGILState_Ensure(); }
2036 ~gil_scoped_acquire() { PyGILState_Release(state); }
2037};
2038
2039class gil_scoped_release {
2040 PyThreadState *state;
2041public:
2042 gil_scoped_release() { state = PyEval_SaveThread(); }
2043 ~gil_scoped_release() { PyEval_RestoreThread(state); }
2044};
Wenzel Jakob39e97e62016-04-25 03:26:15 +02002045#else
2046class gil_scoped_acquire { };
2047class gil_scoped_release { };
Felipe Lema2547ca42016-01-25 16:22:44 -03002048#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +02002049
Wenzel Jakob8d396fc2016-11-24 23:11:02 +01002050error_already_set::~error_already_set() {
martinRenou35045ee2019-05-03 14:32:28 +02002051 if (m_type) {
Wenzel Jakob8d396fc2016-11-24 23:11:02 +01002052 gil_scoped_acquire gil;
Wenzel Jakob8b90b1d2019-07-06 14:52:32 +02002053 error_scope scope;
martinRenou35045ee2019-05-03 14:32:28 +02002054 m_type.release().dec_ref();
2055 m_value.release().dec_ref();
2056 m_trace.release().dec_ref();
Wenzel Jakob8d396fc2016-11-24 23:11:02 +01002057 }
2058}
2059
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04002060inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002061 handle self = detail::get_object_handle(this_ptr, this_type);
2062 if (!self)
Wenzel Jakobac0fde92015-10-01 18:37:26 +02002063 return function();
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002064 handle type = self.get_type();
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002065 auto key = std::make_pair(type.ptr(), name);
2066
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02002067 /* Cache functions that aren't overloaded in Python to avoid
2068 many costly Python dictionary lookups below */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002069 auto &cache = detail::get_internals().inactive_overload_cache;
2070 if (cache.find(key) != cache.end())
2071 return function();
2072
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002073 function overload = getattr(self, name, function());
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002074 if (overload.is_cpp_function()) {
2075 cache.insert(key);
2076 return function();
2077 }
Wenzel Jakob27e8e102016-01-17 22:36:37 +01002078
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002079 /* Don't call dispatch code if invoked from overridden function.
2080 Unfortunately this doesn't work on PyPy. */
2081#if !defined(PYPY_VERSION)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002082 PyFrameObject *frame = PyThreadState_Get()->frame;
Dean Moldovane18bc022016-10-25 22:12:39 +02002083 if (frame && (std::string) str(frame->f_code->co_name) == name &&
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02002084 frame->f_code->co_argcount > 0) {
2085 PyFrame_FastToLocals(frame);
2086 PyObject *self_caller = PyDict_GetItem(
2087 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002088 if (self_caller == self.ptr())
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02002089 return function();
2090 }
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002091#else
2092 /* PyPy currently doesn't provide a detailed cpyext emulation of
2093 frame objects, so we have to emulate this using Python. This
2094 is going to be slow..*/
2095 dict d; d["self"] = self; d["name"] = pybind11::str(name);
2096 PyObject *result = PyRun_String(
2097 "import inspect\n"
2098 "frame = inspect.currentframe()\n"
2099 "if frame is not None:\n"
2100 " frame = frame.f_back\n"
2101 " if frame is not None and str(frame.f_code.co_name) == name and "
2102 "frame.f_code.co_argcount > 0:\n"
2103 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2104 " if self_caller == self:\n"
2105 " self = None\n",
2106 Py_file_input, d.ptr(), d.ptr());
2107 if (result == nullptr)
2108 throw error_already_set();
Dean Moldovan36f0a152017-02-08 01:01:56 +01002109 if (d["self"].is_none())
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01002110 return function();
2111 Py_DECREF(result);
2112#endif
2113
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002114 return overload;
2115}
2116
Ivor Wanders2b045752019-06-10 16:12:28 -04002117/** \rst
2118 Try to retrieve a python method by the provided name from the instance pointed to by the this_ptr.
2119
2120 :this_ptr: The pointer to the object the overload should be retrieved for. This should be the first
2121 non-trampoline class encountered in the inheritance chain.
2122 :name: The name of the overloaded Python method to retrieve.
2123 :return: The Python method by this name from the object or an empty function wrapper.
2124 \endrst */
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04002125template <class T> function get_overload(const T *this_ptr, const char *name) {
Ivan Smirnov8f3e0452016-10-23 15:43:03 +01002126 auto tinfo = detail::get_type_info(typeid(T));
2127 return tinfo ? get_type_overload(this_ptr, tinfo, name) : function();
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04002128}
2129
Jason Rhinelander20978262016-08-29 18:16:46 -04002130#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02002131 pybind11::gil_scoped_acquire gil; \
Jason Rhinelander20978262016-08-29 18:16:46 -04002132 pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04002133 if (overload) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04002134 auto o = overload(__VA_ARGS__); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04002135 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04002136 static pybind11::detail::overload_caster_t<ret_type> caster; \
2137 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04002138 } \
2139 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2140 } \
2141 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +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 a method named 'fn'
2145 from the Python side, deals with the :ref:`gil` and necessary argument conversions to call this method and return
2146 the appropriate type. See :ref:`overriding_virtuals` for more information. This macro should be used when the method
2147 name in C is not the same as the method name in Python. For example with `__str__`.
2148
2149 .. code-block:: cpp
2150
2151 std::string toString() override {
2152 PYBIND11_OVERLOAD_NAME(
2153 std::string, // Return type (ret_type)
2154 Animal, // Parent class (cname)
methylDragond96c3452020-06-16 03:34:45 +08002155 "__str__", // Name of method in Python (name)
2156 toString, // Name of function in C++ (fn)
Ivor Wanders2b045752019-06-10 16:12:28 -04002157 );
2158 }
2159\endrst */
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002160#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelandere88656a2018-02-27 22:33:41 -04002161 PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002162 return cname::fn(__VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002163
Ivor Wanders2b045752019-06-10 16:12:28 -04002164/** \rst
2165 Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERLOAD_NAME`, except that it
2166 throws if no overload can be found.
2167\endrst */
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002168#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelandere88656a2018-02-27 22:33:41 -04002169 PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
Jason Rhinelander9f41c8e2018-02-27 23:43:16 -04002170 pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\"");
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002171
Ivor Wanders2b045752019-06-10 16:12:28 -04002172/** \rst
2173 Macro to populate the virtual method in the trampoline class. This macro tries to look up the method
2174 from the Python side, deals with the :ref:`gil` and necessary argument conversions to call this method and return
2175 the appropriate type. This macro should be used if the method name in C and in Python are identical.
2176 See :ref:`overriding_virtuals` for more information.
2177
2178 .. code-block:: cpp
2179
2180 class PyAnimal : public Animal {
2181 public:
2182 // Inherit the constructors
2183 using Animal::Animal;
2184
2185 // Trampoline (need one for each virtual function)
2186 std::string go(int n_times) override {
2187 PYBIND11_OVERLOAD_PURE(
2188 std::string, // Return type (ret_type)
2189 Animal, // Parent class (cname)
2190 go, // Name of function in C++ (must match Python name) (fn)
2191 n_times // Argument(s) (...)
2192 );
2193 }
2194 };
2195\endrst */
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002196#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
Jason Rhinelandere88656a2018-02-27 22:33:41 -04002197 PYBIND11_OVERLOAD_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002198
Ivor Wanders2b045752019-06-10 16:12:28 -04002199/** \rst
2200 Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERLOAD`, except that it throws
2201 if no overload can be found.
2202\endrst */
Wenzel Jakob1e3be732016-05-24 23:42:05 +02002203#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
Jason Rhinelandere88656a2018-02-27 22:33:41 -04002204 PYBIND11_OVERLOAD_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02002205
Yannick Jadoulf980d762020-07-09 00:14:41 +02002206PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02002207
Baljak81da9882018-11-20 23:22:02 +01002208#if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01002209# pragma warning(pop)
Wenzel Jakob6d252962016-05-01 20:47:49 +02002210#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01002211# pragma GCC diagnostic pop
Wenzel Jakob38bd7112015-07-05 20:05:44 +02002212#endif