common.h 28.9 KB
Newer Older
Wenzel Jakob's avatar
Wenzel Jakob committed
1
/*
2
    pybind11/common.h -- Basic macros
Wenzel Jakob's avatar
Wenzel Jakob committed
3

4
    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakob's avatar
Wenzel Jakob committed
5
6
7
8
9

    All rights reserved. Use of this source code is governed by a
    BSD-style license that can be found in the LICENSE file.
*/

10
#pragma once
Wenzel Jakob's avatar
Wenzel Jakob committed
11
12

#if !defined(NAMESPACE_BEGIN)
13
#  define NAMESPACE_BEGIN(name) namespace name {
Wenzel Jakob's avatar
Wenzel Jakob committed
14
15
#endif
#if !defined(NAMESPACE_END)
16
#  define NAMESPACE_END(name) }
Wenzel Jakob's avatar
Wenzel Jakob committed
17
18
#endif

19
20
21
22
23
24
25
26
27
28
29
30
// Neither MSVC nor Intel support enough of C++14 yet (in particular, as of MSVC 2015 and ICC 17
// beta, neither support extended constexpr, which we rely on in descr.h), so don't enable pybind
// CPP14 features for them.
#if !defined(_MSC_VER) && !defined(__INTEL_COMPILER)
#  if __cplusplus >= 201402L
#    define PYBIND11_CPP14
#    if __cplusplus > 201402L /* Temporary: should be updated to >= the final C++17 value once known */
#      define PYBIND11_CPP17
#    endif
#  endif
#endif

31
#if !defined(PYBIND11_EXPORT)
32
33
34
35
36
#  if defined(WIN32) || defined(_WIN32)
#    define PYBIND11_EXPORT __declspec(dllexport)
#  else
#    define PYBIND11_EXPORT __attribute__ ((visibility("default")))
#  endif
Wenzel Jakob's avatar
Wenzel Jakob committed
37
#endif
38

39
#if defined(_MSC_VER)
40
#  define PYBIND11_NOINLINE __declspec(noinline)
41
#else
42
#  define PYBIND11_NOINLINE __attribute__ ((noinline))
43
44
#endif

45
#if defined(PYBIND11_CPP14)
46
47
48
49
50
51
52
53
54
#  define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
#elif defined(__clang__)
#  define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
#elif defined(__GNUG__)
#  define PYBIND11_DEPRECATED(reason) __attribute__((deprecated))
#elif defined(_MSC_VER)
#  define PYBIND11_DEPRECATED(reason) __declspec(deprecated)
#endif

Wenzel Jakob's avatar
Wenzel Jakob committed
55
#define PYBIND11_VERSION_MAJOR 2
Wenzel Jakob's avatar
Wenzel Jakob committed
56
57
#define PYBIND11_VERSION_MINOR 1
#define PYBIND11_VERSION_PATCH dev0
58

Wenzel Jakob's avatar
Wenzel Jakob committed
59
60
/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
#if defined(_MSC_VER)
61
62
63
#  define HAVE_ROUND
#  pragma warning(push)
#  pragma warning(disable: 4510 4610 4512 4005)
Matthias Möller's avatar
Matthias Möller committed
64
#  if defined(_DEBUG)
65
#    define PYBIND11_DEBUG_MARKER
66
67
#    undef _DEBUG
#  endif
Wenzel Jakob's avatar
Wenzel Jakob committed
68
#endif
69

Wenzel Jakob's avatar
Wenzel Jakob committed
70
#include <Python.h>
71
#include <frameobject.h>
72
#include <pythread.h>
73

74
75
76
77
78
#if defined(_WIN32) && (defined(min) || defined(max))
#  error Macro clash with min and max -- define NOMINMAX when compiling your program on Windows
#endif

#if defined(isalnum)
79
80
81
82
83
84
85
#  undef isalnum
#  undef isalpha
#  undef islower
#  undef isspace
#  undef isupper
#  undef tolower
#  undef toupper
86
#endif
87

