common.h 40 KB

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