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