Wenzel Jakob's avatar
Wenzel Jakob committed
88
#if defined(_MSC_VER)
89
#  if defined(PYBIND11_DEBUG_MARKER)
90
#    define _DEBUG
91
92
#    undef PYBIND11_DEBUG_MARKER
#  endif
93
#  pragma warning(pop)
Wenzel Jakob's avatar
Wenzel Jakob committed
94
95
#endif

96
#include <cstddef>
97
#include <forward_list>
98
99
100
101
102
103
#include <vector>
#include <string>
#include <stdexcept>
#include <unordered_set>
#include <unordered_map>
#include <memory>
104
#include <typeindex>
Wenzel Jakob's avatar
Wenzel Jakob committed
105
#include <type_traits>
106

107
#if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
Wenzel Jakob's avatar
Wenzel Jakob committed
108
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
109
110
111
112
113
114
115
116
#define PYBIND11_BYTES_CHECK PyBytes_Check
#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) PyLong_AsUnsignedLongLong(o)
117
#define PYBIND11_BYTES_NAME "bytes"
118
119
#define PYBIND11_STRING_NAME "str"
#define PYBIND11_SLICE_OBJECT PyObject
120
#define PYBIND11_FROM_STRING PyUnicode_FromString
121
#define PYBIND11_STR_TYPE ::pybind11::str
122
123
124
#define PYBIND11_OB_TYPE(ht_type) (ht_type).ob_base.ob_base.ob_type
#define PYBIND11_PLUGIN_IMPL(name) \
    extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
125
#else
Wenzel Jakob's avatar
Wenzel Jakob committed
126
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
127
128
129
130
131
132
133
134
#define PYBIND11_BYTES_CHECK PyString_Check
#define PYBIND11_BYTES_FROM_STRING PyString_FromString
#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
#define PYBIND11_BYTES_AS_STRING PyString_AsString
#define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
#define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) (PyInt_Check(o) ? (unsigned long long) PyLong_AsUnsignedLong(o) : PyLong_AsUnsignedLongLong(o))
135
#define PYBIND11_BYTES_NAME "str"
136
137
#define PYBIND11_STRING_NAME "unicode"
#define PYBIND11_SLICE_OBJECT PySliceObject
138
#define PYBIND11_FROM_STRING PyString_FromString
139
#define PYBIND11_STR_TYPE ::pybind11::bytes
140
141
#define PYBIND11_OB_TYPE(ht_type) (ht_type).ob_type
#define PYBIND11_PLUGIN_IMPL(name) \
142
143
144
145
146
    static PyObject *pybind11_init_wrapper();               \
    extern "C" PYBIND11_EXPORT void init##name() {          \
        (void)pybind11_init_wrapper();                      \
    }                                                       \
    PyObject *pybind11_init_wrapper()
147
#endif
148

149
150
151
152
#if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
extern "C" {
    struct _Py_atomic_address { void *value; };
    PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
153
}
154
155
#endif

156
#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
157
158
159
160
#define PYBIND11_STRINGIFY(x) #x
#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
#define PYBIND11_INTERNALS_ID "__pybind11_" \
    PYBIND11_TOSTRING(PYBIND11_VERSION_MAJOR) "_" PYBIND11_TOSTRING(PYBIND11_VERSION_MINOR) "__"
161

162
163
164
165
166
167
168
169
170
171
172
173
174
/** \rst
    This macro creates the entry point that will be invoked when the Python interpreter
    imports a plugin library. Please create a `module` in the function body and return
    the pointer to its underlying Python object at the end.

    .. code-block:: cpp

        PYBIND11_PLUGIN(example) {
            pybind11::module m("example", "pybind11 example plugin");
            /// Set up bindings here
            return m.ptr();
        }
\endrst */
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#define PYBIND11_PLUGIN(name)                                                  \
    static PyObject *pybind11_init();                                          \
    PYBIND11_PLUGIN_IMPL(name) {                                               \
        int major, minor;                                                      \
        if (sscanf(Py_GetVersion(), "%i.%i", &major, &minor) != 2) {           \
            PyErr_SetString(PyExc_ImportError, "Can't parse Python version."); \
            return nullptr;                                                    \
        } else if (major != PY_MAJOR_VERSION || minor != PY_MINOR_VERSION) {   \
            PyErr_Format(PyExc_ImportError,                                    \
                         "Python version mismatch: module was compiled for "   \
                         "version %i.%i, while the interpreter is running "    \
                         "version %i.%i.", PY_MAJOR_VERSION, PY_MINOR_VERSION, \
                         major, minor);                                        \
            return nullptr;                                                    \
        }                                                                      \
        try {                                                                  \
            return pybind11_init();                                            \
        } catch (const std::exception &e) {                                    \
            PyErr_SetString(PyExc_ImportError, e.what());                      \
            return nullptr;                                                    \
        }                                                                      \
    }                                                                          \
