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