112391Sjason@lowepower.com/*
212391Sjason@lowepower.com    pybind11/detail/common.h -- Basic macros
312391Sjason@lowepower.com
412391Sjason@lowepower.com    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
512391Sjason@lowepower.com
612391Sjason@lowepower.com    All rights reserved. Use of this source code is governed by a
712391Sjason@lowepower.com    BSD-style license that can be found in the LICENSE file.
812391Sjason@lowepower.com*/
912391Sjason@lowepower.com
1012391Sjason@lowepower.com#pragma once
1112391Sjason@lowepower.com
1212391Sjason@lowepower.com#if !defined(NAMESPACE_BEGIN)
1312391Sjason@lowepower.com#  define NAMESPACE_BEGIN(name) namespace name {
1412391Sjason@lowepower.com#endif
1512391Sjason@lowepower.com#if !defined(NAMESPACE_END)
1612391Sjason@lowepower.com#  define NAMESPACE_END(name) }
1712391Sjason@lowepower.com#endif
1812391Sjason@lowepower.com
1912391Sjason@lowepower.com// Robust support for some features and loading modules compiled against different pybind versions
2012391Sjason@lowepower.com// requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute on
2112391Sjason@lowepower.com// the main `pybind11` namespace.
2212391Sjason@lowepower.com#if !defined(PYBIND11_NAMESPACE)
2312391Sjason@lowepower.com#  ifdef __GNUG__
2412391Sjason@lowepower.com#    define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
2512391Sjason@lowepower.com#  else
2612391Sjason@lowepower.com#    define PYBIND11_NAMESPACE pybind11
2712391Sjason@lowepower.com#  endif
2812391Sjason@lowepower.com#endif
2912391Sjason@lowepower.com
3014299Sbbruce@ucdavis.edu#if !(defined(_MSC_VER) && __cplusplus == 199711L) && !defined(__INTEL_COMPILER)
3112391Sjason@lowepower.com#  if __cplusplus >= 201402L
3212391Sjason@lowepower.com#    define PYBIND11_CPP14
3314299Sbbruce@ucdavis.edu#    if __cplusplus >= 201703L
3412391Sjason@lowepower.com#      define PYBIND11_CPP17
3512391Sjason@lowepower.com#    endif
3612391Sjason@lowepower.com#  endif
3714299Sbbruce@ucdavis.edu#elif defined(_MSC_VER) && __cplusplus == 199711L
3812391Sjason@lowepower.com// MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully implemented)
3914299Sbbruce@ucdavis.edu// Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3 or newer
4012391Sjason@lowepower.com#  if _MSVC_LANG >= 201402L
4112391Sjason@lowepower.com#    define PYBIND11_CPP14
4212391Sjason@lowepower.com#    if _MSVC_LANG > 201402L && _MSC_VER >= 1910
4312391Sjason@lowepower.com#      define PYBIND11_CPP17
4412391Sjason@lowepower.com#    endif
4512391Sjason@lowepower.com#  endif
4612391Sjason@lowepower.com#endif
4712391Sjason@lowepower.com
4812391Sjason@lowepower.com// Compiler version assertions
4912391Sjason@lowepower.com#if defined(__INTEL_COMPILER)
5014299Sbbruce@ucdavis.edu#  if __INTEL_COMPILER < 1700
5114299Sbbruce@ucdavis.edu#    error pybind11 requires Intel C++ compiler v17 or newer
5212391Sjason@lowepower.com#  endif
5312391Sjason@lowepower.com#elif defined(__clang__) && !defined(__apple_build_version__)
5412391Sjason@lowepower.com#  if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
5512391Sjason@lowepower.com#    error pybind11 requires clang 3.3 or newer
5612391Sjason@lowepower.com#  endif
5712391Sjason@lowepower.com#elif defined(__clang__)
5812391Sjason@lowepower.com// Apple changes clang version macros to its Xcode version; the first Xcode release based on
5912391Sjason@lowepower.com// (upstream) clang 3.3 was Xcode 5:
6012391Sjason@lowepower.com#  if __clang_major__ < 5
6112391Sjason@lowepower.com#    error pybind11 requires Xcode/clang 5.0 or newer
6212391Sjason@lowepower.com#  endif
6312391Sjason@lowepower.com#elif defined(__GNUG__)
6412391Sjason@lowepower.com#  if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
6512391Sjason@lowepower.com#    error pybind11 requires gcc 4.8 or newer
6612391Sjason@lowepower.com#  endif
6712391Sjason@lowepower.com#elif defined(_MSC_VER)
6812391Sjason@lowepower.com// Pybind hits various compiler bugs in 2015u2 and earlier, and also makes use of some stl features
6912391Sjason@lowepower.com// (e.g. std::negation) added in 2015u3:
7012391Sjason@lowepower.com#  if _MSC_FULL_VER < 190024210
7112391Sjason@lowepower.com#    error pybind11 requires MSVC 2015 update 3 or newer
7212391Sjason@lowepower.com#  endif
7312391Sjason@lowepower.com#endif
7412391Sjason@lowepower.com
7512391Sjason@lowepower.com#if !defined(PYBIND11_EXPORT)
7612391Sjason@lowepower.com#  if defined(WIN32) || defined(_WIN32)
7712391Sjason@lowepower.com#    define PYBIND11_EXPORT __declspec(dllexport)
7812391Sjason@lowepower.com#  else
7912391Sjason@lowepower.com#    define PYBIND11_EXPORT __attribute__ ((visibility("default")))
8012391Sjason@lowepower.com#  endif
8112391Sjason@lowepower.com#endif
8212391Sjason@lowepower.com
8312391Sjason@lowepower.com#if defined(_MSC_VER)
8412391Sjason@lowepower.com#  define PYBIND11_NOINLINE __declspec(noinline)
8512391Sjason@lowepower.com#else
8612391Sjason@lowepower.com#  define PYBIND11_NOINLINE __attribute__ ((noinline))
8712391Sjason@lowepower.com#endif
8812391Sjason@lowepower.com
8912391Sjason@lowepower.com#if defined(PYBIND11_CPP14)
9012391Sjason@lowepower.com#  define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
9112391Sjason@lowepower.com#else
9212391Sjason@lowepower.com#  define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
9312391Sjason@lowepower.com#endif
9412391Sjason@lowepower.com
9512391Sjason@lowepower.com#define PYBIND11_VERSION_MAJOR 2
9614299Sbbruce@ucdavis.edu#define PYBIND11_VERSION_MINOR 4
9712391Sjason@lowepower.com#define PYBIND11_VERSION_PATCH 1
9812391Sjason@lowepower.com
9912391Sjason@lowepower.com/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
10012391Sjason@lowepower.com#if defined(_MSC_VER)
10112391Sjason@lowepower.com#  if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 4)
10212391Sjason@lowepower.com#    define HAVE_ROUND 1
10312391Sjason@lowepower.com#  endif
10412391Sjason@lowepower.com#  pragma warning(push)
10512391Sjason@lowepower.com#  pragma warning(disable: 4510 4610 4512 4005)
10612391Sjason@lowepower.com#  if defined(_DEBUG)
10712391Sjason@lowepower.com#    define PYBIND11_DEBUG_MARKER
10812391Sjason@lowepower.com#    undef _DEBUG
10912391Sjason@lowepower.com#  endif
11012391Sjason@lowepower.com#endif
11112391Sjason@lowepower.com
11212391Sjason@lowepower.com#include <Python.h>
11312391Sjason@lowepower.com#include <frameobject.h>
11412391Sjason@lowepower.com#include <pythread.h>
11512391Sjason@lowepower.com
11612391Sjason@lowepower.com#if defined(isalnum)
11712391Sjason@lowepower.com#  undef isalnum
11812391Sjason@lowepower.com#  undef isalpha
11912391Sjason@lowepower.com#  undef islower
12012391Sjason@lowepower.com#  undef isspace
12112391Sjason@lowepower.com#  undef isupper
12212391Sjason@lowepower.com#  undef tolower
12312391Sjason@lowepower.com#  undef toupper
12412391Sjason@lowepower.com#endif
12512391Sjason@lowepower.com
12612391Sjason@lowepower.com#if defined(_MSC_VER)
12712391Sjason@lowepower.com#  if defined(PYBIND11_DEBUG_MARKER)
12812391Sjason@lowepower.com#    define _DEBUG
12912391Sjason@lowepower.com#    undef PYBIND11_DEBUG_MARKER
13012391Sjason@lowepower.com#  endif
13112391Sjason@lowepower.com#  pragma warning(pop)
13212391Sjason@lowepower.com#endif
13312391Sjason@lowepower.com
13412391Sjason@lowepower.com#include <cstddef>
13512391Sjason@lowepower.com#include <cstring>
13612391Sjason@lowepower.com#include <forward_list>
13712391Sjason@lowepower.com#include <vector>
13812391Sjason@lowepower.com#include <string>
13912391Sjason@lowepower.com#include <stdexcept>
14012391Sjason@lowepower.com#include <unordered_set>
14112391Sjason@lowepower.com#include <unordered_map>
14212391Sjason@lowepower.com#include <memory>
14312391Sjason@lowepower.com#include <typeindex>
14412391Sjason@lowepower.com#include <type_traits>
14512391Sjason@lowepower.com
14612391Sjason@lowepower.com#if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
14712391Sjason@lowepower.com#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
14812391Sjason@lowepower.com#define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
14912391Sjason@lowepower.com#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
15012391Sjason@lowepower.com#define PYBIND11_BYTES_CHECK PyBytes_Check
15112391Sjason@lowepower.com#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
15212391Sjason@lowepower.com#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
15312391Sjason@lowepower.com#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
15412391Sjason@lowepower.com#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
15512391Sjason@lowepower.com#define PYBIND11_BYTES_SIZE PyBytes_Size
15612391Sjason@lowepower.com#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
15712391Sjason@lowepower.com#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
15814299Sbbruce@ucdavis.edu#define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) o)
15914299Sbbruce@ucdavis.edu#define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) o)
16012391Sjason@lowepower.com#define PYBIND11_BYTES_NAME "bytes"
16112391Sjason@lowepower.com#define PYBIND11_STRING_NAME "str"
16212391Sjason@lowepower.com#define PYBIND11_SLICE_OBJECT PyObject
16312391Sjason@lowepower.com#define PYBIND11_FROM_STRING PyUnicode_FromString
16412391Sjason@lowepower.com#define PYBIND11_STR_TYPE ::pybind11::str
16512391Sjason@lowepower.com#define PYBIND11_BOOL_ATTR "__bool__"
16612391Sjason@lowepower.com#define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
16714299Sbbruce@ucdavis.edu// Providing a separate declaration to make Clang's -Wmissing-prototypes happy
16812391Sjason@lowepower.com#define PYBIND11_PLUGIN_IMPL(name) \
16914299Sbbruce@ucdavis.edu    extern "C" PYBIND11_EXPORT PyObject *PyInit_##name();   \
17012391Sjason@lowepower.com    extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
17112391Sjason@lowepower.com
17212391Sjason@lowepower.com#else
17312391Sjason@lowepower.com#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
17412391Sjason@lowepower.com#define PYBIND11_INSTANCE_METHOD_CHECK PyMethod_Check
17512391Sjason@lowepower.com#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyMethod_GET_FUNCTION
17612391Sjason@lowepower.com#define PYBIND11_BYTES_CHECK PyString_Check
17712391Sjason@lowepower.com#define PYBIND11_BYTES_FROM_STRING PyString_FromString
17812391Sjason@lowepower.com#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
17912391Sjason@lowepower.com#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
18012391Sjason@lowepower.com#define PYBIND11_BYTES_AS_STRING PyString_AsString
18112391Sjason@lowepower.com#define PYBIND11_BYTES_SIZE PyString_Size
18212391Sjason@lowepower.com#define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
18312391Sjason@lowepower.com#define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
18414299Sbbruce@ucdavis.edu#define PYBIND11_LONG_FROM_SIGNED(o) PyInt_FromSsize_t((ssize_t) o) // Returns long if needed.
18514299Sbbruce@ucdavis.edu#define PYBIND11_LONG_FROM_UNSIGNED(o) PyInt_FromSize_t((size_t) o) // Returns long if needed.
18612391Sjason@lowepower.com#define PYBIND11_BYTES_NAME "str"
18712391Sjason@lowepower.com#define PYBIND11_STRING_NAME "unicode"
18812391Sjason@lowepower.com#define PYBIND11_SLICE_OBJECT PySliceObject
18912391Sjason@lowepower.com#define PYBIND11_FROM_STRING PyString_FromString
19012391Sjason@lowepower.com#define PYBIND11_STR_TYPE ::pybind11::bytes
19112391Sjason@lowepower.com#define PYBIND11_BOOL_ATTR "__nonzero__"
19212391Sjason@lowepower.com#define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_nonzero)
19314299Sbbruce@ucdavis.edu// Providing a separate PyInit decl to make Clang's -Wmissing-prototypes happy
19412391Sjason@lowepower.com#define PYBIND11_PLUGIN_IMPL(name) \
19512391Sjason@lowepower.com    static PyObject *pybind11_init_wrapper();               \
19614299Sbbruce@ucdavis.edu    extern "C" PYBIND11_EXPORT void init##name();           \
19712391Sjason@lowepower.com    extern "C" PYBIND11_EXPORT void init##name() {          \
19812391Sjason@lowepower.com        (void)pybind11_init_wrapper();                      \
19912391Sjason@lowepower.com    }                                                       \
20012391Sjason@lowepower.com    PyObject *pybind11_init_wrapper()
20112391Sjason@lowepower.com#endif
20212391Sjason@lowepower.com
20312391Sjason@lowepower.com#if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
20412391Sjason@lowepower.comextern "C" {
20512391Sjason@lowepower.com    struct _Py_atomic_address { void *value; };
20612391Sjason@lowepower.com    PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
20712391Sjason@lowepower.com}
20812391Sjason@lowepower.com#endif
20912391Sjason@lowepower.com
21012391Sjason@lowepower.com#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
21112391Sjason@lowepower.com#define PYBIND11_STRINGIFY(x) #x
21212391Sjason@lowepower.com#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
21312391Sjason@lowepower.com#define PYBIND11_CONCAT(first, second) first##second
21412391Sjason@lowepower.com
21514299Sbbruce@ucdavis.edu#define PYBIND11_CHECK_PYTHON_VERSION \
21614299Sbbruce@ucdavis.edu    {                                                                          \
21714299Sbbruce@ucdavis.edu        const char *compiled_ver = PYBIND11_TOSTRING(PY_MAJOR_VERSION)         \
21814299Sbbruce@ucdavis.edu            "." PYBIND11_TOSTRING(PY_MINOR_VERSION);                           \
21914299Sbbruce@ucdavis.edu        const char *runtime_ver = Py_GetVersion();                             \
22014299Sbbruce@ucdavis.edu        size_t len = std::strlen(compiled_ver);                                \
22114299Sbbruce@ucdavis.edu        if (std::strncmp(runtime_ver, compiled_ver, len) != 0                  \
22214299Sbbruce@ucdavis.edu                || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) {     \
22314299Sbbruce@ucdavis.edu            PyErr_Format(PyExc_ImportError,                                    \
22414299Sbbruce@ucdavis.edu                "Python version mismatch: module was compiled for Python %s, " \
22514299Sbbruce@ucdavis.edu                "but the interpreter version is incompatible: %s.",            \
22614299Sbbruce@ucdavis.edu                compiled_ver, runtime_ver);                                    \
22714299Sbbruce@ucdavis.edu            return nullptr;                                                    \
22814299Sbbruce@ucdavis.edu        }                                                                      \
22914299Sbbruce@ucdavis.edu    }
23014299Sbbruce@ucdavis.edu
23114299Sbbruce@ucdavis.edu#define PYBIND11_CATCH_INIT_EXCEPTIONS \
23214299Sbbruce@ucdavis.edu        catch (pybind11::error_already_set &e) {                               \
23314299Sbbruce@ucdavis.edu            PyErr_SetString(PyExc_ImportError, e.what());                      \
23414299Sbbruce@ucdavis.edu            return nullptr;                                                    \
23514299Sbbruce@ucdavis.edu        } catch (const std::exception &e) {                                    \
23614299Sbbruce@ucdavis.edu            PyErr_SetString(PyExc_ImportError, e.what());                      \
23714299Sbbruce@ucdavis.edu            return nullptr;                                                    \
23814299Sbbruce@ucdavis.edu        }                                                                      \
23914299Sbbruce@ucdavis.edu
24012391Sjason@lowepower.com/** \rst
24112391Sjason@lowepower.com    ***Deprecated in favor of PYBIND11_MODULE***
24212391Sjason@lowepower.com
24312391Sjason@lowepower.com    This macro creates the entry point that will be invoked when the Python interpreter
24412391Sjason@lowepower.com    imports a plugin library. Please create a `module` in the function body and return
24512391Sjason@lowepower.com    the pointer to its underlying Python object at the end.
24612391Sjason@lowepower.com
24712391Sjason@lowepower.com    .. code-block:: cpp
24812391Sjason@lowepower.com
24912391Sjason@lowepower.com        PYBIND11_PLUGIN(example) {
25012391Sjason@lowepower.com            pybind11::module m("example", "pybind11 example plugin");
25112391Sjason@lowepower.com            /// Set up bindings here
25212391Sjason@lowepower.com            return m.ptr();
25312391Sjason@lowepower.com        }
25412391Sjason@lowepower.com\endrst */
25512391Sjason@lowepower.com#define PYBIND11_PLUGIN(name)                                                  \
25612391Sjason@lowepower.com    PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE")  \
25712391Sjason@lowepower.com    static PyObject *pybind11_init();                                          \
25812391Sjason@lowepower.com    PYBIND11_PLUGIN_IMPL(name) {                                               \
25914299Sbbruce@ucdavis.edu        PYBIND11_CHECK_PYTHON_VERSION                                          \
26012391Sjason@lowepower.com        try {                                                                  \
26112391Sjason@lowepower.com            return pybind11_init();                                            \
26214299Sbbruce@ucdavis.edu        } PYBIND11_CATCH_INIT_EXCEPTIONS                                       \
26312391Sjason@lowepower.com    }                                                                          \
26412391Sjason@lowepower.com    PyObject *pybind11_init()
26512391Sjason@lowepower.com
26612391Sjason@lowepower.com/** \rst
26712391Sjason@lowepower.com    This macro creates the entry point that will be invoked when the Python interpreter
26812391Sjason@lowepower.com    imports an extension module. The module name is given as the fist argument and it
26912391Sjason@lowepower.com    should not be in quotes. The second macro argument defines a variable of type
27012391Sjason@lowepower.com    `py::module` which can be used to initialize the module.
27112391Sjason@lowepower.com
27212391Sjason@lowepower.com    .. code-block:: cpp
27312391Sjason@lowepower.com
27412391Sjason@lowepower.com        PYBIND11_MODULE(example, m) {
27512391Sjason@lowepower.com            m.doc() = "pybind11 example module";
27612391Sjason@lowepower.com
27712391Sjason@lowepower.com            // Add bindings here
27812391Sjason@lowepower.com            m.def("foo", []() {
27912391Sjason@lowepower.com                return "Hello, World!";
28012391Sjason@lowepower.com            });
28112391Sjason@lowepower.com        }
28212391Sjason@lowepower.com\endrst */
28312391Sjason@lowepower.com#define PYBIND11_MODULE(name, variable)                                        \
28412391Sjason@lowepower.com    static void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &);     \
28512391Sjason@lowepower.com    PYBIND11_PLUGIN_IMPL(name) {                                               \
28614299Sbbruce@ucdavis.edu        PYBIND11_CHECK_PYTHON_VERSION                                          \
28712391Sjason@lowepower.com        auto m = pybind11::module(PYBIND11_TOSTRING(name));                    \
28812391Sjason@lowepower.com        try {                                                                  \
28912391Sjason@lowepower.com            PYBIND11_CONCAT(pybind11_init_, name)(m);                          \
29012391Sjason@lowepower.com            return m.ptr();                                                    \
29114299Sbbruce@ucdavis.edu        } PYBIND11_CATCH_INIT_EXCEPTIONS                                       \
29212391Sjason@lowepower.com    }                                                                          \
29312391Sjason@lowepower.com    void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &variable)
29412391Sjason@lowepower.com
29512391Sjason@lowepower.com
29612391Sjason@lowepower.comNAMESPACE_BEGIN(PYBIND11_NAMESPACE)
29712391Sjason@lowepower.com
29812391Sjason@lowepower.comusing ssize_t = Py_ssize_t;
29912391Sjason@lowepower.comusing size_t  = std::size_t;
30012391Sjason@lowepower.com
30112391Sjason@lowepower.com/// Approach used to cast a previously unknown C++ instance into a Python object
30212391Sjason@lowepower.comenum class return_value_policy : uint8_t {
30312391Sjason@lowepower.com    /** This is the default return value policy, which falls back to the policy
30412391Sjason@lowepower.com        return_value_policy::take_ownership when the return value is a pointer.
30512391Sjason@lowepower.com        Otherwise, it uses return_value::move or return_value::copy for rvalue
30612391Sjason@lowepower.com        and lvalue references, respectively. See below for a description of what
30712391Sjason@lowepower.com        all of these different policies do. */
30812391Sjason@lowepower.com    automatic = 0,
30912391Sjason@lowepower.com
31012391Sjason@lowepower.com    /** As above, but use policy return_value_policy::reference when the return
31112391Sjason@lowepower.com        value is a pointer. This is the default conversion policy for function
31212391Sjason@lowepower.com        arguments when calling Python functions manually from C++ code (i.e. via
31312391Sjason@lowepower.com        handle::operator()). You probably won't need to use this. */
31412391Sjason@lowepower.com    automatic_reference,
31512391Sjason@lowepower.com
31612391Sjason@lowepower.com    /** Reference an existing object (i.e. do not create a new copy) and take
31712391Sjason@lowepower.com        ownership. Python will call the destructor and delete operator when the
31812391Sjason@lowepower.com        object’s reference count reaches zero. Undefined behavior ensues when
31912391Sjason@lowepower.com        the C++ side does the same.. */
32012391Sjason@lowepower.com    take_ownership,
32112391Sjason@lowepower.com
32212391Sjason@lowepower.com    /** Create a new copy of the returned object, which will be owned by
32312391Sjason@lowepower.com        Python. This policy is comparably safe because the lifetimes of the two
32412391Sjason@lowepower.com        instances are decoupled. */
32512391Sjason@lowepower.com    copy,
32612391Sjason@lowepower.com
32712391Sjason@lowepower.com    /** Use std::move to move the return value contents into a new instance
32812391Sjason@lowepower.com        that will be owned by Python. This policy is comparably safe because the
32912391Sjason@lowepower.com        lifetimes of the two instances (move source and destination) are
33012391Sjason@lowepower.com        decoupled. */
33112391Sjason@lowepower.com    move,
33212391Sjason@lowepower.com
33312391Sjason@lowepower.com    /** Reference an existing object, but do not take ownership. The C++ side
33412391Sjason@lowepower.com        is responsible for managing the object’s lifetime and deallocating it
33512391Sjason@lowepower.com        when it is no longer used. Warning: undefined behavior will ensue when
33612391Sjason@lowepower.com        the C++ side deletes an object that is still referenced and used by
33712391Sjason@lowepower.com        Python. */
33812391Sjason@lowepower.com    reference,
33912391Sjason@lowepower.com
34012391Sjason@lowepower.com    /** This policy only applies to methods and properties. It references the
34112391Sjason@lowepower.com        object without taking ownership similar to the above
34212391Sjason@lowepower.com        return_value_policy::reference policy. In contrast to that policy, the
34312391Sjason@lowepower.com        function or property’s implicit this argument (called the parent) is
34412391Sjason@lowepower.com        considered to be the the owner of the return value (the child).
34512391Sjason@lowepower.com        pybind11 then couples the lifetime of the parent to the child via a
34612391Sjason@lowepower.com        reference relationship that ensures that the parent cannot be garbage
34712391Sjason@lowepower.com        collected while Python is still using the child. More advanced
34812391Sjason@lowepower.com        variations of this scheme are also possible using combinations of
34912391Sjason@lowepower.com        return_value_policy::reference and the keep_alive call policy */
35012391Sjason@lowepower.com    reference_internal
35112391Sjason@lowepower.com};
35212391Sjason@lowepower.com
35312391Sjason@lowepower.comNAMESPACE_BEGIN(detail)
35412391Sjason@lowepower.com
35512391Sjason@lowepower.cominline static constexpr int log2(size_t n, int k = 0) { return (n <= 1) ? k : log2(n >> 1, k + 1); }
35612391Sjason@lowepower.com
35712391Sjason@lowepower.com// Returns the size as a multiple of sizeof(void *), rounded up.
35812391Sjason@lowepower.cominline static constexpr size_t size_in_ptrs(size_t s) { return 1 + ((s - 1) >> log2(sizeof(void *))); }
35912391Sjason@lowepower.com
36012391Sjason@lowepower.com/**
36112391Sjason@lowepower.com * The space to allocate for simple layout instance holders (see below) in multiple of the size of
36212391Sjason@lowepower.com * a pointer (e.g.  2 means 16 bytes on 64-bit architectures).  The default is the minimum required
36312391Sjason@lowepower.com * to holder either a std::unique_ptr or std::shared_ptr (which is almost always
36412391Sjason@lowepower.com * sizeof(std::shared_ptr<T>)).
36512391Sjason@lowepower.com */
36612391Sjason@lowepower.comconstexpr size_t instance_simple_holder_in_ptrs() {
36712391Sjason@lowepower.com    static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
36812391Sjason@lowepower.com            "pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
36912391Sjason@lowepower.com    return size_in_ptrs(sizeof(std::shared_ptr<int>));
37012391Sjason@lowepower.com}
37112391Sjason@lowepower.com
37212391Sjason@lowepower.com// Forward declarations
37312391Sjason@lowepower.comstruct type_info;
37412391Sjason@lowepower.comstruct value_and_holder;
37512391Sjason@lowepower.com
37614299Sbbruce@ucdavis.edustruct nonsimple_values_and_holders {
37714299Sbbruce@ucdavis.edu    void **values_and_holders;
37814299Sbbruce@ucdavis.edu    uint8_t *status;
37914299Sbbruce@ucdavis.edu};
38014299Sbbruce@ucdavis.edu
38112391Sjason@lowepower.com/// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
38212391Sjason@lowepower.comstruct instance {
38312391Sjason@lowepower.com    PyObject_HEAD
38412391Sjason@lowepower.com    /// Storage for pointers and holder; see simple_layout, below, for a description
38512391Sjason@lowepower.com    union {
38612391Sjason@lowepower.com        void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
38714299Sbbruce@ucdavis.edu        nonsimple_values_and_holders nonsimple;
38812391Sjason@lowepower.com    };
38914299Sbbruce@ucdavis.edu    /// Weak references
39012391Sjason@lowepower.com    PyObject *weakrefs;
39112391Sjason@lowepower.com    /// If true, the pointer is owned which means we're free to manage it with a holder.
39212391Sjason@lowepower.com    bool owned : 1;
39312391Sjason@lowepower.com    /**
39412391Sjason@lowepower.com     * An instance has two possible value/holder layouts.
39512391Sjason@lowepower.com     *
39612391Sjason@lowepower.com     * Simple layout (when this flag is true), means the `simple_value_holder` is set with a pointer
39712391Sjason@lowepower.com     * and the holder object governing that pointer, i.e. [val1*][holder].  This layout is applied
39812391Sjason@lowepower.com     * whenever there is no python-side multiple inheritance of bound C++ types *and* the type's
39912391Sjason@lowepower.com     * holder will fit in the default space (which is large enough to hold either a std::unique_ptr
40012391Sjason@lowepower.com     * or std::shared_ptr).
40112391Sjason@lowepower.com     *
40212391Sjason@lowepower.com     * Non-simple layout applies when using custom holders that require more space than `shared_ptr`
40312391Sjason@lowepower.com     * (which is typically the size of two pointers), or when multiple inheritance is used on the
40412391Sjason@lowepower.com     * python side.  Non-simple layout allocates the required amount of memory to have multiple
40512391Sjason@lowepower.com     * bound C++ classes as parents.  Under this layout, `nonsimple.values_and_holders` is set to a
40614299Sbbruce@ucdavis.edu     * pointer to allocated space of the required space to hold a sequence of value pointers and
40712391Sjason@lowepower.com     * holders followed `status`, a set of bit flags (1 byte each), i.e.
40812391Sjason@lowepower.com     * [val1*][holder1][val2*][holder2]...[bb...]  where each [block] is rounded up to a multiple of
40914299Sbbruce@ucdavis.edu     * `sizeof(void *)`.  `nonsimple.status` is, for convenience, a pointer to the
41012391Sjason@lowepower.com     * beginning of the [bb...] block (but not independently allocated).
41112391Sjason@lowepower.com     *
41212391Sjason@lowepower.com     * Status bits indicate whether the associated holder is constructed (&
41312391Sjason@lowepower.com     * status_holder_constructed) and whether the value pointer is registered (&
41412391Sjason@lowepower.com     * status_instance_registered) in `registered_instances`.
41512391Sjason@lowepower.com     */
41612391Sjason@lowepower.com    bool simple_layout : 1;
41712391Sjason@lowepower.com    /// For simple layout, tracks whether the holder has been constructed
41812391Sjason@lowepower.com    bool simple_holder_constructed : 1;
41912391Sjason@lowepower.com    /// For simple layout, tracks whether the instance is registered in `registered_instances`
42012391Sjason@lowepower.com    bool simple_instance_registered : 1;
42112391Sjason@lowepower.com    /// If true, get_internals().patients has an entry for this object
42212391Sjason@lowepower.com    bool has_patients : 1;
42312391Sjason@lowepower.com
42412391Sjason@lowepower.com    /// Initializes all of the above type/values/holders data (but not the instance values themselves)
42512391Sjason@lowepower.com    void allocate_layout();
42612391Sjason@lowepower.com
42712391Sjason@lowepower.com    /// Destroys/deallocates all of the above
42812391Sjason@lowepower.com    void deallocate_layout();
42912391Sjason@lowepower.com
43012391Sjason@lowepower.com    /// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
43112391Sjason@lowepower.com    /// omitted).  Returns a default-constructed (with `.inst = nullptr`) object on failure if
43212391Sjason@lowepower.com    /// `throw_if_missing` is false.
43312391Sjason@lowepower.com    value_and_holder get_value_and_holder(const type_info *find_type = nullptr, bool throw_if_missing = true);
43412391Sjason@lowepower.com
43512391Sjason@lowepower.com    /// Bit values for the non-simple status flags
43612391Sjason@lowepower.com    static constexpr uint8_t status_holder_constructed  = 1;
43712391Sjason@lowepower.com    static constexpr uint8_t status_instance_registered = 2;
43812391Sjason@lowepower.com};
43912391Sjason@lowepower.com
44012391Sjason@lowepower.comstatic_assert(std::is_standard_layout<instance>::value, "Internal error: `pybind11::detail::instance` is not standard layout!");
44112391Sjason@lowepower.com
44212391Sjason@lowepower.com/// from __cpp_future__ import (convenient aliases from C++14/17)
44312391Sjason@lowepower.com#if defined(PYBIND11_CPP14) && (!defined(_MSC_VER) || _MSC_VER >= 1910)
44412391Sjason@lowepower.comusing std::enable_if_t;
44512391Sjason@lowepower.comusing std::conditional_t;
44612391Sjason@lowepower.comusing std::remove_cv_t;
44712391Sjason@lowepower.comusing std::remove_reference_t;
44812391Sjason@lowepower.com#else
44912391Sjason@lowepower.comtemplate <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
45012391Sjason@lowepower.comtemplate <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
45112391Sjason@lowepower.comtemplate <typename T> using remove_cv_t = typename std::remove_cv<T>::type;
45212391Sjason@lowepower.comtemplate <typename T> using remove_reference_t = typename std::remove_reference<T>::type;
45312391Sjason@lowepower.com#endif
45412391Sjason@lowepower.com
45512391Sjason@lowepower.com/// Index sequences
45612391Sjason@lowepower.com#if defined(PYBIND11_CPP14)
45712391Sjason@lowepower.comusing std::index_sequence;
45812391Sjason@lowepower.comusing std::make_index_sequence;
45912391Sjason@lowepower.com#else
46012391Sjason@lowepower.comtemplate<size_t ...> struct index_sequence  { };
46112391Sjason@lowepower.comtemplate<size_t N, size_t ...S> struct make_index_sequence_impl : make_index_sequence_impl <N - 1, N - 1, S...> { };
46212391Sjason@lowepower.comtemplate<size_t ...S> struct make_index_sequence_impl <0, S...> { typedef index_sequence<S...> type; };
46312391Sjason@lowepower.comtemplate<size_t N> using make_index_sequence = typename make_index_sequence_impl<N>::type;
46412391Sjason@lowepower.com#endif
46512391Sjason@lowepower.com
46612391Sjason@lowepower.com/// Make an index sequence of the indices of true arguments
46712391Sjason@lowepower.comtemplate <typename ISeq, size_t, bool...> struct select_indices_impl { using type = ISeq; };
46812391Sjason@lowepower.comtemplate <size_t... IPrev, size_t I, bool B, bool... Bs> struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
46912391Sjason@lowepower.com    : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>, I + 1, Bs...> {};
47012391Sjason@lowepower.comtemplate <bool... Bs> using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
47112391Sjason@lowepower.com
47214299Sbbruce@ucdavis.edu/// Backports of std::bool_constant and std::negation to accommodate older compilers
47312391Sjason@lowepower.comtemplate <bool B> using bool_constant = std::integral_constant<bool, B>;
47412391Sjason@lowepower.comtemplate <typename T> struct negation : bool_constant<!T::value> { };
47512391Sjason@lowepower.com
47612391Sjason@lowepower.comtemplate <typename...> struct void_t_impl { using type = void; };
47712391Sjason@lowepower.comtemplate <typename... Ts> using void_t = typename void_t_impl<Ts...>::type;
47812391Sjason@lowepower.com
47912391Sjason@lowepower.com/// Compile-time all/any/none of that check the boolean value of all template types
48014299Sbbruce@ucdavis.edu#if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
48112391Sjason@lowepower.comtemplate <class... Ts> using all_of = bool_constant<(Ts::value && ...)>;
48212391Sjason@lowepower.comtemplate <class... Ts> using any_of = bool_constant<(Ts::value || ...)>;
48312391Sjason@lowepower.com#elif !defined(_MSC_VER)
48412391Sjason@lowepower.comtemplate <bool...> struct bools {};
48512391Sjason@lowepower.comtemplate <class... Ts> using all_of = std::is_same<
48612391Sjason@lowepower.com    bools<Ts::value..., true>,
48712391Sjason@lowepower.com    bools<true, Ts::value...>>;
48812391Sjason@lowepower.comtemplate <class... Ts> using any_of = negation<all_of<negation<Ts>...>>;
48912391Sjason@lowepower.com#else
49012391Sjason@lowepower.com// MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
49112391Sjason@lowepower.com// at a slight loss of compilation efficiency).
49212391Sjason@lowepower.comtemplate <class... Ts> using all_of = std::conjunction<Ts...>;
49312391Sjason@lowepower.comtemplate <class... Ts> using any_of = std::disjunction<Ts...>;
49412391Sjason@lowepower.com#endif
49512391Sjason@lowepower.comtemplate <class... Ts> using none_of = negation<any_of<Ts...>>;
49612391Sjason@lowepower.com
49712391Sjason@lowepower.comtemplate <class T, template<class> class... Predicates> using satisfies_all_of = all_of<Predicates<T>...>;
49812391Sjason@lowepower.comtemplate <class T, template<class> class... Predicates> using satisfies_any_of = any_of<Predicates<T>...>;
49912391Sjason@lowepower.comtemplate <class T, template<class> class... Predicates> using satisfies_none_of = none_of<Predicates<T>...>;
50012391Sjason@lowepower.com
50112391Sjason@lowepower.com/// Strip the class from a method type
50212391Sjason@lowepower.comtemplate <typename T> struct remove_class { };
50312391Sjason@lowepower.comtemplate <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
50412391Sjason@lowepower.comtemplate <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
50512391Sjason@lowepower.com
50612391Sjason@lowepower.com/// Helper template to strip away type modifiers
50712391Sjason@lowepower.comtemplate <typename T> struct intrinsic_type                       { typedef T type; };
50812391Sjason@lowepower.comtemplate <typename T> struct intrinsic_type<const T>              { typedef typename intrinsic_type<T>::type type; };
50912391Sjason@lowepower.comtemplate <typename T> struct intrinsic_type<T*>                   { typedef typename intrinsic_type<T>::type type; };
51012391Sjason@lowepower.comtemplate <typename T> struct intrinsic_type<T&>                   { typedef typename intrinsic_type<T>::type type; };
51112391Sjason@lowepower.comtemplate <typename T> struct intrinsic_type<T&&>                  { typedef typename intrinsic_type<T>::type type; };
51212391Sjason@lowepower.comtemplate <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
51312391Sjason@lowepower.comtemplate <typename T, size_t N> struct intrinsic_type<T[N]>       { typedef typename intrinsic_type<T>::type type; };
51412391Sjason@lowepower.comtemplate <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
51512391Sjason@lowepower.com
51612391Sjason@lowepower.com/// Helper type to replace 'void' in some expressions
51712391Sjason@lowepower.comstruct void_type { };
51812391Sjason@lowepower.com
51912391Sjason@lowepower.com/// Helper template which holds a list of types
52012391Sjason@lowepower.comtemplate <typename...> struct type_list { };
52112391Sjason@lowepower.com
52212391Sjason@lowepower.com/// Compile-time integer sum
52312391Sjason@lowepower.com#ifdef __cpp_fold_expressions
52412391Sjason@lowepower.comtemplate <typename... Ts> constexpr size_t constexpr_sum(Ts... ns) { return (0 + ... + size_t{ns}); }
52512391Sjason@lowepower.com#else
52612391Sjason@lowepower.comconstexpr size_t constexpr_sum() { return 0; }
52712391Sjason@lowepower.comtemplate <typename T, typename... Ts>
52812391Sjason@lowepower.comconstexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
52912391Sjason@lowepower.com#endif
53012391Sjason@lowepower.com
53112391Sjason@lowepower.comNAMESPACE_BEGIN(constexpr_impl)
53212391Sjason@lowepower.com/// Implementation details for constexpr functions
53312391Sjason@lowepower.comconstexpr int first(int i) { return i; }
53412391Sjason@lowepower.comtemplate <typename T, typename... Ts>
53512391Sjason@lowepower.comconstexpr int first(int i, T v, Ts... vs) { return v ? i : first(i + 1, vs...); }
53612391Sjason@lowepower.com
53712391Sjason@lowepower.comconstexpr int last(int /*i*/, int result) { return result; }
53812391Sjason@lowepower.comtemplate <typename T, typename... Ts>
53912391Sjason@lowepower.comconstexpr int last(int i, int result, T v, Ts... vs) { return last(i + 1, v ? i : result, vs...); }
54012391Sjason@lowepower.comNAMESPACE_END(constexpr_impl)
54112391Sjason@lowepower.com
54212391Sjason@lowepower.com/// Return the index of the first type in Ts which satisfies Predicate<T>.  Returns sizeof...(Ts) if
54312391Sjason@lowepower.com/// none match.
54412391Sjason@lowepower.comtemplate <template<typename> class Predicate, typename... Ts>
54512391Sjason@lowepower.comconstexpr int constexpr_first() { return constexpr_impl::first(0, Predicate<Ts>::value...); }
54612391Sjason@lowepower.com
54712391Sjason@lowepower.com/// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
54812391Sjason@lowepower.comtemplate <template<typename> class Predicate, typename... Ts>
54912391Sjason@lowepower.comconstexpr int constexpr_last() { return constexpr_impl::last(0, -1, Predicate<Ts>::value...); }
55012391Sjason@lowepower.com
55112391Sjason@lowepower.com/// Return the Nth element from the parameter pack
55212391Sjason@lowepower.comtemplate <size_t N, typename T, typename... Ts>
55312391Sjason@lowepower.comstruct pack_element { using type = typename pack_element<N - 1, Ts...>::type; };
55412391Sjason@lowepower.comtemplate <typename T, typename... Ts>
55512391Sjason@lowepower.comstruct pack_element<0, T, Ts...> { using type = T; };
55612391Sjason@lowepower.com
55712391Sjason@lowepower.com/// Return the one and only type which matches the predicate, or Default if none match.
55812391Sjason@lowepower.com/// If more than one type matches the predicate, fail at compile-time.
55912391Sjason@lowepower.comtemplate <template<typename> class Predicate, typename Default, typename... Ts>
56012391Sjason@lowepower.comstruct exactly_one {
56112391Sjason@lowepower.com    static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
56212391Sjason@lowepower.com    static_assert(found <= 1, "Found more than one type matching the predicate");
56312391Sjason@lowepower.com
56412391Sjason@lowepower.com    static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
56512391Sjason@lowepower.com    using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
56612391Sjason@lowepower.com};
56712391Sjason@lowepower.comtemplate <template<typename> class P, typename Default>
56812391Sjason@lowepower.comstruct exactly_one<P, Default> { using type = Default; };
56912391Sjason@lowepower.com
57012391Sjason@lowepower.comtemplate <template<typename> class Predicate, typename Default, typename... Ts>
57112391Sjason@lowepower.comusing exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
57212391Sjason@lowepower.com
57312391Sjason@lowepower.com/// Defer the evaluation of type T until types Us are instantiated
57412391Sjason@lowepower.comtemplate <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
57512391Sjason@lowepower.comtemplate <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
57612391Sjason@lowepower.com
57712391Sjason@lowepower.com/// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
57812391Sjason@lowepower.com/// unlike `std::is_base_of`)
57912391Sjason@lowepower.comtemplate <typename Base, typename Derived> using is_strict_base_of = bool_constant<
58012391Sjason@lowepower.com    std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
58112391Sjason@lowepower.com
58214299Sbbruce@ucdavis.edu/// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived pointer
58314299Sbbruce@ucdavis.edu/// can be converted to a Base pointer)
58414299Sbbruce@ucdavis.edutemplate <typename Base, typename Derived> using is_accessible_base_of = bool_constant<
58514299Sbbruce@ucdavis.edu    std::is_base_of<Base, Derived>::value && std::is_convertible<Derived *, Base *>::value>;
58614299Sbbruce@ucdavis.edu
58712391Sjason@lowepower.comtemplate <template<typename...> class Base>
58812391Sjason@lowepower.comstruct is_template_base_of_impl {
58912391Sjason@lowepower.com    template <typename... Us> static std::true_type check(Base<Us...> *);
59012391Sjason@lowepower.com    static std::false_type check(...);
59112391Sjason@lowepower.com};
59212391Sjason@lowepower.com
59312391Sjason@lowepower.com/// Check if a template is the base of a type. For example:
59412391Sjason@lowepower.com/// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
59512391Sjason@lowepower.comtemplate <template<typename...> class Base, typename T>
59612391Sjason@lowepower.com#if !defined(_MSC_VER)
59712391Sjason@lowepower.comusing is_template_base_of = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr));
59812391Sjason@lowepower.com#else // MSVC2015 has trouble with decltype in template aliases
59912391Sjason@lowepower.comstruct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr)) { };
60012391Sjason@lowepower.com#endif
60112391Sjason@lowepower.com
60212391Sjason@lowepower.com/// Check if T is an instantiation of the template `Class`. For example:
60312391Sjason@lowepower.com/// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
60412391Sjason@lowepower.comtemplate <template<typename...> class Class, typename T>
60512391Sjason@lowepower.comstruct is_instantiation : std::false_type { };
60612391Sjason@lowepower.comtemplate <template<typename...> class Class, typename... Us>
60712391Sjason@lowepower.comstruct is_instantiation<Class, Class<Us...>> : std::true_type { };
60812391Sjason@lowepower.com
60912391Sjason@lowepower.com/// Check if T is std::shared_ptr<U> where U can be anything
61012391Sjason@lowepower.comtemplate <typename T> using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
61112391Sjason@lowepower.com
61212391Sjason@lowepower.com/// Check if T looks like an input iterator
61312391Sjason@lowepower.comtemplate <typename T, typename = void> struct is_input_iterator : std::false_type {};
61412391Sjason@lowepower.comtemplate <typename T>
61512391Sjason@lowepower.comstruct is_input_iterator<T, void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
61612391Sjason@lowepower.com    : std::true_type {};
61712391Sjason@lowepower.com
61812391Sjason@lowepower.comtemplate <typename T> using is_function_pointer = bool_constant<
61912391Sjason@lowepower.com    std::is_pointer<T>::value && std::is_function<typename std::remove_pointer<T>::type>::value>;
62012391Sjason@lowepower.com
62112391Sjason@lowepower.comtemplate <typename F> struct strip_function_object {
62212391Sjason@lowepower.com    using type = typename remove_class<decltype(&F::operator())>::type;
62312391Sjason@lowepower.com};
62412391Sjason@lowepower.com
62512391Sjason@lowepower.com// Extracts the function signature from a function, function pointer or lambda.
62612391Sjason@lowepower.comtemplate <typename Function, typename F = remove_reference_t<Function>>
62712391Sjason@lowepower.comusing function_signature_t = conditional_t<
62812391Sjason@lowepower.com    std::is_function<F>::value,
62912391Sjason@lowepower.com    F,
63012391Sjason@lowepower.com    typename conditional_t<
63112391Sjason@lowepower.com        std::is_pointer<F>::value || std::is_member_pointer<F>::value,
63212391Sjason@lowepower.com        std::remove_pointer<F>,
63312391Sjason@lowepower.com        strip_function_object<F>
63412391Sjason@lowepower.com    >::type
63512391Sjason@lowepower.com>;
63612391Sjason@lowepower.com
63712391Sjason@lowepower.com/// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
63812391Sjason@lowepower.com/// pointer.  Note that this can catch all sorts of other things, too; this is intended to be used
63912391Sjason@lowepower.com/// in a place where passing a lambda makes sense.
64012391Sjason@lowepower.comtemplate <typename T> using is_lambda = satisfies_none_of<remove_reference_t<T>,
64112391Sjason@lowepower.com        std::is_function, std::is_pointer, std::is_member_pointer>;
64212391Sjason@lowepower.com
64312391Sjason@lowepower.com/// Ignore that a variable is unused in compiler warnings
64412391Sjason@lowepower.cominline void ignore_unused(const int *) { }
64512391Sjason@lowepower.com
64612391Sjason@lowepower.com/// Apply a function over each element of a parameter pack
64712391Sjason@lowepower.com#ifdef __cpp_fold_expressions
64812391Sjason@lowepower.com#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
64912391Sjason@lowepower.com#else
65012391Sjason@lowepower.comusing expand_side_effects = bool[];
65112391Sjason@lowepower.com#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) pybind11::detail::expand_side_effects{ ((PATTERN), void(), false)..., false }
65212391Sjason@lowepower.com#endif
65312391Sjason@lowepower.com
65412391Sjason@lowepower.comNAMESPACE_END(detail)
65512391Sjason@lowepower.com
65612391Sjason@lowepower.com/// C++ bindings of builtin Python exceptions
65712391Sjason@lowepower.comclass builtin_exception : public std::runtime_error {
65812391Sjason@lowepower.compublic:
65912391Sjason@lowepower.com    using std::runtime_error::runtime_error;
66012391Sjason@lowepower.com    /// Set the error using the Python C API
66112391Sjason@lowepower.com    virtual void set_error() const = 0;
66212391Sjason@lowepower.com};
66312391Sjason@lowepower.com
66412391Sjason@lowepower.com#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
66512391Sjason@lowepower.com    class name : public builtin_exception { public: \
66612391Sjason@lowepower.com        using builtin_exception::builtin_exception; \
66712391Sjason@lowepower.com        name() : name("") { } \
66812391Sjason@lowepower.com        void set_error() const override { PyErr_SetString(type, what()); } \
66912391Sjason@lowepower.com    };
67012391Sjason@lowepower.com
67112391Sjason@lowepower.comPYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
67212391Sjason@lowepower.comPYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
67312391Sjason@lowepower.comPYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
67412391Sjason@lowepower.comPYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
67512391Sjason@lowepower.comPYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
67614299Sbbruce@ucdavis.eduPYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)
67712391Sjason@lowepower.comPYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
67812391Sjason@lowepower.comPYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
67912391Sjason@lowepower.com
68012391Sjason@lowepower.com[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
68112391Sjason@lowepower.com[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
68212391Sjason@lowepower.com
68312391Sjason@lowepower.comtemplate <typename T, typename SFINAE = void> struct format_descriptor { };
68412391Sjason@lowepower.com
68512391Sjason@lowepower.comNAMESPACE_BEGIN(detail)
68612391Sjason@lowepower.com// Returns the index of the given type in the type char array below, and in the list in numpy.h
68712391Sjason@lowepower.com// The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
68812391Sjason@lowepower.com// complex float,double,long double.  Note that the long double types only participate when long
68912391Sjason@lowepower.com// double is actually longer than double (it isn't under MSVC).
69012391Sjason@lowepower.com// NB: not only the string below but also complex.h and numpy.h rely on this order.
69112391Sjason@lowepower.comtemplate <typename T, typename SFINAE = void> struct is_fmt_numeric { static constexpr bool value = false; };
69212391Sjason@lowepower.comtemplate <typename T> struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
69312391Sjason@lowepower.com    static constexpr bool value = true;
69412391Sjason@lowepower.com    static constexpr int index = std::is_same<T, bool>::value ? 0 : 1 + (
69512391Sjason@lowepower.com        std::is_integral<T>::value ? detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value : 8 + (
69612391Sjason@lowepower.com        std::is_same<T, double>::value ? 1 : std::is_same<T, long double>::value ? 2 : 0));
69712391Sjason@lowepower.com};
69812391Sjason@lowepower.comNAMESPACE_END(detail)
69912391Sjason@lowepower.com
70012391Sjason@lowepower.comtemplate <typename T> struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
70112391Sjason@lowepower.com    static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
70212391Sjason@lowepower.com    static constexpr const char value[2] = { c, '\0' };
70312391Sjason@lowepower.com    static std::string format() { return std::string(1, c); }
70412391Sjason@lowepower.com};
70512391Sjason@lowepower.com
70614299Sbbruce@ucdavis.edu#if !defined(PYBIND11_CPP17)
70714299Sbbruce@ucdavis.edu
70812391Sjason@lowepower.comtemplate <typename T> constexpr const char format_descriptor<
70912391Sjason@lowepower.com    T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
71012391Sjason@lowepower.com
71114299Sbbruce@ucdavis.edu#endif
71214299Sbbruce@ucdavis.edu
71312391Sjason@lowepower.com/// RAII wrapper that temporarily clears any Python error state
71412391Sjason@lowepower.comstruct error_scope {
71512391Sjason@lowepower.com    PyObject *type, *value, *trace;
71612391Sjason@lowepower.com    error_scope() { PyErr_Fetch(&type, &value, &trace); }
71712391Sjason@lowepower.com    ~error_scope() { PyErr_Restore(type, value, trace); }
71812391Sjason@lowepower.com};
71912391Sjason@lowepower.com
72012391Sjason@lowepower.com/// Dummy destructor wrapper that can be used to expose classes with a private destructor
72112391Sjason@lowepower.comstruct nodelete { template <typename T> void operator()(T*) { } };
72212391Sjason@lowepower.com
72312391Sjason@lowepower.comNAMESPACE_BEGIN(detail)
72412391Sjason@lowepower.comtemplate <typename... Args>
72512391Sjason@lowepower.comstruct overload_cast_impl {
72612391Sjason@lowepower.com    constexpr overload_cast_impl() {} // MSVC 2015 needs this
72712391Sjason@lowepower.com
72812391Sjason@lowepower.com    template <typename Return>
72912391Sjason@lowepower.com    constexpr auto operator()(Return (*pf)(Args...)) const noexcept
73012391Sjason@lowepower.com                              -> decltype(pf) { return pf; }
73112391Sjason@lowepower.com
73212391Sjason@lowepower.com    template <typename Return, typename Class>
73312391Sjason@lowepower.com    constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
73412391Sjason@lowepower.com                              -> decltype(pmf) { return pmf; }
73512391Sjason@lowepower.com
73612391Sjason@lowepower.com    template <typename Return, typename Class>
73712391Sjason@lowepower.com    constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
73812391Sjason@lowepower.com                              -> decltype(pmf) { return pmf; }
73912391Sjason@lowepower.com};
74012391Sjason@lowepower.comNAMESPACE_END(detail)
74112391Sjason@lowepower.com
74214299Sbbruce@ucdavis.edu// overload_cast requires variable templates: C++14
74314299Sbbruce@ucdavis.edu#if defined(PYBIND11_CPP14)
74414299Sbbruce@ucdavis.edu#define PYBIND11_OVERLOAD_CAST 1
74512391Sjason@lowepower.com/// Syntax sugar for resolving overloaded function pointers:
74612391Sjason@lowepower.com///  - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
74712391Sjason@lowepower.com///  - sweet:   overload_cast<Arg0, Arg1, Arg2>(&Class::func)
74812391Sjason@lowepower.comtemplate <typename... Args>
74912391Sjason@lowepower.comstatic constexpr detail::overload_cast_impl<Args...> overload_cast = {};
75012391Sjason@lowepower.com// MSVC 2015 only accepts this particular initialization syntax for this variable template.
75114299Sbbruce@ucdavis.edu#endif
75212391Sjason@lowepower.com
75312391Sjason@lowepower.com/// Const member function selector for overload_cast
75412391Sjason@lowepower.com///  - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
75512391Sjason@lowepower.com///  - sweet:   overload_cast<Arg>(&Class::func, const_)
75612391Sjason@lowepower.comstatic constexpr auto const_ = std::true_type{};
75712391Sjason@lowepower.com
75814299Sbbruce@ucdavis.edu#if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:
75912391Sjason@lowepower.comtemplate <typename... Args> struct overload_cast {
76012391Sjason@lowepower.com    static_assert(detail::deferred_t<std::false_type, Args...>::value,
76112391Sjason@lowepower.com                  "pybind11::overload_cast<...> requires compiling in C++14 mode");
76212391Sjason@lowepower.com};
76312391Sjason@lowepower.com#endif // overload_cast
76412391Sjason@lowepower.com
76512391Sjason@lowepower.comNAMESPACE_BEGIN(detail)
76612391Sjason@lowepower.com
76712391Sjason@lowepower.com// Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
76812391Sjason@lowepower.com// any standard container (or C-style array) supporting std::begin/std::end, any singleton
76912391Sjason@lowepower.com// arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
77012391Sjason@lowepower.comtemplate <typename T>
77112391Sjason@lowepower.comclass any_container {
77212391Sjason@lowepower.com    std::vector<T> v;
77312391Sjason@lowepower.compublic:
77412391Sjason@lowepower.com    any_container() = default;
77512391Sjason@lowepower.com
77612391Sjason@lowepower.com    // Can construct from a pair of iterators
77712391Sjason@lowepower.com    template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
77812391Sjason@lowepower.com    any_container(It first, It last) : v(first, last) { }
77912391Sjason@lowepower.com
78012391Sjason@lowepower.com    // Implicit conversion constructor from any arbitrary container type with values convertible to T
78112391Sjason@lowepower.com    template <typename Container, typename = enable_if_t<std::is_convertible<decltype(*std::begin(std::declval<const Container &>())), T>::value>>
78212391Sjason@lowepower.com    any_container(const Container &c) : any_container(std::begin(c), std::end(c)) { }
78312391Sjason@lowepower.com
78412391Sjason@lowepower.com    // initializer_list's aren't deducible, so don't get matched by the above template; we need this
78512391Sjason@lowepower.com    // to explicitly allow implicit conversion from one:
78612391Sjason@lowepower.com    template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
78712391Sjason@lowepower.com    any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) { }
78812391Sjason@lowepower.com
78912391Sjason@lowepower.com    // Avoid copying if given an rvalue vector of the correct type.
79012391Sjason@lowepower.com    any_container(std::vector<T> &&v) : v(std::move(v)) { }
79112391Sjason@lowepower.com
79212391Sjason@lowepower.com    // Moves the vector out of an rvalue any_container
79312391Sjason@lowepower.com    operator std::vector<T> &&() && { return std::move(v); }
79412391Sjason@lowepower.com
79512391Sjason@lowepower.com    // Dereferencing obtains a reference to the underlying vector
79612391Sjason@lowepower.com    std::vector<T> &operator*() { return v; }
79712391Sjason@lowepower.com    const std::vector<T> &operator*() const { return v; }
79812391Sjason@lowepower.com
79912391Sjason@lowepower.com    // -> lets you call methods on the underlying vector
80012391Sjason@lowepower.com    std::vector<T> *operator->() { return &v; }
80112391Sjason@lowepower.com    const std::vector<T> *operator->() const { return &v; }
80212391Sjason@lowepower.com};
80312391Sjason@lowepower.com
80412391Sjason@lowepower.comNAMESPACE_END(detail)
80512391Sjason@lowepower.com
80612391Sjason@lowepower.com
80712391Sjason@lowepower.com
80812391Sjason@lowepower.comNAMESPACE_END(PYBIND11_NAMESPACE)
809