197
198
    PyObject *pybind11_init()

199
200
201
202
203
204
205
206
207
208
209
// Function return value and argument type deduction support.  When compiling under C++17 these
// differ as C++17 makes the noexcept specifier part of the function type, while it is not part of
// the type under earlier standards.
#ifdef __cpp_noexcept_function_type
#  define PYBIND11_NOEXCEPT_TPL_ARG , bool NoExceptions
#  define PYBIND11_NOEXCEPT_SPECIFIER noexcept(NoExceptions)
#else
#  define PYBIND11_NOEXCEPT_TPL_ARG
#  define PYBIND11_NOEXCEPT_SPECIFIER
#endif

210
NAMESPACE_BEGIN(pybind11)
Wenzel Jakob's avatar
Wenzel Jakob committed
211

212
213
using ssize_t = Py_ssize_t;
using size_t  = std::size_t;
Wenzel Jakob's avatar
Wenzel Jakob committed
214
215

/// Approach used to cast a previously unknown C++ instance into a Python object
216
enum class return_value_policy : uint8_t {
Wenzel Jakob's avatar
Wenzel Jakob committed
217
218
219
220
221
    /** This is the default return value policy, which falls back to the policy
        return_value_policy::take_ownership when the return value is a pointer.
        Otherwise, it uses return_value::move or return_value::copy for rvalue
        and lvalue references, respectively. See below for a description of what
        all of these different policies do. */
Wenzel Jakob's avatar
Wenzel Jakob committed
222
    automatic = 0,
Wenzel Jakob's avatar
Wenzel Jakob committed
223

Wenzel Jakob's avatar
Wenzel Jakob committed
224
    /** As above, but use policy return_value_policy::reference when the return
225
226
227
        value is a pointer. This is the default conversion policy for function
        arguments when calling Python functions manually from C++ code (i.e. via
        handle::operator()). You probably won't need to use this. */
228
    automatic_reference,
Wenzel Jakob's avatar
Wenzel Jakob committed
229

Wenzel Jakob's avatar
Wenzel Jakob committed
230
231
232
233
    /** Reference an existing object (i.e. do not create a new copy) and take
        ownership. Python will call the destructor and delete operator when the
        object’s reference count reaches zero. Undefined behavior ensues when
        the C++ side does the same.. */
Wenzel Jakob's avatar
Wenzel Jakob committed
234
    take_ownership,
Wenzel Jakob's avatar
Wenzel Jakob committed
235

Wenzel Jakob's avatar
Wenzel Jakob committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    /** Create a new copy of the returned object, which will be owned by
        Python. This policy is comparably safe because the lifetimes of the two
        instances are decoupled. */
    copy,

    /** Use std::move to move the return value contents into a new instance
        that will be owned by Python. This policy is comparably safe because the
        lifetimes of the two instances (move source and destination) are
        decoupled. */
    move,

