blob: ca6cebc73dec0913e145543391eff4537906d225 [file] [log] [blame]
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001/*
Wenzel Jakob48548ea2016-01-17 22:36:44 +01002 pybind11/pybind11.h: Main header file of the C++11 python
3 binding generator library
Wenzel Jakob38bd7112015-07-05 20:05:44 +02004
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +02005 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakob38bd7112015-07-05 20:05:44 +02006
7 All rights reserved. Use of this source code is governed by a
8 BSD-style license that can be found in the LICENSE file.
9*/
10
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020011#pragma once
Wenzel Jakob38bd7112015-07-05 20:05:44 +020012
13#if defined(_MSC_VER)
Wenzel Jakob48548ea2016-01-17 22:36:44 +010014# pragma warning(push)
Wenzel Jakob1ffce742016-08-25 01:43:33 +020015# pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
Wenzel Jakob48548ea2016-01-17 22:36:44 +010016# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
Wenzel Jakob1ffce742016-08-25 01:43:33 +020017# pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
Wenzel Jakob48548ea2016-01-17 22:36:44 +010018# pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
19# pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +090020# pragma warning(disable: 4702) // warning C4702: unreachable code
Dean Moldovan2bab5792016-09-23 00:27:59 +020021# pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
Wenzel Jakob1ffce742016-08-25 01:43:33 +020022#elif defined(__INTEL_COMPILER)
Ben Pritchard33f34302016-02-18 15:25:51 -050023# pragma warning(push)
Wenzel Jakob1ffce742016-08-25 01:43:33 +020024# pragma warning(disable: 186) // pointless comparison of unsigned integer with zero
25# pragma warning(disable: 1334) // the "template" keyword used for syntactic disambiguation may only be used within a template
26# pragma warning(disable: 2196) // warning #2196: routine is both "inline" and "noinline"
Wenzel Jakob6d252962016-05-01 20:47:49 +020027#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +010028# pragma GCC diagnostic push
29# pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
30# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
31# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
Wenzel Jakobdeeab552016-05-15 23:54:34 +020032# pragma GCC diagnostic ignored "-Wstrict-aliasing"
33# pragma GCC diagnostic ignored "-Wattributes"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020034#endif
35
Wenzel Jakob48548ea2016-01-17 22:36:44 +010036#include "attr.h"
Alexander Stukowski9a110e62016-11-15 12:38:05 +010037#include "options.h"
Dean Moldovanc91f8bd2017-02-13 18:11:24 +010038#include "class_support.h"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020039
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020040NAMESPACE_BEGIN(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +020041
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020042/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020043class cpp_function : public function {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020044public:
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020045 cpp_function() { }
Wenzel Jakob38bd7112015-07-05 20:05:44 +020046
Wenzel Jakob5984baa2016-05-10 15:05:03 +010047 /// Construct a cpp_function from a vanilla function pointer
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050048 template <typename Return, typename... Args, typename... Extra>
49 cpp_function(Return (*f)(Args...), const Extra&... extra) {
Wenzel Jakob5984baa2016-05-10 15:05:03 +010050 initialize(f, f, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +020051 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020052
Wenzel Jakob5984baa2016-05-10 15:05:03 +010053 /// Construct a cpp_function from a lambda function (possibly with internal state)
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050054 template <typename Func, typename... Extra,
55 typename FuncType = typename detail::remove_class<decltype(&std::remove_reference<Func>::type::operator())>::type>
56 cpp_function(Func &&f, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020057 initialize(std::forward<Func>(f),
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050058 (FuncType *) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020059 }
60
Wenzel Jakob5984baa2016-05-10 15:05:03 +010061 /// Construct a cpp_function from a class method (non-const)
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050062 template <typename Return, typename Class, typename... Arg, typename... Extra>
63 cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020064 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050065 (Return (*) (Class *, Arg...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020066 }
67
Wenzel Jakob5984baa2016-05-10 15:05:03 +010068 /// Construct a cpp_function from a class method (const)
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050069 template <typename Return, typename Class, typename... Arg, typename... Extra>
70 cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020071 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050072 (Return (*)(const Class *, Arg ...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020073 }
74
Wenzel Jakob57082212015-09-04 23:42:12 +020075 /// Return the function name
Wenzel Jakob48548ea2016-01-17 22:36:44 +010076 object name() const { return attr("__name__"); }
Wenzel Jakob57082212015-09-04 23:42:12 +020077
Wenzel Jakobd561cb02016-01-17 22:36:41 +010078protected:
Wenzel Jakob382484a2016-09-10 15:28:37 +090079 /// Space optimization: don't inline this frequently instantiated fragment
80 PYBIND11_NOINLINE detail::function_record *make_function_record() {
81 return new detail::function_record();
82 }
83
Wenzel Jakobd561cb02016-01-17 22:36:41 +010084 /// Special internal constructor for functors, lambda functions, etc.
Jason Rhinelander1d7998e2017-02-17 06:56:41 -050085 template <typename Func, typename Return, typename... Args, typename... Extra>
86 void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
Dean Moldovan9e625582016-06-04 00:27:32 +020087
Wenzel Jakob66c9a402016-01-17 22:36:36 +010088 struct capture { typename std::remove_reference<Func>::type f; };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020089
Wenzel Jakobd561cb02016-01-17 22:36:41 +010090 /* Store the function including any extra state it might have (e.g. a lambda capture object) */
Wenzel Jakob382484a2016-09-10 15:28:37 +090091 auto rec = make_function_record();
Wenzel Jakob71867832015-07-29 17:43:52 +020092
Wenzel Jakob5984baa2016-05-10 15:05:03 +010093 /* Store the capture object directly in the function record if there is enough space */
94 if (sizeof(capture) <= sizeof(rec->data)) {
Wenzel Jakob954b7932016-07-10 10:13:18 +020095 /* Without these pragmas, GCC warns that there might not be
96 enough space to use the placement new operator. However, the
97 'if' statement above ensures that this is the case. */
Jason Rhinelander0b12f912016-07-07 16:26:04 -040098#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -040099# pragma GCC diagnostic push
100# pragma GCC diagnostic ignored "-Wplacement-new"
101#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100102 new ((capture *) &rec->data) capture { std::forward<Func>(f) };
Jason Rhinelander0b12f912016-07-07 16:26:04 -0400103#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -0400104# pragma GCC diagnostic pop
105#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100106 if (!std::is_trivially_destructible<Func>::value)
107 rec->free_data = [](detail::function_record *r) { ((capture *) &r->data)->~capture(); };
108 } else {
109 rec->data[0] = new capture { std::forward<Func>(f) };
110 rec->free_data = [](detail::function_record *r) { delete ((capture *) r->data[0]); };
111 }
Wenzel Jakob19208fe2015-10-13 17:37:25 +0200112
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100113 /* Type casters for the function arguments and return value */
Dean Moldovan719c1732016-11-27 18:19:34 +0100114 using cast_in = detail::argument_loader<Args...>;
115 using cast_out = detail::make_caster<
116 detail::conditional_t<std::is_void<Return>::value, detail::void_type, Return>
117 >;
Wenzel Jakob71867832015-07-29 17:43:52 +0200118
Jason Rhinelander2686da82017-01-21 23:42:14 -0500119 static_assert(detail::expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
120 "The number of named arguments does not match the function signature");
121
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100122 /* Dispatch code which converts function arguments and performs the actual function call */
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500123 rec->impl = [](detail::function_call &call) -> handle {
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100124 cast_in args_converter;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100125
126 /* Try to cast the function arguments into the C++ domain */
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500127 if (!args_converter.load_args(call))
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100128 return PYBIND11_TRY_NEXT_OVERLOAD;
129
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100130 /* Invoke call policy pre-call hook */
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500131 detail::process_attributes<Extra...>::precall(call);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100132
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100133 /* Get a pointer to the capture object */
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500134 auto data = (sizeof(capture) <= sizeof(call.func.data)
135 ? &call.func.data : call.func.data[0]);
136 capture *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100137
Dean Moldovand079f412016-11-20 05:31:02 +0100138 /* Override policy for rvalues -- always move */
139 constexpr auto is_rvalue = !std::is_pointer<Return>::value
140 && !std::is_lvalue_reference<Return>::value;
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500141 const auto policy = is_rvalue ? return_value_policy::move : call.func.policy;
Dean Moldovand079f412016-11-20 05:31:02 +0100142
Wenzel Jakob954b7932016-07-10 10:13:18 +0200143 /* Perform the function call */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100144 handle result = cast_out::cast(args_converter.template call<Return>(cap->f),
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500145 policy, call.parent);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100146
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100147 /* Invoke call policy post-call hook */
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500148 detail::process_attributes<Extra...>::postcall(call, result);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100149
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100150 return result;
Wenzel Jakob71867832015-07-29 17:43:52 +0200151 };
152
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100153 /* Process any user-provided function attributes */
154 detail::process_attributes<Extra...>::init(extra..., rec);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100155
156 /* Generate a readable signature describing the function's arguments and return value types */
Dean Moldovaned23dda2016-08-04 01:40:40 +0200157 using detail::descr; using detail::_;
Dean Moldovan719c1732016-11-27 18:19:34 +0100158 PYBIND11_DESCR signature = _("(") + cast_in::arg_names() + _(") -> ") + cast_out::name();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100159
160 /* Register the function with Python from generic (non-templated) code */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100161 initialize_generic(rec, signature.text(), signature.types(), sizeof...(Args));
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100162
163 if (cast_in::has_args) rec->has_args = true;
164 if (cast_in::has_kwargs) rec->has_kwargs = true;
Wenzel Jakob954b7932016-07-10 10:13:18 +0200165
166 /* Stash some additional information used by an important optimization in 'functional.h' */
Jason Rhinelander1d7998e2017-02-17 06:56:41 -0500167 using FunctionType = Return (*)(Args...);
Wenzel Jakob954b7932016-07-10 10:13:18 +0200168 constexpr bool is_function_ptr =
169 std::is_convertible<Func, FunctionType>::value &&
170 sizeof(capture) == sizeof(void *);
171 if (is_function_ptr) {
172 rec->is_stateless = true;
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500173 rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
Wenzel Jakob954b7932016-07-10 10:13:18 +0200174 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200175 }
176
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100177 /// Register a function call with Python (generic non-templated code goes here)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100178 void initialize_generic(detail::function_record *rec, const char *text,
Dean Moldovanecced6c2016-07-31 20:03:18 +0200179 const std::type_info *const *types, size_t args) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100180
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100181 /* Create copies of all referenced C-style strings */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100182 rec->name = strdup(rec->name ? rec->name : "");
183 if (rec->doc) rec->doc = strdup(rec->doc);
184 for (auto &a: rec->args) {
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100185 if (a.name)
186 a.name = strdup(a.name);
187 if (a.descr)
188 a.descr = strdup(a.descr);
189 else if (a.value)
Dean Moldovan242b1462016-09-08 17:02:04 +0200190 a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100191 }
Wenzel Jakob954b7932016-07-10 10:13:18 +0200192
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100193 /* Generate a proper function signature */
194 std::string signature;
195 size_t type_depth = 0, char_index = 0, type_index = 0, arg_index = 0;
196 while (true) {
197 char c = text[char_index++];
198 if (c == '\0')
199 break;
200
201 if (c == '{') {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200202 // Write arg name for everything except *args, **kwargs and return type.
Dean Moldovaned23dda2016-08-04 01:40:40 +0200203 if (type_depth == 0 && text[char_index] != '*' && arg_index < args) {
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500204 if (!rec->args.empty() && rec->args[arg_index].name) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200205 signature += rec->args[arg_index].name;
Wenzel Jakob31fbf182016-11-20 05:27:05 +0100206 } else if (arg_index == 0 && rec->is_method) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200207 signature += "self";
208 } else {
Wenzel Jakob31fbf182016-11-20 05:27:05 +0100209 signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
Dean Moldovanecced6c2016-07-31 20:03:18 +0200210 }
211 signature += ": ";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100212 }
213 ++type_depth;
214 } else if (c == '}') {
215 --type_depth;
Dean Moldovaned23dda2016-08-04 01:40:40 +0200216 if (type_depth == 0) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200217 if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
218 signature += "=";
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100219 signature += rec->args[arg_index].descr;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100220 }
221 arg_index++;
222 }
223 } else if (c == '%') {
224 const std::type_info *t = types[type_index++];
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100225 if (!t)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100226 pybind11_fail("Internal error while parsing type signature (1)");
Ivan Smirnov8f3e0452016-10-23 15:43:03 +0100227 if (auto tinfo = detail::get_type_info(*t)) {
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100228#if defined(PYPY_VERSION)
229 signature += handle((PyObject *) tinfo->type)
230 .attr("__module__")
231 .cast<std::string>() + ".";
232#endif
Ivan Smirnov8f3e0452016-10-23 15:43:03 +0100233 signature += tinfo->type->tp_name;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100234 } else {
235 std::string tname(t->name());
236 detail::clean_type_id(tname);
237 signature += tname;
238 }
239 } else {
240 signature += c;
241 }
242 }
Wenzel Jakob95d18692016-01-17 22:36:40 +0100243 if (type_depth != 0 || types[type_index] != nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100244 pybind11_fail("Internal error while parsing type signature (2)");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100245
246 #if !defined(PYBIND11_CPP14)
247 delete[] types;
248 delete[] text;
249 #endif
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200250
Wenzel Jakob57082212015-09-04 23:42:12 +0200251#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100252 if (strcmp(rec->name, "__next__") == 0) {
253 std::free(rec->name);
254 rec->name = strdup("next");
Wenzel Jakobd1bfc4e2016-05-16 18:52:46 +0200255 } else if (strcmp(rec->name, "__bool__") == 0) {
256 std::free(rec->name);
257 rec->name = strdup("__nonzero__");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100258 }
Wenzel Jakob57082212015-09-04 23:42:12 +0200259#endif
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100260 rec->signature = strdup(signature.c_str());
261 rec->args.shrink_to_fit();
Wenzel Jakoba380ed92016-05-15 23:54:13 +0200262 rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500263 rec->nargs = (std::uint16_t) args;
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200264
Wenzel Jakob57082212015-09-04 23:42:12 +0200265#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100266 if (rec->sibling && PyMethod_Check(rec->sibling.ptr()))
267 rec->sibling = PyMethod_GET_FUNCTION(rec->sibling.ptr());
Wenzel Jakob57082212015-09-04 23:42:12 +0200268#endif
269
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100270 detail::function_record *chain = nullptr, *chain_start = rec;
Jason Rhinelander6873c202016-10-24 21:58:22 -0400271 if (rec->sibling) {
272 if (PyCFunction_Check(rec->sibling.ptr())) {
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100273 auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
Jason Rhinelander6873c202016-10-24 21:58:22 -0400274 chain = (detail::function_record *) rec_capsule;
275 /* Never append a method to an overload chain of a parent class;
276 instead, hide the parent's overloads in this case */
Wenzel Jakob7c2461e2016-11-20 05:26:02 +0100277 if (chain->scope != rec->scope)
Jason Rhinelander6873c202016-10-24 21:58:22 -0400278 chain = nullptr;
279 }
280 // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
281 else if (!rec->sibling.is_none() && rec->name[0] != '_')
282 pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
283 "\" with a function of the same name");
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200284 }
285
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100286 if (!chain) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100287 /* No existing overload was found, create a new function object */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100288 rec->def = new PyMethodDef();
289 memset(rec->def, 0, sizeof(PyMethodDef));
290 rec->def->ml_name = rec->name;
291 rec->def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
292 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
Wenzel Jakoba6501792016-02-04 23:02:07 +0100293
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100294 capsule rec_capsule(rec, [](PyObject *o) {
295 destruct((detail::function_record *) PyCapsule_GetPointer(o, nullptr));
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100296 });
Wenzel Jakoba6501792016-02-04 23:02:07 +0100297
298 object scope_module;
299 if (rec->scope) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200300 if (hasattr(rec->scope, "__module__")) {
301 scope_module = rec->scope.attr("__module__");
302 } else if (hasattr(rec->scope, "__name__")) {
303 scope_module = rec->scope.attr("__name__");
304 }
Wenzel Jakoba6501792016-02-04 23:02:07 +0100305 }
306
307 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200308 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100309 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200310 } else {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100311 /* Append at the end of the overload chain */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100312 m_ptr = rec->sibling.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200313 inc_ref();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100314 chain_start = chain;
315 while (chain->next)
316 chain = chain->next;
317 chain->next = rec;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200318 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200319
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200320 std::string signatures;
Wenzel Jakob71867832015-07-29 17:43:52 +0200321 int index = 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100322 /* Create a nice pydoc rec including all signatures and
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100323 docstrings of the functions in the overload chain */
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100324 if (chain && options::show_function_signatures()) {
Sylvain Corlay0e04fdf2016-03-08 16:42:12 -0500325 // First a generic signature
326 signatures += rec->name;
327 signatures += "(*args, **kwargs)\n";
328 signatures += "Overloaded function.\n\n";
329 }
330 // Then specific overload signatures
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100331 for (auto it = chain_start; it != nullptr; it = it->next) {
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100332 if (options::show_function_signatures()) {
333 if (chain)
334 signatures += std::to_string(++index) + ". ";
335 signatures += rec->name;
336 signatures += it->signature;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100337 signatures += "\n";
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100338 }
339 if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
340 if (options::show_function_signatures()) signatures += "\n";
Wenzel Jakob218b6ce2016-02-28 23:52:37 +0100341 signatures += it->doc;
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100342 if (options::show_function_signatures()) signatures += "\n";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100343 }
Wenzel Jakob71867832015-07-29 17:43:52 +0200344 if (it->next)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200345 signatures += "\n";
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200346 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100347
348 /* Install docstring */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200349 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
350 if (func->m_ml->ml_doc)
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500351 std::free(const_cast<char *>(func->m_ml->ml_doc));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200352 func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100353
Wenzel Jakob31fbf182016-11-20 05:27:05 +0100354 if (rec->is_method) {
355 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200356 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100357 pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200358 Py_DECREF(func);
359 }
360 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100361
362 /// When a cpp_function is GCed, release any memory allocated by pybind11
363 static void destruct(detail::function_record *rec) {
364 while (rec) {
365 detail::function_record *next = rec->next;
366 if (rec->free_data)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100367 rec->free_data(rec);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100368 std::free((char *) rec->name);
369 std::free((char *) rec->doc);
370 std::free((char *) rec->signature);
371 for (auto &arg: rec->args) {
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500372 std::free(const_cast<char *>(arg.name));
373 std::free(const_cast<char *>(arg.descr));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100374 arg.value.dec_ref();
375 }
376 if (rec->def) {
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -0500377 std::free(const_cast<char *>(rec->def->ml_doc));
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100378 delete rec->def;
379 }
380 delete rec;
381 rec = next;
382 }
383 }
384
385 /// Main dispatch logic for calls to functions bound using pybind11
Jason Rhinelander2686da82017-01-21 23:42:14 -0500386 static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500387 using namespace detail;
388
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100389 /* Iterator over the list of potentially admissible overloads */
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500390 function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
391 *it = overloads;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100392
393 /* Need to know how many arguments + keyword arguments there are to pick the right overload */
Jason Rhinelander2686da82017-01-21 23:42:14 -0500394 const size_t n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100395
Jason Rhinelander2686da82017-01-21 23:42:14 -0500396 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100397 result = PYBIND11_TRY_NEXT_OVERLOAD;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500398
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100399 try {
Jason Rhinelandere5505892017-02-03 18:25:34 -0500400 // We do this in two passes: in the first pass, we load arguments with `convert=false`;
401 // in the second, we allow conversion (except for arguments with an explicit
402 // py::arg().noconvert()). This lets us prefer calls without conversion, with
403 // conversion as a fallback.
404 std::vector<function_call> second_pass;
405
406 // However, if there are no overloads, we can just skip the no-convert pass entirely
407 const bool overloaded = it != nullptr && it->next != nullptr;
408
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100409 for (; it != nullptr; it = it->next) {
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500410
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100411 /* For each overload:
Jason Rhinelander2686da82017-01-21 23:42:14 -0500412 1. Copy all positional arguments we were given, also checking to make sure that
413 named positional arguments weren't *also* specified via kwarg.
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100414 2. If we weren't given enough, try to make up the omitted ones by checking
Jason Rhinelander2686da82017-01-21 23:42:14 -0500415 whether they were provided by a kwarg matching the `py::arg("name")` name. If
416 so, use it (and remove it from kwargs; if not, see if the function binding
417 provided a default that we can use.
418 3. Ensure that either all keyword arguments were "consumed", or that the function
419 takes a kwargs argument to accept unconsumed kwargs.
420 4. Any positional arguments still left get put into a tuple (for args), and any
421 leftover kwargs get put into a dict.
422 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
423 extra tuple or dict at the end of the positional arguments.
424 6. Call the function call dispatcher (function_record::impl)
425
426 If one of these fail, move on to the next overload and keep trying until we get a
427 result other than PYBIND11_TRY_NEXT_OVERLOAD.
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100428 */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100429
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500430 function_record &func = *it;
431 size_t pos_args = func.nargs; // Number of positional arguments that we need
432 if (func.has_args) --pos_args; // (but don't count py::args
433 if (func.has_kwargs) --pos_args; // or py::kwargs)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100434
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500435 if (!func.has_args && n_args_in > pos_args)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500436 continue; // Too many arguments for this overload
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100437
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500438 if (n_args_in < pos_args && func.args.size() < pos_args)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500439 continue; // Not enough arguments given, and not enough defaults to fill in the blanks
440
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500441 function_call call(func, parent);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500442
443 size_t args_to_copy = std::min(pos_args, n_args_in);
444 size_t args_copied = 0;
445
446 // 1. Copy any position arguments given.
447 for (; args_copied < args_to_copy; ++args_copied) {
448 // If we find a given positional argument that also has a named kwargs argument,
449 // raise a TypeError like Python does. (We could also continue with the next
450 // overload, but this seems highly likely to be a caller mistake rather than a
451 // legitimate overload).
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500452 if (kwargs_in && args_copied < func.args.size() && func.args[args_copied].name) {
453 handle value = PyDict_GetItemString(kwargs_in, func.args[args_copied].name);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100454 if (value)
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500455 throw type_error(std::string(func.name) + "(): got multiple values for argument '" +
456 std::string(func.args[args_copied].name) + "'");
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100457 }
Jason Rhinelander2686da82017-01-21 23:42:14 -0500458
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500459 call.args.push_back(PyTuple_GET_ITEM(args_in, args_copied));
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500460 call.args_convert.push_back(args_copied < func.args.size() ? func.args[args_copied].convert : true);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100461 }
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200462
Jason Rhinelander2686da82017-01-21 23:42:14 -0500463 // We'll need to copy this if we steal some kwargs for defaults
464 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
465
466 // 2. Check kwargs and, failing that, defaults that may help complete the list
467 if (args_copied < pos_args) {
468 bool copied_kwargs = false;
469
470 for (; args_copied < pos_args; ++args_copied) {
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500471 const auto &arg = func.args[args_copied];
Jason Rhinelander2686da82017-01-21 23:42:14 -0500472
473 handle value;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500474 if (kwargs_in && arg.name)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500475 value = PyDict_GetItemString(kwargs.ptr(), arg.name);
476
477 if (value) {
478 // Consume a kwargs value
479 if (!copied_kwargs) {
480 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
481 copied_kwargs = true;
482 }
483 PyDict_DelItemString(kwargs.ptr(), arg.name);
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100484 } else if (arg.value) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500485 value = arg.value;
486 }
487
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500488 if (value) {
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500489 call.args.push_back(value);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500490 call.args_convert.push_back(arg.convert);
491 }
Jason Rhinelander2686da82017-01-21 23:42:14 -0500492 else
493 break;
494 }
495
496 if (args_copied < pos_args)
497 continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments
498 }
499
500 // 3. Check everything was consumed (unless we have a kwargs arg)
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500501 if (kwargs && kwargs.size() > 0 && !func.has_kwargs)
Jason Rhinelander2686da82017-01-21 23:42:14 -0500502 continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
503
504 // 4a. If we have a py::args argument, create a new tuple with leftovers
505 tuple extra_args;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500506 if (func.has_args) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500507 if (args_to_copy == 0) {
508 // We didn't copy out any position arguments from the args_in tuple, so we
509 // can reuse it directly without copying:
510 extra_args = reinterpret_borrow<tuple>(args_in);
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100511 } else if (args_copied >= n_args_in) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500512 extra_args = tuple(0);
Wenzel Jakobab60bf12017-01-31 17:23:53 +0100513 } else {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500514 size_t args_size = n_args_in - args_copied;
515 extra_args = tuple(args_size);
516 for (size_t i = 0; i < args_size; ++i) {
517 handle item = PyTuple_GET_ITEM(args_in, args_copied + i);
518 extra_args[i] = item.inc_ref().ptr();
519 }
520 }
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500521 call.args.push_back(extra_args);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500522 call.args_convert.push_back(false);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500523 }
524
525 // 4b. If we have a py::kwargs, pass on any remaining kwargs
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500526 if (func.has_kwargs) {
Jason Rhinelander2686da82017-01-21 23:42:14 -0500527 if (!kwargs.ptr())
528 kwargs = dict(); // If we didn't get one, send an empty one
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500529 call.args.push_back(kwargs);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500530 call.args_convert.push_back(false);
Jason Rhinelander2686da82017-01-21 23:42:14 -0500531 }
532
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500533 // 5. Put everything in a vector. Not technically step 5, we've been building it
534 // in `call.args` all along.
535 #if !defined(NDEBUG)
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500536 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500537 pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
538 #endif
Jason Rhinelander2686da82017-01-21 23:42:14 -0500539
Jason Rhinelandere5505892017-02-03 18:25:34 -0500540 std::vector<bool> second_pass_convert;
541 if (overloaded) {
542 // We're in the first no-convert pass, so swap out the conversion flags for a
543 // set of all-false flags. If the call fails, we'll swap the flags back in for
544 // the conversion-allowed call below.
545 second_pass_convert.resize(func.nargs, false);
546 call.args_convert.swap(second_pass_convert);
547 }
548
Jason Rhinelander2686da82017-01-21 23:42:14 -0500549 // 6. Call the function.
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200550 try {
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500551 result = func.impl(call);
Wenzel Jakob00062592016-07-01 16:07:35 +0200552 } catch (reference_cast_error &) {
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200553 result = PYBIND11_TRY_NEXT_OVERLOAD;
554 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100555
556 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
557 break;
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500558
Jason Rhinelandere5505892017-02-03 18:25:34 -0500559 if (overloaded) {
560 // The (overloaded) call failed; if the call has at least one argument that
561 // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
562 // then add this call to the list of second pass overloads to try.
563 for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
564 if (second_pass_convert[i]) {
565 // Found one: swap the converting flags back in and store the call for
566 // the second pass.
567 call.args_convert.swap(second_pass_convert);
568 second_pass.push_back(std::move(call));
569 break;
570 }
571 }
572 }
573 }
574
575 if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
576 // The no-conversion pass finished without success, try again with conversion allowed
577 for (auto &call : second_pass) {
578 try {
579 result = call.func.impl(call);
580 } catch (reference_cast_error &) {
581 result = PYBIND11_TRY_NEXT_OVERLOAD;
582 }
583
584 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
585 break;
586 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100587 }
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200588 } catch (error_already_set &e) {
589 e.restore();
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400590 return nullptr;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100591 } catch (...) {
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400592 /* When an exception is caught, give each registered exception
593 translator a chance to translate it to a Python exception
594 in reverse order of registration.
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200595
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400596 A translator may choose to do one of the following:
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200597
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400598 - catch the exception and call PyErr_SetString or PyErr_SetObject
599 to set a standard (or custom) Python exception, or
600 - do nothing and let the exception fall through to the next translator, or
601 - delegate translation to the next translator by throwing a new type of exception. */
602
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200603 auto last_exception = std::current_exception();
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500604 auto &registered_exception_translators = get_internals().registered_exception_translators;
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400605 for (auto& translator : registered_exception_translators) {
606 try {
607 translator(last_exception);
608 } catch (...) {
609 last_exception = std::current_exception();
610 continue;
611 }
612 return nullptr;
613 }
614 PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100615 return nullptr;
616 }
617
618 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
Wenzel Jakob382484a2016-09-10 15:28:37 +0900619 if (overloads->is_operator)
620 return handle(Py_NotImplemented).inc_ref().ptr();
621
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900622 std::string msg = std::string(overloads->name) + "(): incompatible " +
623 std::string(overloads->is_constructor ? "constructor" : "function") +
624 " arguments. The following argument types are supported:\n";
625
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100626 int ctr = 0;
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500627 for (function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100628 msg += " "+ std::to_string(++ctr) + ". ";
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400629
630 bool wrote_sig = false;
631 if (overloads->is_constructor) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200632 // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400633 std::string sig = it2->signature;
Dean Moldovanecced6c2016-07-31 20:03:18 +0200634 size_t start = sig.find('(') + 7; // skip "(self: "
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400635 if (start < sig.size()) {
636 // End at the , for the next argument
637 size_t end = sig.find(", "), next = end + 2;
638 size_t ret = sig.rfind(" -> ");
639 // Or the ), if there is no comma:
640 if (end >= sig.size()) next = end = sig.find(')');
641 if (start < end && next < sig.size()) {
642 msg.append(sig, start, end - start);
643 msg += '(';
644 msg.append(sig, next, ret - next);
645 wrote_sig = true;
646 }
647 }
648 }
649 if (!wrote_sig) msg += it2->signature;
650
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100651 msg += "\n";
652 }
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900653 msg += "\nInvoked with: ";
Jason Rhinelander2686da82017-01-21 23:42:14 -0500654 auto args_ = reinterpret_borrow<tuple>(args_in);
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200655 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
Jason Rhinelander7146d622016-11-22 05:28:40 -0500656 msg += pybind11::repr(args_[ti]);
Andreas Bergmeier16d43942016-05-24 09:19:35 +0200657 if ((ti + 1) != args_.size() )
658 msg += ", ";
659 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100660 PyErr_SetString(PyExc_TypeError, msg.c_str());
661 return nullptr;
662 } else if (!result) {
663 std::string msg = "Unable to convert function return value to a "
664 "Python type! The signature was\n\t";
665 msg += it->signature;
666 PyErr_SetString(PyExc_TypeError, msg.c_str());
667 return nullptr;
668 } else {
669 if (overloads->is_constructor) {
Wenzel Jakob772c6d52016-04-30 19:56:10 +0200670 /* When a constructor ran successfully, the corresponding
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100671 holder type (e.g. std::unique_ptr) must still be initialized. */
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -0500672 auto tinfo = get_type_info(Py_TYPE(parent.ptr()));
Jason Rhinelander2686da82017-01-21 23:42:14 -0500673 tinfo->init_holder(parent.ptr(), nullptr);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100674 }
675 return result.ptr();
676 }
677 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200678};
679
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100680/// Wrapper for Python extension modules
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200681class module : public object {
682public:
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200683 PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200684
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100685 /// Create a new top-level Python module with the given name and docstring
Jason Rhinelander12d76602016-10-16 16:27:42 -0400686 explicit module(const char *name, const char *doc = nullptr) {
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100687 if (!options::show_user_defined_docstrings()) doc = nullptr;
Wenzel Jakob57082212015-09-04 23:42:12 +0200688#if PY_MAJOR_VERSION >= 3
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200689 PyModuleDef *def = new PyModuleDef();
690 memset(def, 0, sizeof(PyModuleDef));
691 def->m_name = name;
692 def->m_doc = doc;
693 def->m_size = -1;
694 Py_INCREF(def);
695 m_ptr = PyModule_Create(def);
Wenzel Jakob57082212015-09-04 23:42:12 +0200696#else
697 m_ptr = Py_InitModule3(name, nullptr, doc);
698#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200699 if (m_ptr == nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100700 pybind11_fail("Internal error in module::module()");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200701 inc_ref();
702 }
703
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100704 /** \rst
705 Create Python binding for a new function within the module scope. ``Func``
706 can be a plain C++ function, a function pointer, or a lambda function. For
707 details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
708 \endrst */
Wenzel Jakob71867832015-07-29 17:43:52 +0200709 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100710 module &def(const char *name_, Func &&f, const Extra& ... extra) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200711 cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
712 sibling(getattr(*this, name_, none())), extra...);
Jason Rhinelander6873c202016-10-24 21:58:22 -0400713 // NB: allow overwriting here because cpp_function sets up a chain with the intention of
714 // overwriting (and has already checked internally that it isn't overwriting non-functions).
715 add_object(name_, func, true /* overwrite */);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200716 return *this;
717 }
718
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100719 /** \rst
720 Create and return a new Python submodule with the given name and docstring.
721 This also works recursively, i.e.
722
723 .. code-block:: cpp
724
725 py::module m("example", "pybind11 example plugin");
726 py::module m2 = m.def_submodule("sub", "A submodule of 'example'");
727 py::module m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
728 \endrst */
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200729 module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200730 std::string full_name = std::string(PyModule_GetName(m_ptr))
731 + std::string(".") + std::string(name);
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200732 auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
Alexander Stukowski9a110e62016-11-15 12:38:05 +0100733 if (doc && options::show_user_defined_docstrings())
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200734 result.attr("__doc__") = pybind11::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200735 attr(name) = result;
736 return result;
737 }
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200738
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100739 /// Import and return a module or throws `error_already_set`.
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200740 static module import(const char *name) {
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100741 PyObject *obj = PyImport_ImportModule(name);
742 if (!obj)
esquires67a68f12016-12-01 05:35:34 -0500743 throw error_already_set();
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200744 return reinterpret_steal<module>(obj);
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200745 }
Jason Rhinelander6873c202016-10-24 21:58:22 -0400746
747 // Adds an object to the module using the given name. Throws if an object with the given name
748 // already exists.
749 //
750 // overwrite should almost always be false: attempting to overwrite objects that pybind11 has
751 // established will, in most cases, break things.
752 PYBIND11_NOINLINE void add_object(const char *name, object &obj, bool overwrite = false) {
753 if (!overwrite && hasattr(*this, name))
754 pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
755 std::string(name) + "\"");
756
757 obj.inc_ref(); // PyModule_AddObject() steals a reference
758 PyModule_AddObject(ptr(), name, obj.ptr());
759 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200760};
761
762NAMESPACE_BEGIN(detail)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100763/// Generic support for creating new Python heap types
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100764class generic_type : public object {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400765 template <typename...> friend class class_;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200766public:
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100767 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100768protected:
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100769 void initialize(const type_record &rec) {
770 if (rec.scope && hasattr(rec.scope, rec.name))
771 pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
772 "\": an object with that name is already defined");
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200773
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100774 if (get_type_info(*rec.type))
775 pybind11_fail("generic_type: type \"" + std::string(rec.name) +
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200776 "\" is already registered!");
777
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100778 m_ptr = make_new_python_type(rec);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200779
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100780 /* Register supplemental type information in C++ dict */
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100781 auto *tinfo = new detail::type_info();
782 tinfo->type = (PyTypeObject *) m_ptr;
783 tinfo->type_size = rec.type_size;
784 tinfo->init_holder = rec.init_holder;
785 tinfo->dealloc = rec.dealloc;
786
787 auto &internals = get_internals();
788 auto tindex = std::type_index(*rec.type);
Ivan Smirnova6e6a8b2016-10-23 15:27:13 +0100789 tinfo->direct_conversions = &internals.direct_conversions[tindex];
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100790 tinfo->default_holder = rec.default_holder;
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200791 internals.registered_types_cpp[tindex] = tinfo;
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100792 internals.registered_types_py[m_ptr] = tinfo;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100793
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100794 if (rec.bases.size() > 1 || rec.multiple_inheritance)
795 mark_parents_nonsimple(tinfo->type);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200796 }
797
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900798 /// Helper function which tags all parents of a type using mult. inheritance
799 void mark_parents_nonsimple(PyTypeObject *value) {
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200800 auto t = reinterpret_borrow<tuple>(value->tp_bases);
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900801 for (handle h : t) {
802 auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
803 if (tinfo2)
804 tinfo2->simple_type = false;
805 mark_parents_nonsimple((PyTypeObject *) h.ptr());
806 }
807 }
808
Wenzel Jakob43398a82015-07-28 16:12:20 +0200809 void install_buffer_funcs(
810 buffer_info *(*get_buffer)(PyObject *, void *),
811 void *get_buffer_data) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200812 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100813 auto tinfo = detail::get_type_info(&type->ht_type);
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100814
815 if (!type->ht_type.tp_as_buffer)
816 pybind11_fail(
817 "To be able to register buffer protocol support for the type '" +
818 std::string(tinfo->type->tp_name) +
819 "' the associated class<>(..) invocation must "
820 "include the pybind11::buffer_protocol() annotation!");
821
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100822 tinfo->get_buffer = get_buffer;
823 tinfo->get_buffer_data = get_buffer_data;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200824 }
825
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100826 void def_property_static_impl(const char *name,
827 handle fget, handle fset,
828 detail::function_record *rec_fget) {
Dean Moldovanc91f8bd2017-02-13 18:11:24 +0100829 const auto is_static = !(rec_fget->is_method && rec_fget->scope);
830 const auto has_doc = rec_fget->doc && pybind11::options::show_user_defined_docstrings();
831
832 if (is_static) {
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100833 auto mclass = handle((PyObject *) Py_TYPE(m_ptr));
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100834
835 if ((PyTypeObject *) mclass.ptr() == &PyType_Type)
836 pybind11_fail(
837 "Adding static properties to the type '" +
838 std::string(((PyTypeObject *) m_ptr)->tp_name) +
839 "' requires the type to have a custom metaclass. Please "
840 "ensure that one is created by supplying the pybind11::metaclass() "
841 "annotation to the associated class_<>(..) invocation.");
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100842 }
Dean Moldovanc91f8bd2017-02-13 18:11:24 +0100843
844 auto property = handle((PyObject *) (is_static ? get_internals().static_property_type
845 : &PyProperty_Type));
846 attr(name) = property(fget.ptr() ? fget : none(),
847 fset.ptr() ? fset : none(),
848 /*deleter*/none(),
849 pybind11::str(has_doc ? rec_fget->doc : ""));
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100850 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200851};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400852
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200853NAMESPACE_END(detail)
854
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400855template <typename type_, typename... options>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100856class class_ : public detail::generic_type {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400857 template <typename T> using is_holder = detail::is_holder_type<type_, T>;
858 template <typename T> using is_subtype = detail::bool_constant<std::is_base_of<type_, T>::value && !std::is_same<T, type_>::value>;
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900859 template <typename T> using is_base = detail::bool_constant<std::is_base_of<T, type_>::value && !std::is_same<T, type_>::value>;
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -0500860 // struct instead of using here to help MSVC:
861 template <typename T> struct is_valid_class_option :
862 detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400863
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200864public:
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400865 using type = type_;
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400866 using type_alias = detail::first_of_t<is_subtype, void, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400867 constexpr static bool has_alias = !std::is_void<type_alias>::value;
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400868 using holder_type = detail::first_of_t<is_holder, std::unique_ptr<type>, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400869 using instance_type = detail::instance<type, holder_type>;
870
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -0500871 static_assert(detail::all_of<is_valid_class_option<options>...>::value,
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400872 "Unknown/invalid class_ template parameters provided");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200873
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200874 PYBIND11_OBJECT(class_, generic_type, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200875
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100876 template <typename... Extra>
877 class_(handle scope, const char *name, const Extra &... extra) {
878 detail::type_record record;
879 record.scope = scope;
880 record.name = name;
881 record.type = &typeid(type);
Jason Rhinelander9c6859e2016-09-08 11:03:08 -0400882 record.type_size = sizeof(detail::conditional_t<has_alias, type_alias, type>);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100883 record.instance_size = sizeof(instance_type);
884 record.init_holder = init_holder;
885 record.dealloc = dealloc;
Pim Schellartcc88aae2017-01-31 10:52:11 -0500886 record.default_holder = std::is_same<holder_type, std::unique_ptr<type>>::value;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200887
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900888 /* Register base classes specified via template arguments to class_, if any */
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900889 bool unused[] = { (add_base<options>(record), false)..., false };
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900890 (void) unused;
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400891
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100892 /* Process optional arguments, if any */
893 detail::process_attributes<Extra...>::init(extra..., &record);
894
Dean Moldovan08cbe8d2017-02-15 21:10:25 +0100895 detail::generic_type::initialize(record);
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200896
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400897 if (has_alias) {
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200898 auto &instances = pybind11::detail::get_internals().registered_types_cpp;
899 instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
900 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100901 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200902
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900903 template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900904 static void add_base(detail::type_record &rec) {
905 rec.add_base(&typeid(Base), [](void *src) -> void * {
906 return static_cast<Base *>(reinterpret_cast<type *>(src));
907 });
908 }
909
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900910 template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900911 static void add_base(detail::type_record &) { }
912
Wenzel Jakob71867832015-07-29 17:43:52 +0200913 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100914 class_ &def(const char *name_, Func&& f, const Extra&... extra) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200915 cpp_function cf(std::forward<Func>(f), name(name_), is_method(*this),
916 sibling(getattr(*this, name_, none())), extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +0200917 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200918 return *this;
919 }
920
Wenzel Jakob71867832015-07-29 17:43:52 +0200921 template <typename Func, typename... Extra> class_ &
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100922 def_static(const char *name_, Func f, const Extra&... extra) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200923 cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
924 sibling(getattr(*this, name_, none())), extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +0200925 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200926 return *this;
927 }
928
Wenzel Jakob71867832015-07-29 17:43:52 +0200929 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100930 class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400931 op.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200932 return *this;
933 }
934
Wenzel Jakob71867832015-07-29 17:43:52 +0200935 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100936 class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400937 op.execute_cast(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200938 return *this;
939 }
940
Wenzel Jakob71867832015-07-29 17:43:52 +0200941 template <typename... Args, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100942 class_ &def(const detail::init<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400943 init.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200944 return *this;
945 }
946
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200947 template <typename... Args, typename... Extra>
948 class_ &def(const detail::init_alias<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400949 init.execute(*this, extra...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200950 return *this;
951 }
952
Wenzel Jakob71867832015-07-29 17:43:52 +0200953 template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob43398a82015-07-28 16:12:20 +0200954 struct capture { Func func; };
955 capture *ptr = new capture { std::forward<Func>(func) };
956 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Dean Moldovan5f07fac2017-01-03 11:52:05 +0100957 detail::make_caster<type> caster;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200958 if (!caster.load(obj, false))
959 return nullptr;
Wenzel Jakob43398a82015-07-28 16:12:20 +0200960 return new buffer_info(((capture *) ptr)->func(caster));
961 }, ptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200962 return *this;
963 }
964
Wenzel Jakob71867832015-07-29 17:43:52 +0200965 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100966 class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100967 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this)),
968 fset([pm](C &c, const D &value) { c.*pm = value; }, is_method(*this));
969 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200970 return *this;
971 }
972
Wenzel Jakob71867832015-07-29 17:43:52 +0200973 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100974 class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100975 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this));
976 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200977 return *this;
978 }
979
Wenzel Jakob71867832015-07-29 17:43:52 +0200980 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100981 class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100982 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
983 fset([pm](object, const D &value) { *pm = value; }, scope(*this));
984 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200985 return *this;
986 }
987
Wenzel Jakob71867832015-07-29 17:43:52 +0200988 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100989 class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100990 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
991 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200992 return *this;
993 }
994
Dean Moldovan03f627e2016-11-01 11:44:57 +0100995 /// Uses return_value_policy::reference_internal by default
996 template <typename Getter, typename... Extra>
997 class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
998 return def_property_readonly(name, cpp_function(fget), return_value_policy::reference_internal, extra...);
999 }
1000
1001 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001002 template <typename... Extra>
1003 class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
Dean Moldovan03f627e2016-11-01 11:44:57 +01001004 return def_property(name, fget, cpp_function(), extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001005 }
1006
Dean Moldovan03f627e2016-11-01 11:44:57 +01001007 /// Uses return_value_policy::reference by default
1008 template <typename Getter, typename... Extra>
1009 class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
1010 return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...);
1011 }
1012
1013 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001014 template <typename... Extra>
1015 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
Dean Moldovan03f627e2016-11-01 11:44:57 +01001016 return def_property_static(name, fget, cpp_function(), extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001017 }
1018
Dean Moldovan03f627e2016-11-01 11:44:57 +01001019 /// Uses return_value_policy::reference_internal by default
1020 template <typename Getter, typename... Extra>
1021 class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1022 return def_property(name, cpp_function(fget), fset, return_value_policy::reference_internal, extra...);
1023 }
1024
1025 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001026 template <typename... Extra>
1027 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001028 return def_property_static(name, fget, fset, is_method(*this), extra...);
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001029 }
1030
Dean Moldovan03f627e2016-11-01 11:44:57 +01001031 /// Uses return_value_policy::reference by default
1032 template <typename Getter, typename... Extra>
1033 class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1034 return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1035 }
1036
1037 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001038 template <typename... Extra>
1039 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1040 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001041 char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001042 detail::process_attributes<Extra...>::init(extra..., rec_fget);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001043 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1044 free(doc_prev);
1045 rec_fget->doc = strdup(rec_fget->doc);
1046 }
1047 if (rec_fset) {
1048 doc_prev = rec_fset->doc;
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001049 detail::process_attributes<Extra...>::init(extra..., rec_fset);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001050 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1051 free(doc_prev);
1052 rec_fset->doc = strdup(rec_fset->doc);
1053 }
1054 }
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001055 def_property_static_impl(name, fget, fset, rec_fget);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001056 return *this;
1057 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001058
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001059private:
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001060 /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1061 template <typename T>
1062 static void init_holder_helper(instance_type *inst, const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001063 try {
hbruintjes70d2e572016-07-01 12:39:55 +02001064 new (&inst->holder) holder_type(std::static_pointer_cast<typename holder_type::element_type>(inst->value->shared_from_this()));
Dean Moldovanab90ec62016-12-07 02:36:44 +01001065 inst->holder_constructed = true;
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001066 } catch (const std::bad_weak_ptr &) {
Dean Moldovanab90ec62016-12-07 02:36:44 +01001067 if (inst->owned) {
1068 new (&inst->holder) holder_type(inst->value);
1069 inst->holder_constructed = true;
1070 }
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001071 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001072 }
1073
Dean Moldovanec009a72017-01-31 17:05:44 +01001074 static void init_holder_from_existing(instance_type *inst, const holder_type *holder_ptr,
1075 std::true_type /*is_copy_constructible*/) {
1076 new (&inst->holder) holder_type(*holder_ptr);
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001077 }
1078
Dean Moldovanec009a72017-01-31 17:05:44 +01001079 static void init_holder_from_existing(instance_type *inst, const holder_type *holder_ptr,
1080 std::false_type /*is_copy_constructible*/) {
1081 new (&inst->holder) holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1082 }
1083
1084 /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
1085 static void init_holder_helper(instance_type *inst, const holder_type *holder_ptr, const void * /* dummy */) {
1086 if (holder_ptr) {
1087 init_holder_from_existing(inst, holder_ptr, std::is_copy_constructible<holder_type>());
1088 inst->holder_constructed = true;
1089 } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
Jason Rhinelanderc07ec312016-11-06 13:12:48 -05001090 new (&inst->holder) holder_type(inst->value);
1091 inst->holder_constructed = true;
1092 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001093 }
1094
1095 /// Initialize holder object of an instance, possibly given a pointer to an existing holder
1096 static void init_holder(PyObject *inst_, const void *holder_ptr) {
1097 auto inst = (instance_type *) inst_;
1098 init_holder_helper(inst, (const holder_type *) holder_ptr, inst->value);
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001099 }
1100
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001101 static void dealloc(PyObject *inst_) {
1102 instance_type *inst = (instance_type *) inst_;
Jason Rhinelanderc07ec312016-11-06 13:12:48 -05001103 if (inst->holder_constructed)
1104 inst->holder.~holder_type();
1105 else if (inst->owned)
1106 ::operator delete(inst->value);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001107 }
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001108
1109 static detail::function_record *get_function_record(handle h) {
1110 h = detail::get_function(h);
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001111 return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
Dean Moldovanc7ac16b2016-10-28 03:08:15 +02001112 : nullptr;
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001113 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001114};
1115
1116/// Binds C++ enumerations and enumeration classes to Python
1117template <typename Type> class enum_ : public class_<Type> {
1118public:
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001119 using class_<Type>::def;
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001120 using Scalar = typename std::underlying_type<Type>::type;
1121 template <typename T> using arithmetic_tag = std::is_same<T, arithmetic>;
1122
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001123 template <typename... Extra>
1124 enum_(const handle &scope, const char *name, const Extra&... extra)
1125 : class_<Type>(scope, name, extra...), m_parent(scope) {
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001126
1127 constexpr bool is_arithmetic =
1128 !std::is_same<detail::first_of_t<arithmetic_tag, void, Extra...>,
1129 void>::value;
1130
1131 auto entries = new std::unordered_map<Scalar, const char *>();
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001132 def("__repr__", [name, entries](Type value) -> std::string {
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001133 auto it = entries->find((Scalar) value);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001134 return std::string(name) + "." +
1135 ((it == entries->end()) ? std::string("???")
1136 : std::string(it->second));
1137 });
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001138 def("__init__", [](Type& value, Scalar i) { value = (Type)i; });
1139 def("__init__", [](Type& value, Scalar i) { new (&value) Type((Type) i); });
1140 def("__int__", [](Type value) { return (Scalar) value; });
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001141 def("__eq__", [](const Type &value, Type *value2) { return value2 && value == *value2; });
1142 def("__ne__", [](const Type &value, Type *value2) { return !value2 || value != *value2; });
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001143 if (is_arithmetic) {
1144 def("__lt__", [](const Type &value, Type *value2) { return value2 && value < *value2; });
1145 def("__gt__", [](const Type &value, Type *value2) { return value2 && value > *value2; });
1146 def("__le__", [](const Type &value, Type *value2) { return value2 && value <= *value2; });
1147 def("__ge__", [](const Type &value, Type *value2) { return value2 && value >= *value2; });
1148 }
1149 if (std::is_convertible<Type, Scalar>::value) {
Jason Rhinelanderd41a2732016-08-04 00:21:37 -04001150 // Don't provide comparison with the underlying type if the enum isn't convertible,
1151 // i.e. if Type is a scoped enum, mirroring the C++ behaviour. (NB: we explicitly
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001152 // convert Type to Scalar below anyway because this needs to compile).
1153 def("__eq__", [](const Type &value, Scalar value2) { return (Scalar) value == value2; });
1154 def("__ne__", [](const Type &value, Scalar value2) { return (Scalar) value != value2; });
1155 if (is_arithmetic) {
1156 def("__lt__", [](const Type &value, Scalar value2) { return (Scalar) value < value2; });
1157 def("__gt__", [](const Type &value, Scalar value2) { return (Scalar) value > value2; });
1158 def("__le__", [](const Type &value, Scalar value2) { return (Scalar) value <= value2; });
1159 def("__ge__", [](const Type &value, Scalar value2) { return (Scalar) value >= value2; });
1160 def("__invert__", [](const Type &value) { return ~((Scalar) value); });
1161 def("__and__", [](const Type &value, Scalar value2) { return (Scalar) value & value2; });
1162 def("__or__", [](const Type &value, Scalar value2) { return (Scalar) value | value2; });
1163 def("__xor__", [](const Type &value, Scalar value2) { return (Scalar) value ^ value2; });
1164 def("__rand__", [](const Type &value, Scalar value2) { return (Scalar) value & value2; });
1165 def("__ror__", [](const Type &value, Scalar value2) { return (Scalar) value | value2; });
1166 def("__rxor__", [](const Type &value, Scalar value2) { return (Scalar) value ^ value2; });
1167 def("__and__", [](const Type &value, const Type &value2) { return (Scalar) value & (Scalar) value2; });
1168 def("__or__", [](const Type &value, const Type &value2) { return (Scalar) value | (Scalar) value2; });
1169 def("__xor__", [](const Type &value, const Type &value2) { return (Scalar) value ^ (Scalar) value2; });
1170 }
Jason Rhinelanderd41a2732016-08-04 00:21:37 -04001171 }
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001172 def("__hash__", [](const Type &value) { return (Scalar) value; });
Wenzel Jakobfe342412016-09-06 13:02:29 +09001173 // Pickling and unpickling -- needed for use with the 'multiprocessing' module
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001174 def("__getstate__", [](const Type &value) { return pybind11::make_tuple((Scalar) value); });
1175 def("__setstate__", [](Type &p, tuple t) { new (&p) Type((Type) t[0].cast<Scalar>()); });
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001176 m_entries = entries;
1177 }
1178
1179 /// Export enumeration entries into the parent scope
Wenzel Jakobe916d842016-11-04 16:51:14 +01001180 enum_ &export_values() {
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001181#if !defined(PYPY_VERSION)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001182 PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict;
1183 PyObject *key, *value;
Wenzel Jakob27e8e102016-01-17 22:36:37 +01001184 ssize_t pos = 0;
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001185
1186 while (PyDict_Next(dict, &pos, &key, &value)) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001187 if (PyObject_IsInstance(value, this->m_ptr))
1188 m_parent.attr(key) = value;
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001189 }
1190#else
1191 /* PyPy's cpyext still has difficulties with the above
1192 CPython API calls; emulate using Python code. */
1193 dict d; d["t"] = *this; d["p"] = m_parent;
1194 PyObject *result = PyRun_String(
1195 "for k, v in t.__dict__.items():\n"
1196 " if isinstance(v, t):\n"
1197 " setattr(p, k, v)\n",
1198 Py_file_input, d.ptr(), d.ptr());
1199 if (result == nullptr)
1200 throw error_already_set();
1201 Py_DECREF(result);
1202#endif
1203
Wenzel Jakobe916d842016-11-04 16:51:14 +01001204 return *this;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001205 }
1206
1207 /// Add an enumeration entry
1208 enum_& value(char const* name, Type value) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001209 this->attr(name) = pybind11::cast(value, return_value_policy::copy);
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001210 (*m_entries)[(Scalar) value] = name;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001211 return *this;
1212 }
1213private:
Wenzel Jakob405f6d12016-11-17 23:24:47 +01001214 std::unordered_map<Scalar, const char *> *m_entries;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001215 handle m_parent;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001216};
1217
1218NAMESPACE_BEGIN(detail)
Wenzel Jakob71867832015-07-29 17:43:52 +02001219template <typename... Args> struct init {
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001220 template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
1221 static void execute(Class &cl, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001222 using Base = typename Class::type;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001223 /// Function which calls a specific C++ in-place constructor
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001224 cl.def("__init__", [](Base *self_, Args... args) { new (self_) Base(args...); }, extra...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001225 }
1226
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001227 template <typename Class, typename... Extra,
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001228 enable_if_t<Class::has_alias &&
1229 std::is_constructible<typename Class::type, Args...>::value, int> = 0>
1230 static void execute(Class &cl, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001231 using Base = typename Class::type;
1232 using Alias = typename Class::type_alias;
1233 handle cl_type = cl;
1234 cl.def("__init__", [cl_type](handle self_, Args... args) {
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001235 if (self_.get_type() == cl_type)
1236 new (self_.cast<Base *>()) Base(args...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001237 else
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001238 new (self_.cast<Alias *>()) Alias(args...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001239 }, extra...);
1240 }
1241
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001242 template <typename Class, typename... Extra,
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001243 enable_if_t<Class::has_alias &&
1244 !std::is_constructible<typename Class::type, Args...>::value, int> = 0>
1245 static void execute(Class &cl, const Extra&... extra) {
1246 init_alias<Args...>::execute(cl, extra...);
1247 }
1248};
1249template <typename... Args> struct init_alias {
1250 template <typename Class, typename... Extra,
1251 enable_if_t<Class::has_alias && std::is_constructible<typename Class::type_alias, Args...>::value, int> = 0>
1252 static void execute(Class &cl, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001253 using Alias = typename Class::type_alias;
1254 cl.def("__init__", [](Alias *self_, Args... args) { new (self_) Alias(args...); }, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001255 }
1256};
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001257
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001258
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001259inline void keep_alive_impl(handle nurse, handle patient) {
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001260 /* Clever approach based on weak references taken from Boost.Python */
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001261 if (!nurse || !patient)
Wenzel Jakob678d7872016-01-17 22:36:41 +01001262 pybind11_fail("Could not activate keep_alive!");
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001263
Ivan Smirnov984c7622016-08-29 02:38:47 +01001264 if (patient.is_none() || nurse.is_none())
Glen Walkerf45bb582016-08-16 17:50:43 +12001265 return; /* Nothing to keep alive or nothing to be kept alive by */
Wenzel Jakob9b880ba2016-04-25 03:25:13 +02001266
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001267 cpp_function disable_lifesupport(
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001268 [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001269
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001270 weakref wr(nurse, disable_lifesupport);
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001271
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001272 patient.inc_ref(); /* reference patient and leak the weak reference */
1273 (void) wr.release();
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001274}
1275
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -05001276PYBIND11_NOINLINE inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
Jason Rhinelander2686da82017-01-21 23:42:14 -05001277 keep_alive_impl(
Jason Rhinelanderbfcf9522017-01-30 13:34:38 -05001278 Nurse == 0 ? ret : Nurse <= call.args.size() ? call.args[Nurse - 1] : handle(),
1279 Patient == 0 ? ret : Patient <= call.args.size() ? call.args[Patient - 1] : handle()
Jason Rhinelander2686da82017-01-21 23:42:14 -05001280 );
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001281}
1282
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001283template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001284struct iterator_state {
1285 Iterator it;
1286 Sentinel end;
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001287 bool first;
1288};
Wenzel Jakobb2825952016-04-13 23:33:00 +02001289
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001290NAMESPACE_END(detail)
1291
Ben Pritchard2de6e1d2016-02-18 13:20:15 -05001292template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); }
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001293template <typename... Args> detail::init_alias<Args...> init_alias() { return detail::init_alias<Args...>(); }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001294
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001295template <return_value_policy Policy = return_value_policy::reference_internal,
1296 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001297 typename Sentinel,
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001298 typename ValueType = decltype(*std::declval<Iterator>()),
1299 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001300iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001301 typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001302
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001303 if (!detail::get_type_info(typeid(state), false)) {
Wenzel Jakob146397e2016-09-06 13:06:31 +09001304 class_<state>(handle(), "iterator")
Wenzel Jakobb2825952016-04-13 23:33:00 +02001305 .def("__iter__", [](state &s) -> state& { return s; })
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001306 .def("__next__", [](state &s) -> ValueType {
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001307 if (!s.first)
1308 ++s.it;
1309 else
1310 s.first = false;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001311 if (s.it == s.end)
1312 throw stop_iteration();
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001313 return *s.it;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001314 }, std::forward<Extra>(extra)..., Policy);
Wenzel Jakobb2825952016-04-13 23:33:00 +02001315 }
1316
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001317 return (iterator) cast(state { first, last, true });
Wenzel Jakobb2825952016-04-13 23:33:00 +02001318}
Wenzel Jakob146397e2016-09-06 13:06:31 +09001319
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001320template <return_value_policy Policy = return_value_policy::reference_internal,
1321 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001322 typename Sentinel,
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001323 typename KeyType = decltype((*std::declval<Iterator>()).first),
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001324 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001325iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001326 typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001327
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001328 if (!detail::get_type_info(typeid(state), false)) {
Wenzel Jakob146397e2016-09-06 13:06:31 +09001329 class_<state>(handle(), "iterator")
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001330 .def("__iter__", [](state &s) -> state& { return s; })
1331 .def("__next__", [](state &s) -> KeyType {
1332 if (!s.first)
1333 ++s.it;
1334 else
1335 s.first = false;
1336 if (s.it == s.end)
1337 throw stop_iteration();
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001338 return (*s.it).first;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001339 }, std::forward<Extra>(extra)..., Policy);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001340 }
1341
1342 return (iterator) cast(state { first, last, true });
1343}
Wenzel Jakobb2825952016-04-13 23:33:00 +02001344
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001345template <return_value_policy Policy = return_value_policy::reference_internal,
1346 typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
1347 return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
Wenzel Jakobbf0c7dc2016-04-18 10:52:12 +02001348}
1349
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001350template <return_value_policy Policy = return_value_policy::reference_internal,
1351 typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
1352 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001353}
1354
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001355template <typename InputType, typename OutputType> void implicitly_convertible() {
Wenzel Jakob2ac50442016-01-17 22:36:35 +01001356 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
Dean Moldovan5f07fac2017-01-03 11:52:05 +01001357 if (!detail::make_caster<InputType>().load(obj, false))
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001358 return nullptr;
1359 tuple args(1);
1360 args[0] = obj;
1361 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1362 if (result == nullptr)
1363 PyErr_Clear();
1364 return result;
1365 };
Ivan Smirnov8f3e0452016-10-23 15:43:03 +01001366
1367 if (auto tinfo = detail::get_type_info(typeid(OutputType)))
1368 tinfo->implicit_conversions.push_back(implicit_caster);
1369 else
Wenzel Jakob678d7872016-01-17 22:36:41 +01001370 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001371}
1372
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001373template <typename ExceptionTranslator>
1374void register_exception_translator(ExceptionTranslator&& translator) {
1375 detail::get_internals().registered_exception_translators.push_front(
1376 std::forward<ExceptionTranslator>(translator));
1377}
1378
1379/* Wrapper to generate a new Python exception type.
1380 *
1381 * This should only be used with PyErr_SetString for now.
1382 * It is not (yet) possible to use as a py::base.
1383 * Template type argument is reserved for future use.
1384 */
1385template <typename type>
1386class exception : public object {
1387public:
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001388 exception(handle scope, const char *name, PyObject *base = PyExc_Exception) {
1389 std::string full_name = scope.attr("__name__").cast<std::string>() +
1390 std::string(".") + name;
Matthew Woehlkee15fa9f2017-02-08 17:43:08 -05001391 m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base, NULL);
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001392 if (hasattr(scope, name))
1393 pybind11_fail("Error during initialization: multiple incompatible "
1394 "definitions with name \"" + std::string(name) + "\"");
1395 scope.attr(name) = *this;
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001396 }
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001397
1398 // Sets the current python exception to this exception object with the given message
1399 void operator()(const char *message) {
1400 PyErr_SetString(m_ptr, message);
1401 }
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001402};
1403
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001404/** Registers a Python exception in `m` of the given `name` and installs an exception translator to
1405 * translate the C++ exception to the created Python exception using the exceptions what() method.
1406 * This is intended for simple exception translations; for more complex translation, register the
1407 * exception object and translator directly.
1408 */
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001409template <typename CppException>
1410exception<CppException> &register_exception(handle scope,
1411 const char *name,
1412 PyObject *base = PyExc_Exception) {
1413 static exception<CppException> ex(scope, name, base);
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001414 register_exception_translator([](std::exception_ptr p) {
1415 if (!p) return;
1416 try {
1417 std::rethrow_exception(p);
Wenzel Jakob281ccc62016-11-16 17:59:56 +01001418 } catch (const CppException &e) {
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001419 ex(e.what());
1420 }
1421 });
1422 return ex;
1423}
1424
Dean Moldovan67990d92016-08-29 18:03:34 +02001425NAMESPACE_BEGIN(detail)
1426PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
1427 auto strings = tuple(args.size());
1428 for (size_t i = 0; i < args.size(); ++i) {
Dean Moldovane18bc022016-10-25 22:12:39 +02001429 strings[i] = str(args[i]);
Dean Moldovan67990d92016-08-29 18:03:34 +02001430 }
Dean Moldovan865e4302016-09-21 01:06:32 +02001431 auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
Dean Moldovan242b1462016-09-08 17:02:04 +02001432 auto line = sep.attr("join")(strings);
Dean Moldovan67990d92016-08-29 18:03:34 +02001433
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001434 object file;
1435 if (kwargs.contains("file")) {
1436 file = kwargs["file"].cast<object>();
1437 } else {
1438 try {
1439 file = module::import("sys").attr("stdout");
esquires67a68f12016-12-01 05:35:34 -05001440 } catch (const error_already_set &) {
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001441 /* If print() is called from code that is executed as
1442 part of garbage collection during interpreter shutdown,
1443 importing 'sys' can fail. Give up rather than crashing the
1444 interpreter in this case. */
1445 return;
1446 }
1447 }
1448
Dean Moldovan242b1462016-09-08 17:02:04 +02001449 auto write = file.attr("write");
Dean Moldovan67990d92016-08-29 18:03:34 +02001450 write(line);
Dean Moldovan865e4302016-09-21 01:06:32 +02001451 write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
Dean Moldovan67990d92016-08-29 18:03:34 +02001452
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001453 if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
Dean Moldovan242b1462016-09-08 17:02:04 +02001454 file.attr("flush")();
Dean Moldovan67990d92016-08-29 18:03:34 +02001455}
1456NAMESPACE_END(detail)
1457
1458template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1459void print(Args &&...args) {
1460 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
1461 detail::print(c.args(), c.kwargs());
1462}
1463
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001464#if defined(WITH_THREAD) && !defined(PYPY_VERSION)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001465
1466/* The functions below essentially reproduce the PyGILState_* API using a RAII
1467 * pattern, but there are a few important differences:
1468 *
1469 * 1. When acquiring the GIL from an non-main thread during the finalization
1470 * phase, the GILState API blindly terminates the calling thread, which
1471 * is often not what is wanted. This API does not do this.
1472 *
1473 * 2. The gil_scoped_release function can optionally cut the relationship
1474 * of a PyThreadState and its associated thread, which allows moving it to
1475 * another thread (this is a fairly rare/advanced use case).
1476 *
1477 * 3. The reference count of an acquired thread state can be controlled. This
1478 * can be handy to prevent cases where callbacks issued from an external
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001479 * thread would otherwise constantly construct and destroy thread state data
1480 * structures.
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001481 *
1482 * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
1483 * example which uses features 2 and 3 to migrate the Python thread of
1484 * execution to another thread (to run the event loop on the original thread,
1485 * in this case).
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001486 */
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001487
1488class gil_scoped_acquire {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001489public:
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001490 PYBIND11_NOINLINE gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001491 auto const &internals = detail::get_internals();
1492 tstate = (PyThreadState *) PyThread_get_key_value(internals.tstate);
1493
1494 if (!tstate) {
1495 tstate = PyThreadState_New(internals.istate);
1496 #if !defined(NDEBUG)
1497 if (!tstate)
1498 pybind11_fail("scoped_acquire: could not create thread state!");
1499 #endif
1500 tstate->gilstate_counter = 0;
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001501 #if PY_MAJOR_VERSION < 3
1502 PyThread_delete_key_value(internals.tstate);
1503 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001504 PyThread_set_key_value(internals.tstate, tstate);
1505 } else {
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001506 release = detail::get_thread_state_unchecked() != tstate;
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001507 }
1508
1509 if (release) {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001510 /* Work around an annoying assertion in PyThreadState_Swap */
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001511 #if defined(Py_DEBUG)
1512 PyInterpreterState *interp = tstate->interp;
1513 tstate->interp = nullptr;
1514 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001515 PyEval_AcquireThread(tstate);
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001516 #if defined(Py_DEBUG)
1517 tstate->interp = interp;
1518 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001519 }
1520
1521 inc_ref();
1522 }
1523
1524 void inc_ref() {
1525 ++tstate->gilstate_counter;
1526 }
1527
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001528 PYBIND11_NOINLINE void dec_ref() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001529 --tstate->gilstate_counter;
1530 #if !defined(NDEBUG)
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001531 if (detail::get_thread_state_unchecked() != tstate)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001532 pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
1533 if (tstate->gilstate_counter < 0)
1534 pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
1535 #endif
1536 if (tstate->gilstate_counter == 0) {
1537 #if !defined(NDEBUG)
1538 if (!release)
1539 pybind11_fail("scoped_acquire::dec_ref(): internal error!");
1540 #endif
1541 PyThreadState_Clear(tstate);
1542 PyThreadState_DeleteCurrent();
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001543 PyThread_delete_key_value(detail::get_internals().tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001544 release = false;
1545 }
1546 }
1547
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001548 PYBIND11_NOINLINE ~gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001549 dec_ref();
1550 if (release)
1551 PyEval_SaveThread();
1552 }
1553private:
1554 PyThreadState *tstate = nullptr;
1555 bool release = true;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001556};
1557
1558class gil_scoped_release {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001559public:
Jason Rhinelander12d76602016-10-16 16:27:42 -04001560 explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001561 tstate = PyEval_SaveThread();
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001562 if (disassoc) {
Boris Schäling20ee9352016-05-28 12:26:18 +02001563 auto key = detail::get_internals().tstate;
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001564 #if PY_MAJOR_VERSION < 3
1565 PyThread_delete_key_value(key);
1566 #else
1567 PyThread_set_key_value(key, nullptr);
1568 #endif
1569 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001570 }
1571 ~gil_scoped_release() {
1572 if (!tstate)
1573 return;
1574 PyEval_RestoreThread(tstate);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001575 if (disassoc) {
Boris Schäling20ee9352016-05-28 12:26:18 +02001576 auto key = detail::get_internals().tstate;
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001577 #if PY_MAJOR_VERSION < 3
1578 PyThread_delete_key_value(key);
1579 #endif
1580 PyThread_set_key_value(key, tstate);
1581 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001582 }
1583private:
1584 PyThreadState *tstate;
1585 bool disassoc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001586};
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001587#elif defined(PYPY_VERSION)
1588class gil_scoped_acquire {
1589 PyGILState_STATE state;
1590public:
1591 gil_scoped_acquire() { state = PyGILState_Ensure(); }
1592 ~gil_scoped_acquire() { PyGILState_Release(state); }
1593};
1594
1595class gil_scoped_release {
1596 PyThreadState *state;
1597public:
1598 gil_scoped_release() { state = PyEval_SaveThread(); }
1599 ~gil_scoped_release() { PyEval_RestoreThread(state); }
1600};
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001601#else
1602class gil_scoped_acquire { };
1603class gil_scoped_release { };
Felipe Lema2547ca42016-01-25 16:22:44 -03001604#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001605
Wenzel Jakob8d396fc2016-11-24 23:11:02 +01001606error_already_set::~error_already_set() {
1607 if (value) {
1608 gil_scoped_acquire gil;
Dean Moldovand534bd62017-02-08 20:23:56 +01001609 clear();
Wenzel Jakob8d396fc2016-11-24 23:11:02 +01001610 }
1611}
1612
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04001613inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001614 handle self = detail::get_object_handle(this_ptr, this_type);
1615 if (!self)
Wenzel Jakobac0fde92015-10-01 18:37:26 +02001616 return function();
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001617 handle type = self.get_type();
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001618 auto key = std::make_pair(type.ptr(), name);
1619
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001620 /* Cache functions that aren't overloaded in Python to avoid
1621 many costly Python dictionary lookups below */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001622 auto &cache = detail::get_internals().inactive_overload_cache;
1623 if (cache.find(key) != cache.end())
1624 return function();
1625
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001626 function overload = getattr(self, name, function());
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001627 if (overload.is_cpp_function()) {
1628 cache.insert(key);
1629 return function();
1630 }
Wenzel Jakob27e8e102016-01-17 22:36:37 +01001631
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001632 /* Don't call dispatch code if invoked from overridden function.
1633 Unfortunately this doesn't work on PyPy. */
1634#if !defined(PYPY_VERSION)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001635 PyFrameObject *frame = PyThreadState_Get()->frame;
Dean Moldovane18bc022016-10-25 22:12:39 +02001636 if (frame && (std::string) str(frame->f_code->co_name) == name &&
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001637 frame->f_code->co_argcount > 0) {
1638 PyFrame_FastToLocals(frame);
1639 PyObject *self_caller = PyDict_GetItem(
1640 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001641 if (self_caller == self.ptr())
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001642 return function();
1643 }
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +01001644#else
1645 /* PyPy currently doesn't provide a detailed cpyext emulation of
1646 frame objects, so we have to emulate this using Python. This
1647 is going to be slow..*/
1648 dict d; d["self"] = self; d["name"] = pybind11::str(name);
1649 PyObject *result = PyRun_String(
1650 "import inspect\n"
1651 "frame = inspect.currentframe()\n"
1652 "if frame is not None:\n"
1653 " frame = frame.f_back\n"
1654 " if frame is not None and str(frame.f_code.co_name) == name and "
1655 "frame.f_code.co_argcount > 0:\n"
1656 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
1657 " if self_caller == self:\n"
1658 " self = None\n",
1659 Py_file_input, d.ptr(), d.ptr());
1660 if (result == nullptr)
1661 throw error_already_set();
1662 if ((handle) d["self"] == Py_None)
1663 return function();
1664 Py_DECREF(result);
1665#endif
1666
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001667 return overload;
1668}
1669
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04001670template <class T> function get_overload(const T *this_ptr, const char *name) {
Ivan Smirnov8f3e0452016-10-23 15:43:03 +01001671 auto tinfo = detail::get_type_info(typeid(T));
1672 return tinfo ? get_type_overload(this_ptr, tinfo, name) : function();
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04001673}
1674
Jason Rhinelander20978262016-08-29 18:16:46 -04001675#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001676 pybind11::gil_scoped_acquire gil; \
Jason Rhinelander20978262016-08-29 18:16:46 -04001677 pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04001678 if (overload) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04001679 auto o = overload(__VA_ARGS__); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04001680 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04001681 static pybind11::detail::overload_caster_t<ret_type> caster; \
1682 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04001683 } \
1684 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
1685 } \
1686 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001687
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001688#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelander20978262016-08-29 18:16:46 -04001689 PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001690 return cname::fn(__VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001691
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001692#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelander20978262016-08-29 18:16:46 -04001693 PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001694 pybind11::pybind11_fail("Tried to call pure virtual function \"" #cname "::" name "\"");
1695
1696#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
1697 PYBIND11_OVERLOAD_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
1698
1699#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
1700 PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001701
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001702NAMESPACE_END(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001703
1704#if defined(_MSC_VER)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001705# pragma warning(pop)
Wenzel Jakob1ffce742016-08-25 01:43:33 +02001706#elif defined(__INTEL_COMPILER)
1707/* Leave ignored warnings on */
Wenzel Jakob6d252962016-05-01 20:47:49 +02001708#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001709# pragma GCC diagnostic pop
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001710#endif