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