    /** Reference an existing object, but do not take ownership. The C++ side
        is responsible for managing the object’s lifetime and deallocating it
        when it is no longer used. Warning: undefined behavior will ensue when
Wenzel Jakob's avatar
Wenzel Jakob committed
250
251
        the C++ side deletes an object that is still referenced and used by
        Python. */
Wenzel Jakob's avatar
Wenzel Jakob committed
252
    reference,
Wenzel Jakob's avatar
Wenzel Jakob committed
253

Wenzel Jakob's avatar
Wenzel Jakob committed
254
255
256
257
258
259
260
261
262
263
    /** This policy only applies to methods and properties. It references the
        object without taking ownership similar to the above
        return_value_policy::reference policy. In contrast to that policy, the
        function or property’s implicit this argument (called the parent) is
        considered to be the the owner of the return value (the child).
        pybind11 then couples the lifetime of the parent to the child via a
        reference relationship that ensures that the parent cannot be garbage
        collected while Python is still using the child. More advanced
        variations of this scheme are also possible using combinations of
        return_value_policy::reference and the keep_alive call policy */
Wenzel Jakob's avatar
Wenzel Jakob committed
264
    reference_internal
Wenzel Jakob's avatar
Wenzel Jakob committed
265
266
267
268
};

/// Information record describing a Python buffer object
struct buffer_info {
Jason Newton's avatar
Jason Newton committed
269
270
271
    void *ptr = nullptr;         // Pointer to the underlying storage
    size_t itemsize = 0;         // Size of individual items in bytes
    size_t size = 0;             // Total number of entries
272
    std::string format;          // For homogeneous buffers, this should be set to format_descriptor<T>::format()
Jason Newton's avatar
Jason Newton committed
273
    size_t ndim = 0;             // Number of dimensions
274
275
    std::vector<size_t> shape;   // Shape of the tensor (1 entry per dimension)
    std::vector<size_t> strides; // Number of entries between adjacent entries (for each per dimension)
Wenzel Jakob's avatar
Wenzel Jakob committed
276

Wenzel Jakob's avatar
Wenzel Jakob committed
277
    buffer_info() { }
278

279
    buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t ndim,
Wenzel Jakob's avatar
Wenzel Jakob committed
280
                const std::vector<size_t> &shape, const std::vector<size_t> &strides)
281
282
        : ptr(ptr), itemsize(itemsize), size(1), format(format),
          ndim(ndim), shape(shape), strides(strides) {
283
284
        for (size_t i = 0; i < ndim; ++i)
            size *= shape[i];
Wenzel Jakob's avatar
Wenzel Jakob committed
285
    }
286

287
288
289
290
    buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t size)
    : buffer_info(ptr, itemsize, format, 1, std::vector<size_t> { size },
                  std::vector<size_t> { itemsize }) { }

291
    explicit buffer_info(Py_buffer *view, bool ownview = true)
292
        : ptr(view->buf), itemsize((size_t) view->itemsize), size(1), format(view->format),
Jason Newton's avatar
Jason Newton committed
293
          ndim((size_t) view->ndim), shape((size_t) view->ndim), strides((size_t) view->ndim), view(view), ownview(ownview) {
294
        for (size_t i = 0; i < (size_t) view->ndim; ++i) {
295
296
297
298
299
300
            shape[i] = (size_t) view->shape[i];
            strides[i] = (size_t) view->strides[i];
            size *= shape[i];
        }
    }

301
302
303
    buffer_info(const buffer_info &) = delete;
    buffer_info& operator=(const buffer_info &) = delete;

Wenzel Jakob's avatar
Wenzel Jakob committed
304
    buffer_info(buffer_info &&other) {
305
306
307
        (*this) = std::move(other);
    }

Wenzel Jakob's avatar
Wenzel Jakob committed
308
    buffer_info& operator=(buffer_info &&rhs) {
309
310
311
312
313
314
315
316
317
318
319
320
        ptr = rhs.ptr;
        itemsize = rhs.itemsize;
        size = rhs.size;
        format = std::move(rhs.format);
        ndim = rhs.ndim;
        shape = std::move(rhs.shape);
        strides = std::move(rhs.strides);
        std::swap(view, rhs.view);
        std::swap(ownview, rhs.ownview);
        return *this;
    }

321
    ~buffer_info() {
Jason Newton's avatar
Jason Newton committed
322
        if (view && ownview) { PyBuffer_Release(view); delete view; }
323
    }
