blob: 6f79f91ba503114c4194196bbac91bb143d09e3a [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
Wenzel Jakobb1b71402015-10-18 16:48:30 +020019#if !defined(PYBIND11_EXPORT)
Wenzel Jakob53b26542016-01-17 22:36:43 +010020# if defined(WIN32) || defined(_WIN32)
21# define PYBIND11_EXPORT __declspec(dllexport)
22# else
23# define PYBIND11_EXPORT __attribute__ ((visibility("default")))
24# endif
Wenzel Jakob0fb85282015-10-19 23:50:51 +020025#endif
26
Wenzel Jakob53b26542016-01-17 22:36:43 +010027#if defined(_MSC_VER)
28# define PYBIND11_NOINLINE __declspec(noinline)
29#else
30# define PYBIND11_NOINLINE __attribute__ ((noinline))
31#endif
32
Wenzel Jakobbad589a2016-09-12 12:03:20 +090033#if __cplusplus > 201103L
34# define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
35#elif defined(__clang__)
36# define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
37#elif defined(__GNUG__)
38# define PYBIND11_DEPRECATED(reason) __attribute__((deprecated))
39#elif defined(_MSC_VER)
40# define PYBIND11_DEPRECATED(reason) __declspec(deprecated)
41#endif
42
Wenzel Jakob1ae77fe2016-01-17 22:36:43 +010043#define PYBIND11_VERSION_MAJOR 1
Wenzel Jakobf85c5292016-06-14 15:24:47 +020044#define PYBIND11_VERSION_MINOR 9
Wenzel Jakoba720a602016-07-12 18:02:13 +020045#define PYBIND11_VERSION_PATCH dev0
Wenzel Jakob1ae77fe2016-01-17 22:36:43 +010046
Wenzel Jakob53b26542016-01-17 22:36:43 +010047/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
48#if defined(_MSC_VER)
49# define HAVE_ROUND
50# pragma warning(push)
51# pragma warning(disable: 4510 4610 4512 4005)
52# if _DEBUG
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +020053# define PYBIND11_DEBUG_MARKER
Wenzel Jakob53b26542016-01-17 22:36:43 +010054# undef _DEBUG
55# endif
56#endif
57
58#include <Python.h>
59#include <frameobject.h>
Wenzel Jakob39e97e62016-04-25 03:26:15 +020060#include <pythread.h>
Wenzel Jakob53b26542016-01-17 22:36:43 +010061
Wenzel Jakoba771e362016-07-19 17:47:59 +020062#if defined(_WIN32) && (defined(min) || defined(max))
63# error Macro clash with min and max -- define NOMINMAX when compiling your program on Windows
64#endif
65
66#if defined(isalnum)
Wenzel Jakob53b26542016-01-17 22:36:43 +010067# undef isalnum
68# undef isalpha
69# undef islower
70# undef isspace
71# undef isupper
72# undef tolower
73# undef toupper
74#endif
75
76#if defined(_MSC_VER)
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +020077# if defined(PYBIND11_DEBUG_MARKER)
Wenzel Jakob53b26542016-01-17 22:36:43 +010078# define _DEBUG
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +020079# undef PYBIND11_DEBUG_MARKER
80# endif
Wenzel Jakob53b26542016-01-17 22:36:43 +010081# pragma warning(pop)
82#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +020083
Pim Schellart5a7d17f2016-06-17 17:35:59 -040084#include <forward_list>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020085#include <vector>
86#include <string>
87#include <stdexcept>
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +020088#include <unordered_set>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020089#include <unordered_map>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020090#include <memory>
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +010091#include <typeindex>
Wenzel Jakob8e5dceb2016-09-11 20:00:40 +090092#include <type_traits>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020093
Wenzel Jakob27e8e102016-01-17 22:36:37 +010094#if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
Wenzel Jakob48548ea2016-01-17 22:36:44 +010095#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
Wenzel Jakob27e8e102016-01-17 22:36:37 +010096#define PYBIND11_BYTES_CHECK PyBytes_Check
97#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
98#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
99#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
100#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
Wenzel Jakob5612a0c2016-05-01 00:32:18 +0200101#define PYBIND11_BYTES_CHECK PyBytes_Check
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100102#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
103#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
104#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) PyLong_AsUnsignedLongLong(o)
Wenzel Jakob56e9f492016-01-17 22:36:38 +0100105#define PYBIND11_BYTES_NAME "bytes"
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100106#define PYBIND11_STRING_NAME "str"
107#define PYBIND11_SLICE_OBJECT PyObject
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100108#define PYBIND11_FROM_STRING PyUnicode_FromString
Ivan Smirnov1cdd1712016-08-13 12:39:16 +0100109#define PYBIND11_STR_TYPE ::pybind11::str
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100110#define PYBIND11_OB_TYPE(ht_type) (ht_type).ob_base.ob_base.ob_type
111#define PYBIND11_PLUGIN_IMPL(name) \
112 extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100113#else
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100114#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100115#define PYBIND11_BYTES_CHECK PyString_Check
116#define PYBIND11_BYTES_FROM_STRING PyString_FromString
117#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
118#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
119#define PYBIND11_BYTES_AS_STRING PyString_AsString
Wenzel Jakob5612a0c2016-05-01 00:32:18 +0200120#define PYBIND11_BYTES_CHECK PyString_Check
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100121#define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
122#define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
123#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 +0100124#define PYBIND11_BYTES_NAME "str"
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100125#define PYBIND11_STRING_NAME "unicode"
126#define PYBIND11_SLICE_OBJECT PySliceObject
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100127#define PYBIND11_FROM_STRING PyString_FromString
Ivan Smirnov1cdd1712016-08-13 12:39:16 +0100128#define PYBIND11_STR_TYPE ::pybind11::bytes
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100129#define PYBIND11_OB_TYPE(ht_type) (ht_type).ob_type
130#define PYBIND11_PLUGIN_IMPL(name) \
131 extern "C" PYBIND11_EXPORT PyObject *init##name()
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100132#endif
Wenzel Jakob57082212015-09-04 23:42:12 +0200133
Wenzel Jakobfbafdea2016-04-25 15:02:43 +0200134#if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
135extern "C" {
136 struct _Py_atomic_address { void *value; };
137 PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
Ivan Smirnov3ae5bd72016-06-17 22:29:10 +0100138}
Wenzel Jakobfbafdea2016-04-25 15:02:43 +0200139#endif
140
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100141#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
Wenzel Jakob77586fd2016-03-06 13:38:18 +0100142#define PYBIND11_STRINGIFY(x) #x
143#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
144#define PYBIND11_INTERNALS_ID "__pybind11_" \
145 PYBIND11_TOSTRING(PYBIND11_VERSION_MAJOR) "_" PYBIND11_TOSTRING(PYBIND11_VERSION_MINOR) "__"
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100146
Wenzel Jakob4c00fd92016-10-09 19:40:15 +0200147#define PYBIND11_PLUGIN(name) \
148 static PyObject *pybind11_init(); \
149 PYBIND11_PLUGIN_IMPL(name) { \
150 int major, minor; \
151 if (sscanf(Py_GetVersion(), "%i.%i", &major, &minor) != 2) { \
152 PyErr_SetString(PyExc_ImportError, "Can't parse Python version."); \
153 return nullptr; \
154 } else if (major != PY_MAJOR_VERSION || minor != PY_MINOR_VERSION) { \
155 PyErr_Format(PyExc_ImportError, \
156 "Python version mismatch: module was compiled for " \
157 "version %i.%i, while the interpreter is running " \
158 "version %i.%i.", PY_MAJOR_VERSION, PY_MINOR_VERSION, \
159 major, minor); \
160 return nullptr; \
161 } \
162 try { \
163 return pybind11_init(); \
164 } catch (const std::exception &e) { \
165 PyErr_SetString(PyExc_ImportError, e.what()); \
166 return nullptr; \
167 } \
168 } \
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100169 PyObject *pybind11_init()
170
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200171NAMESPACE_BEGIN(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200172
173typedef Py_ssize_t ssize_t;
174
175/// Approach used to cast a previously unknown C++ instance into a Python object
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100176enum class return_value_policy : uint8_t {
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200177 /** This is the default return value policy, which falls back to the policy
178 return_value_policy::take_ownership when the return value is a pointer.
179 Otherwise, it uses return_value::move or return_value::copy for rvalue
180 and lvalue references, respectively. See below for a description of what
181 all of these different policies do. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200182 automatic = 0,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200183
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200184 /** As above, but use policy return_value_policy::reference when the return
Wenzel Jakob37e1f612016-06-22 14:29:13 +0200185 value is a pointer. This is the default conversion policy for function
186 arguments when calling Python functions manually from C++ code (i.e. via
187 handle::operator()). You probably won't need to use this. */
Wenzel Jakob8bd31c72016-04-14 14:26:13 +0200188 automatic_reference,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200189
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200190 /** Reference an existing object (i.e. do not create a new copy) and take
191 ownership. Python will call the destructor and delete operator when the
192 object’s reference count reaches zero. Undefined behavior ensues when
193 the C++ side does the same.. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200194 take_ownership,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200195
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200196 /** Create a new copy of the returned object, which will be owned by
197 Python. This policy is comparably safe because the lifetimes of the two
198 instances are decoupled. */
199 copy,
200
201 /** Use std::move to move the return value contents into a new instance
202 that will be owned by Python. This policy is comparably safe because the
203 lifetimes of the two instances (move source and destination) are
204 decoupled. */
205 move,
206
207 /** Reference an existing object, but do not take ownership. The C++ side
208 is responsible for managing the object’s lifetime and deallocating it
209 when it is no longer used. Warning: undefined behavior will ensue when
Wenzel Jakobe84f5572016-04-26 23:19:19 +0200210 the C++ side deletes an object that is still referenced and used by
211 Python. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200212 reference,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200213
Wenzel Jakobe84f5572016-04-26 23:19:19 +0200214 /** This policy only applies to methods and properties. It references the
215 object without taking ownership similar to the above
216 return_value_policy::reference policy. In contrast to that policy, the
217 function or property’s implicit this argument (called the parent) is
218 considered to be the the owner of the return value (the child).
219 pybind11 then couples the lifetime of the parent to the child via a
220 reference relationship that ensures that the parent cannot be garbage
221 collected while Python is still using the child. More advanced
222 variations of this scheme are also possible using combinations of
223 return_value_policy::reference and the keep_alive call policy */
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200224 reference_internal
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200225};
226
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200227/// Information record describing a Python buffer object
228struct buffer_info {
Jason Newton3718c382016-09-02 17:10:02 -0400229 void *ptr = nullptr; // Pointer to the underlying storage
230 size_t itemsize = 0; // Size of individual items in bytes
231 size_t size = 0; // Total number of entries
Ivan Smirnov5e71e172016-06-26 12:42:34 +0100232 std::string format; // For homogeneous buffers, this should be set to format_descriptor<T>::format()
Jason Newton3718c382016-09-02 17:10:02 -0400233 size_t ndim = 0; // Number of dimensions
Wenzel Jakobe45b2902016-01-17 22:36:41 +0100234 std::vector<size_t> shape; // Shape of the tensor (1 entry per dimension)
235 std::vector<size_t> strides; // Number of entries between adjacent entries (for each per dimension)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200236
Wenzel Jakobf3be07c2016-09-04 23:03:48 +0900237 buffer_info() { }
Ivan Smirnov98ba98c2016-07-24 20:29:44 +0100238
Wenzel Jakob0a078052016-05-29 13:40:40 +0200239 buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t ndim,
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200240 const std::vector<size_t> &shape, const std::vector<size_t> &strides)
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100241 : ptr(ptr), itemsize(itemsize), size(1), format(format),
242 ndim(ndim), shape(shape), strides(strides) {
Wenzel Jakob0a078052016-05-29 13:40:40 +0200243 for (size_t i = 0; i < ndim; ++i)
244 size *= shape[i];
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200245 }
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100246
Ivan Smirnov98ba98c2016-07-24 20:29:44 +0100247 buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t size)
248 : buffer_info(ptr, itemsize, format, 1, std::vector<size_t> { size },
249 std::vector<size_t> { itemsize }) { }
250
Jason Rhinelander12d76602016-10-16 16:27:42 -0400251 explicit buffer_info(Py_buffer *view, bool ownview = true)
Wenzel Jakob0a078052016-05-29 13:40:40 +0200252 : ptr(view->buf), itemsize((size_t) view->itemsize), size(1), format(view->format),
Jason Newton514c6da2016-09-02 17:10:25 -0400253 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 +0200254 for (size_t i = 0; i < (size_t) view->ndim; ++i) {
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100255 shape[i] = (size_t) view->shape[i];
256 strides[i] = (size_t) view->strides[i];
257 size *= shape[i];
258 }
259 }
260
Jason Newton10d46e72016-09-02 18:39:47 -0400261 buffer_info(const buffer_info &) = delete;
262 buffer_info& operator=(const buffer_info &) = delete;
263
Wenzel Jakobf3be07c2016-09-04 23:03:48 +0900264 buffer_info(buffer_info &&other) {
Jason Newton47646982016-09-02 17:11:30 -0400265 (*this) = std::move(other);
266 }
267
Wenzel Jakobcc4e4062016-09-05 08:25:10 +0900268 buffer_info& operator=(buffer_info &&rhs) {
Jason Newton47646982016-09-02 17:11:30 -0400269 ptr = rhs.ptr;
270 itemsize = rhs.itemsize;
271 size = rhs.size;
272 format = std::move(rhs.format);
273 ndim = rhs.ndim;
274 shape = std::move(rhs.shape);
275 strides = std::move(rhs.strides);
276 std::swap(view, rhs.view);
277 std::swap(ownview, rhs.ownview);
278 return *this;
279 }
280
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100281 ~buffer_info() {
Jason Newton514c6da2016-09-02 17:10:25 -0400282 if (view && ownview) { PyBuffer_Release(view); delete view; }
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100283 }
Ivan Smirnova7e62e12016-06-19 14:37:55 +0100284
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100285private:
286 Py_buffer *view = nullptr;
Jason Newton514c6da2016-09-02 17:10:25 -0400287 bool ownview = false;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200288};
289
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200290NAMESPACE_BEGIN(detail)
291
Wenzel Jakobe6118232016-05-05 21:54:24 +0200292inline 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 +0200293
Wenzel Jakob96c10532015-10-01 16:42:15 +0200294inline std::string error_string();
295
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100296/// Core part of the 'instance' type which POD (needed to be able to use 'offsetof')
297template <typename type> struct instance_essentials {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200298 PyObject_HEAD
299 type *value;
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100300 PyObject *weakrefs;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200301 bool owned : 1;
302 bool constructed : 1;
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100303};
304
305/// PyObject wrapper around generic types, includes a special holder type that is responsible for lifetime management
306template <typename type, typename holder_type = std::unique_ptr<type>> struct instance : instance_essentials<type> {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200307 holder_type holder;
308};
309
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200310struct overload_hash {
311 inline std::size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
312 size_t value = std::hash<const void *>()(v.first);
313 value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value<<6) + (value>>2);
314 return value;
315 }
316};
317
Wenzel Jakob43398a82015-07-28 16:12:20 +0200318/// Internal data struture used to track registered instances and types
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200319struct internals {
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400320 std::unordered_map<std::type_index, void*> registered_types_cpp; // std::type_index -> type_info
321 std::unordered_map<const void *, void*> registered_types_py; // PyTypeObject* -> type_info
322 std::unordered_multimap<const void *, void*> registered_instances; // void * -> PyObject*
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200323 std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400324 std::forward_list<void (*) (std::exception_ptr)> registered_exception_translators;
Wenzel Jakob39e97e62016-04-25 03:26:15 +0200325#if defined(WITH_THREAD)
Boris Schäling20ee9352016-05-28 12:26:18 +0200326 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 +0200327 PyInterpreterState *istate = nullptr;
328#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200329};
330
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200331/// Return a reference to the current 'internals' information
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200332inline internals &get_internals();
333
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200334/// Index sequence for convenient template metaprogramming involving tuples
335template<size_t ...> struct index_sequence { };
336template<size_t N, size_t ...S> struct make_index_sequence : make_index_sequence <N - 1, N - 1, S...> { };
337template<size_t ...S> struct make_index_sequence <0, S...> { typedef index_sequence<S...> type; };
338
339/// Strip the class from a method type
Wenzel Jakobad696342016-05-03 13:28:40 +0200340template <typename T> struct remove_class { };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200341template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
342template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
343
344/// Helper template to strip away type modifiers
Wenzel Jakob4177ed42016-01-17 22:36:38 +0100345template <typename T> struct intrinsic_type { typedef T type; };
346template <typename T> struct intrinsic_type<const T> { typedef typename intrinsic_type<T>::type type; };
347template <typename T> struct intrinsic_type<T*> { typedef typename intrinsic_type<T>::type type; };
348template <typename T> struct intrinsic_type<T&> { typedef typename intrinsic_type<T>::type type; };
349template <typename T> struct intrinsic_type<T&&> { typedef typename intrinsic_type<T>::type type; };
350template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
351template <typename T, size_t N> struct intrinsic_type<T[N]> { typedef typename intrinsic_type<T>::type type; };
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200352template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200353
354/// Helper type to replace 'void' in some expressions
355struct void_type { };
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200356
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200357/// from __cpp_future__ import (convenient aliases from C++14/17)
358template <bool B> using bool_constant = std::integral_constant<bool, B>;
359template <class T> using negation = bool_constant<!T::value>;
360template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
361template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
362
363/// Compile-time integer sum
364constexpr size_t constexpr_sum() { return 0; }
365template <typename T, typename... Ts>
366constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
367
Jason Rhinelander5aa2cd52016-09-08 17:45:53 -0400368// Counts the number of types in the template parameter pack matching the predicate
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200369#if !defined(_MSC_VER)
370template <template<typename> class Predicate, typename... Ts>
Jason Rhinelander5aa2cd52016-09-08 17:45:53 -0400371using count_t = std::integral_constant<size_t, constexpr_sum(Predicate<Ts>::value...)>;
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200372#else
373// MSVC workaround (2015 Update 3 has issues with some member type aliases and constexpr)
Jason Rhinelander5aa2cd52016-09-08 17:45:53 -0400374template <template<typename> class Predicate, typename... Ts> struct count_t;
375template <template<typename> class Predicate> struct count_t<Predicate> : std::integral_constant<size_t, 0> {};
376template <template<typename> class Predicate, class T, class... Ts>
377struct count_t<Predicate, T, Ts...> : std::integral_constant<size_t, Predicate<T>::value + count_t<Predicate, Ts...>::value> {};
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200378#endif
379
Jason Rhinelander5aa2cd52016-09-08 17:45:53 -0400380/// Return true if all/any Ts satify Predicate<T>
381template <template<typename> class Predicate, typename... Ts>
382using all_of_t = bool_constant<(count_t<Predicate, Ts...>::value == sizeof...(Ts))>;
383template <template<typename> class Predicate, typename... Ts>
384using any_of_t = bool_constant<(count_t<Predicate, Ts...>::value > 0)>;
385
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400386// Extracts the first type from the template parameter pack matching the predicate, or Default if none match.
387template <template<class> class Predicate, class Default, class... Ts> struct first_of;
388template <template<class> class Predicate, class Default> struct first_of<Predicate, Default> {
389 using type = Default;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400390};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400391template <template<class> class Predicate, class Default, class T, class... Ts>
392struct first_of<Predicate, Default, T, Ts...> {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400393 using type = typename std::conditional<
394 Predicate<T>::value,
395 T,
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400396 typename first_of<Predicate, Default, Ts...>::type
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400397 >::type;
398};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400399template <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 -0400400
Dean Moldovan56e86ed2016-09-04 21:30:08 +0200401/// Defer the evaluation of type T until types Us are instantiated
402template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
403template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
404
Dean Moldovan71af3b02016-09-24 23:54:02 +0200405template <template<typename...> class Base>
406struct is_template_base_of_impl {
407 template <typename... Us> static std::true_type check(Base<Us...> *);
408 static std::false_type check(...);
409};
410
411/// Check if a template is the base of a type. For example:
412/// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
413template <template<typename...> class Base, typename T>
414#if !defined(_MSC_VER)
415using is_template_base_of = decltype(is_template_base_of_impl<Base>::check((T*)nullptr));
416#else // MSVC2015 has trouble with decltype in template aliases
417struct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((T*)nullptr)) { };
418#endif
419
Dean Moldovan5d28dd12016-10-18 13:56:33 +0200420/// Check if T is std::shared_ptr<U> where U can be anything
421template <typename T> struct is_shared_ptr : std::false_type { };
422template <typename U> struct is_shared_ptr<std::shared_ptr<U>> : std::true_type { };
423
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200424/// Ignore that a variable is unused in compiler warnings
425inline void ignore_unused(const int *) { }
426
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200427NAMESPACE_END(detail)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200428
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200429/// Fetch and hold an error which was already set in Python
430class error_already_set : public std::runtime_error {
431public:
432 error_already_set() : std::runtime_error(detail::error_string()) {
433 PyErr_Fetch(&type, &value, &trace);
434 }
435 ~error_already_set() { Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(trace); }
436
437 /// Give the error back to Python
438 void restore() { PyErr_Restore(type, value, trace); type = value = trace = nullptr; }
439
440private:
441 PyObject *type, *value, *trace;
442};
443
Dean Moldovanf69071c2016-09-10 14:43:28 +0200444/// C++ bindings of builtin Python exceptions
445class builtin_exception : public std::runtime_error {
446public:
447 using std::runtime_error::runtime_error;
448 virtual void set_error() const = 0; /// Set the error using the Python C API
449};
450
451#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
452 class name : public builtin_exception { public: \
453 using builtin_exception::builtin_exception; \
454 name() : name("") { } \
455 void set_error() const override { PyErr_SetString(type, what()); } \
Wenzel Jakobad696342016-05-03 13:28:40 +0200456 };
457
Dean Moldovanf69071c2016-09-10 14:43:28 +0200458PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
459PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
460PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
461PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
Wenzel Jakobc49d6e52016-10-13 10:34:52 +0200462PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
Dean Moldovanf69071c2016-09-10 14:43:28 +0200463PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
464PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
465PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200466
Wenzel Jakobfc92d822016-04-30 23:55:44 +0200467[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
468[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
Wenzel Jakob678d7872016-01-17 22:36:41 +0100469
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200470/// Format strings for basic number types
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100471#define PYBIND11_DECL_FMT(t, v) template<> struct format_descriptor<t> \
Ivan Smirnov5e71e172016-06-26 12:42:34 +0100472 { static constexpr const char* value = v; /* for backwards compatibility */ \
Ivan Smirnov03fb4882016-08-14 13:45:49 +0100473 static std::string format() { return value; } }
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100474
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200475template <typename T, typename SFINAE = void> struct format_descriptor { };
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100476
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900477template <typename T> struct format_descriptor<T, detail::enable_if_t<std::is_integral<T>::value>> {
Wenzel Jakobb0c44442016-09-27 11:23:52 +0200478 static constexpr const char c = "bBhHiIqQ"[detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value];
479 static constexpr const char value[2] = { c, '\0' };
480 static std::string format() { return std::string(1, c); }
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200481};
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100482
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200483template <typename T> constexpr const char format_descriptor<
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900484 T, detail::enable_if_t<std::is_integral<T>::value>>::value[2];
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100485
Wenzel Jakob720136b2016-09-10 16:32:17 +0900486/// RAII wrapper that temporarily clears any Python error state
487struct error_scope {
488 PyObject *type, *value, *trace;
489 error_scope() { PyErr_Fetch(&type, &value, &trace); }
490 ~error_scope() { PyErr_Restore(type, value, trace); }
491};
492
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100493PYBIND11_DECL_FMT(float, "f");
494PYBIND11_DECL_FMT(double, "d");
495PYBIND11_DECL_FMT(bool, "?");
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200496
Wenzel Jakob5e4e4772016-08-28 02:03:15 +0200497/// Dummy destructor wrapper that can be used to expose classes with a private destructor
498struct nodelete { template <typename T> void operator()(T*) { } };
Nickolai Belakovski63338252016-08-27 11:57:55 -0700499
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200500NAMESPACE_END(pybind11)