common.h 49 KB

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