324

325
326
private:
    Py_buffer *view = nullptr;
Jason Newton's avatar
Jason Newton committed
327
    bool ownview = false;
Wenzel Jakob's avatar
Wenzel Jakob committed
328
329
330
331
};

NAMESPACE_BEGIN(detail)

Wenzel Jakob's avatar
Wenzel Jakob committed
332
inline static constexpr int log2(size_t n, int k = 0) { return (n <= 1) ? k : log2(n >> 1, k + 1); }
333

334
335
inline std::string error_string();

336
337
/// Core part of the 'instance' type which POD (needed to be able to use 'offsetof')
template <typename type> struct instance_essentials {
Wenzel Jakob's avatar
Wenzel Jakob committed
338
339
    PyObject_HEAD
    type *value;
340
    PyObject *weakrefs;
Wenzel Jakob's avatar
Wenzel Jakob committed
341
    bool owned : 1;
342
    bool holder_constructed : 1;
343
344
345
346
};

/// PyObject wrapper around generic types, includes a special holder type that is responsible for lifetime management
template <typename type, typename holder_type = std::unique_ptr<type>> struct instance : instance_essentials<type> {
Wenzel Jakob's avatar
Wenzel Jakob committed
347
348
349
    holder_type holder;
};

350
struct overload_hash {
351
    inline size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
352
353
354
355
356
357
        size_t value = std::hash<const void *>()(v.first);
        value ^= std::hash<const void *>()(v.second)  + 0x9e3779b9 + (value<<6) + (value>>2);
        return value;
    }
};

Wenzel Jakob's avatar
Wenzel Jakob committed
358
/// Internal data struture used to track registered instances and types
Wenzel Jakob's avatar
Wenzel Jakob committed
359
struct internals {
360
361
362
    std::unordered_map<std::type_index, void*> registered_types_cpp;   // std::type_index -> type_info
    std::unordered_map<const void *, void*> registered_types_py;       // PyTypeObject* -> type_info
    std::unordered_multimap<const void *, void*> registered_instances; // void * -> PyObject*
363
    std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
364
    std::unordered_map<std::type_index, std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
365
    std::forward_list<void (*) (std::exception_ptr)> registered_exception_translators;
Ivan Smirnov's avatar
Ivan Smirnov committed
366
    std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions
367
#if defined(WITH_THREAD)
368
    decltype(PyThread_create_key()) tstate = 0; // Usually an int but a long on Cygwin64 with Python 3.x
369
370
    PyInterpreterState *istate = nullptr;
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
371
372
};

Wenzel Jakob's avatar
Wenzel Jakob committed
373
/// Return a reference to the current 'internals' information
Wenzel Jakob's avatar
Wenzel Jakob committed
374
375
inline internals &get_internals();

376
/// from __cpp_future__ import (convenient aliases from C++14/17)
377
#ifdef PYBIND11_CPP14
378
379
380
381
382
383
384
385
386
using std::enable_if_t;
using std::conditional_t;
#else
template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
#endif

/// Index sequences
#if defined(PYBIND11_CPP14) || defined(_MSC_VER)
387
388
389
using std::index_sequence;
using std::make_index_sequence;
#else
Wenzel Jakob's avatar
Wenzel Jakob committed
390
template<size_t ...> struct index_sequence  { };
391
392
393
394
template<size_t N, size_t ...S> struct make_index_sequence_impl : make_index_sequence_impl <N - 1, N - 1, S...> { };
template<size_t ...S> struct make_index_sequence_impl <0, S...> { typedef index_sequence<S...> type; };
template<size_t N> using make_index_sequence = typename make_index_sequence_impl<N>::type;
#endif
Wenzel Jakob's avatar
Wenzel Jakob committed
395

396
397
398
399
400
401
402
403
#if defined(PYBIND11_CPP17) || defined(_MSC_VER)
using std::bool_constant;
using std::negation;
#else
template <bool B> using bool_constant = std::integral_constant<bool, B>;
template <class T> using negation = bool_constant<!T::value>;
#endif

