Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 10:06:11

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