common.h revision 12037:d28054ac6ec9
1/*
2    pybind11/common.h -- Basic macros
3
4    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
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
10#pragma once
11
12#if !defined(NAMESPACE_BEGIN)
13#  define NAMESPACE_BEGIN(name) namespace name {
14#endif
15#if !defined(NAMESPACE_END)
16#  define NAMESPACE_END(name) }
17#endif
18
19// 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
31// Compiler version assertions
32#if defined(__INTEL_COMPILER)
33#  if __INTEL_COMPILER < 1500
34#    error pybind11 requires Intel C++ compiler v15 or newer
35#  endif
36#elif defined(__clang__) && !defined(__apple_build_version__)
37#  if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
38#    error pybind11 requires clang 3.3 or newer
39#  endif
40#elif defined(__clang__)
41// Apple changes clang version macros to its Xcode version; the first Xcode release based on
42// (upstream) clang 3.3 was Xcode 5:
43#  if __clang_major__ < 5
44#    error pybind11 requires Xcode/clang 5.0 or newer
45#  endif
46#elif defined(__GNUG__)
47#  if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
48#    error pybind11 requires gcc 4.8 or newer
49#  endif
50#elif defined(_MSC_VER)
51// Pybind hits various compiler bugs in 2015u2 and earlier, and also makes use of some stl features
52// (e.g. std::negation) added in 2015u3:
53#  if _MSC_FULL_VER < 190024210
54#    error pybind11 requires MSVC 2015 update 3 or newer
55#  endif
56#endif
57
58#if !defined(PYBIND11_EXPORT)
59#  if defined(WIN32) || defined(_WIN32)
60#    define PYBIND11_EXPORT __declspec(dllexport)
61#  else
62#    define PYBIND11_EXPORT __attribute__ ((visibility("default")))
63#  endif
64#endif
65
66#if defined(_MSC_VER)
67#  define PYBIND11_NOINLINE __declspec(noinline)
68#else
69#  define PYBIND11_NOINLINE __attribute__ ((noinline))
70#endif
71
72#if defined(PYBIND11_CPP14)
73#  define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
74#elif defined(__clang__)
75#  define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
76#elif defined(__GNUG__)
77#  define PYBIND11_DEPRECATED(reason) __attribute__((deprecated))
78#elif defined(_MSC_VER)
79#  define PYBIND11_DEPRECATED(reason) __declspec(deprecated)
80#endif
81
82#define PYBIND11_VERSION_MAJOR 2
83#define PYBIND11_VERSION_MINOR 1
84#define PYBIND11_VERSION_PATCH 1
85
86/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
87#if defined(_MSC_VER)
88#  if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 4)
89#    define HAVE_ROUND 1
90#  endif
91#  pragma warning(push)
92#  pragma warning(disable: 4510 4610 4512 4005)
93#  if defined(_DEBUG)
94#    define PYBIND11_DEBUG_MARKER
95#    undef _DEBUG
96#  endif
97#endif
98
99#include <Python.h>
100#include <frameobject.h>
101#include <pythread.h>
102
103#if defined(_WIN32) && (defined(min) || defined(max))
104#  error Macro clash with min and max -- define NOMINMAX when compiling your program on Windows
105#endif
106
107#if defined(isalnum)
108#  undef isalnum
109#  undef isalpha
110#  undef islower
111#  undef isspace
112#  undef isupper
113#  undef tolower
114#  undef toupper
115#endif
116
117#if defined(_MSC_VER)
118#  if defined(PYBIND11_DEBUG_MARKER)
119#    define _DEBUG
120#    undef PYBIND11_DEBUG_MARKER
121#  endif
122#  pragma warning(pop)
123#endif
124
125#include <cstddef>
126#include <forward_list>
127#include <vector>
128#include <string>
129#include <stdexcept>
130#include <unordered_set>
131#include <unordered_map>
132#include <memory>
133#include <typeindex>
134#include <type_traits>
135
136#if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
137#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
138#define PYBIND11_BYTES_CHECK PyBytes_Check
139#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
140#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
141#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
142#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
143#define PYBIND11_BYTES_SIZE PyBytes_Size
144#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
145#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
146#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) PyLong_AsUnsignedLongLong(o)
147#define PYBIND11_BYTES_NAME "bytes"
148#define PYBIND11_STRING_NAME "str"
149#define PYBIND11_SLICE_OBJECT PyObject
150#define PYBIND11_FROM_STRING PyUnicode_FromString
151#define PYBIND11_STR_TYPE ::pybind11::str
152#define PYBIND11_PLUGIN_IMPL(name) \
153    extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
154#else
155#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
156#define PYBIND11_BYTES_CHECK PyString_Check
157#define PYBIND11_BYTES_FROM_STRING PyString_FromString
158#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
159#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
160#define PYBIND11_BYTES_AS_STRING PyString_AsString
161#define PYBIND11_BYTES_SIZE PyString_Size
162#define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
163#define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
164#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) (PyInt_Check(o) ? (unsigned long long) PyLong_AsUnsignedLong(o) : PyLong_AsUnsignedLongLong(o))
165#define PYBIND11_BYTES_NAME "str"
166#define PYBIND11_STRING_NAME "unicode"
167#define PYBIND11_SLICE_OBJECT PySliceObject
168#define PYBIND11_FROM_STRING PyString_FromString
169#define PYBIND11_STR_TYPE ::pybind11::bytes
170#define PYBIND11_PLUGIN_IMPL(name) \
171    static PyObject *pybind11_init_wrapper();               \
172    extern "C" PYBIND11_EXPORT void init##name() {          \
173        (void)pybind11_init_wrapper();                      \
174    }                                                       \
175    PyObject *pybind11_init_wrapper()
176#endif
177
178#if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
179extern "C" {
180    struct _Py_atomic_address { void *value; };
181    PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
182}
183#endif
184
185#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
186#define PYBIND11_STRINGIFY(x) #x
187#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
188#define PYBIND11_INTERNALS_ID "__pybind11_" \
189    PYBIND11_TOSTRING(PYBIND11_VERSION_MAJOR) "_" PYBIND11_TOSTRING(PYBIND11_VERSION_MINOR) "__"
190
191/** \rst
192    This macro creates the entry point that will be invoked when the Python interpreter
193    imports a plugin library. Please create a `module` in the function body and return
194    the pointer to its underlying Python object at the end.
195
196    .. code-block:: cpp
197
198        PYBIND11_PLUGIN(example) {
199            pybind11::module m("example", "pybind11 example plugin");
200            /// Set up bindings here
201            return m.ptr();
202        }
203\endrst */
204#define PYBIND11_PLUGIN(name)                                                  \
205    static PyObject *pybind11_init();                                          \
206    PYBIND11_PLUGIN_IMPL(name) {                                               \
207        int major, minor;                                                      \
208        if (sscanf(Py_GetVersion(), "%i.%i", &major, &minor) != 2) {           \
209            PyErr_SetString(PyExc_ImportError, "Can't parse Python version."); \
210            return nullptr;                                                    \
211        } else if (major != PY_MAJOR_VERSION || minor != PY_MINOR_VERSION) {   \
212            PyErr_Format(PyExc_ImportError,                                    \
213                         "Python version mismatch: module was compiled for "   \
214                         "version %i.%i, while the interpreter is running "    \
215                         "version %i.%i.", PY_MAJOR_VERSION, PY_MINOR_VERSION, \
216                         major, minor);                                        \
217            return nullptr;                                                    \
218        }                                                                      \
219        try {                                                                  \
220            return pybind11_init();                                            \
221        } catch (pybind11::error_already_set &e) {                             \
222            e.clear();                                                         \
223            PyErr_SetString(PyExc_ImportError, e.what());                      \
224            return nullptr;                                                    \
225        } catch (const std::exception &e) {                                    \
226            PyErr_SetString(PyExc_ImportError, e.what());                      \
227            return nullptr;                                                    \
228        }                                                                      \
229    }                                                                          \
230    PyObject *pybind11_init()
231
232NAMESPACE_BEGIN(pybind11)
233
234using ssize_t = Py_ssize_t;
235using size_t  = std::size_t;
236
237/// Approach used to cast a previously unknown C++ instance into a Python object
238enum class return_value_policy : uint8_t {
239    /** This is the default return value policy, which falls back to the policy
240        return_value_policy::take_ownership when the return value is a pointer.
241        Otherwise, it uses return_value::move or return_value::copy for rvalue
242        and lvalue references, respectively. See below for a description of what
243        all of these different policies do. */
244    automatic = 0,
245
246    /** As above, but use policy return_value_policy::reference when the return
247        value is a pointer. This is the default conversion policy for function
248        arguments when calling Python functions manually from C++ code (i.e. via
249        handle::operator()). You probably won't need to use this. */
250    automatic_reference,
251
252    /** Reference an existing object (i.e. do not create a new copy) and take
253        ownership. Python will call the destructor and delete operator when the
254        object’s reference count reaches zero. Undefined behavior ensues when
255        the C++ side does the same.. */
256    take_ownership,
257
258    /** Create a new copy of the returned object, which will be owned by
259        Python. This policy is comparably safe because the lifetimes of the two
260        instances are decoupled. */
261    copy,
262
263    /** Use std::move to move the return value contents into a new instance
264        that will be owned by Python. This policy is comparably safe because the
265        lifetimes of the two instances (move source and destination) are
266        decoupled. */
267    move,
268
269    /** Reference an existing object, but do not take ownership. The C++ side
270        is responsible for managing the object’s lifetime and deallocating it
271        when it is no longer used. Warning: undefined behavior will ensue when
272        the C++ side deletes an object that is still referenced and used by
273        Python. */
274    reference,
275
276    /** This policy only applies to methods and properties. It references the
277        object without taking ownership similar to the above
278        return_value_policy::reference policy. In contrast to that policy, the
279        function or property’s implicit this argument (called the parent) is
280        considered to be the the owner of the return value (the child).
281        pybind11 then couples the lifetime of the parent to the child via a
282        reference relationship that ensures that the parent cannot be garbage
283        collected while Python is still using the child. More advanced
284        variations of this scheme are also possible using combinations of
285        return_value_policy::reference and the keep_alive call policy */
286    reference_internal
287};
288
289/// Information record describing a Python buffer object
290struct buffer_info {
291    void *ptr = nullptr;         // Pointer to the underlying storage
292    size_t itemsize = 0;         // Size of individual items in bytes
293    size_t size = 0;             // Total number of entries
294    std::string format;          // For homogeneous buffers, this should be set to format_descriptor<T>::format()
295    size_t ndim = 0;             // Number of dimensions
296    std::vector<size_t> shape;   // Shape of the tensor (1 entry per dimension)
297    std::vector<size_t> strides; // Number of entries between adjacent entries (for each per dimension)
298
299    buffer_info() { }
300
301    buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t ndim,
302                const std::vector<size_t> &shape, const std::vector<size_t> &strides)
303        : ptr(ptr), itemsize(itemsize), size(1), format(format),
304          ndim(ndim), shape(shape), strides(strides) {
305        for (size_t i = 0; i < ndim; ++i)
306            size *= shape[i];
307    }
308
309    buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t size)
310    : buffer_info(ptr, itemsize, format, 1, std::vector<size_t> { size },
311                  std::vector<size_t> { itemsize }) { }
312
313    explicit buffer_info(Py_buffer *view, bool ownview = true)
314        : ptr(view->buf), itemsize((size_t) view->itemsize), size(1), format(view->format),
315          ndim((size_t) view->ndim), shape((size_t) view->ndim), strides((size_t) view->ndim), view(view), ownview(ownview) {
316        for (size_t i = 0; i < (size_t) view->ndim; ++i) {
317            shape[i] = (size_t) view->shape[i];
318            strides[i] = (size_t) view->strides[i];
319            size *= shape[i];
320        }
321    }
322
323    buffer_info(const buffer_info &) = delete;
324    buffer_info& operator=(const buffer_info &) = delete;
325
326    buffer_info(buffer_info &&other) {
327        (*this) = std::move(other);
328    }
329
330    buffer_info& operator=(buffer_info &&rhs) {
331        ptr = rhs.ptr;
332        itemsize = rhs.itemsize;
333        size = rhs.size;
334        format = std::move(rhs.format);
335        ndim = rhs.ndim;
336        shape = std::move(rhs.shape);
337        strides = std::move(rhs.strides);
338        std::swap(view, rhs.view);
339        std::swap(ownview, rhs.ownview);
340        return *this;
341    }
342
343    ~buffer_info() {
344        if (view && ownview) { PyBuffer_Release(view); delete view; }
345    }
346
347private:
348    Py_buffer *view = nullptr;
349    bool ownview = false;
350};
351
352NAMESPACE_BEGIN(detail)
353
354inline static constexpr int log2(size_t n, int k = 0) { return (n <= 1) ? k : log2(n >> 1, k + 1); }
355
356inline std::string error_string();
357
358/// Core part of the 'instance' type which POD (needed to be able to use 'offsetof')
359template <typename type> struct instance_essentials {
360    PyObject_HEAD
361    type *value;
362    PyObject *weakrefs;
363    bool owned : 1;
364    bool holder_constructed : 1;
365};
366
367/// PyObject wrapper around generic types, includes a special holder type that is responsible for lifetime management
368template <typename type, typename holder_type = std::unique_ptr<type>> struct instance : instance_essentials<type> {
369    holder_type holder;
370};
371
372struct overload_hash {
373    inline size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
374        size_t value = std::hash<const void *>()(v.first);
375        value ^= std::hash<const void *>()(v.second)  + 0x9e3779b9 + (value<<6) + (value>>2);
376        return value;
377    }
378};
379
380/// Internal data structure used to track registered instances and types
381struct internals {
382    std::unordered_map<std::type_index, void*> registered_types_cpp;   // std::type_index -> type_info
383    std::unordered_map<const void *, void*> registered_types_py;       // PyTypeObject* -> type_info
384    std::unordered_multimap<const void *, void*> registered_instances; // void * -> PyObject*
385    std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
386    std::unordered_map<std::type_index, std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
387    std::forward_list<void (*) (std::exception_ptr)> registered_exception_translators;
388    std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions
389    PyTypeObject *static_property_type;
390    PyTypeObject *default_metaclass;
391    std::unordered_map<size_t, PyObject *> bases; // one base type per `instance_size` (very few)
392#if defined(WITH_THREAD)
393    decltype(PyThread_create_key()) tstate = 0; // Usually an int but a long on Cygwin64 with Python 3.x
394    PyInterpreterState *istate = nullptr;
395#endif
396
397    /// Return the appropriate base type for the given instance size
398    PyObject *get_base(size_t instance_size);
399};
400
401/// Return a reference to the current 'internals' information
402inline internals &get_internals();
403
404/// from __cpp_future__ import (convenient aliases from C++14/17)
405#ifdef PYBIND11_CPP14
406using std::enable_if_t;
407using std::conditional_t;
408using std::remove_cv_t;
409#else
410template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
411template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
412template <typename T> using remove_cv_t = typename std::remove_cv<T>::type;
413#endif
414
415/// Index sequences
416#if defined(PYBIND11_CPP14) || defined(_MSC_VER)
417using std::index_sequence;
418using std::make_index_sequence;
419#else
420template<size_t ...> struct index_sequence  { };
421template<size_t N, size_t ...S> struct make_index_sequence_impl : make_index_sequence_impl <N - 1, N - 1, S...> { };
422template<size_t ...S> struct make_index_sequence_impl <0, S...> { typedef index_sequence<S...> type; };
423template<size_t N> using make_index_sequence = typename make_index_sequence_impl<N>::type;
424#endif
425
426/// Backports of std::bool_constant and std::negation to accomodate older compilers
427template <bool B> using bool_constant = std::integral_constant<bool, B>;
428template <typename T> struct negation : bool_constant<!T::value> { };
429
430template <typename...> struct void_t_impl { using type = void; };
431template <typename... Ts> using void_t = typename void_t_impl<Ts...>::type;
432
433/// Compile-time all/any/none of that check the boolean value of all template types
434#ifdef __cpp_fold_expressions
435template <class... Ts> using all_of = bool_constant<(Ts::value && ...)>;
436template <class... Ts> using any_of = bool_constant<(Ts::value || ...)>;
437#elif !defined(_MSC_VER)
438template <bool...> struct bools {};
439template <class... Ts> using all_of = std::is_same<
440    bools<Ts::value..., true>,
441    bools<true, Ts::value...>>;
442template <class... Ts> using any_of = negation<all_of<negation<Ts>...>>;
443#else
444// MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
445// at a slight loss of compilation efficiency).
446template <class... Ts> using all_of = std::conjunction<Ts...>;
447template <class... Ts> using any_of = std::disjunction<Ts...>;
448#endif
449template <class... Ts> using none_of = negation<any_of<Ts...>>;
450
451template <class T, template<class> class... Predicates> using satisfies_all_of = all_of<Predicates<T>...>;
452template <class T, template<class> class... Predicates> using satisfies_any_of = any_of<Predicates<T>...>;
453template <class T, template<class> class... Predicates> using satisfies_none_of = none_of<Predicates<T>...>;
454
455/// Strip the class from a method type
456template <typename T> struct remove_class { };
457template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
458template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
459
460/// Helper template to strip away type modifiers
461template <typename T> struct intrinsic_type                       { typedef T type; };
462template <typename T> struct intrinsic_type<const T>              { typedef typename intrinsic_type<T>::type type; };
463template <typename T> struct intrinsic_type<T*>                   { typedef typename intrinsic_type<T>::type type; };
464template <typename T> struct intrinsic_type<T&>                   { typedef typename intrinsic_type<T>::type type; };
465template <typename T> struct intrinsic_type<T&&>                  { typedef typename intrinsic_type<T>::type type; };
466template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
467template <typename T, size_t N> struct intrinsic_type<T[N]>       { typedef typename intrinsic_type<T>::type type; };
468template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
469
470/// Helper type to replace 'void' in some expressions
471struct void_type { };
472
473/// Helper template which holds a list of types
474template <typename...> struct type_list { };
475
476/// Compile-time integer sum
477#ifdef __cpp_fold_expressions
478template <typename... Ts> constexpr size_t constexpr_sum(Ts... ns) { return (0 + ... + size_t{ns}); }
479#else
480constexpr size_t constexpr_sum() { return 0; }
481template <typename T, typename... Ts>
482constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
483#endif
484
485NAMESPACE_BEGIN(constexpr_impl)
486/// Implementation details for constexpr functions
487constexpr int first(int i) { return i; }
488template <typename T, typename... Ts>
489constexpr int first(int i, T v, Ts... vs) { return v ? i : first(i + 1, vs...); }
490
491constexpr int last(int /*i*/, int result) { return result; }
492template <typename T, typename... Ts>
493constexpr int last(int i, int result, T v, Ts... vs) { return last(i + 1, v ? i : result, vs...); }
494NAMESPACE_END(constexpr_impl)
495
496/// Return the index of the first type in Ts which satisfies Predicate<T>.  Returns sizeof...(Ts) if
497/// none match.
498template <template<typename> class Predicate, typename... Ts>
499constexpr int constexpr_first() { return constexpr_impl::first(0, Predicate<Ts>::value...); }
500
501/// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
502template <template<typename> class Predicate, typename... Ts>
503constexpr int constexpr_last() { return constexpr_impl::last(0, -1, Predicate<Ts>::value...); }
504
505// Extracts the first type from the template parameter pack matching the predicate, or Default if none match.
506template <template<class> class Predicate, class Default, class... Ts> struct first_of;
507template <template<class> class Predicate, class Default> struct first_of<Predicate, Default> {
508    using type = Default;
509};
510template <template<class> class Predicate, class Default, class T, class... Ts>
511struct first_of<Predicate, Default, T, Ts...> {
512    using type = typename std::conditional<
513        Predicate<T>::value,
514        T,
515        typename first_of<Predicate, Default, Ts...>::type
516    >::type;
517};
518template <template<class> class Predicate, class Default, class... T> using first_of_t = typename first_of<Predicate, Default, T...>::type;
519
520/// Defer the evaluation of type T until types Us are instantiated
521template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
522template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
523
524template <template<typename...> class Base>
525struct is_template_base_of_impl {
526    template <typename... Us> static std::true_type check(Base<Us...> *);
527    static std::false_type check(...);
528};
529
530/// Check if a template is the base of a type. For example:
531/// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
532template <template<typename...> class Base, typename T>
533#if !defined(_MSC_VER)
534using is_template_base_of = decltype(is_template_base_of_impl<Base>::check((remove_cv_t<T>*)nullptr));
535#else // MSVC2015 has trouble with decltype in template aliases
536struct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((remove_cv_t<T>*)nullptr)) { };
537#endif
538
539/// Check if T is std::shared_ptr<U> where U can be anything
540template <typename T> struct is_shared_ptr : std::false_type { };
541template <typename U> struct is_shared_ptr<std::shared_ptr<U>> : std::true_type { };
542
543/// Ignore that a variable is unused in compiler warnings
544inline void ignore_unused(const int *) { }
545
546NAMESPACE_END(detail)
547
548/// Returns a named pointer that is shared among all extension modules (using the same
549/// pybind11 version) running in the current interpreter. Names starting with underscores
550/// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
551inline PYBIND11_NOINLINE void* get_shared_data(const std::string& name) {
552    auto& internals = detail::get_internals();
553    auto it = internals.shared_data.find(name);
554    return it != internals.shared_data.end() ? it->second : nullptr;
555}
556
557/// Set the shared data that can be later recovered by `get_shared_data()`.
558inline PYBIND11_NOINLINE void *set_shared_data(const std::string& name, void *data) {
559    detail::get_internals().shared_data[name] = data;
560    return data;
561}
562
563/// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
564/// such entry exists. Otherwise, a new object of default-constructible type `T` is
565/// added to the shared data under the given name and a reference to it is returned.
566template<typename T> T& get_or_create_shared_data(const std::string& name) {
567    auto& internals = detail::get_internals();
568    auto it = internals.shared_data.find(name);
569    T* ptr = (T*) (it != internals.shared_data.end() ? it->second : nullptr);
570    if (!ptr) {
571        ptr = new T();
572        internals.shared_data[name] = ptr;
573    }
574    return *ptr;
575}
576
577/// Fetch and hold an error which was already set in Python
578class error_already_set : public std::runtime_error {
579public:
580    error_already_set() : std::runtime_error(detail::error_string()) {
581        PyErr_Fetch(&type, &value, &trace);
582    }
583
584    error_already_set(const error_already_set &) = delete;
585
586    error_already_set(error_already_set &&e)
587        : std::runtime_error(e.what()), type(e.type), value(e.value),
588          trace(e.trace) { e.type = e.value = e.trace = nullptr; }
589
590    inline ~error_already_set(); // implementation in pybind11.h
591
592    error_already_set& operator=(const error_already_set &) = delete;
593
594    /// Give the error back to Python
595    void restore() { PyErr_Restore(type, value, trace); type = value = trace = nullptr; }
596
597    /// Clear the held Python error state (the C++ `what()` message remains intact)
598    void clear() { restore(); PyErr_Clear(); }
599
600private:
601    PyObject *type, *value, *trace;
602};
603
604/// C++ bindings of builtin Python exceptions
605class builtin_exception : public std::runtime_error {
606public:
607    using std::runtime_error::runtime_error;
608    /// Set the error using the Python C API
609    virtual void set_error() const = 0;
610};
611
612#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
613    class name : public builtin_exception { public: \
614        using builtin_exception::builtin_exception; \
615        name() : name("") { } \
616        void set_error() const override { PyErr_SetString(type, what()); } \
617    };
618
619PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
620PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
621PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
622PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
623PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
624PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
625PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
626
627[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
628[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
629
630template <typename T, typename SFINAE = void> struct format_descriptor { };
631
632NAMESPACE_BEGIN(detail)
633// Returns the index of the given type in the type char array below, and in the list in numpy.h
634// The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
635// complex float,double,long double.  Note that the long double types only participate when long
636// double is actually longer than double (it isn't under MSVC).
637// NB: not only the string below but also complex.h and numpy.h rely on this order.
638template <typename T, typename SFINAE = void> struct is_fmt_numeric { static constexpr bool value = false; };
639template <typename T> struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
640    static constexpr bool value = true;
641    static constexpr int index = std::is_same<T, bool>::value ? 0 : 1 + (
642        std::is_integral<T>::value ? detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value : 8 + (
643        std::is_same<T, double>::value ? 1 : std::is_same<T, long double>::value ? 2 : 0));
644};
645NAMESPACE_END(detail)
646
647template <typename T> struct format_descriptor<T, detail::enable_if_t<detail::is_fmt_numeric<T>::value>> {
648    static constexpr const char c = "?bBhHiIqQfdgFDG"[detail::is_fmt_numeric<T>::index];
649    static constexpr const char value[2] = { c, '\0' };
650    static std::string format() { return std::string(1, c); }
651};
652
653template <typename T> constexpr const char format_descriptor<
654    T, detail::enable_if_t<detail::is_fmt_numeric<T>::value>>::value[2];
655
656NAMESPACE_BEGIN(detail)
657
658template <typename T, typename SFINAE = void> struct compare_buffer_info {
659    static bool compare(const buffer_info& b) {
660        return b.format == format_descriptor<T>::format() && b.itemsize == sizeof(T);
661    }
662};
663
664template <typename T> struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> {
665    static bool compare(const buffer_info& b) {
666        return b.itemsize == sizeof(T) && (b.format == format_descriptor<T>::value ||
667            ((sizeof(T) == sizeof(long)) && b.format == (std::is_unsigned<T>::value ? "L" : "l")) ||
668            ((sizeof(T) == sizeof(size_t)) && b.format == (std::is_unsigned<T>::value ? "N" : "n")));
669    }
670};
671
672NAMESPACE_END(detail)
673
674/// RAII wrapper that temporarily clears any Python error state
675struct error_scope {
676    PyObject *type, *value, *trace;
677    error_scope() { PyErr_Fetch(&type, &value, &trace); }
678    ~error_scope() { PyErr_Restore(type, value, trace); }
679};
680
681/// Dummy destructor wrapper that can be used to expose classes with a private destructor
682struct nodelete { template <typename T> void operator()(T*) { } };
683
684// overload_cast requires variable templates: C++14 or MSVC
685#if defined(PYBIND11_CPP14) || defined(_MSC_VER)
686#define PYBIND11_OVERLOAD_CAST 1
687
688NAMESPACE_BEGIN(detail)
689template <typename... Args>
690struct overload_cast_impl {
691    template <typename Return>
692    constexpr auto operator()(Return (*pf)(Args...)) const noexcept
693                              -> decltype(pf) { return pf; }
694
695    template <typename Return, typename Class>
696    constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
697                              -> decltype(pmf) { return pmf; }
698
699    template <typename Return, typename Class>
700    constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
701                              -> decltype(pmf) { return pmf; }
702};
703NAMESPACE_END(detail)
704
705/// Syntax sugar for resolving overloaded function pointers:
706///  - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
707///  - sweet:   overload_cast<Arg0, Arg1, Arg2>(&Class::func)
708template <typename... Args>
709static constexpr detail::overload_cast_impl<Args...> overload_cast = {};
710// MSVC 2015 only accepts this particular initialization syntax for this variable template.
711
712/// Const member function selector for overload_cast
713///  - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
714///  - sweet:   overload_cast<Arg>(&Class::func, const_)
715static constexpr auto const_ = std::true_type{};
716
717#endif // overload_cast
718
719NAMESPACE_END(pybind11)
720