404
/// Compile-time all/any/none of that check the boolean value of all template types
405
406
407
408
#ifdef PYBIND11_CPP17
template <class... Ts> using all_of = bool_constant<(Ts::value && ...)>;
template <class... Ts> using any_of = bool_constant<(Ts::value || ...)>;
#elif !defined(_MSC_VER)
409
410
411
412
413
414
415
416
417
418
419
420
421
template <bool...> struct bools {};
template <class... Ts> using all_of = std::is_same<
    bools<Ts::value..., true>,
    bools<true, Ts::value...>>;
template <class... Ts> using any_of = negation<all_of<negation<Ts>...>>;
#else
// MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
// at a slight loss of compilation efficiency).
template <class... Ts> using all_of = std::conjunction<Ts...>;
template <class... Ts> using any_of = std::disjunction<Ts...>;
#endif
template <class... Ts> using none_of = negation<any_of<Ts...>>;

422
423
424
425
template <class T, template<class> class... Predicates> using satisfies_all_of = all_of<Predicates<T>...>;
template <class T, template<class> class... Predicates> using satisfies_any_of = any_of<Predicates<T>...>;
template <class T, template<class> class... Predicates> using satisfies_none_of = none_of<Predicates<T>...>;

Wenzel Jakob's avatar
Wenzel Jakob committed
426
/// Strip the class from a method type
Wenzel Jakob's avatar
Wenzel Jakob committed
427
template <typename T> struct remove_class { };
Wenzel Jakob's avatar
Wenzel Jakob committed
428
429
430
431
template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };

/// Helper template to strip away type modifiers
432
433
434
435
436
437
438
template <typename T> struct intrinsic_type                       { typedef T type; };
template <typename T> struct intrinsic_type<const T>              { typedef typename intrinsic_type<T>::type type; };
template <typename T> struct intrinsic_type<T*>                   { typedef typename intrinsic_type<T>::type type; };
template <typename T> struct intrinsic_type<T&>                   { typedef typename intrinsic_type<T>::type type; };
template <typename T> struct intrinsic_type<T&&>                  { typedef typename intrinsic_type<T>::type type; };
template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
template <typename T, size_t N> struct intrinsic_type<T[N]>       { typedef typename intrinsic_type<T>::type type; };
439
template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
Wenzel Jakob's avatar
Wenzel Jakob committed
440
441
442

/// Helper type to replace 'void' in some expressions
struct void_type { };
443

444
445
446
/// Helper template which holds a list of types
template <typename...> struct type_list { };

447
448
449
450
451
/// Compile-time integer sum
constexpr size_t constexpr_sum() { return 0; }
template <typename T, typename... Ts>
constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }

452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
NAMESPACE_BEGIN(constexpr_impl)
/// Implementation details for constexpr functions
constexpr int first(int i) { return i; }
template <typename T, typename... Ts>
constexpr int first(int i, T v, Ts... vs) { return v ? i : first(i + 1, vs...); }

constexpr int last(int /*i*/, int result) { return result; }
template <typename T, typename... Ts>
constexpr int last(int i, int result, T v, Ts... vs) { return last(i + 1, v ? i : result, vs...); }
NAMESPACE_END(constexpr_impl)

/// Return the index of the first type in Ts which satisfies Predicate<T>.  Returns sizeof...(Ts) if
/// none match.
template <template<typename> class Predicate, typename... Ts>
constexpr int constexpr_first() { return constexpr_impl::first(0, Predicate<Ts>::value...); }

/// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
template <template<typename> class Predicate, typename... Ts>
constexpr int constexpr_last() { return constexpr_impl::last(0, -1, Predicate<Ts>::value...); }

