blob: fd65fe7628da531df77ba38c9752a28c75c03c83 [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 Jakob1ae77fe2016-01-17 22:36:43 +010033#define PYBIND11_VERSION_MAJOR 1
Wenzel Jakobf85c5292016-06-14 15:24:47 +020034#define PYBIND11_VERSION_MINOR 9
Wenzel Jakoba720a602016-07-12 18:02:13 +020035#define PYBIND11_VERSION_PATCH dev0
Wenzel Jakob1ae77fe2016-01-17 22:36:43 +010036
Wenzel Jakob53b26542016-01-17 22:36:43 +010037/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
38#if defined(_MSC_VER)
39# define HAVE_ROUND
40# pragma warning(push)
41# pragma warning(disable: 4510 4610 4512 4005)
42# if _DEBUG
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +020043# define PYBIND11_DEBUG_MARKER
Wenzel Jakob53b26542016-01-17 22:36:43 +010044# undef _DEBUG
45# endif
46#endif
47
48#include <Python.h>
49#include <frameobject.h>
Wenzel Jakob39e97e62016-04-25 03:26:15 +020050#include <pythread.h>
Wenzel Jakob53b26542016-01-17 22:36:43 +010051
Wenzel Jakoba771e362016-07-19 17:47:59 +020052#if defined(_WIN32) && (defined(min) || defined(max))
53# error Macro clash with min and max -- define NOMINMAX when compiling your program on Windows
54#endif
55
56#if defined(isalnum)
Wenzel Jakob53b26542016-01-17 22:36:43 +010057# undef isalnum
58# undef isalpha
59# undef islower
60# undef isspace
61# undef isupper
62# undef tolower
63# undef toupper
64#endif
65
66#if defined(_MSC_VER)
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +020067# if defined(PYBIND11_DEBUG_MARKER)
Wenzel Jakob53b26542016-01-17 22:36:43 +010068# define _DEBUG
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +020069# undef PYBIND11_DEBUG_MARKER
70# endif
Wenzel Jakob53b26542016-01-17 22:36:43 +010071# pragma warning(pop)
72#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +020073
Pim Schellart5a7d17f2016-06-17 17:35:59 -040074#include <forward_list>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020075#include <vector>
76#include <string>
77#include <stdexcept>
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +020078#include <unordered_set>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020079#include <unordered_map>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020080#include <memory>
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +010081#include <typeindex>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020082
Wenzel Jakob27e8e102016-01-17 22:36:37 +010083#if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
Wenzel Jakob48548ea2016-01-17 22:36:44 +010084#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
Wenzel Jakob27e8e102016-01-17 22:36:37 +010085#define PYBIND11_BYTES_CHECK PyBytes_Check
86#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
87#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
88#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
89#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
Wenzel Jakob5612a0c2016-05-01 00:32:18 +020090#define PYBIND11_BYTES_CHECK PyBytes_Check
Wenzel Jakob27e8e102016-01-17 22:36:37 +010091#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
92#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
93#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) PyLong_AsUnsignedLongLong(o)
Wenzel Jakob56e9f492016-01-17 22:36:38 +010094#define PYBIND11_BYTES_NAME "bytes"
Wenzel Jakob27e8e102016-01-17 22:36:37 +010095#define PYBIND11_STRING_NAME "str"
96#define PYBIND11_SLICE_OBJECT PyObject
Wenzel Jakobd561cb02016-01-17 22:36:41 +010097#define PYBIND11_FROM_STRING PyUnicode_FromString
Ivan Smirnov1cdd1712016-08-13 12:39:16 +010098#define PYBIND11_STR_TYPE ::pybind11::str
Wenzel Jakobd561cb02016-01-17 22:36:41 +010099#define PYBIND11_OB_TYPE(ht_type) (ht_type).ob_base.ob_base.ob_type
100#define PYBIND11_PLUGIN_IMPL(name) \
101 extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100102#else
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100103#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100104#define PYBIND11_BYTES_CHECK PyString_Check
105#define PYBIND11_BYTES_FROM_STRING PyString_FromString
106#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
107#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
108#define PYBIND11_BYTES_AS_STRING PyString_AsString
Wenzel Jakob5612a0c2016-05-01 00:32:18 +0200109#define PYBIND11_BYTES_CHECK PyString_Check
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100110#define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
111#define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
112#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 +0100113#define PYBIND11_BYTES_NAME "str"
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100114#define PYBIND11_STRING_NAME "unicode"
115#define PYBIND11_SLICE_OBJECT PySliceObject
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100116#define PYBIND11_FROM_STRING PyString_FromString
Ivan Smirnov1cdd1712016-08-13 12:39:16 +0100117#define PYBIND11_STR_TYPE ::pybind11::bytes
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100118#define PYBIND11_OB_TYPE(ht_type) (ht_type).ob_type
119#define PYBIND11_PLUGIN_IMPL(name) \
120 extern "C" PYBIND11_EXPORT PyObject *init##name()
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100121#endif
Wenzel Jakob57082212015-09-04 23:42:12 +0200122
Wenzel Jakobfbafdea2016-04-25 15:02:43 +0200123#if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
124extern "C" {
125 struct _Py_atomic_address { void *value; };
126 PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
Ivan Smirnov3ae5bd72016-06-17 22:29:10 +0100127}
Wenzel Jakobfbafdea2016-04-25 15:02:43 +0200128#endif
129
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100130#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
Wenzel Jakob77586fd2016-03-06 13:38:18 +0100131#define PYBIND11_STRINGIFY(x) #x
132#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
133#define PYBIND11_INTERNALS_ID "__pybind11_" \
134 PYBIND11_TOSTRING(PYBIND11_VERSION_MAJOR) "_" PYBIND11_TOSTRING(PYBIND11_VERSION_MINOR) "__"
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100135
136#define PYBIND11_PLUGIN(name) \
137 static PyObject *pybind11_init(); \
138 PYBIND11_PLUGIN_IMPL(name) { \
139 try { \
140 return pybind11_init(); \
141 } catch (const std::exception &e) { \
142 PyErr_SetString(PyExc_ImportError, e.what()); \
143 return nullptr; \
144 } \
145 } \
146 PyObject *pybind11_init()
147
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200148NAMESPACE_BEGIN(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200149
150typedef Py_ssize_t ssize_t;
151
152/// Approach used to cast a previously unknown C++ instance into a Python object
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100153enum class return_value_policy : uint8_t {
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200154 /** This is the default return value policy, which falls back to the policy
155 return_value_policy::take_ownership when the return value is a pointer.
156 Otherwise, it uses return_value::move or return_value::copy for rvalue
157 and lvalue references, respectively. See below for a description of what
158 all of these different policies do. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200159 automatic = 0,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200160
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200161 /** As above, but use policy return_value_policy::reference when the return
Wenzel Jakob37e1f612016-06-22 14:29:13 +0200162 value is a pointer. This is the default conversion policy for function
163 arguments when calling Python functions manually from C++ code (i.e. via
164 handle::operator()). You probably won't need to use this. */
Wenzel Jakob8bd31c72016-04-14 14:26:13 +0200165 automatic_reference,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200166
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200167 /** Reference an existing object (i.e. do not create a new copy) and take
168 ownership. Python will call the destructor and delete operator when the
169 object’s reference count reaches zero. Undefined behavior ensues when
170 the C++ side does the same.. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200171 take_ownership,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200172
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200173 /** Create a new copy of the returned object, which will be owned by
174 Python. This policy is comparably safe because the lifetimes of the two
175 instances are decoupled. */
176 copy,
177
178 /** Use std::move to move the return value contents into a new instance
179 that will be owned by Python. This policy is comparably safe because the
180 lifetimes of the two instances (move source and destination) are
181 decoupled. */
182 move,
183
184 /** Reference an existing object, but do not take ownership. The C++ side
185 is responsible for managing the object’s lifetime and deallocating it
186 when it is no longer used. Warning: undefined behavior will ensue when
Wenzel Jakobe84f5572016-04-26 23:19:19 +0200187 the C++ side deletes an object that is still referenced and used by
188 Python. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200189 reference,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200190
Wenzel Jakobe84f5572016-04-26 23:19:19 +0200191 /** This policy only applies to methods and properties. It references the
192 object without taking ownership similar to the above
193 return_value_policy::reference policy. In contrast to that policy, the
194 function or property’s implicit this argument (called the parent) is
195 considered to be the the owner of the return value (the child).
196 pybind11 then couples the lifetime of the parent to the child via a
197 reference relationship that ensures that the parent cannot be garbage
198 collected while Python is still using the child. More advanced
199 variations of this scheme are also possible using combinations of
200 return_value_policy::reference and the keep_alive call policy */
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200201 reference_internal
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200202};
203
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200204/// Information record describing a Python buffer object
205struct buffer_info {
Jason Newton3718c382016-09-02 17:10:02 -0400206 void *ptr = nullptr; // Pointer to the underlying storage
207 size_t itemsize = 0; // Size of individual items in bytes
208 size_t size = 0; // Total number of entries
Ivan Smirnov5e71e172016-06-26 12:42:34 +0100209 std::string format; // For homogeneous buffers, this should be set to format_descriptor<T>::format()
Jason Newton3718c382016-09-02 17:10:02 -0400210 size_t ndim = 0; // Number of dimensions
Wenzel Jakobe45b2902016-01-17 22:36:41 +0100211 std::vector<size_t> shape; // Shape of the tensor (1 entry per dimension)
212 std::vector<size_t> strides; // Number of entries between adjacent entries (for each per dimension)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200213
Wenzel Jakobf3be07c2016-09-04 23:03:48 +0900214 buffer_info() { }
Ivan Smirnov98ba98c2016-07-24 20:29:44 +0100215
Wenzel Jakob0a078052016-05-29 13:40:40 +0200216 buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t ndim,
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200217 const std::vector<size_t> &shape, const std::vector<size_t> &strides)
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100218 : ptr(ptr), itemsize(itemsize), size(1), format(format),
219 ndim(ndim), shape(shape), strides(strides) {
Wenzel Jakob0a078052016-05-29 13:40:40 +0200220 for (size_t i = 0; i < ndim; ++i)
221 size *= shape[i];
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200222 }
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100223
Ivan Smirnov98ba98c2016-07-24 20:29:44 +0100224 buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t size)
225 : buffer_info(ptr, itemsize, format, 1, std::vector<size_t> { size },
226 std::vector<size_t> { itemsize }) { }
227
Jason Newton514c6da2016-09-02 17:10:25 -0400228 buffer_info(Py_buffer *view, bool ownview = true)
Wenzel Jakob0a078052016-05-29 13:40:40 +0200229 : ptr(view->buf), itemsize((size_t) view->itemsize), size(1), format(view->format),
Jason Newton514c6da2016-09-02 17:10:25 -0400230 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 +0200231 for (size_t i = 0; i < (size_t) view->ndim; ++i) {
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100232 shape[i] = (size_t) view->shape[i];
233 strides[i] = (size_t) view->strides[i];
234 size *= shape[i];
235 }
236 }
237
Jason Newton10d46e72016-09-02 18:39:47 -0400238 buffer_info(const buffer_info &) = delete;
239 buffer_info& operator=(const buffer_info &) = delete;
240
Wenzel Jakobf3be07c2016-09-04 23:03:48 +0900241 buffer_info(buffer_info &&other) {
Jason Newton47646982016-09-02 17:11:30 -0400242 (*this) = std::move(other);
243 }
244
Wenzel Jakobcc4e4062016-09-05 08:25:10 +0900245 buffer_info& operator=(buffer_info &&rhs) {
Jason Newton47646982016-09-02 17:11:30 -0400246 ptr = rhs.ptr;
247 itemsize = rhs.itemsize;
248 size = rhs.size;
249 format = std::move(rhs.format);
250 ndim = rhs.ndim;
251 shape = std::move(rhs.shape);
252 strides = std::move(rhs.strides);
253 std::swap(view, rhs.view);
254 std::swap(ownview, rhs.ownview);
255 return *this;
256 }
257
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100258 ~buffer_info() {
Jason Newton514c6da2016-09-02 17:10:25 -0400259 if (view && ownview) { PyBuffer_Release(view); delete view; }
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100260 }
Ivan Smirnova7e62e12016-06-19 14:37:55 +0100261
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100262private:
263 Py_buffer *view = nullptr;
Jason Newton514c6da2016-09-02 17:10:25 -0400264 bool ownview = false;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200265};
266
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200267NAMESPACE_BEGIN(detail)
268
Wenzel Jakobe6118232016-05-05 21:54:24 +0200269inline 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 +0200270
Wenzel Jakob96c10532015-10-01 16:42:15 +0200271inline std::string error_string();
272
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100273/// Core part of the 'instance' type which POD (needed to be able to use 'offsetof')
274template <typename type> struct instance_essentials {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200275 PyObject_HEAD
276 type *value;
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100277 PyObject *weakrefs;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200278 bool owned : 1;
279 bool constructed : 1;
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100280};
281
282/// PyObject wrapper around generic types, includes a special holder type that is responsible for lifetime management
283template <typename type, typename holder_type = std::unique_ptr<type>> struct instance : instance_essentials<type> {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200284 holder_type holder;
285};
286
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200287struct overload_hash {
288 inline std::size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
289 size_t value = std::hash<const void *>()(v.first);
290 value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value<<6) + (value>>2);
291 return value;
292 }
293};
294
Wenzel Jakob43398a82015-07-28 16:12:20 +0200295/// Internal data struture used to track registered instances and types
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200296struct internals {
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400297 std::unordered_map<std::type_index, void*> registered_types_cpp; // std::type_index -> type_info
298 std::unordered_map<const void *, void*> registered_types_py; // PyTypeObject* -> type_info
299 std::unordered_multimap<const void *, void*> registered_instances; // void * -> PyObject*
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200300 std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400301 std::forward_list<void (*) (std::exception_ptr)> registered_exception_translators;
Wenzel Jakob39e97e62016-04-25 03:26:15 +0200302#if defined(WITH_THREAD)
Boris Schäling20ee9352016-05-28 12:26:18 +0200303 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 +0200304 PyInterpreterState *istate = nullptr;
305#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200306};
307
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200308/// Return a reference to the current 'internals' information
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200309inline internals &get_internals();
310
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200311/// Index sequence for convenient template metaprogramming involving tuples
312template<size_t ...> struct index_sequence { };
313template<size_t N, size_t ...S> struct make_index_sequence : make_index_sequence <N - 1, N - 1, S...> { };
314template<size_t ...S> struct make_index_sequence <0, S...> { typedef index_sequence<S...> type; };
315
316/// Strip the class from a method type
Wenzel Jakobad696342016-05-03 13:28:40 +0200317template <typename T> struct remove_class { };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200318template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
319template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
320
321/// Helper template to strip away type modifiers
Wenzel Jakob4177ed42016-01-17 22:36:38 +0100322template <typename T> struct intrinsic_type { typedef T type; };
323template <typename T> struct intrinsic_type<const T> { typedef typename intrinsic_type<T>::type type; };
324template <typename T> struct intrinsic_type<T*> { typedef typename intrinsic_type<T>::type type; };
325template <typename T> struct intrinsic_type<T&> { typedef typename intrinsic_type<T>::type type; };
326template <typename T> struct intrinsic_type<T&&> { typedef typename intrinsic_type<T>::type type; };
327template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
328template <typename T, size_t N> struct intrinsic_type<T[N]> { typedef typename intrinsic_type<T>::type type; };
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200329template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200330
331/// Helper type to replace 'void' in some expressions
332struct void_type { };
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200333
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200334/// from __cpp_future__ import (convenient aliases from C++14/17)
335template <bool B> using bool_constant = std::integral_constant<bool, B>;
336template <class T> using negation = bool_constant<!T::value>;
337template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
338template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
339
340/// Compile-time integer sum
341constexpr size_t constexpr_sum() { return 0; }
342template <typename T, typename... Ts>
343constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
344
Jason Rhinelander5aa2cd52016-09-08 17:45:53 -0400345// Counts the number of types in the template parameter pack matching the predicate
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200346#if !defined(_MSC_VER)
347template <template<typename> class Predicate, typename... Ts>
Jason Rhinelander5aa2cd52016-09-08 17:45:53 -0400348using count_t = std::integral_constant<size_t, constexpr_sum(Predicate<Ts>::value...)>;
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200349#else
350// MSVC workaround (2015 Update 3 has issues with some member type aliases and constexpr)
Jason Rhinelander5aa2cd52016-09-08 17:45:53 -0400351template <template<typename> class Predicate, typename... Ts> struct count_t;
352template <template<typename> class Predicate> struct count_t<Predicate> : std::integral_constant<size_t, 0> {};
353template <template<typename> class Predicate, class T, class... Ts>
354struct 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 +0200355#endif
356
Jason Rhinelander5aa2cd52016-09-08 17:45:53 -0400357/// Return true if all/any Ts satify Predicate<T>
358template <template<typename> class Predicate, typename... Ts>
359using all_of_t = bool_constant<(count_t<Predicate, Ts...>::value == sizeof...(Ts))>;
360template <template<typename> class Predicate, typename... Ts>
361using any_of_t = bool_constant<(count_t<Predicate, Ts...>::value > 0)>;
362
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400363// Extracts the first type from the template parameter pack matching the predicate, or Default if none match.
364template <template<class> class Predicate, class Default, class... Ts> struct first_of;
365template <template<class> class Predicate, class Default> struct first_of<Predicate, Default> {
366 using type = Default;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400367};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400368template <template<class> class Predicate, class Default, class T, class... Ts>
369struct first_of<Predicate, Default, T, Ts...> {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400370 using type = typename std::conditional<
371 Predicate<T>::value,
372 T,
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400373 typename first_of<Predicate, Default, Ts...>::type
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400374 >::type;
375};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400376template <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 -0400377
Dean Moldovan56e86ed2016-09-04 21:30:08 +0200378/// Defer the evaluation of type T until types Us are instantiated
379template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
380template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
381
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200382/// Ignore that a variable is unused in compiler warnings
383inline void ignore_unused(const int *) { }
384
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200385NAMESPACE_END(detail)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200386
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200387/// Fetch and hold an error which was already set in Python
388class error_already_set : public std::runtime_error {
389public:
390 error_already_set() : std::runtime_error(detail::error_string()) {
391 PyErr_Fetch(&type, &value, &trace);
392 }
393 ~error_already_set() { Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(trace); }
394
395 /// Give the error back to Python
396 void restore() { PyErr_Restore(type, value, trace); type = value = trace = nullptr; }
397
398private:
399 PyObject *type, *value, *trace;
400};
401
Dean Moldovanf69071c2016-09-10 14:43:28 +0200402/// C++ bindings of builtin Python exceptions
403class builtin_exception : public std::runtime_error {
404public:
405 using std::runtime_error::runtime_error;
406 virtual void set_error() const = 0; /// Set the error using the Python C API
407};
408
409#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
410 class name : public builtin_exception { public: \
411 using builtin_exception::builtin_exception; \
412 name() : name("") { } \
413 void set_error() const override { PyErr_SetString(type, what()); } \
Wenzel Jakobad696342016-05-03 13:28:40 +0200414 };
415
Dean Moldovanf69071c2016-09-10 14:43:28 +0200416PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
417PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
418PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
419PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
420PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
421PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
422PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200423
Wenzel Jakobfc92d822016-04-30 23:55:44 +0200424[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
425[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
Wenzel Jakob678d7872016-01-17 22:36:41 +0100426
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200427/// Format strings for basic number types
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100428#define PYBIND11_DECL_FMT(t, v) template<> struct format_descriptor<t> \
Ivan Smirnov5e71e172016-06-26 12:42:34 +0100429 { static constexpr const char* value = v; /* for backwards compatibility */ \
Ivan Smirnov03fb4882016-08-14 13:45:49 +0100430 static std::string format() { return value; } }
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100431
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200432template <typename T, typename SFINAE = void> struct format_descriptor { };
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100433
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200434template <typename T> struct format_descriptor<T, typename std::enable_if<std::is_integral<T>::value>::type> {
Ivan Smirnov5e71e172016-06-26 12:42:34 +0100435 static constexpr const char value[2] =
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200436 { "bBhHiIqQ"[detail::log2(sizeof(T))*2 + (std::is_unsigned<T>::value ? 1 : 0)], '\0' };
Ivan Smirnov03fb4882016-08-14 13:45:49 +0100437 static std::string format() { return value; }
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200438};
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100439
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200440template <typename T> constexpr const char format_descriptor<
Ivan Smirnov5e71e172016-06-26 12:42:34 +0100441 T, typename std::enable_if<std::is_integral<T>::value>::type>::value[2];
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100442
Wenzel Jakob720136b2016-09-10 16:32:17 +0900443/// RAII wrapper that temporarily clears any Python error state
444struct error_scope {
445 PyObject *type, *value, *trace;
446 error_scope() { PyErr_Fetch(&type, &value, &trace); }
447 ~error_scope() { PyErr_Restore(type, value, trace); }
448};
449
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100450PYBIND11_DECL_FMT(float, "f");
451PYBIND11_DECL_FMT(double, "d");
452PYBIND11_DECL_FMT(bool, "?");
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200453
Wenzel Jakob5e4e4772016-08-28 02:03:15 +0200454/// Dummy destructor wrapper that can be used to expose classes with a private destructor
455struct nodelete { template <typename T> void operator()(T*) { } };
Nickolai Belakovski63338252016-08-27 11:57:55 -0700456
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200457NAMESPACE_END(pybind11)