blob: bbe92dfded543b2f7368863cbd8908fb74176174 [file] [log] [blame]
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001/*
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02002 pybind11/common.h -- Basic macros
Wenzel Jakob38bd7112015-07-05 20:05:44 +02003
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +02004 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakob38bd7112015-07-05 20:05:44 +02005
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020010#pragma once
Wenzel Jakob38bd7112015-07-05 20:05:44 +020011
12#if !defined(NAMESPACE_BEGIN)
Wenzel Jakob53b26542016-01-17 22:36:43 +010013# define NAMESPACE_BEGIN(name) namespace name {
Wenzel Jakob38bd7112015-07-05 20:05:44 +020014#endif
15#if !defined(NAMESPACE_END)
Wenzel Jakob53b26542016-01-17 22:36:43 +010016# define NAMESPACE_END(name) }
Wenzel Jakob38bd7112015-07-05 20:05:44 +020017#endif
18
Jason Rhinelanderf1b44a02016-11-04 09:49:37 -040019// Neither MSVC nor Intel support enough of C++14 yet (in particular, as of MSVC 2015 and ICC 17
20// beta, neither support extended constexpr, which we rely on in descr.h), so don't enable pybind
21// CPP14 features for them.
22#if !defined(_MSC_VER) && !defined(__INTEL_COMPILER)
23# if __cplusplus >= 201402L
24# define PYBIND11_CPP14
25# if __cplusplus > 201402L /* Temporary: should be updated to >= the final C++17 value once known */
26# define PYBIND11_CPP17
27# endif
28# endif
29#endif
30
Wenzel Jakobb1b71402015-10-18 16:48:30 +020031#if !defined(PYBIND11_EXPORT)
Wenzel Jakob53b26542016-01-17 22:36:43 +010032# if defined(WIN32) || defined(_WIN32)
33# define PYBIND11_EXPORT __declspec(dllexport)
34# else
35# define PYBIND11_EXPORT __attribute__ ((visibility("default")))
36# endif
Wenzel Jakob0fb85282015-10-19 23:50:51 +020037#endif
38
Wenzel Jakob53b26542016-01-17 22:36:43 +010039#if defined(_MSC_VER)
40# define PYBIND11_NOINLINE __declspec(noinline)
41#else
42# define PYBIND11_NOINLINE __attribute__ ((noinline))
43#endif
44
Jason Rhinelanderf1b44a02016-11-04 09:49:37 -040045#if defined(PYBIND11_CPP14)
Wenzel Jakobbad589a2016-09-12 12:03:20 +090046# define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
47#elif defined(__clang__)
48# define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
49#elif defined(__GNUG__)
50# define PYBIND11_DEPRECATED(reason) __attribute__((deprecated))
51#elif defined(_MSC_VER)
52# define PYBIND11_DEPRECATED(reason) __declspec(deprecated)
53#endif
54
Wenzel Jakobe33ef9c2017-01-01 13:55:06 +010055#define PYBIND11_VERSION_MAJOR 2
Wenzel Jakobfb4e1042017-01-01 14:29:40 +010056#define PYBIND11_VERSION_MINOR 1
57#define PYBIND11_VERSION_PATCH dev0
Wenzel Jakob1ae77fe2016-01-17 22:36:43 +010058
Wenzel Jakob53b26542016-01-17 22:36:43 +010059/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
60#if defined(_MSC_VER)
61# define HAVE_ROUND
62# pragma warning(push)
63# pragma warning(disable: 4510 4610 4512 4005)
Matthias Möllerc2d1d952017-01-31 16:54:49 +010064# if defined(_DEBUG)
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +020065# define PYBIND11_DEBUG_MARKER
Wenzel Jakob53b26542016-01-17 22:36:43 +010066# undef _DEBUG
67# endif
68#endif
69
70#include <Python.h>
71#include <frameobject.h>
Wenzel Jakob39e97e62016-04-25 03:26:15 +020072#include <pythread.h>
Wenzel Jakob53b26542016-01-17 22:36:43 +010073
Wenzel Jakoba771e362016-07-19 17:47:59 +020074#if defined(_WIN32) && (defined(min) || defined(max))
75# error Macro clash with min and max -- define NOMINMAX when compiling your program on Windows
76#endif
77
78#if defined(isalnum)
Wenzel Jakob53b26542016-01-17 22:36:43 +010079# undef isalnum
80# undef isalpha
81# undef islower
82# undef isspace
83# undef isupper
84# undef tolower
85# undef toupper
86#endif
87
88#if defined(_MSC_VER)
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +020089# if defined(PYBIND11_DEBUG_MARKER)
Wenzel Jakob53b26542016-01-17 22:36:43 +010090# define _DEBUG
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +020091# undef PYBIND11_DEBUG_MARKER
92# endif
Wenzel Jakob53b26542016-01-17 22:36:43 +010093# pragma warning(pop)
94#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +020095
Wenzel Jakob06bd27f2016-11-15 06:37:39 +010096#include <cstddef>
Pim Schellart5a7d17f2016-06-17 17:35:59 -040097#include <forward_list>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020098#include <vector>
99#include <string>
100#include <stdexcept>
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200101#include <unordered_set>
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200102#include <unordered_map>
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200103#include <memory>
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +0100104#include <typeindex>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +0900105#include <type_traits>
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200106
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100107#if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100108#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100109#define PYBIND11_BYTES_CHECK PyBytes_Check
110#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
111#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
112#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
113#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
114#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
115#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
116#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) PyLong_AsUnsignedLongLong(o)
Wenzel Jakob56e9f492016-01-17 22:36:38 +0100117#define PYBIND11_BYTES_NAME "bytes"
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100118#define PYBIND11_STRING_NAME "str"
119#define PYBIND11_SLICE_OBJECT PyObject
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100120#define PYBIND11_FROM_STRING PyUnicode_FromString
Ivan Smirnov1cdd1712016-08-13 12:39:16 +0100121#define PYBIND11_STR_TYPE ::pybind11::str
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100122#define PYBIND11_OB_TYPE(ht_type) (ht_type).ob_base.ob_base.ob_type
123#define PYBIND11_PLUGIN_IMPL(name) \
124 extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100125#else
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100126#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100127#define PYBIND11_BYTES_CHECK PyString_Check
128#define PYBIND11_BYTES_FROM_STRING PyString_FromString
129#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
130#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
131#define PYBIND11_BYTES_AS_STRING PyString_AsString
132#define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
133#define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
134#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) (PyInt_Check(o) ? (unsigned long long) PyLong_AsUnsignedLong(o) : PyLong_AsUnsignedLongLong(o))
Wenzel Jakob56e9f492016-01-17 22:36:38 +0100135#define PYBIND11_BYTES_NAME "str"
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100136#define PYBIND11_STRING_NAME "unicode"
137#define PYBIND11_SLICE_OBJECT PySliceObject
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100138#define PYBIND11_FROM_STRING PyString_FromString
Ivan Smirnov1cdd1712016-08-13 12:39:16 +0100139#define PYBIND11_STR_TYPE ::pybind11::bytes
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100140#define PYBIND11_OB_TYPE(ht_type) (ht_type).ob_type
141#define PYBIND11_PLUGIN_IMPL(name) \
Alexander Stukowski05bc1ff2017-01-13 11:12:22 +0100142 static PyObject *pybind11_init_wrapper(); \
143 extern "C" PYBIND11_EXPORT void init##name() { \
144 (void)pybind11_init_wrapper(); \
145 } \
146 PyObject *pybind11_init_wrapper()
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100147#endif
Wenzel Jakob57082212015-09-04 23:42:12 +0200148
Wenzel Jakobfbafdea2016-04-25 15:02:43 +0200149#if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
150extern "C" {
151 struct _Py_atomic_address { void *value; };
152 PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
Ivan Smirnov3ae5bd72016-06-17 22:29:10 +0100153}
Wenzel Jakobfbafdea2016-04-25 15:02:43 +0200154#endif
155
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100156#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
Wenzel Jakob77586fd2016-03-06 13:38:18 +0100157#define PYBIND11_STRINGIFY(x) #x
158#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
159#define PYBIND11_INTERNALS_ID "__pybind11_" \
160 PYBIND11_TOSTRING(PYBIND11_VERSION_MAJOR) "_" PYBIND11_TOSTRING(PYBIND11_VERSION_MINOR) "__"
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100161
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100162/** \rst
163 This macro creates the entry point that will be invoked when the Python interpreter
164 imports a plugin library. Please create a `module` in the function body and return
165 the pointer to its underlying Python object at the end.
166
167 .. code-block:: cpp
168
169 PYBIND11_PLUGIN(example) {
170 pybind11::module m("example", "pybind11 example plugin");
171 /// Set up bindings here
172 return m.ptr();
173 }
174\endrst */
Wenzel Jakob4c00fd92016-10-09 19:40:15 +0200175#define PYBIND11_PLUGIN(name) \
176 static PyObject *pybind11_init(); \
177 PYBIND11_PLUGIN_IMPL(name) { \
178 int major, minor; \
179 if (sscanf(Py_GetVersion(), "%i.%i", &major, &minor) != 2) { \
180 PyErr_SetString(PyExc_ImportError, "Can't parse Python version."); \
181 return nullptr; \
182 } else if (major != PY_MAJOR_VERSION || minor != PY_MINOR_VERSION) { \
183 PyErr_Format(PyExc_ImportError, \
184 "Python version mismatch: module was compiled for " \
185 "version %i.%i, while the interpreter is running " \
186 "version %i.%i.", PY_MAJOR_VERSION, PY_MINOR_VERSION, \
187 major, minor); \
188 return nullptr; \
189 } \
190 try { \
191 return pybind11_init(); \
192 } catch (const std::exception &e) { \
193 PyErr_SetString(PyExc_ImportError, e.what()); \
194 return nullptr; \
195 } \
196 } \
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100197 PyObject *pybind11_init()
198
Jason Rhinelander6e036e72016-12-13 20:06:41 -0500199// Function return value and argument type deduction support. When compiling under C++17 these
200// differ as C++17 makes the noexcept specifier part of the function type, while it is not part of
201// the type under earlier standards.
202#ifdef __cpp_noexcept_function_type
203# define PYBIND11_NOEXCEPT_TPL_ARG , bool NoExceptions
204# define PYBIND11_NOEXCEPT_SPECIFIER noexcept(NoExceptions)
205#else
206# define PYBIND11_NOEXCEPT_TPL_ARG
207# define PYBIND11_NOEXCEPT_SPECIFIER
208#endif
209
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200210NAMESPACE_BEGIN(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200211
Wenzel Jakob06bd27f2016-11-15 06:37:39 +0100212using ssize_t = Py_ssize_t;
213using size_t = std::size_t;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200214
215/// Approach used to cast a previously unknown C++ instance into a Python object
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100216enum class return_value_policy : uint8_t {
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200217 /** This is the default return value policy, which falls back to the policy
218 return_value_policy::take_ownership when the return value is a pointer.
219 Otherwise, it uses return_value::move or return_value::copy for rvalue
220 and lvalue references, respectively. See below for a description of what
221 all of these different policies do. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200222 automatic = 0,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200223
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200224 /** As above, but use policy return_value_policy::reference when the return
Wenzel Jakob37e1f612016-06-22 14:29:13 +0200225 value is a pointer. This is the default conversion policy for function
226 arguments when calling Python functions manually from C++ code (i.e. via
227 handle::operator()). You probably won't need to use this. */
Wenzel Jakob8bd31c72016-04-14 14:26:13 +0200228 automatic_reference,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200229
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200230 /** Reference an existing object (i.e. do not create a new copy) and take
231 ownership. Python will call the destructor and delete operator when the
232 object’s reference count reaches zero. Undefined behavior ensues when
233 the C++ side does the same.. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200234 take_ownership,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200235
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200236 /** Create a new copy of the returned object, which will be owned by
237 Python. This policy is comparably safe because the lifetimes of the two
238 instances are decoupled. */
239 copy,
240
241 /** Use std::move to move the return value contents into a new instance
242 that will be owned by Python. This policy is comparably safe because the
243 lifetimes of the two instances (move source and destination) are
244 decoupled. */
245 move,
246
247 /** Reference an existing object, but do not take ownership. The C++ side
248 is responsible for managing the object’s lifetime and deallocating it
249 when it is no longer used. Warning: undefined behavior will ensue when
Wenzel Jakobe84f5572016-04-26 23:19:19 +0200250 the C++ side deletes an object that is still referenced and used by
251 Python. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200252 reference,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200253
Wenzel Jakobe84f5572016-04-26 23:19:19 +0200254 /** This policy only applies to methods and properties. It references the
255 object without taking ownership similar to the above
256 return_value_policy::reference policy. In contrast to that policy, the
257 function or property’s implicit this argument (called the parent) is
258 considered to be the the owner of the return value (the child).
259 pybind11 then couples the lifetime of the parent to the child via a
260 reference relationship that ensures that the parent cannot be garbage
261 collected while Python is still using the child. More advanced
262 variations of this scheme are also possible using combinations of
263 return_value_policy::reference and the keep_alive call policy */
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200264 reference_internal
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200265};
266
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200267/// Information record describing a Python buffer object
268struct buffer_info {
Jason Newton3718c382016-09-02 17:10:02 -0400269 void *ptr = nullptr; // Pointer to the underlying storage
270 size_t itemsize = 0; // Size of individual items in bytes
271 size_t size = 0; // Total number of entries
Ivan Smirnov5e71e172016-06-26 12:42:34 +0100272 std::string format; // For homogeneous buffers, this should be set to format_descriptor<T>::format()
Jason Newton3718c382016-09-02 17:10:02 -0400273 size_t ndim = 0; // Number of dimensions
Wenzel Jakobe45b2902016-01-17 22:36:41 +0100274 std::vector<size_t> shape; // Shape of the tensor (1 entry per dimension)
275 std::vector<size_t> strides; // Number of entries between adjacent entries (for each per dimension)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200276
Wenzel Jakobf3be07c2016-09-04 23:03:48 +0900277 buffer_info() { }
Ivan Smirnov98ba98c2016-07-24 20:29:44 +0100278
Wenzel Jakob0a078052016-05-29 13:40:40 +0200279 buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t ndim,
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200280 const std::vector<size_t> &shape, const std::vector<size_t> &strides)
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100281 : ptr(ptr), itemsize(itemsize), size(1), format(format),
282 ndim(ndim), shape(shape), strides(strides) {
Wenzel Jakob0a078052016-05-29 13:40:40 +0200283 for (size_t i = 0; i < ndim; ++i)
284 size *= shape[i];
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200285 }
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100286
Ivan Smirnov98ba98c2016-07-24 20:29:44 +0100287 buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t size)
288 : buffer_info(ptr, itemsize, format, 1, std::vector<size_t> { size },
289 std::vector<size_t> { itemsize }) { }
290
Jason Rhinelander12d76602016-10-16 16:27:42 -0400291 explicit buffer_info(Py_buffer *view, bool ownview = true)
Wenzel Jakob0a078052016-05-29 13:40:40 +0200292 : ptr(view->buf), itemsize((size_t) view->itemsize), size(1), format(view->format),
Jason Newton514c6da2016-09-02 17:10:25 -0400293 ndim((size_t) view->ndim), shape((size_t) view->ndim), strides((size_t) view->ndim), view(view), ownview(ownview) {
Wenzel Jakob0a078052016-05-29 13:40:40 +0200294 for (size_t i = 0; i < (size_t) view->ndim; ++i) {
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100295 shape[i] = (size_t) view->shape[i];
296 strides[i] = (size_t) view->strides[i];
297 size *= shape[i];
298 }
299 }
300
Jason Newton10d46e72016-09-02 18:39:47 -0400301 buffer_info(const buffer_info &) = delete;
302 buffer_info& operator=(const buffer_info &) = delete;
303
Wenzel Jakobf3be07c2016-09-04 23:03:48 +0900304 buffer_info(buffer_info &&other) {
Jason Newton47646982016-09-02 17:11:30 -0400305 (*this) = std::move(other);
306 }
307
Wenzel Jakobcc4e4062016-09-05 08:25:10 +0900308 buffer_info& operator=(buffer_info &&rhs) {
Jason Newton47646982016-09-02 17:11:30 -0400309 ptr = rhs.ptr;
310 itemsize = rhs.itemsize;
311 size = rhs.size;
312 format = std::move(rhs.format);
313 ndim = rhs.ndim;
314 shape = std::move(rhs.shape);
315 strides = std::move(rhs.strides);
316 std::swap(view, rhs.view);
317 std::swap(ownview, rhs.ownview);
318 return *this;
319 }
320
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100321 ~buffer_info() {
Jason Newton514c6da2016-09-02 17:10:25 -0400322 if (view && ownview) { PyBuffer_Release(view); delete view; }
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100323 }
Ivan Smirnova7e62e12016-06-19 14:37:55 +0100324
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100325private:
326 Py_buffer *view = nullptr;
Jason Newton514c6da2016-09-02 17:10:25 -0400327 bool ownview = false;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200328};
329
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200330NAMESPACE_BEGIN(detail)
331
Wenzel Jakobe6118232016-05-05 21:54:24 +0200332inline static constexpr int log2(size_t n, int k = 0) { return (n <= 1) ? k : log2(n >> 1, k + 1); }
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200333
Wenzel Jakob96c10532015-10-01 16:42:15 +0200334inline std::string error_string();
335
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100336/// Core part of the 'instance' type which POD (needed to be able to use 'offsetof')
337template <typename type> struct instance_essentials {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200338 PyObject_HEAD
339 type *value;
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100340 PyObject *weakrefs;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200341 bool owned : 1;
Jason Rhinelanderc07ec312016-11-06 13:12:48 -0500342 bool holder_constructed : 1;
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100343};
344
345/// PyObject wrapper around generic types, includes a special holder type that is responsible for lifetime management
346template <typename type, typename holder_type = std::unique_ptr<type>> struct instance : instance_essentials<type> {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200347 holder_type holder;
348};
349
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200350struct overload_hash {
Wenzel Jakob06bd27f2016-11-15 06:37:39 +0100351 inline size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200352 size_t value = std::hash<const void *>()(v.first);
353 value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value<<6) + (value>>2);
354 return value;
355 }
356};
357
Wenzel Jakob43398a82015-07-28 16:12:20 +0200358/// Internal data struture used to track registered instances and types
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200359struct internals {
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400360 std::unordered_map<std::type_index, void*> registered_types_cpp; // std::type_index -> type_info
361 std::unordered_map<const void *, void*> registered_types_py; // PyTypeObject* -> type_info
362 std::unordered_multimap<const void *, void*> registered_instances; // void * -> PyObject*
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200363 std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
Ivan Smirnovc275ee62016-10-20 16:09:31 +0100364 std::unordered_map<std::type_index, std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400365 std::forward_list<void (*) (std::exception_ptr)> registered_exception_translators;
Ivan Smirnov2dbf0292016-10-31 14:11:10 +0000366 std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions
Wenzel Jakob39e97e62016-04-25 03:26:15 +0200367#if defined(WITH_THREAD)
Boris Schäling20ee9352016-05-28 12:26:18 +0200368 decltype(PyThread_create_key()) tstate = 0; // Usually an int but a long on Cygwin64 with Python 3.x
Wenzel Jakob39e97e62016-04-25 03:26:15 +0200369 PyInterpreterState *istate = nullptr;
370#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200371};
372
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200373/// Return a reference to the current 'internals' information
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200374inline internals &get_internals();
375
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -0500376/// from __cpp_future__ import (convenient aliases from C++14/17)
Dean Moldovan8c85a852016-11-27 20:56:04 +0100377#ifdef PYBIND11_CPP14
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -0500378using std::enable_if_t;
379using std::conditional_t;
380#else
381template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
382template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
383#endif
384
385/// Index sequences
386#if defined(PYBIND11_CPP14) || defined(_MSC_VER)
Dean Moldovan8c85a852016-11-27 20:56:04 +0100387using std::index_sequence;
388using std::make_index_sequence;
389#else
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200390template<size_t ...> struct index_sequence { };
Dean Moldovan8c85a852016-11-27 20:56:04 +0100391template<size_t N, size_t ...S> struct make_index_sequence_impl : make_index_sequence_impl <N - 1, N - 1, S...> { };
392template<size_t ...S> struct make_index_sequence_impl <0, S...> { typedef index_sequence<S...> type; };
393template<size_t N> using make_index_sequence = typename make_index_sequence_impl<N>::type;
394#endif
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200395
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -0500396#if defined(PYBIND11_CPP17) || defined(_MSC_VER)
397using std::bool_constant;
398using std::negation;
399#else
400template <bool B> using bool_constant = std::integral_constant<bool, B>;
401template <class T> using negation = bool_constant<!T::value>;
402#endif
403
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100404/// Compile-time all/any/none of that check the boolean value of all template types
Jason Rhinelander6ae68fe2016-12-13 12:23:12 -0500405#ifdef PYBIND11_CPP17
406template <class... Ts> using all_of = bool_constant<(Ts::value && ...)>;
407template <class... Ts> using any_of = bool_constant<(Ts::value || ...)>;
408#elif !defined(_MSC_VER)
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -0500409template <bool...> struct bools {};
410template <class... Ts> using all_of = std::is_same<
411 bools<Ts::value..., true>,
412 bools<true, Ts::value...>>;
413template <class... Ts> using any_of = negation<all_of<negation<Ts>...>>;
414#else
415// MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
416// at a slight loss of compilation efficiency).
417template <class... Ts> using all_of = std::conjunction<Ts...>;
418template <class... Ts> using any_of = std::disjunction<Ts...>;
419#endif
420template <class... Ts> using none_of = negation<any_of<Ts...>>;
421
Jason Rhinelanderf7f5bc82017-01-31 11:00:15 -0500422template <class T, template<class> class... Predicates> using satisfies_all_of = all_of<Predicates<T>...>;
423template <class T, template<class> class... Predicates> using satisfies_any_of = any_of<Predicates<T>...>;
424template <class T, template<class> class... Predicates> using satisfies_none_of = none_of<Predicates<T>...>;
425
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200426/// Strip the class from a method type
Wenzel Jakobad696342016-05-03 13:28:40 +0200427template <typename T> struct remove_class { };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200428template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
429template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
430
431/// Helper template to strip away type modifiers
Wenzel Jakob4177ed42016-01-17 22:36:38 +0100432template <typename T> struct intrinsic_type { typedef T type; };
433template <typename T> struct intrinsic_type<const T> { typedef typename intrinsic_type<T>::type type; };
434template <typename T> struct intrinsic_type<T*> { typedef typename intrinsic_type<T>::type type; };
435template <typename T> struct intrinsic_type<T&> { typedef typename intrinsic_type<T>::type type; };
436template <typename T> struct intrinsic_type<T&&> { typedef typename intrinsic_type<T>::type type; };
437template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
438template <typename T, size_t N> struct intrinsic_type<T[N]> { typedef typename intrinsic_type<T>::type type; };
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200439template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200440
441/// Helper type to replace 'void' in some expressions
442struct void_type { };
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200443
Dean Moldovan719c1732016-11-27 18:19:34 +0100444/// Helper template which holds a list of types
445template <typename...> struct type_list { };
446
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200447/// Compile-time integer sum
448constexpr size_t constexpr_sum() { return 0; }
449template <typename T, typename... Ts>
450constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
451
Jason Rhinelander34d308a2017-01-22 19:12:24 -0500452NAMESPACE_BEGIN(constexpr_impl)
453/// Implementation details for constexpr functions
454constexpr int first(int i) { return i; }
455template <typename T, typename... Ts>
456constexpr int first(int i, T v, Ts... vs) { return v ? i : first(i + 1, vs...); }
457
458constexpr int last(int /*i*/, int result) { return result; }
459template <typename T, typename... Ts>
460constexpr int last(int i, int result, T v, Ts... vs) { return last(i + 1, v ? i : result, vs...); }
461NAMESPACE_END(constexpr_impl)
462
463/// Return the index of the first type in Ts which satisfies Predicate<T>. Returns sizeof...(Ts) if
464/// none match.
465template <template<typename> class Predicate, typename... Ts>
466constexpr int constexpr_first() { return constexpr_impl::first(0, Predicate<Ts>::value...); }
467
468/// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
469template <template<typename> class Predicate, typename... Ts>
470constexpr int constexpr_last() { return constexpr_impl::last(0, -1, Predicate<Ts>::value...); }
471
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400472// Extracts the first type from the template parameter pack matching the predicate, or Default if none match.
473template <template<class> class Predicate, class Default, class... Ts> struct first_of;
474template <template<class> class Predicate, class Default> struct first_of<Predicate, Default> {
475 using type = Default;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400476};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400477template <template<class> class Predicate, class Default, class T, class... Ts>
478struct first_of<Predicate, Default, T, Ts...> {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400479 using type = typename std::conditional<
480 Predicate<T>::value,
481 T,
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400482 typename first_of<Predicate, Default, Ts...>::type
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400483 >::type;
484};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400485template <template<class> class Predicate, class Default, class... T> using first_of_t = typename first_of<Predicate, Default, T...>::type;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400486
Dean Moldovan56e86ed2016-09-04 21:30:08 +0200487/// Defer the evaluation of type T until types Us are instantiated
488template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
489template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
490
Dean Moldovan71af3b02016-09-24 23:54:02 +0200491template <template<typename...> class Base>
492struct is_template_base_of_impl {
493 template <typename... Us> static std::true_type check(Base<Us...> *);
494 static std::false_type check(...);
495};
496
497/// Check if a template is the base of a type. For example:
498/// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
499template <template<typename...> class Base, typename T>
500#if !defined(_MSC_VER)
501using is_template_base_of = decltype(is_template_base_of_impl<Base>::check((T*)nullptr));
502#else // MSVC2015 has trouble with decltype in template aliases
503struct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((T*)nullptr)) { };
504#endif
505
Dean Moldovan5d28dd12016-10-18 13:56:33 +0200506/// Check if T is std::shared_ptr<U> where U can be anything
507template <typename T> struct is_shared_ptr : std::false_type { };
508template <typename U> struct is_shared_ptr<std::shared_ptr<U>> : std::true_type { };
509
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200510/// Ignore that a variable is unused in compiler warnings
511inline void ignore_unused(const int *) { }
512
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200513NAMESPACE_END(detail)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200514
Ivan Smirnov2dbf0292016-10-31 14:11:10 +0000515/// Returns a named pointer that is shared among all extension modules (using the same
516/// pybind11 version) running in the current interpreter. Names starting with underscores
517/// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
518inline PYBIND11_NOINLINE void* get_shared_data(const std::string& name) {
519 auto& internals = detail::get_internals();
520 auto it = internals.shared_data.find(name);
521 return it != internals.shared_data.end() ? it->second : nullptr;
522}
523
524/// Set the shared data that can be later recovered by `get_shared_data()`.
525inline PYBIND11_NOINLINE void *set_shared_data(const std::string& name, void *data) {
526 detail::get_internals().shared_data[name] = data;
527 return data;
528}
529
530/// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
531/// such entry exists. Otherwise, a new object of default-constructible type `T` is
532/// added to the shared data under the given name and a reference to it is returned.
533template<typename T> T& get_or_create_shared_data(const std::string& name) {
534 auto& internals = detail::get_internals();
535 auto it = internals.shared_data.find(name);
536 T* ptr = (T*) (it != internals.shared_data.end() ? it->second : nullptr);
537 if (!ptr) {
538 ptr = new T();
539 internals.shared_data[name] = ptr;
540 }
541 return *ptr;
542}
543
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200544/// Fetch and hold an error which was already set in Python
545class error_already_set : public std::runtime_error {
546public:
547 error_already_set() : std::runtime_error(detail::error_string()) {
548 PyErr_Fetch(&type, &value, &trace);
549 }
Wenzel Jakobfbec17c2016-11-24 12:30:11 +0100550
551 error_already_set(const error_already_set &) = delete;
552
553 error_already_set(error_already_set &&e)
554 : std::runtime_error(e.what()), type(e.type), value(e.value),
555 trace(e.trace) { e.type = e.value = e.trace = nullptr; }
556
Wenzel Jakob8d396fc2016-11-24 23:11:02 +0100557 inline ~error_already_set(); // implementation in pybind11.h
Wenzel Jakob099d6e92016-11-24 18:52:31 +0100558
559 error_already_set& operator=(const error_already_set &) = delete;
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200560
561 /// Give the error back to Python
562 void restore() { PyErr_Restore(type, value, trace); type = value = trace = nullptr; }
563
564private:
565 PyObject *type, *value, *trace;
566};
567
Dean Moldovanf69071c2016-09-10 14:43:28 +0200568/// C++ bindings of builtin Python exceptions
569class builtin_exception : public std::runtime_error {
570public:
571 using std::runtime_error::runtime_error;
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100572 /// Set the error using the Python C API
573 virtual void set_error() const = 0;
Dean Moldovanf69071c2016-09-10 14:43:28 +0200574};
575
576#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
577 class name : public builtin_exception { public: \
578 using builtin_exception::builtin_exception; \
579 name() : name("") { } \
580 void set_error() const override { PyErr_SetString(type, what()); } \
Wenzel Jakobad696342016-05-03 13:28:40 +0200581 };
582
Dean Moldovanf69071c2016-09-10 14:43:28 +0200583PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
584PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
585PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
586PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
587PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
588PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
589PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200590
Wenzel Jakobfc92d822016-04-30 23:55:44 +0200591[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
592[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
Wenzel Jakob678d7872016-01-17 22:36:41 +0100593
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200594template <typename T, typename SFINAE = void> struct format_descriptor { };
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100595
Jason Rhinelanderf7f5bc82017-01-31 11:00:15 -0500596NAMESPACE_BEGIN(detail)
597// Returns the index of the given type in the type char array below, and in the list in numpy.h
598// The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
599// complex float,double,long double. Note that the long double types only participate when long
600// double is actually longer than double (it isn't under MSVC).
601// NB: not only the string below but also complex.h and numpy.h rely on this order.
602template <typename T, typename SFINAE = void> struct is_fmt_numeric { static constexpr bool value = false; };
603template <typename T> struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
604 static constexpr bool value = true;
605 static constexpr int index = std::is_same<T, bool>::value ? 0 : 1 + (
606 std::is_integral<T>::value ? detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value : 8 + (
607 std::is_same<T, double>::value ? 1 : std::is_same<T, long double>::value ? 2 : 0));
608};
609NAMESPACE_END(detail)
610
611template <typename T> struct format_descriptor<T, detail::enable_if_t<detail::is_fmt_numeric<T>::value>> {
612 static constexpr const char c = "?bBhHiIqQfdgFDG"[detail::is_fmt_numeric<T>::index];
Wenzel Jakobb0c44442016-09-27 11:23:52 +0200613 static constexpr const char value[2] = { c, '\0' };
614 static std::string format() { return std::string(1, c); }
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200615};
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100616
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200617template <typename T> constexpr const char format_descriptor<
Jason Rhinelanderf7f5bc82017-01-31 11:00:15 -0500618 T, detail::enable_if_t<detail::is_fmt_numeric<T>::value>>::value[2];
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100619
Wenzel Jakob720136b2016-09-10 16:32:17 +0900620/// RAII wrapper that temporarily clears any Python error state
621struct error_scope {
622 PyObject *type, *value, *trace;
623 error_scope() { PyErr_Fetch(&type, &value, &trace); }
624 ~error_scope() { PyErr_Restore(type, value, trace); }
625};
626
Wenzel Jakob5e4e4772016-08-28 02:03:15 +0200627/// Dummy destructor wrapper that can be used to expose classes with a private destructor
628struct nodelete { template <typename T> void operator()(T*) { } };
Nickolai Belakovski63338252016-08-27 11:57:55 -0700629
Dean Moldovan4e959c92016-12-08 11:07:52 +0100630// overload_cast requires variable templates: C++14 or MSVC 2015 Update 2
631#if defined(PYBIND11_CPP14) || _MSC_FULL_VER >= 190023918
632#define PYBIND11_OVERLOAD_CAST 1
633
634NAMESPACE_BEGIN(detail)
635template <typename... Args>
636struct overload_cast_impl {
Jason Rhinelander6e036e72016-12-13 20:06:41 -0500637 template <typename Return /*,*/ PYBIND11_NOEXCEPT_TPL_ARG>
638 constexpr auto operator()(Return (*pf)(Args...) PYBIND11_NOEXCEPT_SPECIFIER) const noexcept
Dean Moldovan4e959c92016-12-08 11:07:52 +0100639 -> decltype(pf) { return pf; }
640
Jason Rhinelander6e036e72016-12-13 20:06:41 -0500641 template <typename Return, typename Class /*,*/ PYBIND11_NOEXCEPT_TPL_ARG>
642 constexpr auto operator()(Return (Class::*pmf)(Args...) PYBIND11_NOEXCEPT_SPECIFIER, std::false_type = {}) const noexcept
Dean Moldovan4e959c92016-12-08 11:07:52 +0100643 -> decltype(pmf) { return pmf; }
644
Jason Rhinelander6e036e72016-12-13 20:06:41 -0500645 template <typename Return, typename Class /*,*/ PYBIND11_NOEXCEPT_TPL_ARG>
646 constexpr auto operator()(Return (Class::*pmf)(Args...) const PYBIND11_NOEXCEPT_SPECIFIER, std::true_type) const noexcept
Dean Moldovan4e959c92016-12-08 11:07:52 +0100647 -> decltype(pmf) { return pmf; }
648};
649NAMESPACE_END(detail)
650
651/// Syntax sugar for resolving overloaded function pointers:
652/// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
653/// - sweet: overload_cast<Arg0, Arg1, Arg2>(&Class::func)
654template <typename... Args>
655static constexpr detail::overload_cast_impl<Args...> overload_cast = {};
656// MSVC 2015 only accepts this particular initialization syntax for this variable template.
657
658/// Const member function selector for overload_cast
659/// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
660/// - sweet: overload_cast<Arg>(&Class::func, const_)
661static constexpr auto const_ = std::true_type{};
662
663#endif // overload_cast
664
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200665NAMESPACE_END(pybind11)