blob: 93f55ef967e146bc931043f783021b77d8498fdf [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"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020037
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020038NAMESPACE_BEGIN(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +020039
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020040/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020041class cpp_function : public function {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020042public:
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020043 cpp_function() { }
Wenzel Jakob38bd7112015-07-05 20:05:44 +020044
Wenzel Jakob5984baa2016-05-10 15:05:03 +010045 /// Construct a cpp_function from a vanilla function pointer
Wenzel Jakob66c9a402016-01-17 22:36:36 +010046 template <typename Return, typename... Args, typename... Extra>
Dean Moldovan5b7e1902016-10-21 18:51:14 +020047 cpp_function(Return (*f)(Args...), const Extra&... extra) {
Wenzel Jakob5984baa2016-05-10 15:05:03 +010048 initialize(f, f, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +020049 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020050
Wenzel Jakob5984baa2016-05-10 15:05:03 +010051 /// Construct a cpp_function from a lambda function (possibly with internal state)
Dean Moldovan5b7e1902016-10-21 18:51:14 +020052 template <typename Func, typename... Extra> cpp_function(Func &&f, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020053 initialize(std::forward<Func>(f),
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020054 (typename detail::remove_class<decltype(
Wenzel Jakob48548ea2016-01-17 22:36:44 +010055 &std::remove_reference<Func>::type::operator())>::type *) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020056 }
57
Wenzel Jakob5984baa2016-05-10 15:05:03 +010058 /// Construct a cpp_function from a class method (non-const)
59 template <typename Return, typename Class, typename... Arg, typename... Extra>
Dean Moldovan5b7e1902016-10-21 18:51:14 +020060 cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020061 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Wenzel Jakob48548ea2016-01-17 22:36:44 +010062 (Return (*) (Class *, Arg...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020063 }
64
Wenzel Jakob5984baa2016-05-10 15:05:03 +010065 /// Construct a cpp_function from a class method (const)
66 template <typename Return, typename Class, typename... Arg, typename... Extra>
Dean Moldovan5b7e1902016-10-21 18:51:14 +020067 cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020068 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Wenzel Jakob48548ea2016-01-17 22:36:44 +010069 (Return (*)(const Class *, Arg ...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020070 }
71
Wenzel Jakob57082212015-09-04 23:42:12 +020072 /// Return the function name
Wenzel Jakob48548ea2016-01-17 22:36:44 +010073 object name() const { return attr("__name__"); }
Wenzel Jakob57082212015-09-04 23:42:12 +020074
Wenzel Jakobd561cb02016-01-17 22:36:41 +010075protected:
Wenzel Jakob382484a2016-09-10 15:28:37 +090076 /// Space optimization: don't inline this frequently instantiated fragment
77 PYBIND11_NOINLINE detail::function_record *make_function_record() {
78 return new detail::function_record();
79 }
80
Wenzel Jakobd561cb02016-01-17 22:36:41 +010081 /// Special internal constructor for functors, lambda functions, etc.
Wenzel Jakob66c9a402016-01-17 22:36:36 +010082 template <typename Func, typename Return, typename... Args, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +010083 void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
Dean Moldovan9e625582016-06-04 00:27:32 +020084 static_assert(detail::expected_num_args<Extra...>(sizeof...(Args)),
85 "The number of named arguments does not match the function signature");
86
Wenzel Jakob66c9a402016-01-17 22:36:36 +010087 struct capture { typename std::remove_reference<Func>::type f; };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020088
Wenzel Jakobd561cb02016-01-17 22:36:41 +010089 /* Store the function including any extra state it might have (e.g. a lambda capture object) */
Wenzel Jakob382484a2016-09-10 15:28:37 +090090 auto rec = make_function_record();
Wenzel Jakob71867832015-07-29 17:43:52 +020091
Wenzel Jakob5984baa2016-05-10 15:05:03 +010092 /* Store the capture object directly in the function record if there is enough space */
93 if (sizeof(capture) <= sizeof(rec->data)) {
Wenzel Jakob954b7932016-07-10 10:13:18 +020094 /* Without these pragmas, GCC warns that there might not be
95 enough space to use the placement new operator. However, the
96 'if' statement above ensures that this is the case. */
Jason Rhinelander0b12f912016-07-07 16:26:04 -040097#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -040098# pragma GCC diagnostic push
99# pragma GCC diagnostic ignored "-Wplacement-new"
100#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100101 new ((capture *) &rec->data) capture { std::forward<Func>(f) };
Jason Rhinelander0b12f912016-07-07 16:26:04 -0400102#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -0400103# pragma GCC diagnostic pop
104#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100105 if (!std::is_trivially_destructible<Func>::value)
106 rec->free_data = [](detail::function_record *r) { ((capture *) &r->data)->~capture(); };
107 } else {
108 rec->data[0] = new capture { std::forward<Func>(f) };
109 rec->free_data = [](detail::function_record *r) { delete ((capture *) r->data[0]); };
110 }
Wenzel Jakob19208fe2015-10-13 17:37:25 +0200111
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100112 /* Type casters for the function arguments and return value */
113 typedef detail::type_caster<typename std::tuple<Args...>> cast_in;
114 typedef detail::type_caster<typename std::conditional<
115 std::is_void<Return>::value, detail::void_type,
116 typename detail::intrinsic_type<Return>::type>::type> cast_out;
Wenzel Jakob71867832015-07-29 17:43:52 +0200117
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100118 /* Dispatch code which converts function arguments and performs the actual function call */
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100119 rec->impl = [](detail::function_record *rec, handle args, handle kwargs, handle parent) -> handle {
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100120 cast_in args_converter;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100121
122 /* Try to cast the function arguments into the C++ domain */
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100123 if (!args_converter.load_args(args, kwargs, true))
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100124 return PYBIND11_TRY_NEXT_OVERLOAD;
125
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100126 /* Invoke call policy pre-call hook */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100127 detail::process_attributes<Extra...>::precall(args);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100128
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100129 /* Get a pointer to the capture object */
130 capture *cap = (capture *) (sizeof(capture) <= sizeof(rec->data)
131 ? &rec->data : rec->data[0]);
132
Wenzel Jakob954b7932016-07-10 10:13:18 +0200133 /* Perform the function call */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100134 handle result = cast_out::cast(args_converter.template call<Return>(cap->f),
135 rec->policy, parent);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100136
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100137 /* Invoke call policy post-call hook */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100138 detail::process_attributes<Extra...>::postcall(args, result);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100139
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100140 return result;
Wenzel Jakob71867832015-07-29 17:43:52 +0200141 };
142
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100143 /* Process any user-provided function attributes */
144 detail::process_attributes<Extra...>::init(extra..., rec);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100145
146 /* Generate a readable signature describing the function's arguments and return value types */
Dean Moldovaned23dda2016-08-04 01:40:40 +0200147 using detail::descr; using detail::_;
148 PYBIND11_DESCR signature = _("(") + cast_in::element_names() + _(") -> ") + cast_out::name();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100149
150 /* Register the function with Python from generic (non-templated) code */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100151 initialize_generic(rec, signature.text(), signature.types(), sizeof...(Args));
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100152
153 if (cast_in::has_args) rec->has_args = true;
154 if (cast_in::has_kwargs) rec->has_kwargs = true;
Wenzel Jakob954b7932016-07-10 10:13:18 +0200155
156 /* Stash some additional information used by an important optimization in 'functional.h' */
157 using FunctionType = Return (*)(Args...);
158 constexpr bool is_function_ptr =
159 std::is_convertible<Func, FunctionType>::value &&
160 sizeof(capture) == sizeof(void *);
161 if (is_function_ptr) {
162 rec->is_stateless = true;
163 rec->data[1] = (void *) &typeid(FunctionType);
164 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200165 }
166
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100167 /// Register a function call with Python (generic non-templated code goes here)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100168 void initialize_generic(detail::function_record *rec, const char *text,
Dean Moldovanecced6c2016-07-31 20:03:18 +0200169 const std::type_info *const *types, size_t args) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100170
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100171 /* Create copies of all referenced C-style strings */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100172 rec->name = strdup(rec->name ? rec->name : "");
173 if (rec->doc) rec->doc = strdup(rec->doc);
174 for (auto &a: rec->args) {
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100175 if (a.name)
176 a.name = strdup(a.name);
177 if (a.descr)
178 a.descr = strdup(a.descr);
179 else if (a.value)
Dean Moldovan242b1462016-09-08 17:02:04 +0200180 a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100181 }
Wenzel Jakob954b7932016-07-10 10:13:18 +0200182
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100183 /* Generate a proper function signature */
184 std::string signature;
185 size_t type_depth = 0, char_index = 0, type_index = 0, arg_index = 0;
186 while (true) {
187 char c = text[char_index++];
188 if (c == '\0')
189 break;
190
191 if (c == '{') {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200192 // Write arg name for everything except *args, **kwargs and return type.
Dean Moldovaned23dda2016-08-04 01:40:40 +0200193 if (type_depth == 0 && text[char_index] != '*' && arg_index < args) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200194 if (!rec->args.empty()) {
195 signature += rec->args[arg_index].name;
196 } else if (arg_index == 0 && rec->class_) {
197 signature += "self";
198 } else {
199 signature += "arg" + std::to_string(arg_index - (rec->class_ ? 1 : 0));
200 }
201 signature += ": ";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100202 }
203 ++type_depth;
204 } else if (c == '}') {
205 --type_depth;
Dean Moldovaned23dda2016-08-04 01:40:40 +0200206 if (type_depth == 0) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200207 if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
208 signature += "=";
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100209 signature += rec->args[arg_index].descr;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100210 }
211 arg_index++;
212 }
213 } else if (c == '%') {
214 const std::type_info *t = types[type_index++];
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100215 if (!t)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100216 pybind11_fail("Internal error while parsing type signature (1)");
Ivan Smirnov8f3e0452016-10-23 15:43:03 +0100217 if (auto tinfo = detail::get_type_info(*t)) {
218 signature += tinfo->type->tp_name;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100219 } else {
220 std::string tname(t->name());
221 detail::clean_type_id(tname);
222 signature += tname;
223 }
224 } else {
225 signature += c;
226 }
227 }
Wenzel Jakob95d18692016-01-17 22:36:40 +0100228 if (type_depth != 0 || types[type_index] != nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100229 pybind11_fail("Internal error while parsing type signature (2)");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100230
231 #if !defined(PYBIND11_CPP14)
232 delete[] types;
233 delete[] text;
234 #endif
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200235
Wenzel Jakob57082212015-09-04 23:42:12 +0200236#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100237 if (strcmp(rec->name, "__next__") == 0) {
238 std::free(rec->name);
239 rec->name = strdup("next");
Wenzel Jakobd1bfc4e2016-05-16 18:52:46 +0200240 } else if (strcmp(rec->name, "__bool__") == 0) {
241 std::free(rec->name);
242 rec->name = strdup("__nonzero__");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100243 }
Wenzel Jakob57082212015-09-04 23:42:12 +0200244#endif
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100245 rec->signature = strdup(signature.c_str());
246 rec->args.shrink_to_fit();
Wenzel Jakoba380ed92016-05-15 23:54:13 +0200247 rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
Wenzel Jakobaffb9f42016-05-15 23:55:06 +0200248 rec->nargs = (uint16_t) args;
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200249
Wenzel Jakob57082212015-09-04 23:42:12 +0200250#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100251 if (rec->sibling && PyMethod_Check(rec->sibling.ptr()))
252 rec->sibling = PyMethod_GET_FUNCTION(rec->sibling.ptr());
Wenzel Jakob57082212015-09-04 23:42:12 +0200253#endif
254
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100255 detail::function_record *chain = nullptr, *chain_start = rec;
Jason Rhinelander6873c202016-10-24 21:58:22 -0400256 if (rec->sibling) {
257 if (PyCFunction_Check(rec->sibling.ptr())) {
258 capsule rec_capsule(PyCFunction_GetSelf(rec->sibling.ptr()), true);
259 chain = (detail::function_record *) rec_capsule;
260 /* Never append a method to an overload chain of a parent class;
261 instead, hide the parent's overloads in this case */
262 if (chain->class_ != rec->class_)
263 chain = nullptr;
264 }
265 // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
266 else if (!rec->sibling.is_none() && rec->name[0] != '_')
267 pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
268 "\" with a function of the same name");
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200269 }
270
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100271 if (!chain) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100272 /* No existing overload was found, create a new function object */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100273 rec->def = new PyMethodDef();
274 memset(rec->def, 0, sizeof(PyMethodDef));
275 rec->def->ml_name = rec->name;
276 rec->def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
277 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
Wenzel Jakoba6501792016-02-04 23:02:07 +0100278
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100279 capsule rec_capsule(rec, [](PyObject *o) {
280 destruct((detail::function_record *) PyCapsule_GetPointer(o, nullptr));
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100281 });
Wenzel Jakoba6501792016-02-04 23:02:07 +0100282
283 object scope_module;
284 if (rec->scope) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200285 if (hasattr(rec->scope, "__module__")) {
286 scope_module = rec->scope.attr("__module__");
287 } else if (hasattr(rec->scope, "__name__")) {
288 scope_module = rec->scope.attr("__name__");
289 }
Wenzel Jakoba6501792016-02-04 23:02:07 +0100290 }
291
292 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200293 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100294 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200295 } else {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100296 /* Append at the end of the overload chain */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100297 m_ptr = rec->sibling.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200298 inc_ref();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100299 chain_start = chain;
300 while (chain->next)
301 chain = chain->next;
302 chain->next = rec;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200303 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200304
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200305 std::string signatures;
Wenzel Jakob71867832015-07-29 17:43:52 +0200306 int index = 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100307 /* Create a nice pydoc rec including all signatures and
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100308 docstrings of the functions in the overload chain */
Sylvain Corlay0e04fdf2016-03-08 16:42:12 -0500309 if (chain) {
310 // First a generic signature
311 signatures += rec->name;
312 signatures += "(*args, **kwargs)\n";
313 signatures += "Overloaded function.\n\n";
314 }
315 // Then specific overload signatures
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100316 for (auto it = chain_start; it != nullptr; it = it->next) {
317 if (chain)
Wenzel Jakob71867832015-07-29 17:43:52 +0200318 signatures += std::to_string(++index) + ". ";
Sylvain Corlay13b22bf2016-02-28 21:23:39 -0500319 signatures += rec->name;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100320 signatures += it->signature;
321 signatures += "\n";
322 if (it->doc && strlen(it->doc) > 0) {
323 signatures += "\n";
Wenzel Jakob218b6ce2016-02-28 23:52:37 +0100324 signatures += it->doc;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100325 signatures += "\n";
326 }
Wenzel Jakob71867832015-07-29 17:43:52 +0200327 if (it->next)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200328 signatures += "\n";
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200329 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100330
331 /* Install docstring */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200332 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
333 if (func->m_ml->ml_doc)
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100334 std::free((char *) func->m_ml->ml_doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200335 func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100336
337 if (rec->class_) {
338 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->class_.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200339 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100340 pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200341 Py_DECREF(func);
342 }
343 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100344
345 /// When a cpp_function is GCed, release any memory allocated by pybind11
346 static void destruct(detail::function_record *rec) {
347 while (rec) {
348 detail::function_record *next = rec->next;
349 if (rec->free_data)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100350 rec->free_data(rec);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100351 std::free((char *) rec->name);
352 std::free((char *) rec->doc);
353 std::free((char *) rec->signature);
354 for (auto &arg: rec->args) {
355 std::free((char *) arg.name);
356 std::free((char *) arg.descr);
357 arg.value.dec_ref();
358 }
359 if (rec->def) {
360 std::free((char *) rec->def->ml_doc);
361 delete rec->def;
362 }
363 delete rec;
364 rec = next;
365 }
366 }
367
368 /// Main dispatch logic for calls to functions bound using pybind11
369 static PyObject *dispatcher(PyObject *self, PyObject *args, PyObject *kwargs) {
370 /* Iterator over the list of potentially admissible overloads */
371 detail::function_record *overloads = (detail::function_record *) PyCapsule_GetPointer(self, nullptr),
372 *it = overloads;
373
374 /* Need to know how many arguments + keyword arguments there are to pick the right overload */
Wenzel Jakob0a078052016-05-29 13:40:40 +0200375 size_t nargs = (size_t) PyTuple_GET_SIZE(args),
376 nkwargs = kwargs ? (size_t) PyDict_Size(kwargs) : 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100377
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100378 handle parent = nargs > 0 ? PyTuple_GET_ITEM(args, 0) : nullptr,
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100379 result = PYBIND11_TRY_NEXT_OVERLOAD;
380 try {
381 for (; it != nullptr; it = it->next) {
382 tuple args_(args, true);
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100383 size_t kwargs_consumed = 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100384
385 /* For each overload:
386 1. If the required list of arguments is longer than the
387 actually provided amount, create a copy of the argument
388 list and fill in any available keyword/default arguments.
389 2. Ensure that all keyword arguments were "consumed"
390 3. Call the function call dispatcher (function_record::impl)
391 */
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100392 size_t nargs_ = nargs;
393 if (nargs < it->args.size()) {
394 nargs_ = it->args.size();
395 args_ = tuple(nargs_);
396 for (size_t i = 0; i < nargs; ++i) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100397 handle item = PyTuple_GET_ITEM(args, i);
398 PyTuple_SET_ITEM(args_.ptr(), i, item.inc_ref().ptr());
399 }
400
401 int arg_ctr = 0;
402 for (auto const &it2 : it->args) {
403 int index = arg_ctr++;
404 if (PyTuple_GET_ITEM(args_.ptr(), index))
405 continue;
406
407 handle value;
408 if (kwargs)
409 value = PyDict_GetItemString(kwargs, it2.name);
410
411 if (value)
412 kwargs_consumed++;
413 else if (it2.value)
414 value = it2.value;
415
416 if (value) {
417 PyTuple_SET_ITEM(args_.ptr(), index, value.inc_ref().ptr());
418 } else {
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100419 kwargs_consumed = (size_t) -1; /* definite failure */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100420 break;
421 }
422 }
423 }
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200424
425 try {
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100426 if ((kwargs_consumed == nkwargs || it->has_kwargs) &&
427 (nargs_ == it->nargs || it->has_args))
428 result = it->impl(it, args_, kwargs, parent);
Wenzel Jakob00062592016-07-01 16:07:35 +0200429 } catch (reference_cast_error &) {
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200430 result = PYBIND11_TRY_NEXT_OVERLOAD;
431 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100432
433 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
434 break;
435 }
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200436 } catch (error_already_set &e) {
437 e.restore();
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400438 return nullptr;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100439 } catch (...) {
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400440 /* When an exception is caught, give each registered exception
441 translator a chance to translate it to a Python exception
442 in reverse order of registration.
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200443
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400444 A translator may choose to do one of the following:
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200445
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400446 - catch the exception and call PyErr_SetString or PyErr_SetObject
447 to set a standard (or custom) Python exception, or
448 - do nothing and let the exception fall through to the next translator, or
449 - delegate translation to the next translator by throwing a new type of exception. */
450
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200451 auto last_exception = std::current_exception();
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400452 auto &registered_exception_translators = pybind11::detail::get_internals().registered_exception_translators;
453 for (auto& translator : registered_exception_translators) {
454 try {
455 translator(last_exception);
456 } catch (...) {
457 last_exception = std::current_exception();
458 continue;
459 }
460 return nullptr;
461 }
462 PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100463 return nullptr;
464 }
465
466 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
Wenzel Jakob382484a2016-09-10 15:28:37 +0900467 if (overloads->is_operator)
468 return handle(Py_NotImplemented).inc_ref().ptr();
469
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900470 std::string msg = std::string(overloads->name) + "(): incompatible " +
471 std::string(overloads->is_constructor ? "constructor" : "function") +
472 " arguments. The following argument types are supported:\n";
473
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100474 int ctr = 0;
475 for (detail::function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
476 msg += " "+ std::to_string(++ctr) + ". ";
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400477
478 bool wrote_sig = false;
479 if (overloads->is_constructor) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200480 // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400481 std::string sig = it2->signature;
Dean Moldovanecced6c2016-07-31 20:03:18 +0200482 size_t start = sig.find('(') + 7; // skip "(self: "
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400483 if (start < sig.size()) {
484 // End at the , for the next argument
485 size_t end = sig.find(", "), next = end + 2;
486 size_t ret = sig.rfind(" -> ");
487 // Or the ), if there is no comma:
488 if (end >= sig.size()) next = end = sig.find(')');
489 if (start < end && next < sig.size()) {
490 msg.append(sig, start, end - start);
491 msg += '(';
492 msg.append(sig, next, ret - next);
493 wrote_sig = true;
494 }
495 }
496 }
497 if (!wrote_sig) msg += it2->signature;
498
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100499 msg += "\n";
500 }
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900501 msg += "\nInvoked with: ";
Andreas Bergmeier16d43942016-05-24 09:19:35 +0200502 tuple args_(args, true);
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200503 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
Andreas Bergmeier16d43942016-05-24 09:19:35 +0200504 msg += static_cast<std::string>(static_cast<object>(args_[ti]).str());
505 if ((ti + 1) != args_.size() )
506 msg += ", ";
507 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100508 PyErr_SetString(PyExc_TypeError, msg.c_str());
509 return nullptr;
510 } else if (!result) {
511 std::string msg = "Unable to convert function return value to a "
512 "Python type! The signature was\n\t";
513 msg += it->signature;
514 PyErr_SetString(PyExc_TypeError, msg.c_str());
515 return nullptr;
516 } else {
517 if (overloads->is_constructor) {
Wenzel Jakob772c6d52016-04-30 19:56:10 +0200518 /* When a constructor ran successfully, the corresponding
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100519 holder type (e.g. std::unique_ptr) must still be initialized. */
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100520 PyObject *inst = PyTuple_GET_ITEM(args, 0);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100521 auto tinfo = detail::get_type_info(Py_TYPE(inst));
522 tinfo->init_holder(inst, nullptr);
523 }
524 return result.ptr();
525 }
526 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200527};
528
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100529/// Wrapper for Python extension modules
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200530class module : public object {
531public:
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200532 PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200533
Jason Rhinelander12d76602016-10-16 16:27:42 -0400534 explicit module(const char *name, const char *doc = nullptr) {
Wenzel Jakob57082212015-09-04 23:42:12 +0200535#if PY_MAJOR_VERSION >= 3
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200536 PyModuleDef *def = new PyModuleDef();
537 memset(def, 0, sizeof(PyModuleDef));
538 def->m_name = name;
539 def->m_doc = doc;
540 def->m_size = -1;
541 Py_INCREF(def);
542 m_ptr = PyModule_Create(def);
Wenzel Jakob57082212015-09-04 23:42:12 +0200543#else
544 m_ptr = Py_InitModule3(name, nullptr, doc);
545#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200546 if (m_ptr == nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100547 pybind11_fail("Internal error in module::module()");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200548 inc_ref();
549 }
550
Wenzel Jakob71867832015-07-29 17:43:52 +0200551 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100552 module &def(const char *name_, Func &&f, const Extra& ... extra) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200553 cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
554 sibling(getattr(*this, name_, none())), extra...);
Jason Rhinelander6873c202016-10-24 21:58:22 -0400555 // NB: allow overwriting here because cpp_function sets up a chain with the intention of
556 // overwriting (and has already checked internally that it isn't overwriting non-functions).
557 add_object(name_, func, true /* overwrite */);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200558 return *this;
559 }
560
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200561 module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200562 std::string full_name = std::string(PyModule_GetName(m_ptr))
563 + std::string(".") + std::string(name);
564 module result(PyImport_AddModule(full_name.c_str()), true);
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200565 if (doc)
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200566 result.attr("__doc__") = pybind11::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200567 attr(name) = result;
568 return result;
569 }
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200570
571 static module import(const char *name) {
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100572 PyObject *obj = PyImport_ImportModule(name);
573 if (!obj)
Wenzel Jakobc49d6e52016-10-13 10:34:52 +0200574 throw import_error("Module \"" + std::string(name) + "\" not found!");
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100575 return module(obj, false);
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200576 }
Jason Rhinelander6873c202016-10-24 21:58:22 -0400577
578 // Adds an object to the module using the given name. Throws if an object with the given name
579 // already exists.
580 //
581 // overwrite should almost always be false: attempting to overwrite objects that pybind11 has
582 // established will, in most cases, break things.
583 PYBIND11_NOINLINE void add_object(const char *name, object &obj, bool overwrite = false) {
584 if (!overwrite && hasattr(*this, name))
585 pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
586 std::string(name) + "\"");
587
588 obj.inc_ref(); // PyModule_AddObject() steals a reference
589 PyModule_AddObject(ptr(), name, obj.ptr());
590 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200591};
592
593NAMESPACE_BEGIN(detail)
Dean Moldovan6fccf692016-10-11 01:12:48 +0200594extern "C" inline PyObject *get_dict(PyObject *op, void *) {
Dean Moldovan22726c92016-10-12 23:20:32 +0200595 PyObject *&dict = *_PyObject_GetDictPtr(op);
596 if (!dict) {
597 dict = PyDict_New();
Dean Moldovan6fccf692016-10-11 01:12:48 +0200598 }
Dean Moldovan22726c92016-10-12 23:20:32 +0200599 Py_XINCREF(dict);
600 return dict;
Dean Moldovan6fccf692016-10-11 01:12:48 +0200601}
602
Dean Moldovan22726c92016-10-12 23:20:32 +0200603extern "C" inline int set_dict(PyObject *op, PyObject *new_dict, void *) {
604 if (!PyDict_Check(new_dict)) {
Dean Moldovan6fccf692016-10-11 01:12:48 +0200605 PyErr_Format(PyExc_TypeError, "__dict__ must be set to a dictionary, not a '%.200s'",
Dean Moldovan22726c92016-10-12 23:20:32 +0200606 Py_TYPE(new_dict)->tp_name);
Dean Moldovan6fccf692016-10-11 01:12:48 +0200607 return -1;
608 }
Dean Moldovan22726c92016-10-12 23:20:32 +0200609 PyObject *&dict = *_PyObject_GetDictPtr(op);
610 Py_INCREF(new_dict);
611 Py_CLEAR(dict);
612 dict = new_dict;
Dean Moldovan6fccf692016-10-11 01:12:48 +0200613 return 0;
614}
615
616static PyGetSetDef generic_getset[] = {
617 {const_cast<char*>("__dict__"), get_dict, set_dict, nullptr, nullptr},
618 {nullptr, nullptr, nullptr, nullptr, nullptr}
619};
620
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100621/// Generic support for creating new Python heap types
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100622class generic_type : public object {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400623 template <typename...> friend class class_;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200624public:
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100625 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100626protected:
627 void initialize(type_record *rec) {
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200628 auto &internals = get_internals();
629 auto tindex = std::type_index(*(rec->type));
630
Ivan Smirnov8f3e0452016-10-23 15:43:03 +0100631 if (get_type_info(*(rec->type)))
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200632 pybind11_fail("generic_type: type \"" + std::string(rec->name) +
633 "\" is already registered!");
634
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100635 object name(PYBIND11_FROM_STRING(rec->name), false);
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200636 object scope_module;
637 if (rec->scope) {
Jason Rhinelander6873c202016-10-24 21:58:22 -0400638 if (hasattr(rec->scope, rec->name))
639 pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec->name) +
640 "\": an object with that name is already defined");
641
Dean Moldovan865e4302016-09-21 01:06:32 +0200642 if (hasattr(rec->scope, "__module__")) {
643 scope_module = rec->scope.attr("__module__");
644 } else if (hasattr(rec->scope, "__name__")) {
645 scope_module = rec->scope.attr("__name__");
646 }
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200647 }
648
649#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
650 /* Qualified names for Python >= 3.3 */
651 object scope_qualname;
Dean Moldovan865e4302016-09-21 01:06:32 +0200652 if (rec->scope && hasattr(rec->scope, "__qualname__"))
653 scope_qualname = rec->scope.attr("__qualname__");
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200654 object ht_qualname;
655 if (scope_qualname) {
656 ht_qualname = object(PyUnicode_FromFormat(
657 "%U.%U", scope_qualname.ptr(), name.ptr()), false);
658 } else {
659 ht_qualname = name;
660 }
661#endif
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900662
663 size_t num_bases = rec->bases.size();
664 tuple bases(num_bases);
665 for (size_t i = 0; i < num_bases; ++i)
666 bases[i] = rec->bases[i];
667
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200668 std::string full_name = (scope_module ? ((std::string) scope_module.str() + "." + rec->name)
669 : std::string(rec->name));
670
671 char *tp_doc = nullptr;
672 if (rec->doc) {
673 /* Allocate memory for docstring (using PyObject_MALLOC, since
674 Python will free this later on) */
675 size_t size = strlen(rec->doc) + 1;
676 tp_doc = (char *) PyObject_MALLOC(size);
677 memcpy((void *) tp_doc, rec->doc, size);
678 }
679
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900680 /* Danger zone: from now (and until PyType_Ready), make sure to
681 issue no Python C API calls which could potentially invoke the
682 garbage collector (the GC will call type_traverse(), which will in
683 turn find the newly constructed type in an invalid state) */
684
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200685 object type_holder(PyType_Type.tp_alloc(&PyType_Type, 0), false);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100686 auto type = (PyHeapTypeObject*) type_holder.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200687
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100688 if (!type_holder || !name)
Wenzel Jakobe72a6762016-09-14 23:39:16 +0800689 pybind11_fail(std::string(rec->name) + ": Unable to create type object!");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200690
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100691 /* Register supplemental type information in C++ dict */
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100692 detail::type_info *tinfo = new detail::type_info();
693 tinfo->type = (PyTypeObject *) type;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100694 tinfo->type_size = rec->type_size;
695 tinfo->init_holder = rec->init_holder;
Ivan Smirnova6e6a8b2016-10-23 15:27:13 +0100696 tinfo->direct_conversions = &internals.direct_conversions[tindex];
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200697 internals.registered_types_cpp[tindex] = tinfo;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100698 internals.registered_types_py[type] = tinfo;
699
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100700 /* Basic type attributes */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200701 type->ht_type.tp_name = strdup(full_name.c_str());
Wenzel Jakob0a078052016-05-29 13:40:40 +0200702 type->ht_type.tp_basicsize = (ssize_t) rec->instance_size;
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900703
704 if (num_bases > 0) {
705 type->ht_type.tp_base = (PyTypeObject *) ((object) bases[0]).inc_ref().ptr();
706 type->ht_type.tp_bases = bases.release().ptr();
707 rec->multiple_inheritance |= num_bases > 1;
708 }
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100709
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100710 type->ht_name = name.release().ptr();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100711
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200712#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
713 type->ht_qualname = ht_qualname.release().ptr();
714#endif
715
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100716 /* Supported protocols */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200717 type->ht_type.tp_as_number = &type->as_number;
718 type->ht_type.tp_as_sequence = &type->as_sequence;
719 type->ht_type.tp_as_mapping = &type->as_mapping;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100720
721 /* Supported elementary operations */
722 type->ht_type.tp_init = (initproc) init;
723 type->ht_type.tp_new = (newfunc) new_instance;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100724 type->ht_type.tp_dealloc = rec->dealloc;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100725
726 /* Support weak references (needed for the keep_alive feature) */
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100727 type->ht_type.tp_weaklistoffset = offsetof(instance_essentials<void>, weakrefs);
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100728
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100729 /* Flags */
730 type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
731#if PY_MAJOR_VERSION < 3
732 type->ht_type.tp_flags |= Py_TPFLAGS_CHECKTYPES;
733#endif
734 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
735
Dean Moldovan6fccf692016-10-11 01:12:48 +0200736 /* Support dynamic attributes */
737 if (rec->dynamic_attr) {
738 type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_GC;
Dean Moldovan22726c92016-10-12 23:20:32 +0200739 type->ht_type.tp_dictoffset = type->ht_type.tp_basicsize; // place the dict at the end
740 type->ht_type.tp_basicsize += sizeof(PyObject *); // and allocate enough space for it
Dean Moldovan6fccf692016-10-11 01:12:48 +0200741 type->ht_type.tp_getset = generic_getset;
742 type->ht_type.tp_traverse = traverse;
743 type->ht_type.tp_clear = clear;
744 }
745
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200746 type->ht_type.tp_doc = tp_doc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200747
748 if (PyType_Ready(&type->ht_type) < 0)
Wenzel Jakobe72a6762016-09-14 23:39:16 +0800749 pybind11_fail(std::string(rec->name) + ": PyType_Ready failed (" +
750 detail::error_string() + ")!");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200751
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100752 m_ptr = type_holder.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200753
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100754 if (scope_module) // Needed by pydoc
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100755 attr("__module__") = scope_module;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200756
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100757 /* Register type with the parent scope */
Wenzel Jakobb2825952016-04-13 23:33:00 +0200758 if (rec->scope)
759 rec->scope.attr(handle(type->ht_name)) = *this;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100760
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900761 if (rec->multiple_inheritance)
762 mark_parents_nonsimple(&type->ht_type);
763
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100764 type_holder.release();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200765 }
766
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900767 /// Helper function which tags all parents of a type using mult. inheritance
768 void mark_parents_nonsimple(PyTypeObject *value) {
769 tuple t(value->tp_bases, true);
770 for (handle h : t) {
771 auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
772 if (tinfo2)
773 tinfo2->simple_type = false;
774 mark_parents_nonsimple((PyTypeObject *) h.ptr());
775 }
776 }
777
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100778 /// Allocate a metaclass on demand (for static properties)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200779 handle metaclass() {
780 auto &ht_type = ((PyHeapTypeObject *) m_ptr)->ht_type;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100781 auto &ob_type = PYBIND11_OB_TYPE(ht_type);
Wenzel Jakob57082212015-09-04 23:42:12 +0200782
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200783 if (ob_type == &PyType_Type) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100784 std::string name_ = std::string(ht_type.tp_name) + "__Meta";
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200785#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
Dean Moldovan242b1462016-09-08 17:02:04 +0200786 object ht_qualname(PyUnicode_FromFormat("%U__Meta", attr("__qualname__").ptr()), false);
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200787#endif
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100788 object name(PYBIND11_FROM_STRING(name_.c_str()), false);
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200789 object type_holder(PyType_Type.tp_alloc(&PyType_Type, 0), false);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100790 if (!type_holder || !name)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100791 pybind11_fail("generic_type::metaclass(): unable to create type object!");
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100792
793 auto type = (PyHeapTypeObject*) type_holder.ptr();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100794 type->ht_name = name.release().ptr();
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200795
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100796#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
797 /* Qualified names for Python >= 3.3 */
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200798 type->ht_qualname = ht_qualname.release().ptr();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100799#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200800 type->ht_type.tp_name = strdup(name_.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100801 type->ht_type.tp_base = ob_type;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100802 type->ht_type.tp_flags |= (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE) &
803 ~Py_TPFLAGS_HAVE_GC;
804
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200805 if (PyType_Ready(&type->ht_type) < 0)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100806 pybind11_fail("generic_type::metaclass(): PyType_Ready failed!");
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100807
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100808 ob_type = (PyTypeObject *) type_holder.release().ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200809 }
810 return handle((PyObject *) ob_type);
811 }
812
813 static int init(void *self, PyObject *, PyObject *) {
814 std::string msg = std::string(Py_TYPE(self)->tp_name) + ": No constructor defined!";
815 PyErr_SetString(PyExc_TypeError, msg.c_str());
816 return -1;
817 }
818
819 static PyObject *new_instance(PyTypeObject *type, PyObject *, PyObject *) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100820 instance<void> *self = (instance<void> *) PyType_GenericAlloc((PyTypeObject *) type, 0);
821 auto tinfo = detail::get_type_info(type);
822 self->value = ::operator new(tinfo->type_size);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200823 self->owned = true;
Jason Rhinelanderc07ec312016-11-06 13:12:48 -0500824 self->holder_constructed = false;
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400825 detail::get_internals().registered_instances.emplace(self->value, (PyObject *) self);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200826 return (PyObject *) self;
827 }
828
829 static void dealloc(instance<void> *self) {
830 if (self->value) {
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400831 auto instance_type = Py_TYPE(self);
832 auto &registered_instances = detail::get_internals().registered_instances;
833 auto range = registered_instances.equal_range(self->value);
834 bool found = false;
835 for (auto it = range.first; it != range.second; ++it) {
836 if (instance_type == Py_TYPE(it->second)) {
837 registered_instances.erase(it);
838 found = true;
839 break;
840 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200841 }
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400842 if (!found)
843 pybind11_fail("generic_type::dealloc(): Tried to deallocate unregistered instance!");
844
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100845 if (self->weakrefs)
846 PyObject_ClearWeakRefs((PyObject *) self);
Dean Moldovan6fccf692016-10-11 01:12:48 +0200847
Dean Moldovan22726c92016-10-12 23:20:32 +0200848 PyObject **dict_ptr = _PyObject_GetDictPtr((PyObject *) self);
849 if (dict_ptr) {
850 Py_CLEAR(*dict_ptr);
851 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200852 }
853 Py_TYPE(self)->tp_free((PyObject*) self);
854 }
855
Dean Moldovan6fccf692016-10-11 01:12:48 +0200856 static int traverse(PyObject *op, visitproc visit, void *arg) {
Dean Moldovan22726c92016-10-12 23:20:32 +0200857 PyObject *&dict = *_PyObject_GetDictPtr(op);
858 Py_VISIT(dict);
Dean Moldovan6fccf692016-10-11 01:12:48 +0200859 return 0;
860 }
861
862 static int clear(PyObject *op) {
Dean Moldovan22726c92016-10-12 23:20:32 +0200863 PyObject *&dict = *_PyObject_GetDictPtr(op);
864 Py_CLEAR(dict);
Dean Moldovan6fccf692016-10-11 01:12:48 +0200865 return 0;
866 }
867
Wenzel Jakob43398a82015-07-28 16:12:20 +0200868 void install_buffer_funcs(
869 buffer_info *(*get_buffer)(PyObject *, void *),
870 void *get_buffer_data) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200871 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
872 type->ht_type.tp_as_buffer = &type->as_buffer;
Wenzel Jakob57082212015-09-04 23:42:12 +0200873#if PY_MAJOR_VERSION < 3
874 type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
875#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200876 type->as_buffer.bf_getbuffer = getbuffer;
877 type->as_buffer.bf_releasebuffer = releasebuffer;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100878 auto tinfo = detail::get_type_info(&type->ht_type);
879 tinfo->get_buffer = get_buffer;
880 tinfo->get_buffer_data = get_buffer_data;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200881 }
882
883 static int getbuffer(PyObject *obj, Py_buffer *view, int flags) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100884 auto tinfo = detail::get_type_info(Py_TYPE(obj));
885 if (view == nullptr || obj == nullptr || !tinfo || !tinfo->get_buffer) {
886 PyErr_SetString(PyExc_BufferError, "generic_type::getbuffer(): Internal error");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200887 return -1;
888 }
889 memset(view, 0, sizeof(Py_buffer));
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100890 buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200891 view->obj = obj;
892 view->ndim = 1;
893 view->internal = info;
894 view->buf = info->ptr;
Wenzel Jakob0a078052016-05-29 13:40:40 +0200895 view->itemsize = (ssize_t) info->itemsize;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200896 view->len = view->itemsize;
897 for (auto s : info->shape)
898 view->len *= s;
899 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
900 view->format = const_cast<char *>(info->format.c_str());
901 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
Wenzel Jakob0a078052016-05-29 13:40:40 +0200902 view->ndim = (int) info->ndim;
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100903 view->strides = (ssize_t *) &info->strides[0];
904 view->shape = (ssize_t *) &info->shape[0];
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200905 }
906 Py_INCREF(view->obj);
907 return 0;
908 }
909
910 static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; }
911};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400912
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200913NAMESPACE_END(detail)
914
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400915template <typename type_, typename... options>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100916class class_ : public detail::generic_type {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400917 template <typename T> using is_holder = detail::is_holder_type<type_, T>;
918 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 +0900919 template <typename T> using is_base = detail::bool_constant<std::is_base_of<T, type_>::value && !std::is_same<T, type_>::value>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400920 template <typename T> using is_valid_class_option =
921 detail::bool_constant<
922 is_holder<T>::value ||
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400923 is_subtype<T>::value ||
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900924 is_base<T>::value
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400925 >;
926
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200927public:
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400928 using type = type_;
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400929 using type_alias = detail::first_of_t<is_subtype, void, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400930 constexpr static bool has_alias = !std::is_void<type_alias>::value;
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400931 using holder_type = detail::first_of_t<is_holder, std::unique_ptr<type>, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400932 using instance_type = detail::instance<type, holder_type>;
933
934 static_assert(detail::all_of_t<is_valid_class_option, options...>::value,
935 "Unknown/invalid class_ template parameters provided");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200936
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100937 PYBIND11_OBJECT(class_, detail::generic_type, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200938
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100939 template <typename... Extra>
940 class_(handle scope, const char *name, const Extra &... extra) {
941 detail::type_record record;
942 record.scope = scope;
943 record.name = name;
944 record.type = &typeid(type);
Jason Rhinelander9c6859e2016-09-08 11:03:08 -0400945 record.type_size = sizeof(detail::conditional_t<has_alias, type_alias, type>);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100946 record.instance_size = sizeof(instance_type);
947 record.init_holder = init_holder;
948 record.dealloc = dealloc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200949
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900950 /* Register base classes specified via template arguments to class_, if any */
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900951 bool unused[] = { (add_base<options>(record), false)..., false };
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900952 (void) unused;
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400953
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100954 /* Process optional arguments, if any */
955 detail::process_attributes<Extra...>::init(extra..., &record);
956
957 detail::generic_type::initialize(&record);
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200958
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400959 if (has_alias) {
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200960 auto &instances = pybind11::detail::get_internals().registered_types_cpp;
961 instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
962 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100963 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200964
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900965 template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900966 static void add_base(detail::type_record &rec) {
967 rec.add_base(&typeid(Base), [](void *src) -> void * {
968 return static_cast<Base *>(reinterpret_cast<type *>(src));
969 });
970 }
971
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900972 template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900973 static void add_base(detail::type_record &) { }
974
Wenzel Jakob71867832015-07-29 17:43:52 +0200975 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100976 class_ &def(const char *name_, Func&& f, const Extra&... extra) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200977 cpp_function cf(std::forward<Func>(f), name(name_), is_method(*this),
978 sibling(getattr(*this, name_, none())), extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +0200979 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200980 return *this;
981 }
982
Wenzel Jakob71867832015-07-29 17:43:52 +0200983 template <typename Func, typename... Extra> class_ &
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100984 def_static(const char *name_, Func f, const Extra&... extra) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200985 cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
986 sibling(getattr(*this, name_, none())), extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +0200987 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200988 return *this;
989 }
990
Wenzel Jakob71867832015-07-29 17:43:52 +0200991 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100992 class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400993 op.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200994 return *this;
995 }
996
Wenzel Jakob71867832015-07-29 17:43:52 +0200997 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100998 class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400999 op.execute_cast(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001000 return *this;
1001 }
1002
Wenzel Jakob71867832015-07-29 17:43:52 +02001003 template <typename... Args, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001004 class_ &def(const detail::init<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001005 init.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001006 return *this;
1007 }
1008
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001009 template <typename... Args, typename... Extra>
1010 class_ &def(const detail::init_alias<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001011 init.execute(*this, extra...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001012 return *this;
1013 }
1014
Wenzel Jakob71867832015-07-29 17:43:52 +02001015 template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob43398a82015-07-28 16:12:20 +02001016 struct capture { Func func; };
1017 capture *ptr = new capture { std::forward<Func>(func) };
1018 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001019 detail::type_caster<type> caster;
1020 if (!caster.load(obj, false))
1021 return nullptr;
Wenzel Jakob43398a82015-07-28 16:12:20 +02001022 return new buffer_info(((capture *) ptr)->func(caster));
1023 }, ptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001024 return *this;
1025 }
1026
Wenzel Jakob71867832015-07-29 17:43:52 +02001027 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001028 class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001029 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this)),
1030 fset([pm](C &c, const D &value) { c.*pm = value; }, is_method(*this));
1031 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001032 return *this;
1033 }
1034
Wenzel Jakob71867832015-07-29 17:43:52 +02001035 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001036 class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001037 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this));
1038 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001039 return *this;
1040 }
1041
Wenzel Jakob71867832015-07-29 17:43:52 +02001042 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001043 class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001044 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
1045 fset([pm](object, const D &value) { *pm = value; }, scope(*this));
1046 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001047 return *this;
1048 }
1049
Wenzel Jakob71867832015-07-29 17:43:52 +02001050 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001051 class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001052 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
1053 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001054 return *this;
1055 }
1056
Dean Moldovan03f627e2016-11-01 11:44:57 +01001057 /// Uses return_value_policy::reference_internal by default
1058 template <typename Getter, typename... Extra>
1059 class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
1060 return def_property_readonly(name, cpp_function(fget), return_value_policy::reference_internal, extra...);
1061 }
1062
1063 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001064 template <typename... Extra>
1065 class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
Dean Moldovan03f627e2016-11-01 11:44:57 +01001066 return def_property(name, fget, cpp_function(), extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001067 }
1068
Dean Moldovan03f627e2016-11-01 11:44:57 +01001069 /// Uses return_value_policy::reference by default
1070 template <typename Getter, typename... Extra>
1071 class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
1072 return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...);
1073 }
1074
1075 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001076 template <typename... Extra>
1077 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
Dean Moldovan03f627e2016-11-01 11:44:57 +01001078 return def_property_static(name, fget, cpp_function(), extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001079 }
1080
Dean Moldovan03f627e2016-11-01 11:44:57 +01001081 /// Uses return_value_policy::reference_internal by default
1082 template <typename Getter, typename... Extra>
1083 class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1084 return def_property(name, cpp_function(fget), fset, return_value_policy::reference_internal, extra...);
1085 }
1086
1087 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001088 template <typename... Extra>
1089 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +01001090 return def_property_static(name, fget, fset, is_method(*this), extra...);
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001091 }
1092
Dean Moldovan03f627e2016-11-01 11:44:57 +01001093 /// Uses return_value_policy::reference by default
1094 template <typename Getter, typename... Extra>
1095 class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1096 return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1097 }
1098
1099 /// Uses cpp_function's return_value_policy by default
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001100 template <typename... Extra>
1101 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1102 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001103 char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001104 detail::process_attributes<Extra...>::init(extra..., rec_fget);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001105 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1106 free(doc_prev);
1107 rec_fget->doc = strdup(rec_fget->doc);
1108 }
1109 if (rec_fset) {
1110 doc_prev = rec_fset->doc;
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001111 detail::process_attributes<Extra...>::init(extra..., rec_fset);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001112 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1113 free(doc_prev);
1114 rec_fset->doc = strdup(rec_fset->doc);
1115 }
1116 }
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001117 pybind11::str doc_obj = pybind11::str(rec_fget->doc ? rec_fget->doc : "");
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001118 object property(
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001119 PyObject_CallFunctionObjArgs((PyObject *) &PyProperty_Type, fget.ptr() ? fget.ptr() : Py_None,
1120 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr(), nullptr), false);
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001121 if (rec_fget->class_)
1122 attr(name) = property;
1123 else
1124 metaclass().attr(name) = property;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001125 return *this;
1126 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001127
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001128private:
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001129 /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1130 template <typename T>
1131 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 +01001132 try {
hbruintjes70d2e572016-07-01 12:39:55 +02001133 new (&inst->holder) holder_type(std::static_pointer_cast<typename holder_type::element_type>(inst->value->shared_from_this()));
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001134 } catch (const std::bad_weak_ptr &) {
1135 new (&inst->holder) holder_type(inst->value);
1136 }
Jason Rhinelanderc07ec312016-11-06 13:12:48 -05001137 inst->holder_constructed = true;
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001138 }
1139
1140 /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
1141 template <typename T = holder_type,
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +09001142 detail::enable_if_t<std::is_copy_constructible<T>::value, int> = 0>
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001143 static void init_holder_helper(instance_type *inst, const holder_type *holder_ptr, const void * /* dummy */) {
1144 if (holder_ptr)
1145 new (&inst->holder) holder_type(*holder_ptr);
1146 else
1147 new (&inst->holder) holder_type(inst->value);
Jason Rhinelanderc07ec312016-11-06 13:12:48 -05001148 inst->holder_constructed = true;
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001149 }
1150
1151 /// Initialize holder object, variant 3: holder is not copy constructible (e.g. unique_ptr), always initialize from raw pointer
1152 template <typename T = holder_type,
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +09001153 detail::enable_if_t<!std::is_copy_constructible<T>::value, int> = 0>
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001154 static void init_holder_helper(instance_type *inst, const holder_type * /* unused */, const void * /* dummy */) {
Jason Rhinelanderc07ec312016-11-06 13:12:48 -05001155 if (inst->owned) {
1156 new (&inst->holder) holder_type(inst->value);
1157 inst->holder_constructed = true;
1158 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001159 }
1160
1161 /// Initialize holder object of an instance, possibly given a pointer to an existing holder
1162 static void init_holder(PyObject *inst_, const void *holder_ptr) {
1163 auto inst = (instance_type *) inst_;
1164 init_holder_helper(inst, (const holder_type *) holder_ptr, inst->value);
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001165 }
1166
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001167 static void dealloc(PyObject *inst_) {
1168 instance_type *inst = (instance_type *) inst_;
Jason Rhinelanderc07ec312016-11-06 13:12:48 -05001169 if (inst->holder_constructed)
1170 inst->holder.~holder_type();
1171 else if (inst->owned)
1172 ::operator delete(inst->value);
1173
Wenzel Jakobd561cb02016-01-17 22:36:41 +01001174 generic_type::dealloc((detail::instance<void> *) inst);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001175 }
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001176
1177 static detail::function_record *get_function_record(handle h) {
1178 h = detail::get_function(h);
1179 return h ? (detail::function_record *) capsule(
1180 PyCFunction_GetSelf(h.ptr()), true) : nullptr;
1181 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001182};
1183
1184/// Binds C++ enumerations and enumeration classes to Python
1185template <typename Type> class enum_ : public class_<Type> {
1186public:
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001187 using class_<Type>::def;
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001188 using UnderlyingType = typename std::underlying_type<Type>::type;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001189 template <typename... Extra>
1190 enum_(const handle &scope, const char *name, const Extra&... extra)
1191 : class_<Type>(scope, name, extra...), m_parent(scope) {
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001192 auto entries = new std::unordered_map<UnderlyingType, const char *>();
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001193 def("__repr__", [name, entries](Type value) -> std::string {
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001194 auto it = entries->find((UnderlyingType) value);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001195 return std::string(name) + "." +
1196 ((it == entries->end()) ? std::string("???")
1197 : std::string(it->second));
1198 });
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001199 def("__init__", [](Type& value, UnderlyingType i) { value = (Type)i; });
1200 def("__init__", [](Type& value, UnderlyingType i) { new (&value) Type((Type) i); });
1201 def("__int__", [](Type value) { return (UnderlyingType) value; });
1202 def("__eq__", [](const Type &value, Type *value2) { return value2 && value == *value2; });
1203 def("__ne__", [](const Type &value, Type *value2) { return !value2 || value != *value2; });
Jason Rhinelanderd41a2732016-08-04 00:21:37 -04001204 if (std::is_convertible<Type, UnderlyingType>::value) {
1205 // Don't provide comparison with the underlying type if the enum isn't convertible,
1206 // i.e. if Type is a scoped enum, mirroring the C++ behaviour. (NB: we explicitly
1207 // convert Type to UnderlyingType below anyway because this needs to compile).
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001208 def("__eq__", [](const Type &value, UnderlyingType value2) { return (UnderlyingType) value == value2; });
1209 def("__ne__", [](const Type &value, UnderlyingType value2) { return (UnderlyingType) value != value2; });
Jason Rhinelanderd41a2732016-08-04 00:21:37 -04001210 }
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001211 def("__hash__", [](const Type &value) { return (UnderlyingType) value; });
Wenzel Jakobfe342412016-09-06 13:02:29 +09001212 // Pickling and unpickling -- needed for use with the 'multiprocessing' module
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001213 def("__getstate__", [](const Type &value) { return pybind11::make_tuple((UnderlyingType) value); });
1214 def("__setstate__", [](Type &p, tuple t) { new (&p) Type((Type) t[0].cast<UnderlyingType>()); });
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001215 m_entries = entries;
1216 }
1217
1218 /// Export enumeration entries into the parent scope
Wenzel Jakobe916d842016-11-04 16:51:14 +01001219 enum_ &export_values() {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001220 PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict;
1221 PyObject *key, *value;
Wenzel Jakob27e8e102016-01-17 22:36:37 +01001222 ssize_t pos = 0;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001223 while (PyDict_Next(dict, &pos, &key, &value))
1224 if (PyObject_IsInstance(value, this->m_ptr))
1225 m_parent.attr(key) = value;
Wenzel Jakobe916d842016-11-04 16:51:14 +01001226 return *this;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001227 }
1228
1229 /// Add an enumeration entry
1230 enum_& value(char const* name, Type value) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001231 this->attr(name) = pybind11::cast(value, return_value_policy::copy);
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001232 (*m_entries)[(UnderlyingType) value] = name;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001233 return *this;
1234 }
1235private:
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001236 std::unordered_map<UnderlyingType, const char *> *m_entries;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001237 handle m_parent;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001238};
1239
1240NAMESPACE_BEGIN(detail)
Wenzel Jakob71867832015-07-29 17:43:52 +02001241template <typename... Args> struct init {
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001242 template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
1243 static void execute(Class &cl, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001244 using Base = typename Class::type;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001245 /// Function which calls a specific C++ in-place constructor
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001246 cl.def("__init__", [](Base *self_, Args... args) { new (self_) Base(args...); }, extra...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001247 }
1248
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001249 template <typename Class, typename... Extra,
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001250 enable_if_t<Class::has_alias &&
1251 std::is_constructible<typename Class::type, Args...>::value, int> = 0>
1252 static void execute(Class &cl, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001253 using Base = typename Class::type;
1254 using Alias = typename Class::type_alias;
1255 handle cl_type = cl;
1256 cl.def("__init__", [cl_type](handle self_, Args... args) {
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001257 if (self_.get_type() == cl_type)
1258 new (self_.cast<Base *>()) Base(args...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001259 else
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001260 new (self_.cast<Alias *>()) Alias(args...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001261 }, extra...);
1262 }
1263
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001264 template <typename Class, typename... Extra,
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001265 enable_if_t<Class::has_alias &&
1266 !std::is_constructible<typename Class::type, Args...>::value, int> = 0>
1267 static void execute(Class &cl, const Extra&... extra) {
1268 init_alias<Args...>::execute(cl, extra...);
1269 }
1270};
1271template <typename... Args> struct init_alias {
1272 template <typename Class, typename... Extra,
1273 enable_if_t<Class::has_alias && std::is_constructible<typename Class::type_alias, Args...>::value, int> = 0>
1274 static void execute(Class &cl, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001275 using Alias = typename Class::type_alias;
1276 cl.def("__init__", [](Alias *self_, Args... args) { new (self_) Alias(args...); }, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001277 }
1278};
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001279
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001280
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001281inline void keep_alive_impl(handle nurse, handle patient) {
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001282 /* Clever approach based on weak references taken from Boost.Python */
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001283 if (!nurse || !patient)
Wenzel Jakob678d7872016-01-17 22:36:41 +01001284 pybind11_fail("Could not activate keep_alive!");
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001285
Ivan Smirnov984c7622016-08-29 02:38:47 +01001286 if (patient.is_none() || nurse.is_none())
Glen Walkerf45bb582016-08-16 17:50:43 +12001287 return; /* Nothing to keep alive or nothing to be kept alive by */
Wenzel Jakob9b880ba2016-04-25 03:25:13 +02001288
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001289 cpp_function disable_lifesupport(
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001290 [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001291
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001292 weakref wr(nurse, disable_lifesupport);
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001293
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001294 patient.inc_ref(); /* reference patient and leak the weak reference */
1295 (void) wr.release();
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001296}
1297
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001298PYBIND11_NOINLINE inline void keep_alive_impl(int Nurse, int Patient, handle args, handle ret) {
1299 handle nurse (Nurse > 0 ? PyTuple_GetItem(args.ptr(), Nurse - 1) : ret.ptr());
1300 handle patient(Patient > 0 ? PyTuple_GetItem(args.ptr(), Patient - 1) : ret.ptr());
1301
1302 keep_alive_impl(nurse, patient);
1303}
1304
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001305template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001306struct iterator_state {
1307 Iterator it;
1308 Sentinel end;
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001309 bool first;
1310};
Wenzel Jakobb2825952016-04-13 23:33:00 +02001311
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001312NAMESPACE_END(detail)
1313
Ben Pritchard2de6e1d2016-02-18 13:20:15 -05001314template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); }
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001315template <typename... Args> detail::init_alias<Args...> init_alias() { return detail::init_alias<Args...>(); }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001316
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001317template <return_value_policy Policy = return_value_policy::reference_internal,
1318 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001319 typename Sentinel,
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001320 typename ValueType = decltype(*std::declval<Iterator>()),
1321 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001322iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001323 typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001324
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001325 if (!detail::get_type_info(typeid(state), false)) {
Wenzel Jakob146397e2016-09-06 13:06:31 +09001326 class_<state>(handle(), "iterator")
Wenzel Jakobb2825952016-04-13 23:33:00 +02001327 .def("__iter__", [](state &s) -> state& { return s; })
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001328 .def("__next__", [](state &s) -> ValueType {
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001329 if (!s.first)
1330 ++s.it;
1331 else
1332 s.first = false;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001333 if (s.it == s.end)
1334 throw stop_iteration();
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001335 return *s.it;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001336 }, std::forward<Extra>(extra)..., Policy);
Wenzel Jakobb2825952016-04-13 23:33:00 +02001337 }
1338
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001339 return (iterator) cast(state { first, last, true });
Wenzel Jakobb2825952016-04-13 23:33:00 +02001340}
Wenzel Jakob146397e2016-09-06 13:06:31 +09001341
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001342template <return_value_policy Policy = return_value_policy::reference_internal,
1343 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001344 typename Sentinel,
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001345 typename KeyType = decltype((*std::declval<Iterator>()).first),
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001346 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001347iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001348 typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001349
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001350 if (!detail::get_type_info(typeid(state), false)) {
Wenzel Jakob146397e2016-09-06 13:06:31 +09001351 class_<state>(handle(), "iterator")
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001352 .def("__iter__", [](state &s) -> state& { return s; })
1353 .def("__next__", [](state &s) -> KeyType {
1354 if (!s.first)
1355 ++s.it;
1356 else
1357 s.first = false;
1358 if (s.it == s.end)
1359 throw stop_iteration();
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001360 return (*s.it).first;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001361 }, std::forward<Extra>(extra)..., Policy);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001362 }
1363
1364 return (iterator) cast(state { first, last, true });
1365}
Wenzel Jakobb2825952016-04-13 23:33:00 +02001366
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001367template <return_value_policy Policy = return_value_policy::reference_internal,
1368 typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
1369 return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
Wenzel Jakobbf0c7dc2016-04-18 10:52:12 +02001370}
1371
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001372template <return_value_policy Policy = return_value_policy::reference_internal,
1373 typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
1374 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001375}
1376
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001377template <typename InputType, typename OutputType> void implicitly_convertible() {
Wenzel Jakob2ac50442016-01-17 22:36:35 +01001378 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001379 if (!detail::type_caster<InputType>().load(obj, false))
1380 return nullptr;
1381 tuple args(1);
1382 args[0] = obj;
1383 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1384 if (result == nullptr)
1385 PyErr_Clear();
1386 return result;
1387 };
Ivan Smirnov8f3e0452016-10-23 15:43:03 +01001388
1389 if (auto tinfo = detail::get_type_info(typeid(OutputType)))
1390 tinfo->implicit_conversions.push_back(implicit_caster);
1391 else
Wenzel Jakob678d7872016-01-17 22:36:41 +01001392 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001393}
1394
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001395template <typename ExceptionTranslator>
1396void register_exception_translator(ExceptionTranslator&& translator) {
1397 detail::get_internals().registered_exception_translators.push_front(
1398 std::forward<ExceptionTranslator>(translator));
1399}
1400
1401/* Wrapper to generate a new Python exception type.
1402 *
1403 * This should only be used with PyErr_SetString for now.
1404 * It is not (yet) possible to use as a py::base.
1405 * Template type argument is reserved for future use.
1406 */
1407template <typename type>
1408class exception : public object {
1409public:
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001410 exception(module &m, const std::string &name, PyObject* base=PyExc_Exception) {
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001411 std::string full_name = std::string(PyModule_GetName(m.ptr()))
1412 + std::string(".") + name;
1413 char* exception_name = const_cast<char*>(full_name.c_str());
1414 m_ptr = PyErr_NewException(exception_name, base, NULL);
Jason Rhinelander6873c202016-10-24 21:58:22 -04001415 m.add_object(name.c_str(), *this);
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001416 }
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001417
1418 // Sets the current python exception to this exception object with the given message
1419 void operator()(const char *message) {
1420 PyErr_SetString(m_ptr, message);
1421 }
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001422};
1423
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001424/** Registers a Python exception in `m` of the given `name` and installs an exception translator to
1425 * translate the C++ exception to the created Python exception using the exceptions what() method.
1426 * This is intended for simple exception translations; for more complex translation, register the
1427 * exception object and translator directly.
1428 */
1429template <typename CppException> exception<CppException>& register_exception(module &m, const std::string &name, PyObject* base = PyExc_Exception) {
1430 static exception<CppException> ex(m, name, base);
1431 register_exception_translator([](std::exception_ptr p) {
1432 if (!p) return;
1433 try {
1434 std::rethrow_exception(p);
1435 }
1436 catch (const CppException &e) {
1437 ex(e.what());
1438 }
1439 });
1440 return ex;
1441}
1442
Dean Moldovan67990d92016-08-29 18:03:34 +02001443NAMESPACE_BEGIN(detail)
1444PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
1445 auto strings = tuple(args.size());
1446 for (size_t i = 0; i < args.size(); ++i) {
Dean Moldovanea763a52016-09-22 23:39:06 +02001447 strings[i] = args[i].str();
Dean Moldovan67990d92016-08-29 18:03:34 +02001448 }
Dean Moldovan865e4302016-09-21 01:06:32 +02001449 auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
Dean Moldovan242b1462016-09-08 17:02:04 +02001450 auto line = sep.attr("join")(strings);
Dean Moldovan67990d92016-08-29 18:03:34 +02001451
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001452 object file;
1453 if (kwargs.contains("file")) {
1454 file = kwargs["file"].cast<object>();
1455 } else {
1456 try {
1457 file = module::import("sys").attr("stdout");
1458 } catch (const import_error &) {
1459 /* If print() is called from code that is executed as
1460 part of garbage collection during interpreter shutdown,
1461 importing 'sys' can fail. Give up rather than crashing the
1462 interpreter in this case. */
1463 return;
1464 }
1465 }
1466
Dean Moldovan242b1462016-09-08 17:02:04 +02001467 auto write = file.attr("write");
Dean Moldovan67990d92016-08-29 18:03:34 +02001468 write(line);
Dean Moldovan865e4302016-09-21 01:06:32 +02001469 write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
Dean Moldovan67990d92016-08-29 18:03:34 +02001470
Wenzel Jakobc49d6e52016-10-13 10:34:52 +02001471 if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
Dean Moldovan242b1462016-09-08 17:02:04 +02001472 file.attr("flush")();
Dean Moldovan67990d92016-08-29 18:03:34 +02001473}
1474NAMESPACE_END(detail)
1475
1476template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1477void print(Args &&...args) {
1478 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
1479 detail::print(c.args(), c.kwargs());
1480}
1481
Felipe Lema2547ca42016-01-25 16:22:44 -03001482#if defined(WITH_THREAD)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001483
1484/* The functions below essentially reproduce the PyGILState_* API using a RAII
1485 * pattern, but there are a few important differences:
1486 *
1487 * 1. When acquiring the GIL from an non-main thread during the finalization
1488 * phase, the GILState API blindly terminates the calling thread, which
1489 * is often not what is wanted. This API does not do this.
1490 *
1491 * 2. The gil_scoped_release function can optionally cut the relationship
1492 * of a PyThreadState and its associated thread, which allows moving it to
1493 * another thread (this is a fairly rare/advanced use case).
1494 *
1495 * 3. The reference count of an acquired thread state can be controlled. This
1496 * can be handy to prevent cases where callbacks issued from an external
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001497 * thread would otherwise constantly construct and destroy thread state data
1498 * structures.
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001499 *
1500 * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
1501 * example which uses features 2 and 3 to migrate the Python thread of
1502 * execution to another thread (to run the event loop on the original thread,
1503 * in this case).
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001504 */
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001505
1506class gil_scoped_acquire {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001507public:
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001508 PYBIND11_NOINLINE gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001509 auto const &internals = detail::get_internals();
1510 tstate = (PyThreadState *) PyThread_get_key_value(internals.tstate);
1511
1512 if (!tstate) {
1513 tstate = PyThreadState_New(internals.istate);
1514 #if !defined(NDEBUG)
1515 if (!tstate)
1516 pybind11_fail("scoped_acquire: could not create thread state!");
1517 #endif
1518 tstate->gilstate_counter = 0;
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001519 #if PY_MAJOR_VERSION < 3
1520 PyThread_delete_key_value(internals.tstate);
1521 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001522 PyThread_set_key_value(internals.tstate, tstate);
1523 } else {
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001524 release = detail::get_thread_state_unchecked() != tstate;
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001525 }
1526
1527 if (release) {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001528 /* Work around an annoying assertion in PyThreadState_Swap */
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001529 #if defined(Py_DEBUG)
1530 PyInterpreterState *interp = tstate->interp;
1531 tstate->interp = nullptr;
1532 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001533 PyEval_AcquireThread(tstate);
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001534 #if defined(Py_DEBUG)
1535 tstate->interp = interp;
1536 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001537 }
1538
1539 inc_ref();
1540 }
1541
1542 void inc_ref() {
1543 ++tstate->gilstate_counter;
1544 }
1545
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001546 PYBIND11_NOINLINE void dec_ref() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001547 --tstate->gilstate_counter;
1548 #if !defined(NDEBUG)
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001549 if (detail::get_thread_state_unchecked() != tstate)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001550 pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
1551 if (tstate->gilstate_counter < 0)
1552 pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
1553 #endif
1554 if (tstate->gilstate_counter == 0) {
1555 #if !defined(NDEBUG)
1556 if (!release)
1557 pybind11_fail("scoped_acquire::dec_ref(): internal error!");
1558 #endif
1559 PyThreadState_Clear(tstate);
1560 PyThreadState_DeleteCurrent();
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001561 PyThread_delete_key_value(detail::get_internals().tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001562 release = false;
1563 }
1564 }
1565
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001566 PYBIND11_NOINLINE ~gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001567 dec_ref();
1568 if (release)
1569 PyEval_SaveThread();
1570 }
1571private:
1572 PyThreadState *tstate = nullptr;
1573 bool release = true;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001574};
1575
1576class gil_scoped_release {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001577public:
Jason Rhinelander12d76602016-10-16 16:27:42 -04001578 explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001579 tstate = PyEval_SaveThread();
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001580 if (disassoc) {
Boris Schäling20ee9352016-05-28 12:26:18 +02001581 auto key = detail::get_internals().tstate;
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001582 #if PY_MAJOR_VERSION < 3
1583 PyThread_delete_key_value(key);
1584 #else
1585 PyThread_set_key_value(key, nullptr);
1586 #endif
1587 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001588 }
1589 ~gil_scoped_release() {
1590 if (!tstate)
1591 return;
1592 PyEval_RestoreThread(tstate);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001593 if (disassoc) {
Boris Schäling20ee9352016-05-28 12:26:18 +02001594 auto key = detail::get_internals().tstate;
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001595 #if PY_MAJOR_VERSION < 3
1596 PyThread_delete_key_value(key);
1597 #endif
1598 PyThread_set_key_value(key, tstate);
1599 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001600 }
1601private:
1602 PyThreadState *tstate;
1603 bool disassoc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001604};
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001605#else
1606class gil_scoped_acquire { };
1607class gil_scoped_release { };
Felipe Lema2547ca42016-01-25 16:22:44 -03001608#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001609
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04001610inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
1611 handle py_object = detail::get_object_handle(this_ptr, this_type);
Wenzel Jakobac0fde92015-10-01 18:37:26 +02001612 if (!py_object)
1613 return function();
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001614 handle type = py_object.get_type();
1615 auto key = std::make_pair(type.ptr(), name);
1616
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001617 /* Cache functions that aren't overloaded in Python to avoid
1618 many costly Python dictionary lookups below */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001619 auto &cache = detail::get_internals().inactive_overload_cache;
1620 if (cache.find(key) != cache.end())
1621 return function();
1622
Dean Moldovan865e4302016-09-21 01:06:32 +02001623 function overload = getattr(py_object, name, function());
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001624 if (overload.is_cpp_function()) {
1625 cache.insert(key);
1626 return function();
1627 }
Wenzel Jakob27e8e102016-01-17 22:36:37 +01001628
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001629 /* Don't call dispatch code if invoked from overridden function */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001630 PyFrameObject *frame = PyThreadState_Get()->frame;
Wenzel Jakobb2b44a92016-04-15 17:50:40 +02001631 if (frame && (std::string) pybind11::handle(frame->f_code->co_name).str() == name &&
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001632 frame->f_code->co_argcount > 0) {
1633 PyFrame_FastToLocals(frame);
1634 PyObject *self_caller = PyDict_GetItem(
1635 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
1636 if (self_caller == py_object.ptr())
1637 return function();
1638 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001639 return overload;
1640}
1641
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04001642template <class T> function get_overload(const T *this_ptr, const char *name) {
Ivan Smirnov8f3e0452016-10-23 15:43:03 +01001643 auto tinfo = detail::get_type_info(typeid(T));
1644 return tinfo ? get_type_overload(this_ptr, tinfo, name) : function();
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04001645}
1646
Jason Rhinelander20978262016-08-29 18:16:46 -04001647#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001648 pybind11::gil_scoped_acquire gil; \
Jason Rhinelander20978262016-08-29 18:16:46 -04001649 pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04001650 if (overload) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04001651 auto o = overload(__VA_ARGS__); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04001652 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04001653 static pybind11::detail::overload_caster_t<ret_type> caster; \
1654 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04001655 } \
1656 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
1657 } \
1658 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001659
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001660#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelander20978262016-08-29 18:16:46 -04001661 PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001662 return cname::fn(__VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001663
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001664#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelander20978262016-08-29 18:16:46 -04001665 PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001666 pybind11::pybind11_fail("Tried to call pure virtual function \"" #cname "::" name "\"");
1667
1668#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
1669 PYBIND11_OVERLOAD_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
1670
1671#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
1672 PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001673
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001674NAMESPACE_END(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001675
1676#if defined(_MSC_VER)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001677# pragma warning(pop)
Wenzel Jakob1ffce742016-08-25 01:43:33 +02001678#elif defined(__INTEL_COMPILER)
1679/* Leave ignored warnings on */
Wenzel Jakob6d252962016-05-01 20:47:49 +02001680#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001681# pragma GCC diagnostic pop
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001682#endif