472
473
474
475
// Extracts the first type from the template parameter pack matching the predicate, or Default if none match.
template <template<class> class Predicate, class Default, class... Ts> struct first_of;
template <template<class> class Predicate, class Default> struct first_of<Predicate, Default> {
    using type = Default;
476
};
477
478
template <template<class> class Predicate, class Default, class T, class... Ts>
struct first_of<Predicate, Default, T, Ts...> {
479
480
481
    using type = typename std::conditional<
        Predicate<T>::value,
        T,
482
        typename first_of<Predicate, Default, Ts...>::type
483
484
    >::type;
};
485
template <template<class> class Predicate, class Default, class... T> using first_of_t = typename first_of<Predicate, Default, T...>::type;
486

487
488
489
490
/// Defer the evaluation of type T until types Us are instantiated
template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;

491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
template <template<typename...> class Base>
struct is_template_base_of_impl {
    template <typename... Us> static std::true_type check(Base<Us...> *);
    static std::false_type check(...);
};

/// Check if a template is the base of a type. For example:
/// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
template <template<typename...> class Base, typename T>
#if !defined(_MSC_VER)
using is_template_base_of = decltype(is_template_base_of_impl<Base>::check((T*)nullptr));
#else // MSVC2015 has trouble with decltype in template aliases
struct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((T*)nullptr)) { };
#endif

506
507
508
509
/// Check if T is std::shared_ptr<U> where U can be anything
template <typename T> struct is_shared_ptr : std::false_type { };
template <typename U> struct is_shared_ptr<std::shared_ptr<U>> : std::true_type { };

510
511
512
/// Ignore that a variable is unused in compiler warnings
inline void ignore_unused(const int *) { }

Wenzel Jakob's avatar
Wenzel Jakob committed
513
NAMESPACE_END(detail)
514

Ivan Smirnov's avatar
Ivan Smirnov committed
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/// Returns a named pointer that is shared among all extension modules (using the same
/// pybind11 version) running in the current interpreter. Names starting with underscores
/// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
inline PYBIND11_NOINLINE void* get_shared_data(const std::string& name) {
    auto& internals = detail::get_internals();
    auto it = internals.shared_data.find(name);
    return it != internals.shared_data.end() ? it->second : nullptr;
}

/// Set the shared data that can be later recovered by `get_shared_data()`.
inline PYBIND11_NOINLINE void *set_shared_data(const std::string& name, void *data) {
    detail::get_internals().shared_data[name] = data;
    return data;
}

/// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
/// such entry exists. Otherwise, a new object of default-constructible type `T` is
/// added to the shared data under the given name and a reference to it is returned.
template<typename T> T& get_or_create_shared_data(const std::string& name) {
    auto& internals = detail::get_internals();
    auto it = internals.shared_data.find(name);
    T* ptr = (T*) (it != internals.shared_data.end() ? it->second : nullptr);
    if (!ptr) {
        ptr = new T();
        internals.shared_data[name] = ptr;
    }
    return *ptr;
}

544
545
546
547
548
549
/// Fetch and hold an error which was already set in Python
class error_already_set : public std::runtime_error {
public:
    error_already_set() : std::runtime_error(detail::error_string()) {
        PyErr_Fetch(&type, &value, &trace);
    }
550
551
552
553
554
555
556

    error_already_set(const error_already_set &) = delete;

    error_already_set(error_already_set &&e)
        : std::runtime_error(e.what()), type(e.type), value(e.value),
          trace(e.trace) { e.type = e.value = e.trace = nullptr; }

557
    inline ~error_already_set(); // implementation in pybind11.h
558
559

    error_already_set& operator=(const error_already_set &) = delete;
560
561
562
563
564
565
566
567

    /// Give the error back to Python
    void restore() { PyErr_Restore(type, value, trace); type = value = trace = nullptr; }

private:
    PyObject *type, *value, *trace;
};

568
569
570
571
/// C++ bindings of builtin Python exceptions
class builtin_exception : public std::runtime_error {
public:
    using std::runtime_error::runtime_error;
572
573
    /// Set the error using the Python C API
    virtual void set_error() const = 0;
574
575
576
577
578
579
580
};

#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
    class name : public builtin_exception { public: \
        using builtin_exception::builtin_exception; \
        name() : name("") { } \
        void set_error() const override { PyErr_SetString(type, what()); } \
Wenzel Jakob's avatar
Wenzel Jakob committed
581
582
    };

