common.h 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  1. #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
  2. /*
  3. pybind11/detail/common.h -- Basic macros
  4. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #pragma once
  9. #include <pybind11/conduit/wrap_include_python_h.h>
  10. #if PY_VERSION_HEX < 0x03080000
  11. # error "PYTHON < 3.8 IS UNSUPPORTED. pybind11 v2.13 was the last to support Python 3.7."
  12. #endif
  13. // Similar to Python's convention: https://docs.python.org/3/c-api/apiabiversion.html
  14. // See also: https://github.com/python/cpython/blob/HEAD/Include/patchlevel.h
  15. /* -- start version constants -- */
  16. #define PYBIND11_VERSION_MAJOR 3
  17. #define PYBIND11_VERSION_MINOR 0
  18. #define PYBIND11_VERSION_MICRO 1
  19. // ALPHA = 0xA, BETA = 0xB, GAMMA = 0xC (release candidate), FINAL = 0xF (stable release)
  20. // - The release level is set to "alpha" for development versions.
  21. // Use 0xA0 (LEVEL=0xA, SERIAL=0) for development versions.
  22. // - For stable releases, set the serial to 0.
  23. #define PYBIND11_VERSION_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL
  24. #define PYBIND11_VERSION_RELEASE_SERIAL 0
  25. // String version of (micro, release level, release serial), e.g.: 0a0, 0b1, 0rc1, 0
  26. #define PYBIND11_VERSION_PATCH 1
  27. /* -- end version constants -- */
  28. #if !defined(Py_PACK_FULL_VERSION)
  29. // Stable API since Python 3.14.0a4
  30. # define Py_PACK_FULL_VERSION(X, Y, Z, LEVEL, SERIAL) \
  31. ((((X) & 0xff) << 24) | (((Y) & 0xff) << 16) | (((Z) & 0xff) << 8) \
  32. | (((LEVEL) & 0xf) << 4) | (((SERIAL) & 0xf) << 0))
  33. #endif
  34. // Version as a single 4-byte hex number, e.g. 0x030C04B5 == 3.12.4b5.
  35. #define PYBIND11_VERSION_HEX \
  36. Py_PACK_FULL_VERSION(PYBIND11_VERSION_MAJOR, \
  37. PYBIND11_VERSION_MINOR, \
  38. PYBIND11_VERSION_MICRO, \
  39. PYBIND11_VERSION_RELEASE_LEVEL, \
  40. PYBIND11_VERSION_RELEASE_SERIAL)
  41. #include "pybind11_namespace_macros.h"
  42. #if !(defined(_MSC_VER) && __cplusplus == 199711L)
  43. # if __cplusplus >= 201402L
  44. # define PYBIND11_CPP14
  45. # if __cplusplus >= 201703L
  46. # define PYBIND11_CPP17
  47. # if __cplusplus >= 202002L
  48. # define PYBIND11_CPP20
  49. // Please update tests/pybind11_tests.cpp `cpp_std()` when adding a macro here.
  50. # endif
  51. # endif
  52. # endif
  53. #elif defined(_MSC_VER) && __cplusplus == 199711L
  54. // MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully
  55. // implemented). Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3
  56. // or newer.
  57. # if _MSVC_LANG >= 201402L
  58. # define PYBIND11_CPP14
  59. # if _MSVC_LANG > 201402L
  60. # define PYBIND11_CPP17
  61. # if _MSVC_LANG >= 202002L
  62. # define PYBIND11_CPP20
  63. # endif
  64. # endif
  65. # endif
  66. #endif
  67. // These PYBIND11_HAS_... macros are consolidated in pybind11/detail/common.h
  68. // to simplify backward compatibility handling for users (e.g., via #ifdef checks):
  69. #define PYBIND11_HAS_TYPE_CASTER_STD_FUNCTION_SPECIALIZATIONS 1
  70. #define PYBIND11_HAS_INTERNALS_WITH_SMART_HOLDER_SUPPORT 1
  71. #define PYBIND11_HAS_CPP_CONDUIT 1
  72. #define PYBIND11_HAS_NATIVE_ENUM 1
  73. #if defined(PYBIND11_CPP17) && defined(__has_include)
  74. # if __has_include(<filesystem>)
  75. # define PYBIND11_HAS_FILESYSTEM 1
  76. # elif __has_include(<experimental/filesystem>)
  77. # define PYBIND11_HAS_EXPERIMENTAL_FILESYSTEM 1
  78. # endif
  79. #endif
  80. #if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914))
  81. # define PYBIND11_STD_LAUNDER std::launder
  82. # define PYBIND11_HAS_STD_LAUNDER 1
  83. #else
  84. # define PYBIND11_STD_LAUNDER
  85. # define PYBIND11_HAS_STD_LAUNDER 0
  86. #endif
  87. #if defined(PYBIND11_CPP20)
  88. # define PYBIND11_CONSTINIT constinit
  89. # define PYBIND11_DTOR_CONSTEXPR constexpr
  90. #else
  91. # define PYBIND11_CONSTINIT
  92. # define PYBIND11_DTOR_CONSTEXPR
  93. #endif
  94. // Compiler version assertions
  95. #if defined(__INTEL_COMPILER)
  96. # if __INTEL_COMPILER < 1800
  97. # error pybind11 requires Intel C++ compiler v18 or newer
  98. # elif __INTEL_COMPILER < 1900 && defined(PYBIND11_CPP14)
  99. # error pybind11 supports only C++11 with Intel C++ compiler v18. Use v19 or newer for C++14.
  100. # endif
  101. /* The following pragma cannot be pop'ed:
  102. https://community.intel.com/t5/Intel-C-Compiler/Inline-and-no-inline-warning/td-p/1216764 */
  103. # pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
  104. #elif defined(__clang__) && !defined(__apple_build_version__)
  105. # if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
  106. # error pybind11 requires clang 3.3 or newer
  107. # endif
  108. #elif defined(__clang__)
  109. // Apple changes clang version macros to its Xcode version; the first Xcode release based on
  110. // (upstream) clang 3.3 was Xcode 5:
  111. # if __clang_major__ < 5
  112. # error pybind11 requires Xcode/clang 5.0 or newer
  113. # endif
  114. #elif defined(__GNUG__)
  115. # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
  116. # error pybind11 requires gcc 4.8 or newer
  117. # endif
  118. #elif defined(_MSC_VER)
  119. # if _MSC_VER < 1910
  120. # error pybind11 2.10+ requires MSVC 2017 or newer
  121. # endif
  122. #endif
  123. #if !defined(PYBIND11_EXPORT)
  124. # if defined(WIN32) || defined(_WIN32)
  125. # define PYBIND11_EXPORT __declspec(dllexport)
  126. # else
  127. # define PYBIND11_EXPORT __attribute__((visibility("default")))
  128. # endif
  129. #endif
  130. // For CUDA, GCC7, GCC8:
  131. // PYBIND11_NOINLINE_FORCED is incompatible with `-Wattributes -Werror`.
  132. // When defining PYBIND11_NOINLINE_FORCED, it is best to also use `-Wno-attributes`.
  133. // However, the measured shared-library size saving when using noinline are only
  134. // 1.7% for CUDA, -0.2% for GCC7, and 0.0% for GCC8 (using -DCMAKE_BUILD_TYPE=MinSizeRel,
  135. // the default under pybind11/tests).
  136. #if !defined(PYBIND11_NOINLINE_FORCED) \
  137. && (defined(__CUDACC__) || (defined(__GNUC__) && (__GNUC__ == 7 || __GNUC__ == 8)))
  138. # define PYBIND11_NOINLINE_DISABLED
  139. #endif
  140. // The PYBIND11_NOINLINE macro is for function DEFINITIONS.
  141. // In contrast, FORWARD DECLARATIONS should never use this macro:
  142. // https://stackoverflow.com/questions/9317473/forward-declaration-of-inline-functions
  143. #if defined(PYBIND11_NOINLINE_DISABLED) // Option for maximum portability and experimentation.
  144. # define PYBIND11_NOINLINE inline
  145. #elif defined(_MSC_VER)
  146. # define PYBIND11_NOINLINE __declspec(noinline) inline
  147. #else
  148. # define PYBIND11_NOINLINE __attribute__((noinline)) inline
  149. #endif
  150. #if defined(__MINGW32__)
  151. // For unknown reasons all PYBIND11_DEPRECATED member trigger a warning when declared
  152. // whether it is used or not
  153. # define PYBIND11_DEPRECATED(reason)
  154. #elif defined(PYBIND11_CPP14)
  155. # define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
  156. #else
  157. # define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
  158. #endif
  159. #if defined(PYBIND11_CPP17)
  160. # define PYBIND11_MAYBE_UNUSED [[maybe_unused]]
  161. #elif defined(_MSC_VER) && !defined(__clang__)
  162. # define PYBIND11_MAYBE_UNUSED
  163. #else
  164. # define PYBIND11_MAYBE_UNUSED __attribute__((__unused__))
  165. #endif
  166. // https://en.cppreference.com/w/c/chrono/localtime
  167. #if defined(__STDC_LIB_EXT1__) && !defined(__STDC_WANT_LIB_EXT1__)
  168. # define __STDC_WANT_LIB_EXT1__
  169. #endif
  170. #ifdef __has_include
  171. // std::optional (but including it in c++14 mode isn't allowed)
  172. # if defined(PYBIND11_CPP17) && __has_include(<optional>)
  173. # define PYBIND11_HAS_OPTIONAL 1
  174. # endif
  175. // std::experimental::optional (but not allowed in c++11 mode)
  176. # if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
  177. !__has_include(<optional>))
  178. # define PYBIND11_HAS_EXP_OPTIONAL 1
  179. # endif
  180. // std::variant
  181. # if defined(PYBIND11_CPP17) && __has_include(<variant>)
  182. # define PYBIND11_HAS_VARIANT 1
  183. # endif
  184. #elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
  185. # define PYBIND11_HAS_OPTIONAL 1
  186. # define PYBIND11_HAS_VARIANT 1
  187. #endif
  188. #if defined(PYBIND11_CPP17) \
  189. && ((defined(__has_include) && __has_include(<string_view>)) || defined(_MSC_VER))
  190. # define PYBIND11_HAS_STRING_VIEW 1
  191. #endif
  192. #if (defined(PYPY_VERSION) || defined(GRAALVM_PYTHON)) && !defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
  193. # define PYBIND11_SIMPLE_GIL_MANAGEMENT
  194. #endif
  195. #include <cstddef>
  196. #include <cstring>
  197. #include <exception>
  198. #include <forward_list>
  199. #include <memory>
  200. #include <stdexcept>
  201. #include <string>
  202. #include <type_traits>
  203. #include <typeindex>
  204. #include <unordered_map>
  205. #include <unordered_set>
  206. #include <vector>
  207. #if defined(__has_include)
  208. # if __has_include(<version>)
  209. # include <version>
  210. # endif
  211. #endif
  212. // For libc++, the exceptions should be exported,
  213. // otherwise, the exception translation would be incorrect.
  214. // IMPORTANT: This code block must stay BELOW the #include <exception> above (see PR #5390).
  215. #if !defined(PYBIND11_EXPORT_EXCEPTION)
  216. # if defined(_LIBCPP_EXCEPTION)
  217. # define PYBIND11_EXPORT_EXCEPTION PYBIND11_EXPORT
  218. # else
  219. # define PYBIND11_EXPORT_EXCEPTION
  220. # endif
  221. #endif
  222. // Must be after including <version> or one of the other headers specified by the standard
  223. #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
  224. # define PYBIND11_HAS_U8STRING 1
  225. #endif
  226. // See description of PR #4246:
  227. #if !defined(PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF) && !defined(NDEBUG) \
  228. && !defined(PYPY_VERSION) && !defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
  229. # define PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
  230. #endif
  231. // Slightly faster code paths are available when PYBIND11_HAS_SUBINTERPRETER_SUPPORT is *not*
  232. // defined, so avoid defining it for implementations that do not support subinterpreters. However,
  233. // defining it unnecessarily is not expected to break anything.
  234. // This can be overridden by the user with -DPYBIND11_HAS_SUBINTERPRETER_SUPPORT=1 or 0
  235. #ifndef PYBIND11_HAS_SUBINTERPRETER_SUPPORT
  236. # if PY_VERSION_HEX >= 0x030C0000 && !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON)
  237. # define PYBIND11_HAS_SUBINTERPRETER_SUPPORT 1
  238. # endif
  239. #else
  240. # if PYBIND11_HAS_SUBINTERPRETER_SUPPORT == 0
  241. # undef PYBIND11_HAS_SUBINTERPRETER_SUPPORT
  242. # endif
  243. #endif
  244. // 3.13 Compatibility
  245. #if 0x030D0000 <= PY_VERSION_HEX
  246. # define PYBIND11_TYPE_IS_TYPE_HINT "typing.TypeIs"
  247. # define PYBIND11_CAPSULE_TYPE_TYPE_HINT "types.CapsuleType"
  248. #else
  249. # define PYBIND11_TYPE_IS_TYPE_HINT "typing_extensions.TypeIs"
  250. # define PYBIND11_CAPSULE_TYPE_TYPE_HINT "typing_extensions.CapsuleType"
  251. #endif
  252. // 3.12 Compatibility
  253. #if 0x030C0000 <= PY_VERSION_HEX
  254. # define PYBIND11_BUFFER_TYPE_HINT "collections.abc.Buffer"
  255. #else
  256. # define PYBIND11_BUFFER_TYPE_HINT "typing_extensions.Buffer"
  257. #endif
  258. // 3.11 Compatibility
  259. #if 0x030B0000 <= PY_VERSION_HEX
  260. # define PYBIND11_NEVER_TYPE_HINT "typing.Never"
  261. #else
  262. # define PYBIND11_NEVER_TYPE_HINT "typing_extensions.Never"
  263. #endif
  264. // 3.10 Compatibility
  265. #if 0x030A0000 <= PY_VERSION_HEX
  266. # define PYBIND11_TYPE_GUARD_TYPE_HINT "typing.TypeGuard"
  267. #else
  268. # define PYBIND11_TYPE_GUARD_TYPE_HINT "typing_extensions.TypeGuard"
  269. #endif
  270. // #define PYBIND11_STR_LEGACY_PERMISSIVE
  271. // If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
  272. // (probably surprising and never documented, but this was the
  273. // legacy behavior until and including v2.6.x). As a side-effect,
  274. // pybind11::isinstance<str>() is true for both pybind11::str and
  275. // pybind11::bytes.
  276. // If UNDEFINED, pybind11::str can only hold PyUnicodeObject, and
  277. // pybind11::isinstance<str>() is true only for pybind11::str.
  278. // However, for Python 2 only (!), the pybind11::str caster
  279. // implicitly decoded bytes to PyUnicodeObject. This was to ease
  280. // the transition from the legacy behavior to the non-permissive
  281. // behavior.
  282. /// Compatibility macros for Python 2 / Python 3 versions TODO: remove
  283. #define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
  284. #define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
  285. #define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
  286. #define PYBIND11_BYTES_CHECK PyBytes_Check
  287. #define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
  288. #define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
  289. #define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
  290. #define PYBIND11_BYTES_AS_STRING PyBytes_AsString
  291. #define PYBIND11_BYTES_SIZE PyBytes_Size
  292. #define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
  293. #define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
  294. #define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) (o))
  295. #define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) (o))
  296. #define PYBIND11_BYTES_NAME "bytes"
  297. #define PYBIND11_STRING_NAME "str"
  298. #define PYBIND11_SLICE_OBJECT PyObject
  299. #define PYBIND11_FROM_STRING PyUnicode_FromString
  300. #define PYBIND11_STR_TYPE ::pybind11::str
  301. #define PYBIND11_BOOL_ATTR "__bool__"
  302. #define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
  303. #define PYBIND11_BUILTINS_MODULE "builtins"
  304. // Providing a separate declaration to make Clang's -Wmissing-prototypes happy.
  305. // See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
  306. #define PYBIND11_PLUGIN_DECL(name) \
  307. extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT PyObject *PyInit_##name();
  308. #define PYBIND11_PLUGIN_IMPL(name) \
  309. PYBIND11_PLUGIN_DECL(name) \
  310. extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
  311. #define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
  312. #define PYBIND11_STRINGIFY(x) #x
  313. #define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
  314. #define PYBIND11_CONCAT(first, second) first##second
  315. #define PYBIND11_ENSURE_INTERNALS_READY \
  316. { \
  317. pybind11::detail::get_internals_pp_manager().unref(); \
  318. pybind11::detail::get_internals(); \
  319. }
  320. #if !defined(GRAALVM_PYTHON)
  321. # define PYBIND11_PYCFUNCTION_GET_DOC(func) ((func)->m_ml->ml_doc)
  322. # define PYBIND11_PYCFUNCTION_SET_DOC(func, doc) \
  323. do { \
  324. (func)->m_ml->ml_doc = (doc); \
  325. } while (0)
  326. #else
  327. # define PYBIND11_PYCFUNCTION_GET_DOC(func) (GraalPyCFunction_GetDoc((PyObject *) (func)))
  328. # define PYBIND11_PYCFUNCTION_SET_DOC(func, doc) \
  329. do { \
  330. GraalPyCFunction_SetDoc((PyObject *) (func), (doc)); \
  331. } while (0)
  332. #endif
  333. #define PYBIND11_CHECK_PYTHON_VERSION \
  334. { \
  335. const char *compiled_ver \
  336. = PYBIND11_TOSTRING(PY_MAJOR_VERSION) "." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
  337. const char *runtime_ver = Py_GetVersion(); \
  338. size_t len = std::strlen(compiled_ver); \
  339. if (std::strncmp(runtime_ver, compiled_ver, len) != 0 \
  340. || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) { \
  341. PyErr_Format(PyExc_ImportError, \
  342. "Python version mismatch: module was compiled for Python %s, " \
  343. "but the interpreter version is incompatible: %s.", \
  344. compiled_ver, \
  345. runtime_ver); \
  346. return nullptr; \
  347. } \
  348. }
  349. #define PYBIND11_CATCH_INIT_EXCEPTIONS \
  350. catch (pybind11::error_already_set & e) { \
  351. pybind11::raise_from(e, PyExc_ImportError, "initialization failed"); \
  352. } \
  353. catch (const std::exception &e) { \
  354. ::pybind11::set_error(PyExc_ImportError, e.what()); \
  355. }
  356. /** \rst
  357. ***Deprecated in favor of PYBIND11_MODULE***
  358. This macro creates the entry point that will be invoked when the Python interpreter
  359. imports a plugin library. Please create a `module_` in the function body and return
  360. the pointer to its underlying Python object at the end.
  361. .. code-block:: cpp
  362. PYBIND11_PLUGIN(example) {
  363. pybind11::module_ m("example", "pybind11 example plugin");
  364. /// Set up bindings here
  365. return m.ptr();
  366. }
  367. \endrst */
  368. #define PYBIND11_PLUGIN(name) \
  369. PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE") \
  370. static PyObject *pybind11_init(); \
  371. PYBIND11_PLUGIN_IMPL(name) { \
  372. PYBIND11_CHECK_PYTHON_VERSION \
  373. PYBIND11_ENSURE_INTERNALS_READY \
  374. try { \
  375. return pybind11_init(); \
  376. } \
  377. PYBIND11_CATCH_INIT_EXCEPTIONS \
  378. return nullptr; \
  379. } \
  380. PyObject *pybind11_init()
  381. // this push is for the next several macros
  382. PYBIND11_WARNING_PUSH
  383. PYBIND11_WARNING_DISABLE_CLANG("-Wgnu-zero-variadic-macro-arguments")
  384. /**
  385. Create a PyInit_ function for this module.
  386. Note that this is run once for each (sub-)interpreter the module is imported into, including
  387. possibly concurrently. The PyModuleDef is allowed to be static, but the PyObject* resulting from
  388. PyModuleDef_Init should be treated like any other PyObject (so not shared across interpreters).
  389. */
  390. #define PYBIND11_MODULE_PYINIT(name, pre_init, ...) \
  391. static int PYBIND11_CONCAT(pybind11_exec_, name)(PyObject *); \
  392. PYBIND11_PLUGIN_IMPL(name) { \
  393. PYBIND11_CHECK_PYTHON_VERSION \
  394. pre_init; \
  395. PYBIND11_ENSURE_INTERNALS_READY \
  396. static ::pybind11::detail::slots_array mod_def_slots = ::pybind11::detail::init_slots( \
  397. &PYBIND11_CONCAT(pybind11_exec_, name), ##__VA_ARGS__); \
  398. static PyModuleDef def{/* m_base */ PyModuleDef_HEAD_INIT, \
  399. /* m_name */ PYBIND11_TOSTRING(name), \
  400. /* m_doc */ nullptr, \
  401. /* m_size */ 0, \
  402. /* m_methods */ nullptr, \
  403. /* m_slots */ mod_def_slots.data(), \
  404. /* m_traverse */ nullptr, \
  405. /* m_clear */ nullptr, \
  406. /* m_free */ nullptr}; \
  407. return PyModuleDef_Init(&def); \
  408. }
  409. #define PYBIND11_MODULE_EXEC(name, variable) \
  410. static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
  411. int PYBIND11_CONCAT(pybind11_exec_, name)(PyObject * pm) { \
  412. try { \
  413. auto m = pybind11::reinterpret_borrow<::pybind11::module_>(pm); \
  414. if (!pybind11::detail::get_cached_module(m.attr("__spec__").attr("name"))) { \
  415. PYBIND11_CONCAT(pybind11_init_, name)(m); \
  416. pybind11::detail::cache_completed_module(m); \
  417. } \
  418. return 0; \
  419. } \
  420. PYBIND11_CATCH_INIT_EXCEPTIONS \
  421. return -1; \
  422. } \
  423. void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ \
  424. & variable) // NOLINT(bugprone-macro-parentheses)
  425. /** \rst
  426. This macro creates the entry point that will be invoked when the Python interpreter
  427. imports an extension module. The module name is given as the first argument and it
  428. should not be in quotes. The second macro argument defines a variable of type
  429. ``py::module_`` which can be used to initialize the module.
  430. The entry point is marked as "maybe unused" to aid dead-code detection analysis:
  431. since the entry point is typically only looked up at runtime and not referenced
  432. during translation, it would otherwise appear as unused ("dead") code.
  433. .. code-block:: cpp
  434. PYBIND11_MODULE(example, m) {
  435. m.doc() = "pybind11 example module";
  436. // Add bindings here
  437. m.def("foo", []() {
  438. return "Hello, World!";
  439. });
  440. }
  441. The third and subsequent macro arguments are optional (available since 2.13.0), and
  442. can be used to mark the extension module as supporting various Python features.
  443. - ``mod_gil_not_used()``
  444. - ``multiple_interpreters::per_interpreter_gil()``
  445. - ``multiple_interpreters::shared_gil()``
  446. - ``multiple_interpreters::not_supported()``
  447. .. code-block:: cpp
  448. PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {
  449. m.doc() = "pybind11 example module safe to run without the GIL";
  450. m.def("foo", []() {
  451. return "Hello, Free-threaded World!";
  452. });
  453. }
  454. \endrst */
  455. #define PYBIND11_MODULE(name, variable, ...) \
  456. PYBIND11_MODULE_PYINIT( \
  457. name, (pybind11::detail::get_num_interpreters_seen() += 1), ##__VA_ARGS__) \
  458. PYBIND11_MODULE_EXEC(name, variable)
  459. // pop gnu-zero-variadic-macro-arguments
  460. PYBIND11_WARNING_POP
  461. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  462. using ssize_t = Py_ssize_t;
  463. using size_t = std::size_t;
  464. template <typename IntType>
  465. inline ssize_t ssize_t_cast(const IntType &val) {
  466. static_assert(sizeof(IntType) <= sizeof(ssize_t), "Implicit narrowing is not permitted.");
  467. return static_cast<ssize_t>(val);
  468. }
  469. /// Approach used to cast a previously unknown C++ instance into a Python object
  470. enum class return_value_policy : uint8_t {
  471. /** This is the default return value policy, which falls back to the policy
  472. return_value_policy::take_ownership when the return value is a pointer.
  473. Otherwise, it uses return_value::move or return_value::copy for rvalue
  474. and lvalue references, respectively. See below for a description of what
  475. all of these different policies do. */
  476. automatic = 0,
  477. /** As above, but use policy return_value_policy::reference when the return
  478. value is a pointer. This is the default conversion policy for function
  479. arguments when calling Python functions manually from C++ code (i.e. via
  480. handle::operator()). You probably won't need to use this. */
  481. automatic_reference,
  482. /** Reference an existing object (i.e. do not create a new copy) and take
  483. ownership. Python will call the destructor and delete operator when the
  484. object's reference count reaches zero. Undefined behavior ensues when
  485. the C++ side does the same.. */
  486. take_ownership,
  487. /** Create a new copy of the returned object, which will be owned by
  488. Python. This policy is comparably safe because the lifetimes of the two
  489. instances are decoupled. */
  490. copy,
  491. /** Use std::move to move the return value contents into a new instance
  492. that will be owned by Python. This policy is comparably safe because the
  493. lifetimes of the two instances (move source and destination) are
  494. decoupled. */
  495. move,
  496. /** Reference an existing object, but do not take ownership. The C++ side
  497. is responsible for managing the object's lifetime and deallocating it
  498. when it is no longer used. Warning: undefined behavior will ensue when
  499. the C++ side deletes an object that is still referenced and used by
  500. Python. */
  501. reference,
  502. /** This policy only applies to methods and properties. It references the
  503. object without taking ownership similar to the above
  504. return_value_policy::reference policy. In contrast to that policy, the
  505. function or property's implicit this argument (called the parent) is
  506. considered to be the owner of the return value (the child).
  507. pybind11 then couples the lifetime of the parent to the child via a
  508. reference relationship that ensures that the parent cannot be garbage
  509. collected while Python is still using the child. More advanced
  510. variations of this scheme are also possible using combinations of
  511. return_value_policy::reference and the keep_alive call policy */
  512. reference_internal
  513. };
  514. PYBIND11_NAMESPACE_BEGIN(detail)
  515. inline static constexpr int log2(size_t n, int k = 0) {
  516. return (n <= 1) ? k : log2(n >> 1, k + 1);
  517. }
  518. // Returns the size as a multiple of sizeof(void *), rounded up.
  519. inline static constexpr size_t size_in_ptrs(size_t s) {
  520. return 1 + ((s - 1) >> log2(sizeof(void *)));
  521. }
  522. /**
  523. * The space to allocate for simple layout instance holders (see below) in multiple of the size of
  524. * a pointer (e.g. 2 means 16 bytes on 64-bit architectures). The default is the minimum required
  525. * to holder either a std::unique_ptr or std::shared_ptr (which is almost always
  526. * sizeof(std::shared_ptr<T>)).
  527. */
  528. constexpr size_t instance_simple_holder_in_ptrs() {
  529. static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
  530. "pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
  531. return size_in_ptrs(sizeof(std::shared_ptr<int>));
  532. }
  533. // Forward declarations
  534. struct type_info;
  535. struct value_and_holder;
  536. struct nonsimple_values_and_holders {
  537. void **values_and_holders;
  538. uint8_t *status;
  539. };
  540. /// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
  541. struct instance {
  542. PyObject_HEAD
  543. /// Storage for pointers and holder; see simple_layout, below, for a description
  544. union {
  545. void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
  546. nonsimple_values_and_holders nonsimple;
  547. };
  548. /// Weak references
  549. PyObject *weakrefs;
  550. /// If true, the pointer is owned which means we're free to manage it with a holder.
  551. bool owned : 1;
  552. /**
  553. * An instance has two possible value/holder layouts.
  554. *
  555. * Simple layout (when this flag is true), means the `simple_value_holder` is set with a
  556. * pointer and the holder object governing that pointer, i.e. [val1*][holder]. This layout is
  557. * applied whenever there is no python-side multiple inheritance of bound C++ types *and* the
  558. * type's holder will fit in the default space (which is large enough to hold either a
  559. * std::unique_ptr or std::shared_ptr).
  560. *
  561. * Non-simple layout applies when using custom holders that require more space than
  562. * `shared_ptr` (which is typically the size of two pointers), or when multiple inheritance is
  563. * used on the python side. Non-simple layout allocates the required amount of memory to have
  564. * multiple bound C++ classes as parents. Under this layout, `nonsimple.values_and_holders` is
  565. * set to a pointer to allocated space of the required space to hold a sequence of value
  566. * pointers and holders followed `status`, a set of bit flags (1 byte each), i.e.
  567. * [val1*][holder1][val2*][holder2]...[bb...] where each [block] is rounded up to a multiple
  568. * of `sizeof(void *)`. `nonsimple.status` is, for convenience, a pointer to the beginning of
  569. * the [bb...] block (but not independently allocated).
  570. *
  571. * Status bits indicate whether the associated holder is constructed (&
  572. * status_holder_constructed) and whether the value pointer is registered (&
  573. * status_instance_registered) in `registered_instances`.
  574. */
  575. bool simple_layout : 1;
  576. /// For simple layout, tracks whether the holder has been constructed
  577. bool simple_holder_constructed : 1;
  578. /// For simple layout, tracks whether the instance is registered in `registered_instances`
  579. bool simple_instance_registered : 1;
  580. /// If true, get_internals().patients has an entry for this object
  581. bool has_patients : 1;
  582. /// If true, this Python object needs to be kept alive for the lifetime of the C++ value.
  583. bool is_alias : 1;
  584. /// Initializes all of the above type/values/holders data (but not the instance values
  585. /// themselves)
  586. void allocate_layout();
  587. /// Destroys/deallocates all of the above
  588. void deallocate_layout();
  589. /// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
  590. /// omitted). Returns a default-constructed (with `.inst = nullptr`) object on failure if
  591. /// `throw_if_missing` is false.
  592. value_and_holder get_value_and_holder(const type_info *find_type = nullptr,
  593. bool throw_if_missing = true);
  594. /// Bit values for the non-simple status flags
  595. static constexpr uint8_t status_holder_constructed = 1;
  596. static constexpr uint8_t status_instance_registered = 2;
  597. };
  598. static_assert(std::is_standard_layout<instance>::value,
  599. "Internal error: `pybind11::detail::instance` is not standard layout!");
  600. // Some older compilers (e.g. gcc 9.4.0) require
  601. // static_assert(always_false<T>::value, "...");
  602. // instead of
  603. // static_assert(false, "...");
  604. // to trigger the static_assert() in a template only if it is actually instantiated.
  605. template <typename>
  606. struct always_false : std::false_type {};
  607. /// from __cpp_future__ import (convenient aliases from C++14/17)
  608. #if defined(PYBIND11_CPP14)
  609. using std::conditional_t;
  610. using std::enable_if_t;
  611. using std::remove_cv_t;
  612. using std::remove_reference_t;
  613. #else
  614. template <bool B, typename T = void>
  615. using enable_if_t = typename std::enable_if<B, T>::type;
  616. template <bool B, typename T, typename F>
  617. using conditional_t = typename std::conditional<B, T, F>::type;
  618. template <typename T>
  619. using remove_cv_t = typename std::remove_cv<T>::type;
  620. template <typename T>
  621. using remove_reference_t = typename std::remove_reference<T>::type;
  622. #endif
  623. #if defined(PYBIND11_CPP20) && defined(__cpp_lib_remove_cvref)
  624. using std::remove_cvref;
  625. using std::remove_cvref_t;
  626. #else
  627. template <class T>
  628. struct remove_cvref {
  629. using type = remove_cv_t<remove_reference_t<T>>;
  630. };
  631. template <class T>
  632. using remove_cvref_t = typename remove_cvref<T>::type;
  633. #endif
  634. /// Example usage: is_same_ignoring_cvref<T, PyObject *>::value
  635. template <typename T, typename U>
  636. using is_same_ignoring_cvref = std::is_same<detail::remove_cvref_t<T>, U>;
  637. /// Index sequences
  638. #if defined(PYBIND11_CPP14)
  639. using std::index_sequence;
  640. using std::make_index_sequence;
  641. #else
  642. template <size_t...>
  643. struct index_sequence {};
  644. // Comments about the algorithm below.
  645. //
  646. // Credit: This is based on an algorithm by taocpp here:
  647. // https://github.com/taocpp/sequences/blob/main/include/tao/seq/make_integer_sequence.hpp
  648. // but significantly simplified.
  649. //
  650. // We build up a sequence S by repeatedly doubling its length and sometimes adding 1 to the end.
  651. // E.g. if the current S is 0...3, then we either go to 0...7 or 0...8 on the next pass.
  652. // The goal is to end with S = 0...N-1.
  653. // The key insight is that the times we need to add an additional digit to S correspond
  654. // exactly to the 1's in the binary representation of the number N.
  655. //
  656. // Invariants:
  657. // - digit is a power of 2
  658. // - N_digit_is_1 is whether N's binary representation has a 1 in that digit's position.
  659. // - end <= N
  660. // - S is 0...end-1.
  661. // - if digit > 0, end * digit * 2 <= N < (end+1) * digit * 2
  662. //
  663. // The process starts with digit > N, end = 0, and S is empty.
  664. // The process concludes with digit=0, in which case, end == N and S is 0...N-1.
  665. template <size_t digit, bool N_digit_is_1, size_t N, size_t end, size_t... S> // N_digit_is_1=false
  666. struct make_index_sequence_impl
  667. : make_index_sequence_impl<digit / 2, (N & (digit / 2)) != 0, N, 2 * end, S..., (S + end)...> {
  668. };
  669. template <size_t digit, size_t N, size_t end, size_t... S>
  670. struct make_index_sequence_impl<digit, true, N, end, S...>
  671. : make_index_sequence_impl<digit / 2,
  672. (N & (digit / 2)) != 0,
  673. N,
  674. 2 * end + 1,
  675. S...,
  676. (S + end)...,
  677. 2 * end> {};
  678. template <size_t N, size_t end, size_t... S>
  679. struct make_index_sequence_impl<0, false, N, end, S...> {
  680. using type = index_sequence<S...>;
  681. };
  682. constexpr size_t next_power_of_2(size_t N) { return N == 0 ? 1 : next_power_of_2(N >> 1) << 1; }
  683. template <size_t N>
  684. using make_index_sequence =
  685. typename make_index_sequence_impl<next_power_of_2(N), false, N, 0>::type;
  686. #endif
  687. /// Make an index sequence of the indices of true arguments
  688. template <typename ISeq, size_t, bool...>
  689. struct select_indices_impl {
  690. using type = ISeq;
  691. };
  692. template <size_t... IPrev, size_t I, bool B, bool... Bs>
  693. struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
  694. : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>,
  695. I + 1,
  696. Bs...> {};
  697. template <bool... Bs>
  698. using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
  699. /// Backports of std::bool_constant and std::negation to accommodate older compilers
  700. template <bool B>
  701. using bool_constant = std::integral_constant<bool, B>;
  702. template <typename T>
  703. struct negation : bool_constant<!T::value> {};
  704. // PGI/Intel cannot detect operator delete with the "compatible" void_t impl, so
  705. // using the new one (C++14 defect, so generally works on newer compilers, even
  706. // if not in C++17 mode)
  707. #if defined(__PGIC__) || defined(__INTEL_COMPILER)
  708. template <typename...>
  709. using void_t = void;
  710. #else
  711. template <typename...>
  712. struct void_t_impl {
  713. using type = void;
  714. };
  715. template <typename... Ts>
  716. using void_t = typename void_t_impl<Ts...>::type;
  717. #endif
  718. /// Compile-time all/any/none of that check the boolean value of all template types
  719. #if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
  720. template <class... Ts>
  721. using all_of = bool_constant<(Ts::value && ...)>;
  722. template <class... Ts>
  723. using any_of = bool_constant<(Ts::value || ...)>;
  724. #elif !defined(_MSC_VER)
  725. template <bool...>
  726. struct bools {};
  727. template <class... Ts>
  728. using all_of = std::is_same<bools<Ts::value..., true>, bools<true, Ts::value...>>;
  729. template <class... Ts>
  730. using any_of = negation<all_of<negation<Ts>...>>;
  731. #else
  732. // MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
  733. // at a slight loss of compilation efficiency).
  734. template <class... Ts>
  735. using all_of = std::conjunction<Ts...>;
  736. template <class... Ts>
  737. using any_of = std::disjunction<Ts...>;
  738. #endif
  739. template <class... Ts>
  740. using none_of = negation<any_of<Ts...>>;
  741. template <class T, template <class> class... Predicates>
  742. using satisfies_all_of = all_of<Predicates<T>...>;
  743. template <class T, template <class> class... Predicates>
  744. using satisfies_any_of = any_of<Predicates<T>...>;
  745. template <class T, template <class> class... Predicates>
  746. using satisfies_none_of = none_of<Predicates<T>...>;
  747. /// Strip the class from a method type
  748. template <typename T>
  749. struct remove_class {};
  750. template <typename C, typename R, typename... A>
  751. struct remove_class<R (C::*)(A...)> {
  752. using type = R(A...);
  753. };
  754. template <typename C, typename R, typename... A>
  755. struct remove_class<R (C::*)(A...) const> {
  756. using type = R(A...);
  757. };
  758. #ifdef __cpp_noexcept_function_type
  759. template <typename C, typename R, typename... A>
  760. struct remove_class<R (C::*)(A...) noexcept> {
  761. using type = R(A...);
  762. };
  763. template <typename C, typename R, typename... A>
  764. struct remove_class<R (C::*)(A...) const noexcept> {
  765. using type = R(A...);
  766. };
  767. #endif
  768. /// Helper template to strip away type modifiers
  769. template <typename T>
  770. struct intrinsic_type {
  771. using type = T;
  772. };
  773. template <typename T>
  774. struct intrinsic_type<const T> {
  775. using type = typename intrinsic_type<T>::type;
  776. };
  777. template <typename T>
  778. struct intrinsic_type<T *> {
  779. using type = typename intrinsic_type<T>::type;
  780. };
  781. template <typename T>
  782. struct intrinsic_type<T &> {
  783. using type = typename intrinsic_type<T>::type;
  784. };
  785. template <typename T>
  786. struct intrinsic_type<T &&> {
  787. using type = typename intrinsic_type<T>::type;
  788. };
  789. template <typename T, size_t N>
  790. struct intrinsic_type<const T[N]> {
  791. using type = typename intrinsic_type<T>::type;
  792. };
  793. template <typename T, size_t N>
  794. struct intrinsic_type<T[N]> {
  795. using type = typename intrinsic_type<T>::type;
  796. };
  797. template <typename T>
  798. using intrinsic_t = typename intrinsic_type<T>::type;
  799. /// Helper type to replace 'void' in some expressions
  800. struct void_type {};
  801. /// Helper template which holds a list of types
  802. template <typename...>
  803. struct type_list {};
  804. /// Compile-time integer sum
  805. #ifdef __cpp_fold_expressions
  806. template <typename... Ts>
  807. constexpr size_t constexpr_sum(Ts... ns) {
  808. return (0 + ... + size_t{ns});
  809. }
  810. #else
  811. constexpr size_t constexpr_sum() { return 0; }
  812. template <typename T, typename... Ts>
  813. constexpr size_t constexpr_sum(T n, Ts... ns) {
  814. return size_t{n} + constexpr_sum(ns...);
  815. }
  816. #endif
  817. PYBIND11_NAMESPACE_BEGIN(constexpr_impl)
  818. /// Implementation details for constexpr functions
  819. constexpr int first(int i) { return i; }
  820. template <typename T, typename... Ts>
  821. constexpr int first(int i, T v, Ts... vs) {
  822. return v ? i : first(i + 1, vs...);
  823. }
  824. constexpr int last(int /*i*/, int result) { return result; }
  825. template <typename T, typename... Ts>
  826. constexpr int last(int i, int result, T v, Ts... vs) {
  827. return last(i + 1, v ? i : result, vs...);
  828. }
  829. PYBIND11_NAMESPACE_END(constexpr_impl)
  830. /// Return the index of the first type in Ts which satisfies Predicate<T>.
  831. /// Returns sizeof...(Ts) if none match.
  832. template <template <typename> class Predicate, typename... Ts>
  833. constexpr int constexpr_first() {
  834. return constexpr_impl::first(0, Predicate<Ts>::value...);
  835. }
  836. /// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
  837. template <template <typename> class Predicate, typename... Ts>
  838. constexpr int constexpr_last() {
  839. return constexpr_impl::last(0, -1, Predicate<Ts>::value...);
  840. }
  841. /// Return the Nth element from the parameter pack
  842. template <size_t N, typename T, typename... Ts>
  843. struct pack_element {
  844. using type = typename pack_element<N - 1, Ts...>::type;
  845. };
  846. template <typename T, typename... Ts>
  847. struct pack_element<0, T, Ts...> {
  848. using type = T;
  849. };
  850. /// Return the one and only type which matches the predicate, or Default if none match.
  851. /// If more than one type matches the predicate, fail at compile-time.
  852. template <template <typename> class Predicate, typename Default, typename... Ts>
  853. struct exactly_one {
  854. static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
  855. static_assert(found <= 1, "Found more than one type matching the predicate");
  856. static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
  857. using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
  858. };
  859. template <template <typename> class P, typename Default>
  860. struct exactly_one<P, Default> {
  861. using type = Default;
  862. };
  863. template <template <typename> class Predicate, typename Default, typename... Ts>
  864. using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
  865. /// Defer the evaluation of type T until types Us are instantiated
  866. template <typename T, typename... /*Us*/>
  867. struct deferred_type {
  868. using type = T;
  869. };
  870. template <typename T, typename... Us>
  871. using deferred_t = typename deferred_type<T, Us...>::type;
  872. /// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
  873. /// unlike `std::is_base_of`)
  874. template <typename Base, typename Derived>
  875. using is_strict_base_of
  876. = bool_constant<std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
  877. /// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived
  878. /// pointer can be converted to a Base pointer) For unions, `is_base_of<T, T>::value` is False, so
  879. /// we need to check `is_same` as well.
  880. template <typename Base, typename Derived>
  881. using is_accessible_base_of
  882. = bool_constant<(std::is_same<Base, Derived>::value || std::is_base_of<Base, Derived>::value)
  883. && std::is_convertible<Derived *, Base *>::value>;
  884. template <template <typename...> class Base>
  885. struct is_template_base_of_impl {
  886. template <typename... Us>
  887. static std::true_type check(Base<Us...> *);
  888. static std::false_type check(...);
  889. };
  890. /// Check if a template is the base of a type. For example:
  891. /// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
  892. template <template <typename...> class Base, typename T>
  893. // Sadly, all MSVC versions incl. 2022 need the workaround, even in C++20 mode.
  894. // See also: https://github.com/pybind/pybind11/pull/3741
  895. #if !defined(_MSC_VER)
  896. using is_template_base_of
  897. = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr));
  898. #else
  899. struct is_template_base_of
  900. : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)){};
  901. #endif
  902. /// Check if T is an instantiation of the template `Class`. For example:
  903. /// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
  904. template <template <typename...> class Class, typename T>
  905. struct is_instantiation : std::false_type {};
  906. template <template <typename...> class Class, typename... Us>
  907. struct is_instantiation<Class, Class<Us...>> : std::true_type {};
  908. /// Check if T is std::shared_ptr<U> where U can be anything
  909. template <typename T>
  910. using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
  911. /// Check if T looks like an input iterator
  912. template <typename T, typename = void>
  913. struct is_input_iterator : std::false_type {};
  914. template <typename T>
  915. struct is_input_iterator<T,
  916. void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
  917. : std::true_type {};
  918. template <typename T>
  919. using is_function_pointer
  920. = bool_constant<std::is_pointer<T>::value
  921. && std::is_function<typename std::remove_pointer<T>::type>::value>;
  922. template <typename F>
  923. struct strip_function_object {
  924. // If you are encountering an
  925. // 'error: name followed by "::" must be a class or namespace name'
  926. // with the Intel compiler and a noexcept function here,
  927. // try to use noexcept(true) instead of plain noexcept.
  928. using type = typename remove_class<decltype(&F::operator())>::type;
  929. };
  930. // Extracts the function signature from a function, function pointer or lambda.
  931. template <typename Function, typename F = remove_reference_t<Function>>
  932. using function_signature_t = conditional_t<
  933. std::is_function<F>::value,
  934. F,
  935. typename conditional_t<std::is_pointer<F>::value || std::is_member_pointer<F>::value,
  936. std::remove_pointer<F>,
  937. strip_function_object<F>>::type>;
  938. /// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
  939. /// pointer. Note that this can catch all sorts of other things, too; this is intended to be used
  940. /// in a place where passing a lambda makes sense.
  941. template <typename T>
  942. using is_lambda = satisfies_none_of<remove_reference_t<T>,
  943. std::is_function,
  944. std::is_pointer,
  945. std::is_member_pointer>;
  946. // [workaround(intel)] Internal error on fold expression
  947. /// Apply a function over each element of a parameter pack
  948. #if defined(__cpp_fold_expressions) && !defined(__INTEL_COMPILER)
  949. // Intel compiler produces an internal error on this fold expression (tested with ICC 19.0.2)
  950. # define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
  951. #else
  952. using expand_side_effects = bool[];
  953. # define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) \
  954. (void) pybind11::detail::expand_side_effects { ((PATTERN), void(), false)..., false }
  955. #endif
  956. PYBIND11_NAMESPACE_END(detail)
  957. /// C++ bindings of builtin Python exceptions
  958. class PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error {
  959. public:
  960. using std::runtime_error::runtime_error;
  961. /// Set the error using the Python C API
  962. virtual void set_error() const = 0;
  963. };
  964. #define PYBIND11_RUNTIME_EXCEPTION(name, type) \
  965. class PYBIND11_EXPORT_EXCEPTION name : public builtin_exception { \
  966. public: \
  967. using builtin_exception::builtin_exception; \
  968. name() : name("") {} \
  969. void set_error() const override { PyErr_SetString(type, what()); } \
  970. };
  971. PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
  972. PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
  973. PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
  974. PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
  975. PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
  976. PYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)
  977. PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
  978. PYBIND11_RUNTIME_EXCEPTION(attribute_error, PyExc_AttributeError)
  979. PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or
  980. /// handle::call fail due to a type
  981. /// casting error
  982. PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
  983. [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason) {
  984. assert(!PyErr_Occurred());
  985. throw std::runtime_error(reason);
  986. }
  987. [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const std::string &reason) {
  988. assert(!PyErr_Occurred());
  989. throw std::runtime_error(reason);
  990. }
  991. template <typename T, typename SFINAE = void>
  992. struct format_descriptor {};
  993. template <typename T>
  994. struct format_descriptor<
  995. T,
  996. detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value>> {
  997. static constexpr const char c = 'O';
  998. static constexpr const char value[2] = {c, '\0'};
  999. static std::string format() { return std::string(1, c); }
  1000. };
  1001. PYBIND11_NAMESPACE_BEGIN(detail)
  1002. // Returns the index of the given type in the type char array below, and in the list in numpy.h
  1003. // The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
  1004. // complex float,double,long double. Note that the long double types only participate when long
  1005. // double is actually longer than double (it isn't under MSVC).
  1006. // NB: not only the string below but also complex.h and numpy.h rely on this order.
  1007. template <typename T, typename SFINAE = void>
  1008. struct is_fmt_numeric {
  1009. static constexpr bool value = false;
  1010. };
  1011. template <typename T>
  1012. struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
  1013. static constexpr bool value = true;
  1014. static constexpr int index
  1015. = std::is_same<T, bool>::value
  1016. ? 0
  1017. : 1
  1018. + (std::is_integral<T>::value
  1019. ? detail::log2(sizeof(T)) * 2 + std::is_unsigned<T>::value
  1020. : 8
  1021. + (std::is_same<T, double>::value ? 1
  1022. : std::is_same<T, long double>::value ? 2
  1023. : 0));
  1024. };
  1025. PYBIND11_NAMESPACE_END(detail)
  1026. template <typename T>
  1027. struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
  1028. static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
  1029. static constexpr const char value[2] = {c, '\0'};
  1030. static std::string format() { return std::string(1, c); }
  1031. };
  1032. #if !defined(PYBIND11_CPP17)
  1033. template <typename T>
  1034. constexpr const char
  1035. format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
  1036. #endif
  1037. /// RAII wrapper that temporarily clears any Python error state
  1038. struct error_scope {
  1039. PyObject *type, *value, *trace;
  1040. error_scope() { PyErr_Fetch(&type, &value, &trace); }
  1041. error_scope(const error_scope &) = delete;
  1042. error_scope &operator=(const error_scope &) = delete;
  1043. ~error_scope() { PyErr_Restore(type, value, trace); }
  1044. };
  1045. /// Dummy destructor wrapper that can be used to expose classes with a private destructor
  1046. struct nodelete {
  1047. template <typename T>
  1048. void operator()(T *) {}
  1049. };
  1050. PYBIND11_NAMESPACE_BEGIN(detail)
  1051. template <typename... Args>
  1052. struct overload_cast_impl {
  1053. template <typename Return>
  1054. constexpr auto operator()(Return (*pf)(Args...)) const noexcept -> decltype(pf) {
  1055. return pf;
  1056. }
  1057. template <typename Return, typename Class>
  1058. constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
  1059. -> decltype(pmf) {
  1060. return pmf;
  1061. }
  1062. template <typename Return, typename Class>
  1063. constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
  1064. -> decltype(pmf) {
  1065. return pmf;
  1066. }
  1067. };
  1068. PYBIND11_NAMESPACE_END(detail)
  1069. // overload_cast requires variable templates: C++14
  1070. #if defined(PYBIND11_CPP14)
  1071. # define PYBIND11_OVERLOAD_CAST 1
  1072. /// Syntax sugar for resolving overloaded function pointers:
  1073. /// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
  1074. /// - sweet: overload_cast<Arg0, Arg1, Arg2>(&Class::func)
  1075. template <typename... Args>
  1076. static constexpr detail::overload_cast_impl<Args...> overload_cast{};
  1077. #endif
  1078. /// Const member function selector for overload_cast
  1079. /// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
  1080. /// - sweet: overload_cast<Arg>(&Class::func, const_)
  1081. static constexpr auto const_ = std::true_type{};
  1082. #if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:
  1083. template <typename... Args>
  1084. struct overload_cast {
  1085. static_assert(detail::deferred_t<std::false_type, Args...>::value,
  1086. "pybind11::overload_cast<...> requires compiling in C++14 mode");
  1087. };
  1088. #endif // overload_cast
  1089. PYBIND11_NAMESPACE_BEGIN(detail)
  1090. // Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
  1091. // any standard container (or C-style array) supporting std::begin/std::end, any singleton
  1092. // arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
  1093. template <typename T>
  1094. class any_container {
  1095. std::vector<T> v;
  1096. public:
  1097. any_container() = default;
  1098. // Can construct from a pair of iterators
  1099. template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
  1100. any_container(It first, It last) : v(first, last) {}
  1101. // Implicit conversion constructor from any arbitrary container type
  1102. // with values convertible to T
  1103. template <typename Container,
  1104. typename = enable_if_t<
  1105. std::is_convertible<decltype(*std::begin(std::declval<const Container &>())),
  1106. T>::value>>
  1107. // NOLINTNEXTLINE(google-explicit-constructor)
  1108. any_container(const Container &c) : any_container(std::begin(c), std::end(c)) {}
  1109. // initializer_list's aren't deducible, so don't get matched by the above template;
  1110. // we need this to explicitly allow implicit conversion from one:
  1111. template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
  1112. any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) {}
  1113. // Avoid copying if given an rvalue vector of the correct type.
  1114. // NOLINTNEXTLINE(google-explicit-constructor)
  1115. any_container(std::vector<T> &&v) : v(std::move(v)) {}
  1116. // Moves the vector out of an rvalue any_container
  1117. // NOLINTNEXTLINE(google-explicit-constructor)
  1118. operator std::vector<T> &&() && { return std::move(v); }
  1119. // Dereferencing obtains a reference to the underlying vector
  1120. std::vector<T> &operator*() { return v; }
  1121. const std::vector<T> &operator*() const { return v; }
  1122. // -> lets you call methods on the underlying vector
  1123. std::vector<T> *operator->() { return &v; }
  1124. const std::vector<T> *operator->() const { return &v; }
  1125. };
  1126. // Forward-declaration; see detail/class.h
  1127. std::string get_fully_qualified_tp_name(PyTypeObject *);
  1128. template <typename T>
  1129. inline static std::shared_ptr<T>
  1130. try_get_shared_from_this(std::enable_shared_from_this<T> *holder_value_ptr) {
  1131. // Pre C++17, this code path exploits undefined behavior, but is known to work on many platforms.
  1132. // Use at your own risk!
  1133. // See also https://en.cppreference.com/w/cpp/memory/enable_shared_from_this, and in particular
  1134. // the `std::shared_ptr<Good> gp1 = not_so_good.getptr();` and `try`-`catch` parts of the example.
  1135. #if defined(__cpp_lib_enable_shared_from_this) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
  1136. return holder_value_ptr->weak_from_this().lock();
  1137. #else
  1138. try {
  1139. return holder_value_ptr->shared_from_this();
  1140. } catch (const std::bad_weak_ptr &) {
  1141. return nullptr;
  1142. }
  1143. #endif
  1144. }
  1145. // For silencing "unused" compiler warnings in special situations.
  1146. template <typename... Args>
  1147. #if defined(_MSC_VER) && _MSC_VER < 1920 // MSVC 2017
  1148. constexpr
  1149. #endif
  1150. inline void
  1151. silence_unused_warnings(Args &&...) {
  1152. }
  1153. // MSVC warning C4100: Unreferenced formal parameter
  1154. #if defined(_MSC_VER) && _MSC_VER <= 1916
  1155. # define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...) \
  1156. detail::silence_unused_warnings(__VA_ARGS__)
  1157. #else
  1158. # define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
  1159. #endif
  1160. // GCC -Wunused-but-set-parameter All GCC versions (as of July 2021).
  1161. #if defined(__GNUG__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
  1162. # define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...) \
  1163. detail::silence_unused_warnings(__VA_ARGS__)
  1164. #else
  1165. # define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)
  1166. #endif
  1167. #if defined(__clang__) \
  1168. && (defined(__apple_build_version__) /* AppleClang 13.0.0.13000029 was the only data point \
  1169. available. */ \
  1170. || (__clang_major__ >= 7 \
  1171. && __clang_major__ <= 12) /* Clang 3, 5, 13, 14, 15 do not generate the warning. */ \
  1172. )
  1173. # define PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
  1174. // Example:
  1175. // tests/test_kwargs_and_defaults.cpp:46:68: error: local variable 'args' will be copied despite
  1176. // being returned by name [-Werror,-Wreturn-std-move]
  1177. // m.def("args_function", [](py::args args) -> py::tuple { return args; });
  1178. // ^~~~
  1179. // test_kwargs_and_defaults.cpp:46:68: note: call 'std::move' explicitly to avoid copying
  1180. // m.def("args_function", [](py::args args) -> py::tuple { return args; });
  1181. // ^~~~
  1182. // std::move(args)
  1183. #endif
  1184. // Pybind offers detailed error messages by default for all builts that are debug (through the
  1185. // negation of NDEBUG). This can also be manually enabled by users, for any builds, through
  1186. // defining PYBIND11_DETAILED_ERROR_MESSAGES. This information is primarily useful for those
  1187. // who are writing (as opposed to merely using) libraries that use pybind11.
  1188. #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(NDEBUG)
  1189. # define PYBIND11_DETAILED_ERROR_MESSAGES
  1190. #endif
  1191. // CPython 3.11+ provides Py_TPFLAGS_MANAGED_DICT, but PyPy3.11 does not, see PR #5508.
  1192. #if PY_VERSION_HEX < 0x030B0000 || defined(PYPY_VERSION)
  1193. # define PYBIND11_BACKWARD_COMPATIBILITY_TP_DICTOFFSET
  1194. #endif
  1195. PYBIND11_NAMESPACE_END(detail)
  1196. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
  1197. #else
  1198. #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
  1199. #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)