You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

719 lines
31 KiB

8 years ago
  1. /*
  2. pybind11/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. // Neither MSVC nor Intel support enough of C++14 yet (in particular, as of MSVC 2015 and ICC 17
  15. // beta, neither support extended constexpr, which we rely on in descr.h), so don't enable pybind
  16. // CPP14 features for them.
  17. #if !defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  18. # if __cplusplus >= 201402L
  19. # define PYBIND11_CPP14
  20. # if __cplusplus > 201402L /* Temporary: should be updated to >= the final C++17 value once known */
  21. # define PYBIND11_CPP17
  22. # endif
  23. # endif
  24. #endif
  25. // Compiler version assertions
  26. #if defined(__INTEL_COMPILER)
  27. # if __INTEL_COMPILER < 1500
  28. # error pybind11 requires Intel C++ compiler v15 or newer
  29. # endif
  30. #elif defined(__clang__) && !defined(__apple_build_version__)
  31. # if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
  32. # error pybind11 requires clang 3.3 or newer
  33. # endif
  34. #elif defined(__clang__)
  35. // Apple changes clang version macros to its Xcode version; the first Xcode release based on
  36. // (upstream) clang 3.3 was Xcode 5:
  37. # if __clang_major__ < 5
  38. # error pybind11 requires Xcode/clang 5.0 or newer
  39. # endif
  40. #elif defined(__GNUG__)
  41. # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
  42. # error pybind11 requires gcc 4.8 or newer
  43. # endif
  44. #elif defined(_MSC_VER)
  45. // Pybind hits various compiler bugs in 2015u2 and earlier, and also makes use of some stl features
  46. // (e.g. std::negation) added in 2015u3:
  47. # if _MSC_FULL_VER < 190024213
  48. # error pybind11 requires MSVC 2015 update 3 or newer
  49. # endif
  50. #endif
  51. #if !defined(PYBIND11_EXPORT)
  52. # if defined(WIN32) || defined(_WIN32)
  53. # define PYBIND11_EXPORT __declspec(dllexport)
  54. # else
  55. # define PYBIND11_EXPORT __attribute__ ((visibility("default")))
  56. # endif
  57. #endif
  58. #if defined(_MSC_VER)
  59. # define PYBIND11_NOINLINE __declspec(noinline)
  60. #else
  61. # define PYBIND11_NOINLINE __attribute__ ((noinline))
  62. #endif
  63. #if defined(PYBIND11_CPP14)
  64. # define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
  65. #elif defined(__clang__)
  66. # define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
  67. #elif defined(__GNUG__)
  68. # define PYBIND11_DEPRECATED(reason) __attribute__((deprecated))
  69. #elif defined(_MSC_VER)
  70. # define PYBIND11_DEPRECATED(reason) __declspec(deprecated)
  71. #endif
  72. #define PYBIND11_VERSION_MAJOR 2
  73. #define PYBIND11_VERSION_MINOR 2
  74. #define PYBIND11_VERSION_PATCH dev0
  75. /// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
  76. #if defined(_MSC_VER)
  77. # if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 4)
  78. # define HAVE_ROUND 1
  79. # endif
  80. # pragma warning(push)
  81. # pragma warning(disable: 4510 4610 4512 4005)
  82. # if defined(_DEBUG)
  83. # define PYBIND11_DEBUG_MARKER
  84. # undef _DEBUG
  85. # endif
  86. #endif
  87. #include <Python.h>
  88. #include <frameobject.h>
  89. #include <pythread.h>
  90. #if defined(_WIN32) && (defined(min) || defined(max))
  91. # error Macro clash with min and max -- define NOMINMAX when compiling your program on Windows
  92. #endif
  93. #if defined(isalnum)
  94. # undef isalnum
  95. # undef isalpha
  96. # undef islower
  97. # undef isspace
  98. # undef isupper
  99. # undef tolower
  100. # undef toupper
  101. #endif
  102. #if defined(_MSC_VER)
  103. # if defined(PYBIND11_DEBUG_MARKER)
  104. # define _DEBUG
  105. # undef PYBIND11_DEBUG_MARKER
  106. # endif
  107. # pragma warning(pop)
  108. #endif
  109. #include <cstddef>
  110. #include <forward_list>
  111. #include <vector>
  112. #include <string>
  113. #include <stdexcept>
  114. #include <unordered_set>
  115. #include <unordered_map>
  116. #include <memory>
  117. #include <typeindex>
  118. #include <type_traits>
  119. #if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
  120. #define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
  121. #define PYBIND11_BYTES_CHECK PyBytes_Check
  122. #define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
  123. #define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
  124. #define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
  125. #define PYBIND11_BYTES_AS_STRING PyBytes_AsString
  126. #define PYBIND11_BYTES_SIZE PyBytes_Size
  127. #define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
  128. #define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
  129. #define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) PyLong_AsUnsignedLongLong(o)
  130. #define PYBIND11_BYTES_NAME "bytes"
  131. #define PYBIND11_STRING_NAME "str"
  132. #define PYBIND11_SLICE_OBJECT PyObject
  133. #define PYBIND11_FROM_STRING PyUnicode_FromString
  134. #define PYBIND11_STR_TYPE ::pybind11::str
  135. #define PYBIND11_PLUGIN_IMPL(name) \
  136. extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
  137. #else
  138. #define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
  139. #define PYBIND11_BYTES_CHECK PyString_Check
  140. #define PYBIND11_BYTES_FROM_STRING PyString_FromString
  141. #define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
  142. #define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
  143. #define PYBIND11_BYTES_AS_STRING PyString_AsString
  144. #define PYBIND11_BYTES_SIZE PyString_Size
  145. #define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
  146. #define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
  147. #define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) (PyInt_Check(o) ? (unsigned long long) PyLong_AsUnsignedLong(o) : PyLong_AsUnsignedLongLong(o))
  148. #define PYBIND11_BYTES_NAME "str"
  149. #define PYBIND11_STRING_NAME "unicode"
  150. #define PYBIND11_SLICE_OBJECT PySliceObject
  151. #define PYBIND11_FROM_STRING PyString_FromString
  152. #define PYBIND11_STR_TYPE ::pybind11::bytes
  153. #define PYBIND11_PLUGIN_IMPL(name) \
  154. static PyObject *pybind11_init_wrapper(); \
  155. extern "C" PYBIND11_EXPORT void init##name() { \
  156. (void)pybind11_init_wrapper(); \
  157. } \
  158. PyObject *pybind11_init_wrapper()
  159. #endif
  160. #if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
  161. extern "C" {
  162. struct _Py_atomic_address { void *value; };
  163. PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
  164. }
  165. #endif
  166. #define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
  167. #define PYBIND11_STRINGIFY(x) #x
  168. #define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
  169. #define PYBIND11_INTERNALS_ID "__pybind11_" \
  170. PYBIND11_TOSTRING(PYBIND11_VERSION_MAJOR) "_" PYBIND11_TOSTRING(PYBIND11_VERSION_MINOR) "__"
  171. /** \rst
  172. This macro creates the entry point that will be invoked when the Python interpreter
  173. imports a plugin library. Please create a `module` in the function body and return
  174. the pointer to its underlying Python object at the end.
  175. .. code-block:: cpp
  176. PYBIND11_PLUGIN(example) {
  177. pybind11::module m("example", "pybind11 example plugin");
  178. /// Set up bindings here
  179. return m.ptr();
  180. }
  181. \endrst */
  182. #define PYBIND11_PLUGIN(name) \
  183. static PyObject *pybind11_init(); \
  184. PYBIND11_PLUGIN_IMPL(name) { \
  185. int major, minor; \
  186. if (sscanf(Py_GetVersion(), "%i.%i", &major, &minor) != 2) { \
  187. PyErr_SetString(PyExc_ImportError, "Can't parse Python version."); \
  188. return nullptr; \
  189. } else if (major != PY_MAJOR_VERSION || minor != PY_MINOR_VERSION) { \
  190. PyErr_Format(PyExc_ImportError, \
  191. "Python version mismatch: module was compiled for " \
  192. "version %i.%i, while the interpreter is running " \
  193. "version %i.%i.", PY_MAJOR_VERSION, PY_MINOR_VERSION, \
  194. major, minor); \
  195. return nullptr; \
  196. } \
  197. try { \
  198. return pybind11_init(); \
  199. } catch (pybind11::error_already_set &e) { \
  200. e.clear(); \
  201. PyErr_SetString(PyExc_ImportError, e.what()); \
  202. return nullptr; \
  203. } catch (const std::exception &e) { \
  204. PyErr_SetString(PyExc_ImportError, e.what()); \
  205. return nullptr; \
  206. } \
  207. } \
  208. PyObject *pybind11_init()
  209. NAMESPACE_BEGIN(pybind11)
  210. using ssize_t = Py_ssize_t;
  211. using size_t = std::size_t;
  212. /// Approach used to cast a previously unknown C++ instance into a Python object
  213. enum class return_value_policy : uint8_t {
  214. /** This is the default return value policy, which falls back to the policy
  215. return_value_policy::take_ownership when the return value is a pointer.
  216. Otherwise, it uses return_value::move or return_value::copy for rvalue
  217. and lvalue references, respectively. See below for a description of what
  218. all of these different policies do. */
  219. automatic = 0,
  220. /** As above, but use policy return_value_policy::reference when the return
  221. value is a pointer. This is the default conversion policy for function
  222. arguments when calling Python functions manually from C++ code (i.e. via
  223. handle::operator()). You probably won't need to use this. */
  224. automatic_reference,
  225. /** Reference an existing object (i.e. do not create a new copy) and take
  226. ownership. Python will call the destructor and delete operator when the
  227. objects reference count reaches zero. Undefined behavior ensues when
  228. the C++ side does the same.. */
  229. take_ownership,
  230. /** Create a new copy of the returned object, which will be owned by
  231. Python. This policy is comparably safe because the lifetimes of the two
  232. instances are decoupled. */
  233. copy,
  234. /** Use std::move to move the return value contents into a new instance
  235. that will be owned by Python. This policy is comparably safe because the
  236. lifetimes of the two instances (move source and destination) are
  237. decoupled. */
  238. move,
  239. /** Reference an existing object, but do not take ownership. The C++ side
  240. is responsible for managing the objects lifetime and deallocating it
  241. when it is no longer used. Warning: undefined behavior will ensue when
  242. the C++ side deletes an object that is still referenced and used by
  243. Python. */
  244. reference,
  245. /** This policy only applies to methods and properties. It references the
  246. object without taking ownership similar to the above
  247. return_value_policy::reference policy. In contrast to that policy, the
  248. function or propertys implicit this argument (called the parent) is
  249. considered to be the the owner of the return value (the child).
  250. pybind11 then couples the lifetime of the parent to the child via a
  251. reference relationship that ensures that the parent cannot be garbage
  252. collected while Python is still using the child. More advanced
  253. variations of this scheme are also possible using combinations of
  254. return_value_policy::reference and the keep_alive call policy */
  255. reference_internal
  256. };
  257. /// Information record describing a Python buffer object
  258. struct buffer_info {
  259. void *ptr = nullptr; // Pointer to the underlying storage
  260. size_t itemsize = 0; // Size of individual items in bytes
  261. size_t size = 0; // Total number of entries
  262. std::string format; // For homogeneous buffers, this should be set to format_descriptor<T>::format()
  263. size_t ndim = 0; // Number of dimensions
  264. std::vector<size_t> shape; // Shape of the tensor (1 entry per dimension)
  265. std::vector<size_t> strides; // Number of entries between adjacent entries (for each per dimension)
  266. buffer_info() { }
  267. buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t ndim,
  268. const std::vector<size_t> &shape, const std::vector<size_t> &strides)
  269. : ptr(ptr), itemsize(itemsize), size(1), format(format),
  270. ndim(ndim), shape(shape), strides(strides) {
  271. for (size_t i = 0; i < ndim; ++i)
  272. size *= shape[i];
  273. }
  274. buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t size)
  275. : buffer_info(ptr, itemsize, format, 1, std::vector<size_t> { size },
  276. std::vector<size_t> { itemsize }) { }
  277. explicit buffer_info(Py_buffer *view, bool ownview = true)
  278. : ptr(view->buf), itemsize((size_t) view->itemsize), size(1), format(view->format),
  279. ndim((size_t) view->ndim), shape((size_t) view->ndim), strides((size_t) view->ndim), view(view), ownview(ownview) {
  280. for (size_t i = 0; i < (size_t) view->ndim; ++i) {
  281. shape[i] = (size_t) view->shape[i];
  282. strides[i] = (size_t) view->strides[i];
  283. size *= shape[i];
  284. }
  285. }
  286. buffer_info(const buffer_info &) = delete;
  287. buffer_info& operator=(const buffer_info &) = delete;
  288. buffer_info(buffer_info &&other) {
  289. (*this) = std::move(other);
  290. }
  291. buffer_info& operator=(buffer_info &&rhs) {
  292. ptr = rhs.ptr;
  293. itemsize = rhs.itemsize;
  294. size = rhs.size;
  295. format = std::move(rhs.format);
  296. ndim = rhs.ndim;
  297. shape = std::move(rhs.shape);
  298. strides = std::move(rhs.strides);
  299. std::swap(view, rhs.view);
  300. std::swap(ownview, rhs.ownview);
  301. return *this;
  302. }
  303. ~buffer_info() {
  304. if (view && ownview) { PyBuffer_Release(view); delete view; }
  305. }
  306. private:
  307. Py_buffer *view = nullptr;
  308. bool ownview = false;
  309. };
  310. NAMESPACE_BEGIN(detail)
  311. inline static constexpr int log2(size_t n, int k = 0) { return (n <= 1) ? k : log2(n >> 1, k + 1); }
  312. inline std::string error_string();
  313. /// Core part of the 'instance' type which POD (needed to be able to use 'offsetof')
  314. template <typename type> struct instance_essentials {
  315. PyObject_HEAD
  316. type *value;
  317. PyObject *weakrefs;
  318. bool owned : 1;
  319. bool holder_constructed : 1;
  320. };
  321. /// PyObject wrapper around generic types, includes a special holder type that is responsible for lifetime management
  322. template <typename type, typename holder_type = std::unique_ptr<type>> struct instance : instance_essentials<type> {
  323. holder_type holder;
  324. };
  325. struct overload_hash {
  326. inline size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
  327. size_t value = std::hash<const void *>()(v.first);
  328. value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value<<6) + (value>>2);
  329. return value;
  330. }
  331. };
  332. /// Internal data structure used to track registered instances and types
  333. struct internals {
  334. std::unordered_map<std::type_index, void*> registered_types_cpp; // std::type_index -> type_info
  335. std::unordered_map<const void *, void*> registered_types_py; // PyTypeObject* -> type_info
  336. std::unordered_multimap<const void *, void*> registered_instances; // void * -> PyObject*
  337. std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
  338. std::unordered_map<std::type_index, std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
  339. std::forward_list<void (*) (std::exception_ptr)> registered_exception_translators;
  340. std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions
  341. PyTypeObject *static_property_type;
  342. PyTypeObject *default_metaclass;
  343. std::unordered_map<size_t, PyObject *> bases; // one base type per `instance_size` (very few)
  344. #if defined(WITH_THREAD)
  345. decltype(PyThread_create_key()) tstate = 0; // Usually an int but a long on Cygwin64 with Python 3.x
  346. PyInterpreterState *istate = nullptr;
  347. #endif
  348. /// Return the appropriate base type for the given instance size
  349. PyObject *get_base(size_t instance_size);
  350. };
  351. /// Return a reference to the current 'internals' information
  352. inline internals &get_internals();
  353. /// from __cpp_future__ import (convenient aliases from C++14/17)
  354. #ifdef PYBIND11_CPP14
  355. using std::enable_if_t;
  356. using std::conditional_t;
  357. using std::remove_cv_t;
  358. #else
  359. template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
  360. template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
  361. template <typename T> using remove_cv_t = typename std::remove_cv<T>::type;
  362. #endif
  363. /// Index sequences
  364. #if defined(PYBIND11_CPP14) || defined(_MSC_VER)
  365. using std::index_sequence;
  366. using std::make_index_sequence;
  367. #else
  368. template<size_t ...> struct index_sequence { };
  369. template<size_t N, size_t ...S> struct make_index_sequence_impl : make_index_sequence_impl <N - 1, N - 1, S...> { };
  370. template<size_t ...S> struct make_index_sequence_impl <0, S...> { typedef index_sequence<S...> type; };
  371. template<size_t N> using make_index_sequence = typename make_index_sequence_impl<N>::type;
  372. #endif
  373. /// Backports of std::bool_constant and std::negation to accomodate older compilers
  374. template <bool B> using bool_constant = std::integral_constant<bool, B>;
  375. template <typename T> struct negation : bool_constant<!T::value> { };
  376. template <typename...> struct void_t_impl { using type = void; };
  377. template <typename... Ts> using void_t = typename void_t_impl<Ts...>::type;
  378. /// Compile-time all/any/none of that check the boolean value of all template types
  379. #ifdef __cpp_fold_expressions
  380. template <class... Ts> using all_of = bool_constant<(Ts::value && ...)>;
  381. template <class... Ts> using any_of = bool_constant<(Ts::value || ...)>;
  382. #elif !defined(_MSC_VER)
  383. template <bool...> struct bools {};
  384. template <class... Ts> using all_of = std::is_same<
  385. bools<Ts::value..., true>,
  386. bools<true, Ts::value...>>;
  387. template <class... Ts> using any_of = negation<all_of<negation<Ts>...>>;
  388. #else
  389. // MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
  390. // at a slight loss of compilation efficiency).
  391. template <class... Ts> using all_of = std::conjunction<Ts...>;
  392. template <class... Ts> using any_of = std::disjunction<Ts...>;
  393. #endif
  394. template <class... Ts> using none_of = negation<any_of<Ts...>>;
  395. template <class T, template<class> class... Predicates> using satisfies_all_of = all_of<Predicates<T>...>;
  396. template <class T, template<class> class... Predicates> using satisfies_any_of = any_of<Predicates<T>...>;
  397. template <class T, template<class> class... Predicates> using satisfies_none_of = none_of<Predicates<T>...>;
  398. /// Strip the class from a method type
  399. template <typename T> struct remove_class { };
  400. template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
  401. template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
  402. /// Helper template to strip away type modifiers
  403. template <typename T> struct intrinsic_type { typedef T type; };
  404. template <typename T> struct intrinsic_type<const T> { typedef typename intrinsic_type<T>::type type; };
  405. template <typename T> struct intrinsic_type<T*> { typedef typename intrinsic_type<T>::type type; };
  406. template <typename T> struct intrinsic_type<T&> { typedef typename intrinsic_type<T>::type type; };
  407. template <typename T> struct intrinsic_type<T&&> { typedef typename intrinsic_type<T>::type type; };
  408. template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
  409. template <typename T, size_t N> struct intrinsic_type<T[N]> { typedef typename intrinsic_type<T>::type type; };
  410. template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
  411. /// Helper type to replace 'void' in some expressions
  412. struct void_type { };
  413. /// Helper template which holds a list of types
  414. template <typename...> struct type_list { };
  415. /// Compile-time integer sum
  416. #ifdef __cpp_fold_expressions
  417. template <typename... Ts> constexpr size_t constexpr_sum(Ts... ns) { return (0 + ... + size_t{ns}); }
  418. #else
  419. constexpr size_t constexpr_sum() { return 0; }
  420. template <typename T, typename... Ts>
  421. constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
  422. #endif
  423. NAMESPACE_BEGIN(constexpr_impl)
  424. /// Implementation details for constexpr functions
  425. constexpr int first(int i) { return i; }
  426. template <typename T, typename... Ts>
  427. constexpr int first(int i, T v, Ts... vs) { return v ? i : first(i + 1, vs...); }
  428. constexpr int last(int /*i*/, int result) { return result; }
  429. template <typename T, typename... Ts>
  430. constexpr int last(int i, int result, T v, Ts... vs) { return last(i + 1, v ? i : result, vs...); }
  431. NAMESPACE_END(constexpr_impl)
  432. /// Return the index of the first type in Ts which satisfies Predicate<T>. Returns sizeof...(Ts) if
  433. /// none match.
  434. template <template<typename> class Predicate, typename... Ts>
  435. constexpr int constexpr_first() { return constexpr_impl::first(0, Predicate<Ts>::value...); }
  436. /// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
  437. template <template<typename> class Predicate, typename... Ts>
  438. constexpr int constexpr_last() { return constexpr_impl::last(0, -1, Predicate<Ts>::value...); }
  439. // Extracts the first type from the template parameter pack matching the predicate, or Default if none match.
  440. template <template<class> class Predicate, class Default, class... Ts> struct first_of;
  441. template <template<class> class Predicate, class Default> struct first_of<Predicate, Default> {
  442. using type = Default;
  443. };
  444. template <template<class> class Predicate, class Default, class T, class... Ts>
  445. struct first_of<Predicate, Default, T, Ts...> {
  446. using type = typename std::conditional<
  447. Predicate<T>::value,
  448. T,
  449. typename first_of<Predicate, Default, Ts...>::type
  450. >::type;
  451. };
  452. template <template<class> class Predicate, class Default, class... T> using first_of_t = typename first_of<Predicate, Default, T...>::type;
  453. /// Defer the evaluation of type T until types Us are instantiated
  454. template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
  455. template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
  456. template <template<typename...> class Base>
  457. struct is_template_base_of_impl {
  458. template <typename... Us> static std::true_type check(Base<Us...> *);
  459. static std::false_type check(...);
  460. };
  461. /// Check if a template is the base of a type. For example:
  462. /// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
  463. template <template<typename...> class Base, typename T>
  464. #if !defined(_MSC_VER)
  465. using is_template_base_of = decltype(is_template_base_of_impl<Base>::check((remove_cv_t<T>*)nullptr));
  466. #else // MSVC2015 has trouble with decltype in template aliases
  467. struct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((remove_cv_t<T>*)nullptr)) { };
  468. #endif
  469. /// Check if T is std::shared_ptr<U> where U can be anything
  470. template <typename T> struct is_shared_ptr : std::false_type { };
  471. template <typename U> struct is_shared_ptr<std::shared_ptr<U>> : std::true_type { };
  472. /// Ignore that a variable is unused in compiler warnings
  473. inline void ignore_unused(const int *) { }
  474. NAMESPACE_END(detail)
  475. /// Returns a named pointer that is shared among all extension modules (using the same
  476. /// pybind11 version) running in the current interpreter. Names starting with underscores
  477. /// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
  478. inline PYBIND11_NOINLINE void* get_shared_data(const std::string& name) {
  479. auto& internals = detail::get_internals();
  480. auto it = internals.shared_data.find(name);
  481. return it != internals.shared_data.end() ? it->second : nullptr;
  482. }
  483. /// Set the shared data that can be later recovered by `get_shared_data()`.
  484. inline PYBIND11_NOINLINE void *set_shared_data(const std::string& name, void *data) {
  485. detail::get_internals().shared_data[name] = data;
  486. return data;
  487. }
  488. /// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
  489. /// such entry exists. Otherwise, a new object of default-constructible type `T` is
  490. /// added to the shared data under the given name and a reference to it is returned.
  491. template<typename T> T& get_or_create_shared_data(const std::string& name) {
  492. auto& internals = detail::get_internals();
  493. auto it = internals.shared_data.find(name);
  494. T* ptr = (T*) (it != internals.shared_data.end() ? it->second : nullptr);
  495. if (!ptr) {
  496. ptr = new T();
  497. internals.shared_data[name] = ptr;
  498. }
  499. return *ptr;
  500. }
  501. /// Fetch and hold an error which was already set in Python
  502. class error_already_set : public std::runtime_error {
  503. public:
  504. error_already_set() : std::runtime_error(detail::error_string()) {
  505. PyErr_Fetch(&type, &value, &trace);
  506. }
  507. error_already_set(const error_already_set &) = delete;
  508. error_already_set(error_already_set &&e)
  509. : std::runtime_error(e.what()), type(e.type), value(e.value),
  510. trace(e.trace) { e.type = e.value = e.trace = nullptr; }
  511. inline ~error_already_set(); // implementation in pybind11.h
  512. error_already_set& operator=(const error_already_set &) = delete;
  513. /// Give the error back to Python
  514. void restore() { PyErr_Restore(type, value, trace); type = value = trace = nullptr; }
  515. /// Clear the held Python error state (the C++ `what()` message remains intact)
  516. void clear() { restore(); PyErr_Clear(); }
  517. private:
  518. PyObject *type, *value, *trace;
  519. };
  520. /// C++ bindings of builtin Python exceptions
  521. class builtin_exception : public std::runtime_error {
  522. public:
  523. using std::runtime_error::runtime_error;
  524. /// Set the error using the Python C API
  525. virtual void set_error() const = 0;
  526. };
  527. #define PYBIND11_RUNTIME_EXCEPTION(name, type) \
  528. class name : public builtin_exception { public: \
  529. using builtin_exception::builtin_exception; \
  530. name() : name("") { } \
  531. void set_error() const override { PyErr_SetString(type, what()); } \
  532. };
  533. PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
  534. PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
  535. PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
  536. PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
  537. PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
  538. PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
  539. PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
  540. [[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
  541. [[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
  542. template <typename T, typename SFINAE = void> struct format_descriptor { };
  543. NAMESPACE_BEGIN(detail)
  544. // Returns the index of the given type in the type char array below, and in the list in numpy.h
  545. // The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
  546. // complex float,double,long double. Note that the long double types only participate when long
  547. // double is actually longer than double (it isn't under MSVC).
  548. // NB: not only the string below but also complex.h and numpy.h rely on this order.
  549. template <typename T, typename SFINAE = void> struct is_fmt_numeric { static constexpr bool value = false; };
  550. template <typename T> struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
  551. static constexpr bool value = true;
  552. static constexpr int index = std::is_same<T, bool>::value ? 0 : 1 + (
  553. std::is_integral<T>::value ? detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value : 8 + (
  554. std::is_same<T, double>::value ? 1 : std::is_same<T, long double>::value ? 2 : 0));
  555. };
  556. NAMESPACE_END(detail)
  557. template <typename T> struct format_descriptor<T, detail::enable_if_t<detail::is_fmt_numeric<T>::value>> {
  558. static constexpr const char c = "?bBhHiIqQfdgFDG"[detail::is_fmt_numeric<T>::index];
  559. static constexpr const char value[2] = { c, '\0' };
  560. static std::string format() { return std::string(1, c); }
  561. };
  562. template <typename T> constexpr const char format_descriptor<
  563. T, detail::enable_if_t<detail::is_fmt_numeric<T>::value>>::value[2];
  564. NAMESPACE_BEGIN(detail)
  565. template <typename T, typename SFINAE = void> struct compare_buffer_info {
  566. static bool compare(const buffer_info& b) {
  567. return b.format == format_descriptor<T>::format() && b.itemsize == sizeof(T);
  568. }
  569. };
  570. template <typename T> struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> {
  571. static bool compare(const buffer_info& b) {
  572. return b.itemsize == sizeof(T) && (b.format == format_descriptor<T>::value ||
  573. ((sizeof(T) == sizeof(long)) && b.format == (std::is_unsigned<T>::value ? "L" : "l")) ||
  574. ((sizeof(T) == sizeof(size_t)) && b.format == (std::is_unsigned<T>::value ? "N" : "n")));
  575. }
  576. };
  577. NAMESPACE_END(detail)
  578. /// RAII wrapper that temporarily clears any Python error state
  579. struct error_scope {
  580. PyObject *type, *value, *trace;
  581. error_scope() { PyErr_Fetch(&type, &value, &trace); }
  582. ~error_scope() { PyErr_Restore(type, value, trace); }
  583. };
  584. /// Dummy destructor wrapper that can be used to expose classes with a private destructor
  585. struct nodelete { template <typename T> void operator()(T*) { } };
  586. // overload_cast requires variable templates: C++14 or MSVC
  587. #if defined(PYBIND11_CPP14) || defined(_MSC_VER)
  588. #define PYBIND11_OVERLOAD_CAST 1
  589. NAMESPACE_BEGIN(detail)
  590. template <typename... Args>
  591. struct overload_cast_impl {
  592. template <typename Return>
  593. constexpr auto operator()(Return (*pf)(Args...)) const noexcept
  594. -> decltype(pf) { return pf; }
  595. template <typename Return, typename Class>
  596. constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
  597. -> decltype(pmf) { return pmf; }
  598. template <typename Return, typename Class>
  599. constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
  600. -> decltype(pmf) { return pmf; }
  601. };
  602. NAMESPACE_END(detail)
  603. /// Syntax sugar for resolving overloaded function pointers:
  604. /// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
  605. /// - sweet: overload_cast<Arg0, Arg1, Arg2>(&Class::func)
  606. template <typename... Args>
  607. static constexpr detail::overload_cast_impl<Args...> overload_cast = {};
  608. // MSVC 2015 only accepts this particular initialization syntax for this variable template.
  609. /// Const member function selector for overload_cast
  610. /// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
  611. /// - sweet: overload_cast<Arg>(&Class::func, const_)
  612. static constexpr auto const_ = std::true_type{};
  613. #endif // overload_cast
  614. NAMESPACE_END(pybind11)