583
584
585
586
587
588
589
PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
590

591
592
[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
593

594
template <typename T, typename SFINAE = void> struct format_descriptor { };
595

596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
NAMESPACE_BEGIN(detail)
// Returns the index of the given type in the type char array below, and in the list in numpy.h
// The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
// complex float,double,long double.  Note that the long double types only participate when long
// double is actually longer than double (it isn't under MSVC).
// NB: not only the string below but also complex.h and numpy.h rely on this order.
template <typename T, typename SFINAE = void> struct is_fmt_numeric { static constexpr bool value = false; };
template <typename T> struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
    static constexpr bool value = true;
    static constexpr int index = std::is_same<T, bool>::value ? 0 : 1 + (
        std::is_integral<T>::value ? detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value : 8 + (
        std::is_same<T, double>::value ? 1 : std::is_same<T, long double>::value ? 2 : 0));
};
NAMESPACE_END(detail)

template <typename T> struct format_descriptor<T, detail::enable_if_t<detail::is_fmt_numeric<T>::value>> {
    static constexpr const char c = "?bBhHiIqQfdgFDG"[detail::is_fmt_numeric<T>::index];
613
614
    static constexpr const char value[2] = { c, '\0' };
    static std::string format() { return std::string(1, c); }
615
};
616

617
template <typename T> constexpr const char format_descriptor<
618
    T, detail::enable_if_t<detail::is_fmt_numeric<T>::value>>::value[2];
619

Wenzel Jakob's avatar
Wenzel Jakob committed
620
621
622
623
624
625
626
/// RAII wrapper that temporarily clears any Python error state
struct error_scope {
    PyObject *type, *value, *trace;
    error_scope() { PyErr_Fetch(&type, &value, &trace); }
    ~error_scope() { PyErr_Restore(type, value, trace); }
};

Wenzel Jakob's avatar
Wenzel Jakob committed
627
628
/// Dummy destructor wrapper that can be used to expose classes with a private destructor
struct nodelete { template <typename T> void operator()(T*) { } };
629

630
631
632
633
634
635
636
// overload_cast requires variable templates: C++14 or MSVC 2015 Update 2
#if defined(PYBIND11_CPP14) || _MSC_FULL_VER >= 190023918
#define PYBIND11_OVERLOAD_CAST 1

NAMESPACE_BEGIN(detail)
template <typename... Args>
struct overload_cast_impl {
637
638
    template <typename Return /*,*/ PYBIND11_NOEXCEPT_TPL_ARG>
    constexpr auto operator()(Return (*pf)(Args...) PYBIND11_NOEXCEPT_SPECIFIER) const noexcept
639
640
                              -> decltype(pf) { return pf; }

641
642
    template <typename Return, typename Class /*,*/ PYBIND11_NOEXCEPT_TPL_ARG>
    constexpr auto operator()(Return (Class::*pmf)(Args...) PYBIND11_NOEXCEPT_SPECIFIER, std::false_type = {}) const noexcept
643
644
                              -> decltype(pmf) { return pmf; }

645
646
    template <typename Return, typename Class /*,*/ PYBIND11_NOEXCEPT_TPL_ARG>
    constexpr auto operator()(Return (Class::*pmf)(Args...) const PYBIND11_NOEXCEPT_SPECIFIER, std::true_type) const noexcept
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
                              -> decltype(pmf) { return pmf; }
};
NAMESPACE_END(detail)

/// Syntax sugar for resolving overloaded function pointers:
///  - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
///  - sweet:   overload_cast<Arg0, Arg1, Arg2>(&Class::func)
template <typename... Args>
static constexpr detail::overload_cast_impl<Args...> overload_cast = {};
// MSVC 2015 only accepts this particular initialization syntax for this variable template.

/// Const member function selector for overload_cast
///  - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
///  - sweet:   overload_cast<Arg>(&Class::func, const_)
static constexpr auto const_ = std::true_type{};

#endif // overload_cast

665
NAMESPACE_END(pybind11)