common.h 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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. #if !defined(NAMESPACE_BEGIN)
  9. # define NAMESPACE_BEGIN(name) namespace name {
  10. #endif
  11. #if !defined(NAMESPACE_END)
  12. # define NAMESPACE_END(name) }
  13. #endif
  14. // Robust support for some features and loading modules compiled against different pybind versions
  15. // requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute on
  16. // the main `pybind11` namespace.
  17. #if !defined(PYBIND11_NAMESPACE)
  18. # ifdef __GNUG__
  19. # define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
  20. # else
  21. # define PYBIND11_NAMESPACE pybind11
  22. # endif
  23. #endif
  24. #if !(defined(_MSC_VER) && __cplusplus == 199711L) && !defined(__INTEL_COMPILER)
  25. # if __cplusplus >= 201402L
  26. # define PYBIND11_CPP14
  27. # if __cplusplus >= 201703L
  28. # define PYBIND11_CPP17
  29. # endif
  30. # endif
  31. #elif defined(_MSC_VER) && __cplusplus == 199711L
  32. // MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully implemented)
  33. // Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3 or newer
  34. # if _MSVC_LANG >= 201402L
  35. # define PYBIND11_CPP14
  36. # if _MSVC_LANG > 201402L && _MSC_VER >= 1910
  37. # define PYBIND11_CPP17
  38. # endif
  39. # endif
  40. #endif
  41. // Compiler version assertions
  42. #if defined(__INTEL_COMPILER)
  43. # if __INTEL_COMPILER < 1700
  44. # error pybind11 requires Intel C++ compiler v17 or newer
  45. # endif
  46. #elif defined(__clang__) && !defined(__apple_build_version__)
  47. # if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
  48. # error pybind11 requires clang 3.3 or newer
  49. # endif
  50. #elif defined(__clang__)
  51. // Apple changes clang version macros to its Xcode version; the first Xcode release based on
  52. // (upstream) clang 3.3 was Xcode 5:
  53. # if __clang_major__ < 5
  54. # error pybind11 requires Xcode/clang 5.0 or newer
  55. # endif
  56. #elif defined(__GNUG__)
  57. # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
  58. # error pybind11 requires gcc 4.8 or newer
  59. # endif
  60. #elif defined(_MSC_VER)
  61. // Pybind hits various compiler bugs in 2015u2 and earlier, and also makes use of some stl features
  62. // (e.g. std::negation) added in 2015u3:
  63. # if _MSC_FULL_VER < 190024210
  64. # error pybind11 requires MSVC 2015 update 3 or newer
  65. # endif
  66. #endif
  67. #if !defined(PYBIND11_EXPORT)
  68. # if defined(WIN32) || defined(_WIN32)
  69. # define PYBIND11_EXPORT __declspec(dllexport)
  70. # else
  71. # define PYBIND11_EXPORT __attribute__ ((visibility("default")))
  72. # endif
  73. #endif
  74. #if defined(_MSC_VER)
  75. # define PYBIND11_NOINLINE __declspec(noinline)
  76. #else
  77. # define PYBIND11_NOINLINE __attribute__ ((noinline))
  78. #endif
  79. #if defined(PYBIND11_CPP14)
  80. # define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
  81. #else
  82. # define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
  83. #endif
  84. #define PYBIND11_VERSION_MAJOR 2
  85. #define PYBIND11_VERSION_MINOR 3
  86. #define PYBIND11_VERSION_PATCH dev0
  87. /// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
  88. #if defined(_MSC_VER)
  89. # if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 4)
  90. # define HAVE_ROUND 1
  91. # endif
  92. # pragma warning(push)
  93. # pragma warning(disable: 4510 4610 4512 4005)
  94. # if defined(_DEBUG)
  95. # define PYBIND11_DEBUG_MARKER
  96. # undef _DEBUG
  97. # endif
  98. #endif
  99. #include <Python.h>
  100. #include <frameobject.h>
  101. #include <pythread.h>
  102. #if defined(_WIN32) && (defined(min) || defined(max))
  103. # error Macro clash with min and max -- define NOMINMAX when compiling your program on Windows
  104. #endif
  105. #if defined(isalnum)
  106. # undef isalnum
  107. # undef isalpha
  108. # undef islower
  109. # undef isspace
  110. # undef isupper
  111. # undef tolower
  112. # undef toupper
  113. #endif
  114. #if defined(_MSC_VER)
  115. # if defined(PYBIND11_DEBUG_MARKER)
  116. # define _DEBUG
  117. # undef PYBIND11_DEBUG_MARKER
  118. # endif
  119. # pragma warning(pop)
  120. #endif
  121. #include <cstddef>
  122. #include <cstring>
  123. #include <forward_list>
  124. #include <vector>
  125. #include <string>
  126. #include <stdexcept>
  127. #include <unordered_set>
  128. #include <unordered_map>
  129. #include <memory>
  130. #include <typeindex>
  131. #include <type_traits>
  132. #if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
  133. #define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
  134. #define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
  135. #define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
  136. #define PYBIND11_BYTES_CHECK PyBytes_Check
  137. #define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
  138. #define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
  139. #define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
  140. #define PYBIND11_BYTES_AS_STRING PyBytes_AsString
  141. #define PYBIND11_BYTES_SIZE PyBytes_Size
  142. #define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
  143. #define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
  144. #define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) o)
  145. #define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) o)
  146. #define PYBIND11_BYTES_NAME "bytes"
  147. #define PYBIND11_STRING_NAME "str"
  148. #define PYBIND11_SLICE_OBJECT PyObject
  149. #define PYBIND11_FROM_STRING PyUnicode_FromString
  150. #define PYBIND11_STR_TYPE ::pybind11::str
  151. #define PYBIND11_BOOL_ATTR "__bool__"
  152. #define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
  153. #define PYBIND11_PLUGIN_IMPL(name) \
  154. extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
  155. #else
  156. #define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
  157. #define PYBIND11_INSTANCE_METHOD_CHECK PyMethod_Check
  158. #define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyMethod_GET_FUNCTION
  159. #define PYBIND11_BYTES_CHECK PyString_Check
  160. #define PYBIND11_BYTES_FROM_STRING PyString_FromString
  161. #define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
  162. #define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
  163. #define PYBIND11_BYTES_AS_STRING PyString_AsString
  164. #define PYBIND11_BYTES_SIZE PyString_Size
  165. #define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
  166. #define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
  167. #define PYBIND11_LONG_FROM_SIGNED(o) PyInt_FromSsize_t((ssize_t) o) // Returns long if needed.
  168. #define PYBIND11_LONG_FROM_UNSIGNED(o) PyInt_FromSize_t((size_t) o) // Returns long if needed.
  169. #define PYBIND11_BYTES_NAME "str"
  170. #define PYBIND11_STRING_NAME "unicode"
  171. #define PYBIND11_SLICE_OBJECT PySliceObject
  172. #define PYBIND11_FROM_STRING PyString_FromString
  173. #define PYBIND11_STR_TYPE ::pybind11::bytes
  174. #define PYBIND11_BOOL_ATTR "__nonzero__"
  175. #define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_nonzero)
  176. #define PYBIND11_PLUGIN_IMPL(name) \
  177. static PyObject *pybind11_init_wrapper(); \
  178. extern "C" PYBIND11_EXPORT void init##name() { \
  179. (void)pybind11_init_wrapper(); \
  180. } \
  181. PyObject *pybind11_init_wrapper()
  182. #endif
  183. #if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
  184. extern "C" {
  185. struct _Py_atomic_address { void *value; };
  186. PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
  187. }
  188. #endif
  189. #define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
  190. #define PYBIND11_STRINGIFY(x) #x
  191. #define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
  192. #define PYBIND11_CONCAT(first, second) first##second
  193. #define PYBIND11_CHECK_PYTHON_VERSION \
  194. { \
  195. const char *compiled_ver = PYBIND11_TOSTRING(PY_MAJOR_VERSION) \
  196. "." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
  197. const char *runtime_ver = Py_GetVersion(); \
  198. size_t len = std::strlen(compiled_ver); \
  199. if (std::strncmp(runtime_ver, compiled_ver, len) != 0 \
  200. || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) { \
  201. PyErr_Format(PyExc_ImportError, \
  202. "Python version mismatch: module was compiled for Python %s, " \
  203. "but the interpreter version is incompatible: %s.", \
  204. compiled_ver, runtime_ver); \
  205. return nullptr; \
  206. } \
  207. }
  208. #define PYBIND11_CATCH_INIT_EXCEPTIONS \
  209. catch (pybind11::error_already_set &e) { \
  210. PyErr_SetString(PyExc_ImportError, e.what()); \
  211. return nullptr; \
  212. } catch (const std::exception &e) { \
  213. PyErr_SetString(PyExc_ImportError, e.what()); \
  214. return nullptr; \
  215. } \
  216. /** \rst
  217. ***Deprecated in favor of PYBIND11_MODULE***
  218. This macro creates the entry point that will be invoked when the Python interpreter
  219. imports a plugin library. Please create a `module` in the function body and return
  220. the pointer to its underlying Python object at the end.
  221. .. code-block:: cpp
  222. PYBIND11_PLUGIN(example) {
  223. pybind11::module m("example", "pybind11 example plugin");
  224. /// Set up bindings here
  225. return m.ptr();
  226. }
  227. \endrst */
  228. #define PYBIND11_PLUGIN(name) \
  229. PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE") \
  230. static PyObject *pybind11_init(); \
  231. PYBIND11_PLUGIN_IMPL(name) { \
  232. PYBIND11_CHECK_PYTHON_VERSION \
  233. try { \
  234. return pybind11_init(); \
  235. } PYBIND11_CATCH_INIT_EXCEPTIONS \
  236. } \
  237. PyObject *pybind11_init()
  238. /** \rst
  239. This macro creates the entry point that will be invoked when the Python interpreter
  240. imports an extension module. The module name is given as the fist argument and it
  241. should not be in quotes. The second macro argument defines a variable of type
  242. `py::module` which can be used to initialize the module.
  243. .. code-block:: cpp
  244. PYBIND11_MODULE(example, m) {
  245. m.doc() = "pybind11 example module";
  246. // Add bindings here
  247. m.def("foo", []() {
  248. return "Hello, World!";
  249. });
  250. }
  251. \endrst */
  252. #define PYBIND11_MODULE(name, variable) \
  253. static void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &); \
  254. PYBIND11_PLUGIN_IMPL(name) { \
  255. PYBIND11_CHECK_PYTHON_VERSION \
  256. auto m = pybind11::module(PYBIND11_TOSTRING(name)); \
  257. try { \
  258. PYBIND11_CONCAT(pybind11_init_, name)(m); \
  259. return m.ptr(); \
  260. } PYBIND11_CATCH_INIT_EXCEPTIONS \
  261. } \
  262. void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &variable)
  263. NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  264. using ssize_t = Py_ssize_t;
  265. using size_t = std::size_t;
  266. /// Approach used to cast a previously unknown C++ instance into a Python object
  267. enum class return_value_policy : uint8_t {
  268. /** This is the default return value policy, which falls back to the policy
  269. return_value_policy::take_ownership when the return value is a pointer.
  270. Otherwise, it uses return_value::move or return_value::copy for rvalue
  271. and lvalue references, respectively. See below for a description of what
  272. all of these different policies do. */
  273. automatic = 0,
  274. /** As above, but use policy return_value_policy::reference when the return
  275. value is a pointer. This is the default conversion policy for function
  276. arguments when calling Python functions manually from C++ code (i.e. via
  277. handle::operator()). You probably won't need to use this. */
  278. automatic_reference,
  279. /** Reference an existing object (i.e. do not create a new copy) and take
  280. ownership. Python will call the destructor and delete operator when the
  281. object’s reference count reaches zero. Undefined behavior ensues when
  282. the C++ side does the same.. */
  283. take_ownership,
  284. /** Create a new copy of the returned object, which will be owned by
  285. Python. This policy is comparably safe because the lifetimes of the two
  286. instances are decoupled. */
  287. copy,
  288. /** Use std::move to move the return value contents into a new instance
  289. that will be owned by Python. This policy is comparably safe because the
  290. lifetimes of the two instances (move source and destination) are
  291. decoupled. */
  292. move,
  293. /** Reference an existing object, but do not take ownership. The C++ side
  294. is responsible for managing the object’s lifetime and deallocating it
  295. when it is no longer used. Warning: undefined behavior will ensue when
  296. the C++ side deletes an object that is still referenced and used by
  297. Python. */
  298. reference,
  299. /** This policy only applies to methods and properties. It references the
  300. object without taking ownership similar to the above
  301. return_value_policy::reference policy. In contrast to that policy, the
  302. function or property’s implicit this argument (called the parent) is
  303. considered to be the the owner of the return value (the child).
  304. pybind11 then couples the lifetime of the parent to the child via a
  305. reference relationship that ensures that the parent cannot be garbage
  306. collected while Python is still using the child. More advanced
  307. variations of this scheme are also possible using combinations of
  308. return_value_policy::reference and the keep_alive call policy */
  309. reference_internal
  310. };
  311. NAMESPACE_BEGIN(detail)
  312. inline static constexpr int log2(size_t n, int k = 0) { return (n <= 1) ? k : log2(n >> 1, k + 1); }
  313. // Returns the size as a multiple of sizeof(void *), rounded up.
  314. inline static constexpr size_t size_in_ptrs(size_t s) { return 1 + ((s - 1) >> log2(sizeof(void *))); }
  315. /**
  316. * The space to allocate for simple layout instance holders (see below) in multiple of the size of
  317. * a pointer (e.g. 2 means 16 bytes on 64-bit architectures). The default is the minimum required
  318. * to holder either a std::unique_ptr or std::shared_ptr (which is almost always
  319. * sizeof(std::shared_ptr<T>)).
  320. */
  321. constexpr size_t instance_simple_holder_in_ptrs() {
  322. static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
  323. "pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
  324. return size_in_ptrs(sizeof(std::shared_ptr<int>));
  325. }
  326. // Forward declarations
  327. struct type_info;
  328. struct value_and_holder;
  329. struct nonsimple_values_and_holders {
  330. void **values_and_holders;
  331. uint8_t *status;
  332. };
  333. /// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
  334. struct instance {
  335. PyObject_HEAD
  336. /// Storage for pointers and holder; see simple_layout, below, for a description
  337. union {
  338. void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
  339. nonsimple_values_and_holders nonsimple;
  340. };
  341. /// Weak references
  342. PyObject *weakrefs;
  343. /// If true, the pointer is owned which means we're free to manage it with a holder.
  344. bool owned : 1;
  345. /**
  346. * An instance has two possible value/holder layouts.
  347. *
  348. * Simple layout (when this flag is true), means the `simple_value_holder` is set with a pointer
  349. * and the holder object governing that pointer, i.e. [val1*][holder]. This layout is applied
  350. * whenever there is no python-side multiple inheritance of bound C++ types *and* the type's
  351. * holder will fit in the default space (which is large enough to hold either a std::unique_ptr
  352. * or std::shared_ptr).
  353. *
  354. * Non-simple layout applies when using custom holders that require more space than `shared_ptr`
  355. * (which is typically the size of two pointers), or when multiple inheritance is used on the
  356. * python side. Non-simple layout allocates the required amount of memory to have multiple
  357. * bound C++ classes as parents. Under this layout, `nonsimple.values_and_holders` is set to a
  358. * pointer to allocated space of the required space to hold a sequence of value pointers and
  359. * holders followed `status`, a set of bit flags (1 byte each), i.e.
  360. * [val1*][holder1][val2*][holder2]...[bb...] where each [block] is rounded up to a multiple of
  361. * `sizeof(void *)`. `nonsimple.status` is, for convenience, a pointer to the
  362. * beginning of the [bb...] block (but not independently allocated).
  363. *
  364. * Status bits indicate whether the associated holder is constructed (&
  365. * status_holder_constructed) and whether the value pointer is registered (&
  366. * status_instance_registered) in `registered_instances`.
  367. */
  368. bool simple_layout : 1;
  369. /// For simple layout, tracks whether the holder has been constructed
  370. bool simple_holder_constructed : 1;
  371. /// For simple layout, tracks whether the instance is registered in `registered_instances`
  372. bool simple_instance_registered : 1;
  373. /// If true, get_internals().patients has an entry for this object
  374. bool has_patients : 1;
  375. /// Initializes all of the above type/values/holders data (but not the instance values themselves)
  376. void allocate_layout();
  377. /// Destroys/deallocates all of the above
  378. void deallocate_layout();
  379. /// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
  380. /// omitted). Returns a default-constructed (with `.inst = nullptr`) object on failure if
  381. /// `throw_if_missing` is false.
  382. value_and_holder get_value_and_holder(const type_info *find_type = nullptr, bool throw_if_missing = true);
  383. /// Bit values for the non-simple status flags
  384. static constexpr uint8_t status_holder_constructed = 1;
  385. static constexpr uint8_t status_instance_registered = 2;
  386. };
  387. static_assert(std::is_standard_layout<instance>::value, "Internal error: `pybind11::detail::instance` is not standard layout!");
  388. /// from __cpp_future__ import (convenient aliases from C++14/17)
  389. #if defined(PYBIND11_CPP14) && (!defined(_MSC_VER) || _MSC_VER >= 1910)
  390. using std::enable_if_t;
  391. using std::conditional_t;
  392. using std::remove_cv_t;
  393. using std::remove_reference_t;
  394. #else
  395. template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
  396. template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
  397. template <typename T> using remove_cv_t = typename std::remove_cv<T>::type;
  398. template <typename T> using remove_reference_t = typename std::remove_reference<T>::type;
  399. #endif
  400. /// Index sequences
  401. #if defined(PYBIND11_CPP14)
  402. using std::index_sequence;
  403. using std::make_index_sequence;
  404. #else
  405. template<size_t ...> struct index_sequence { };
  406. template<size_t N, size_t ...S> struct make_index_sequence_impl : make_index_sequence_impl <N - 1, N - 1, S...> { };
  407. template<size_t ...S> struct make_index_sequence_impl <0, S...> { typedef index_sequence<S...> type; };
  408. template<size_t N> using make_index_sequence = typename make_index_sequence_impl<N>::type;
  409. #endif
  410. /// Make an index sequence of the indices of true arguments
  411. template <typename ISeq, size_t, bool...> struct select_indices_impl { using type = ISeq; };
  412. template <size_t... IPrev, size_t I, bool B, bool... Bs> struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
  413. : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>, I + 1, Bs...> {};
  414. template <bool... Bs> using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
  415. /// Backports of std::bool_constant and std::negation to accommodate older compilers
  416. template <bool B> using bool_constant = std::integral_constant<bool, B>;
  417. template <typename T> struct negation : bool_constant<!T::value> { };
  418. template <typename...> struct void_t_impl { using type = void; };
  419. template <typename... Ts> using void_t = typename void_t_impl<Ts...>::type;
  420. /// Compile-time all/any/none of that check the boolean value of all template types
  421. #if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
  422. template <class... Ts> using all_of = bool_constant<(Ts::value && ...)>;
  423. template <class... Ts> using any_of = bool_constant<(Ts::value || ...)>;
  424. #elif !defined(_MSC_VER)
  425. template <bool...> struct bools {};
  426. template <class... Ts> using all_of = std::is_same<
  427. bools<Ts::value..., true>,
  428. bools<true, Ts::value...>>;
  429. template <class... Ts> using any_of = negation<all_of<negation<Ts>...>>;
  430. #else
  431. // MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
  432. // at a slight loss of compilation efficiency).
  433. template <class... Ts> using all_of = std::conjunction<Ts...>;
  434. template <class... Ts> using any_of = std::disjunction<Ts...>;
  435. #endif
  436. template <class... Ts> using none_of = negation<any_of<Ts...>>;
  437. template <class T, template<class> class... Predicates> using satisfies_all_of = all_of<Predicates<T>...>;
  438. template <class T, template<class> class... Predicates> using satisfies_any_of = any_of<Predicates<T>...>;
  439. template <class T, template<class> class... Predicates> using satisfies_none_of = none_of<Predicates<T>...>;
  440. /// Strip the class from a method type
  441. template <typename T> struct remove_class { };
  442. template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
  443. template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
  444. /// Helper template to strip away type modifiers
  445. template <typename T> struct intrinsic_type { typedef T type; };
  446. template <typename T> struct intrinsic_type<const T> { typedef typename intrinsic_type<T>::type type; };
  447. template <typename T> struct intrinsic_type<T*> { typedef typename intrinsic_type<T>::type type; };
  448. template <typename T> struct intrinsic_type<T&> { typedef typename intrinsic_type<T>::type type; };
  449. template <typename T> struct intrinsic_type<T&&> { typedef typename intrinsic_type<T>::type type; };
  450. template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
  451. template <typename T, size_t N> struct intrinsic_type<T[N]> { typedef typename intrinsic_type<T>::type type; };
  452. template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
  453. /// Helper type to replace 'void' in some expressions
  454. struct void_type { };
  455. /// Helper template which holds a list of types
  456. template <typename...> struct type_list { };
  457. /// Compile-time integer sum
  458. #ifdef __cpp_fold_expressions
  459. template <typename... Ts> constexpr size_t constexpr_sum(Ts... ns) { return (0 + ... + size_t{ns}); }
  460. #else
  461. constexpr size_t constexpr_sum() { return 0; }
  462. template <typename T, typename... Ts>
  463. constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
  464. #endif
  465. NAMESPACE_BEGIN(constexpr_impl)
  466. /// Implementation details for constexpr functions
  467. constexpr int first(int i) { return i; }
  468. template <typename T, typename... Ts>
  469. constexpr int first(int i, T v, Ts... vs) { return v ? i : first(i + 1, vs...); }
  470. constexpr int last(int /*i*/, int result) { return result; }
  471. template <typename T, typename... Ts>
  472. constexpr int last(int i, int result, T v, Ts... vs) { return last(i + 1, v ? i : result, vs...); }
  473. NAMESPACE_END(constexpr_impl)
  474. /// Return the index of the first type in Ts which satisfies Predicate<T>. Returns sizeof...(Ts) if
  475. /// none match.
  476. template <template<typename> class Predicate, typename... Ts>
  477. constexpr int constexpr_first() { return constexpr_impl::first(0, Predicate<Ts>::value...); }
  478. /// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
  479. template <template<typename> class Predicate, typename... Ts>
  480. constexpr int constexpr_last() { return constexpr_impl::last(0, -1, Predicate<Ts>::value...); }
  481. /// Return the Nth element from the parameter pack
  482. template <size_t N, typename T, typename... Ts>
  483. struct pack_element { using type = typename pack_element<N - 1, Ts...>::type; };
  484. template <typename T, typename... Ts>
  485. struct pack_element<0, T, Ts...> { using type = T; };
  486. /// Return the one and only type which matches the predicate, or Default if none match.
  487. /// If more than one type matches the predicate, fail at compile-time.
  488. template <template<typename> class Predicate, typename Default, typename... Ts>
  489. struct exactly_one {
  490. static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
  491. static_assert(found <= 1, "Found more than one type matching the predicate");
  492. static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
  493. using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
  494. };
  495. template <template<typename> class P, typename Default>
  496. struct exactly_one<P, Default> { using type = Default; };
  497. template <template<typename> class Predicate, typename Default, typename... Ts>
  498. using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
  499. /// Defer the evaluation of type T until types Us are instantiated
  500. template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
  501. template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
  502. /// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
  503. /// unlike `std::is_base_of`)
  504. template <typename Base, typename Derived> using is_strict_base_of = bool_constant<
  505. std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
  506. /// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived pointer
  507. /// can be converted to a Base pointer)
  508. template <typename Base, typename Derived> using is_accessible_base_of = bool_constant<
  509. std::is_base_of<Base, Derived>::value && std::is_convertible<Derived *, Base *>::value>;
  510. template <template<typename...> class Base>
  511. struct is_template_base_of_impl {
  512. template <typename... Us> static std::true_type check(Base<Us...> *);
  513. static std::false_type check(...);
  514. };
  515. /// Check if a template is the base of a type. For example:
  516. /// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
  517. template <template<typename...> class Base, typename T>
  518. #if !defined(_MSC_VER)
  519. using is_template_base_of = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr));
  520. #else // MSVC2015 has trouble with decltype in template aliases
  521. struct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr)) { };
  522. #endif
  523. /// Check if T is an instantiation of the template `Class`. For example:
  524. /// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
  525. template <template<typename...> class Class, typename T>
  526. struct is_instantiation : std::false_type { };
  527. template <template<typename...> class Class, typename... Us>
  528. struct is_instantiation<Class, Class<Us...>> : std::true_type { };
  529. /// Check if T is std::shared_ptr<U> where U can be anything
  530. template <typename T> using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
  531. /// Check if T looks like an input iterator
  532. template <typename T, typename = void> struct is_input_iterator : std::false_type {};
  533. template <typename T>
  534. struct is_input_iterator<T, void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
  535. : std::true_type {};
  536. template <typename T> using is_function_pointer = bool_constant<
  537. std::is_pointer<T>::value && std::is_function<typename std::remove_pointer<T>::type>::value>;
  538. template <typename F> struct strip_function_object {
  539. using type = typename remove_class<decltype(&F::operator())>::type;
  540. };
  541. // Extracts the function signature from a function, function pointer or lambda.
  542. template <typename Function, typename F = remove_reference_t<Function>>
  543. using function_signature_t = conditional_t<
  544. std::is_function<F>::value,
  545. F,
  546. typename conditional_t<
  547. std::is_pointer<F>::value || std::is_member_pointer<F>::value,
  548. std::remove_pointer<F>,
  549. strip_function_object<F>
  550. >::type
  551. >;
  552. /// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
  553. /// pointer. Note that this can catch all sorts of other things, too; this is intended to be used
  554. /// in a place where passing a lambda makes sense.
  555. template <typename T> using is_lambda = satisfies_none_of<remove_reference_t<T>,
  556. std::is_function, std::is_pointer, std::is_member_pointer>;
  557. /// Ignore that a variable is unused in compiler warnings
  558. inline void ignore_unused(const int *) { }
  559. /// Apply a function over each element of a parameter pack
  560. #ifdef __cpp_fold_expressions
  561. #define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
  562. #else
  563. using expand_side_effects = bool[];
  564. #define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) pybind11::detail::expand_side_effects{ ((PATTERN), void(), false)..., false }
  565. #endif
  566. NAMESPACE_END(detail)
  567. /// C++ bindings of builtin Python exceptions
  568. class builtin_exception : public std::runtime_error {
  569. public:
  570. using std::runtime_error::runtime_error;
  571. /// Set the error using the Python C API
  572. virtual void set_error() const = 0;
  573. };
  574. #define PYBIND11_RUNTIME_EXCEPTION(name, type) \
  575. class name : public builtin_exception { public: \
  576. using builtin_exception::builtin_exception; \
  577. name() : name("") { } \
  578. void set_error() const override { PyErr_SetString(type, what()); } \
  579. };
  580. PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
  581. PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
  582. PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
  583. PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
  584. PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
  585. PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
  586. PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
  587. [[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
  588. [[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
  589. template <typename T, typename SFINAE = void> struct format_descriptor { };
  590. NAMESPACE_BEGIN(detail)
  591. // Returns the index of the given type in the type char array below, and in the list in numpy.h
  592. // The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
  593. // complex float,double,long double. Note that the long double types only participate when long
  594. // double is actually longer than double (it isn't under MSVC).
  595. // NB: not only the string below but also complex.h and numpy.h rely on this order.
  596. template <typename T, typename SFINAE = void> struct is_fmt_numeric { static constexpr bool value = false; };
  597. template <typename T> struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
  598. static constexpr bool value = true;
  599. static constexpr int index = std::is_same<T, bool>::value ? 0 : 1 + (
  600. std::is_integral<T>::value ? detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value : 8 + (
  601. std::is_same<T, double>::value ? 1 : std::is_same<T, long double>::value ? 2 : 0));
  602. };
  603. NAMESPACE_END(detail)
  604. template <typename T> struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
  605. static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
  606. static constexpr const char value[2] = { c, '\0' };
  607. static std::string format() { return std::string(1, c); }
  608. };
  609. #if !defined(PYBIND11_CPP17)
  610. template <typename T> constexpr const char format_descriptor<
  611. T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
  612. #endif
  613. /// RAII wrapper that temporarily clears any Python error state
  614. struct error_scope {
  615. PyObject *type, *value, *trace;
  616. error_scope() { PyErr_Fetch(&type, &value, &trace); }
  617. ~error_scope() { PyErr_Restore(type, value, trace); }
  618. };
  619. /// Dummy destructor wrapper that can be used to expose classes with a private destructor
  620. struct nodelete { template <typename T> void operator()(T*) { } };
  621. // overload_cast requires variable templates: C++14
  622. #if defined(PYBIND11_CPP14)
  623. #define PYBIND11_OVERLOAD_CAST 1
  624. NAMESPACE_BEGIN(detail)
  625. template <typename... Args>
  626. struct overload_cast_impl {
  627. constexpr overload_cast_impl() {} // MSVC 2015 needs this
  628. template <typename Return>
  629. constexpr auto operator()(Return (*pf)(Args...)) const noexcept
  630. -> decltype(pf) { return pf; }
  631. template <typename Return, typename Class>
  632. constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
  633. -> decltype(pmf) { return pmf; }
  634. template <typename Return, typename Class>
  635. constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
  636. -> decltype(pmf) { return pmf; }
  637. };
  638. NAMESPACE_END(detail)
  639. /// Syntax sugar for resolving overloaded function pointers:
  640. /// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
  641. /// - sweet: overload_cast<Arg0, Arg1, Arg2>(&Class::func)
  642. template <typename... Args>
  643. static constexpr detail::overload_cast_impl<Args...> overload_cast = {};
  644. // MSVC 2015 only accepts this particular initialization syntax for this variable template.
  645. /// Const member function selector for overload_cast
  646. /// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
  647. /// - sweet: overload_cast<Arg>(&Class::func, const_)
  648. static constexpr auto const_ = std::true_type{};
  649. #else // no overload_cast: providing something that static_assert-fails:
  650. template <typename... Args> struct overload_cast {
  651. static_assert(detail::deferred_t<std::false_type, Args...>::value,
  652. "pybind11::overload_cast<...> requires compiling in C++14 mode");
  653. };
  654. #endif // overload_cast
  655. NAMESPACE_BEGIN(detail)
  656. // Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
  657. // any standard container (or C-style array) supporting std::begin/std::end, any singleton
  658. // arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
  659. template <typename T>
  660. class any_container {
  661. std::vector<T> v;
  662. public:
  663. any_container() = default;
  664. // Can construct from a pair of iterators
  665. template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
  666. any_container(It first, It last) : v(first, last) { }
  667. // Implicit conversion constructor from any arbitrary container type with values convertible to T
  668. template <typename Container, typename = enable_if_t<std::is_convertible<decltype(*std::begin(std::declval<const Container &>())), T>::value>>
  669. any_container(const Container &c) : any_container(std::begin(c), std::end(c)) { }
  670. // initializer_list's aren't deducible, so don't get matched by the above template; we need this
  671. // to explicitly allow implicit conversion from one:
  672. template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
  673. any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) { }
  674. // Avoid copying if given an rvalue vector of the correct type.
  675. any_container(std::vector<T> &&v) : v(std::move(v)) { }
  676. // Moves the vector out of an rvalue any_container
  677. operator std::vector<T> &&() && { return std::move(v); }
  678. // Dereferencing obtains a reference to the underlying vector
  679. std::vector<T> &operator*() { return v; }
  680. const std::vector<T> &operator*() const { return v; }
  681. // -> lets you call methods on the underlying vector
  682. std::vector<T> *operator->() { return &v; }
  683. const std::vector<T> *operator->() const { return &v; }
  684. };
  685. NAMESPACE_END(detail)
  686. NAMESPACE_END(PYBIND11_NAMESPACE)