Back to home page

EIC code displayed by LXR

 
 

    


Warning, file /jana2/src/python/externals/pybind11-2.10.3/include/pybind11/detail/common.h was not indexed or was modified since last indexation (in which case cross-reference links may be missing, inaccurate or erroneous).

0001 /*
0002     pybind11/detail/common.h -- Basic macros
0003 
0004     Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
0005 
0006     All rights reserved. Use of this source code is governed by a
0007     BSD-style license that can be found in the LICENSE file.
0008 */
0009 
0010 #pragma once
0011 
0012 #define PYBIND11_VERSION_MAJOR 2
0013 #define PYBIND11_VERSION_MINOR 10
0014 #define PYBIND11_VERSION_PATCH 3
0015 
0016 // Similar to Python's convention: https://docs.python.org/3/c-api/apiabiversion.html
0017 // Additional convention: 0xD = dev
0018 #define PYBIND11_VERSION_HEX 0x020A0300
0019 
0020 // Define some generic pybind11 helper macros for warning management.
0021 //
0022 // Note that compiler-specific push/pop pairs are baked into the
0023 // PYBIND11_NAMESPACE_BEGIN/PYBIND11_NAMESPACE_END pair of macros. Therefore manual
0024 // PYBIND11_WARNING_PUSH/PYBIND11_WARNING_POP are usually only needed in `#include` sections.
0025 //
0026 // If you find you need to suppress a warning, please try to make the suppression as local as
0027 // possible using these macros. Please also be sure to push/pop with the pybind11 macros. Please
0028 // only use compiler specifics if you need to check specific versions, e.g. Apple Clang vs. vanilla
0029 // Clang.
0030 #if defined(_MSC_VER)
0031 #    define PYBIND11_COMPILER_MSVC
0032 #    define PYBIND11_PRAGMA(...) __pragma(__VA_ARGS__)
0033 #    define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(warning(push))
0034 #    define PYBIND11_WARNING_POP PYBIND11_PRAGMA(warning(pop))
0035 #elif defined(__INTEL_COMPILER)
0036 #    define PYBIND11_COMPILER_INTEL
0037 #    define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)
0038 #    define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(warning push)
0039 #    define PYBIND11_WARNING_POP PYBIND11_PRAGMA(warning pop)
0040 #elif defined(__clang__)
0041 #    define PYBIND11_COMPILER_CLANG
0042 #    define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)
0043 #    define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(clang diagnostic push)
0044 #    define PYBIND11_WARNING_POP PYBIND11_PRAGMA(clang diagnostic push)
0045 #elif defined(__GNUC__)
0046 #    define PYBIND11_COMPILER_GCC
0047 #    define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)
0048 #    define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(GCC diagnostic push)
0049 #    define PYBIND11_WARNING_POP PYBIND11_PRAGMA(GCC diagnostic pop)
0050 #endif
0051 
0052 #ifdef PYBIND11_COMPILER_MSVC
0053 #    define PYBIND11_WARNING_DISABLE_MSVC(name) PYBIND11_PRAGMA(warning(disable : name))
0054 #else
0055 #    define PYBIND11_WARNING_DISABLE_MSVC(name)
0056 #endif
0057 
0058 #ifdef PYBIND11_COMPILER_CLANG
0059 #    define PYBIND11_WARNING_DISABLE_CLANG(name) PYBIND11_PRAGMA(clang diagnostic ignored name)
0060 #else
0061 #    define PYBIND11_WARNING_DISABLE_CLANG(name)
0062 #endif
0063 
0064 #ifdef PYBIND11_COMPILER_GCC
0065 #    define PYBIND11_WARNING_DISABLE_GCC(name) PYBIND11_PRAGMA(GCC diagnostic ignored name)
0066 #else
0067 #    define PYBIND11_WARNING_DISABLE_GCC(name)
0068 #endif
0069 
0070 #ifdef PYBIND11_COMPILER_INTEL
0071 #    define PYBIND11_WARNING_DISABLE_INTEL(name) PYBIND11_PRAGMA(warning disable name)
0072 #else
0073 #    define PYBIND11_WARNING_DISABLE_INTEL(name)
0074 #endif
0075 
0076 #define PYBIND11_NAMESPACE_BEGIN(name)                                                            \
0077     namespace name {                                                                              \
0078     PYBIND11_WARNING_PUSH
0079 
0080 #define PYBIND11_NAMESPACE_END(name)                                                              \
0081     PYBIND11_WARNING_POP                                                                          \
0082     }
0083 
0084 // Robust support for some features and loading modules compiled against different pybind versions
0085 // requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute
0086 // on the main `pybind11` namespace.
0087 #if !defined(PYBIND11_NAMESPACE)
0088 #    ifdef __GNUG__
0089 #        define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
0090 #    else
0091 #        define PYBIND11_NAMESPACE pybind11
0092 #    endif
0093 #endif
0094 
0095 #if !(defined(_MSC_VER) && __cplusplus == 199711L)
0096 #    if __cplusplus >= 201402L
0097 #        define PYBIND11_CPP14
0098 #        if __cplusplus >= 201703L
0099 #            define PYBIND11_CPP17
0100 #            if __cplusplus >= 202002L
0101 #                define PYBIND11_CPP20
0102 // Please update tests/pybind11_tests.cpp `cpp_std()` when adding a macro here.
0103 #            endif
0104 #        endif
0105 #    endif
0106 #elif defined(_MSC_VER) && __cplusplus == 199711L
0107 // MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully
0108 // implemented). Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3
0109 // or newer.
0110 #    if _MSVC_LANG >= 201402L
0111 #        define PYBIND11_CPP14
0112 #        if _MSVC_LANG > 201402L
0113 #            define PYBIND11_CPP17
0114 #            if _MSVC_LANG >= 202002L
0115 #                define PYBIND11_CPP20
0116 #            endif
0117 #        endif
0118 #    endif
0119 #endif
0120 
0121 // Compiler version assertions
0122 #if defined(__INTEL_COMPILER)
0123 #    if __INTEL_COMPILER < 1800
0124 #        error pybind11 requires Intel C++ compiler v18 or newer
0125 #    elif __INTEL_COMPILER < 1900 && defined(PYBIND11_CPP14)
0126 #        error pybind11 supports only C++11 with Intel C++ compiler v18. Use v19 or newer for C++14.
0127 #    endif
0128 /* The following pragma cannot be pop'ed:
0129    https://community.intel.com/t5/Intel-C-Compiler/Inline-and-no-inline-warning/td-p/1216764 */
0130 #    pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
0131 #elif defined(__clang__) && !defined(__apple_build_version__)
0132 #    if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
0133 #        error pybind11 requires clang 3.3 or newer
0134 #    endif
0135 #elif defined(__clang__)
0136 // Apple changes clang version macros to its Xcode version; the first Xcode release based on
0137 // (upstream) clang 3.3 was Xcode 5:
0138 #    if __clang_major__ < 5
0139 #        error pybind11 requires Xcode/clang 5.0 or newer
0140 #    endif
0141 #elif defined(__GNUG__)
0142 #    if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
0143 #        error pybind11 requires gcc 4.8 or newer
0144 #    endif
0145 #elif defined(_MSC_VER)
0146 #    if _MSC_VER < 1910
0147 #        error pybind11 2.10+ requires MSVC 2017 or newer
0148 #    endif
0149 #endif
0150 
0151 #if !defined(PYBIND11_EXPORT)
0152 #    if defined(WIN32) || defined(_WIN32)
0153 #        define PYBIND11_EXPORT __declspec(dllexport)
0154 #    else
0155 #        define PYBIND11_EXPORT __attribute__((visibility("default")))
0156 #    endif
0157 #endif
0158 
0159 #if !defined(PYBIND11_EXPORT_EXCEPTION)
0160 #    if defined(__apple_build_version__)
0161 #        define PYBIND11_EXPORT_EXCEPTION PYBIND11_EXPORT
0162 #    else
0163 #        define PYBIND11_EXPORT_EXCEPTION
0164 #    endif
0165 #endif
0166 
0167 // For CUDA, GCC7, GCC8:
0168 // PYBIND11_NOINLINE_FORCED is incompatible with `-Wattributes -Werror`.
0169 // When defining PYBIND11_NOINLINE_FORCED, it is best to also use `-Wno-attributes`.
0170 // However, the measured shared-library size saving when using noinline are only
0171 // 1.7% for CUDA, -0.2% for GCC7, and 0.0% for GCC8 (using -DCMAKE_BUILD_TYPE=MinSizeRel,
0172 // the default under pybind11/tests).
0173 #if !defined(PYBIND11_NOINLINE_FORCED)                                                            \
0174     && (defined(__CUDACC__) || (defined(__GNUC__) && (__GNUC__ == 7 || __GNUC__ == 8)))
0175 #    define PYBIND11_NOINLINE_DISABLED
0176 #endif
0177 
0178 // The PYBIND11_NOINLINE macro is for function DEFINITIONS.
0179 // In contrast, FORWARD DECLARATIONS should never use this macro:
0180 // https://stackoverflow.com/questions/9317473/forward-declaration-of-inline-functions
0181 #if defined(PYBIND11_NOINLINE_DISABLED) // Option for maximum portability and experimentation.
0182 #    define PYBIND11_NOINLINE inline
0183 #elif defined(_MSC_VER)
0184 #    define PYBIND11_NOINLINE __declspec(noinline) inline
0185 #else
0186 #    define PYBIND11_NOINLINE __attribute__((noinline)) inline
0187 #endif
0188 
0189 #if defined(__MINGW32__)
0190 // For unknown reasons all PYBIND11_DEPRECATED member trigger a warning when declared
0191 // whether it is used or not
0192 #    define PYBIND11_DEPRECATED(reason)
0193 #elif defined(PYBIND11_CPP14)
0194 #    define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
0195 #else
0196 #    define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
0197 #endif
0198 
0199 #if defined(PYBIND11_CPP17)
0200 #    define PYBIND11_MAYBE_UNUSED [[maybe_unused]]
0201 #elif defined(_MSC_VER) && !defined(__clang__)
0202 #    define PYBIND11_MAYBE_UNUSED
0203 #else
0204 #    define PYBIND11_MAYBE_UNUSED __attribute__((__unused__))
0205 #endif
0206 
0207 /* Don't let Python.h #define (v)snprintf as macro because they are implemented
0208    properly in Visual Studio since 2015. */
0209 #if defined(_MSC_VER)
0210 #    define HAVE_SNPRINTF 1
0211 #endif
0212 
0213 /// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
0214 #if defined(_MSC_VER)
0215 PYBIND11_WARNING_PUSH
0216 PYBIND11_WARNING_DISABLE_MSVC(4505)
0217 // C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
0218 #    if defined(_DEBUG) && !defined(Py_DEBUG)
0219 // Workaround for a VS 2022 issue.
0220 // NOTE: This workaround knowingly violates the Python.h include order requirement:
0221 // https://docs.python.org/3/c-api/intro.html#include-files
0222 // See https://github.com/pybind/pybind11/pull/3497 for full context.
0223 #        include <yvals.h>
0224 #        if _MSVC_STL_VERSION >= 143
0225 #            include <crtdefs.h>
0226 #        endif
0227 #        define PYBIND11_DEBUG_MARKER
0228 #        undef _DEBUG
0229 #    endif
0230 #endif
0231 
0232 // https://en.cppreference.com/w/c/chrono/localtime
0233 #if defined(__STDC_LIB_EXT1__) && !defined(__STDC_WANT_LIB_EXT1__)
0234 #    define __STDC_WANT_LIB_EXT1__
0235 #endif
0236 
0237 #ifdef __has_include
0238 // std::optional (but including it in c++14 mode isn't allowed)
0239 #    if defined(PYBIND11_CPP17) && __has_include(<optional>)
0240 #        define PYBIND11_HAS_OPTIONAL 1
0241 #    endif
0242 // std::experimental::optional (but not allowed in c++11 mode)
0243 #    if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
0244                                  !__has_include(<optional>))
0245 #        define PYBIND11_HAS_EXP_OPTIONAL 1
0246 #    endif
0247 // std::variant
0248 #    if defined(PYBIND11_CPP17) && __has_include(<variant>)
0249 #        define PYBIND11_HAS_VARIANT 1
0250 #    endif
0251 #elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
0252 #    define PYBIND11_HAS_OPTIONAL 1
0253 #    define PYBIND11_HAS_VARIANT 1
0254 #endif
0255 
0256 #if defined(PYBIND11_CPP17)
0257 #    if defined(__has_include)
0258 #        if __has_include(<string_view>)
0259 #            define PYBIND11_HAS_STRING_VIEW
0260 #        endif
0261 #    elif defined(_MSC_VER)
0262 #        define PYBIND11_HAS_STRING_VIEW
0263 #    endif
0264 #endif
0265 
0266 #include <Python.h>
0267 // Reminder: WITH_THREAD is always defined if PY_VERSION_HEX >= 0x03070000
0268 #if PY_VERSION_HEX < 0x03060000
0269 #    error "PYTHON < 3.6 IS UNSUPPORTED. pybind11 v2.9 was the last to support Python 2 and 3.5."
0270 #endif
0271 #include <frameobject.h>
0272 #include <pythread.h>
0273 
0274 /* Python #defines overrides on all sorts of core functions, which
0275    tends to weak havok in C++ codebases that expect these to work
0276    like regular functions (potentially with several overloads) */
0277 #if defined(isalnum)
0278 #    undef isalnum
0279 #    undef isalpha
0280 #    undef islower
0281 #    undef isspace
0282 #    undef isupper
0283 #    undef tolower
0284 #    undef toupper
0285 #endif
0286 
0287 #if defined(copysign)
0288 #    undef copysign
0289 #endif
0290 
0291 #if defined(PYPY_VERSION) && !defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
0292 #    define PYBIND11_SIMPLE_GIL_MANAGEMENT
0293 #endif
0294 
0295 #if defined(_MSC_VER)
0296 #    if defined(PYBIND11_DEBUG_MARKER)
0297 #        define _DEBUG
0298 #        undef PYBIND11_DEBUG_MARKER
0299 #    endif
0300 PYBIND11_WARNING_POP
0301 #endif
0302 
0303 #include <cstddef>
0304 #include <cstring>
0305 #include <exception>
0306 #include <forward_list>
0307 #include <memory>
0308 #include <stdexcept>
0309 #include <string>
0310 #include <type_traits>
0311 #include <typeindex>
0312 #include <unordered_map>
0313 #include <unordered_set>
0314 #include <vector>
0315 #if defined(__has_include)
0316 #    if __has_include(<version>)
0317 #        include <version>
0318 #    endif
0319 #endif
0320 
0321 // Must be after including <version> or one of the other headers specified by the standard
0322 #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
0323 #    define PYBIND11_HAS_U8STRING
0324 #endif
0325 
0326 // See description of PR #4246:
0327 #if !defined(NDEBUG) && !defined(PY_ASSERT_GIL_HELD_INCREF_DECREF)                                \
0328     && !(defined(PYPY_VERSION)                                                                    \
0329          && defined(_MSC_VER)) /* PyPy Windows: pytest hangs indefinitely at the end of the       \
0330                                   process (see PR #4268) */                                       \
0331     && !defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
0332 // The following define will be enabled by default in the 2.11 release
0333 // define PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
0334 #endif
0335 
0336 // #define PYBIND11_STR_LEGACY_PERMISSIVE
0337 // If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
0338 //             (probably surprising and never documented, but this was the
0339 //             legacy behavior until and including v2.6.x). As a side-effect,
0340 //             pybind11::isinstance<str>() is true for both pybind11::str and
0341 //             pybind11::bytes.
0342 // If UNDEFINED, pybind11::str can only hold PyUnicodeObject, and
0343 //               pybind11::isinstance<str>() is true only for pybind11::str.
0344 //               However, for Python 2 only (!), the pybind11::str caster
0345 //               implicitly decoded bytes to PyUnicodeObject. This was to ease
0346 //               the transition from the legacy behavior to the non-permissive
0347 //               behavior.
0348 
0349 /// Compatibility macros for Python 2 / Python 3 versions TODO: remove
0350 #define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
0351 #define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
0352 #define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
0353 #define PYBIND11_BYTES_CHECK PyBytes_Check
0354 #define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
0355 #define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
0356 #define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
0357 #define PYBIND11_BYTES_AS_STRING PyBytes_AsString
0358 #define PYBIND11_BYTES_SIZE PyBytes_Size
0359 #define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
0360 #define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
0361 #define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) (o))
0362 #define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) (o))
0363 #define PYBIND11_BYTES_NAME "bytes"
0364 #define PYBIND11_STRING_NAME "str"
0365 #define PYBIND11_SLICE_OBJECT PyObject
0366 #define PYBIND11_FROM_STRING PyUnicode_FromString
0367 #define PYBIND11_STR_TYPE ::pybind11::str
0368 #define PYBIND11_BOOL_ATTR "__bool__"
0369 #define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
0370 #define PYBIND11_BUILTINS_MODULE "builtins"
0371 // Providing a separate declaration to make Clang's -Wmissing-prototypes happy.
0372 // See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
0373 #define PYBIND11_PLUGIN_IMPL(name)                                                                \
0374     extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT PyObject *PyInit_##name();                   \
0375     extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
0376 
0377 #define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
0378 #define PYBIND11_STRINGIFY(x) #x
0379 #define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
0380 #define PYBIND11_CONCAT(first, second) first##second
0381 #define PYBIND11_ENSURE_INTERNALS_READY pybind11::detail::get_internals();
0382 
0383 #define PYBIND11_CHECK_PYTHON_VERSION                                                             \
0384     {                                                                                             \
0385         const char *compiled_ver                                                                  \
0386             = PYBIND11_TOSTRING(PY_MAJOR_VERSION) "." PYBIND11_TOSTRING(PY_MINOR_VERSION);        \
0387         const char *runtime_ver = Py_GetVersion();                                                \
0388         size_t len = std::strlen(compiled_ver);                                                   \
0389         if (std::strncmp(runtime_ver, compiled_ver, len) != 0                                     \
0390             || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) {                            \
0391             PyErr_Format(PyExc_ImportError,                                                       \
0392                          "Python version mismatch: module was compiled for Python %s, "           \
0393                          "but the interpreter version is incompatible: %s.",                      \
0394                          compiled_ver,                                                            \
0395                          runtime_ver);                                                            \
0396             return nullptr;                                                                       \
0397         }                                                                                         \
0398     }
0399 
0400 #define PYBIND11_CATCH_INIT_EXCEPTIONS                                                            \
0401     catch (pybind11::error_already_set & e) {                                                     \
0402         pybind11::raise_from(e, PyExc_ImportError, "initialization failed");                      \
0403         return nullptr;                                                                           \
0404     }                                                                                             \
0405     catch (const std::exception &e) {                                                             \
0406         PyErr_SetString(PyExc_ImportError, e.what());                                             \
0407         return nullptr;                                                                           \
0408     }
0409 
0410 /** \rst
0411     ***Deprecated in favor of PYBIND11_MODULE***
0412 
0413     This macro creates the entry point that will be invoked when the Python interpreter
0414     imports a plugin library. Please create a `module_` in the function body and return
0415     the pointer to its underlying Python object at the end.
0416 
0417     .. code-block:: cpp
0418 
0419         PYBIND11_PLUGIN(example) {
0420             pybind11::module_ m("example", "pybind11 example plugin");
0421             /// Set up bindings here
0422             return m.ptr();
0423         }
0424 \endrst */
0425 #define PYBIND11_PLUGIN(name)                                                                     \
0426     PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE")                     \
0427     static PyObject *pybind11_init();                                                             \
0428     PYBIND11_PLUGIN_IMPL(name) {                                                                  \
0429         PYBIND11_CHECK_PYTHON_VERSION                                                             \
0430         PYBIND11_ENSURE_INTERNALS_READY                                                           \
0431         try {                                                                                     \
0432             return pybind11_init();                                                               \
0433         }                                                                                         \
0434         PYBIND11_CATCH_INIT_EXCEPTIONS                                                            \
0435     }                                                                                             \
0436     PyObject *pybind11_init()
0437 
0438 /** \rst
0439     This macro creates the entry point that will be invoked when the Python interpreter
0440     imports an extension module. The module name is given as the fist argument and it
0441     should not be in quotes. The second macro argument defines a variable of type
0442     `py::module_` which can be used to initialize the module.
0443 
0444     The entry point is marked as "maybe unused" to aid dead-code detection analysis:
0445     since the entry point is typically only looked up at runtime and not referenced
0446     during translation, it would otherwise appear as unused ("dead") code.
0447 
0448     .. code-block:: cpp
0449 
0450         PYBIND11_MODULE(example, m) {
0451             m.doc() = "pybind11 example module";
0452 
0453             // Add bindings here
0454             m.def("foo", []() {
0455                 return "Hello, World!";
0456             });
0457         }
0458 \endrst */
0459 #define PYBIND11_MODULE(name, variable)                                                           \
0460     static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name)            \
0461         PYBIND11_MAYBE_UNUSED;                                                                    \
0462     PYBIND11_MAYBE_UNUSED                                                                         \
0463     static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &);                     \
0464     PYBIND11_PLUGIN_IMPL(name) {                                                                  \
0465         PYBIND11_CHECK_PYTHON_VERSION                                                             \
0466         PYBIND11_ENSURE_INTERNALS_READY                                                           \
0467         auto m = ::pybind11::module_::create_extension_module(                                    \
0468             PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name));      \
0469         try {                                                                                     \
0470             PYBIND11_CONCAT(pybind11_init_, name)(m);                                             \
0471             return m.ptr();                                                                       \
0472         }                                                                                         \
0473         PYBIND11_CATCH_INIT_EXCEPTIONS                                                            \
0474     }                                                                                             \
0475     void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ & (variable))
0476 
0477 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0478 
0479 using ssize_t = Py_ssize_t;
0480 using size_t = std::size_t;
0481 
0482 template <typename IntType>
0483 inline ssize_t ssize_t_cast(const IntType &val) {
0484     static_assert(sizeof(IntType) <= sizeof(ssize_t), "Implicit narrowing is not permitted.");
0485     return static_cast<ssize_t>(val);
0486 }
0487 
0488 /// Approach used to cast a previously unknown C++ instance into a Python object
0489 enum class return_value_policy : uint8_t {
0490     /** This is the default return value policy, which falls back to the policy
0491         return_value_policy::take_ownership when the return value is a pointer.
0492         Otherwise, it uses return_value::move or return_value::copy for rvalue
0493         and lvalue references, respectively. See below for a description of what
0494         all of these different policies do. */
0495     automatic = 0,
0496 
0497     /** As above, but use policy return_value_policy::reference when the return
0498         value is a pointer. This is the default conversion policy for function
0499         arguments when calling Python functions manually from C++ code (i.e. via
0500         handle::operator()). You probably won't need to use this. */
0501     automatic_reference,
0502 
0503     /** Reference an existing object (i.e. do not create a new copy) and take
0504         ownership. Python will call the destructor and delete operator when the
0505         object's reference count reaches zero. Undefined behavior ensues when
0506         the C++ side does the same.. */
0507     take_ownership,
0508 
0509     /** Create a new copy of the returned object, which will be owned by
0510         Python. This policy is comparably safe because the lifetimes of the two
0511         instances are decoupled. */
0512     copy,
0513 
0514     /** Use std::move to move the return value contents into a new instance
0515         that will be owned by Python. This policy is comparably safe because the
0516         lifetimes of the two instances (move source and destination) are
0517         decoupled. */
0518     move,
0519 
0520     /** Reference an existing object, but do not take ownership. The C++ side
0521         is responsible for managing the object's lifetime and deallocating it
0522         when it is no longer used. Warning: undefined behavior will ensue when
0523         the C++ side deletes an object that is still referenced and used by
0524         Python. */
0525     reference,
0526 
0527     /** This policy only applies to methods and properties. It references the
0528         object without taking ownership similar to the above
0529         return_value_policy::reference policy. In contrast to that policy, the
0530         function or property's implicit this argument (called the parent) is
0531         considered to be the the owner of the return value (the child).
0532         pybind11 then couples the lifetime of the parent to the child via a
0533         reference relationship that ensures that the parent cannot be garbage
0534         collected while Python is still using the child. More advanced
0535         variations of this scheme are also possible using combinations of
0536         return_value_policy::reference and the keep_alive call policy */
0537     reference_internal
0538 };
0539 
0540 PYBIND11_NAMESPACE_BEGIN(detail)
0541 
0542 inline static constexpr int log2(size_t n, int k = 0) {
0543     return (n <= 1) ? k : log2(n >> 1, k + 1);
0544 }
0545 
0546 // Returns the size as a multiple of sizeof(void *), rounded up.
0547 inline static constexpr size_t size_in_ptrs(size_t s) {
0548     return 1 + ((s - 1) >> log2(sizeof(void *)));
0549 }
0550 
0551 /**
0552  * The space to allocate for simple layout instance holders (see below) in multiple of the size of
0553  * a pointer (e.g.  2 means 16 bytes on 64-bit architectures).  The default is the minimum required
0554  * to holder either a std::unique_ptr or std::shared_ptr (which is almost always
0555  * sizeof(std::shared_ptr<T>)).
0556  */
0557 constexpr size_t instance_simple_holder_in_ptrs() {
0558     static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
0559                   "pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
0560     return size_in_ptrs(sizeof(std::shared_ptr<int>));
0561 }
0562 
0563 // Forward declarations
0564 struct type_info;
0565 struct value_and_holder;
0566 
0567 struct nonsimple_values_and_holders {
0568     void **values_and_holders;
0569     uint8_t *status;
0570 };
0571 
0572 /// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
0573 struct instance {
0574     PyObject_HEAD
0575     /// Storage for pointers and holder; see simple_layout, below, for a description
0576     union {
0577         void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
0578         nonsimple_values_and_holders nonsimple;
0579     };
0580     /// Weak references
0581     PyObject *weakrefs;
0582     /// If true, the pointer is owned which means we're free to manage it with a holder.
0583     bool owned : 1;
0584     /**
0585      * An instance has two possible value/holder layouts.
0586      *
0587      * Simple layout (when this flag is true), means the `simple_value_holder` is set with a
0588      * pointer and the holder object governing that pointer, i.e. [val1*][holder].  This layout is
0589      * applied whenever there is no python-side multiple inheritance of bound C++ types *and* the
0590      * type's holder will fit in the default space (which is large enough to hold either a
0591      * std::unique_ptr or std::shared_ptr).
0592      *
0593      * Non-simple layout applies when using custom holders that require more space than
0594      * `shared_ptr` (which is typically the size of two pointers), or when multiple inheritance is
0595      * used on the python side.  Non-simple layout allocates the required amount of memory to have
0596      * multiple bound C++ classes as parents.  Under this layout, `nonsimple.values_and_holders` is
0597      * set to a pointer to allocated space of the required space to hold a sequence of value
0598      * pointers and holders followed `status`, a set of bit flags (1 byte each), i.e.
0599      * [val1*][holder1][val2*][holder2]...[bb...]  where each [block] is rounded up to a multiple
0600      * of `sizeof(void *)`.  `nonsimple.status` is, for convenience, a pointer to the beginning of
0601      * the [bb...] block (but not independently allocated).
0602      *
0603      * Status bits indicate whether the associated holder is constructed (&
0604      * status_holder_constructed) and whether the value pointer is registered (&
0605      * status_instance_registered) in `registered_instances`.
0606      */
0607     bool simple_layout : 1;
0608     /// For simple layout, tracks whether the holder has been constructed
0609     bool simple_holder_constructed : 1;
0610     /// For simple layout, tracks whether the instance is registered in `registered_instances`
0611     bool simple_instance_registered : 1;
0612     /// If true, get_internals().patients has an entry for this object
0613     bool has_patients : 1;
0614 
0615     /// Initializes all of the above type/values/holders data (but not the instance values
0616     /// themselves)
0617     void allocate_layout();
0618 
0619     /// Destroys/deallocates all of the above
0620     void deallocate_layout();
0621 
0622     /// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
0623     /// omitted).  Returns a default-constructed (with `.inst = nullptr`) object on failure if
0624     /// `throw_if_missing` is false.
0625     value_and_holder get_value_and_holder(const type_info *find_type = nullptr,
0626                                           bool throw_if_missing = true);
0627 
0628     /// Bit values for the non-simple status flags
0629     static constexpr uint8_t status_holder_constructed = 1;
0630     static constexpr uint8_t status_instance_registered = 2;
0631 };
0632 
0633 static_assert(std::is_standard_layout<instance>::value,
0634               "Internal error: `pybind11::detail::instance` is not standard layout!");
0635 
0636 /// from __cpp_future__ import (convenient aliases from C++14/17)
0637 #if defined(PYBIND11_CPP14)
0638 using std::conditional_t;
0639 using std::enable_if_t;
0640 using std::remove_cv_t;
0641 using std::remove_reference_t;
0642 #else
0643 template <bool B, typename T = void>
0644 using enable_if_t = typename std::enable_if<B, T>::type;
0645 template <bool B, typename T, typename F>
0646 using conditional_t = typename std::conditional<B, T, F>::type;
0647 template <typename T>
0648 using remove_cv_t = typename std::remove_cv<T>::type;
0649 template <typename T>
0650 using remove_reference_t = typename std::remove_reference<T>::type;
0651 #endif
0652 
0653 #if defined(PYBIND11_CPP20)
0654 using std::remove_cvref;
0655 using std::remove_cvref_t;
0656 #else
0657 template <class T>
0658 struct remove_cvref {
0659     using type = remove_cv_t<remove_reference_t<T>>;
0660 };
0661 template <class T>
0662 using remove_cvref_t = typename remove_cvref<T>::type;
0663 #endif
0664 
0665 /// Index sequences
0666 #if defined(PYBIND11_CPP14)
0667 using std::index_sequence;
0668 using std::make_index_sequence;
0669 #else
0670 template <size_t...>
0671 struct index_sequence {};
0672 template <size_t N, size_t... S>
0673 struct make_index_sequence_impl : make_index_sequence_impl<N - 1, N - 1, S...> {};
0674 template <size_t... S>
0675 struct make_index_sequence_impl<0, S...> {
0676     using type = index_sequence<S...>;
0677 };
0678 template <size_t N>
0679 using make_index_sequence = typename make_index_sequence_impl<N>::type;
0680 #endif
0681 
0682 /// Make an index sequence of the indices of true arguments
0683 template <typename ISeq, size_t, bool...>
0684 struct select_indices_impl {
0685     using type = ISeq;
0686 };
0687 template <size_t... IPrev, size_t I, bool B, bool... Bs>
0688 struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
0689     : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>,
0690                           I + 1,
0691                           Bs...> {};
0692 template <bool... Bs>
0693 using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
0694 
0695 /// Backports of std::bool_constant and std::negation to accommodate older compilers
0696 template <bool B>
0697 using bool_constant = std::integral_constant<bool, B>;
0698 template <typename T>
0699 struct negation : bool_constant<!T::value> {};
0700 
0701 // PGI/Intel cannot detect operator delete with the "compatible" void_t impl, so
0702 // using the new one (C++14 defect, so generally works on newer compilers, even
0703 // if not in C++17 mode)
0704 #if defined(__PGIC__) || defined(__INTEL_COMPILER)
0705 template <typename...>
0706 using void_t = void;
0707 #else
0708 template <typename...>
0709 struct void_t_impl {
0710     using type = void;
0711 };
0712 template <typename... Ts>
0713 using void_t = typename void_t_impl<Ts...>::type;
0714 #endif
0715 
0716 /// Compile-time all/any/none of that check the boolean value of all template types
0717 #if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
0718 template <class... Ts>
0719 using all_of = bool_constant<(Ts::value && ...)>;
0720 template <class... Ts>
0721 using any_of = bool_constant<(Ts::value || ...)>;
0722 #elif !defined(_MSC_VER)
0723 template <bool...>
0724 struct bools {};
0725 template <class... Ts>
0726 using all_of = std::is_same<bools<Ts::value..., true>, bools<true, Ts::value...>>;
0727 template <class... Ts>
0728 using any_of = negation<all_of<negation<Ts>...>>;
0729 #else
0730 // MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
0731 // at a slight loss of compilation efficiency).
0732 template <class... Ts>
0733 using all_of = std::conjunction<Ts...>;
0734 template <class... Ts>
0735 using any_of = std::disjunction<Ts...>;
0736 #endif
0737 template <class... Ts>
0738 using none_of = negation<any_of<Ts...>>;
0739 
0740 template <class T, template <class> class... Predicates>
0741 using satisfies_all_of = all_of<Predicates<T>...>;
0742 template <class T, template <class> class... Predicates>
0743 using satisfies_any_of = any_of<Predicates<T>...>;
0744 template <class T, template <class> class... Predicates>
0745 using satisfies_none_of = none_of<Predicates<T>...>;
0746 
0747 /// Strip the class from a method type
0748 template <typename T>
0749 struct remove_class {};
0750 template <typename C, typename R, typename... A>
0751 struct remove_class<R (C::*)(A...)> {
0752     using type = R(A...);
0753 };
0754 template <typename C, typename R, typename... A>
0755 struct remove_class<R (C::*)(A...) const> {
0756     using type = R(A...);
0757 };
0758 
0759 /// Helper template to strip away type modifiers
0760 template <typename T>
0761 struct intrinsic_type {
0762     using type = T;
0763 };
0764 template <typename T>
0765 struct intrinsic_type<const T> {
0766     using type = typename intrinsic_type<T>::type;
0767 };
0768 template <typename T>
0769 struct intrinsic_type<T *> {
0770     using type = typename intrinsic_type<T>::type;
0771 };
0772 template <typename T>
0773 struct intrinsic_type<T &> {
0774     using type = typename intrinsic_type<T>::type;
0775 };
0776 template <typename T>
0777 struct intrinsic_type<T &&> {
0778     using type = typename intrinsic_type<T>::type;
0779 };
0780 template <typename T, size_t N>
0781 struct intrinsic_type<const T[N]> {
0782     using type = typename intrinsic_type<T>::type;
0783 };
0784 template <typename T, size_t N>
0785 struct intrinsic_type<T[N]> {
0786     using type = typename intrinsic_type<T>::type;
0787 };
0788 template <typename T>
0789 using intrinsic_t = typename intrinsic_type<T>::type;
0790 
0791 /// Helper type to replace 'void' in some expressions
0792 struct void_type {};
0793 
0794 /// Helper template which holds a list of types
0795 template <typename...>
0796 struct type_list {};
0797 
0798 /// Compile-time integer sum
0799 #ifdef __cpp_fold_expressions
0800 template <typename... Ts>
0801 constexpr size_t constexpr_sum(Ts... ns) {
0802     return (0 + ... + size_t{ns});
0803 }
0804 #else
0805 constexpr size_t constexpr_sum() { return 0; }
0806 template <typename T, typename... Ts>
0807 constexpr size_t constexpr_sum(T n, Ts... ns) {
0808     return size_t{n} + constexpr_sum(ns...);
0809 }
0810 #endif
0811 
0812 PYBIND11_NAMESPACE_BEGIN(constexpr_impl)
0813 /// Implementation details for constexpr functions
0814 constexpr int first(int i) { return i; }
0815 template <typename T, typename... Ts>
0816 constexpr int first(int i, T v, Ts... vs) {
0817     return v ? i : first(i + 1, vs...);
0818 }
0819 
0820 constexpr int last(int /*i*/, int result) { return result; }
0821 template <typename T, typename... Ts>
0822 constexpr int last(int i, int result, T v, Ts... vs) {
0823     return last(i + 1, v ? i : result, vs...);
0824 }
0825 PYBIND11_NAMESPACE_END(constexpr_impl)
0826 
0827 /// Return the index of the first type in Ts which satisfies Predicate<T>.
0828 /// Returns sizeof...(Ts) if none match.
0829 template <template <typename> class Predicate, typename... Ts>
0830 constexpr int constexpr_first() {
0831     return constexpr_impl::first(0, Predicate<Ts>::value...);
0832 }
0833 
0834 /// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
0835 template <template <typename> class Predicate, typename... Ts>
0836 constexpr int constexpr_last() {
0837     return constexpr_impl::last(0, -1, Predicate<Ts>::value...);
0838 }
0839 
0840 /// Return the Nth element from the parameter pack
0841 template <size_t N, typename T, typename... Ts>
0842 struct pack_element {
0843     using type = typename pack_element<N - 1, Ts...>::type;
0844 };
0845 template <typename T, typename... Ts>
0846 struct pack_element<0, T, Ts...> {
0847     using type = T;
0848 };
0849 
0850 /// Return the one and only type which matches the predicate, or Default if none match.
0851 /// If more than one type matches the predicate, fail at compile-time.
0852 template <template <typename> class Predicate, typename Default, typename... Ts>
0853 struct exactly_one {
0854     static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
0855     static_assert(found <= 1, "Found more than one type matching the predicate");
0856 
0857     static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
0858     using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
0859 };
0860 template <template <typename> class P, typename Default>
0861 struct exactly_one<P, Default> {
0862     using type = Default;
0863 };
0864 
0865 template <template <typename> class Predicate, typename Default, typename... Ts>
0866 using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
0867 
0868 /// Defer the evaluation of type T until types Us are instantiated
0869 template <typename T, typename... /*Us*/>
0870 struct deferred_type {
0871     using type = T;
0872 };
0873 template <typename T, typename... Us>
0874 using deferred_t = typename deferred_type<T, Us...>::type;
0875 
0876 /// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
0877 /// unlike `std::is_base_of`)
0878 template <typename Base, typename Derived>
0879 using is_strict_base_of
0880     = bool_constant<std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
0881 
0882 /// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived
0883 /// pointer can be converted to a Base pointer) For unions, `is_base_of<T, T>::value` is False, so
0884 /// we need to check `is_same` as well.
0885 template <typename Base, typename Derived>
0886 using is_accessible_base_of
0887     = bool_constant<(std::is_same<Base, Derived>::value || std::is_base_of<Base, Derived>::value)
0888                     && std::is_convertible<Derived *, Base *>::value>;
0889 
0890 template <template <typename...> class Base>
0891 struct is_template_base_of_impl {
0892     template <typename... Us>
0893     static std::true_type check(Base<Us...> *);
0894     static std::false_type check(...);
0895 };
0896 
0897 /// Check if a template is the base of a type. For example:
0898 /// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
0899 template <template <typename...> class Base, typename T>
0900 // Sadly, all MSVC versions incl. 2022 need the workaround, even in C++20 mode.
0901 // See also: https://github.com/pybind/pybind11/pull/3741
0902 #if !defined(_MSC_VER)
0903 using is_template_base_of
0904     = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr));
0905 #else
0906 struct is_template_base_of
0907     : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)) {
0908 };
0909 #endif
0910 
0911 /// Check if T is an instantiation of the template `Class`. For example:
0912 /// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
0913 template <template <typename...> class Class, typename T>
0914 struct is_instantiation : std::false_type {};
0915 template <template <typename...> class Class, typename... Us>
0916 struct is_instantiation<Class, Class<Us...>> : std::true_type {};
0917 
0918 /// Check if T is std::shared_ptr<U> where U can be anything
0919 template <typename T>
0920 using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
0921 
0922 /// Check if T looks like an input iterator
0923 template <typename T, typename = void>
0924 struct is_input_iterator : std::false_type {};
0925 template <typename T>
0926 struct is_input_iterator<T,
0927                          void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
0928     : std::true_type {};
0929 
0930 template <typename T>
0931 using is_function_pointer
0932     = bool_constant<std::is_pointer<T>::value
0933                     && std::is_function<typename std::remove_pointer<T>::type>::value>;
0934 
0935 template <typename F>
0936 struct strip_function_object {
0937     // If you are encountering an
0938     // 'error: name followed by "::" must be a class or namespace name'
0939     // with the Intel compiler and a noexcept function here,
0940     // try to use noexcept(true) instead of plain noexcept.
0941     using type = typename remove_class<decltype(&F::operator())>::type;
0942 };
0943 
0944 // Extracts the function signature from a function, function pointer or lambda.
0945 template <typename Function, typename F = remove_reference_t<Function>>
0946 using function_signature_t = conditional_t<
0947     std::is_function<F>::value,
0948     F,
0949     typename conditional_t<std::is_pointer<F>::value || std::is_member_pointer<F>::value,
0950                            std::remove_pointer<F>,
0951                            strip_function_object<F>>::type>;
0952 
0953 /// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
0954 /// pointer.  Note that this can catch all sorts of other things, too; this is intended to be used
0955 /// in a place where passing a lambda makes sense.
0956 template <typename T>
0957 using is_lambda = satisfies_none_of<remove_reference_t<T>,
0958                                     std::is_function,
0959                                     std::is_pointer,
0960                                     std::is_member_pointer>;
0961 
0962 // [workaround(intel)] Internal error on fold expression
0963 /// Apply a function over each element of a parameter pack
0964 #if defined(__cpp_fold_expressions) && !defined(__INTEL_COMPILER)
0965 // Intel compiler produces an internal error on this fold expression (tested with ICC 19.0.2)
0966 #    define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
0967 #else
0968 using expand_side_effects = bool[];
0969 #    define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)                                                 \
0970         (void) pybind11::detail::expand_side_effects { ((PATTERN), void(), false)..., false }
0971 #endif
0972 
0973 PYBIND11_NAMESPACE_END(detail)
0974 
0975 /// C++ bindings of builtin Python exceptions
0976 class PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error {
0977 public:
0978     using std::runtime_error::runtime_error;
0979     /// Set the error using the Python C API
0980     virtual void set_error() const = 0;
0981 };
0982 
0983 #define PYBIND11_RUNTIME_EXCEPTION(name, type)                                                    \
0984     class PYBIND11_EXPORT_EXCEPTION name : public builtin_exception {                             \
0985     public:                                                                                       \
0986         using builtin_exception::builtin_exception;                                               \
0987         name() : name("") {}                                                                      \
0988         void set_error() const override { PyErr_SetString(type, what()); }                        \
0989     };
0990 
0991 PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
0992 PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
0993 PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
0994 PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
0995 PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
0996 PYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)
0997 PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
0998 PYBIND11_RUNTIME_EXCEPTION(attribute_error, PyExc_AttributeError)
0999 PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or
1000                                                            /// handle::call fail due to a type
1001                                                            /// casting error
1002 PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
1003 
1004 [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason) {
1005     assert(!PyErr_Occurred());
1006     throw std::runtime_error(reason);
1007 }
1008 [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const std::string &reason) {
1009     assert(!PyErr_Occurred());
1010     throw std::runtime_error(reason);
1011 }
1012 
1013 template <typename T, typename SFINAE = void>
1014 struct format_descriptor {};
1015 
1016 PYBIND11_NAMESPACE_BEGIN(detail)
1017 // Returns the index of the given type in the type char array below, and in the list in numpy.h
1018 // The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
1019 // complex float,double,long double.  Note that the long double types only participate when long
1020 // double is actually longer than double (it isn't under MSVC).
1021 // NB: not only the string below but also complex.h and numpy.h rely on this order.
1022 template <typename T, typename SFINAE = void>
1023 struct is_fmt_numeric {
1024     static constexpr bool value = false;
1025 };
1026 template <typename T>
1027 struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
1028     static constexpr bool value = true;
1029     static constexpr int index
1030         = std::is_same<T, bool>::value
1031               ? 0
1032               : 1
1033                     + (std::is_integral<T>::value
1034                            ? detail::log2(sizeof(T)) * 2 + std::is_unsigned<T>::value
1035                            : 8
1036                                  + (std::is_same<T, double>::value        ? 1
1037                                     : std::is_same<T, long double>::value ? 2
1038                                                                           : 0));
1039 };
1040 PYBIND11_NAMESPACE_END(detail)
1041 
1042 template <typename T>
1043 struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
1044     static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
1045     static constexpr const char value[2] = {c, '\0'};
1046     static std::string format() { return std::string(1, c); }
1047 };
1048 
1049 #if !defined(PYBIND11_CPP17)
1050 
1051 template <typename T>
1052 constexpr const char
1053     format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
1054 
1055 #endif
1056 
1057 /// RAII wrapper that temporarily clears any Python error state
1058 struct error_scope {
1059     PyObject *type, *value, *trace;
1060     error_scope() { PyErr_Fetch(&type, &value, &trace); }
1061     error_scope(const error_scope &) = delete;
1062     error_scope &operator=(const error_scope &) = delete;
1063     ~error_scope() { PyErr_Restore(type, value, trace); }
1064 };
1065 
1066 /// Dummy destructor wrapper that can be used to expose classes with a private destructor
1067 struct nodelete {
1068     template <typename T>
1069     void operator()(T *) {}
1070 };
1071 
1072 PYBIND11_NAMESPACE_BEGIN(detail)
1073 template <typename... Args>
1074 struct overload_cast_impl {
1075     template <typename Return>
1076     constexpr auto operator()(Return (*pf)(Args...)) const noexcept -> decltype(pf) {
1077         return pf;
1078     }
1079 
1080     template <typename Return, typename Class>
1081     constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
1082         -> decltype(pmf) {
1083         return pmf;
1084     }
1085 
1086     template <typename Return, typename Class>
1087     constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
1088         -> decltype(pmf) {
1089         return pmf;
1090     }
1091 };
1092 PYBIND11_NAMESPACE_END(detail)
1093 
1094 // overload_cast requires variable templates: C++14
1095 #if defined(PYBIND11_CPP14)
1096 #    define PYBIND11_OVERLOAD_CAST 1
1097 /// Syntax sugar for resolving overloaded function pointers:
1098 ///  - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
1099 ///  - sweet:   overload_cast<Arg0, Arg1, Arg2>(&Class::func)
1100 template <typename... Args>
1101 static constexpr detail::overload_cast_impl<Args...> overload_cast{};
1102 #endif
1103 
1104 /// Const member function selector for overload_cast
1105 ///  - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
1106 ///  - sweet:   overload_cast<Arg>(&Class::func, const_)
1107 static constexpr auto const_ = std::true_type{};
1108 
1109 #if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:
1110 template <typename... Args>
1111 struct overload_cast {
1112     static_assert(detail::deferred_t<std::false_type, Args...>::value,
1113                   "pybind11::overload_cast<...> requires compiling in C++14 mode");
1114 };
1115 #endif // overload_cast
1116 
1117 PYBIND11_NAMESPACE_BEGIN(detail)
1118 
1119 // Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
1120 // any standard container (or C-style array) supporting std::begin/std::end, any singleton
1121 // arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
1122 template <typename T>
1123 class any_container {
1124     std::vector<T> v;
1125 
1126 public:
1127     any_container() = default;
1128 
1129     // Can construct from a pair of iterators
1130     template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
1131     any_container(It first, It last) : v(first, last) {}
1132 
1133     // Implicit conversion constructor from any arbitrary container type
1134     // with values convertible to T
1135     template <typename Container,
1136               typename = enable_if_t<
1137                   std::is_convertible<decltype(*std::begin(std::declval<const Container &>())),
1138                                       T>::value>>
1139     // NOLINTNEXTLINE(google-explicit-constructor)
1140     any_container(const Container &c) : any_container(std::begin(c), std::end(c)) {}
1141 
1142     // initializer_list's aren't deducible, so don't get matched by the above template;
1143     // we need this to explicitly allow implicit conversion from one:
1144     template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
1145     any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) {}
1146 
1147     // Avoid copying if given an rvalue vector of the correct type.
1148     // NOLINTNEXTLINE(google-explicit-constructor)
1149     any_container(std::vector<T> &&v) : v(std::move(v)) {}
1150 
1151     // Moves the vector out of an rvalue any_container
1152     // NOLINTNEXTLINE(google-explicit-constructor)
1153     operator std::vector<T> &&() && { return std::move(v); }
1154 
1155     // Dereferencing obtains a reference to the underlying vector
1156     std::vector<T> &operator*() { return v; }
1157     const std::vector<T> &operator*() const { return v; }
1158 
1159     // -> lets you call methods on the underlying vector
1160     std::vector<T> *operator->() { return &v; }
1161     const std::vector<T> *operator->() const { return &v; }
1162 };
1163 
1164 // Forward-declaration; see detail/class.h
1165 std::string get_fully_qualified_tp_name(PyTypeObject *);
1166 
1167 template <typename T>
1168 inline static std::shared_ptr<T>
1169 try_get_shared_from_this(std::enable_shared_from_this<T> *holder_value_ptr) {
1170 // Pre C++17, this code path exploits undefined behavior, but is known to work on many platforms.
1171 // Use at your own risk!
1172 // See also https://en.cppreference.com/w/cpp/memory/enable_shared_from_this, and in particular
1173 // the `std::shared_ptr<Good> gp1 = not_so_good.getptr();` and `try`-`catch` parts of the example.
1174 #if defined(__cpp_lib_enable_shared_from_this) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1175     return holder_value_ptr->weak_from_this().lock();
1176 #else
1177     try {
1178         return holder_value_ptr->shared_from_this();
1179     } catch (const std::bad_weak_ptr &) {
1180         return nullptr;
1181     }
1182 #endif
1183 }
1184 
1185 // For silencing "unused" compiler warnings in special situations.
1186 template <typename... Args>
1187 #if defined(_MSC_VER) && _MSC_VER < 1920 // MSVC 2017
1188 constexpr
1189 #endif
1190     inline void
1191     silence_unused_warnings(Args &&...) {
1192 }
1193 
1194 // MSVC warning C4100: Unreferenced formal parameter
1195 #if defined(_MSC_VER) && _MSC_VER <= 1916
1196 #    define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)                                         \
1197         detail::silence_unused_warnings(__VA_ARGS__)
1198 #else
1199 #    define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
1200 #endif
1201 
1202 // GCC -Wunused-but-set-parameter  All GCC versions (as of July 2021).
1203 #if defined(__GNUG__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
1204 #    define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)                       \
1205         detail::silence_unused_warnings(__VA_ARGS__)
1206 #else
1207 #    define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)
1208 #endif
1209 
1210 #if defined(__clang__)                                                                            \
1211     && (defined(__apple_build_version__) /* AppleClang 13.0.0.13000029 was the only data point    \
1212                                             available. */                                         \
1213         || (__clang_major__ >= 7                                                                  \
1214             && __clang_major__ <= 12) /* Clang 3, 5, 13, 14, 15 do not generate the warning. */   \
1215     )
1216 #    define PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
1217 // Example:
1218 // tests/test_kwargs_and_defaults.cpp:46:68: error: local variable 'args' will be copied despite
1219 // being returned by name [-Werror,-Wreturn-std-move]
1220 //     m.def("args_function", [](py::args args) -> py::tuple { return args; });
1221 //                                                                    ^~~~
1222 // test_kwargs_and_defaults.cpp:46:68: note: call 'std::move' explicitly to avoid copying
1223 //     m.def("args_function", [](py::args args) -> py::tuple { return args; });
1224 //                                                                    ^~~~
1225 //                                                                    std::move(args)
1226 #endif
1227 
1228 // Pybind offers detailed error messages by default for all builts that are debug (through the
1229 // negation of ndebug). This can also be manually enabled by users, for any builds, through
1230 // defining PYBIND11_DETAILED_ERROR_MESSAGES.
1231 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(NDEBUG)
1232 #    define PYBIND11_DETAILED_ERROR_MESSAGES
1233 #endif
1234 
1235 PYBIND11_NAMESPACE_END(detail)
1236 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)