common.h revision 12391:ceeca8b41e4b
1/*
2    pybind11/detail/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// Robust support for some features and loading modules compiled against different pybind versions
20// requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute on
21// the main `pybind11` namespace.
22#if !defined(PYBIND11_NAMESPACE)
23#  ifdef __GNUG__
24#    define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
25#  else
26#    define PYBIND11_NAMESPACE pybind11
27#  endif
28#endif
29
30#if !defined(_MSC_VER) && !defined(__INTEL_COMPILER)
31#  if __cplusplus >= 201402L
32#    define PYBIND11_CPP14
33#    if __cplusplus > 201402L /* Temporary: should be updated to >= the final C++17 value once known */
34#      define PYBIND11_CPP17
35#    endif
36#  endif
37#elif defined(_MSC_VER)
38// MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully implemented)
39#  if _MSVC_LANG >= 201402L
40#    define PYBIND11_CPP14
41#    if _MSVC_LANG > 201402L && _MSC_VER >= 1910
42#      define PYBIND11_CPP17
43#    endif
44#  endif
45#endif
46
47// Compiler version assertions
48#if defined(__INTEL_COMPILER)
49#  if __INTEL_COMPILER < 1500
50#    error pybind11 requires Intel C++ compiler v15 or newer
51#  endif
52#elif defined(__clang__) && !defined(__apple_build_version__)
53#  if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
54#    error pybind11 requires clang 3.3 or newer
55#  endif
56#elif defined(__clang__)
57// Apple changes clang version macros to its Xcode version; the first Xcode release based on
58// (upstream) clang 3.3 was Xcode 5:
59#  if __clang_major__ < 5
60#    error pybind11 requires Xcode/clang 5.0 or newer
61#  endif
62#elif defined(__GNUG__)
63#  if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
64#    error pybind11 requires gcc 4.8 or newer
65#  endif
66#elif defined(_MSC_VER)
67// Pybind hits various compiler bugs in 2015u2 and earlier, and also makes use of some stl features
68// (e.g. std::negation) added in 2015u3:
69#  if _MSC_FULL_VER < 190024210
70#    error pybind11 requires MSVC 2015 update 3 or newer
71#  endif
72#endif
73
74#if !defined(PYBIND11_EXPORT)
75#  if defined(WIN32) || defined(_WIN32)
76#    define PYBIND11_EXPORT __declspec(dllexport)
77#  else
78#    define PYBIND11_EXPORT __attribute__ ((visibility("default")))
79#  endif
80#endif
81
82#if defined(_MSC_VER)
83#  define PYBIND11_NOINLINE __declspec(noinline)
84#else
85#  define PYBIND11_NOINLINE __attribute__ ((noinline))
86#endif
87
88#if defined(PYBIND11_CPP14)
89#  define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
90#else
91#  define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
92#endif
93
94#define PYBIND11_VERSION_MAJOR 2
95#define PYBIND11_VERSION_MINOR 2
96#define PYBIND11_VERSION_PATCH 1
97
98/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
99#if defined(_MSC_VER)
100#  if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 4)
101#    define HAVE_ROUND 1
102#  endif
103#  pragma warning(push)
104#  pragma warning(disable: 4510 4610 4512 4005)
105#  if defined(_DEBUG)
106#    define PYBIND11_DEBUG_MARKER
107#    undef _DEBUG
108#  endif
109#endif
110
111#include <Python.h>
112#include <frameobject.h>
113#include <pythread.h>
114
115#if defined(_WIN32) && (defined(min) || defined(max))
116#  error Macro clash with min and max -- define NOMINMAX when compiling your program on Windows
117#endif
118
119#if defined(isalnum)
120#  undef isalnum
121#  undef isalpha
122#  undef islower
123#  undef isspace
124#  undef isupper
125#  undef tolower
126#  undef toupper
127#endif
128
129#if defined(_MSC_VER)
130#  if defined(PYBIND11_DEBUG_MARKER)
131#    define _DEBUG
132#    undef PYBIND11_DEBUG_MARKER
133#  endif
134#  pragma warning(pop)
135#endif
136
137#include <cstddef>
138#include <cstring>
139#include <forward_list>
140#include <vector>
141#include <string>
142#include <stdexcept>
143#include <unordered_set>
144#include <unordered_map>
145#include <memory>
146#include <typeindex>
147#include <type_traits>
148
149#if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
150#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
151#define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
152#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
153#define PYBIND11_BYTES_CHECK PyBytes_Check
154#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
155#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
156#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
157#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
158#define PYBIND11_BYTES_SIZE PyBytes_Size
159#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
160#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
161#define PYBIND11_BYTES_NAME "bytes"
162#define PYBIND11_STRING_NAME "str"
163#define PYBIND11_SLICE_OBJECT PyObject
164#define PYBIND11_FROM_STRING PyUnicode_FromString
165#define PYBIND11_STR_TYPE ::pybind11::str
166#define PYBIND11_BOOL_ATTR "__bool__"
167#define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
168#define PYBIND11_PLUGIN_IMPL(name) \
169    extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
170
171#else
172#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
173#define PYBIND11_INSTANCE_METHOD_CHECK PyMethod_Check
174#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyMethod_GET_FUNCTION
175#define PYBIND11_BYTES_CHECK PyString_Check
176#define PYBIND11_BYTES_FROM_STRING PyString_FromString
177#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
178#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
179#define PYBIND11_BYTES_AS_STRING PyString_AsString
180#define PYBIND11_BYTES_SIZE PyString_Size
181#define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
182#define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
183#define PYBIND11_BYTES_NAME "str"
184#define PYBIND11_STRING_NAME "unicode"
185#define PYBIND11_SLICE_OBJECT PySliceObject
186#define PYBIND11_FROM_STRING PyString_FromString
187#define PYBIND11_STR_TYPE ::pybind11::bytes
188#define PYBIND11_BOOL_ATTR "__nonzero__"
189#define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_nonzero)
190#define PYBIND11_PLUGIN_IMPL(name) \
191    static PyObject *pybind11_init_wrapper();               \
192    extern "C" PYBIND11_EXPORT void init##name() {          \
193        (void)pybind11_init_wrapper();                      \
194    }                                                       \
195    PyObject *pybind11_init_wrapper()
196#endif
197
198#if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
199extern "C" {
200    struct _Py_atomic_address { void *value; };
201    PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
202}
203#endif
204
205#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
206#define PYBIND11_STRINGIFY(x) #x
207#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
208#define PYBIND11_CONCAT(first, second) first##second
209
210/** \rst
211    ***Deprecated in favor of PYBIND11_MODULE***
212
213    This macro creates the entry point that will be invoked when the Python interpreter
214    imports a plugin library. Please create a `module` in the function body and return
215    the pointer to its underlying Python object at the end.
216
217    .. code-block:: cpp
218
219        PYBIND11_PLUGIN(example) {
220            pybind11::module m("example", "pybind11 example plugin");
221            /// Set up bindings here
222            return m.ptr();
223        }
224\endrst */
225#define PYBIND11_PLUGIN(name)                                                  \
226    PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE")  \
227    static PyObject *pybind11_init();                                          \
228    PYBIND11_PLUGIN_IMPL(name) {                                               \
229        int major, minor;                                                      \
230        if (sscanf(Py_GetVersion(), "%i.%i", &major, &minor) != 2) {           \
231            PyErr_SetString(PyExc_ImportError, "Can't parse Python version."); \
232            return nullptr;                                                    \
233        } else if (major != PY_MAJOR_VERSION || minor != PY_MINOR_VERSION) {   \
234            PyErr_Format(PyExc_ImportError,                                    \
235                         "Python version mismatch: module was compiled for "   \
236                         "version %i.%i, while the interpreter is running "    \
237                         "version %i.%i.", PY_MAJOR_VERSION, PY_MINOR_VERSION, \
238                         major, minor);                                        \
239            return nullptr;                                                    \
240        }                                                                      \
241        try {                                                                  \
242            return pybind11_init();                                            \
243        } catch (pybind11::error_already_set &e) {                             \
244            PyErr_SetString(PyExc_ImportError, e.what());                      \
245            return nullptr;                                                    \
246        } catch (const std::exception &e) {                                    \
247            PyErr_SetString(PyExc_ImportError, e.what());                      \
248            return nullptr;                                                    \
249        }                                                                      \
250    }                                                                          \
251    PyObject *pybind11_init()
252
253/** \rst
254    This macro creates the entry point that will be invoked when the Python interpreter
255    imports an extension module. The module name is given as the fist argument and it
256    should not be in quotes. The second macro argument defines a variable of type
257    `py::module` which can be used to initialize the module.
258
259    .. code-block:: cpp
260
261        PYBIND11_MODULE(example, m) {
262            m.doc() = "pybind11 example module";
263
264            // Add bindings here
265            m.def("foo", []() {
266                return "Hello, World!";
267            });
268        }
269\endrst */
270#define PYBIND11_MODULE(name, variable)                                        \
271    static void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &);     \
272    PYBIND11_PLUGIN_IMPL(name) {                                               \
273        int major, minor;                                                      \
274        if (sscanf(Py_GetVersion(), "%i.%i", &major, &minor) != 2) {           \
275            PyErr_SetString(PyExc_ImportError, "Can't parse Python version."); \
276            return nullptr;                                                    \
277        } else if (major != PY_MAJOR_VERSION || minor != PY_MINOR_VERSION) {   \
278            PyErr_Format(PyExc_ImportError,                                    \
279                         "Python version mismatch: module was compiled for "   \
280                         "version %i.%i, while the interpreter is running "    \
281                         "version %i.%i.", PY_MAJOR_VERSION, PY_MINOR_VERSION, \
282                         major, minor);                                        \
283            return nullptr;                                                    \
284        }                                                                      \
285        auto m = pybind11::module(PYBIND11_TOSTRING(name));                    \
286        try {                                                                  \
287            PYBIND11_CONCAT(pybind11_init_, name)(m);                          \
288            return m.ptr();                                                    \
289        } catch (pybind11::error_already_set &e) {                             \
290            PyErr_SetString(PyExc_ImportError, e.what());                      \
291            return nullptr;                                                    \
292        } catch (const std::exception &e) {                                    \
293            PyErr_SetString(PyExc_ImportError, e.what());                      \
294            return nullptr;                                                    \
295        }                                                                      \
296    }                                                                          \
297    void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &variable)
298
299
300NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
301
302using ssize_t = Py_ssize_t;
303using size_t  = std::size_t;
304
305/// Approach used to cast a previously unknown C++ instance into a Python object
306enum class return_value_policy : uint8_t {
307    /** This is the default return value policy, which falls back to the policy
308        return_value_policy::take_ownership when the return value is a pointer.
309        Otherwise, it uses return_value::move or return_value::copy for rvalue
310        and lvalue references, respectively. See below for a description of what
311        all of these different policies do. */
312    automatic = 0,
313
314    /** As above, but use policy return_value_policy::reference when the return
315        value is a pointer. This is the default conversion policy for function
316        arguments when calling Python functions manually from C++ code (i.e. via
317        handle::operator()). You probably won't need to use this. */
318    automatic_reference,
319
320    /** Reference an existing object (i.e. do not create a new copy) and take
321        ownership. Python will call the destructor and delete operator when the
322        object’s reference count reaches zero. Undefined behavior ensues when
323        the C++ side does the same.. */
324    take_ownership,
325
326    /** Create a new copy of the returned object, which will be owned by
327        Python. This policy is comparably safe because the lifetimes of the two
328        instances are decoupled. */
329    copy,
330
331    /** Use std::move to move the return value contents into a new instance
332        that will be owned by Python. This policy is comparably safe because the
333        lifetimes of the two instances (move source and destination) are
334        decoupled. */
335    move,
336
337    /** Reference an existing object, but do not take ownership. The C++ side
338        is responsible for managing the object’s lifetime and deallocating it
339        when it is no longer used. Warning: undefined behavior will ensue when
340        the C++ side deletes an object that is still referenced and used by
341        Python. */
342    reference,
343
344    /** This policy only applies to methods and properties. It references the
345        object without taking ownership similar to the above
346        return_value_policy::reference policy. In contrast to that policy, the
347        function or property’s implicit this argument (called the parent) is
348        considered to be the the owner of the return value (the child).
349        pybind11 then couples the lifetime of the parent to the child via a
350        reference relationship that ensures that the parent cannot be garbage
351        collected while Python is still using the child. More advanced
352        variations of this scheme are also possible using combinations of
353        return_value_policy::reference and the keep_alive call policy */
354    reference_internal
355};
356
357NAMESPACE_BEGIN(detail)
358
359inline static constexpr int log2(size_t n, int k = 0) { return (n <= 1) ? k : log2(n >> 1, k + 1); }
360
361// Returns the size as a multiple of sizeof(void *), rounded up.
362inline static constexpr size_t size_in_ptrs(size_t s) { return 1 + ((s - 1) >> log2(sizeof(void *))); }
363
364/**
365 * The space to allocate for simple layout instance holders (see below) in multiple of the size of
366 * a pointer (e.g.  2 means 16 bytes on 64-bit architectures).  The default is the minimum required
367 * to holder either a std::unique_ptr or std::shared_ptr (which is almost always
368 * sizeof(std::shared_ptr<T>)).
369 */
370constexpr size_t instance_simple_holder_in_ptrs() {
371    static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
372            "pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
373    return size_in_ptrs(sizeof(std::shared_ptr<int>));
374}
375
376// Forward declarations
377struct type_info;
378struct value_and_holder;
379
380/// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
381struct instance {
382    PyObject_HEAD
383    /// Storage for pointers and holder; see simple_layout, below, for a description
384    union {
385        void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
386        struct {
387            void **values_and_holders;
388            uint8_t *status;
389        } nonsimple;
390    };
391    /// Weak references (needed for keep alive):
392    PyObject *weakrefs;
393    /// If true, the pointer is owned which means we're free to manage it with a holder.
394    bool owned : 1;
395    /**
396     * An instance has two possible value/holder layouts.
397     *
398     * Simple layout (when this flag is true), means the `simple_value_holder` is set with a pointer
399     * and the holder object governing that pointer, i.e. [val1*][holder].  This layout is applied
400     * whenever there is no python-side multiple inheritance of bound C++ types *and* the type's
401     * holder will fit in the default space (which is large enough to hold either a std::unique_ptr
402     * or std::shared_ptr).
403     *
404     * Non-simple layout applies when using custom holders that require more space than `shared_ptr`
405     * (which is typically the size of two pointers), or when multiple inheritance is used on the
406     * python side.  Non-simple layout allocates the required amount of memory to have multiple
407     * bound C++ classes as parents.  Under this layout, `nonsimple.values_and_holders` is set to a
408     * pointer to allocated space of the required space to hold a a sequence of value pointers and
409     * holders followed `status`, a set of bit flags (1 byte each), i.e.
410     * [val1*][holder1][val2*][holder2]...[bb...]  where each [block] is rounded up to a multiple of
411     * `sizeof(void *)`.  `nonsimple.holder_constructed` is, for convenience, a pointer to the
412     * beginning of the [bb...] block (but not independently allocated).
413     *
414     * Status bits indicate whether the associated holder is constructed (&
415     * status_holder_constructed) and whether the value pointer is registered (&
416     * status_instance_registered) in `registered_instances`.
417     */
418    bool simple_layout : 1;
419    /// For simple layout, tracks whether the holder has been constructed
420    bool simple_holder_constructed : 1;
421    /// For simple layout, tracks whether the instance is registered in `registered_instances`
422    bool simple_instance_registered : 1;
423    /// If true, get_internals().patients has an entry for this object
424    bool has_patients : 1;
425
426    /// Initializes all of the above type/values/holders data (but not the instance values themselves)
427    void allocate_layout();
428
429    /// Destroys/deallocates all of the above
430    void deallocate_layout();
431
432    /// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
433    /// omitted).  Returns a default-constructed (with `.inst = nullptr`) object on failure if
434    /// `throw_if_missing` is false.
435    value_and_holder get_value_and_holder(const type_info *find_type = nullptr, bool throw_if_missing = true);
436
437    /// Bit values for the non-simple status flags
438    static constexpr uint8_t status_holder_constructed  = 1;
439    static constexpr uint8_t status_instance_registered = 2;
440};
441
442static_assert(std::is_standard_layout<instance>::value, "Internal error: `pybind11::detail::instance` is not standard layout!");
443
444/// from __cpp_future__ import (convenient aliases from C++14/17)
445#if defined(PYBIND11_CPP14) && (!defined(_MSC_VER) || _MSC_VER >= 1910)
446using std::enable_if_t;
447using std::conditional_t;
448using std::remove_cv_t;
449using std::remove_reference_t;
450#else
451template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
452template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
453template <typename T> using remove_cv_t = typename std::remove_cv<T>::type;
454template <typename T> using remove_reference_t = typename std::remove_reference<T>::type;
455#endif
456
457/// Index sequences
458#if defined(PYBIND11_CPP14)
459using std::index_sequence;
460using std::make_index_sequence;
461#else
462template<size_t ...> struct index_sequence  { };
463template<size_t N, size_t ...S> struct make_index_sequence_impl : make_index_sequence_impl <N - 1, N - 1, S...> { };
464template<size_t ...S> struct make_index_sequence_impl <0, S...> { typedef index_sequence<S...> type; };
465template<size_t N> using make_index_sequence = typename make_index_sequence_impl<N>::type;
466#endif
467
468/// Make an index sequence of the indices of true arguments
469template <typename ISeq, size_t, bool...> struct select_indices_impl { using type = ISeq; };
470template <size_t... IPrev, size_t I, bool B, bool... Bs> struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
471    : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>, I + 1, Bs...> {};
472template <bool... Bs> using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
473
474/// Backports of std::bool_constant and std::negation to accomodate older compilers
475template <bool B> using bool_constant = std::integral_constant<bool, B>;
476template <typename T> struct negation : bool_constant<!T::value> { };
477
478template <typename...> struct void_t_impl { using type = void; };
479template <typename... Ts> using void_t = typename void_t_impl<Ts...>::type;
480
481/// Compile-time all/any/none of that check the boolean value of all template types
482#ifdef __cpp_fold_expressions
483template <class... Ts> using all_of = bool_constant<(Ts::value && ...)>;
484template <class... Ts> using any_of = bool_constant<(Ts::value || ...)>;
485#elif !defined(_MSC_VER)
486template <bool...> struct bools {};
487template <class... Ts> using all_of = std::is_same<
488    bools<Ts::value..., true>,
489    bools<true, Ts::value...>>;
490template <class... Ts> using any_of = negation<all_of<negation<Ts>...>>;
491#else
492// MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
493// at a slight loss of compilation efficiency).
494template <class... Ts> using all_of = std::conjunction<Ts...>;
495template <class... Ts> using any_of = std::disjunction<Ts...>;
496#endif
497template <class... Ts> using none_of = negation<any_of<Ts...>>;
498
499template <class T, template<class> class... Predicates> using satisfies_all_of = all_of<Predicates<T>...>;
500template <class T, template<class> class... Predicates> using satisfies_any_of = any_of<Predicates<T>...>;
501template <class T, template<class> class... Predicates> using satisfies_none_of = none_of<Predicates<T>...>;
502
503/// Strip the class from a method type
504template <typename T> struct remove_class { };
505template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
506template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
507
508/// Helper template to strip away type modifiers
509template <typename T> struct intrinsic_type                       { typedef T type; };
510template <typename T> struct intrinsic_type<const T>              { typedef typename intrinsic_type<T>::type type; };
511template <typename T> struct intrinsic_type<T*>                   { typedef typename intrinsic_type<T>::type type; };
512template <typename T> struct intrinsic_type<T&>                   { typedef typename intrinsic_type<T>::type type; };
513template <typename T> struct intrinsic_type<T&&>                  { typedef typename intrinsic_type<T>::type type; };
514template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
515template <typename T, size_t N> struct intrinsic_type<T[N]>       { typedef typename intrinsic_type<T>::type type; };
516template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
517
518/// Helper type to replace 'void' in some expressions
519struct void_type { };
520
521/// Helper template which holds a list of types
522template <typename...> struct type_list { };
523
524/// Compile-time integer sum
525#ifdef __cpp_fold_expressions
526template <typename... Ts> constexpr size_t constexpr_sum(Ts... ns) { return (0 + ... + size_t{ns}); }
527#else
528constexpr size_t constexpr_sum() { return 0; }
529template <typename T, typename... Ts>
530constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
531#endif
532
533NAMESPACE_BEGIN(constexpr_impl)
534/// Implementation details for constexpr functions
535constexpr int first(int i) { return i; }
536template <typename T, typename... Ts>
537constexpr int first(int i, T v, Ts... vs) { return v ? i : first(i + 1, vs...); }
538
539constexpr int last(int /*i*/, int result) { return result; }
540template <typename T, typename... Ts>
541constexpr int last(int i, int result, T v, Ts... vs) { return last(i + 1, v ? i : result, vs...); }
542NAMESPACE_END(constexpr_impl)
543
544/// Return the index of the first type in Ts which satisfies Predicate<T>.  Returns sizeof...(Ts) if
545/// none match.
546template <template<typename> class Predicate, typename... Ts>
547constexpr int constexpr_first() { return constexpr_impl::first(0, Predicate<Ts>::value...); }
548
549/// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
550template <template<typename> class Predicate, typename... Ts>
551constexpr int constexpr_last() { return constexpr_impl::last(0, -1, Predicate<Ts>::value...); }
552
553/// Return the Nth element from the parameter pack
554template <size_t N, typename T, typename... Ts>
555struct pack_element { using type = typename pack_element<N - 1, Ts...>::type; };
556template <typename T, typename... Ts>
557struct pack_element<0, T, Ts...> { using type = T; };
558
559/// Return the one and only type which matches the predicate, or Default if none match.
560/// If more than one type matches the predicate, fail at compile-time.
561template <template<typename> class Predicate, typename Default, typename... Ts>
562struct exactly_one {
563    static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
564    static_assert(found <= 1, "Found more than one type matching the predicate");
565
566    static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
567    using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
568};
569template <template<typename> class P, typename Default>
570struct exactly_one<P, Default> { using type = Default; };
571
572template <template<typename> class Predicate, typename Default, typename... Ts>
573using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
574
575/// Defer the evaluation of type T until types Us are instantiated
576template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
577template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
578
579/// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
580/// unlike `std::is_base_of`)
581template <typename Base, typename Derived> using is_strict_base_of = bool_constant<
582    std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
583
584template <template<typename...> class Base>
585struct is_template_base_of_impl {
586    template <typename... Us> static std::true_type check(Base<Us...> *);
587    static std::false_type check(...);
588};
589
590/// Check if a template is the base of a type. For example:
591/// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
592template <template<typename...> class Base, typename T>
593#if !defined(_MSC_VER)
594using is_template_base_of = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr));
595#else // MSVC2015 has trouble with decltype in template aliases
596struct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr)) { };
597#endif
598
599/// Check if T is an instantiation of the template `Class`. For example:
600/// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
601template <template<typename...> class Class, typename T>
602struct is_instantiation : std::false_type { };
603template <template<typename...> class Class, typename... Us>
604struct is_instantiation<Class, Class<Us...>> : std::true_type { };
605
606/// Check if T is std::shared_ptr<U> where U can be anything
607template <typename T> using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
608
609/// Check if T looks like an input iterator
610template <typename T, typename = void> struct is_input_iterator : std::false_type {};
611template <typename T>
612struct is_input_iterator<T, void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
613    : std::true_type {};
614
615template <typename T> using is_function_pointer = bool_constant<
616    std::is_pointer<T>::value && std::is_function<typename std::remove_pointer<T>::type>::value>;
617
618template <typename F> struct strip_function_object {
619    using type = typename remove_class<decltype(&F::operator())>::type;
620};
621
622// Extracts the function signature from a function, function pointer or lambda.
623template <typename Function, typename F = remove_reference_t<Function>>
624using function_signature_t = conditional_t<
625    std::is_function<F>::value,
626    F,
627    typename conditional_t<
628        std::is_pointer<F>::value || std::is_member_pointer<F>::value,
629        std::remove_pointer<F>,
630        strip_function_object<F>
631    >::type
632>;
633
634/// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
635/// pointer.  Note that this can catch all sorts of other things, too; this is intended to be used
636/// in a place where passing a lambda makes sense.
637template <typename T> using is_lambda = satisfies_none_of<remove_reference_t<T>,
638        std::is_function, std::is_pointer, std::is_member_pointer>;
639
640/// Ignore that a variable is unused in compiler warnings
641inline void ignore_unused(const int *) { }
642
643/// Apply a function over each element of a parameter pack
644#ifdef __cpp_fold_expressions
645#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
646#else
647using expand_side_effects = bool[];
648#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) pybind11::detail::expand_side_effects{ ((PATTERN), void(), false)..., false }
649#endif
650
651NAMESPACE_END(detail)
652
653/// C++ bindings of builtin Python exceptions
654class builtin_exception : public std::runtime_error {
655public:
656    using std::runtime_error::runtime_error;
657    /// Set the error using the Python C API
658    virtual void set_error() const = 0;
659};
660
661#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
662    class name : public builtin_exception { public: \
663        using builtin_exception::builtin_exception; \
664        name() : name("") { } \
665        void set_error() const override { PyErr_SetString(type, what()); } \
666    };
667
668PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
669PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
670PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
671PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
672PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
673PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
674PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
675
676[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
677[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
678
679template <typename T, typename SFINAE = void> struct format_descriptor { };
680
681NAMESPACE_BEGIN(detail)
682// Returns the index of the given type in the type char array below, and in the list in numpy.h
683// The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
684// complex float,double,long double.  Note that the long double types only participate when long
685// double is actually longer than double (it isn't under MSVC).
686// NB: not only the string below but also complex.h and numpy.h rely on this order.
687template <typename T, typename SFINAE = void> struct is_fmt_numeric { static constexpr bool value = false; };
688template <typename T> struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
689    static constexpr bool value = true;
690    static constexpr int index = std::is_same<T, bool>::value ? 0 : 1 + (
691        std::is_integral<T>::value ? detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value : 8 + (
692        std::is_same<T, double>::value ? 1 : std::is_same<T, long double>::value ? 2 : 0));
693};
694NAMESPACE_END(detail)
695
696template <typename T> struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
697    static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
698    static constexpr const char value[2] = { c, '\0' };
699    static std::string format() { return std::string(1, c); }
700};
701
702template <typename T> constexpr const char format_descriptor<
703    T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
704
705/// RAII wrapper that temporarily clears any Python error state
706struct error_scope {
707    PyObject *type, *value, *trace;
708    error_scope() { PyErr_Fetch(&type, &value, &trace); }
709    ~error_scope() { PyErr_Restore(type, value, trace); }
710};
711
712/// Dummy destructor wrapper that can be used to expose classes with a private destructor
713struct nodelete { template <typename T> void operator()(T*) { } };
714
715// overload_cast requires variable templates: C++14
716#if defined(PYBIND11_CPP14)
717#define PYBIND11_OVERLOAD_CAST 1
718
719NAMESPACE_BEGIN(detail)
720template <typename... Args>
721struct overload_cast_impl {
722    constexpr overload_cast_impl() {} // MSVC 2015 needs this
723
724    template <typename Return>
725    constexpr auto operator()(Return (*pf)(Args...)) const noexcept
726                              -> decltype(pf) { return pf; }
727
728    template <typename Return, typename Class>
729    constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
730                              -> decltype(pmf) { return pmf; }
731
732    template <typename Return, typename Class>
733    constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
734                              -> decltype(pmf) { return pmf; }
735};
736NAMESPACE_END(detail)
737
738/// Syntax sugar for resolving overloaded function pointers:
739///  - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
740///  - sweet:   overload_cast<Arg0, Arg1, Arg2>(&Class::func)
741template <typename... Args>
742static constexpr detail::overload_cast_impl<Args...> overload_cast = {};
743// MSVC 2015 only accepts this particular initialization syntax for this variable template.
744
745/// Const member function selector for overload_cast
746///  - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
747///  - sweet:   overload_cast<Arg>(&Class::func, const_)
748static constexpr auto const_ = std::true_type{};
749
750#else // no overload_cast: providing something that static_assert-fails:
751template <typename... Args> struct overload_cast {
752    static_assert(detail::deferred_t<std::false_type, Args...>::value,
753                  "pybind11::overload_cast<...> requires compiling in C++14 mode");
754};
755#endif // overload_cast
756
757NAMESPACE_BEGIN(detail)
758
759// Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
760// any standard container (or C-style array) supporting std::begin/std::end, any singleton
761// arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
762template <typename T>
763class any_container {
764    std::vector<T> v;
765public:
766    any_container() = default;
767
768    // Can construct from a pair of iterators
769    template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
770    any_container(It first, It last) : v(first, last) { }
771
772    // Implicit conversion constructor from any arbitrary container type with values convertible to T
773    template <typename Container, typename = enable_if_t<std::is_convertible<decltype(*std::begin(std::declval<const Container &>())), T>::value>>
774    any_container(const Container &c) : any_container(std::begin(c), std::end(c)) { }
775
776    // initializer_list's aren't deducible, so don't get matched by the above template; we need this
777    // to explicitly allow implicit conversion from one:
778    template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
779    any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) { }
780
781    // Avoid copying if given an rvalue vector of the correct type.
782    any_container(std::vector<T> &&v) : v(std::move(v)) { }
783
784    // Moves the vector out of an rvalue any_container
785    operator std::vector<T> &&() && { return std::move(v); }
786
787    // Dereferencing obtains a reference to the underlying vector
788    std::vector<T> &operator*() { return v; }
789    const std::vector<T> &operator*() const { return v; }
790
791    // -> lets you call methods on the underlying vector
792    std::vector<T> *operator->() { return &v; }
793    const std::vector<T> *operator->() const { return &v; }
794};
795
796NAMESPACE_END(detail)
797
798
799
800NAMESPACE_END(PYBIND11_NAMESPACE)
801