/src/pybind11/include/pybind11/pybind11.h
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | pybind11/pybind11.h: Main header file of the C++11 python |
3 | | binding generator library |
4 | | |
5 | | Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> |
6 | | |
7 | | All rights reserved. Use of this source code is governed by a |
8 | | BSD-style license that can be found in the LICENSE file. |
9 | | */ |
10 | | |
11 | | #pragma once |
12 | | #include "detail/class.h" |
13 | | #include "detail/exception_translation.h" |
14 | | #include "detail/init.h" |
15 | | #include "attr.h" |
16 | | #include "gil.h" |
17 | | #include "gil_safe_call_once.h" |
18 | | #include "options.h" |
19 | | #include "typing.h" |
20 | | |
21 | | #include <cstdlib> |
22 | | #include <cstring> |
23 | | #include <memory> |
24 | | #include <new> |
25 | | #include <string> |
26 | | #include <utility> |
27 | | #include <vector> |
28 | | |
29 | | #if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914)) |
30 | | # define PYBIND11_STD_LAUNDER std::launder |
31 | | # define PYBIND11_HAS_STD_LAUNDER 1 |
32 | | #else |
33 | | # define PYBIND11_STD_LAUNDER |
34 | | # define PYBIND11_HAS_STD_LAUNDER 0 |
35 | | #endif |
36 | | #if defined(__GNUG__) && !defined(__clang__) |
37 | | # include <cxxabi.h> |
38 | | #endif |
39 | | |
40 | | PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) |
41 | | |
42 | | /* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning |
43 | | This warning is about ABI compatibility, not code health. |
44 | | It is only actually needed in a couple places, but apparently GCC 7 "generates this warning if |
45 | | and only if the first template instantiation ... involves noexcept" [stackoverflow], therefore |
46 | | it could get triggered from seemingly random places, depending on user code. |
47 | | No other GCC version generates this warning. |
48 | | */ |
49 | | #if defined(__GNUC__) && __GNUC__ == 7 |
50 | | PYBIND11_WARNING_DISABLE_GCC("-Wnoexcept-type") |
51 | | #endif |
52 | | |
53 | | PYBIND11_WARNING_DISABLE_MSVC(4127) |
54 | | |
55 | | PYBIND11_NAMESPACE_BEGIN(detail) |
56 | | |
57 | 0 | inline std::string replace_newlines_and_squash(const char *text) { |
58 | 0 | const char *whitespaces = " \t\n\r\f\v"; |
59 | 0 | std::string result(text); |
60 | 0 | bool previous_is_whitespace = false; |
61 | |
|
62 | 0 | if (result.size() >= 2) { |
63 | | // Do not modify string representations |
64 | 0 | char first_char = result[0]; |
65 | 0 | char last_char = result[result.size() - 1]; |
66 | 0 | if (first_char == last_char && first_char == '\'') { |
67 | 0 | return result; |
68 | 0 | } |
69 | 0 | } |
70 | 0 | result.clear(); |
71 | | |
72 | | // Replace characters in whitespaces array with spaces and squash consecutive spaces |
73 | 0 | while (*text != '\0') { |
74 | 0 | if (std::strchr(whitespaces, *text)) { |
75 | 0 | if (!previous_is_whitespace) { |
76 | 0 | result += ' '; |
77 | 0 | previous_is_whitespace = true; |
78 | 0 | } |
79 | 0 | } else { |
80 | 0 | result += *text; |
81 | 0 | previous_is_whitespace = false; |
82 | 0 | } |
83 | 0 | ++text; |
84 | 0 | } |
85 | | |
86 | | // Strip leading and trailing whitespaces |
87 | 0 | const size_t str_begin = result.find_first_not_of(whitespaces); |
88 | 0 | if (str_begin == std::string::npos) { |
89 | 0 | return ""; |
90 | 0 | } |
91 | | |
92 | 0 | const size_t str_end = result.find_last_not_of(whitespaces); |
93 | 0 | const size_t str_range = str_end - str_begin + 1; |
94 | |
|
95 | 0 | return result.substr(str_begin, str_range); |
96 | 0 | } |
97 | | |
98 | | #if defined(_MSC_VER) |
99 | | # define PYBIND11_COMPAT_STRDUP _strdup |
100 | | #else |
101 | 0 | # define PYBIND11_COMPAT_STRDUP strdup |
102 | | #endif |
103 | | |
104 | | PYBIND11_NAMESPACE_END(detail) |
105 | | |
106 | | /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object |
107 | | class cpp_function : public function { |
108 | | public: |
109 | | cpp_function() = default; |
110 | | // NOLINTNEXTLINE(google-explicit-constructor) |
111 | 0 | cpp_function(std::nullptr_t) {} |
112 | 0 | cpp_function(std::nullptr_t, const is_setter &) {} |
113 | | |
114 | | /// Construct a cpp_function from a vanilla function pointer |
115 | | template <typename Return, typename... Args, typename... Extra> |
116 | | // NOLINTNEXTLINE(google-explicit-constructor) |
117 | | cpp_function(Return (*f)(Args...), const Extra &...extra) { |
118 | | initialize(f, f, extra...); |
119 | | } |
120 | | |
121 | | /// Construct a cpp_function from a lambda function (possibly with internal state) |
122 | | template <typename Func, |
123 | | typename... Extra, |
124 | | typename = detail::enable_if_t<detail::is_lambda<Func>::value>> |
125 | | // NOLINTNEXTLINE(google-explicit-constructor) |
126 | 0 | cpp_function(Func &&f, const Extra &...extra) { |
127 | 0 | initialize( |
128 | 0 | std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...); |
129 | 0 | } |
130 | | |
131 | | /// Construct a cpp_function from a class method (non-const, no ref-qualifier) |
132 | | template <typename Return, typename Class, typename... Arg, typename... Extra> |
133 | | // NOLINTNEXTLINE(google-explicit-constructor) |
134 | | cpp_function(Return (Class::*f)(Arg...), const Extra &...extra) { |
135 | | initialize( |
136 | | [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); }, |
137 | | (Return(*)(Class *, Arg...)) nullptr, |
138 | | extra...); |
139 | | } |
140 | | |
141 | | /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier) |
142 | | /// A copy of the overload for non-const functions without explicit ref-qualifier |
143 | | /// but with an added `&`. |
144 | | template <typename Return, typename Class, typename... Arg, typename... Extra> |
145 | | // NOLINTNEXTLINE(google-explicit-constructor) |
146 | | cpp_function(Return (Class::*f)(Arg...) &, const Extra &...extra) { |
147 | | initialize( |
148 | | [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); }, |
149 | | (Return(*)(Class *, Arg...)) nullptr, |
150 | | extra...); |
151 | | } |
152 | | |
153 | | /// Construct a cpp_function from a class method (const, no ref-qualifier) |
154 | | template <typename Return, typename Class, typename... Arg, typename... Extra> |
155 | | // NOLINTNEXTLINE(google-explicit-constructor) |
156 | | cpp_function(Return (Class::*f)(Arg...) const, const Extra &...extra) { |
157 | | initialize([f](const Class *c, |
158 | | Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); }, |
159 | | (Return(*)(const Class *, Arg...)) nullptr, |
160 | | extra...); |
161 | | } |
162 | | |
163 | | /// Construct a cpp_function from a class method (const, lvalue ref-qualifier) |
164 | | /// A copy of the overload for const functions without explicit ref-qualifier |
165 | | /// but with an added `&`. |
166 | | template <typename Return, typename Class, typename... Arg, typename... Extra> |
167 | | // NOLINTNEXTLINE(google-explicit-constructor) |
168 | | cpp_function(Return (Class::*f)(Arg...) const &, const Extra &...extra) { |
169 | | initialize([f](const Class *c, |
170 | | Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); }, |
171 | | (Return(*)(const Class *, Arg...)) nullptr, |
172 | | extra...); |
173 | | } |
174 | | |
175 | | /// Return the function name |
176 | 0 | object name() const { return attr("__name__"); } |
177 | | |
178 | | protected: |
179 | | struct InitializingFunctionRecordDeleter { |
180 | | // `destruct(function_record, false)`: `initialize_generic` copies strings and |
181 | | // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`. |
182 | 0 | void operator()(detail::function_record *rec) { destruct(rec, false); } |
183 | | }; |
184 | | using unique_function_record |
185 | | = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>; |
186 | | |
187 | | /// Space optimization: don't inline this frequently instantiated fragment |
188 | 0 | PYBIND11_NOINLINE unique_function_record make_function_record() { |
189 | 0 | return unique_function_record(new detail::function_record()); |
190 | 0 | } |
191 | | |
192 | | /// Special internal constructor for functors, lambda functions, etc. |
193 | | template <typename Func, typename Return, typename... Args, typename... Extra> |
194 | 0 | void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) { |
195 | 0 | using namespace detail; |
196 | 0 | struct capture { |
197 | 0 | remove_reference_t<Func> f; |
198 | 0 | }; |
199 | | |
200 | | /* Store the function including any extra state it might have (e.g. a lambda capture |
201 | | * object) */ |
202 | | // The unique_ptr makes sure nothing is leaked in case of an exception. |
203 | 0 | auto unique_rec = make_function_record(); |
204 | 0 | auto *rec = unique_rec.get(); |
205 | | |
206 | | /* Store the capture object directly in the function record if there is enough space */ |
207 | 0 | if (sizeof(capture) <= sizeof(rec->data)) { |
208 | | /* Without these pragmas, GCC warns that there might not be |
209 | | enough space to use the placement new operator. However, the |
210 | | 'if' statement above ensures that this is the case. */ |
211 | 0 | PYBIND11_WARNING_PUSH |
212 | |
|
213 | | #if defined(__GNUG__) && __GNUC__ >= 6 |
214 | | PYBIND11_WARNING_DISABLE_GCC("-Wplacement-new") |
215 | | #endif |
216 | |
|
217 | 0 | new ((capture *) &rec->data) capture{std::forward<Func>(f)}; |
218 | |
|
219 | | #if !PYBIND11_HAS_STD_LAUNDER |
220 | | PYBIND11_WARNING_DISABLE_GCC("-Wstrict-aliasing") |
221 | | #endif |
222 | | |
223 | | // UB without std::launder, but without breaking ABI and/or |
224 | | // a significant refactoring it's "impossible" to solve. |
225 | 0 | if (!std::is_trivially_destructible<capture>::value) { |
226 | 0 | rec->free_data = [](function_record *r) { |
227 | 0 | auto data = PYBIND11_STD_LAUNDER((capture *) &r->data); |
228 | 0 | (void) data; |
229 | 0 | data->~capture(); |
230 | 0 | }; |
231 | 0 | } |
232 | 0 | PYBIND11_WARNING_POP |
233 | 0 | } else { |
234 | 0 | rec->data[0] = new capture{std::forward<Func>(f)}; |
235 | 0 | rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); }; |
236 | 0 | } |
237 | | |
238 | | /* Type casters for the function arguments and return value */ |
239 | 0 | using cast_in = argument_loader<Args...>; |
240 | 0 | using cast_out |
241 | 0 | = make_caster<conditional_t<std::is_void<Return>::value, void_type, Return>>; |
242 | |
|
243 | 0 | static_assert( |
244 | 0 | expected_num_args<Extra...>( |
245 | 0 | sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs), |
246 | 0 | "The number of argument annotations does not match the number of function arguments"); |
247 | | |
248 | | /* Dispatch code which converts function arguments and performs the actual function call */ |
249 | 0 | rec->impl = [](function_call &call) -> handle { |
250 | 0 | cast_in args_converter; |
251 | | |
252 | | /* Try to cast the function arguments into the C++ domain */ |
253 | 0 | if (!args_converter.load_args(call)) { |
254 | 0 | return PYBIND11_TRY_NEXT_OVERLOAD; |
255 | 0 | } |
256 | | |
257 | | /* Invoke call policy pre-call hook */ |
258 | 0 | process_attributes<Extra...>::precall(call); |
259 | | |
260 | | /* Get a pointer to the capture object */ |
261 | 0 | const auto *data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data |
262 | 0 | : call.func.data[0]); |
263 | 0 | auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data)); |
264 | | |
265 | | /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */ |
266 | 0 | return_value_policy policy |
267 | 0 | = return_value_policy_override<Return>::policy(call.func.policy); |
268 | | |
269 | | /* Function scope guard -- defaults to the compile-to-nothing `void_type` */ |
270 | 0 | using Guard = extract_guard_t<Extra...>; |
271 | | |
272 | | /* Perform the function call */ |
273 | 0 | handle result; |
274 | 0 | if (call.func.is_setter) { |
275 | 0 | (void) std::move(args_converter).template call<Return, Guard>(cap->f); |
276 | 0 | result = none().release(); |
277 | 0 | } else { |
278 | 0 | result = cast_out::cast( |
279 | 0 | std::move(args_converter).template call<Return, Guard>(cap->f), |
280 | 0 | policy, |
281 | 0 | call.parent); |
282 | 0 | } |
283 | | |
284 | | /* Invoke call policy post-call hook */ |
285 | 0 | process_attributes<Extra...>::postcall(call, result); |
286 | |
|
287 | 0 | return result; |
288 | 0 | }; |
289 | |
|
290 | 0 | rec->nargs_pos = cast_in::args_pos >= 0 |
291 | 0 | ? static_cast<std::uint16_t>(cast_in::args_pos) |
292 | 0 | : sizeof...(Args) - cast_in::has_kwargs; // Will get reduced more if |
293 | | // we have a kw_only |
294 | 0 | rec->has_args = cast_in::args_pos >= 0; |
295 | 0 | rec->has_kwargs = cast_in::has_kwargs; |
296 | | |
297 | | /* Process any user-provided function attributes */ |
298 | 0 | process_attributes<Extra...>::init(extra..., rec); |
299 | |
|
300 | 0 | { |
301 | 0 | constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value, |
302 | 0 | has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value, |
303 | 0 | has_arg_annotations = any_of<is_keyword<Extra>...>::value; |
304 | 0 | static_assert(has_arg_annotations || !has_kw_only_args, |
305 | 0 | "py::kw_only requires the use of argument annotations"); |
306 | 0 | static_assert(has_arg_annotations || !has_pos_only_args, |
307 | 0 | "py::pos_only requires the use of argument annotations (for docstrings " |
308 | 0 | "and aligning the annotations to the argument)"); |
309 | |
|
310 | 0 | static_assert(constexpr_sum(is_kw_only<Extra>::value...) <= 1, |
311 | 0 | "py::kw_only may be specified only once"); |
312 | 0 | static_assert(constexpr_sum(is_pos_only<Extra>::value...) <= 1, |
313 | 0 | "py::pos_only may be specified only once"); |
314 | 0 | constexpr auto kw_only_pos = constexpr_first<is_kw_only, Extra...>(); |
315 | 0 | constexpr auto pos_only_pos = constexpr_first<is_pos_only, Extra...>(); |
316 | 0 | static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos, |
317 | 0 | "py::pos_only must come before py::kw_only"); |
318 | 0 | } |
319 | | |
320 | | /* Generate a readable signature describing the function's arguments and return |
321 | | value types */ |
322 | 0 | static constexpr auto signature |
323 | 0 | = const_name("(") + cast_in::arg_names + const_name(") -> ") + cast_out::name; |
324 | 0 | PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types(); |
325 | | |
326 | | /* Register the function with Python from generic (non-templated) code */ |
327 | | // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid. |
328 | 0 | initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args)); |
329 | | |
330 | | /* Stash some additional information used by an important optimization in 'functional.h' */ |
331 | 0 | using FunctionType = Return (*)(Args...); |
332 | 0 | constexpr bool is_function_ptr |
333 | 0 | = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *); |
334 | 0 | if (is_function_ptr) { |
335 | 0 | rec->is_stateless = true; |
336 | 0 | rec->data[1] |
337 | 0 | = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType))); |
338 | 0 | } |
339 | 0 | } Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::all_type_info_get_cache(_typeobject*)::{lambda(pybind11::handle)#1}, void, pybind11::handle>(pybind11::detail::all_type_info_get_cache(_typeobject*)::{lambda(pybind11::handle)#1}&&, void (*)(pybind11::handle)) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&)#1}, pybind11::str, pybind11::object const&, pybind11::name, pybind11::is_method>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&)#1}&&, pybind11::str (*)(pybind11::object const&), pybind11::name const&, pybind11::is_method const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::str (*&)(pybind11::handle), pybind11::str, pybind11::handle, pybind11::name, pybind11::is_method>(pybind11::str (*&)(pybind11::handle), pybind11::str (*)(pybind11::handle), pybind11::name const&, pybind11::is_method const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::handle)#1}, pybind11::str, pybind11::handle, pybind11::name, pybind11::is_method>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::handle)#1}&&, pybind11::str (*)(pybind11::handle), pybind11::name const&, pybind11::is_method const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::handle)#2}, std::__1::basic_string<char, pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::handle)#2}::char_traits<char>, pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::handle)#2}::allocator<char> >, pybind11::handle, pybind11::name>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::handle)#2}&&, std::__1::basic_string<char, pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::handle)#2}::char_traits<char>, pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::handle)#2}::allocator<char> > (*)(pybind11::handle), pybind11::name const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::handle)#3}, pybind11::dict, pybind11::handle, pybind11::name>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::handle)#3}&&, pybind11::dict (*)(pybind11::handle), pybind11::name const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#1}, bool, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#1}&&, bool (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#2}, bool, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#2}&&, bool (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#3}, bool, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#3}&&, bool (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#4}, bool, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#4}&&, bool (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#5}, bool, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#5}&&, bool (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#6}, bool, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#6}&&, bool (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#7}, pybind11::object, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#7}&&, pybind11::object (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#8}, pybind11::object, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#8}&&, pybind11::object (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#9}, pybind11::object, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#9}&&, pybind11::object (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#10}, pybind11::object, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#10}&&, pybind11::object (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#11}, pybind11::object, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#11}&&, pybind11::object (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#12}, pybind11::object, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#12}&&, pybind11::object (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&)#2}, pybind11::object, pybind11::object const&, pybind11::name, pybind11::is_method>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&)#2}&&, pybind11::object (*)(pybind11::object const&), pybind11::name const&, pybind11::is_method const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#13}, bool, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#13}&&, bool (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#14}, bool, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#14}&&, bool (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#15}, bool, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#15}&&, bool (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#16}, bool, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#16}&&, bool (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#17}, bool, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#17}&&, bool (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#18}, bool, pybind11::object const&, pybind11::object const&, pybind11::name, pybind11::is_method, pybind11::arg>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&, pybind11::object const&)#18}&&, bool (*)(pybind11::object const&, pybind11::object const&), pybind11::name const&, pybind11::is_method const&, pybind11::arg const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&)#3}, pybind11::int_, pybind11::object const&, pybind11::name, pybind11::is_method>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&)#3}&&, pybind11::int_ (*)(pybind11::object const&), pybind11::name const&, pybind11::is_method const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&)#4}, pybind11::int_, pybind11::object const&, pybind11::name, pybind11::is_method>(pybind11::detail::enum_base::init(bool, bool)::{lambda(pybind11::object const&)#4}&&, pybind11::int_ (*)(pybind11::object const&), pybind11::name const&, pybind11::is_method const&) Unexecuted instantiation: void pybind11::cpp_function::initialize<pybind11::detail::keep_alive_impl(pybind11::handle, pybind11::handle)::{lambda(pybind11::handle)#1}, void, pybind11::handle>(pybind11::detail::keep_alive_impl(pybind11::handle, pybind11::handle)::{lambda(pybind11::handle)#1}&&, void (*)(pybind11::handle)) |
340 | | |
341 | | // Utility class that keeps track of all duplicated strings, and cleans them up in its |
342 | | // destructor, unless they are released. Basically a RAII-solution to deal with exceptions |
343 | | // along the way. |
344 | | class strdup_guard { |
345 | | public: |
346 | 0 | strdup_guard() = default; |
347 | | strdup_guard(const strdup_guard &) = delete; |
348 | | strdup_guard &operator=(const strdup_guard &) = delete; |
349 | | |
350 | 0 | ~strdup_guard() { |
351 | 0 | for (auto *s : strings) { |
352 | 0 | std::free(s); |
353 | 0 | } |
354 | 0 | } |
355 | 0 | char *operator()(const char *s) { |
356 | 0 | auto *t = PYBIND11_COMPAT_STRDUP(s); |
357 | 0 | strings.push_back(t); |
358 | 0 | return t; |
359 | 0 | } |
360 | 0 | void release() { strings.clear(); } |
361 | | |
362 | | private: |
363 | | std::vector<char *> strings; |
364 | | }; |
365 | | |
366 | | /// Register a function call with Python (generic non-templated code goes here) |
367 | | void initialize_generic(unique_function_record &&unique_rec, |
368 | | const char *text, |
369 | | const std::type_info *const *types, |
370 | 0 | size_t args) { |
371 | | // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr, |
372 | | // we do not want this to destruct the pointer. `initialize` (the caller) still relies on |
373 | | // the pointee being alive after this call. Only move out if a `capsule` is going to keep |
374 | | // it alive. |
375 | 0 | auto *rec = unique_rec.get(); |
376 | | |
377 | | // Keep track of strdup'ed strings, and clean them up as long as the function's capsule |
378 | | // has not taken ownership yet (when `unique_rec.release()` is called). |
379 | | // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the |
380 | | // strings are only referenced before strdup'ing. So only *after* the following block could |
381 | | // `destruct` safely be called, but even then, `repr` could still throw in the middle of |
382 | | // copying all strings. |
383 | 0 | strdup_guard guarded_strdup; |
384 | | |
385 | | /* Create copies of all referenced C-style strings */ |
386 | 0 | rec->name = guarded_strdup(rec->name ? rec->name : ""); |
387 | 0 | if (rec->doc) { |
388 | 0 | rec->doc = guarded_strdup(rec->doc); |
389 | 0 | } |
390 | 0 | for (auto &a : rec->args) { |
391 | 0 | if (a.name) { |
392 | 0 | a.name = guarded_strdup(a.name); |
393 | 0 | } |
394 | 0 | if (a.descr) { |
395 | 0 | a.descr = guarded_strdup(a.descr); |
396 | 0 | } else if (a.value) { |
397 | 0 | a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str()); |
398 | 0 | } |
399 | 0 | } |
400 | |
|
401 | 0 | rec->is_constructor = (std::strcmp(rec->name, "__init__") == 0) |
402 | 0 | || (std::strcmp(rec->name, "__setstate__") == 0); |
403 | |
|
404 | 0 | #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING) |
405 | 0 | if (rec->is_constructor && !rec->is_new_style_constructor) { |
406 | 0 | const auto class_name |
407 | 0 | = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr()); |
408 | 0 | const auto func_name = std::string(rec->name); |
409 | 0 | PyErr_WarnEx(PyExc_FutureWarning, |
410 | 0 | ("pybind11-bound class '" + class_name |
411 | 0 | + "' is using an old-style " |
412 | 0 | "placement-new '" |
413 | 0 | + func_name |
414 | 0 | + "' which has been deprecated. See " |
415 | 0 | "the upgrade guide in pybind11's docs. This message is only visible " |
416 | 0 | "when compiled in debug mode.") |
417 | 0 | .c_str(), |
418 | 0 | 0); |
419 | 0 | } |
420 | 0 | #endif |
421 | | |
422 | | /* Generate a proper function signature */ |
423 | 0 | std::string signature; |
424 | 0 | size_t type_index = 0, arg_index = 0; |
425 | 0 | bool is_starred = false; |
426 | 0 | for (const auto *pc = text; *pc != '\0'; ++pc) { |
427 | 0 | const auto c = *pc; |
428 | |
|
429 | 0 | if (c == '{') { |
430 | | // Write arg name for everything except *args and **kwargs. |
431 | 0 | is_starred = *(pc + 1) == '*'; |
432 | 0 | if (is_starred) { |
433 | 0 | continue; |
434 | 0 | } |
435 | | // Separator for keyword-only arguments, placed before the kw |
436 | | // arguments start (unless we are already putting an *args) |
437 | 0 | if (!rec->has_args && arg_index == rec->nargs_pos) { |
438 | 0 | signature += "*, "; |
439 | 0 | } |
440 | 0 | if (arg_index < rec->args.size() && rec->args[arg_index].name) { |
441 | 0 | signature += rec->args[arg_index].name; |
442 | 0 | } else if (arg_index == 0 && rec->is_method) { |
443 | 0 | signature += "self"; |
444 | 0 | } else { |
445 | 0 | signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0)); |
446 | 0 | } |
447 | 0 | signature += ": "; |
448 | 0 | } else if (c == '}') { |
449 | | // Write default value if available. |
450 | 0 | if (!is_starred && arg_index < rec->args.size() && rec->args[arg_index].descr) { |
451 | 0 | signature += " = "; |
452 | 0 | signature += detail::replace_newlines_and_squash(rec->args[arg_index].descr); |
453 | 0 | } |
454 | | // Separator for positional-only arguments (placed after the |
455 | | // argument, rather than before like * |
456 | 0 | if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) { |
457 | 0 | signature += ", /"; |
458 | 0 | } |
459 | 0 | if (!is_starred) { |
460 | 0 | arg_index++; |
461 | 0 | } |
462 | 0 | } else if (c == '%') { |
463 | 0 | const std::type_info *t = types[type_index++]; |
464 | 0 | if (!t) { |
465 | 0 | pybind11_fail("Internal error while parsing type signature (1)"); |
466 | 0 | } |
467 | 0 | if (auto *tinfo = detail::get_type_info(*t)) { |
468 | 0 | handle th((PyObject *) tinfo->type); |
469 | 0 | signature += th.attr("__module__").cast<std::string>() + "." |
470 | 0 | + th.attr("__qualname__").cast<std::string>(); |
471 | 0 | } else if (rec->is_new_style_constructor && arg_index == 0) { |
472 | | // A new-style `__init__` takes `self` as `value_and_holder`. |
473 | | // Rewrite it to the proper class type. |
474 | 0 | signature += rec->scope.attr("__module__").cast<std::string>() + "." |
475 | 0 | + rec->scope.attr("__qualname__").cast<std::string>(); |
476 | 0 | } else { |
477 | 0 | signature += detail::quote_cpp_type_name(detail::clean_type_id(t->name())); |
478 | 0 | } |
479 | 0 | } else { |
480 | 0 | signature += c; |
481 | 0 | } |
482 | 0 | } |
483 | |
|
484 | 0 | if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] != nullptr) { |
485 | 0 | pybind11_fail("Internal error while parsing type signature (2)"); |
486 | 0 | } |
487 | |
|
488 | 0 | rec->signature = guarded_strdup(signature.c_str()); |
489 | 0 | rec->args.shrink_to_fit(); |
490 | 0 | rec->nargs = (std::uint16_t) args; |
491 | |
|
492 | 0 | if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) { |
493 | 0 | rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr()); |
494 | 0 | } |
495 | |
|
496 | 0 | detail::function_record *chain = nullptr, *chain_start = rec; |
497 | 0 | if (rec->sibling) { |
498 | 0 | if (PyCFunction_Check(rec->sibling.ptr())) { |
499 | 0 | auto *self = PyCFunction_GET_SELF(rec->sibling.ptr()); |
500 | 0 | if (!isinstance<capsule>(self)) { |
501 | 0 | chain = nullptr; |
502 | 0 | } else { |
503 | 0 | auto rec_capsule = reinterpret_borrow<capsule>(self); |
504 | 0 | if (detail::is_function_record_capsule(rec_capsule)) { |
505 | 0 | chain = rec_capsule.get_pointer<detail::function_record>(); |
506 | | /* Never append a method to an overload chain of a parent class; |
507 | | instead, hide the parent's overloads in this case */ |
508 | 0 | if (!chain->scope.is(rec->scope)) { |
509 | 0 | chain = nullptr; |
510 | 0 | } |
511 | 0 | } else { |
512 | 0 | chain = nullptr; |
513 | 0 | } |
514 | 0 | } |
515 | 0 | } |
516 | | // Don't trigger for things like the default __init__, which are wrapper_descriptors |
517 | | // that we are intentionally replacing |
518 | 0 | else if (!rec->sibling.is_none() && rec->name[0] != '_') { |
519 | 0 | pybind11_fail("Cannot overload existing non-function object \"" |
520 | 0 | + std::string(rec->name) + "\" with a function of the same name"); |
521 | 0 | } |
522 | 0 | } |
523 | |
|
524 | 0 | if (!chain) { |
525 | | /* No existing overload was found, create a new function object */ |
526 | 0 | rec->def = new PyMethodDef(); |
527 | 0 | std::memset(rec->def, 0, sizeof(PyMethodDef)); |
528 | 0 | rec->def->ml_name = rec->name; |
529 | 0 | rec->def->ml_meth |
530 | 0 | = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher)); |
531 | 0 | rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS; |
532 | |
|
533 | 0 | capsule rec_capsule(unique_rec.release(), |
534 | 0 | detail::get_function_record_capsule_name(), |
535 | 0 | [](void *ptr) { destruct((detail::function_record *) ptr); }); |
536 | 0 | guarded_strdup.release(); |
537 | |
|
538 | 0 | object scope_module; |
539 | 0 | if (rec->scope) { |
540 | 0 | if (hasattr(rec->scope, "__module__")) { |
541 | 0 | scope_module = rec->scope.attr("__module__"); |
542 | 0 | } else if (hasattr(rec->scope, "__name__")) { |
543 | 0 | scope_module = rec->scope.attr("__name__"); |
544 | 0 | } |
545 | 0 | } |
546 | |
|
547 | 0 | m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr()); |
548 | 0 | if (!m_ptr) { |
549 | 0 | pybind11_fail("cpp_function::cpp_function(): Could not allocate function object"); |
550 | 0 | } |
551 | 0 | } else { |
552 | | /* Append at the beginning or end of the overload chain */ |
553 | 0 | m_ptr = rec->sibling.ptr(); |
554 | 0 | inc_ref(); |
555 | 0 | if (chain->is_method != rec->is_method) { |
556 | 0 | pybind11_fail( |
557 | 0 | "overloading a method with both static and instance methods is not supported; " |
558 | | #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES) |
559 | | "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more " |
560 | | "details" |
561 | | #else |
562 | 0 | "error while attempting to bind " |
563 | 0 | + std::string(rec->is_method ? "instance" : "static") + " method " |
564 | 0 | + std::string(pybind11::str(rec->scope.attr("__name__"))) + "." |
565 | 0 | + std::string(rec->name) + signature |
566 | 0 | #endif |
567 | 0 | ); |
568 | 0 | } |
569 | |
|
570 | 0 | if (rec->prepend) { |
571 | | // Beginning of chain; we need to replace the capsule's current head-of-the-chain |
572 | | // pointer with this one, then make this one point to the previous head of the |
573 | | // chain. |
574 | 0 | chain_start = rec; |
575 | 0 | rec->next = chain; |
576 | 0 | auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(m_ptr)); |
577 | 0 | rec_capsule.set_pointer(unique_rec.release()); |
578 | 0 | guarded_strdup.release(); |
579 | 0 | } else { |
580 | | // Or end of chain (normal behavior) |
581 | 0 | chain_start = chain; |
582 | 0 | while (chain->next) { |
583 | 0 | chain = chain->next; |
584 | 0 | } |
585 | 0 | chain->next = unique_rec.release(); |
586 | 0 | guarded_strdup.release(); |
587 | 0 | } |
588 | 0 | } |
589 | |
|
590 | 0 | std::string signatures; |
591 | 0 | int index = 0; |
592 | | /* Create a nice pydoc rec including all signatures and |
593 | | docstrings of the functions in the overload chain */ |
594 | 0 | if (chain && options::show_function_signatures() |
595 | 0 | && std::strcmp(rec->name, "_pybind11_conduit_v1_") != 0) { |
596 | | // First a generic signature |
597 | 0 | signatures += rec->name; |
598 | 0 | signatures += "(*args, **kwargs)\n"; |
599 | 0 | signatures += "Overloaded function.\n\n"; |
600 | 0 | } |
601 | | // Then specific overload signatures |
602 | 0 | bool first_user_def = true; |
603 | 0 | for (auto *it = chain_start; it != nullptr; it = it->next) { |
604 | 0 | if (options::show_function_signatures() |
605 | 0 | && std::strcmp(rec->name, "_pybind11_conduit_v1_") != 0) { |
606 | 0 | if (index > 0) { |
607 | 0 | signatures += '\n'; |
608 | 0 | } |
609 | 0 | if (chain) { |
610 | 0 | signatures += std::to_string(++index) + ". "; |
611 | 0 | } |
612 | 0 | signatures += rec->name; |
613 | 0 | signatures += it->signature; |
614 | 0 | signatures += '\n'; |
615 | 0 | } |
616 | 0 | if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) { |
617 | | // If we're appending another docstring, and aren't printing function signatures, |
618 | | // we need to append a newline first: |
619 | 0 | if (!options::show_function_signatures()) { |
620 | 0 | if (first_user_def) { |
621 | 0 | first_user_def = false; |
622 | 0 | } else { |
623 | 0 | signatures += '\n'; |
624 | 0 | } |
625 | 0 | } |
626 | 0 | if (options::show_function_signatures()) { |
627 | 0 | signatures += '\n'; |
628 | 0 | } |
629 | 0 | signatures += it->doc; |
630 | 0 | if (options::show_function_signatures()) { |
631 | 0 | signatures += '\n'; |
632 | 0 | } |
633 | 0 | } |
634 | 0 | } |
635 | |
|
636 | 0 | auto *func = (PyCFunctionObject *) m_ptr; |
637 | | // Install docstring if it's non-empty (when at least one option is enabled) |
638 | 0 | auto *doc = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str()); |
639 | 0 | std::free(const_cast<char *>(PYBIND11_PYCFUNCTION_GET_DOC(func))); |
640 | 0 | PYBIND11_PYCFUNCTION_SET_DOC(func, doc); |
641 | |
|
642 | 0 | if (rec->is_method) { |
643 | 0 | m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr()); |
644 | 0 | if (!m_ptr) { |
645 | 0 | pybind11_fail( |
646 | 0 | "cpp_function::cpp_function(): Could not allocate instance method object"); |
647 | 0 | } |
648 | 0 | Py_DECREF(func); |
649 | 0 | } |
650 | 0 | } |
651 | | |
652 | | /// When a cpp_function is GCed, release any memory allocated by pybind11 |
653 | 0 | static void destruct(detail::function_record *rec, bool free_strings = true) { |
654 | | // If on Python 3.9, check the interpreter "MICRO" (patch) version. |
655 | | // If this is running on 3.9.0, we have to work around a bug. |
656 | | #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9 |
657 | | static bool is_zero = Py_GetVersion()[4] == '0'; |
658 | | #endif |
659 | |
|
660 | 0 | while (rec) { |
661 | 0 | detail::function_record *next = rec->next; |
662 | 0 | if (rec->free_data) { |
663 | 0 | rec->free_data(rec); |
664 | 0 | } |
665 | | // During initialization, these strings might not have been copied yet, |
666 | | // so they cannot be freed. Once the function has been created, they can. |
667 | | // Check `make_function_record` for more details. |
668 | 0 | if (free_strings) { |
669 | 0 | std::free((char *) rec->name); |
670 | 0 | std::free((char *) rec->doc); |
671 | 0 | std::free((char *) rec->signature); |
672 | 0 | for (auto &arg : rec->args) { |
673 | 0 | std::free(const_cast<char *>(arg.name)); |
674 | 0 | std::free(const_cast<char *>(arg.descr)); |
675 | 0 | } |
676 | 0 | } |
677 | 0 | for (auto &arg : rec->args) { |
678 | 0 | arg.value.dec_ref(); |
679 | 0 | } |
680 | 0 | if (rec->def) { |
681 | 0 | std::free(const_cast<char *>(rec->def->ml_doc)); |
682 | | // Python 3.9.0 decref's these in the wrong order; rec->def |
683 | | // If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix) |
684 | | // See https://github.com/python/cpython/pull/22670 |
685 | | #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9 |
686 | | if (!is_zero) { |
687 | | delete rec->def; |
688 | | } |
689 | | #else |
690 | 0 | delete rec->def; |
691 | 0 | #endif |
692 | 0 | } |
693 | 0 | delete rec; |
694 | 0 | rec = next; |
695 | 0 | } |
696 | 0 | } |
697 | | |
698 | | /// Main dispatch logic for calls to functions bound using pybind11 |
699 | 0 | static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) { |
700 | 0 | using namespace detail; |
701 | 0 | assert(isinstance<capsule>(self)); |
702 | | |
703 | | /* Iterator over the list of potentially admissible overloads */ |
704 | 0 | const function_record *overloads = reinterpret_cast<function_record *>( |
705 | 0 | PyCapsule_GetPointer(self, get_function_record_capsule_name())), |
706 | 0 | *current_overload = overloads; |
707 | 0 | assert(overloads != nullptr); |
708 | | |
709 | | /* Need to know how many arguments + keyword arguments there are to pick the right |
710 | | overload */ |
711 | 0 | const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in); |
712 | | |
713 | 0 | handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr, |
714 | 0 | result = PYBIND11_TRY_NEXT_OVERLOAD; |
715 | | |
716 | 0 | auto self_value_and_holder = value_and_holder(); |
717 | 0 | if (overloads->is_constructor) { |
718 | 0 | if (!parent |
719 | 0 | || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) { |
720 | 0 | set_error(PyExc_TypeError, |
721 | 0 | "__init__(self, ...) called with invalid or missing `self` argument"); |
722 | 0 | return nullptr; |
723 | 0 | } |
724 | | |
725 | 0 | auto *const tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr()); |
726 | 0 | auto *const pi = reinterpret_cast<instance *>(parent.ptr()); |
727 | 0 | self_value_and_holder = pi->get_value_and_holder(tinfo, true); |
728 | | |
729 | | // If this value is already registered it must mean __init__ is invoked multiple times; |
730 | | // we really can't support that in C++, so just ignore the second __init__. |
731 | 0 | if (self_value_and_holder.instance_registered()) { |
732 | 0 | return none().release().ptr(); |
733 | 0 | } |
734 | 0 | } |
735 | | |
736 | 0 | try { |
737 | | // We do this in two passes: in the first pass, we load arguments with `convert=false`; |
738 | | // in the second, we allow conversion (except for arguments with an explicit |
739 | | // py::arg().noconvert()). This lets us prefer calls without conversion, with |
740 | | // conversion as a fallback. |
741 | 0 | std::vector<function_call> second_pass; |
742 | | |
743 | | // However, if there are no overloads, we can just skip the no-convert pass entirely |
744 | 0 | const bool overloaded |
745 | 0 | = current_overload != nullptr && current_overload->next != nullptr; |
746 | |
|
747 | 0 | for (; current_overload != nullptr; current_overload = current_overload->next) { |
748 | | |
749 | | /* For each overload: |
750 | | 1. Copy all positional arguments we were given, also checking to make sure that |
751 | | named positional arguments weren't *also* specified via kwarg. |
752 | | 2. If we weren't given enough, try to make up the omitted ones by checking |
753 | | whether they were provided by a kwarg matching the `py::arg("name")` name. If |
754 | | so, use it (and remove it from kwargs); if not, see if the function binding |
755 | | provided a default that we can use. |
756 | | 3. Ensure that either all keyword arguments were "consumed", or that the |
757 | | function takes a kwargs argument to accept unconsumed kwargs. |
758 | | 4. Any positional arguments still left get put into a tuple (for args), and any |
759 | | leftover kwargs get put into a dict. |
760 | | 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an |
761 | | extra tuple or dict at the end of the positional arguments. |
762 | | 6. Call the function call dispatcher (function_record::impl) |
763 | | |
764 | | If one of these fail, move on to the next overload and keep trying until we get |
765 | | a result other than PYBIND11_TRY_NEXT_OVERLOAD. |
766 | | */ |
767 | |
|
768 | 0 | const function_record &func = *current_overload; |
769 | 0 | size_t num_args = func.nargs; // Number of positional arguments that we need |
770 | 0 | if (func.has_args) { |
771 | 0 | --num_args; // (but don't count py::args |
772 | 0 | } |
773 | 0 | if (func.has_kwargs) { |
774 | 0 | --num_args; // or py::kwargs) |
775 | 0 | } |
776 | 0 | size_t pos_args = func.nargs_pos; |
777 | |
|
778 | 0 | if (!func.has_args && n_args_in > pos_args) { |
779 | 0 | continue; // Too many positional arguments for this overload |
780 | 0 | } |
781 | | |
782 | 0 | if (n_args_in < pos_args && func.args.size() < pos_args) { |
783 | 0 | continue; // Not enough positional arguments given, and not enough defaults to |
784 | | // fill in the blanks |
785 | 0 | } |
786 | | |
787 | 0 | function_call call(func, parent); |
788 | | |
789 | | // Protect std::min with parentheses |
790 | 0 | size_t args_to_copy = (std::min)(pos_args, n_args_in); |
791 | 0 | size_t args_copied = 0; |
792 | | |
793 | | // 0. Inject new-style `self` argument |
794 | 0 | if (func.is_new_style_constructor) { |
795 | | // The `value` may have been preallocated by an old-style `__init__` |
796 | | // if it was a preceding candidate for overload resolution. |
797 | 0 | if (self_value_and_holder) { |
798 | 0 | self_value_and_holder.type->dealloc(self_value_and_holder); |
799 | 0 | } |
800 | |
|
801 | 0 | call.init_self = PyTuple_GET_ITEM(args_in, 0); |
802 | 0 | call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder)); |
803 | 0 | call.args_convert.push_back(false); |
804 | 0 | ++args_copied; |
805 | 0 | } |
806 | | |
807 | | // 1. Copy any position arguments given. |
808 | 0 | bool bad_arg = false; |
809 | 0 | for (; args_copied < args_to_copy; ++args_copied) { |
810 | 0 | const argument_record *arg_rec |
811 | 0 | = args_copied < func.args.size() ? &func.args[args_copied] : nullptr; |
812 | 0 | if (kwargs_in && arg_rec && arg_rec->name |
813 | 0 | && dict_getitemstring(kwargs_in, arg_rec->name)) { |
814 | 0 | bad_arg = true; |
815 | 0 | break; |
816 | 0 | } |
817 | | |
818 | 0 | handle arg(PyTuple_GET_ITEM(args_in, args_copied)); |
819 | 0 | if (arg_rec && !arg_rec->none && arg.is_none()) { |
820 | 0 | bad_arg = true; |
821 | 0 | break; |
822 | 0 | } |
823 | 0 | call.args.push_back(arg); |
824 | 0 | call.args_convert.push_back(arg_rec ? arg_rec->convert : true); |
825 | 0 | } |
826 | 0 | if (bad_arg) { |
827 | 0 | continue; // Maybe it was meant for another overload (issue #688) |
828 | 0 | } |
829 | | |
830 | | // Keep track of how many position args we copied out in case we need to come back |
831 | | // to copy the rest into a py::args argument. |
832 | 0 | size_t positional_args_copied = args_copied; |
833 | | |
834 | | // We'll need to copy this if we steal some kwargs for defaults |
835 | 0 | dict kwargs = reinterpret_borrow<dict>(kwargs_in); |
836 | | |
837 | | // 1.5. Fill in any missing pos_only args from defaults if they exist |
838 | 0 | if (args_copied < func.nargs_pos_only) { |
839 | 0 | for (; args_copied < func.nargs_pos_only; ++args_copied) { |
840 | 0 | const auto &arg_rec = func.args[args_copied]; |
841 | 0 | handle value; |
842 | |
|
843 | 0 | if (arg_rec.value) { |
844 | 0 | value = arg_rec.value; |
845 | 0 | } |
846 | 0 | if (value) { |
847 | 0 | call.args.push_back(value); |
848 | 0 | call.args_convert.push_back(arg_rec.convert); |
849 | 0 | } else { |
850 | 0 | break; |
851 | 0 | } |
852 | 0 | } |
853 | |
|
854 | 0 | if (args_copied < func.nargs_pos_only) { |
855 | 0 | continue; // Not enough defaults to fill the positional arguments |
856 | 0 | } |
857 | 0 | } |
858 | | |
859 | | // 2. Check kwargs and, failing that, defaults that may help complete the list |
860 | 0 | if (args_copied < num_args) { |
861 | 0 | bool copied_kwargs = false; |
862 | |
|
863 | 0 | for (; args_copied < num_args; ++args_copied) { |
864 | 0 | const auto &arg_rec = func.args[args_copied]; |
865 | |
|
866 | 0 | handle value; |
867 | 0 | if (kwargs_in && arg_rec.name) { |
868 | 0 | value = dict_getitemstring(kwargs.ptr(), arg_rec.name); |
869 | 0 | } |
870 | |
|
871 | 0 | if (value) { |
872 | | // Consume a kwargs value |
873 | 0 | if (!copied_kwargs) { |
874 | 0 | kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr())); |
875 | 0 | copied_kwargs = true; |
876 | 0 | } |
877 | 0 | if (PyDict_DelItemString(kwargs.ptr(), arg_rec.name) == -1) { |
878 | 0 | throw error_already_set(); |
879 | 0 | } |
880 | 0 | } else if (arg_rec.value) { |
881 | 0 | value = arg_rec.value; |
882 | 0 | } |
883 | | |
884 | 0 | if (!arg_rec.none && value.is_none()) { |
885 | 0 | break; |
886 | 0 | } |
887 | | |
888 | 0 | if (value) { |
889 | | // If we're at the py::args index then first insert a stub for it to be |
890 | | // replaced later |
891 | 0 | if (func.has_args && call.args.size() == func.nargs_pos) { |
892 | 0 | call.args.push_back(none()); |
893 | 0 | } |
894 | |
|
895 | 0 | call.args.push_back(value); |
896 | 0 | call.args_convert.push_back(arg_rec.convert); |
897 | 0 | } else { |
898 | 0 | break; |
899 | 0 | } |
900 | 0 | } |
901 | | |
902 | 0 | if (args_copied < num_args) { |
903 | 0 | continue; // Not enough arguments, defaults, or kwargs to fill the |
904 | | // positional arguments |
905 | 0 | } |
906 | 0 | } |
907 | | |
908 | | // 3. Check everything was consumed (unless we have a kwargs arg) |
909 | 0 | if (kwargs && !kwargs.empty() && !func.has_kwargs) { |
910 | 0 | continue; // Unconsumed kwargs, but no py::kwargs argument to accept them |
911 | 0 | } |
912 | | |
913 | | // 4a. If we have a py::args argument, create a new tuple with leftovers |
914 | 0 | if (func.has_args) { |
915 | 0 | tuple extra_args; |
916 | 0 | if (args_to_copy == 0) { |
917 | | // We didn't copy out any position arguments from the args_in tuple, so we |
918 | | // can reuse it directly without copying: |
919 | 0 | extra_args = reinterpret_borrow<tuple>(args_in); |
920 | 0 | } else if (positional_args_copied >= n_args_in) { |
921 | 0 | extra_args = tuple(0); |
922 | 0 | } else { |
923 | 0 | size_t args_size = n_args_in - positional_args_copied; |
924 | 0 | extra_args = tuple(args_size); |
925 | 0 | for (size_t i = 0; i < args_size; ++i) { |
926 | 0 | extra_args[i] = PyTuple_GET_ITEM(args_in, positional_args_copied + i); |
927 | 0 | } |
928 | 0 | } |
929 | 0 | if (call.args.size() <= func.nargs_pos) { |
930 | 0 | call.args.push_back(extra_args); |
931 | 0 | } else { |
932 | 0 | call.args[func.nargs_pos] = extra_args; |
933 | 0 | } |
934 | 0 | call.args_convert.push_back(false); |
935 | 0 | call.args_ref = std::move(extra_args); |
936 | 0 | } |
937 | | |
938 | | // 4b. If we have a py::kwargs, pass on any remaining kwargs |
939 | 0 | if (func.has_kwargs) { |
940 | 0 | if (!kwargs.ptr()) { |
941 | 0 | kwargs = dict(); // If we didn't get one, send an empty one |
942 | 0 | } |
943 | 0 | call.args.push_back(kwargs); |
944 | 0 | call.args_convert.push_back(false); |
945 | 0 | call.kwargs_ref = std::move(kwargs); |
946 | 0 | } |
947 | | |
948 | | // 5. Put everything in a vector. Not technically step 5, we've been building it |
949 | | // in `call.args` all along. |
950 | 0 | #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) |
951 | 0 | if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) { |
952 | 0 | pybind11_fail("Internal error: function call dispatcher inserted wrong number " |
953 | 0 | "of arguments!"); |
954 | 0 | } |
955 | 0 | #endif |
956 | |
|
957 | 0 | std::vector<bool> second_pass_convert; |
958 | 0 | if (overloaded) { |
959 | | // We're in the first no-convert pass, so swap out the conversion flags for a |
960 | | // set of all-false flags. If the call fails, we'll swap the flags back in for |
961 | | // the conversion-allowed call below. |
962 | 0 | second_pass_convert.resize(func.nargs, false); |
963 | 0 | call.args_convert.swap(second_pass_convert); |
964 | 0 | } |
965 | | |
966 | | // 6. Call the function. |
967 | 0 | try { |
968 | 0 | loader_life_support guard{}; |
969 | 0 | result = func.impl(call); |
970 | 0 | } catch (reference_cast_error &) { |
971 | 0 | result = PYBIND11_TRY_NEXT_OVERLOAD; |
972 | 0 | } |
973 | |
|
974 | 0 | if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) { |
975 | 0 | break; |
976 | 0 | } |
977 | | |
978 | 0 | if (overloaded) { |
979 | | // The (overloaded) call failed; if the call has at least one argument that |
980 | | // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`) |
981 | | // then add this call to the list of second pass overloads to try. |
982 | 0 | for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) { |
983 | 0 | if (second_pass_convert[i]) { |
984 | | // Found one: swap the converting flags back in and store the call for |
985 | | // the second pass. |
986 | 0 | call.args_convert.swap(second_pass_convert); |
987 | 0 | second_pass.push_back(std::move(call)); |
988 | 0 | break; |
989 | 0 | } |
990 | 0 | } |
991 | 0 | } |
992 | 0 | } |
993 | | |
994 | 0 | if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) { |
995 | | // The no-conversion pass finished without success, try again with conversion |
996 | | // allowed |
997 | 0 | for (auto &call : second_pass) { |
998 | 0 | try { |
999 | 0 | loader_life_support guard{}; |
1000 | 0 | result = call.func.impl(call); |
1001 | 0 | } catch (reference_cast_error &) { |
1002 | 0 | result = PYBIND11_TRY_NEXT_OVERLOAD; |
1003 | 0 | } |
1004 | |
|
1005 | 0 | if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) { |
1006 | | // The error reporting logic below expects 'current_overload' to be valid, |
1007 | | // as it would be if we'd encountered this failure in the first-pass loop. |
1008 | 0 | if (!result) { |
1009 | 0 | current_overload = &call.func; |
1010 | 0 | } |
1011 | 0 | break; |
1012 | 0 | } |
1013 | 0 | } |
1014 | 0 | } |
1015 | 0 | } catch (error_already_set &e) { |
1016 | 0 | e.restore(); |
1017 | 0 | return nullptr; |
1018 | | #ifdef __GLIBCXX__ |
1019 | | } catch (abi::__forced_unwind &) { |
1020 | | throw; |
1021 | | #endif |
1022 | 0 | } catch (...) { |
1023 | 0 | try_translate_exceptions(); |
1024 | 0 | return nullptr; |
1025 | 0 | } |
1026 | | |
1027 | 0 | auto append_note_if_missing_header_is_suspected = [](std::string &msg) { |
1028 | 0 | if (msg.find("std::") != std::string::npos) { |
1029 | 0 | msg += "\n\n" |
1030 | 0 | "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n" |
1031 | 0 | "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n" |
1032 | 0 | "conversions are optional and require extra headers to be included\n" |
1033 | 0 | "when compiling your pybind11 module."; |
1034 | 0 | } |
1035 | 0 | }; |
1036 | |
|
1037 | 0 | if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) { |
1038 | 0 | if (overloads->is_operator) { |
1039 | 0 | return handle(Py_NotImplemented).inc_ref().ptr(); |
1040 | 0 | } |
1041 | | |
1042 | 0 | std::string msg = std::string(overloads->name) + "(): incompatible " |
1043 | 0 | + std::string(overloads->is_constructor ? "constructor" : "function") |
1044 | 0 | + " arguments. The following argument types are supported:\n"; |
1045 | |
|
1046 | 0 | int ctr = 0; |
1047 | 0 | for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) { |
1048 | 0 | msg += " " + std::to_string(++ctr) + ". "; |
1049 | |
|
1050 | 0 | bool wrote_sig = false; |
1051 | 0 | if (overloads->is_constructor) { |
1052 | | // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as |
1053 | | // `Object(arg0, ...)` |
1054 | 0 | std::string sig = it2->signature; |
1055 | 0 | size_t start = sig.find('(') + 7; // skip "(self: " |
1056 | 0 | if (start < sig.size()) { |
1057 | | // End at the , for the next argument |
1058 | 0 | size_t end = sig.find(", "), next = end + 2; |
1059 | 0 | size_t ret = sig.rfind(" -> "); |
1060 | | // Or the ), if there is no comma: |
1061 | 0 | if (end >= sig.size()) { |
1062 | 0 | next = end = sig.find(')'); |
1063 | 0 | } |
1064 | 0 | if (start < end && next < sig.size()) { |
1065 | 0 | msg.append(sig, start, end - start); |
1066 | 0 | msg += '('; |
1067 | 0 | msg.append(sig, next, ret - next); |
1068 | 0 | wrote_sig = true; |
1069 | 0 | } |
1070 | 0 | } |
1071 | 0 | } |
1072 | 0 | if (!wrote_sig) { |
1073 | 0 | msg += it2->signature; |
1074 | 0 | } |
1075 | |
|
1076 | 0 | msg += '\n'; |
1077 | 0 | } |
1078 | 0 | msg += "\nInvoked with: "; |
1079 | 0 | auto args_ = reinterpret_borrow<tuple>(args_in); |
1080 | 0 | bool some_args = false; |
1081 | 0 | for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) { |
1082 | 0 | if (!some_args) { |
1083 | 0 | some_args = true; |
1084 | 0 | } else { |
1085 | 0 | msg += ", "; |
1086 | 0 | } |
1087 | 0 | try { |
1088 | 0 | msg += pybind11::repr(args_[ti]); |
1089 | 0 | } catch (const error_already_set &) { |
1090 | 0 | msg += "<repr raised Error>"; |
1091 | 0 | } |
1092 | 0 | } |
1093 | 0 | if (kwargs_in) { |
1094 | 0 | auto kwargs = reinterpret_borrow<dict>(kwargs_in); |
1095 | 0 | if (!kwargs.empty()) { |
1096 | 0 | if (some_args) { |
1097 | 0 | msg += "; "; |
1098 | 0 | } |
1099 | 0 | msg += "kwargs: "; |
1100 | 0 | bool first = true; |
1101 | 0 | for (const auto &kwarg : kwargs) { |
1102 | 0 | if (first) { |
1103 | 0 | first = false; |
1104 | 0 | } else { |
1105 | 0 | msg += ", "; |
1106 | 0 | } |
1107 | 0 | msg += pybind11::str("{}=").format(kwarg.first); |
1108 | 0 | try { |
1109 | 0 | msg += pybind11::repr(kwarg.second); |
1110 | 0 | } catch (const error_already_set &) { |
1111 | 0 | msg += "<repr raised Error>"; |
1112 | 0 | } |
1113 | 0 | } |
1114 | 0 | } |
1115 | 0 | } |
1116 | |
|
1117 | 0 | append_note_if_missing_header_is_suspected(msg); |
1118 | | // Attach additional error info to the exception if supported |
1119 | 0 | if (PyErr_Occurred()) { |
1120 | | // #HelpAppreciated: unit test coverage for this branch. |
1121 | 0 | raise_from(PyExc_TypeError, msg.c_str()); |
1122 | 0 | return nullptr; |
1123 | 0 | } |
1124 | 0 | set_error(PyExc_TypeError, msg.c_str()); |
1125 | 0 | return nullptr; |
1126 | 0 | } |
1127 | 0 | if (!result) { |
1128 | 0 | std::string msg = "Unable to convert function return value to a " |
1129 | 0 | "Python type! The signature was\n\t"; |
1130 | 0 | assert(current_overload != nullptr); |
1131 | 0 | msg += current_overload->signature; |
1132 | 0 | append_note_if_missing_header_is_suspected(msg); |
1133 | | // Attach additional error info to the exception if supported |
1134 | 0 | if (PyErr_Occurred()) { |
1135 | 0 | raise_from(PyExc_TypeError, msg.c_str()); |
1136 | 0 | return nullptr; |
1137 | 0 | } |
1138 | 0 | set_error(PyExc_TypeError, msg.c_str()); |
1139 | 0 | return nullptr; |
1140 | 0 | } |
1141 | 0 | if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) { |
1142 | 0 | auto *pi = reinterpret_cast<instance *>(parent.ptr()); |
1143 | 0 | self_value_and_holder.type->init_instance(pi, nullptr); |
1144 | 0 | } |
1145 | 0 | return result.ptr(); |
1146 | 0 | } |
1147 | | }; |
1148 | | |
1149 | | PYBIND11_NAMESPACE_BEGIN(detail) |
1150 | | |
1151 | | template <> |
1152 | | struct handle_type_name<cpp_function> { |
1153 | | static constexpr auto name = const_name("Callable"); |
1154 | | }; |
1155 | | |
1156 | | PYBIND11_NAMESPACE_END(detail) |
1157 | | |
1158 | | // Use to activate Py_MOD_GIL_NOT_USED. |
1159 | | class mod_gil_not_used { |
1160 | | public: |
1161 | 0 | explicit mod_gil_not_used(bool flag = true) : flag_(flag) {} |
1162 | 0 | bool flag() const { return flag_; } |
1163 | | |
1164 | | private: |
1165 | | bool flag_; |
1166 | | }; |
1167 | | |
1168 | | /// Wrapper for Python extension modules |
1169 | | class module_ : public object { |
1170 | | public: |
1171 | | PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check) |
1172 | | |
1173 | | /// Create a new top-level Python module with the given name and docstring |
1174 | | PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead") |
1175 | 0 | explicit module_(const char *name, const char *doc = nullptr) { |
1176 | 0 | *this = create_extension_module(name, doc, new PyModuleDef()); |
1177 | 0 | } |
1178 | | |
1179 | | /** \rst |
1180 | | Create Python binding for a new function within the module scope. ``Func`` |
1181 | | can be a plain C++ function, a function pointer, or a lambda function. For |
1182 | | details on the ``Extra&& ... extra`` argument, see section :ref:`extras`. |
1183 | | \endrst */ |
1184 | | template <typename Func, typename... Extra> |
1185 | | module_ &def(const char *name_, Func &&f, const Extra &...extra) { |
1186 | | cpp_function func(std::forward<Func>(f), |
1187 | | name(name_), |
1188 | | scope(*this), |
1189 | | sibling(getattr(*this, name_, none())), |
1190 | | extra...); |
1191 | | // NB: allow overwriting here because cpp_function sets up a chain with the intention of |
1192 | | // overwriting (and has already checked internally that it isn't overwriting |
1193 | | // non-functions). |
1194 | | add_object(name_, func, true /* overwrite */); |
1195 | | return *this; |
1196 | | } |
1197 | | |
1198 | | /** \rst |
1199 | | Create and return a new Python submodule with the given name and docstring. |
1200 | | This also works recursively, i.e. |
1201 | | |
1202 | | .. code-block:: cpp |
1203 | | |
1204 | | py::module_ m("example", "pybind11 example plugin"); |
1205 | | py::module_ m2 = m.def_submodule("sub", "A submodule of 'example'"); |
1206 | | py::module_ m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'"); |
1207 | | \endrst */ |
1208 | 0 | module_ def_submodule(const char *name, const char *doc = nullptr) { |
1209 | 0 | const char *this_name = PyModule_GetName(m_ptr); |
1210 | 0 | if (this_name == nullptr) { |
1211 | 0 | throw error_already_set(); |
1212 | 0 | } |
1213 | 0 | std::string full_name = std::string(this_name) + '.' + name; |
1214 | 0 | handle submodule = PyImport_AddModule(full_name.c_str()); |
1215 | 0 | if (!submodule) { |
1216 | 0 | throw error_already_set(); |
1217 | 0 | } |
1218 | 0 | auto result = reinterpret_borrow<module_>(submodule); |
1219 | 0 | if (doc && options::show_user_defined_docstrings()) { |
1220 | 0 | result.attr("__doc__") = pybind11::str(doc); |
1221 | 0 | } |
1222 | 0 | attr(name) = result; |
1223 | 0 | return result; |
1224 | 0 | } |
1225 | | |
1226 | | /// Import and return a module or throws `error_already_set`. |
1227 | 3.84k | static module_ import(const char *name) { |
1228 | 3.84k | PyObject *obj = PyImport_ImportModule(name); |
1229 | 3.84k | if (!obj) { |
1230 | 0 | throw error_already_set(); |
1231 | 0 | } |
1232 | 3.84k | return reinterpret_steal<module_>(obj); |
1233 | 3.84k | } |
1234 | | |
1235 | | /// Reload the module or throws `error_already_set`. |
1236 | 0 | void reload() { |
1237 | 0 | PyObject *obj = PyImport_ReloadModule(ptr()); |
1238 | 0 | if (!obj) { |
1239 | 0 | throw error_already_set(); |
1240 | 0 | } |
1241 | 0 | *this = reinterpret_steal<module_>(obj); |
1242 | 0 | } |
1243 | | |
1244 | | /** \rst |
1245 | | Adds an object to the module using the given name. Throws if an object with the given name |
1246 | | already exists. |
1247 | | |
1248 | | ``overwrite`` should almost always be false: attempting to overwrite objects that pybind11 |
1249 | | has established will, in most cases, break things. |
1250 | | \endrst */ |
1251 | 0 | PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) { |
1252 | 0 | if (!overwrite && hasattr(*this, name)) { |
1253 | 0 | pybind11_fail( |
1254 | 0 | "Error during initialization: multiple incompatible definitions with name \"" |
1255 | 0 | + std::string(name) + "\""); |
1256 | 0 | } |
1257 | 0 |
|
1258 | 0 | PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */); |
1259 | 0 | } |
1260 | | |
1261 | | using module_def = PyModuleDef; // TODO: Can this be removed (it was needed only for Python 2)? |
1262 | | |
1263 | | /** \rst |
1264 | | Create a new top-level module that can be used as the main module of a C extension. |
1265 | | |
1266 | | ``def`` should point to a statically allocated module_def. |
1267 | | \endrst */ |
1268 | | static module_ create_extension_module(const char *name, |
1269 | | const char *doc, |
1270 | | module_def *def, |
1271 | | mod_gil_not_used gil_not_used |
1272 | 0 | = mod_gil_not_used(false)) { |
1273 | 0 | // module_def is PyModuleDef |
1274 | 0 | // Placement new (not an allocation). |
1275 | 0 | def = new (def) |
1276 | 0 | PyModuleDef{/* m_base */ PyModuleDef_HEAD_INIT, |
1277 | 0 | /* m_name */ name, |
1278 | 0 | /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr, |
1279 | 0 | /* m_size */ -1, |
1280 | 0 | /* m_methods */ nullptr, |
1281 | 0 | /* m_slots */ nullptr, |
1282 | 0 | /* m_traverse */ nullptr, |
1283 | 0 | /* m_clear */ nullptr, |
1284 | 0 | /* m_free */ nullptr}; |
1285 | 0 | auto *m = PyModule_Create(def); |
1286 | 0 | if (m == nullptr) { |
1287 | 0 | if (PyErr_Occurred()) { |
1288 | 0 | throw error_already_set(); |
1289 | 0 | } |
1290 | 0 | pybind11_fail("Internal error in module_::create_extension_module()"); |
1291 | 0 | } |
1292 | 0 | if (gil_not_used.flag()) { |
1293 | 0 | #ifdef Py_GIL_DISABLED |
1294 | 0 | PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED); |
1295 | 0 | #endif |
1296 | 0 | } |
1297 | 0 | // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when |
1298 | 0 | // returned from PyInit_... |
1299 | 0 | // For Python 2, reinterpret_borrow was correct. |
1300 | 0 | return reinterpret_borrow<module_>(m); |
1301 | 0 | } |
1302 | | }; |
1303 | | |
1304 | | PYBIND11_NAMESPACE_BEGIN(detail) |
1305 | | |
1306 | | template <> |
1307 | | struct handle_type_name<module_> { |
1308 | | static constexpr auto name = const_name("module"); |
1309 | | }; |
1310 | | |
1311 | | PYBIND11_NAMESPACE_END(detail) |
1312 | | |
1313 | | // When inside a namespace (or anywhere as long as it's not the first item on a line), |
1314 | | // C++20 allows "module" to be used. This is provided for backward compatibility, and for |
1315 | | // simplicity, if someone wants to use py::module for example, that is perfectly safe. |
1316 | | using module = module_; |
1317 | | |
1318 | | /// \ingroup python_builtins |
1319 | | /// Return a dictionary representing the global variables in the current execution frame, |
1320 | | /// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded). |
1321 | 1.29k | inline dict globals() { |
1322 | | #if PY_VERSION_HEX >= 0x030d0000 |
1323 | | PyObject *p = PyEval_GetFrameGlobals(); |
1324 | | return p ? reinterpret_steal<dict>(p) |
1325 | | : reinterpret_borrow<dict>(module_::import("__main__").attr("__dict__").ptr()); |
1326 | | #else |
1327 | 1.29k | PyObject *p = PyEval_GetGlobals(); |
1328 | 1.29k | return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr()); |
1329 | 1.29k | #endif |
1330 | 1.29k | } |
1331 | | |
1332 | | template <typename... Args, typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>> |
1333 | | PYBIND11_DEPRECATED("make_simple_namespace should be replaced with " |
1334 | | "py::module_::import(\"types\").attr(\"SimpleNamespace\") ") |
1335 | | object make_simple_namespace(Args &&...args_) { |
1336 | | return module_::import("types").attr("SimpleNamespace")(std::forward<Args>(args_)...); |
1337 | | } |
1338 | | |
1339 | | PYBIND11_NAMESPACE_BEGIN(detail) |
1340 | | /// Generic support for creating new Python heap types |
1341 | | class generic_type : public object { |
1342 | | public: |
1343 | | PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check) |
1344 | | protected: |
1345 | 0 | void initialize(const type_record &rec) { |
1346 | 0 | if (rec.scope && hasattr(rec.scope, "__dict__") |
1347 | 0 | && rec.scope.attr("__dict__").contains(rec.name)) { |
1348 | 0 | pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) |
1349 | 0 | + "\": an object with that name is already defined"); |
1350 | 0 | } |
1351 | 0 |
|
1352 | 0 | if ((rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type)) |
1353 | 0 | != nullptr) { |
1354 | 0 | pybind11_fail("generic_type: type \"" + std::string(rec.name) |
1355 | 0 | + "\" is already registered!"); |
1356 | 0 | } |
1357 | 0 |
|
1358 | 0 | m_ptr = make_new_python_type(rec); |
1359 | 0 |
|
1360 | 0 | /* Register supplemental type information in C++ dict */ |
1361 | 0 | auto *tinfo = new detail::type_info(); |
1362 | 0 | tinfo->type = (PyTypeObject *) m_ptr; |
1363 | 0 | tinfo->cpptype = rec.type; |
1364 | 0 | tinfo->type_size = rec.type_size; |
1365 | 0 | tinfo->type_align = rec.type_align; |
1366 | 0 | tinfo->operator_new = rec.operator_new; |
1367 | 0 | tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size); |
1368 | 0 | tinfo->init_instance = rec.init_instance; |
1369 | 0 | tinfo->dealloc = rec.dealloc; |
1370 | 0 | tinfo->simple_type = true; |
1371 | 0 | tinfo->simple_ancestors = true; |
1372 | 0 | tinfo->default_holder = rec.default_holder; |
1373 | 0 | tinfo->module_local = rec.module_local; |
1374 | 0 |
|
1375 | 0 | with_internals([&](internals &internals) { |
1376 | 0 | auto tindex = std::type_index(*rec.type); |
1377 | 0 | tinfo->direct_conversions = &internals.direct_conversions[tindex]; |
1378 | 0 | if (rec.module_local) { |
1379 | 0 | get_local_internals().registered_types_cpp[tindex] = tinfo; |
1380 | 0 | } else { |
1381 | 0 | internals.registered_types_cpp[tindex] = tinfo; |
1382 | 0 | } |
1383 | 0 |
|
1384 | 0 | PYBIND11_WARNING_PUSH |
1385 | 0 | #if defined(__GNUC__) && __GNUC__ == 12 |
1386 | 0 | // When using GCC 12 these warnings are disabled as they trigger |
1387 | 0 | // false positive warnings. Discussed here: |
1388 | 0 | // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115824. |
1389 | 0 | PYBIND11_WARNING_DISABLE_GCC("-Warray-bounds") |
1390 | 0 | PYBIND11_WARNING_DISABLE_GCC("-Wstringop-overread") |
1391 | 0 | #endif |
1392 | 0 | internals.registered_types_py[(PyTypeObject *) m_ptr] = {tinfo}; |
1393 | 0 | PYBIND11_WARNING_POP |
1394 | 0 | }); |
1395 | 0 |
|
1396 | 0 | if (rec.bases.size() > 1 || rec.multiple_inheritance) { |
1397 | 0 | mark_parents_nonsimple(tinfo->type); |
1398 | 0 | tinfo->simple_ancestors = false; |
1399 | 0 | } else if (rec.bases.size() == 1) { |
1400 | 0 | auto *parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr()); |
1401 | 0 | assert(parent_tinfo != nullptr); |
1402 | 0 | bool parent_simple_ancestors = parent_tinfo->simple_ancestors; |
1403 | 0 | tinfo->simple_ancestors = parent_simple_ancestors; |
1404 | 0 | // The parent can no longer be a simple type if it has MI and has a child |
1405 | 0 | parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors; |
1406 | 0 | } |
1407 | 0 |
|
1408 | 0 | if (rec.module_local) { |
1409 | 0 | // Stash the local typeinfo and loader so that external modules can access it. |
1410 | 0 | tinfo->module_local_load = &type_caster_generic::local_load; |
1411 | 0 | setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo)); |
1412 | 0 | } |
1413 | 0 | } |
1414 | | |
1415 | | /// Helper function which tags all parents of a type using mult. inheritance |
1416 | 0 | void mark_parents_nonsimple(PyTypeObject *value) { |
1417 | 0 | auto t = reinterpret_borrow<tuple>(value->tp_bases); |
1418 | 0 | for (handle h : t) { |
1419 | 0 | auto *tinfo2 = get_type_info((PyTypeObject *) h.ptr()); |
1420 | 0 | if (tinfo2) { |
1421 | 0 | tinfo2->simple_type = false; |
1422 | 0 | } |
1423 | 0 | mark_parents_nonsimple((PyTypeObject *) h.ptr()); |
1424 | 0 | } |
1425 | 0 | } |
1426 | | |
1427 | | void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *), |
1428 | 0 | void *get_buffer_data) { |
1429 | 0 | auto *type = (PyHeapTypeObject *) m_ptr; |
1430 | 0 | auto *tinfo = detail::get_type_info(&type->ht_type); |
1431 | 0 |
|
1432 | 0 | if (!type->ht_type.tp_as_buffer) { |
1433 | 0 | pybind11_fail("To be able to register buffer protocol support for the type '" |
1434 | 0 | + get_fully_qualified_tp_name(tinfo->type) |
1435 | 0 | + "' the associated class<>(..) invocation must " |
1436 | 0 | "include the pybind11::buffer_protocol() annotation!"); |
1437 | 0 | } |
1438 | 0 |
|
1439 | 0 | tinfo->get_buffer = get_buffer; |
1440 | 0 | tinfo->get_buffer_data = get_buffer_data; |
1441 | 0 | } |
1442 | | |
1443 | | // rec_func must be set for either fget or fset. |
1444 | | void def_property_static_impl(const char *name, |
1445 | | handle fget, |
1446 | | handle fset, |
1447 | 0 | detail::function_record *rec_func) { |
1448 | 0 | const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope); |
1449 | 0 | const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr) |
1450 | 0 | && pybind11::options::show_user_defined_docstrings(); |
1451 | 0 | auto property = handle( |
1452 | 0 | (PyObject *) (is_static ? get_internals().static_property_type : &PyProperty_Type)); |
1453 | 0 | attr(name) = property(fget.ptr() ? fget : none(), |
1454 | 0 | fset.ptr() ? fset : none(), |
1455 | 0 | /*deleter*/ none(), |
1456 | 0 | pybind11::str(has_doc ? rec_func->doc : "")); |
1457 | 0 | } |
1458 | | }; |
1459 | | |
1460 | | /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded. |
1461 | | template <typename T, |
1462 | | typename = void_t<decltype(static_cast<void *(*) (size_t)>(T::operator new))>> |
1463 | | void set_operator_new(type_record *r) { |
1464 | | r->operator_new = &T::operator new; |
1465 | | } |
1466 | | |
1467 | | template <typename> |
1468 | | void set_operator_new(...) {} |
1469 | | |
1470 | | template <typename T, typename SFINAE = void> |
1471 | | struct has_operator_delete : std::false_type {}; |
1472 | | template <typename T> |
1473 | | struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>> |
1474 | | : std::true_type {}; |
1475 | | template <typename T, typename SFINAE = void> |
1476 | | struct has_operator_delete_size : std::false_type {}; |
1477 | | template <typename T> |
1478 | | struct has_operator_delete_size< |
1479 | | T, |
1480 | | void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type { |
1481 | | }; |
1482 | | /// Call class-specific delete if it exists or global otherwise. Can also be an overload set. |
1483 | | template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0> |
1484 | | void call_operator_delete(T *p, size_t, size_t) { |
1485 | | T::operator delete(p); |
1486 | | } |
1487 | | template <typename T, |
1488 | | enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> |
1489 | | = 0> |
1490 | | void call_operator_delete(T *p, size_t s, size_t) { |
1491 | | T::operator delete(p, s); |
1492 | | } |
1493 | | |
1494 | 0 | inline void call_operator_delete(void *p, size_t s, size_t a) { |
1495 | 0 | (void) s; |
1496 | 0 | (void) a; |
1497 | 0 | #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912) |
1498 | 0 | if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) { |
1499 | 0 | # ifdef __cpp_sized_deallocation |
1500 | 0 | ::operator delete(p, s, std::align_val_t(a)); |
1501 | 0 | # else |
1502 | 0 | ::operator delete(p, std::align_val_t(a)); |
1503 | 0 | # endif |
1504 | 0 | return; |
1505 | 0 | } |
1506 | 0 | #endif |
1507 | 0 | #ifdef __cpp_sized_deallocation |
1508 | 0 | ::operator delete(p, s); |
1509 | 0 | #else |
1510 | 0 | ::operator delete(p); |
1511 | 0 | #endif |
1512 | 0 | } |
1513 | | |
1514 | 0 | inline void add_class_method(object &cls, const char *name_, const cpp_function &cf) { |
1515 | 0 | cls.attr(cf.name()) = cf; |
1516 | 0 | if (std::strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) { |
1517 | 0 | cls.attr("__hash__") = none(); |
1518 | 0 | } |
1519 | 0 | } |
1520 | | |
1521 | | PYBIND11_NAMESPACE_END(detail) |
1522 | | |
1523 | | /// Given a pointer to a member function, cast it to its `Derived` version. |
1524 | | /// Forward everything else unchanged. |
1525 | | template <typename /*Derived*/, typename F> |
1526 | | auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) { |
1527 | | return std::forward<F>(f); |
1528 | | } |
1529 | | |
1530 | | template <typename Derived, typename Return, typename Class, typename... Args> |
1531 | | auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) { |
1532 | | static_assert( |
1533 | | detail::is_accessible_base_of<Class, Derived>::value, |
1534 | | "Cannot bind an inaccessible base class method; use a lambda definition instead"); |
1535 | | return pmf; |
1536 | | } |
1537 | | |
1538 | | template <typename Derived, typename Return, typename Class, typename... Args> |
1539 | | auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const { |
1540 | | static_assert( |
1541 | | detail::is_accessible_base_of<Class, Derived>::value, |
1542 | | "Cannot bind an inaccessible base class method; use a lambda definition instead"); |
1543 | | return pmf; |
1544 | | } |
1545 | | |
1546 | | template <typename type_, typename... options> |
1547 | | class class_ : public detail::generic_type { |
1548 | | template <typename T> |
1549 | | using is_holder = detail::is_holder_type<type_, T>; |
1550 | | template <typename T> |
1551 | | using is_subtype = detail::is_strict_base_of<type_, T>; |
1552 | | template <typename T> |
1553 | | using is_base = detail::is_strict_base_of<T, type_>; |
1554 | | // struct instead of using here to help MSVC: |
1555 | | template <typename T> |
1556 | | struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {}; |
1557 | | |
1558 | | public: |
1559 | | using type = type_; |
1560 | | using type_alias = detail::exactly_one_t<is_subtype, void, options...>; |
1561 | | constexpr static bool has_alias = !std::is_void<type_alias>::value; |
1562 | | using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>; |
1563 | | |
1564 | | static_assert(detail::all_of<is_valid_class_option<options>...>::value, |
1565 | | "Unknown/invalid class_ template parameters provided"); |
1566 | | |
1567 | | static_assert(!has_alias || std::is_polymorphic<type>::value, |
1568 | | "Cannot use an alias class with a non-polymorphic type"); |
1569 | | |
1570 | | PYBIND11_OBJECT(class_, generic_type, PyType_Check) |
1571 | | |
1572 | | template <typename... Extra> |
1573 | | class_(handle scope, const char *name, const Extra &...extra) { |
1574 | | using namespace detail; |
1575 | | |
1576 | | // MI can only be specified via class_ template options, not constructor parameters |
1577 | | static_assert( |
1578 | | none_of<is_pyobject<Extra>...>::value || // no base class arguments, or: |
1579 | | (constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base |
1580 | | constexpr_sum(is_base<options>::value...) == 0 && // no template option bases |
1581 | | // no multiple_inheritance attr |
1582 | | none_of<std::is_same<multiple_inheritance, Extra>...>::value), |
1583 | | "Error: multiple inheritance bases must be specified via class_ template options"); |
1584 | | |
1585 | | type_record record; |
1586 | | record.scope = scope; |
1587 | | record.name = name; |
1588 | | record.type = &typeid(type); |
1589 | | record.type_size = sizeof(conditional_t<has_alias, type_alias, type>); |
1590 | | record.type_align = alignof(conditional_t<has_alias, type_alias, type> &); |
1591 | | record.holder_size = sizeof(holder_type); |
1592 | | record.init_instance = init_instance; |
1593 | | record.dealloc = dealloc; |
1594 | | record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value; |
1595 | | |
1596 | | set_operator_new<type>(&record); |
1597 | | |
1598 | | /* Register base classes specified via template arguments to class_, if any */ |
1599 | | PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record)); |
1600 | | |
1601 | | /* Process optional arguments, if any */ |
1602 | | process_attributes<Extra...>::init(extra..., &record); |
1603 | | |
1604 | | generic_type::initialize(record); |
1605 | | |
1606 | | if (has_alias) { |
1607 | | with_internals([&](internals &internals) { |
1608 | | auto &instances = record.module_local ? get_local_internals().registered_types_cpp |
1609 | | : internals.registered_types_cpp; |
1610 | | instances[std::type_index(typeid(type_alias))] |
1611 | | = instances[std::type_index(typeid(type))]; |
1612 | | }); |
1613 | | } |
1614 | | def("_pybind11_conduit_v1_", cpp_conduit_method); |
1615 | | } |
1616 | | |
1617 | | template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0> |
1618 | | static void add_base(detail::type_record &rec) { |
1619 | | rec.add_base(typeid(Base), [](void *src) -> void * { |
1620 | | return static_cast<Base *>(reinterpret_cast<type *>(src)); |
1621 | | }); |
1622 | | } |
1623 | | |
1624 | | template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0> |
1625 | | static void add_base(detail::type_record &) {} |
1626 | | |
1627 | | template <typename Func, typename... Extra> |
1628 | | class_ &def(const char *name_, Func &&f, const Extra &...extra) { |
1629 | | cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), |
1630 | | name(name_), |
1631 | | is_method(*this), |
1632 | | sibling(getattr(*this, name_, none())), |
1633 | | extra...); |
1634 | | add_class_method(*this, name_, cf); |
1635 | | return *this; |
1636 | | } |
1637 | | |
1638 | | template <typename Func, typename... Extra> |
1639 | | class_ &def_static(const char *name_, Func &&f, const Extra &...extra) { |
1640 | | static_assert(!std::is_member_function_pointer<Func>::value, |
1641 | | "def_static(...) called with a non-static member function pointer"); |
1642 | | cpp_function cf(std::forward<Func>(f), |
1643 | | name(name_), |
1644 | | scope(*this), |
1645 | | sibling(getattr(*this, name_, none())), |
1646 | | extra...); |
1647 | | auto cf_name = cf.name(); |
1648 | | attr(std::move(cf_name)) = staticmethod(std::move(cf)); |
1649 | | return *this; |
1650 | | } |
1651 | | |
1652 | | template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0> |
1653 | | class_ &def(const T &op, const Extra &...extra) { |
1654 | | op.execute(*this, extra...); |
1655 | | return *this; |
1656 | | } |
1657 | | |
1658 | | template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0> |
1659 | | class_ &def_cast(const T &op, const Extra &...extra) { |
1660 | | op.execute_cast(*this, extra...); |
1661 | | return *this; |
1662 | | } |
1663 | | |
1664 | | template <typename... Args, typename... Extra> |
1665 | | class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra &...extra) { |
1666 | | PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init); |
1667 | | init.execute(*this, extra...); |
1668 | | return *this; |
1669 | | } |
1670 | | |
1671 | | template <typename... Args, typename... Extra> |
1672 | | class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra &...extra) { |
1673 | | PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init); |
1674 | | init.execute(*this, extra...); |
1675 | | return *this; |
1676 | | } |
1677 | | |
1678 | | template <typename... Args, typename... Extra> |
1679 | | class_ &def(detail::initimpl::factory<Args...> &&init, const Extra &...extra) { |
1680 | | std::move(init).execute(*this, extra...); |
1681 | | return *this; |
1682 | | } |
1683 | | |
1684 | | template <typename... Args, typename... Extra> |
1685 | | class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) { |
1686 | | std::move(pf).execute(*this, extra...); |
1687 | | return *this; |
1688 | | } |
1689 | | |
1690 | | template <typename Func> |
1691 | | class_ &def_buffer(Func &&func) { |
1692 | | struct capture { |
1693 | | Func func; |
1694 | | }; |
1695 | | auto *ptr = new capture{std::forward<Func>(func)}; |
1696 | | install_buffer_funcs( |
1697 | | [](PyObject *obj, void *ptr) -> buffer_info * { |
1698 | | detail::make_caster<type> caster; |
1699 | | if (!caster.load(obj, false)) { |
1700 | | return nullptr; |
1701 | | } |
1702 | | return new buffer_info(((capture *) ptr)->func(std::move(caster))); |
1703 | | }, |
1704 | | ptr); |
1705 | | weakref(m_ptr, cpp_function([ptr](handle wr) { |
1706 | | delete ptr; |
1707 | | wr.dec_ref(); |
1708 | | })) |
1709 | | .release(); |
1710 | | return *this; |
1711 | | } |
1712 | | |
1713 | | template <typename Return, typename Class, typename... Args> |
1714 | | class_ &def_buffer(Return (Class::*func)(Args...)) { |
1715 | | return def_buffer([func](type &obj) { return (obj.*func)(); }); |
1716 | | } |
1717 | | |
1718 | | template <typename Return, typename Class, typename... Args> |
1719 | | class_ &def_buffer(Return (Class::*func)(Args...) const) { |
1720 | | return def_buffer([func](const type &obj) { return (obj.*func)(); }); |
1721 | | } |
1722 | | |
1723 | | template <typename C, typename D, typename... Extra> |
1724 | | class_ &def_readwrite(const char *name, D C::*pm, const Extra &...extra) { |
1725 | | static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value, |
1726 | | "def_readwrite() requires a class member (or base class member)"); |
1727 | | cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this)), |
1728 | | fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this)); |
1729 | | def_property(name, fget, fset, return_value_policy::reference_internal, extra...); |
1730 | | return *this; |
1731 | | } |
1732 | | |
1733 | | template <typename C, typename D, typename... Extra> |
1734 | | class_ &def_readonly(const char *name, const D C::*pm, const Extra &...extra) { |
1735 | | static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value, |
1736 | | "def_readonly() requires a class member (or base class member)"); |
1737 | | cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this)); |
1738 | | def_property_readonly(name, fget, return_value_policy::reference_internal, extra...); |
1739 | | return *this; |
1740 | | } |
1741 | | |
1742 | | template <typename D, typename... Extra> |
1743 | | class_ &def_readwrite_static(const char *name, D *pm, const Extra &...extra) { |
1744 | | cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)), |
1745 | | fset([pm](const object &, const D &value) { *pm = value; }, scope(*this)); |
1746 | | def_property_static(name, fget, fset, return_value_policy::reference, extra...); |
1747 | | return *this; |
1748 | | } |
1749 | | |
1750 | | template <typename D, typename... Extra> |
1751 | | class_ &def_readonly_static(const char *name, const D *pm, const Extra &...extra) { |
1752 | | cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)); |
1753 | | def_property_readonly_static(name, fget, return_value_policy::reference, extra...); |
1754 | | return *this; |
1755 | | } |
1756 | | |
1757 | | /// Uses return_value_policy::reference_internal by default |
1758 | | template <typename Getter, typename... Extra> |
1759 | | class_ &def_property_readonly(const char *name, const Getter &fget, const Extra &...extra) { |
1760 | | return def_property_readonly(name, |
1761 | | cpp_function(method_adaptor<type>(fget)), |
1762 | | return_value_policy::reference_internal, |
1763 | | extra...); |
1764 | | } |
1765 | | |
1766 | | /// Uses cpp_function's return_value_policy by default |
1767 | | template <typename... Extra> |
1768 | | class_ & |
1769 | | def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra) { |
1770 | | return def_property(name, fget, nullptr, extra...); |
1771 | | } |
1772 | | |
1773 | | /// Uses return_value_policy::reference by default |
1774 | | template <typename Getter, typename... Extra> |
1775 | | class_ & |
1776 | | def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra) { |
1777 | | return def_property_readonly_static( |
1778 | | name, cpp_function(fget), return_value_policy::reference, extra...); |
1779 | | } |
1780 | | |
1781 | | /// Uses cpp_function's return_value_policy by default |
1782 | | template <typename... Extra> |
1783 | | class_ &def_property_readonly_static(const char *name, |
1784 | | const cpp_function &fget, |
1785 | | const Extra &...extra) { |
1786 | | return def_property_static(name, fget, nullptr, extra...); |
1787 | | } |
1788 | | |
1789 | | /// Uses return_value_policy::reference_internal by default |
1790 | | template <typename Getter, typename Setter, typename... Extra> |
1791 | | class_ & |
1792 | | def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) { |
1793 | | return def_property( |
1794 | | name, fget, cpp_function(method_adaptor<type>(fset), is_setter()), extra...); |
1795 | | } |
1796 | | template <typename Getter, typename... Extra> |
1797 | | class_ &def_property(const char *name, |
1798 | | const Getter &fget, |
1799 | | const cpp_function &fset, |
1800 | | const Extra &...extra) { |
1801 | | return def_property(name, |
1802 | | cpp_function(method_adaptor<type>(fget)), |
1803 | | fset, |
1804 | | return_value_policy::reference_internal, |
1805 | | extra...); |
1806 | | } |
1807 | | |
1808 | | /// Uses cpp_function's return_value_policy by default |
1809 | | template <typename... Extra> |
1810 | | class_ &def_property(const char *name, |
1811 | | const cpp_function &fget, |
1812 | | const cpp_function &fset, |
1813 | | const Extra &...extra) { |
1814 | | return def_property_static(name, fget, fset, is_method(*this), extra...); |
1815 | | } |
1816 | | |
1817 | | /// Uses return_value_policy::reference by default |
1818 | | template <typename Getter, typename... Extra> |
1819 | | class_ &def_property_static(const char *name, |
1820 | | const Getter &fget, |
1821 | | const cpp_function &fset, |
1822 | | const Extra &...extra) { |
1823 | | return def_property_static( |
1824 | | name, cpp_function(fget), fset, return_value_policy::reference, extra...); |
1825 | | } |
1826 | | |
1827 | | /// Uses cpp_function's return_value_policy by default |
1828 | | template <typename... Extra> |
1829 | | class_ &def_property_static(const char *name, |
1830 | | const cpp_function &fget, |
1831 | | const cpp_function &fset, |
1832 | | const Extra &...extra) { |
1833 | | static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...), |
1834 | | "Argument annotations are not allowed for properties"); |
1835 | | auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset); |
1836 | | auto *rec_active = rec_fget; |
1837 | | if (rec_fget) { |
1838 | | char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific |
1839 | | documentation string */ |
1840 | | detail::process_attributes<Extra...>::init(extra..., rec_fget); |
1841 | | if (rec_fget->doc && rec_fget->doc != doc_prev) { |
1842 | | std::free(doc_prev); |
1843 | | rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc); |
1844 | | } |
1845 | | } |
1846 | | if (rec_fset) { |
1847 | | char *doc_prev = rec_fset->doc; |
1848 | | detail::process_attributes<Extra...>::init(extra..., rec_fset); |
1849 | | if (rec_fset->doc && rec_fset->doc != doc_prev) { |
1850 | | std::free(doc_prev); |
1851 | | rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc); |
1852 | | } |
1853 | | if (!rec_active) { |
1854 | | rec_active = rec_fset; |
1855 | | } |
1856 | | } |
1857 | | def_property_static_impl(name, fget, fset, rec_active); |
1858 | | return *this; |
1859 | | } |
1860 | | |
1861 | | private: |
1862 | | /// Initialize holder object, variant 1: object derives from enable_shared_from_this |
1863 | | template <typename T> |
1864 | | static void init_holder(detail::instance *inst, |
1865 | | detail::value_and_holder &v_h, |
1866 | | const holder_type * /* unused */, |
1867 | | const std::enable_shared_from_this<T> * /* dummy */) { |
1868 | | |
1869 | | auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>( |
1870 | | detail::try_get_shared_from_this(v_h.value_ptr<type>())); |
1871 | | if (sh) { |
1872 | | new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh)); |
1873 | | v_h.set_holder_constructed(); |
1874 | | } |
1875 | | |
1876 | | if (!v_h.holder_constructed() && inst->owned) { |
1877 | | new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>()); |
1878 | | v_h.set_holder_constructed(); |
1879 | | } |
1880 | | } |
1881 | | |
1882 | | static void init_holder_from_existing(const detail::value_and_holder &v_h, |
1883 | | const holder_type *holder_ptr, |
1884 | | std::true_type /*is_copy_constructible*/) { |
1885 | | new (std::addressof(v_h.holder<holder_type>())) |
1886 | | holder_type(*reinterpret_cast<const holder_type *>(holder_ptr)); |
1887 | | } |
1888 | | |
1889 | | static void init_holder_from_existing(const detail::value_and_holder &v_h, |
1890 | | const holder_type *holder_ptr, |
1891 | | std::false_type /*is_copy_constructible*/) { |
1892 | | new (std::addressof(v_h.holder<holder_type>())) |
1893 | | holder_type(std::move(*const_cast<holder_type *>(holder_ptr))); |
1894 | | } |
1895 | | |
1896 | | /// Initialize holder object, variant 2: try to construct from existing holder object, if |
1897 | | /// possible |
1898 | | static void init_holder(detail::instance *inst, |
1899 | | detail::value_and_holder &v_h, |
1900 | | const holder_type *holder_ptr, |
1901 | | const void * /* dummy -- not enable_shared_from_this<T>) */) { |
1902 | | if (holder_ptr) { |
1903 | | init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>()); |
1904 | | v_h.set_holder_constructed(); |
1905 | | } else if (detail::always_construct_holder<holder_type>::value || inst->owned) { |
1906 | | new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>()); |
1907 | | v_h.set_holder_constructed(); |
1908 | | } |
1909 | | } |
1910 | | |
1911 | | /// Performs instance initialization including constructing a holder and registering the known |
1912 | | /// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes |
1913 | | /// an optional pointer to an existing holder to use; if not specified and the instance is |
1914 | | /// `.owned`, a new holder will be constructed to manage the value pointer. |
1915 | | static void init_instance(detail::instance *inst, const void *holder_ptr) { |
1916 | | auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type))); |
1917 | | if (!v_h.instance_registered()) { |
1918 | | register_instance(inst, v_h.value_ptr(), v_h.type); |
1919 | | v_h.set_instance_registered(); |
1920 | | } |
1921 | | init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>()); |
1922 | | } |
1923 | | |
1924 | | /// Deallocates an instance; via holder, if constructed; otherwise via operator delete. |
1925 | | static void dealloc(detail::value_and_holder &v_h) { |
1926 | | // We could be deallocating because we are cleaning up after a Python exception. |
1927 | | // If so, the Python error indicator will be set. We need to clear that before |
1928 | | // running the destructor, in case the destructor code calls more Python. |
1929 | | // If we don't, the Python API will exit with an exception, and pybind11 will |
1930 | | // throw error_already_set from the C++ destructor which is forbidden and triggers |
1931 | | // std::terminate(). |
1932 | | error_scope scope; |
1933 | | if (v_h.holder_constructed()) { |
1934 | | v_h.holder<holder_type>().~holder_type(); |
1935 | | v_h.set_holder_constructed(false); |
1936 | | } else { |
1937 | | detail::call_operator_delete( |
1938 | | v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align); |
1939 | | } |
1940 | | v_h.value_ptr() = nullptr; |
1941 | | } |
1942 | | |
1943 | | static detail::function_record *get_function_record(handle h) { |
1944 | | h = detail::get_function(h); |
1945 | | if (!h) { |
1946 | | return nullptr; |
1947 | | } |
1948 | | |
1949 | | handle func_self = PyCFunction_GET_SELF(h.ptr()); |
1950 | | if (!func_self) { |
1951 | | throw error_already_set(); |
1952 | | } |
1953 | | if (!isinstance<capsule>(func_self)) { |
1954 | | return nullptr; |
1955 | | } |
1956 | | auto cap = reinterpret_borrow<capsule>(func_self); |
1957 | | if (!detail::is_function_record_capsule(cap)) { |
1958 | | return nullptr; |
1959 | | } |
1960 | | return cap.get_pointer<detail::function_record>(); |
1961 | | } |
1962 | | }; |
1963 | | |
1964 | | /// Binds an existing constructor taking arguments Args... |
1965 | | template <typename... Args> |
1966 | | detail::initimpl::constructor<Args...> init() { |
1967 | | return {}; |
1968 | | } |
1969 | | /// Like `init<Args...>()`, but the instance is always constructed through the alias class (even |
1970 | | /// when not inheriting on the Python side). |
1971 | | template <typename... Args> |
1972 | | detail::initimpl::alias_constructor<Args...> init_alias() { |
1973 | | return {}; |
1974 | | } |
1975 | | |
1976 | | /// Binds a factory function as a constructor |
1977 | | template <typename Func, typename Ret = detail::initimpl::factory<Func>> |
1978 | | Ret init(Func &&f) { |
1979 | | return {std::forward<Func>(f)}; |
1980 | | } |
1981 | | |
1982 | | /// Dual-argument factory function: the first function is called when no alias is needed, the |
1983 | | /// second when an alias is needed (i.e. due to python-side inheritance). Arguments must be |
1984 | | /// identical. |
1985 | | template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>> |
1986 | | Ret init(CFunc &&c, AFunc &&a) { |
1987 | | return {std::forward<CFunc>(c), std::forward<AFunc>(a)}; |
1988 | | } |
1989 | | |
1990 | | /// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type |
1991 | | /// returned by `__getstate__` is the same as the argument accepted by `__setstate__`. |
1992 | | template <typename GetState, typename SetState> |
1993 | | detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) { |
1994 | | return {std::forward<GetState>(g), std::forward<SetState>(s)}; |
1995 | | } |
1996 | | |
1997 | | PYBIND11_NAMESPACE_BEGIN(detail) |
1998 | | |
1999 | 0 | inline str enum_name(handle arg) { |
2000 | 0 | dict entries = arg.get_type().attr("__entries"); |
2001 | 0 | for (auto kv : entries) { |
2002 | 0 | if (handle(kv.second[int_(0)]).equal(arg)) { |
2003 | 0 | return pybind11::str(kv.first); |
2004 | 0 | } |
2005 | 0 | } |
2006 | 0 | return "???"; |
2007 | 0 | } |
2008 | | |
2009 | | struct enum_base { |
2010 | 0 | enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) {} |
2011 | | |
2012 | 0 | PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) { |
2013 | 0 | m_base.attr("__entries") = dict(); |
2014 | 0 | auto property = handle((PyObject *) &PyProperty_Type); |
2015 | 0 | auto static_property = handle((PyObject *) get_internals().static_property_type); |
2016 | 0 |
|
2017 | 0 | m_base.attr("__repr__") = cpp_function( |
2018 | 0 | [](const object &arg) -> str { |
2019 | 0 | handle type = type::handle_of(arg); |
2020 | 0 | object type_name = type.attr("__name__"); |
2021 | 0 | return pybind11::str("<{}.{}: {}>") |
2022 | 0 | .format(std::move(type_name), enum_name(arg), int_(arg)); |
2023 | 0 | }, |
2024 | 0 | name("__repr__"), |
2025 | 0 | is_method(m_base)); |
2026 | 0 |
|
2027 | 0 | m_base.attr("name") = property(cpp_function(&enum_name, name("name"), is_method(m_base))); |
2028 | 0 |
|
2029 | 0 | m_base.attr("__str__") = cpp_function( |
2030 | 0 | [](handle arg) -> str { |
2031 | 0 | object type_name = type::handle_of(arg).attr("__name__"); |
2032 | 0 | return pybind11::str("{}.{}").format(std::move(type_name), enum_name(arg)); |
2033 | 0 | }, |
2034 | 0 | name("__str__"), |
2035 | 0 | is_method(m_base)); |
2036 | 0 |
|
2037 | 0 | if (options::show_enum_members_docstring()) { |
2038 | 0 | m_base.attr("__doc__") = static_property( |
2039 | 0 | cpp_function( |
2040 | 0 | [](handle arg) -> std::string { |
2041 | 0 | std::string docstring; |
2042 | 0 | dict entries = arg.attr("__entries"); |
2043 | 0 | if (((PyTypeObject *) arg.ptr())->tp_doc) { |
2044 | 0 | docstring += std::string( |
2045 | 0 | reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc); |
2046 | 0 | docstring += "\n\n"; |
2047 | 0 | } |
2048 | 0 | docstring += "Members:"; |
2049 | 0 | for (auto kv : entries) { |
2050 | 0 | auto key = std::string(pybind11::str(kv.first)); |
2051 | 0 | auto comment = kv.second[int_(1)]; |
2052 | 0 | docstring += "\n\n "; |
2053 | 0 | docstring += key; |
2054 | 0 | if (!comment.is_none()) { |
2055 | 0 | docstring += " : "; |
2056 | 0 | docstring += pybind11::str(comment).cast<std::string>(); |
2057 | 0 | } |
2058 | 0 | } |
2059 | 0 | return docstring; |
2060 | 0 | }, |
2061 | 0 | name("__doc__")), |
2062 | 0 | none(), |
2063 | 0 | none(), |
2064 | 0 | ""); |
2065 | 0 | } |
2066 | 0 |
|
2067 | 0 | m_base.attr("__members__") = static_property(cpp_function( |
2068 | 0 | [](handle arg) -> dict { |
2069 | 0 | dict entries = arg.attr("__entries"), |
2070 | 0 | m; |
2071 | 0 | for (auto kv : entries) { |
2072 | 0 | m[kv.first] = kv.second[int_(0)]; |
2073 | 0 | } |
2074 | 0 | return m; |
2075 | 0 | }, |
2076 | 0 | name("__members__")), |
2077 | 0 | none(), |
2078 | 0 | none(), |
2079 | 0 | ""); |
2080 | 0 |
|
2081 | 0 | #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \ |
2082 | 0 | m_base.attr(op) = cpp_function( \ |
2083 | 0 | [](const object &a, const object &b) { \ |
2084 | 0 | if (!type::handle_of(a).is(type::handle_of(b))) \ |
2085 | 0 | strict_behavior; /* NOLINT(bugprone-macro-parentheses) */ \ |
2086 | 0 | return expr; \ |
2087 | 0 | }, \ |
2088 | 0 | name(op), \ |
2089 | 0 | is_method(m_base), \ |
2090 | 0 | arg("other")) |
2091 | 0 |
|
2092 | 0 | #define PYBIND11_ENUM_OP_CONV(op, expr) \ |
2093 | 0 | m_base.attr(op) = cpp_function( \ |
2094 | 0 | [](const object &a_, const object &b_) { \ |
2095 | 0 | int_ a(a_), b(b_); \ |
2096 | 0 | return expr; \ |
2097 | 0 | }, \ |
2098 | 0 | name(op), \ |
2099 | 0 | is_method(m_base), \ |
2100 | 0 | arg("other")) |
2101 | 0 |
|
2102 | 0 | #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \ |
2103 | 0 | m_base.attr(op) = cpp_function( \ |
2104 | 0 | [](const object &a_, const object &b) { \ |
2105 | 0 | int_ a(a_); \ |
2106 | 0 | return expr; \ |
2107 | 0 | }, \ |
2108 | 0 | name(op), \ |
2109 | 0 | is_method(m_base), \ |
2110 | 0 | arg("other")) |
2111 | 0 |
|
2112 | 0 | if (is_convertible) { |
2113 | 0 | PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b)); |
2114 | 0 | PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b)); |
2115 | 0 |
|
2116 | 0 | if (is_arithmetic) { |
2117 | 0 | PYBIND11_ENUM_OP_CONV("__lt__", a < b); |
2118 | 0 | PYBIND11_ENUM_OP_CONV("__gt__", a > b); |
2119 | 0 | PYBIND11_ENUM_OP_CONV("__le__", a <= b); |
2120 | 0 | PYBIND11_ENUM_OP_CONV("__ge__", a >= b); |
2121 | 0 | PYBIND11_ENUM_OP_CONV("__and__", a & b); |
2122 | 0 | PYBIND11_ENUM_OP_CONV("__rand__", a & b); |
2123 | 0 | PYBIND11_ENUM_OP_CONV("__or__", a | b); |
2124 | 0 | PYBIND11_ENUM_OP_CONV("__ror__", a | b); |
2125 | 0 | PYBIND11_ENUM_OP_CONV("__xor__", a ^ b); |
2126 | 0 | PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b); |
2127 | 0 | m_base.attr("__invert__") |
2128 | 0 | = cpp_function([](const object &arg) { return ~(int_(arg)); }, |
2129 | 0 | name("__invert__"), |
2130 | 0 | is_method(m_base)); |
2131 | 0 | } |
2132 | 0 | } else { |
2133 | 0 | PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false); |
2134 | 0 | PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true); |
2135 | 0 |
|
2136 | 0 | if (is_arithmetic) { |
2137 | 0 | #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!"); |
2138 | 0 | PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW); |
2139 | 0 | PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW); |
2140 | 0 | PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW); |
2141 | 0 | PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW); |
2142 | 0 | #undef PYBIND11_THROW |
2143 | 0 | } |
2144 | 0 | } |
2145 | 0 |
|
2146 | 0 | #undef PYBIND11_ENUM_OP_CONV_LHS |
2147 | 0 | #undef PYBIND11_ENUM_OP_CONV |
2148 | 0 | #undef PYBIND11_ENUM_OP_STRICT |
2149 | 0 |
|
2150 | 0 | m_base.attr("__getstate__") = cpp_function( |
2151 | 0 | [](const object &arg) { return int_(arg); }, name("__getstate__"), is_method(m_base)); |
2152 | 0 |
|
2153 | 0 | m_base.attr("__hash__") = cpp_function( |
2154 | 0 | [](const object &arg) { return int_(arg); }, name("__hash__"), is_method(m_base)); |
2155 | 0 | } |
2156 | | |
2157 | 0 | PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc = nullptr) { |
2158 | 0 | dict entries = m_base.attr("__entries"); |
2159 | 0 | str name(name_); |
2160 | 0 | if (entries.contains(name)) { |
2161 | 0 | std::string type_name = (std::string) str(m_base.attr("__name__")); |
2162 | 0 | throw value_error(std::move(type_name) + ": element \"" + std::string(name_) |
2163 | 0 | + "\" already exists!"); |
2164 | 0 | } |
2165 | 0 |
|
2166 | 0 | entries[name] = pybind11::make_tuple(value, doc); |
2167 | 0 | m_base.attr(std::move(name)) = std::move(value); |
2168 | 0 | } |
2169 | | |
2170 | 0 | PYBIND11_NOINLINE void export_values() { |
2171 | 0 | dict entries = m_base.attr("__entries"); |
2172 | 0 | for (auto kv : entries) { |
2173 | 0 | m_parent.attr(kv.first) = kv.second[int_(0)]; |
2174 | 0 | } |
2175 | 0 | } |
2176 | | |
2177 | | handle m_base; |
2178 | | handle m_parent; |
2179 | | }; |
2180 | | |
2181 | | template <bool is_signed, size_t length> |
2182 | | struct equivalent_integer {}; |
2183 | | template <> |
2184 | | struct equivalent_integer<true, 1> { |
2185 | | using type = int8_t; |
2186 | | }; |
2187 | | template <> |
2188 | | struct equivalent_integer<false, 1> { |
2189 | | using type = uint8_t; |
2190 | | }; |
2191 | | template <> |
2192 | | struct equivalent_integer<true, 2> { |
2193 | | using type = int16_t; |
2194 | | }; |
2195 | | template <> |
2196 | | struct equivalent_integer<false, 2> { |
2197 | | using type = uint16_t; |
2198 | | }; |
2199 | | template <> |
2200 | | struct equivalent_integer<true, 4> { |
2201 | | using type = int32_t; |
2202 | | }; |
2203 | | template <> |
2204 | | struct equivalent_integer<false, 4> { |
2205 | | using type = uint32_t; |
2206 | | }; |
2207 | | template <> |
2208 | | struct equivalent_integer<true, 8> { |
2209 | | using type = int64_t; |
2210 | | }; |
2211 | | template <> |
2212 | | struct equivalent_integer<false, 8> { |
2213 | | using type = uint64_t; |
2214 | | }; |
2215 | | |
2216 | | template <typename IntLike> |
2217 | | using equivalent_integer_t = |
2218 | | typename equivalent_integer<std::is_signed<IntLike>::value, sizeof(IntLike)>::type; |
2219 | | |
2220 | | PYBIND11_NAMESPACE_END(detail) |
2221 | | |
2222 | | /// Binds C++ enumerations and enumeration classes to Python |
2223 | | template <typename Type> |
2224 | | class enum_ : public class_<Type> { |
2225 | | public: |
2226 | | using Base = class_<Type>; |
2227 | | using Base::attr; |
2228 | | using Base::def; |
2229 | | using Base::def_property_readonly; |
2230 | | using Base::def_property_readonly_static; |
2231 | | using Underlying = typename std::underlying_type<Type>::type; |
2232 | | // Scalar is the integer representation of underlying type |
2233 | | using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>, |
2234 | | std::is_same<Underlying, bool>>::value, |
2235 | | detail::equivalent_integer_t<Underlying>, |
2236 | | Underlying>; |
2237 | | |
2238 | | template <typename... Extra> |
2239 | | enum_(const handle &scope, const char *name, const Extra &...extra) |
2240 | | : class_<Type>(scope, name, extra...), m_base(*this, scope) { |
2241 | | constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value; |
2242 | | constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value; |
2243 | | m_base.init(is_arithmetic, is_convertible); |
2244 | | |
2245 | | def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value")); |
2246 | | def_property_readonly("value", [](Type value) { return (Scalar) value; }); |
2247 | | def("__int__", [](Type value) { return (Scalar) value; }); |
2248 | | def("__index__", [](Type value) { return (Scalar) value; }); |
2249 | | attr("__setstate__") = cpp_function( |
2250 | | [](detail::value_and_holder &v_h, Scalar arg) { |
2251 | | detail::initimpl::setstate<Base>( |
2252 | | v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type); |
2253 | | }, |
2254 | | detail::is_new_style_constructor(), |
2255 | | pybind11::name("__setstate__"), |
2256 | | is_method(*this), |
2257 | | arg("state")); |
2258 | | } |
2259 | | |
2260 | | /// Export enumeration entries into the parent scope |
2261 | | enum_ &export_values() { |
2262 | | m_base.export_values(); |
2263 | | return *this; |
2264 | | } |
2265 | | |
2266 | | /// Add an enumeration entry |
2267 | | enum_ &value(char const *name, Type value, const char *doc = nullptr) { |
2268 | | m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc); |
2269 | | return *this; |
2270 | | } |
2271 | | |
2272 | | private: |
2273 | | detail::enum_base m_base; |
2274 | | }; |
2275 | | |
2276 | | PYBIND11_NAMESPACE_BEGIN(detail) |
2277 | | |
2278 | 0 | PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient) { |
2279 | 0 | if (!nurse || !patient) { |
2280 | 0 | pybind11_fail("Could not activate keep_alive!"); |
2281 | 0 | } |
2282 | 0 |
|
2283 | 0 | if (patient.is_none() || nurse.is_none()) { |
2284 | 0 | return; /* Nothing to keep alive or nothing to be kept alive by */ |
2285 | 0 | } |
2286 | 0 |
|
2287 | 0 | auto tinfo = all_type_info(Py_TYPE(nurse.ptr())); |
2288 | 0 | if (!tinfo.empty()) { |
2289 | 0 | /* It's a pybind-registered type, so we can store the patient in the |
2290 | 0 | * internal list. */ |
2291 | 0 | add_patient(nurse.ptr(), patient.ptr()); |
2292 | 0 | } else { |
2293 | 0 | /* Fall back to clever approach based on weak references taken from |
2294 | 0 | * Boost.Python. This is not used for pybind-registered types because |
2295 | 0 | * the objects can be destroyed out-of-order in a GC pass. */ |
2296 | 0 | cpp_function disable_lifesupport([patient](handle weakref) { |
2297 | 0 | patient.dec_ref(); |
2298 | 0 | weakref.dec_ref(); |
2299 | 0 | }); |
2300 | 0 |
|
2301 | 0 | weakref wr(nurse, disable_lifesupport); |
2302 | 0 |
|
2303 | 0 | patient.inc_ref(); /* reference patient and leak the weak reference */ |
2304 | 0 | (void) wr.release(); |
2305 | 0 | } |
2306 | 0 | } |
2307 | | |
2308 | | PYBIND11_NOINLINE void |
2309 | 0 | keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) { |
2310 | 0 | auto get_arg = [&](size_t n) { |
2311 | 0 | if (n == 0) { |
2312 | 0 | return ret; |
2313 | 0 | } |
2314 | 0 | if (n == 1 && call.init_self) { |
2315 | 0 | return call.init_self; |
2316 | 0 | } |
2317 | 0 | if (n <= call.args.size()) { |
2318 | 0 | return call.args[n - 1]; |
2319 | 0 | } |
2320 | 0 | return handle(); |
2321 | 0 | }; |
2322 | 0 |
|
2323 | 0 | keep_alive_impl(get_arg(Nurse), get_arg(Patient)); |
2324 | 0 | } |
2325 | | |
2326 | | inline std::pair<decltype(internals::registered_types_py)::iterator, bool> |
2327 | 0 | all_type_info_get_cache(PyTypeObject *type) { |
2328 | 0 | auto res = with_internals([type](internals &internals) { |
2329 | 0 | return internals |
2330 | 0 | .registered_types_py |
2331 | 0 | #ifdef __cpp_lib_unordered_map_try_emplace |
2332 | 0 | .try_emplace(type); |
2333 | | #else |
2334 | | .emplace(type, std::vector<detail::type_info *>()); |
2335 | | #endif |
2336 | 0 | }); |
2337 | 0 | if (res.second) { |
2338 | | // New cache entry created; set up a weak reference to automatically remove it if the type |
2339 | | // gets destroyed: |
2340 | 0 | weakref((PyObject *) type, cpp_function([type](handle wr) { |
2341 | 0 | with_internals([type](internals &internals) { |
2342 | 0 | internals.registered_types_py.erase(type); |
2343 | | |
2344 | | // TODO consolidate the erasure code in pybind11_meta_dealloc() in class.h |
2345 | 0 | auto &cache = internals.inactive_override_cache; |
2346 | 0 | for (auto it = cache.begin(), last = cache.end(); it != last;) { |
2347 | 0 | if (it->first == reinterpret_cast<PyObject *>(type)) { |
2348 | 0 | it = cache.erase(it); |
2349 | 0 | } else { |
2350 | 0 | ++it; |
2351 | 0 | } |
2352 | 0 | } |
2353 | 0 | }); |
2354 | |
|
2355 | 0 | wr.dec_ref(); |
2356 | 0 | })) |
2357 | 0 | .release(); |
2358 | 0 | } |
2359 | |
|
2360 | 0 | return res; |
2361 | 0 | } |
2362 | | |
2363 | | /* There are a large number of apparently unused template arguments because |
2364 | | * each combination requires a separate py::class_ registration. |
2365 | | */ |
2366 | | template <typename Access, |
2367 | | return_value_policy Policy, |
2368 | | typename Iterator, |
2369 | | typename Sentinel, |
2370 | | typename ValueType, |
2371 | | typename... Extra> |
2372 | | struct iterator_state { |
2373 | | Iterator it; |
2374 | | Sentinel end; |
2375 | | bool first_or_done; |
2376 | | }; |
2377 | | |
2378 | | // Note: these helpers take the iterator by non-const reference because some |
2379 | | // iterators in the wild can't be dereferenced when const. The & after Iterator |
2380 | | // is required for MSVC < 16.9. SFINAE cannot be reused for result_type due to |
2381 | | // bugs in ICC, NVCC, and PGI compilers. See PR #3293. |
2382 | | template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())> |
2383 | | struct iterator_access { |
2384 | | using result_type = decltype(*std::declval<Iterator &>()); |
2385 | | // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 |
2386 | | result_type operator()(Iterator &it) const { return *it; } |
2387 | | }; |
2388 | | |
2389 | | template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).first)> |
2390 | | class iterator_key_access { |
2391 | | private: |
2392 | | using pair_type = decltype(*std::declval<Iterator &>()); |
2393 | | |
2394 | | public: |
2395 | | /* If either the pair itself or the element of the pair is a reference, we |
2396 | | * want to return a reference, otherwise a value. When the decltype |
2397 | | * expression is parenthesized it is based on the value category of the |
2398 | | * expression; otherwise it is the declared type of the pair member. |
2399 | | * The use of declval<pair_type> in the second branch rather than directly |
2400 | | * using *std::declval<Iterator &>() is a workaround for nvcc |
2401 | | * (it's not used in the first branch because going via decltype and back |
2402 | | * through declval does not perfectly preserve references). |
2403 | | */ |
2404 | | using result_type |
2405 | | = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value, |
2406 | | decltype(((*std::declval<Iterator &>()).first)), |
2407 | | decltype(std::declval<pair_type>().first)>; |
2408 | | result_type operator()(Iterator &it) const { return (*it).first; } |
2409 | | }; |
2410 | | |
2411 | | template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)> |
2412 | | class iterator_value_access { |
2413 | | private: |
2414 | | using pair_type = decltype(*std::declval<Iterator &>()); |
2415 | | |
2416 | | public: |
2417 | | using result_type |
2418 | | = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value, |
2419 | | decltype(((*std::declval<Iterator &>()).second)), |
2420 | | decltype(std::declval<pair_type>().second)>; |
2421 | | result_type operator()(Iterator &it) const { return (*it).second; } |
2422 | | }; |
2423 | | |
2424 | | template <typename Access, |
2425 | | return_value_policy Policy, |
2426 | | typename Iterator, |
2427 | | typename Sentinel, |
2428 | | typename ValueType, |
2429 | | typename... Extra> |
2430 | | iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra) { |
2431 | | using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>; |
2432 | | // TODO: state captures only the types of Extra, not the values |
2433 | | |
2434 | | if (!detail::get_type_info(typeid(state), false)) { |
2435 | | class_<state>(handle(), "iterator", pybind11::module_local()) |
2436 | | .def("__iter__", [](state &s) -> state & { return s; }) |
2437 | | .def( |
2438 | | "__next__", |
2439 | | [](state &s) -> ValueType { |
2440 | | if (!s.first_or_done) { |
2441 | | ++s.it; |
2442 | | } else { |
2443 | | s.first_or_done = false; |
2444 | | } |
2445 | | if (s.it == s.end) { |
2446 | | s.first_or_done = true; |
2447 | | throw stop_iteration(); |
2448 | | } |
2449 | | return Access()(s.it); |
2450 | | // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 |
2451 | | }, |
2452 | | std::forward<Extra>(extra)..., |
2453 | | Policy); |
2454 | | } |
2455 | | |
2456 | | return cast(state{std::forward<Iterator>(first), std::forward<Sentinel>(last), true}); |
2457 | | } |
2458 | | |
2459 | | PYBIND11_NAMESPACE_END(detail) |
2460 | | |
2461 | | /// Makes a python iterator from a first and past-the-end C++ InputIterator. |
2462 | | template <return_value_policy Policy = return_value_policy::reference_internal, |
2463 | | typename Iterator, |
2464 | | typename Sentinel, |
2465 | | typename ValueType = typename detail::iterator_access<Iterator>::result_type, |
2466 | | typename... Extra> |
2467 | | typing::Iterator<ValueType> make_iterator(Iterator first, Sentinel last, Extra &&...extra) { |
2468 | | return detail::make_iterator_impl<detail::iterator_access<Iterator>, |
2469 | | Policy, |
2470 | | Iterator, |
2471 | | Sentinel, |
2472 | | ValueType, |
2473 | | Extra...>(std::forward<Iterator>(first), |
2474 | | std::forward<Sentinel>(last), |
2475 | | std::forward<Extra>(extra)...); |
2476 | | } |
2477 | | |
2478 | | /// Makes a python iterator over the keys (`.first`) of a iterator over pairs from a |
2479 | | /// first and past-the-end InputIterator. |
2480 | | template <return_value_policy Policy = return_value_policy::reference_internal, |
2481 | | typename Iterator, |
2482 | | typename Sentinel, |
2483 | | typename KeyType = typename detail::iterator_key_access<Iterator>::result_type, |
2484 | | typename... Extra> |
2485 | | typing::Iterator<KeyType> make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) { |
2486 | | return detail::make_iterator_impl<detail::iterator_key_access<Iterator>, |
2487 | | Policy, |
2488 | | Iterator, |
2489 | | Sentinel, |
2490 | | KeyType, |
2491 | | Extra...>(std::forward<Iterator>(first), |
2492 | | std::forward<Sentinel>(last), |
2493 | | std::forward<Extra>(extra)...); |
2494 | | } |
2495 | | |
2496 | | /// Makes a python iterator over the values (`.second`) of a iterator over pairs from a |
2497 | | /// first and past-the-end InputIterator. |
2498 | | template <return_value_policy Policy = return_value_policy::reference_internal, |
2499 | | typename Iterator, |
2500 | | typename Sentinel, |
2501 | | typename ValueType = typename detail::iterator_value_access<Iterator>::result_type, |
2502 | | typename... Extra> |
2503 | | typing::Iterator<ValueType> make_value_iterator(Iterator first, Sentinel last, Extra &&...extra) { |
2504 | | return detail::make_iterator_impl<detail::iterator_value_access<Iterator>, |
2505 | | Policy, |
2506 | | Iterator, |
2507 | | Sentinel, |
2508 | | ValueType, |
2509 | | Extra...>(std::forward<Iterator>(first), |
2510 | | std::forward<Sentinel>(last), |
2511 | | std::forward<Extra>(extra)...); |
2512 | | } |
2513 | | |
2514 | | /// Makes an iterator over values of an stl container or other container supporting |
2515 | | /// `std::begin()`/`std::end()` |
2516 | | template <return_value_policy Policy = return_value_policy::reference_internal, |
2517 | | typename Type, |
2518 | | typename ValueType = typename detail::iterator_access< |
2519 | | decltype(std::begin(std::declval<Type &>()))>::result_type, |
2520 | | typename... Extra> |
2521 | | typing::Iterator<ValueType> make_iterator(Type &value, Extra &&...extra) { |
2522 | | return make_iterator<Policy>( |
2523 | | std::begin(value), std::end(value), std::forward<Extra>(extra)...); |
2524 | | } |
2525 | | |
2526 | | /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting |
2527 | | /// `std::begin()`/`std::end()` |
2528 | | template <return_value_policy Policy = return_value_policy::reference_internal, |
2529 | | typename Type, |
2530 | | typename KeyType = typename detail::iterator_key_access< |
2531 | | decltype(std::begin(std::declval<Type &>()))>::result_type, |
2532 | | typename... Extra> |
2533 | | typing::Iterator<KeyType> make_key_iterator(Type &value, Extra &&...extra) { |
2534 | | return make_key_iterator<Policy>( |
2535 | | std::begin(value), std::end(value), std::forward<Extra>(extra)...); |
2536 | | } |
2537 | | |
2538 | | /// Makes an iterator over the values (`.second`) of a stl map-like container supporting |
2539 | | /// `std::begin()`/`std::end()` |
2540 | | template <return_value_policy Policy = return_value_policy::reference_internal, |
2541 | | typename Type, |
2542 | | typename ValueType = typename detail::iterator_value_access< |
2543 | | decltype(std::begin(std::declval<Type &>()))>::result_type, |
2544 | | typename... Extra> |
2545 | | typing::Iterator<ValueType> make_value_iterator(Type &value, Extra &&...extra) { |
2546 | | return make_value_iterator<Policy>( |
2547 | | std::begin(value), std::end(value), std::forward<Extra>(extra)...); |
2548 | | } |
2549 | | |
2550 | | template <typename InputType, typename OutputType> |
2551 | | void implicitly_convertible() { |
2552 | | struct set_flag { |
2553 | | bool &flag; |
2554 | | explicit set_flag(bool &flag_) : flag(flag_) { flag_ = true; } |
2555 | | ~set_flag() { flag = false; } |
2556 | | }; |
2557 | | auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * { |
2558 | | #ifdef Py_GIL_DISABLED |
2559 | | thread_local bool currently_used = false; |
2560 | | #else |
2561 | | static bool currently_used = false; |
2562 | | #endif |
2563 | | if (currently_used) { // implicit conversions are non-reentrant |
2564 | | return nullptr; |
2565 | | } |
2566 | | set_flag flag_helper(currently_used); |
2567 | | if (!detail::make_caster<InputType>().load(obj, false)) { |
2568 | | return nullptr; |
2569 | | } |
2570 | | tuple args(1); |
2571 | | args[0] = obj; |
2572 | | PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr); |
2573 | | if (result == nullptr) { |
2574 | | PyErr_Clear(); |
2575 | | } |
2576 | | return result; |
2577 | | }; |
2578 | | |
2579 | | if (auto *tinfo = detail::get_type_info(typeid(OutputType))) { |
2580 | | tinfo->implicit_conversions.emplace_back(std::move(implicit_caster)); |
2581 | | } else { |
2582 | | pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>()); |
2583 | | } |
2584 | | } |
2585 | | |
2586 | 0 | inline void register_exception_translator(ExceptionTranslator &&translator) { |
2587 | 0 | detail::with_exception_translators( |
2588 | 0 | [&](std::forward_list<ExceptionTranslator> &exception_translators, |
2589 | 0 | std::forward_list<ExceptionTranslator> &local_exception_translators) { |
2590 | 0 | (void) local_exception_translators; |
2591 | 0 | exception_translators.push_front(std::forward<ExceptionTranslator>(translator)); |
2592 | 0 | }); |
2593 | 0 | } |
2594 | | |
2595 | | /** |
2596 | | * Add a new module-local exception translator. Locally registered functions |
2597 | | * will be tried before any globally registered exception translators, which |
2598 | | * will only be invoked if the module-local handlers do not deal with |
2599 | | * the exception. |
2600 | | */ |
2601 | 0 | inline void register_local_exception_translator(ExceptionTranslator &&translator) { |
2602 | 0 | detail::with_exception_translators( |
2603 | 0 | [&](std::forward_list<ExceptionTranslator> &exception_translators, |
2604 | 0 | std::forward_list<ExceptionTranslator> &local_exception_translators) { |
2605 | 0 | (void) exception_translators; |
2606 | 0 | local_exception_translators.push_front(std::forward<ExceptionTranslator>(translator)); |
2607 | 0 | }); |
2608 | 0 | } |
2609 | | |
2610 | | /** |
2611 | | * Wrapper to generate a new Python exception type. |
2612 | | * |
2613 | | * This should only be used with py::set_error() for now. |
2614 | | * It is not (yet) possible to use as a py::base. |
2615 | | * Template type argument is reserved for future use. |
2616 | | */ |
2617 | | template <typename type> |
2618 | | class exception : public object { |
2619 | | public: |
2620 | | exception() = default; |
2621 | | exception(handle scope, const char *name, handle base = PyExc_Exception) { |
2622 | | std::string full_name |
2623 | | = scope.attr("__name__").cast<std::string>() + std::string(".") + name; |
2624 | | m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), nullptr); |
2625 | | if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name)) { |
2626 | | pybind11_fail("Error during initialization: multiple incompatible " |
2627 | | "definitions with name \"" |
2628 | | + std::string(name) + "\""); |
2629 | | } |
2630 | | scope.attr(name) = *this; |
2631 | | } |
2632 | | |
2633 | | // Sets the current python exception to this exception object with the given message |
2634 | | PYBIND11_DEPRECATED("Please use py::set_error() instead " |
2635 | | "(https://github.com/pybind/pybind11/pull/4772)") |
2636 | | void operator()(const char *message) const { set_error(*this, message); } |
2637 | | }; |
2638 | | |
2639 | | PYBIND11_NAMESPACE_BEGIN(detail) |
2640 | | |
2641 | | template <> |
2642 | | struct handle_type_name<exception<void>> { |
2643 | | static constexpr auto name = const_name("Exception"); |
2644 | | }; |
2645 | | |
2646 | | // Helper function for register_exception and register_local_exception |
2647 | | template <typename CppException> |
2648 | | exception<CppException> & |
2649 | | register_exception_impl(handle scope, const char *name, handle base, bool isLocal) { |
2650 | | PYBIND11_CONSTINIT static gil_safe_call_once_and_store<exception<CppException>> exc_storage; |
2651 | | exc_storage.call_once_and_store_result( |
2652 | | [&]() { return exception<CppException>(scope, name, base); }); |
2653 | | |
2654 | | auto register_func |
2655 | | = isLocal ? ®ister_local_exception_translator : ®ister_exception_translator; |
2656 | | |
2657 | | register_func([](std::exception_ptr p) { |
2658 | | if (!p) { |
2659 | | return; |
2660 | | } |
2661 | | try { |
2662 | | std::rethrow_exception(p); |
2663 | | } catch (const CppException &e) { |
2664 | | set_error(exc_storage.get_stored(), e.what()); |
2665 | | } |
2666 | | }); |
2667 | | return exc_storage.get_stored(); |
2668 | | } |
2669 | | |
2670 | | PYBIND11_NAMESPACE_END(detail) |
2671 | | |
2672 | | /** |
2673 | | * Registers a Python exception in `m` of the given `name` and installs a translator to |
2674 | | * translate the C++ exception to the created Python exception using the what() method. |
2675 | | * This is intended for simple exception translations; for more complex translation, register the |
2676 | | * exception object and translator directly. |
2677 | | */ |
2678 | | template <typename CppException> |
2679 | | exception<CppException> & |
2680 | | register_exception(handle scope, const char *name, handle base = PyExc_Exception) { |
2681 | | return detail::register_exception_impl<CppException>(scope, name, base, false /* isLocal */); |
2682 | | } |
2683 | | |
2684 | | /** |
2685 | | * Registers a Python exception in `m` of the given `name` and installs a translator to |
2686 | | * translate the C++ exception to the created Python exception using the what() method. |
2687 | | * This translator will only be used for exceptions that are thrown in this module and will be |
2688 | | * tried before global exception translators, including those registered with register_exception. |
2689 | | * This is intended for simple exception translations; for more complex translation, register the |
2690 | | * exception object and translator directly. |
2691 | | */ |
2692 | | template <typename CppException> |
2693 | | exception<CppException> & |
2694 | | register_local_exception(handle scope, const char *name, handle base = PyExc_Exception) { |
2695 | | return detail::register_exception_impl<CppException>(scope, name, base, true /* isLocal */); |
2696 | | } |
2697 | | |
2698 | | PYBIND11_NAMESPACE_BEGIN(detail) |
2699 | 0 | PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) { |
2700 | 0 | auto strings = tuple(args.size()); |
2701 | 0 | for (size_t i = 0; i < args.size(); ++i) { |
2702 | 0 | strings[i] = str(args[i]); |
2703 | 0 | } |
2704 | 0 | auto sep = kwargs.contains("sep") ? kwargs["sep"] : str(" "); |
2705 | 0 | auto line = sep.attr("join")(std::move(strings)); |
2706 | 0 |
|
2707 | 0 | object file; |
2708 | 0 | if (kwargs.contains("file")) { |
2709 | 0 | file = kwargs["file"].cast<object>(); |
2710 | 0 | } else { |
2711 | 0 | try { |
2712 | 0 | file = module_::import("sys").attr("stdout"); |
2713 | 0 | } catch (const error_already_set &) { |
2714 | 0 | /* If print() is called from code that is executed as |
2715 | 0 | part of garbage collection during interpreter shutdown, |
2716 | 0 | importing 'sys' can fail. Give up rather than crashing the |
2717 | 0 | interpreter in this case. */ |
2718 | 0 | return; |
2719 | 0 | } |
2720 | 0 | } |
2721 | 0 |
|
2722 | 0 | auto write = file.attr("write"); |
2723 | 0 | write(std::move(line)); |
2724 | 0 | write(kwargs.contains("end") ? kwargs["end"] : str("\n")); |
2725 | 0 |
|
2726 | 0 | if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) { |
2727 | 0 | file.attr("flush")(); |
2728 | 0 | } |
2729 | 0 | } |
2730 | | PYBIND11_NAMESPACE_END(detail) |
2731 | | |
2732 | | template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> |
2733 | | void print(Args &&...args) { |
2734 | | auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...); |
2735 | | detail::print(c.args(), c.kwargs()); |
2736 | | } |
2737 | | |
2738 | | inline void |
2739 | 3.83k | error_already_set::m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr) { |
2740 | 3.83k | gil_scoped_acquire gil; |
2741 | 3.83k | error_scope scope; |
2742 | 3.83k | delete raw_ptr; |
2743 | 3.83k | } |
2744 | | |
2745 | 0 | inline const char *error_already_set::what() const noexcept { |
2746 | 0 | gil_scoped_acquire gil; |
2747 | 0 | error_scope scope; |
2748 | 0 | return m_fetched_error->error_string().c_str(); |
2749 | 0 | } |
2750 | | |
2751 | | PYBIND11_NAMESPACE_BEGIN(detail) |
2752 | | |
2753 | | inline function |
2754 | 0 | get_type_override(const void *this_ptr, const type_info *this_type, const char *name) { |
2755 | 0 | handle self = get_object_handle(this_ptr, this_type); |
2756 | 0 | if (!self) { |
2757 | 0 | return function(); |
2758 | 0 | } |
2759 | 0 | handle type = type::handle_of(self); |
2760 | 0 | auto key = std::make_pair(type.ptr(), name); |
2761 | 0 |
|
2762 | 0 | /* Cache functions that aren't overridden in Python to avoid |
2763 | 0 | many costly Python dictionary lookups below */ |
2764 | 0 | bool not_overridden = with_internals([&key](internals &internals) { |
2765 | 0 | auto &cache = internals.inactive_override_cache; |
2766 | 0 | return cache.find(key) != cache.end(); |
2767 | 0 | }); |
2768 | 0 | if (not_overridden) { |
2769 | 0 | return function(); |
2770 | 0 | } |
2771 | 0 |
|
2772 | 0 | function override = getattr(self, name, function()); |
2773 | 0 | if (override.is_cpp_function()) { |
2774 | 0 | with_internals([&](internals &internals) { |
2775 | 0 | internals.inactive_override_cache.insert(std::move(key)); |
2776 | 0 | }); |
2777 | 0 | return function(); |
2778 | 0 | } |
2779 | 0 |
|
2780 | 0 | /* Don't call dispatch code if invoked from overridden function. |
2781 | 0 | Unfortunately this doesn't work on PyPy and GraalPy. */ |
2782 | 0 | #if !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON) |
2783 | 0 | # if PY_VERSION_HEX >= 0x03090000 |
2784 | 0 | PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get()); |
2785 | 0 | if (frame != nullptr) { |
2786 | 0 | PyCodeObject *f_code = PyFrame_GetCode(frame); |
2787 | 0 | // f_code is guaranteed to not be NULL |
2788 | 0 | if ((std::string) str(f_code->co_name) == name && f_code->co_argcount > 0) { |
2789 | 0 | # if PY_VERSION_HEX >= 0x030d0000 |
2790 | 0 | PyObject *locals = PyEval_GetFrameLocals(); |
2791 | 0 | # else |
2792 | 0 | PyObject *locals = PyEval_GetLocals(); |
2793 | 0 | Py_XINCREF(locals); |
2794 | 0 | # endif |
2795 | 0 | if (locals != nullptr) { |
2796 | 0 | # if PY_VERSION_HEX >= 0x030b0000 |
2797 | 0 | PyObject *co_varnames = PyCode_GetVarnames(f_code); |
2798 | 0 | # else |
2799 | 0 | PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code, "co_varnames"); |
2800 | 0 | # endif |
2801 | 0 | PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0); |
2802 | 0 | Py_DECREF(co_varnames); |
2803 | 0 | PyObject *self_caller = dict_getitem(locals, self_arg); |
2804 | 0 | Py_DECREF(locals); |
2805 | 0 | if (self_caller == self.ptr()) { |
2806 | 0 | Py_DECREF(f_code); |
2807 | 0 | Py_DECREF(frame); |
2808 | 0 | return function(); |
2809 | 0 | } |
2810 | 0 | } |
2811 | 0 | } |
2812 | 0 | Py_DECREF(f_code); |
2813 | 0 | Py_DECREF(frame); |
2814 | 0 | } |
2815 | 0 | # else |
2816 | 0 | PyFrameObject *frame = PyThreadState_Get()->frame; |
2817 | 0 | if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name |
2818 | 0 | && frame->f_code->co_argcount > 0) { |
2819 | 0 | PyFrame_FastToLocals(frame); |
2820 | 0 | PyObject *self_caller |
2821 | 0 | = dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0)); |
2822 | 0 | if (self_caller == self.ptr()) { |
2823 | 0 | return function(); |
2824 | 0 | } |
2825 | 0 | } |
2826 | 0 | # endif |
2827 | 0 |
|
2828 | 0 | #else |
2829 | 0 | /* PyPy currently doesn't provide a detailed cpyext emulation of |
2830 | 0 | frame objects, so we have to emulate this using Python. This |
2831 | 0 | is going to be slow..*/ |
2832 | 0 | dict d; |
2833 | 0 | d["self"] = self; |
2834 | 0 | d["name"] = pybind11::str(name); |
2835 | 0 | PyObject *result |
2836 | 0 | = PyRun_String("import inspect\n" |
2837 | 0 | "frame = inspect.currentframe()\n" |
2838 | 0 | "if frame is not None:\n" |
2839 | 0 | " frame = frame.f_back\n" |
2840 | 0 | " if frame is not None and str(frame.f_code.co_name) == name and " |
2841 | 0 | "frame.f_code.co_argcount > 0:\n" |
2842 | 0 | " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n" |
2843 | 0 | " if self_caller == self:\n" |
2844 | 0 | " self = None\n", |
2845 | 0 | Py_file_input, |
2846 | 0 | d.ptr(), |
2847 | 0 | d.ptr()); |
2848 | 0 | if (result == nullptr) |
2849 | 0 | throw error_already_set(); |
2850 | 0 | Py_DECREF(result); |
2851 | 0 | if (d["self"].is_none()) |
2852 | 0 | return function(); |
2853 | 0 | #endif |
2854 | 0 |
|
2855 | 0 | return override; |
2856 | 0 | } |
2857 | | PYBIND11_NAMESPACE_END(detail) |
2858 | | |
2859 | | /** \rst |
2860 | | Try to retrieve a python method by the provided name from the instance pointed to by the |
2861 | | this_ptr. |
2862 | | |
2863 | | :this_ptr: The pointer to the object the overridden method should be retrieved for. This should |
2864 | | be the first non-trampoline class encountered in the inheritance chain. |
2865 | | :name: The name of the overridden Python method to retrieve. |
2866 | | :return: The Python method by this name from the object or an empty function wrapper. |
2867 | | \endrst */ |
2868 | | template <class T> |
2869 | | function get_override(const T *this_ptr, const char *name) { |
2870 | | auto *tinfo = detail::get_type_info(typeid(T)); |
2871 | | return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function(); |
2872 | | } |
2873 | | |
2874 | | #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \ |
2875 | | do { \ |
2876 | | pybind11::gil_scoped_acquire gil; \ |
2877 | | pybind11::function override \ |
2878 | | = pybind11::get_override(static_cast<const cname *>(this), name); \ |
2879 | | if (override) { \ |
2880 | | auto o = override(__VA_ARGS__); \ |
2881 | | PYBIND11_WARNING_PUSH \ |
2882 | | PYBIND11_WARNING_DISABLE_MSVC(4127) \ |
2883 | | if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value \ |
2884 | | && !pybind11::detail::is_same_ignoring_cvref<ret_type, PyObject *>::value) { \ |
2885 | | static pybind11::detail::override_caster_t<ret_type> caster; \ |
2886 | | return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \ |
2887 | | } \ |
2888 | | PYBIND11_WARNING_POP \ |
2889 | | return pybind11::detail::cast_safe<ret_type>(std::move(o)); \ |
2890 | | } \ |
2891 | | } while (false) |
2892 | | |
2893 | | /** \rst |
2894 | | Macro to populate the virtual method in the trampoline class. This macro tries to look up a |
2895 | | method named 'fn' from the Python side, deals with the :ref:`gil` and necessary argument |
2896 | | conversions to call this method and return the appropriate type. |
2897 | | See :ref:`overriding_virtuals` for more information. This macro should be used when the method |
2898 | | name in C is not the same as the method name in Python. For example with `__str__`. |
2899 | | |
2900 | | .. code-block:: cpp |
2901 | | |
2902 | | std::string toString() override { |
2903 | | PYBIND11_OVERRIDE_NAME( |
2904 | | std::string, // Return type (ret_type) |
2905 | | Animal, // Parent class (cname) |
2906 | | "__str__", // Name of method in Python (name) |
2907 | | toString, // Name of function in C++ (fn) |
2908 | | ); |
2909 | | } |
2910 | | \endrst */ |
2911 | | #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \ |
2912 | | do { \ |
2913 | | PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \ |
2914 | | return cname::fn(__VA_ARGS__); \ |
2915 | | } while (false) |
2916 | | |
2917 | | /** \rst |
2918 | | Macro for pure virtual functions, this function is identical to |
2919 | | :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it throws if no override can be found. |
2920 | | \endrst */ |
2921 | | #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \ |
2922 | | do { \ |
2923 | | PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \ |
2924 | | pybind11::pybind11_fail( \ |
2925 | | "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \ |
2926 | | } while (false) |
2927 | | |
2928 | | /** \rst |
2929 | | Macro to populate the virtual method in the trampoline class. This macro tries to look up the |
2930 | | method from the Python side, deals with the :ref:`gil` and necessary argument conversions to |
2931 | | call this method and return the appropriate type. This macro should be used if the method name |
2932 | | in C and in Python are identical. |
2933 | | See :ref:`overriding_virtuals` for more information. |
2934 | | |
2935 | | .. code-block:: cpp |
2936 | | |
2937 | | class PyAnimal : public Animal { |
2938 | | public: |
2939 | | // Inherit the constructors |
2940 | | using Animal::Animal; |
2941 | | |
2942 | | // Trampoline (need one for each virtual function) |
2943 | | std::string go(int n_times) override { |
2944 | | PYBIND11_OVERRIDE_PURE( |
2945 | | std::string, // Return type (ret_type) |
2946 | | Animal, // Parent class (cname) |
2947 | | go, // Name of function in C++ (must match Python name) (fn) |
2948 | | n_times // Argument(s) (...) |
2949 | | ); |
2950 | | } |
2951 | | }; |
2952 | | \endrst */ |
2953 | | #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \ |
2954 | | PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__) |
2955 | | |
2956 | | /** \rst |
2957 | | Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`, |
2958 | | except that it throws if no override can be found. |
2959 | | \endrst */ |
2960 | | #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \ |
2961 | | PYBIND11_OVERRIDE_PURE_NAME( \ |
2962 | | PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__) |
2963 | | |
2964 | | // Deprecated versions |
2965 | | |
2966 | | PYBIND11_DEPRECATED("get_type_overload has been deprecated") |
2967 | | inline function |
2968 | 0 | get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) { |
2969 | 0 | return detail::get_type_override(this_ptr, this_type, name); |
2970 | 0 | } |
2971 | | |
2972 | | template <class T> |
2973 | | inline function get_overload(const T *this_ptr, const char *name) { |
2974 | | return get_override(this_ptr, name); |
2975 | | } |
2976 | | |
2977 | | #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \ |
2978 | | PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) |
2979 | | #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \ |
2980 | | PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__) |
2981 | | #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \ |
2982 | | PYBIND11_OVERRIDE_PURE_NAME( \ |
2983 | | PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__); |
2984 | | #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \ |
2985 | | PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__) |
2986 | | #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \ |
2987 | | PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__); |
2988 | | |
2989 | | PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) |