blob: e0fa3922374a0d5a45b0e54998ed7f34c698c31d [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 Jakob1ae77fe2016-01-17 22:36:43 +010055#define PYBIND11_VERSION_MAJOR 1
Wenzel Jakobf85c5292016-06-14 15:24:47 +020056#define PYBIND11_VERSION_MINOR 9
Wenzel Jakoba720a602016-07-12 18:02:13 +020057#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)
64# if _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) \
142 extern "C" PYBIND11_EXPORT PyObject *init##name()
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100143#endif
Wenzel Jakob57082212015-09-04 23:42:12 +0200144
Wenzel Jakobfbafdea2016-04-25 15:02:43 +0200145#if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
146extern "C" {
147 struct _Py_atomic_address { void *value; };
148 PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
Ivan Smirnov3ae5bd72016-06-17 22:29:10 +0100149}
Wenzel Jakobfbafdea2016-04-25 15:02:43 +0200150#endif
151
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100152#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
Wenzel Jakob77586fd2016-03-06 13:38:18 +0100153#define PYBIND11_STRINGIFY(x) #x
154#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
155#define PYBIND11_INTERNALS_ID "__pybind11_" \
156 PYBIND11_TOSTRING(PYBIND11_VERSION_MAJOR) "_" PYBIND11_TOSTRING(PYBIND11_VERSION_MINOR) "__"
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100157
Wenzel Jakob4c00fd92016-10-09 19:40:15 +0200158#define PYBIND11_PLUGIN(name) \
159 static PyObject *pybind11_init(); \
160 PYBIND11_PLUGIN_IMPL(name) { \
161 int major, minor; \
162 if (sscanf(Py_GetVersion(), "%i.%i", &major, &minor) != 2) { \
163 PyErr_SetString(PyExc_ImportError, "Can't parse Python version."); \
164 return nullptr; \
165 } else if (major != PY_MAJOR_VERSION || minor != PY_MINOR_VERSION) { \
166 PyErr_Format(PyExc_ImportError, \
167 "Python version mismatch: module was compiled for " \
168 "version %i.%i, while the interpreter is running " \
169 "version %i.%i.", PY_MAJOR_VERSION, PY_MINOR_VERSION, \
170 major, minor); \
171 return nullptr; \
172 } \
173 try { \
174 return pybind11_init(); \
175 } catch (const std::exception &e) { \
176 PyErr_SetString(PyExc_ImportError, e.what()); \
177 return nullptr; \
178 } \
179 } \
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100180 PyObject *pybind11_init()
181
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200182NAMESPACE_BEGIN(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200183
Wenzel Jakob06bd27f2016-11-15 06:37:39 +0100184using ssize_t = Py_ssize_t;
185using size_t = std::size_t;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200186
187/// Approach used to cast a previously unknown C++ instance into a Python object
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100188enum class return_value_policy : uint8_t {
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200189 /** This is the default return value policy, which falls back to the policy
190 return_value_policy::take_ownership when the return value is a pointer.
191 Otherwise, it uses return_value::move or return_value::copy for rvalue
192 and lvalue references, respectively. See below for a description of what
193 all of these different policies do. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200194 automatic = 0,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200195
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200196 /** As above, but use policy return_value_policy::reference when the return
Wenzel Jakob37e1f612016-06-22 14:29:13 +0200197 value is a pointer. This is the default conversion policy for function
198 arguments when calling Python functions manually from C++ code (i.e. via
199 handle::operator()). You probably won't need to use this. */
Wenzel Jakob8bd31c72016-04-14 14:26:13 +0200200 automatic_reference,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200201
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200202 /** Reference an existing object (i.e. do not create a new copy) and take
203 ownership. Python will call the destructor and delete operator when the
204 object’s reference count reaches zero. Undefined behavior ensues when
205 the C++ side does the same.. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200206 take_ownership,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200207
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200208 /** Create a new copy of the returned object, which will be owned by
209 Python. This policy is comparably safe because the lifetimes of the two
210 instances are decoupled. */
211 copy,
212
213 /** Use std::move to move the return value contents into a new instance
214 that will be owned by Python. This policy is comparably safe because the
215 lifetimes of the two instances (move source and destination) are
216 decoupled. */
217 move,
218
219 /** Reference an existing object, but do not take ownership. The C++ side
220 is responsible for managing the object’s lifetime and deallocating it
221 when it is no longer used. Warning: undefined behavior will ensue when
Wenzel Jakobe84f5572016-04-26 23:19:19 +0200222 the C++ side deletes an object that is still referenced and used by
223 Python. */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200224 reference,
Wenzel Jakob7d0162a2016-04-25 03:24:46 +0200225
Wenzel Jakobe84f5572016-04-26 23:19:19 +0200226 /** This policy only applies to methods and properties. It references the
227 object without taking ownership similar to the above
228 return_value_policy::reference policy. In contrast to that policy, the
229 function or property’s implicit this argument (called the parent) is
230 considered to be the the owner of the return value (the child).
231 pybind11 then couples the lifetime of the parent to the child via a
232 reference relationship that ensures that the parent cannot be garbage
233 collected while Python is still using the child. More advanced
234 variations of this scheme are also possible using combinations of
235 return_value_policy::reference and the keep_alive call policy */
Wenzel Jakobf7b58742016-04-25 23:04:27 +0200236 reference_internal
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200237};
238
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200239/// Information record describing a Python buffer object
240struct buffer_info {
Jason Newton3718c382016-09-02 17:10:02 -0400241 void *ptr = nullptr; // Pointer to the underlying storage
242 size_t itemsize = 0; // Size of individual items in bytes
243 size_t size = 0; // Total number of entries
Ivan Smirnov5e71e172016-06-26 12:42:34 +0100244 std::string format; // For homogeneous buffers, this should be set to format_descriptor<T>::format()
Jason Newton3718c382016-09-02 17:10:02 -0400245 size_t ndim = 0; // Number of dimensions
Wenzel Jakobe45b2902016-01-17 22:36:41 +0100246 std::vector<size_t> shape; // Shape of the tensor (1 entry per dimension)
247 std::vector<size_t> strides; // Number of entries between adjacent entries (for each per dimension)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200248
Wenzel Jakobf3be07c2016-09-04 23:03:48 +0900249 buffer_info() { }
Ivan Smirnov98ba98c2016-07-24 20:29:44 +0100250
Wenzel Jakob0a078052016-05-29 13:40:40 +0200251 buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t ndim,
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200252 const std::vector<size_t> &shape, const std::vector<size_t> &strides)
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100253 : ptr(ptr), itemsize(itemsize), size(1), format(format),
254 ndim(ndim), shape(shape), strides(strides) {
Wenzel Jakob0a078052016-05-29 13:40:40 +0200255 for (size_t i = 0; i < ndim; ++i)
256 size *= shape[i];
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200257 }
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100258
Ivan Smirnov98ba98c2016-07-24 20:29:44 +0100259 buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t size)
260 : buffer_info(ptr, itemsize, format, 1, std::vector<size_t> { size },
261 std::vector<size_t> { itemsize }) { }
262
Jason Rhinelander12d76602016-10-16 16:27:42 -0400263 explicit buffer_info(Py_buffer *view, bool ownview = true)
Wenzel Jakob0a078052016-05-29 13:40:40 +0200264 : ptr(view->buf), itemsize((size_t) view->itemsize), size(1), format(view->format),
Jason Newton514c6da2016-09-02 17:10:25 -0400265 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 +0200266 for (size_t i = 0; i < (size_t) view->ndim; ++i) {
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100267 shape[i] = (size_t) view->shape[i];
268 strides[i] = (size_t) view->strides[i];
269 size *= shape[i];
270 }
271 }
272
Jason Newton10d46e72016-09-02 18:39:47 -0400273 buffer_info(const buffer_info &) = delete;
274 buffer_info& operator=(const buffer_info &) = delete;
275
Wenzel Jakobf3be07c2016-09-04 23:03:48 +0900276 buffer_info(buffer_info &&other) {
Jason Newton47646982016-09-02 17:11:30 -0400277 (*this) = std::move(other);
278 }
279
Wenzel Jakobcc4e4062016-09-05 08:25:10 +0900280 buffer_info& operator=(buffer_info &&rhs) {
Jason Newton47646982016-09-02 17:11:30 -0400281 ptr = rhs.ptr;
282 itemsize = rhs.itemsize;
283 size = rhs.size;
284 format = std::move(rhs.format);
285 ndim = rhs.ndim;
286 shape = std::move(rhs.shape);
287 strides = std::move(rhs.strides);
288 std::swap(view, rhs.view);
289 std::swap(ownview, rhs.ownview);
290 return *this;
291 }
292
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100293 ~buffer_info() {
Jason Newton514c6da2016-09-02 17:10:25 -0400294 if (view && ownview) { PyBuffer_Release(view); delete view; }
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100295 }
Ivan Smirnova7e62e12016-06-19 14:37:55 +0100296
Wenzel Jakobd33361a2016-01-17 22:36:40 +0100297private:
298 Py_buffer *view = nullptr;
Jason Newton514c6da2016-09-02 17:10:25 -0400299 bool ownview = false;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200300};
301
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200302NAMESPACE_BEGIN(detail)
303
Wenzel Jakobe6118232016-05-05 21:54:24 +0200304inline 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 +0200305
Wenzel Jakob96c10532015-10-01 16:42:15 +0200306inline std::string error_string();
307
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100308/// Core part of the 'instance' type which POD (needed to be able to use 'offsetof')
309template <typename type> struct instance_essentials {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200310 PyObject_HEAD
311 type *value;
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100312 PyObject *weakrefs;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200313 bool owned : 1;
Jason Rhinelanderc07ec312016-11-06 13:12:48 -0500314 bool holder_constructed : 1;
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100315};
316
317/// PyObject wrapper around generic types, includes a special holder type that is responsible for lifetime management
318template <typename type, typename holder_type = std::unique_ptr<type>> struct instance : instance_essentials<type> {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200319 holder_type holder;
320};
321
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200322struct overload_hash {
Wenzel Jakob06bd27f2016-11-15 06:37:39 +0100323 inline size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200324 size_t value = std::hash<const void *>()(v.first);
325 value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value<<6) + (value>>2);
326 return value;
327 }
328};
329
Wenzel Jakob43398a82015-07-28 16:12:20 +0200330/// Internal data struture used to track registered instances and types
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200331struct internals {
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400332 std::unordered_map<std::type_index, void*> registered_types_cpp; // std::type_index -> type_info
333 std::unordered_map<const void *, void*> registered_types_py; // PyTypeObject* -> type_info
334 std::unordered_multimap<const void *, void*> registered_instances; // void * -> PyObject*
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200335 std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
Ivan Smirnovc275ee62016-10-20 16:09:31 +0100336 std::unordered_map<std::type_index, std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400337 std::forward_list<void (*) (std::exception_ptr)> registered_exception_translators;
Ivan Smirnov2dbf0292016-10-31 14:11:10 +0000338 std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions
Wenzel Jakob39e97e62016-04-25 03:26:15 +0200339#if defined(WITH_THREAD)
Boris Schäling20ee9352016-05-28 12:26:18 +0200340 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 +0200341 PyInterpreterState *istate = nullptr;
342#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200343};
344
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200345/// Return a reference to the current 'internals' information
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200346inline internals &get_internals();
347
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200348/// Index sequence for convenient template metaprogramming involving tuples
349template<size_t ...> struct index_sequence { };
350template<size_t N, size_t ...S> struct make_index_sequence : make_index_sequence <N - 1, N - 1, S...> { };
351template<size_t ...S> struct make_index_sequence <0, S...> { typedef index_sequence<S...> type; };
352
353/// Strip the class from a method type
Wenzel Jakobad696342016-05-03 13:28:40 +0200354template <typename T> struct remove_class { };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200355template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
356template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
357
358/// Helper template to strip away type modifiers
Wenzel Jakob4177ed42016-01-17 22:36:38 +0100359template <typename T> struct intrinsic_type { typedef T type; };
360template <typename T> struct intrinsic_type<const T> { typedef typename intrinsic_type<T>::type type; };
361template <typename T> struct intrinsic_type<T*> { typedef typename intrinsic_type<T>::type type; };
362template <typename T> struct intrinsic_type<T&> { typedef typename intrinsic_type<T>::type type; };
363template <typename T> struct intrinsic_type<T&&> { typedef typename intrinsic_type<T>::type type; };
364template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
365template <typename T, size_t N> struct intrinsic_type<T[N]> { typedef typename intrinsic_type<T>::type type; };
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200366template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200367
368/// Helper type to replace 'void' in some expressions
369struct void_type { };
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200370
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200371/// from __cpp_future__ import (convenient aliases from C++14/17)
372template <bool B> using bool_constant = std::integral_constant<bool, B>;
373template <class T> using negation = bool_constant<!T::value>;
374template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
375template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
376
377/// Compile-time integer sum
378constexpr size_t constexpr_sum() { return 0; }
379template <typename T, typename... Ts>
380constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
381
Jason Rhinelander5aa2cd52016-09-08 17:45:53 -0400382// Counts the number of types in the template parameter pack matching the predicate
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200383#if !defined(_MSC_VER)
384template <template<typename> class Predicate, typename... Ts>
Jason Rhinelander5aa2cd52016-09-08 17:45:53 -0400385using count_t = std::integral_constant<size_t, constexpr_sum(Predicate<Ts>::value...)>;
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200386#else
387// MSVC workaround (2015 Update 3 has issues with some member type aliases and constexpr)
Jason Rhinelander5aa2cd52016-09-08 17:45:53 -0400388template <template<typename> class Predicate, typename... Ts> struct count_t;
389template <template<typename> class Predicate> struct count_t<Predicate> : std::integral_constant<size_t, 0> {};
390template <template<typename> class Predicate, class T, class... Ts>
391struct 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 +0200392#endif
393
Jason Rhinelander5aa2cd52016-09-08 17:45:53 -0400394/// Return true if all/any Ts satify Predicate<T>
395template <template<typename> class Predicate, typename... Ts>
396using all_of_t = bool_constant<(count_t<Predicate, Ts...>::value == sizeof...(Ts))>;
397template <template<typename> class Predicate, typename... Ts>
398using any_of_t = bool_constant<(count_t<Predicate, Ts...>::value > 0)>;
399
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400400// Extracts the first type from the template parameter pack matching the predicate, or Default if none match.
401template <template<class> class Predicate, class Default, class... Ts> struct first_of;
402template <template<class> class Predicate, class Default> struct first_of<Predicate, Default> {
403 using type = Default;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400404};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400405template <template<class> class Predicate, class Default, class T, class... Ts>
406struct first_of<Predicate, Default, T, Ts...> {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400407 using type = typename std::conditional<
408 Predicate<T>::value,
409 T,
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400410 typename first_of<Predicate, Default, Ts...>::type
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400411 >::type;
412};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400413template <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 -0400414
Dean Moldovan56e86ed2016-09-04 21:30:08 +0200415/// Defer the evaluation of type T until types Us are instantiated
416template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
417template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
418
Dean Moldovan71af3b02016-09-24 23:54:02 +0200419template <template<typename...> class Base>
420struct is_template_base_of_impl {
421 template <typename... Us> static std::true_type check(Base<Us...> *);
422 static std::false_type check(...);
423};
424
425/// Check if a template is the base of a type. For example:
426/// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
427template <template<typename...> class Base, typename T>
428#if !defined(_MSC_VER)
429using is_template_base_of = decltype(is_template_base_of_impl<Base>::check((T*)nullptr));
430#else // MSVC2015 has trouble with decltype in template aliases
431struct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((T*)nullptr)) { };
432#endif
433
Dean Moldovan5d28dd12016-10-18 13:56:33 +0200434/// Check if T is std::shared_ptr<U> where U can be anything
435template <typename T> struct is_shared_ptr : std::false_type { };
436template <typename U> struct is_shared_ptr<std::shared_ptr<U>> : std::true_type { };
437
Dean Moldovanc743e1b2016-08-29 03:05:42 +0200438/// Ignore that a variable is unused in compiler warnings
439inline void ignore_unused(const int *) { }
440
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200441NAMESPACE_END(detail)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200442
Ivan Smirnov2dbf0292016-10-31 14:11:10 +0000443/// Returns a named pointer that is shared among all extension modules (using the same
444/// pybind11 version) running in the current interpreter. Names starting with underscores
445/// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
446inline PYBIND11_NOINLINE void* get_shared_data(const std::string& name) {
447 auto& internals = detail::get_internals();
448 auto it = internals.shared_data.find(name);
449 return it != internals.shared_data.end() ? it->second : nullptr;
450}
451
452/// Set the shared data that can be later recovered by `get_shared_data()`.
453inline PYBIND11_NOINLINE void *set_shared_data(const std::string& name, void *data) {
454 detail::get_internals().shared_data[name] = data;
455 return data;
456}
457
458/// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
459/// such entry exists. Otherwise, a new object of default-constructible type `T` is
460/// added to the shared data under the given name and a reference to it is returned.
461template<typename T> T& get_or_create_shared_data(const std::string& name) {
462 auto& internals = detail::get_internals();
463 auto it = internals.shared_data.find(name);
464 T* ptr = (T*) (it != internals.shared_data.end() ? it->second : nullptr);
465 if (!ptr) {
466 ptr = new T();
467 internals.shared_data[name] = ptr;
468 }
469 return *ptr;
470}
471
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200472/// Fetch and hold an error which was already set in Python
473class error_already_set : public std::runtime_error {
474public:
475 error_already_set() : std::runtime_error(detail::error_string()) {
476 PyErr_Fetch(&type, &value, &trace);
477 }
Wenzel Jakobfbec17c2016-11-24 12:30:11 +0100478
479 error_already_set(const error_already_set &) = delete;
480
481 error_already_set(error_already_set &&e)
482 : std::runtime_error(e.what()), type(e.type), value(e.value),
483 trace(e.trace) { e.type = e.value = e.trace = nullptr; }
484
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200485 ~error_already_set() { Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(trace); }
486
487 /// Give the error back to Python
488 void restore() { PyErr_Restore(type, value, trace); type = value = trace = nullptr; }
489
490private:
491 PyObject *type, *value, *trace;
492};
493
Dean Moldovanf69071c2016-09-10 14:43:28 +0200494/// C++ bindings of builtin Python exceptions
495class builtin_exception : public std::runtime_error {
496public:
497 using std::runtime_error::runtime_error;
498 virtual void set_error() const = 0; /// Set the error using the Python C API
499};
500
501#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
502 class name : public builtin_exception { public: \
503 using builtin_exception::builtin_exception; \
504 name() : name("") { } \
505 void set_error() const override { PyErr_SetString(type, what()); } \
Wenzel Jakobad696342016-05-03 13:28:40 +0200506 };
507
Dean Moldovanf69071c2016-09-10 14:43:28 +0200508PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
509PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
510PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
511PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
Wenzel Jakobc49d6e52016-10-13 10:34:52 +0200512PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
Dean Moldovanf69071c2016-09-10 14:43:28 +0200513PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
514PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
515PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200516
Wenzel Jakobfc92d822016-04-30 23:55:44 +0200517[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
518[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
Wenzel Jakob678d7872016-01-17 22:36:41 +0100519
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200520/// Format strings for basic number types
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100521#define PYBIND11_DECL_FMT(t, v) template<> struct format_descriptor<t> \
Ivan Smirnov5e71e172016-06-26 12:42:34 +0100522 { static constexpr const char* value = v; /* for backwards compatibility */ \
Ivan Smirnov03fb4882016-08-14 13:45:49 +0100523 static std::string format() { return value; } }
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100524
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200525template <typename T, typename SFINAE = void> struct format_descriptor { };
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100526
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900527template <typename T> struct format_descriptor<T, detail::enable_if_t<std::is_integral<T>::value>> {
Wenzel Jakobb0c44442016-09-27 11:23:52 +0200528 static constexpr const char c = "bBhHiIqQ"[detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value];
529 static constexpr const char value[2] = { c, '\0' };
530 static std::string format() { return std::string(1, c); }
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200531};
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100532
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200533template <typename T> constexpr const char format_descriptor<
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900534 T, detail::enable_if_t<std::is_integral<T>::value>>::value[2];
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100535
Wenzel Jakob720136b2016-09-10 16:32:17 +0900536/// RAII wrapper that temporarily clears any Python error state
537struct error_scope {
538 PyObject *type, *value, *trace;
539 error_scope() { PyErr_Fetch(&type, &value, &trace); }
540 ~error_scope() { PyErr_Restore(type, value, trace); }
541};
542
Ivan Smirnov42ad3282016-06-19 14:39:41 +0100543PYBIND11_DECL_FMT(float, "f");
544PYBIND11_DECL_FMT(double, "d");
545PYBIND11_DECL_FMT(bool, "?");
Wenzel Jakob876eeab2016-05-04 22:22:48 +0200546
Wenzel Jakob5e4e4772016-08-28 02:03:15 +0200547/// Dummy destructor wrapper that can be used to expose classes with a private destructor
548struct nodelete { template <typename T> void operator()(T*) { } };
Nickolai Belakovski63338252016-08-27 11:57:55 -0700549
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200550NAMESPACE_END(pybind11)