blob: 9c6bc32b844b394957832e00df060e53d601b5b7 [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
Wenzel Jakob1ffce742016-08-25 01:43:33 +020021#elif defined(__INTEL_COMPILER)
Ben Pritchard33f34302016-02-18 15:25:51 -050022# pragma warning(push)
Wenzel Jakob1ffce742016-08-25 01:43:33 +020023# pragma warning(disable: 186) // pointless comparison of unsigned integer with zero
24# pragma warning(disable: 1334) // the "template" keyword used for syntactic disambiguation may only be used within a template
25# pragma warning(disable: 2196) // warning #2196: routine is both "inline" and "noinline"
Wenzel Jakob6d252962016-05-01 20:47:49 +020026#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +010027# pragma GCC diagnostic push
28# pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
29# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
30# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
Wenzel Jakobdeeab552016-05-15 23:54:34 +020031# pragma GCC diagnostic ignored "-Wstrict-aliasing"
32# pragma GCC diagnostic ignored "-Wattributes"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020033#endif
34
Wenzel Jakob48548ea2016-01-17 22:36:44 +010035#include "attr.h"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020036
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020037NAMESPACE_BEGIN(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +020038
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020039/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020040class cpp_function : public function {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020041public:
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020042 cpp_function() { }
Wenzel Jakob38bd7112015-07-05 20:05:44 +020043
Wenzel Jakob5984baa2016-05-10 15:05:03 +010044 /// Construct a cpp_function from a vanilla function pointer
Wenzel Jakob66c9a402016-01-17 22:36:36 +010045 template <typename Return, typename... Args, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +010046 cpp_function(Return (*f)(Args...), const Extra&... extra) {
Wenzel Jakob5984baa2016-05-10 15:05:03 +010047 initialize(f, f, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +020048 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020049
Wenzel Jakob5984baa2016-05-10 15:05:03 +010050 /// Construct a cpp_function from a lambda function (possibly with internal state)
Wenzel Jakob48548ea2016-01-17 22:36:44 +010051 template <typename Func, typename... Extra> cpp_function(Func &&f, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020052 initialize(std::forward<Func>(f),
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020053 (typename detail::remove_class<decltype(
Wenzel Jakob48548ea2016-01-17 22:36:44 +010054 &std::remove_reference<Func>::type::operator())>::type *) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020055 }
56
Wenzel Jakob5984baa2016-05-10 15:05:03 +010057 /// Construct a cpp_function from a class method (non-const)
58 template <typename Return, typename Class, typename... Arg, typename... Extra>
59 cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020060 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Wenzel Jakob48548ea2016-01-17 22:36:44 +010061 (Return (*) (Class *, Arg...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020062 }
63
Wenzel Jakob5984baa2016-05-10 15:05:03 +010064 /// Construct a cpp_function from a class method (const)
65 template <typename Return, typename Class, typename... Arg, typename... Extra>
66 cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020067 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Wenzel Jakob48548ea2016-01-17 22:36:44 +010068 (Return (*)(const Class *, Arg ...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020069 }
70
Wenzel Jakob57082212015-09-04 23:42:12 +020071 /// Return the function name
Wenzel Jakob48548ea2016-01-17 22:36:44 +010072 object name() const { return attr("__name__"); }
Wenzel Jakob57082212015-09-04 23:42:12 +020073
Wenzel Jakobd561cb02016-01-17 22:36:41 +010074protected:
Wenzel Jakob382484a2016-09-10 15:28:37 +090075 /// Space optimization: don't inline this frequently instantiated fragment
76 PYBIND11_NOINLINE detail::function_record *make_function_record() {
77 return new detail::function_record();
78 }
79
Wenzel Jakobd561cb02016-01-17 22:36:41 +010080 /// Special internal constructor for functors, lambda functions, etc.
Wenzel Jakob66c9a402016-01-17 22:36:36 +010081 template <typename Func, typename Return, typename... Args, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +010082 void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
Dean Moldovan9e625582016-06-04 00:27:32 +020083 static_assert(detail::expected_num_args<Extra...>(sizeof...(Args)),
84 "The number of named arguments does not match the function signature");
85
Wenzel Jakob66c9a402016-01-17 22:36:36 +010086 struct capture { typename std::remove_reference<Func>::type f; };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020087
Wenzel Jakobd561cb02016-01-17 22:36:41 +010088 /* Store the function including any extra state it might have (e.g. a lambda capture object) */
Wenzel Jakob382484a2016-09-10 15:28:37 +090089 auto rec = make_function_record();
Wenzel Jakob71867832015-07-29 17:43:52 +020090
Wenzel Jakob5984baa2016-05-10 15:05:03 +010091 /* Store the capture object directly in the function record if there is enough space */
92 if (sizeof(capture) <= sizeof(rec->data)) {
Wenzel Jakob954b7932016-07-10 10:13:18 +020093 /* Without these pragmas, GCC warns that there might not be
94 enough space to use the placement new operator. However, the
95 'if' statement above ensures that this is the case. */
Jason Rhinelander0b12f912016-07-07 16:26:04 -040096#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -040097# pragma GCC diagnostic push
98# pragma GCC diagnostic ignored "-Wplacement-new"
99#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100100 new ((capture *) &rec->data) capture { std::forward<Func>(f) };
Jason Rhinelander0b12f912016-07-07 16:26:04 -0400101#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -0400102# pragma GCC diagnostic pop
103#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100104 if (!std::is_trivially_destructible<Func>::value)
105 rec->free_data = [](detail::function_record *r) { ((capture *) &r->data)->~capture(); };
106 } else {
107 rec->data[0] = new capture { std::forward<Func>(f) };
108 rec->free_data = [](detail::function_record *r) { delete ((capture *) r->data[0]); };
109 }
Wenzel Jakob19208fe2015-10-13 17:37:25 +0200110
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100111 /* Type casters for the function arguments and return value */
112 typedef detail::type_caster<typename std::tuple<Args...>> cast_in;
113 typedef detail::type_caster<typename std::conditional<
114 std::is_void<Return>::value, detail::void_type,
115 typename detail::intrinsic_type<Return>::type>::type> cast_out;
Wenzel Jakob71867832015-07-29 17:43:52 +0200116
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100117 /* Dispatch code which converts function arguments and performs the actual function call */
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100118 rec->impl = [](detail::function_record *rec, handle args, handle kwargs, handle parent) -> handle {
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100119 cast_in args_converter;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100120
121 /* Try to cast the function arguments into the C++ domain */
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100122 if (!args_converter.load_args(args, kwargs, true))
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100123 return PYBIND11_TRY_NEXT_OVERLOAD;
124
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100125 /* Invoke call policy pre-call hook */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100126 detail::process_attributes<Extra...>::precall(args);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100127
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100128 /* Get a pointer to the capture object */
129 capture *cap = (capture *) (sizeof(capture) <= sizeof(rec->data)
130 ? &rec->data : rec->data[0]);
131
Wenzel Jakob954b7932016-07-10 10:13:18 +0200132 /* Perform the function call */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100133 handle result = cast_out::cast(args_converter.template call<Return>(cap->f),
134 rec->policy, parent);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100135
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100136 /* Invoke call policy post-call hook */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100137 detail::process_attributes<Extra...>::postcall(args, result);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100138
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100139 return result;
Wenzel Jakob71867832015-07-29 17:43:52 +0200140 };
141
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100142 /* Process any user-provided function attributes */
143 detail::process_attributes<Extra...>::init(extra..., rec);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100144
145 /* Generate a readable signature describing the function's arguments and return value types */
Dean Moldovaned23dda2016-08-04 01:40:40 +0200146 using detail::descr; using detail::_;
147 PYBIND11_DESCR signature = _("(") + cast_in::element_names() + _(") -> ") + cast_out::name();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100148
149 /* Register the function with Python from generic (non-templated) code */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100150 initialize_generic(rec, signature.text(), signature.types(), sizeof...(Args));
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100151
152 if (cast_in::has_args) rec->has_args = true;
153 if (cast_in::has_kwargs) rec->has_kwargs = true;
Wenzel Jakob954b7932016-07-10 10:13:18 +0200154
155 /* Stash some additional information used by an important optimization in 'functional.h' */
156 using FunctionType = Return (*)(Args...);
157 constexpr bool is_function_ptr =
158 std::is_convertible<Func, FunctionType>::value &&
159 sizeof(capture) == sizeof(void *);
160 if (is_function_ptr) {
161 rec->is_stateless = true;
162 rec->data[1] = (void *) &typeid(FunctionType);
163 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200164 }
165
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100166 /// Register a function call with Python (generic non-templated code goes here)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100167 void initialize_generic(detail::function_record *rec, const char *text,
Dean Moldovanecced6c2016-07-31 20:03:18 +0200168 const std::type_info *const *types, size_t args) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100169
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100170 /* Create copies of all referenced C-style strings */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100171 rec->name = strdup(rec->name ? rec->name : "");
172 if (rec->doc) rec->doc = strdup(rec->doc);
173 for (auto &a: rec->args) {
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100174 if (a.name)
175 a.name = strdup(a.name);
176 if (a.descr)
177 a.descr = strdup(a.descr);
178 else if (a.value)
Dean Moldovan242b1462016-09-08 17:02:04 +0200179 a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100180 }
Wenzel Jakob954b7932016-07-10 10:13:18 +0200181
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100182 auto const &registered_types = detail::get_internals().registered_types_cpp;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100183
184 /* Generate a proper function signature */
185 std::string signature;
186 size_t type_depth = 0, char_index = 0, type_index = 0, arg_index = 0;
187 while (true) {
188 char c = text[char_index++];
189 if (c == '\0')
190 break;
191
192 if (c == '{') {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200193 // Write arg name for everything except *args, **kwargs and return type.
Dean Moldovaned23dda2016-08-04 01:40:40 +0200194 if (type_depth == 0 && text[char_index] != '*' && arg_index < args) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200195 if (!rec->args.empty()) {
196 signature += rec->args[arg_index].name;
197 } else if (arg_index == 0 && rec->class_) {
198 signature += "self";
199 } else {
200 signature += "arg" + std::to_string(arg_index - (rec->class_ ? 1 : 0));
201 }
202 signature += ": ";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100203 }
204 ++type_depth;
205 } else if (c == '}') {
206 --type_depth;
Dean Moldovaned23dda2016-08-04 01:40:40 +0200207 if (type_depth == 0) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200208 if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
209 signature += "=";
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100210 signature += rec->args[arg_index].descr;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100211 }
212 arg_index++;
213 }
214 } else if (c == '%') {
215 const std::type_info *t = types[type_index++];
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100216 if (!t)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100217 pybind11_fail("Internal error while parsing type signature (1)");
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +0100218 auto it = registered_types.find(std::type_index(*t));
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100219 if (it != registered_types.end()) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100220 signature += ((const detail::type_info *) it->second)->type->tp_name;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100221 } else {
222 std::string tname(t->name());
223 detail::clean_type_id(tname);
224 signature += tname;
225 }
226 } else {
227 signature += c;
228 }
229 }
Wenzel Jakob95d18692016-01-17 22:36:40 +0100230 if (type_depth != 0 || types[type_index] != nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100231 pybind11_fail("Internal error while parsing type signature (2)");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100232
233 #if !defined(PYBIND11_CPP14)
234 delete[] types;
235 delete[] text;
236 #endif
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200237
Wenzel Jakob57082212015-09-04 23:42:12 +0200238#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100239 if (strcmp(rec->name, "__next__") == 0) {
240 std::free(rec->name);
241 rec->name = strdup("next");
Wenzel Jakobd1bfc4e2016-05-16 18:52:46 +0200242 } else if (strcmp(rec->name, "__bool__") == 0) {
243 std::free(rec->name);
244 rec->name = strdup("__nonzero__");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100245 }
Wenzel Jakob57082212015-09-04 23:42:12 +0200246#endif
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100247 rec->signature = strdup(signature.c_str());
248 rec->args.shrink_to_fit();
Wenzel Jakoba380ed92016-05-15 23:54:13 +0200249 rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
Wenzel Jakobaffb9f42016-05-15 23:55:06 +0200250 rec->nargs = (uint16_t) args;
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200251
Wenzel Jakob57082212015-09-04 23:42:12 +0200252#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100253 if (rec->sibling && PyMethod_Check(rec->sibling.ptr()))
254 rec->sibling = PyMethod_GET_FUNCTION(rec->sibling.ptr());
Wenzel Jakob57082212015-09-04 23:42:12 +0200255#endif
256
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100257 detail::function_record *chain = nullptr, *chain_start = rec;
258 if (rec->sibling && PyCFunction_Check(rec->sibling.ptr())) {
259 capsule rec_capsule(PyCFunction_GetSelf(rec->sibling.ptr()), true);
260 chain = (detail::function_record *) rec_capsule;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100261 /* Never append a method to an overload chain of a parent class;
262 instead, hide the parent's overloads in this case */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100263 if (chain->class_ != rec->class_)
264 chain = nullptr;
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200265 }
266
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100267 if (!chain) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100268 /* No existing overload was found, create a new function object */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100269 rec->def = new PyMethodDef();
270 memset(rec->def, 0, sizeof(PyMethodDef));
271 rec->def->ml_name = rec->name;
272 rec->def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
273 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
Wenzel Jakoba6501792016-02-04 23:02:07 +0100274
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100275 capsule rec_capsule(rec, [](PyObject *o) {
276 destruct((detail::function_record *) PyCapsule_GetPointer(o, nullptr));
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100277 });
Wenzel Jakoba6501792016-02-04 23:02:07 +0100278
279 object scope_module;
280 if (rec->scope) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200281 if (hasattr(rec->scope, "__module__")) {
282 scope_module = rec->scope.attr("__module__");
283 } else if (hasattr(rec->scope, "__name__")) {
284 scope_module = rec->scope.attr("__name__");
285 }
Wenzel Jakoba6501792016-02-04 23:02:07 +0100286 }
287
288 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200289 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100290 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200291 } else {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100292 /* Append at the end of the overload chain */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100293 m_ptr = rec->sibling.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200294 inc_ref();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100295 chain_start = chain;
296 while (chain->next)
297 chain = chain->next;
298 chain->next = rec;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200299 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200300
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200301 std::string signatures;
Wenzel Jakob71867832015-07-29 17:43:52 +0200302 int index = 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100303 /* Create a nice pydoc rec including all signatures and
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100304 docstrings of the functions in the overload chain */
Sylvain Corlay0e04fdf2016-03-08 16:42:12 -0500305 if (chain) {
306 // First a generic signature
307 signatures += rec->name;
308 signatures += "(*args, **kwargs)\n";
309 signatures += "Overloaded function.\n\n";
310 }
311 // Then specific overload signatures
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100312 for (auto it = chain_start; it != nullptr; it = it->next) {
313 if (chain)
Wenzel Jakob71867832015-07-29 17:43:52 +0200314 signatures += std::to_string(++index) + ". ";
Sylvain Corlay13b22bf2016-02-28 21:23:39 -0500315 signatures += rec->name;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100316 signatures += it->signature;
317 signatures += "\n";
318 if (it->doc && strlen(it->doc) > 0) {
319 signatures += "\n";
Wenzel Jakob218b6ce2016-02-28 23:52:37 +0100320 signatures += it->doc;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100321 signatures += "\n";
322 }
Wenzel Jakob71867832015-07-29 17:43:52 +0200323 if (it->next)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200324 signatures += "\n";
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200325 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100326
327 /* Install docstring */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200328 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
329 if (func->m_ml->ml_doc)
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100330 std::free((char *) func->m_ml->ml_doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200331 func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100332
333 if (rec->class_) {
334 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->class_.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200335 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100336 pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200337 Py_DECREF(func);
338 }
339 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100340
341 /// When a cpp_function is GCed, release any memory allocated by pybind11
342 static void destruct(detail::function_record *rec) {
343 while (rec) {
344 detail::function_record *next = rec->next;
345 if (rec->free_data)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100346 rec->free_data(rec);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100347 std::free((char *) rec->name);
348 std::free((char *) rec->doc);
349 std::free((char *) rec->signature);
350 for (auto &arg: rec->args) {
351 std::free((char *) arg.name);
352 std::free((char *) arg.descr);
353 arg.value.dec_ref();
354 }
355 if (rec->def) {
356 std::free((char *) rec->def->ml_doc);
357 delete rec->def;
358 }
359 delete rec;
360 rec = next;
361 }
362 }
363
364 /// Main dispatch logic for calls to functions bound using pybind11
365 static PyObject *dispatcher(PyObject *self, PyObject *args, PyObject *kwargs) {
366 /* Iterator over the list of potentially admissible overloads */
367 detail::function_record *overloads = (detail::function_record *) PyCapsule_GetPointer(self, nullptr),
368 *it = overloads;
369
370 /* Need to know how many arguments + keyword arguments there are to pick the right overload */
Wenzel Jakob0a078052016-05-29 13:40:40 +0200371 size_t nargs = (size_t) PyTuple_GET_SIZE(args),
372 nkwargs = kwargs ? (size_t) PyDict_Size(kwargs) : 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100373
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100374 handle parent = nargs > 0 ? PyTuple_GET_ITEM(args, 0) : nullptr,
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100375 result = PYBIND11_TRY_NEXT_OVERLOAD;
376 try {
377 for (; it != nullptr; it = it->next) {
378 tuple args_(args, true);
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100379 size_t kwargs_consumed = 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100380
381 /* For each overload:
382 1. If the required list of arguments is longer than the
383 actually provided amount, create a copy of the argument
384 list and fill in any available keyword/default arguments.
385 2. Ensure that all keyword arguments were "consumed"
386 3. Call the function call dispatcher (function_record::impl)
387 */
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100388 size_t nargs_ = nargs;
389 if (nargs < it->args.size()) {
390 nargs_ = it->args.size();
391 args_ = tuple(nargs_);
392 for (size_t i = 0; i < nargs; ++i) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100393 handle item = PyTuple_GET_ITEM(args, i);
394 PyTuple_SET_ITEM(args_.ptr(), i, item.inc_ref().ptr());
395 }
396
397 int arg_ctr = 0;
398 for (auto const &it2 : it->args) {
399 int index = arg_ctr++;
400 if (PyTuple_GET_ITEM(args_.ptr(), index))
401 continue;
402
403 handle value;
404 if (kwargs)
405 value = PyDict_GetItemString(kwargs, it2.name);
406
407 if (value)
408 kwargs_consumed++;
409 else if (it2.value)
410 value = it2.value;
411
412 if (value) {
413 PyTuple_SET_ITEM(args_.ptr(), index, value.inc_ref().ptr());
414 } else {
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100415 kwargs_consumed = (size_t) -1; /* definite failure */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100416 break;
417 }
418 }
419 }
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200420
421 try {
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100422 if ((kwargs_consumed == nkwargs || it->has_kwargs) &&
423 (nargs_ == it->nargs || it->has_args))
424 result = it->impl(it, args_, kwargs, parent);
Wenzel Jakob00062592016-07-01 16:07:35 +0200425 } catch (reference_cast_error &) {
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200426 result = PYBIND11_TRY_NEXT_OVERLOAD;
427 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100428
429 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
430 break;
431 }
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200432 } catch (error_already_set &e) {
433 e.restore();
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400434 return nullptr;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100435 } catch (...) {
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400436 /* When an exception is caught, give each registered exception
437 translator a chance to translate it to a Python exception
438 in reverse order of registration.
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200439
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400440 A translator may choose to do one of the following:
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200441
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400442 - catch the exception and call PyErr_SetString or PyErr_SetObject
443 to set a standard (or custom) Python exception, or
444 - do nothing and let the exception fall through to the next translator, or
445 - delegate translation to the next translator by throwing a new type of exception. */
446
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200447 auto last_exception = std::current_exception();
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400448 auto &registered_exception_translators = pybind11::detail::get_internals().registered_exception_translators;
449 for (auto& translator : registered_exception_translators) {
450 try {
451 translator(last_exception);
452 } catch (...) {
453 last_exception = std::current_exception();
454 continue;
455 }
456 return nullptr;
457 }
458 PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100459 return nullptr;
460 }
461
462 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
Wenzel Jakob382484a2016-09-10 15:28:37 +0900463 if (overloads->is_operator)
464 return handle(Py_NotImplemented).inc_ref().ptr();
465
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900466 std::string msg = std::string(overloads->name) + "(): incompatible " +
467 std::string(overloads->is_constructor ? "constructor" : "function") +
468 " arguments. The following argument types are supported:\n";
469
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100470 int ctr = 0;
471 for (detail::function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
472 msg += " "+ std::to_string(++ctr) + ". ";
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400473
474 bool wrote_sig = false;
475 if (overloads->is_constructor) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200476 // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400477 std::string sig = it2->signature;
Dean Moldovanecced6c2016-07-31 20:03:18 +0200478 size_t start = sig.find('(') + 7; // skip "(self: "
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400479 if (start < sig.size()) {
480 // End at the , for the next argument
481 size_t end = sig.find(", "), next = end + 2;
482 size_t ret = sig.rfind(" -> ");
483 // Or the ), if there is no comma:
484 if (end >= sig.size()) next = end = sig.find(')');
485 if (start < end && next < sig.size()) {
486 msg.append(sig, start, end - start);
487 msg += '(';
488 msg.append(sig, next, ret - next);
489 wrote_sig = true;
490 }
491 }
492 }
493 if (!wrote_sig) msg += it2->signature;
494
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100495 msg += "\n";
496 }
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900497 msg += "\nInvoked with: ";
Andreas Bergmeier16d43942016-05-24 09:19:35 +0200498 tuple args_(args, true);
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200499 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
Andreas Bergmeier16d43942016-05-24 09:19:35 +0200500 msg += static_cast<std::string>(static_cast<object>(args_[ti]).str());
501 if ((ti + 1) != args_.size() )
502 msg += ", ";
503 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100504 PyErr_SetString(PyExc_TypeError, msg.c_str());
505 return nullptr;
506 } else if (!result) {
507 std::string msg = "Unable to convert function return value to a "
508 "Python type! The signature was\n\t";
509 msg += it->signature;
510 PyErr_SetString(PyExc_TypeError, msg.c_str());
511 return nullptr;
512 } else {
513 if (overloads->is_constructor) {
Wenzel Jakob772c6d52016-04-30 19:56:10 +0200514 /* When a constructor ran successfully, the corresponding
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100515 holder type (e.g. std::unique_ptr) must still be initialized. */
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100516 PyObject *inst = PyTuple_GET_ITEM(args, 0);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100517 auto tinfo = detail::get_type_info(Py_TYPE(inst));
518 tinfo->init_holder(inst, nullptr);
519 }
520 return result.ptr();
521 }
522 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200523};
524
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100525/// Wrapper for Python extension modules
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200526class module : public object {
527public:
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200528 PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200529
530 module(const char *name, const char *doc = nullptr) {
Wenzel Jakob57082212015-09-04 23:42:12 +0200531#if PY_MAJOR_VERSION >= 3
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200532 PyModuleDef *def = new PyModuleDef();
533 memset(def, 0, sizeof(PyModuleDef));
534 def->m_name = name;
535 def->m_doc = doc;
536 def->m_size = -1;
537 Py_INCREF(def);
538 m_ptr = PyModule_Create(def);
Wenzel Jakob57082212015-09-04 23:42:12 +0200539#else
540 m_ptr = Py_InitModule3(name, nullptr, doc);
541#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200542 if (m_ptr == nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100543 pybind11_fail("Internal error in module::module()");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200544 inc_ref();
545 }
546
Wenzel Jakob71867832015-07-29 17:43:52 +0200547 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100548 module &def(const char *name_, Func &&f, const Extra& ... extra) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200549 cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
550 sibling(getattr(*this, name_, none())), extra...);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100551 /* PyModule_AddObject steals a reference to 'func' */
552 PyModule_AddObject(ptr(), name_, func.inc_ref().ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200553 return *this;
554 }
555
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200556 module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200557 std::string full_name = std::string(PyModule_GetName(m_ptr))
558 + std::string(".") + std::string(name);
559 module result(PyImport_AddModule(full_name.c_str()), true);
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200560 if (doc)
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200561 result.attr("__doc__") = pybind11::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200562 attr(name) = result;
563 return result;
564 }
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200565
566 static module import(const char *name) {
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100567 PyObject *obj = PyImport_ImportModule(name);
568 if (!obj)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100569 pybind11_fail("Module \"" + std::string(name) + "\" not found!");
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100570 return module(obj, false);
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200571 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200572};
573
574NAMESPACE_BEGIN(detail)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100575/// Generic support for creating new Python heap types
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100576class generic_type : public object {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400577 template <typename...> friend class class_;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200578public:
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100579 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100580protected:
581 void initialize(type_record *rec) {
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200582 auto &internals = get_internals();
583 auto tindex = std::type_index(*(rec->type));
584
585 if (internals.registered_types_cpp.find(tindex) !=
586 internals.registered_types_cpp.end())
587 pybind11_fail("generic_type: type \"" + std::string(rec->name) +
588 "\" is already registered!");
589
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100590 object name(PYBIND11_FROM_STRING(rec->name), false);
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200591 object scope_module;
592 if (rec->scope) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200593 if (hasattr(rec->scope, "__module__")) {
594 scope_module = rec->scope.attr("__module__");
595 } else if (hasattr(rec->scope, "__name__")) {
596 scope_module = rec->scope.attr("__name__");
597 }
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200598 }
599
600#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
601 /* Qualified names for Python >= 3.3 */
602 object scope_qualname;
Dean Moldovan865e4302016-09-21 01:06:32 +0200603 if (rec->scope && hasattr(rec->scope, "__qualname__"))
604 scope_qualname = rec->scope.attr("__qualname__");
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200605 object ht_qualname;
606 if (scope_qualname) {
607 ht_qualname = object(PyUnicode_FromFormat(
608 "%U.%U", scope_qualname.ptr(), name.ptr()), false);
609 } else {
610 ht_qualname = name;
611 }
612#endif
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900613
614 size_t num_bases = rec->bases.size();
615 tuple bases(num_bases);
616 for (size_t i = 0; i < num_bases; ++i)
617 bases[i] = rec->bases[i];
618
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200619 std::string full_name = (scope_module ? ((std::string) scope_module.str() + "." + rec->name)
620 : std::string(rec->name));
621
622 char *tp_doc = nullptr;
623 if (rec->doc) {
624 /* Allocate memory for docstring (using PyObject_MALLOC, since
625 Python will free this later on) */
626 size_t size = strlen(rec->doc) + 1;
627 tp_doc = (char *) PyObject_MALLOC(size);
628 memcpy((void *) tp_doc, rec->doc, size);
629 }
630
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900631 /* Danger zone: from now (and until PyType_Ready), make sure to
632 issue no Python C API calls which could potentially invoke the
633 garbage collector (the GC will call type_traverse(), which will in
634 turn find the newly constructed type in an invalid state) */
635
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200636 object type_holder(PyType_Type.tp_alloc(&PyType_Type, 0), false);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100637 auto type = (PyHeapTypeObject*) type_holder.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200638
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100639 if (!type_holder || !name)
Wenzel Jakobe72a6762016-09-14 23:39:16 +0800640 pybind11_fail(std::string(rec->name) + ": Unable to create type object!");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200641
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100642 /* Register supplemental type information in C++ dict */
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100643 detail::type_info *tinfo = new detail::type_info();
644 tinfo->type = (PyTypeObject *) type;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100645 tinfo->type_size = rec->type_size;
646 tinfo->init_holder = rec->init_holder;
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200647 internals.registered_types_cpp[tindex] = tinfo;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100648 internals.registered_types_py[type] = tinfo;
649
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100650 /* Basic type attributes */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200651 type->ht_type.tp_name = strdup(full_name.c_str());
Wenzel Jakob0a078052016-05-29 13:40:40 +0200652 type->ht_type.tp_basicsize = (ssize_t) rec->instance_size;
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900653
654 if (num_bases > 0) {
655 type->ht_type.tp_base = (PyTypeObject *) ((object) bases[0]).inc_ref().ptr();
656 type->ht_type.tp_bases = bases.release().ptr();
657 rec->multiple_inheritance |= num_bases > 1;
658 }
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100659
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100660 type->ht_name = name.release().ptr();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100661
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200662#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
663 type->ht_qualname = ht_qualname.release().ptr();
664#endif
665
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100666 /* Supported protocols */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200667 type->ht_type.tp_as_number = &type->as_number;
668 type->ht_type.tp_as_sequence = &type->as_sequence;
669 type->ht_type.tp_as_mapping = &type->as_mapping;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100670
671 /* Supported elementary operations */
672 type->ht_type.tp_init = (initproc) init;
673 type->ht_type.tp_new = (newfunc) new_instance;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100674 type->ht_type.tp_dealloc = rec->dealloc;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100675
676 /* Support weak references (needed for the keep_alive feature) */
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100677 type->ht_type.tp_weaklistoffset = offsetof(instance_essentials<void>, weakrefs);
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100678
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100679 /* Flags */
680 type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
681#if PY_MAJOR_VERSION < 3
682 type->ht_type.tp_flags |= Py_TPFLAGS_CHECKTYPES;
683#endif
684 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
685
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200686 type->ht_type.tp_doc = tp_doc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200687
688 if (PyType_Ready(&type->ht_type) < 0)
Wenzel Jakobe72a6762016-09-14 23:39:16 +0800689 pybind11_fail(std::string(rec->name) + ": PyType_Ready failed (" +
690 detail::error_string() + ")!");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200691
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100692 m_ptr = type_holder.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200693
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100694 if (scope_module) // Needed by pydoc
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100695 attr("__module__") = scope_module;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200696
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100697 /* Register type with the parent scope */
Wenzel Jakobb2825952016-04-13 23:33:00 +0200698 if (rec->scope)
699 rec->scope.attr(handle(type->ht_name)) = *this;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100700
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900701 if (rec->multiple_inheritance)
702 mark_parents_nonsimple(&type->ht_type);
703
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100704 type_holder.release();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200705 }
706
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900707 /// Helper function which tags all parents of a type using mult. inheritance
708 void mark_parents_nonsimple(PyTypeObject *value) {
709 tuple t(value->tp_bases, true);
710 for (handle h : t) {
711 auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
712 if (tinfo2)
713 tinfo2->simple_type = false;
714 mark_parents_nonsimple((PyTypeObject *) h.ptr());
715 }
716 }
717
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100718 /// Allocate a metaclass on demand (for static properties)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200719 handle metaclass() {
720 auto &ht_type = ((PyHeapTypeObject *) m_ptr)->ht_type;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100721 auto &ob_type = PYBIND11_OB_TYPE(ht_type);
Wenzel Jakob57082212015-09-04 23:42:12 +0200722
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200723 if (ob_type == &PyType_Type) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100724 std::string name_ = std::string(ht_type.tp_name) + "__Meta";
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200725#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
Dean Moldovan242b1462016-09-08 17:02:04 +0200726 object ht_qualname(PyUnicode_FromFormat("%U__Meta", attr("__qualname__").ptr()), false);
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200727#endif
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100728 object name(PYBIND11_FROM_STRING(name_.c_str()), false);
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200729 object type_holder(PyType_Type.tp_alloc(&PyType_Type, 0), false);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100730 if (!type_holder || !name)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100731 pybind11_fail("generic_type::metaclass(): unable to create type object!");
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100732
733 auto type = (PyHeapTypeObject*) type_holder.ptr();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100734 type->ht_name = name.release().ptr();
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200735
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100736#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
737 /* Qualified names for Python >= 3.3 */
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200738 type->ht_qualname = ht_qualname.release().ptr();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100739#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200740 type->ht_type.tp_name = strdup(name_.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100741 type->ht_type.tp_base = ob_type;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100742 type->ht_type.tp_flags |= (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE) &
743 ~Py_TPFLAGS_HAVE_GC;
744
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200745 if (PyType_Ready(&type->ht_type) < 0)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100746 pybind11_fail("generic_type::metaclass(): PyType_Ready failed!");
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100747
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100748 ob_type = (PyTypeObject *) type_holder.release().ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200749 }
750 return handle((PyObject *) ob_type);
751 }
752
753 static int init(void *self, PyObject *, PyObject *) {
754 std::string msg = std::string(Py_TYPE(self)->tp_name) + ": No constructor defined!";
755 PyErr_SetString(PyExc_TypeError, msg.c_str());
756 return -1;
757 }
758
759 static PyObject *new_instance(PyTypeObject *type, PyObject *, PyObject *) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100760 instance<void> *self = (instance<void> *) PyType_GenericAlloc((PyTypeObject *) type, 0);
761 auto tinfo = detail::get_type_info(type);
762 self->value = ::operator new(tinfo->type_size);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200763 self->owned = true;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200764 self->constructed = false;
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400765 detail::get_internals().registered_instances.emplace(self->value, (PyObject *) self);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200766 return (PyObject *) self;
767 }
768
769 static void dealloc(instance<void> *self) {
770 if (self->value) {
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400771 auto instance_type = Py_TYPE(self);
772 auto &registered_instances = detail::get_internals().registered_instances;
773 auto range = registered_instances.equal_range(self->value);
774 bool found = false;
775 for (auto it = range.first; it != range.second; ++it) {
776 if (instance_type == Py_TYPE(it->second)) {
777 registered_instances.erase(it);
778 found = true;
779 break;
780 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200781 }
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400782 if (!found)
783 pybind11_fail("generic_type::dealloc(): Tried to deallocate unregistered instance!");
784
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100785 if (self->weakrefs)
786 PyObject_ClearWeakRefs((PyObject *) self);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200787 }
788 Py_TYPE(self)->tp_free((PyObject*) self);
789 }
790
Wenzel Jakob43398a82015-07-28 16:12:20 +0200791 void install_buffer_funcs(
792 buffer_info *(*get_buffer)(PyObject *, void *),
793 void *get_buffer_data) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200794 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
795 type->ht_type.tp_as_buffer = &type->as_buffer;
Wenzel Jakob57082212015-09-04 23:42:12 +0200796#if PY_MAJOR_VERSION < 3
797 type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
798#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200799 type->as_buffer.bf_getbuffer = getbuffer;
800 type->as_buffer.bf_releasebuffer = releasebuffer;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100801 auto tinfo = detail::get_type_info(&type->ht_type);
802 tinfo->get_buffer = get_buffer;
803 tinfo->get_buffer_data = get_buffer_data;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200804 }
805
806 static int getbuffer(PyObject *obj, Py_buffer *view, int flags) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100807 auto tinfo = detail::get_type_info(Py_TYPE(obj));
808 if (view == nullptr || obj == nullptr || !tinfo || !tinfo->get_buffer) {
809 PyErr_SetString(PyExc_BufferError, "generic_type::getbuffer(): Internal error");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200810 return -1;
811 }
812 memset(view, 0, sizeof(Py_buffer));
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100813 buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200814 view->obj = obj;
815 view->ndim = 1;
816 view->internal = info;
817 view->buf = info->ptr;
Wenzel Jakob0a078052016-05-29 13:40:40 +0200818 view->itemsize = (ssize_t) info->itemsize;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200819 view->len = view->itemsize;
820 for (auto s : info->shape)
821 view->len *= s;
822 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
823 view->format = const_cast<char *>(info->format.c_str());
824 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
Wenzel Jakob0a078052016-05-29 13:40:40 +0200825 view->ndim = (int) info->ndim;
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100826 view->strides = (ssize_t *) &info->strides[0];
827 view->shape = (ssize_t *) &info->shape[0];
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200828 }
829 Py_INCREF(view->obj);
830 return 0;
831 }
832
833 static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; }
834};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400835
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200836NAMESPACE_END(detail)
837
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400838template <typename type_, typename... options>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100839class class_ : public detail::generic_type {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400840 template <typename T> using is_holder = detail::is_holder_type<type_, T>;
841 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 +0900842 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 -0400843 template <typename T> using is_valid_class_option =
844 detail::bool_constant<
845 is_holder<T>::value ||
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400846 is_subtype<T>::value ||
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900847 is_base<T>::value
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400848 >;
849
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200850public:
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400851 using type = type_;
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400852 using type_alias = detail::first_of_t<is_subtype, void, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400853 constexpr static bool has_alias = !std::is_void<type_alias>::value;
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400854 using holder_type = detail::first_of_t<is_holder, std::unique_ptr<type>, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400855 using instance_type = detail::instance<type, holder_type>;
856
857 static_assert(detail::all_of_t<is_valid_class_option, options...>::value,
858 "Unknown/invalid class_ template parameters provided");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200859
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100860 PYBIND11_OBJECT(class_, detail::generic_type, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200861
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100862 template <typename... Extra>
863 class_(handle scope, const char *name, const Extra &... extra) {
864 detail::type_record record;
865 record.scope = scope;
866 record.name = name;
867 record.type = &typeid(type);
Jason Rhinelander9c6859e2016-09-08 11:03:08 -0400868 record.type_size = sizeof(detail::conditional_t<has_alias, type_alias, type>);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100869 record.instance_size = sizeof(instance_type);
870 record.init_holder = init_holder;
871 record.dealloc = dealloc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200872
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900873 /* Register base classes specified via template arguments to class_, if any */
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900874 bool unused[] = { (add_base<options>(record), false)..., false };
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900875 (void) unused;
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400876
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100877 /* Process optional arguments, if any */
878 detail::process_attributes<Extra...>::init(extra..., &record);
879
880 detail::generic_type::initialize(&record);
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200881
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400882 if (has_alias) {
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200883 auto &instances = pybind11::detail::get_internals().registered_types_cpp;
884 instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
885 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100886 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200887
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900888 template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900889 static void add_base(detail::type_record &rec) {
890 rec.add_base(&typeid(Base), [](void *src) -> void * {
891 return static_cast<Base *>(reinterpret_cast<type *>(src));
892 });
893 }
894
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900895 template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900896 static void add_base(detail::type_record &) { }
897
Wenzel Jakob71867832015-07-29 17:43:52 +0200898 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100899 class_ &def(const char *name_, Func&& f, const Extra&... extra) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200900 cpp_function cf(std::forward<Func>(f), name(name_), is_method(*this),
901 sibling(getattr(*this, name_, none())), extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +0200902 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200903 return *this;
904 }
905
Wenzel Jakob71867832015-07-29 17:43:52 +0200906 template <typename Func, typename... Extra> class_ &
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100907 def_static(const char *name_, Func f, const Extra&... extra) {
Dean Moldovan865e4302016-09-21 01:06:32 +0200908 cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
909 sibling(getattr(*this, name_, none())), extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +0200910 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200911 return *this;
912 }
913
Wenzel Jakob71867832015-07-29 17:43:52 +0200914 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100915 class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400916 op.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200917 return *this;
918 }
919
Wenzel Jakob71867832015-07-29 17:43:52 +0200920 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100921 class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400922 op.execute_cast(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200923 return *this;
924 }
925
Wenzel Jakob71867832015-07-29 17:43:52 +0200926 template <typename... Args, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100927 class_ &def(const detail::init<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400928 init.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200929 return *this;
930 }
931
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200932 template <typename... Args, typename... Extra>
933 class_ &def(const detail::init_alias<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400934 init.execute(*this, extra...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200935 return *this;
936 }
937
Wenzel Jakob71867832015-07-29 17:43:52 +0200938 template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob43398a82015-07-28 16:12:20 +0200939 struct capture { Func func; };
940 capture *ptr = new capture { std::forward<Func>(func) };
941 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200942 detail::type_caster<type> caster;
943 if (!caster.load(obj, false))
944 return nullptr;
Wenzel Jakob43398a82015-07-28 16:12:20 +0200945 return new buffer_info(((capture *) ptr)->func(caster));
946 }, ptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200947 return *this;
948 }
949
Wenzel Jakob71867832015-07-29 17:43:52 +0200950 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100951 class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100952 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this)),
953 fset([pm](C &c, const D &value) { c.*pm = value; }, is_method(*this));
954 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200955 return *this;
956 }
957
Wenzel Jakob71867832015-07-29 17:43:52 +0200958 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100959 class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100960 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this));
961 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200962 return *this;
963 }
964
Wenzel Jakob71867832015-07-29 17:43:52 +0200965 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100966 class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100967 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
968 fset([pm](object, const D &value) { *pm = value; }, scope(*this));
969 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200970 return *this;
971 }
972
Wenzel Jakob71867832015-07-29 17:43:52 +0200973 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100974 class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100975 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
976 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200977 return *this;
978 }
979
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100980 template <typename... Extra>
981 class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
982 def_property(name, fget, cpp_function(), extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200983 return *this;
984 }
985
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100986 template <typename... Extra>
987 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
988 def_property_static(name, fget, cpp_function(), extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200989 return *this;
990 }
991
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100992 template <typename... Extra>
993 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100994 return def_property_static(name, fget, fset, is_method(*this), extra...);
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100995 }
996
997 template <typename... Extra>
998 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
999 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001000 char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001001 detail::process_attributes<Extra...>::init(extra..., rec_fget);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001002 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1003 free(doc_prev);
1004 rec_fget->doc = strdup(rec_fget->doc);
1005 }
1006 if (rec_fset) {
1007 doc_prev = rec_fset->doc;
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001008 detail::process_attributes<Extra...>::init(extra..., rec_fset);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +02001009 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1010 free(doc_prev);
1011 rec_fset->doc = strdup(rec_fset->doc);
1012 }
1013 }
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001014 pybind11::str doc_obj = pybind11::str(rec_fget->doc ? rec_fget->doc : "");
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001015 object property(
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001016 PyObject_CallFunctionObjArgs((PyObject *) &PyProperty_Type, fget.ptr() ? fget.ptr() : Py_None,
1017 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr(), nullptr), false);
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001018 if (rec_fget->class_)
1019 attr(name) = property;
1020 else
1021 metaclass().attr(name) = property;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001022 return *this;
1023 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001024
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001025private:
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001026 /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1027 template <typename T>
1028 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 +01001029 try {
hbruintjes70d2e572016-07-01 12:39:55 +02001030 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 +01001031 } catch (const std::bad_weak_ptr &) {
1032 new (&inst->holder) holder_type(inst->value);
1033 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001034 }
1035
1036 /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
1037 template <typename T = holder_type,
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +09001038 detail::enable_if_t<std::is_copy_constructible<T>::value, int> = 0>
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001039 static void init_holder_helper(instance_type *inst, const holder_type *holder_ptr, const void * /* dummy */) {
1040 if (holder_ptr)
1041 new (&inst->holder) holder_type(*holder_ptr);
1042 else
1043 new (&inst->holder) holder_type(inst->value);
1044 }
1045
1046 /// Initialize holder object, variant 3: holder is not copy constructible (e.g. unique_ptr), always initialize from raw pointer
1047 template <typename T = holder_type,
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +09001048 detail::enable_if_t<!std::is_copy_constructible<T>::value, int> = 0>
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001049 static void init_holder_helper(instance_type *inst, const holder_type * /* unused */, const void * /* dummy */) {
1050 new (&inst->holder) holder_type(inst->value);
1051 }
1052
1053 /// Initialize holder object of an instance, possibly given a pointer to an existing holder
1054 static void init_holder(PyObject *inst_, const void *holder_ptr) {
1055 auto inst = (instance_type *) inst_;
1056 init_holder_helper(inst, (const holder_type *) holder_ptr, inst->value);
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001057 inst->constructed = true;
1058 }
1059
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001060 static void dealloc(PyObject *inst_) {
1061 instance_type *inst = (instance_type *) inst_;
1062 if (inst->owned) {
1063 if (inst->constructed)
1064 inst->holder.~holder_type();
1065 else
1066 ::operator delete(inst->value);
1067 }
Wenzel Jakobd561cb02016-01-17 22:36:41 +01001068 generic_type::dealloc((detail::instance<void> *) inst);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001069 }
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001070
1071 static detail::function_record *get_function_record(handle h) {
1072 h = detail::get_function(h);
1073 return h ? (detail::function_record *) capsule(
1074 PyCFunction_GetSelf(h.ptr()), true) : nullptr;
1075 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001076};
1077
1078/// Binds C++ enumerations and enumeration classes to Python
1079template <typename Type> class enum_ : public class_<Type> {
1080public:
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001081 using class_<Type>::def;
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001082 using UnderlyingType = typename std::underlying_type<Type>::type;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001083 template <typename... Extra>
1084 enum_(const handle &scope, const char *name, const Extra&... extra)
1085 : class_<Type>(scope, name, extra...), m_parent(scope) {
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001086 auto entries = new std::unordered_map<UnderlyingType, const char *>();
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001087 def("__repr__", [name, entries](Type value) -> std::string {
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001088 auto it = entries->find((UnderlyingType) value);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001089 return std::string(name) + "." +
1090 ((it == entries->end()) ? std::string("???")
1091 : std::string(it->second));
1092 });
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001093 def("__init__", [](Type& value, UnderlyingType i) { value = (Type)i; });
1094 def("__init__", [](Type& value, UnderlyingType i) { new (&value) Type((Type) i); });
1095 def("__int__", [](Type value) { return (UnderlyingType) value; });
1096 def("__eq__", [](const Type &value, Type *value2) { return value2 && value == *value2; });
1097 def("__ne__", [](const Type &value, Type *value2) { return !value2 || value != *value2; });
Jason Rhinelanderd41a2732016-08-04 00:21:37 -04001098 if (std::is_convertible<Type, UnderlyingType>::value) {
1099 // Don't provide comparison with the underlying type if the enum isn't convertible,
1100 // i.e. if Type is a scoped enum, mirroring the C++ behaviour. (NB: we explicitly
1101 // convert Type to UnderlyingType below anyway because this needs to compile).
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001102 def("__eq__", [](const Type &value, UnderlyingType value2) { return (UnderlyingType) value == value2; });
1103 def("__ne__", [](const Type &value, UnderlyingType value2) { return (UnderlyingType) value != value2; });
Jason Rhinelanderd41a2732016-08-04 00:21:37 -04001104 }
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001105 def("__hash__", [](const Type &value) { return (UnderlyingType) value; });
Wenzel Jakobfe342412016-09-06 13:02:29 +09001106 // Pickling and unpickling -- needed for use with the 'multiprocessing' module
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001107 def("__getstate__", [](const Type &value) { return pybind11::make_tuple((UnderlyingType) value); });
1108 def("__setstate__", [](Type &p, tuple t) { new (&p) Type((Type) t[0].cast<UnderlyingType>()); });
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001109 m_entries = entries;
1110 }
1111
1112 /// Export enumeration entries into the parent scope
1113 void export_values() {
1114 PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict;
1115 PyObject *key, *value;
Wenzel Jakob27e8e102016-01-17 22:36:37 +01001116 ssize_t pos = 0;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001117 while (PyDict_Next(dict, &pos, &key, &value))
1118 if (PyObject_IsInstance(value, this->m_ptr))
1119 m_parent.attr(key) = value;
1120 }
1121
1122 /// Add an enumeration entry
1123 enum_& value(char const* name, Type value) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001124 this->attr(name) = pybind11::cast(value, return_value_policy::copy);
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001125 (*m_entries)[(UnderlyingType) value] = name;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001126 return *this;
1127 }
1128private:
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001129 std::unordered_map<UnderlyingType, const char *> *m_entries;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001130 handle m_parent;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001131};
1132
1133NAMESPACE_BEGIN(detail)
Wenzel Jakob71867832015-07-29 17:43:52 +02001134template <typename... Args> struct init {
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001135 template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
1136 static void execute(Class &cl, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001137 using Base = typename Class::type;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001138 /// Function which calls a specific C++ in-place constructor
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001139 cl.def("__init__", [](Base *self_, Args... args) { new (self_) Base(args...); }, extra...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001140 }
1141
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001142 template <typename Class, typename... Extra,
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001143 enable_if_t<Class::has_alias &&
1144 std::is_constructible<typename Class::type, Args...>::value, int> = 0>
1145 static void execute(Class &cl, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001146 using Base = typename Class::type;
1147 using Alias = typename Class::type_alias;
1148 handle cl_type = cl;
1149 cl.def("__init__", [cl_type](handle self_, Args... args) {
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001150 if (self_.get_type() == cl_type)
1151 new (self_.cast<Base *>()) Base(args...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001152 else
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001153 new (self_.cast<Alias *>()) Alias(args...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001154 }, extra...);
1155 }
1156
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001157 template <typename Class, typename... Extra,
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001158 enable_if_t<Class::has_alias &&
1159 !std::is_constructible<typename Class::type, Args...>::value, int> = 0>
1160 static void execute(Class &cl, const Extra&... extra) {
1161 init_alias<Args...>::execute(cl, extra...);
1162 }
1163};
1164template <typename... Args> struct init_alias {
1165 template <typename Class, typename... Extra,
1166 enable_if_t<Class::has_alias && std::is_constructible<typename Class::type_alias, Args...>::value, int> = 0>
1167 static void execute(Class &cl, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001168 using Alias = typename Class::type_alias;
1169 cl.def("__init__", [](Alias *self_, Args... args) { new (self_) Alias(args...); }, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001170 }
1171};
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001172
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001173
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001174inline void keep_alive_impl(handle nurse, handle patient) {
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001175 /* Clever approach based on weak references taken from Boost.Python */
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001176 if (!nurse || !patient)
Wenzel Jakob678d7872016-01-17 22:36:41 +01001177 pybind11_fail("Could not activate keep_alive!");
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001178
Ivan Smirnov984c7622016-08-29 02:38:47 +01001179 if (patient.is_none() || nurse.is_none())
Glen Walkerf45bb582016-08-16 17:50:43 +12001180 return; /* Nothing to keep alive or nothing to be kept alive by */
Wenzel Jakob9b880ba2016-04-25 03:25:13 +02001181
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001182 cpp_function disable_lifesupport(
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001183 [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001184
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001185 weakref wr(nurse, disable_lifesupport);
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001186
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001187 patient.inc_ref(); /* reference patient and leak the weak reference */
1188 (void) wr.release();
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001189}
1190
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001191PYBIND11_NOINLINE inline void keep_alive_impl(int Nurse, int Patient, handle args, handle ret) {
1192 handle nurse (Nurse > 0 ? PyTuple_GetItem(args.ptr(), Nurse - 1) : ret.ptr());
1193 handle patient(Patient > 0 ? PyTuple_GetItem(args.ptr(), Patient - 1) : ret.ptr());
1194
1195 keep_alive_impl(nurse, patient);
1196}
1197
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001198template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001199struct iterator_state {
1200 Iterator it;
1201 Sentinel end;
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001202 bool first;
1203};
Wenzel Jakobb2825952016-04-13 23:33:00 +02001204
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001205NAMESPACE_END(detail)
1206
Ben Pritchard2de6e1d2016-02-18 13:20:15 -05001207template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); }
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001208template <typename... Args> detail::init_alias<Args...> init_alias() { return detail::init_alias<Args...>(); }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001209
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001210template <return_value_policy Policy = return_value_policy::reference_internal,
1211 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001212 typename Sentinel,
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001213 typename ValueType = decltype(*std::declval<Iterator>()),
1214 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001215iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001216 typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001217
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001218 if (!detail::get_type_info(typeid(state), false)) {
Wenzel Jakob146397e2016-09-06 13:06:31 +09001219 class_<state>(handle(), "iterator")
Wenzel Jakobb2825952016-04-13 23:33:00 +02001220 .def("__iter__", [](state &s) -> state& { return s; })
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001221 .def("__next__", [](state &s) -> ValueType {
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001222 if (!s.first)
1223 ++s.it;
1224 else
1225 s.first = false;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001226 if (s.it == s.end)
1227 throw stop_iteration();
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001228 return *s.it;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001229 }, std::forward<Extra>(extra)..., Policy);
Wenzel Jakobb2825952016-04-13 23:33:00 +02001230 }
1231
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001232 return (iterator) cast(state { first, last, true });
Wenzel Jakobb2825952016-04-13 23:33:00 +02001233}
Wenzel Jakob146397e2016-09-06 13:06:31 +09001234
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001235template <return_value_policy Policy = return_value_policy::reference_internal,
1236 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001237 typename Sentinel,
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001238 typename KeyType = decltype((*std::declval<Iterator>()).first),
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001239 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001240iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001241 typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001242
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +09001243 if (!detail::get_type_info(typeid(state), false)) {
Wenzel Jakob146397e2016-09-06 13:06:31 +09001244 class_<state>(handle(), "iterator")
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001245 .def("__iter__", [](state &s) -> state& { return s; })
1246 .def("__next__", [](state &s) -> KeyType {
1247 if (!s.first)
1248 ++s.it;
1249 else
1250 s.first = false;
1251 if (s.it == s.end)
1252 throw stop_iteration();
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001253 return (*s.it).first;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001254 }, std::forward<Extra>(extra)..., Policy);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001255 }
1256
1257 return (iterator) cast(state { first, last, true });
1258}
Wenzel Jakobb2825952016-04-13 23:33:00 +02001259
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001260template <return_value_policy Policy = return_value_policy::reference_internal,
1261 typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
1262 return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
Wenzel Jakobbf0c7dc2016-04-18 10:52:12 +02001263}
1264
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001265template <return_value_policy Policy = return_value_policy::reference_internal,
1266 typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
1267 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001268}
1269
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001270template <typename InputType, typename OutputType> void implicitly_convertible() {
Wenzel Jakob2ac50442016-01-17 22:36:35 +01001271 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001272 if (!detail::type_caster<InputType>().load(obj, false))
1273 return nullptr;
1274 tuple args(1);
1275 args[0] = obj;
1276 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1277 if (result == nullptr)
1278 PyErr_Clear();
1279 return result;
1280 };
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +01001281 auto &registered_types = detail::get_internals().registered_types_cpp;
1282 auto it = registered_types.find(std::type_index(typeid(OutputType)));
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001283 if (it == registered_types.end())
Wenzel Jakob678d7872016-01-17 22:36:41 +01001284 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
Wenzel Jakobd561cb02016-01-17 22:36:41 +01001285 ((detail::type_info *) it->second)->implicit_conversions.push_back(implicit_caster);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001286}
1287
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001288template <typename ExceptionTranslator>
1289void register_exception_translator(ExceptionTranslator&& translator) {
1290 detail::get_internals().registered_exception_translators.push_front(
1291 std::forward<ExceptionTranslator>(translator));
1292}
1293
1294/* Wrapper to generate a new Python exception type.
1295 *
1296 * This should only be used with PyErr_SetString for now.
1297 * It is not (yet) possible to use as a py::base.
1298 * Template type argument is reserved for future use.
1299 */
1300template <typename type>
1301class exception : public object {
1302public:
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001303 exception(module &m, const std::string &name, PyObject* base=PyExc_Exception) {
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001304 std::string full_name = std::string(PyModule_GetName(m.ptr()))
1305 + std::string(".") + name;
1306 char* exception_name = const_cast<char*>(full_name.c_str());
1307 m_ptr = PyErr_NewException(exception_name, base, NULL);
1308 inc_ref(); // PyModule_AddObject() steals a reference
1309 PyModule_AddObject(m.ptr(), name.c_str(), m_ptr);
1310 }
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001311
1312 // Sets the current python exception to this exception object with the given message
1313 void operator()(const char *message) {
1314 PyErr_SetString(m_ptr, message);
1315 }
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001316};
1317
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001318/** Registers a Python exception in `m` of the given `name` and installs an exception translator to
1319 * translate the C++ exception to the created Python exception using the exceptions what() method.
1320 * This is intended for simple exception translations; for more complex translation, register the
1321 * exception object and translator directly.
1322 */
1323template <typename CppException> exception<CppException>& register_exception(module &m, const std::string &name, PyObject* base = PyExc_Exception) {
1324 static exception<CppException> ex(m, name, base);
1325 register_exception_translator([](std::exception_ptr p) {
1326 if (!p) return;
1327 try {
1328 std::rethrow_exception(p);
1329 }
1330 catch (const CppException &e) {
1331 ex(e.what());
1332 }
1333 });
1334 return ex;
1335}
1336
Dean Moldovan67990d92016-08-29 18:03:34 +02001337NAMESPACE_BEGIN(detail)
1338PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
1339 auto strings = tuple(args.size());
1340 for (size_t i = 0; i < args.size(); ++i) {
1341 strings[i] = args[i].cast<object>().str();
1342 }
Dean Moldovan865e4302016-09-21 01:06:32 +02001343 auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
Dean Moldovan242b1462016-09-08 17:02:04 +02001344 auto line = sep.attr("join")(strings);
Dean Moldovan67990d92016-08-29 18:03:34 +02001345
Dean Moldovan865e4302016-09-21 01:06:32 +02001346 auto file = kwargs.contains("file") ? kwargs["file"].cast<object>()
1347 : module::import("sys").attr("stdout");
Dean Moldovan242b1462016-09-08 17:02:04 +02001348 auto write = file.attr("write");
Dean Moldovan67990d92016-08-29 18:03:34 +02001349 write(line);
Dean Moldovan865e4302016-09-21 01:06:32 +02001350 write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
Dean Moldovan67990d92016-08-29 18:03:34 +02001351
Dean Moldovan865e4302016-09-21 01:06:32 +02001352 if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) {
Dean Moldovan242b1462016-09-08 17:02:04 +02001353 file.attr("flush")();
Dean Moldovan67990d92016-08-29 18:03:34 +02001354 }
1355}
1356NAMESPACE_END(detail)
1357
1358template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1359void print(Args &&...args) {
1360 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
1361 detail::print(c.args(), c.kwargs());
1362}
1363
Felipe Lema2547ca42016-01-25 16:22:44 -03001364#if defined(WITH_THREAD)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001365
1366/* The functions below essentially reproduce the PyGILState_* API using a RAII
1367 * pattern, but there are a few important differences:
1368 *
1369 * 1. When acquiring the GIL from an non-main thread during the finalization
1370 * phase, the GILState API blindly terminates the calling thread, which
1371 * is often not what is wanted. This API does not do this.
1372 *
1373 * 2. The gil_scoped_release function can optionally cut the relationship
1374 * of a PyThreadState and its associated thread, which allows moving it to
1375 * another thread (this is a fairly rare/advanced use case).
1376 *
1377 * 3. The reference count of an acquired thread state can be controlled. This
1378 * can be handy to prevent cases where callbacks issued from an external
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001379 * thread would otherwise constantly construct and destroy thread state data
1380 * structures.
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001381 *
1382 * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
1383 * example which uses features 2 and 3 to migrate the Python thread of
1384 * execution to another thread (to run the event loop on the original thread,
1385 * in this case).
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001386 */
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001387
1388class gil_scoped_acquire {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001389public:
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001390 PYBIND11_NOINLINE gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001391 auto const &internals = detail::get_internals();
1392 tstate = (PyThreadState *) PyThread_get_key_value(internals.tstate);
1393
1394 if (!tstate) {
1395 tstate = PyThreadState_New(internals.istate);
1396 #if !defined(NDEBUG)
1397 if (!tstate)
1398 pybind11_fail("scoped_acquire: could not create thread state!");
1399 #endif
1400 tstate->gilstate_counter = 0;
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001401 #if PY_MAJOR_VERSION < 3
1402 PyThread_delete_key_value(internals.tstate);
1403 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001404 PyThread_set_key_value(internals.tstate, tstate);
1405 } else {
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001406 release = detail::get_thread_state_unchecked() != tstate;
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001407 }
1408
1409 if (release) {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001410 /* Work around an annoying assertion in PyThreadState_Swap */
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001411 #if defined(Py_DEBUG)
1412 PyInterpreterState *interp = tstate->interp;
1413 tstate->interp = nullptr;
1414 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001415 PyEval_AcquireThread(tstate);
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001416 #if defined(Py_DEBUG)
1417 tstate->interp = interp;
1418 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001419 }
1420
1421 inc_ref();
1422 }
1423
1424 void inc_ref() {
1425 ++tstate->gilstate_counter;
1426 }
1427
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001428 PYBIND11_NOINLINE void dec_ref() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001429 --tstate->gilstate_counter;
1430 #if !defined(NDEBUG)
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001431 if (detail::get_thread_state_unchecked() != tstate)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001432 pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
1433 if (tstate->gilstate_counter < 0)
1434 pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
1435 #endif
1436 if (tstate->gilstate_counter == 0) {
1437 #if !defined(NDEBUG)
1438 if (!release)
1439 pybind11_fail("scoped_acquire::dec_ref(): internal error!");
1440 #endif
1441 PyThreadState_Clear(tstate);
1442 PyThreadState_DeleteCurrent();
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001443 PyThread_delete_key_value(detail::get_internals().tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001444 release = false;
1445 }
1446 }
1447
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001448 PYBIND11_NOINLINE ~gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001449 dec_ref();
1450 if (release)
1451 PyEval_SaveThread();
1452 }
1453private:
1454 PyThreadState *tstate = nullptr;
1455 bool release = true;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001456};
1457
1458class gil_scoped_release {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001459public:
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001460 gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
1461 tstate = PyEval_SaveThread();
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001462 if (disassoc) {
Boris Schäling20ee9352016-05-28 12:26:18 +02001463 auto key = detail::get_internals().tstate;
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001464 #if PY_MAJOR_VERSION < 3
1465 PyThread_delete_key_value(key);
1466 #else
1467 PyThread_set_key_value(key, nullptr);
1468 #endif
1469 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001470 }
1471 ~gil_scoped_release() {
1472 if (!tstate)
1473 return;
1474 PyEval_RestoreThread(tstate);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001475 if (disassoc) {
Boris Schäling20ee9352016-05-28 12:26:18 +02001476 auto key = detail::get_internals().tstate;
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001477 #if PY_MAJOR_VERSION < 3
1478 PyThread_delete_key_value(key);
1479 #endif
1480 PyThread_set_key_value(key, tstate);
1481 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001482 }
1483private:
1484 PyThreadState *tstate;
1485 bool disassoc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001486};
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001487#else
1488class gil_scoped_acquire { };
1489class gil_scoped_release { };
Felipe Lema2547ca42016-01-25 16:22:44 -03001490#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001491
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04001492inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
1493 handle py_object = detail::get_object_handle(this_ptr, this_type);
Wenzel Jakobac0fde92015-10-01 18:37:26 +02001494 if (!py_object)
1495 return function();
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001496 handle type = py_object.get_type();
1497 auto key = std::make_pair(type.ptr(), name);
1498
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001499 /* Cache functions that aren't overloaded in Python to avoid
1500 many costly Python dictionary lookups below */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001501 auto &cache = detail::get_internals().inactive_overload_cache;
1502 if (cache.find(key) != cache.end())
1503 return function();
1504
Dean Moldovan865e4302016-09-21 01:06:32 +02001505 function overload = getattr(py_object, name, function());
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001506 if (overload.is_cpp_function()) {
1507 cache.insert(key);
1508 return function();
1509 }
Wenzel Jakob27e8e102016-01-17 22:36:37 +01001510
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001511 /* Don't call dispatch code if invoked from overridden function */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001512 PyFrameObject *frame = PyThreadState_Get()->frame;
Wenzel Jakobb2b44a92016-04-15 17:50:40 +02001513 if (frame && (std::string) pybind11::handle(frame->f_code->co_name).str() == name &&
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001514 frame->f_code->co_argcount > 0) {
1515 PyFrame_FastToLocals(frame);
1516 PyObject *self_caller = PyDict_GetItem(
1517 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
1518 if (self_caller == py_object.ptr())
1519 return function();
1520 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001521 return overload;
1522}
1523
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04001524template <class T> function get_overload(const T *this_ptr, const char *name) {
1525 auto &cpp_types = detail::get_internals().registered_types_cpp;
1526 auto it = cpp_types.find(typeid(T));
1527 if (it == cpp_types.end())
1528 return function();
1529 return get_type_overload(this_ptr, (const detail::type_info *) it->second, name);
1530}
1531
Jason Rhinelander20978262016-08-29 18:16:46 -04001532#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001533 pybind11::gil_scoped_acquire gil; \
Jason Rhinelander20978262016-08-29 18:16:46 -04001534 pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04001535 if (overload) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04001536 auto o = overload(__VA_ARGS__); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04001537 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04001538 static pybind11::detail::overload_caster_t<ret_type> caster; \
1539 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04001540 } \
1541 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
1542 } \
1543 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001544
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001545#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelander20978262016-08-29 18:16:46 -04001546 PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001547 return cname::fn(__VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001548
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001549#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelander20978262016-08-29 18:16:46 -04001550 PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001551 pybind11::pybind11_fail("Tried to call pure virtual function \"" #cname "::" name "\"");
1552
1553#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
1554 PYBIND11_OVERLOAD_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
1555
1556#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
1557 PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001558
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001559NAMESPACE_END(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001560
1561#if defined(_MSC_VER)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001562# pragma warning(pop)
Wenzel Jakob1ffce742016-08-25 01:43:33 +02001563#elif defined(__INTEL_COMPILER)
1564/* Leave ignored warnings on */
Wenzel Jakob6d252962016-05-01 20:47:49 +02001565#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001566# pragma GCC diagnostic pop
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001567#endif