1 diff -Nur pythia8309.orig/plugins/python/include/pybind11/attr.h pythia8309/plugins/python/include/pybind11/attr.h
2 --- pythia8309.orig/plugins/python/include/pybind11/attr.h 2023-02-16 18:12:45.000000000 +0100
3 +++ pythia8309/plugins/python/include/pybind11/attr.h 2023-03-13 09:52:25.449021580 +0100
8 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
11 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
13 /// \addtogroup annotations
16 /// Annotation for methods
17 -struct is_method { handle class_; is_method(const handle &c) : class_(c) { } };
20 + explicit is_method(const handle &c) : class_(c) {}
23 /// Annotation for operators
24 -struct is_operator { };
25 +struct is_operator {};
27 +/// Annotation for classes that cannot be subclassed
30 /// Annotation for parent scope
31 -struct scope { handle value; scope(const handle &s) : value(s) { } };
34 + explicit scope(const handle &s) : value(s) {}
37 /// Annotation for documentation
38 -struct doc { const char *value; doc(const char *value) : value(value) { } };
41 + explicit doc(const char *value) : value(value) {}
44 /// Annotation for function names
45 -struct name { const char *value; name(const char *value) : value(value) { } };
48 + explicit name(const char *value) : value(value) {}
51 /// Annotation indicating that a function is an overload associated with a given "sibling"
52 -struct sibling { handle value; sibling(const handle &value) : value(value.ptr()) { } };
55 + explicit sibling(const handle &value) : value(value.ptr()) {}
58 /// Annotation indicating that a class derives from another given type
59 -template <typename T> struct base {
60 - PYBIND11_DEPRECATED("base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
62 +template <typename T>
65 + PYBIND11_DEPRECATED(
66 + "base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
67 + base() {} // NOLINT(modernize-use-equals-default): breaks MSVC 2015 when adding an attribute
70 /// Keep patient alive while nurse lives
71 -template <size_t Nurse, size_t Patient> struct keep_alive { };
72 +template <size_t Nurse, size_t Patient>
73 +struct keep_alive {};
75 /// Annotation indicating that a class is involved in a multiple inheritance relationship
76 -struct multiple_inheritance { };
77 +struct multiple_inheritance {};
79 /// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
80 -struct dynamic_attr { };
81 +struct dynamic_attr {};
83 /// Annotation which enables the buffer protocol for a type
84 -struct buffer_protocol { };
85 +struct buffer_protocol {};
87 /// Annotation which requests that a special metaclass is created for a type
91 PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
92 + // NOLINTNEXTLINE(modernize-use-equals-default): breaks MSVC 2015 when adding an attribute
95 /// Override pybind11's default metaclass
96 - explicit metaclass(handle value) : value(value) { }
97 + explicit metaclass(handle value) : value(value) {}
100 +/// Specifies a custom callback with signature `void (PyHeapTypeObject*)` that
101 +/// may be used to customize the Python type.
103 +/// The callback is invoked immediately before `PyType_Ready`.
105 +/// Note: This is an advanced interface, and uses of it may require changes to
106 +/// work with later versions of pybind11. You may wish to consult the
107 +/// implementation of `make_new_python_type` in `detail/classes.h` to understand
108 +/// the context in which the callback will be run.
109 +struct custom_type_setup {
110 + using callback = std::function<void(PyHeapTypeObject *heap_type)>;
112 + explicit custom_type_setup(callback value) : value(std::move(value)) {}
117 /// Annotation that marks a class as local to the module:
118 -struct module_local { const bool value; constexpr module_local(bool v = true) : value(v) { } };
119 +struct module_local {
121 + constexpr explicit module_local(bool v = true) : value(v) {}
124 /// Annotation to mark enums as an arithmetic type
125 -struct arithmetic { };
126 +struct arithmetic {};
128 +/// Mark a function for addition at the beginning of the existing overload chain instead of the end
132 A call policy which places one or more guard variables (``Ts...``) around the function call.
134 return foo(args...); // forwarded arguments
137 -template <typename... Ts> struct call_guard;
138 +template <typename... Ts>
141 -template <> struct call_guard<> { using type = detail::void_type; };
143 +struct call_guard<> {
144 + using type = detail::void_type;
147 template <typename T>
148 struct call_guard<T> {
149 @@ -110,13 +162,14 @@
153 -NAMESPACE_BEGIN(detail)
154 +PYBIND11_NAMESPACE_BEGIN(detail)
155 /* Forward declarations */
159 -template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_;
160 -inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
161 +template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t>
163 +void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
165 /// Internal data structure which holds metadata about a keyword argument
166 struct argument_record {
167 @@ -127,14 +180,16 @@
168 bool none : 1; ///< True if None is allowed when loading
170 argument_record(const char *name, const char *descr, handle value, bool convert, bool none)
171 - : name(name), descr(descr), value(value), convert(convert), none(none) { }
172 + : name(name), descr(descr), value(value), convert(convert), none(none) {}
175 -/// Internal data structure which holds metadata about a bound function (signature, overloads, etc.)
176 +/// Internal data structure which holds metadata about a bound function (signature, overloads,
178 struct function_record {
180 : is_constructor(false), is_new_style_constructor(false), is_stateless(false),
181 - is_operator(false), has_args(false), has_kwargs(false), is_method(false) { }
182 + is_operator(false), is_method(false), has_args(false), has_kwargs(false),
186 char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
187 @@ -149,13 +204,13 @@
188 std::vector<argument_record> args;
190 /// Pointer to lambda function which converts arguments and performs the actual call
191 - handle (*impl) (function_call &) = nullptr;
192 + handle (*impl)(function_call &) = nullptr;
194 /// Storage for the wrapped function pointer and captured data, if any
195 - void *data[3] = { };
196 + void *data[3] = {};
198 /// Pointer to custom destructor for 'data' (if needed)
199 - void (*free_data) (function_record *ptr) = nullptr;
200 + void (*free_data)(function_record *ptr) = nullptr;
202 /// Return value policy associated with this function
203 return_value_policy policy = return_value_policy::automatic;
204 @@ -172,18 +227,28 @@
205 /// True if this is an operator (__add__), etc.
206 bool is_operator : 1;
208 + /// True if this is a method
209 + bool is_method : 1;
211 /// True if the function has a '*args' argument
214 /// True if the function has a '**kwargs' argument
217 - /// True if this is a method
218 - bool is_method : 1;
219 + /// True if this function is to be inserted at the beginning of the overload resolution chain
222 /// Number of arguments (including py::args and/or py::kwargs, if present)
225 + /// Number of leading positional arguments, which are terminated by a py::args or py::kwargs
226 + /// argument or by a py::kw_only annotation.
227 + std::uint16_t nargs_pos = 0;
229 + /// Number of leading arguments (counted in `nargs`) that are positional-only
230 + std::uint16_t nargs_pos_only = 0;
232 /// Python method object
233 PyMethodDef *def = nullptr;
236 /// Special data structure which (temporarily) holds metadata about a bound class
238 PYBIND11_NOINLINE type_record()
239 - : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false), module_local(false) { }
240 + : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false),
241 + default_holder(true), module_local(false), is_final(false) {}
243 /// Handle to the parent scope
246 /// Custom metaclass (optional)
249 + /// Custom type setup.
250 + custom_type_setup::callback custom_type_setup_callback;
252 /// Multiple inheritance marker
253 bool multiple_inheritance : 1;
255 @@ -253,42 +322,46 @@
256 /// Is the class definition local to the module shared object?
257 bool module_local : 1;
259 - PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *)) {
260 - auto base_info = detail::get_type_info(base, false);
261 + /// Is the class inheritable from python classes?
264 + PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *) ) {
265 + auto *base_info = detail::get_type_info(base, false);
267 std::string tname(base.name());
268 detail::clean_type_id(tname);
269 - pybind11_fail("generic_type: type \"" + std::string(name) +
270 - "\" referenced unknown base type \"" + tname + "\"");
271 + pybind11_fail("generic_type: type \"" + std::string(name)
272 + + "\" referenced unknown base type \"" + tname + "\"");
275 if (default_holder != base_info->default_holder) {
276 std::string tname(base.name());
277 detail::clean_type_id(tname);
278 - pybind11_fail("generic_type: type \"" + std::string(name) + "\" " +
279 - (default_holder ? "does not have" : "has") +
280 - " a non-default holder type while its base \"" + tname + "\" " +
281 - (base_info->default_holder ? "does not" : "does"));
282 + pybind11_fail("generic_type: type \"" + std::string(name) + "\" "
283 + + (default_holder ? "does not have" : "has")
284 + + " a non-default holder type while its base \"" + tname + "\" "
285 + + (base_info->default_holder ? "does not" : "does"));
288 bases.append((PyObject *) base_info->type);
290 - if (base_info->type->tp_dictoffset != 0)
291 + if (base_info->type->tp_dictoffset != 0) {
297 base_info->implicit_casts.emplace_back(type, caster);
302 -inline function_call::function_call(const function_record &f, handle p) :
303 - func(f), parent(p) {
304 +inline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) {
305 args.reserve(f.nargs);
306 args_convert.reserve(f.nargs);
309 /// Tag for a new-style `__init__` defined in `detail/init.h`
310 -struct is_new_style_constructor { };
311 +struct is_new_style_constructor {};
314 * Partial template specializations to process custom attributes provided to
315 @@ -296,92 +369,133 @@
316 * fields in the type_record and function_record data structures or executed at
317 * runtime to deal with custom call policies (e.g. keep_alive).
319 -template <typename T, typename SFINAE = void> struct process_attribute;
320 +template <typename T, typename SFINAE = void>
321 +struct process_attribute;
323 -template <typename T> struct process_attribute_default {
324 +template <typename T>
325 +struct process_attribute_default {
326 /// Default implementation: do nothing
327 - static void init(const T &, function_record *) { }
328 - static void init(const T &, type_record *) { }
329 - static void precall(function_call &) { }
330 - static void postcall(function_call &, handle) { }
331 + static void init(const T &, function_record *) {}
332 + static void init(const T &, type_record *) {}
333 + static void precall(function_call &) {}
334 + static void postcall(function_call &, handle) {}
337 /// Process an attribute specifying the function's name
338 -template <> struct process_attribute<name> : process_attribute_default<name> {
340 +struct process_attribute<name> : process_attribute_default<name> {
341 static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
344 /// Process an attribute specifying the function's docstring
345 -template <> struct process_attribute<doc> : process_attribute_default<doc> {
347 +struct process_attribute<doc> : process_attribute_default<doc> {
348 static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
351 /// Process an attribute specifying the function's docstring (provided as a C-style string)
352 -template <> struct process_attribute<const char *> : process_attribute_default<const char *> {
354 +struct process_attribute<const char *> : process_attribute_default<const char *> {
355 static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
356 static void init(const char *d, type_record *r) { r->doc = const_cast<char *>(d); }
358 -template <> struct process_attribute<char *> : process_attribute<const char *> { };
360 +struct process_attribute<char *> : process_attribute<const char *> {};
362 /// Process an attribute indicating the function's return value policy
363 -template <> struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
365 +struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
366 static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
369 -/// Process an attribute which indicates that this is an overloaded function associated with a given sibling
370 -template <> struct process_attribute<sibling> : process_attribute_default<sibling> {
371 +/// Process an attribute which indicates that this is an overloaded function associated with a
374 +struct process_attribute<sibling> : process_attribute_default<sibling> {
375 static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
378 /// Process an attribute which indicates that this function is a method
379 -template <> struct process_attribute<is_method> : process_attribute_default<is_method> {
380 - static void init(const is_method &s, function_record *r) { r->is_method = true; r->scope = s.class_; }
382 +struct process_attribute<is_method> : process_attribute_default<is_method> {
383 + static void init(const is_method &s, function_record *r) {
384 + r->is_method = true;
385 + r->scope = s.class_;
389 /// Process an attribute which indicates the parent scope of a method
390 -template <> struct process_attribute<scope> : process_attribute_default<scope> {
392 +struct process_attribute<scope> : process_attribute_default<scope> {
393 static void init(const scope &s, function_record *r) { r->scope = s.value; }
396 /// Process an attribute which indicates that this function is an operator
397 -template <> struct process_attribute<is_operator> : process_attribute_default<is_operator> {
399 +struct process_attribute<is_operator> : process_attribute_default<is_operator> {
400 static void init(const is_operator &, function_record *r) { r->is_operator = true; }
403 -template <> struct process_attribute<is_new_style_constructor> : process_attribute_default<is_new_style_constructor> {
404 - static void init(const is_new_style_constructor &, function_record *r) { r->is_new_style_constructor = true; }
406 +struct process_attribute<is_new_style_constructor>
407 + : process_attribute_default<is_new_style_constructor> {
408 + static void init(const is_new_style_constructor &, function_record *r) {
409 + r->is_new_style_constructor = true;
413 +inline void check_kw_only_arg(const arg &a, function_record *r) {
414 + if (r->args.size() > r->nargs_pos && (!a.name || a.name[0] == '\0')) {
415 + pybind11_fail("arg(): cannot specify an unnamed argument after a kw_only() annotation or "
416 + "args() argument");
420 +inline void append_self_arg_if_needed(function_record *r) {
421 + if (r->is_method && r->args.empty()) {
422 + r->args.emplace_back("self", nullptr, handle(), /*convert=*/true, /*none=*/false);
426 /// Process a keyword argument attribute (*without* a default value)
427 -template <> struct process_attribute<arg> : process_attribute_default<arg> {
429 +struct process_attribute<arg> : process_attribute_default<arg> {
430 static void init(const arg &a, function_record *r) {
431 - if (r->is_method && r->args.empty())
432 - r->args.emplace_back("self", nullptr, handle(), true /*convert*/, false /*none not allowed*/);
433 + append_self_arg_if_needed(r);
434 r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
436 + check_kw_only_arg(a, r);
440 /// Process a keyword argument attribute (*with* a default value)
441 -template <> struct process_attribute<arg_v> : process_attribute_default<arg_v> {
443 +struct process_attribute<arg_v> : process_attribute_default<arg_v> {
444 static void init(const arg_v &a, function_record *r) {
445 - if (r->is_method && r->args.empty())
446 - r->args.emplace_back("self", nullptr /*descr*/, handle() /*parent*/, true /*convert*/, false /*none not allowed*/);
447 + if (r->is_method && r->args.empty()) {
448 + r->args.emplace_back(
449 + "self", /*descr=*/nullptr, /*parent=*/handle(), /*convert=*/true, /*none=*/false);
454 std::string descr("'");
455 - if (a.name) descr += std::string(a.name) + ": ";
457 + descr += std::string(a.name) + ": ";
459 descr += a.type + "'";
462 - descr += " in method '" + (std::string) str(r->scope) + "." + (std::string) r->name + "'";
465 + descr += " in method '" + (std::string) str(r->scope) + "."
466 + + (std::string) r->name + "'";
468 descr += " in method of '" + (std::string) str(r->scope) + "'";
470 } else if (r->name) {
471 descr += " in function '" + (std::string) r->name + "'";
473 - pybind11_fail("arg(): could not convert default argument "
474 - + descr + " into a Python object (type not registered yet?)");
475 + pybind11_fail("arg(): could not convert default argument " + descr
476 + + " into a Python object (type not registered yet?)");
478 pybind11_fail("arg(): could not convert default argument "
479 "into a Python object (type not registered yet?). "
480 @@ -389,12 +503,42 @@
483 r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
485 + check_kw_only_arg(a, r);
489 +/// Process a keyword-only-arguments-follow pseudo argument
491 +struct process_attribute<kw_only> : process_attribute_default<kw_only> {
492 + static void init(const kw_only &, function_record *r) {
493 + append_self_arg_if_needed(r);
494 + if (r->has_args && r->nargs_pos != static_cast<std::uint16_t>(r->args.size())) {
495 + pybind11_fail("Mismatched args() and kw_only(): they must occur at the same relative "
496 + "argument location (or omit kw_only() entirely)");
498 + r->nargs_pos = static_cast<std::uint16_t>(r->args.size());
502 -/// Process a parent class attribute. Single inheritance only (class_ itself already guarantees that)
503 +/// Process a positional-only-argument maker
505 +struct process_attribute<pos_only> : process_attribute_default<pos_only> {
506 + static void init(const pos_only &, function_record *r) {
507 + append_self_arg_if_needed(r);
508 + r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size());
509 + if (r->nargs_pos_only > r->nargs_pos) {
510 + pybind11_fail("pos_only(): cannot follow a py::args() argument");
512 + // It also can't follow a kw_only, but a static_assert in pybind11.h checks that
516 +/// Process a parent class attribute. Single inheritance only (class_ itself already guarantees
518 template <typename T>
519 -struct process_attribute<T, enable_if_t<is_pyobject<T>::value>> : process_attribute_default<handle> {
520 +struct process_attribute<T, enable_if_t<is_pyobject<T>::value>>
521 + : process_attribute_default<handle> {
522 static void init(const handle &h, type_record *r) { r->bases.append(h); }
526 /// Process a multiple inheritance attribute
528 struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
529 - static void init(const multiple_inheritance &, type_record *r) { r->multiple_inheritance = true; }
530 + static void init(const multiple_inheritance &, type_record *r) {
531 + r->multiple_inheritance = true;
540 +struct process_attribute<custom_type_setup> {
541 + static void init(const custom_type_setup &value, type_record *r) {
542 + r->custom_type_setup_callback = value.value;
547 +struct process_attribute<is_final> : process_attribute_default<is_final> {
548 + static void init(const is_final &, type_record *r) { r->is_final = true; }
552 struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
553 static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
555 @@ -430,46 +588,70 @@
556 static void init(const module_local &l, type_record *r) { r->module_local = l.value; }
559 +/// Process a 'prepend' attribute, putting this at the beginning of the overload chain
561 +struct process_attribute<prepend> : process_attribute_default<prepend> {
562 + static void init(const prepend &, function_record *r) { r->prepend = true; }
565 /// Process an 'arithmetic' attribute for enums (does nothing here)
567 struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
569 template <typename... Ts>
570 -struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> { };
571 +struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> {};
574 * Process a keep_alive call policy -- invokes keep_alive_impl during the
575 * pre-call handler if both Nurse, Patient != 0 and use the post-call handler
578 -template <size_t Nurse, size_t Patient> struct process_attribute<keep_alive<Nurse, Patient>> : public process_attribute_default<keep_alive<Nurse, Patient>> {
579 +template <size_t Nurse, size_t Patient>
580 +struct process_attribute<keep_alive<Nurse, Patient>>
581 + : public process_attribute_default<keep_alive<Nurse, Patient>> {
582 template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
583 - static void precall(function_call &call) { keep_alive_impl(Nurse, Patient, call, handle()); }
584 + static void precall(function_call &call) {
585 + keep_alive_impl(Nurse, Patient, call, handle());
587 template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
588 - static void postcall(function_call &, handle) { }
589 + static void postcall(function_call &, handle) {}
590 template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
591 - static void precall(function_call &) { }
592 + static void precall(function_call &) {}
593 template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
594 - static void postcall(function_call &call, handle ret) { keep_alive_impl(Nurse, Patient, call, ret); }
595 + static void postcall(function_call &call, handle ret) {
596 + keep_alive_impl(Nurse, Patient, call, ret);
600 /// Recursively iterate over variadic template arguments
601 -template <typename... Args> struct process_attributes {
602 - static void init(const Args&... args, function_record *r) {
603 - int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0) ... };
604 - ignore_unused(unused);
606 - static void init(const Args&... args, type_record *r) {
607 - int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0) ... };
608 - ignore_unused(unused);
609 +template <typename... Args>
610 +struct process_attributes {
611 + static void init(const Args &...args, function_record *r) {
612 + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
613 + PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
614 + using expander = int[];
616 + 0, ((void) process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
618 + static void init(const Args &...args, type_record *r) {
619 + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
620 + PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
621 + using expander = int[];
623 + (process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
625 static void precall(function_call &call) {
626 - int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::precall(call), 0) ... };
627 - ignore_unused(unused);
628 + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call);
629 + using expander = int[];
631 + (process_attribute<typename std::decay<Args>::type>::precall(call), 0)...};
633 static void postcall(function_call &call, handle fn_ret) {
634 - int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0) ... };
635 - ignore_unused(unused);
636 + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret);
637 + PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret);
638 + using expander = int[];
640 + 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0)...};
644 @@ -483,10 +665,11 @@
645 /// Check the number of named arguments at compile time
646 template <typename... Extra,
647 size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
648 - size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
649 + size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
650 constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
651 - return named == 0 || (self + named + has_args + has_kwargs) == nargs;
652 + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs);
653 + return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs;
656 -NAMESPACE_END(detail)
657 -NAMESPACE_END(PYBIND11_NAMESPACE)
658 +PYBIND11_NAMESPACE_END(detail)
659 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
660 diff -Nur pythia8309.orig/plugins/python/include/pybind11/buffer_info.h pythia8309/plugins/python/include/pybind11/buffer_info.h
661 --- pythia8309.orig/plugins/python/include/pybind11/buffer_info.h 2023-02-16 18:12:45.000000000 +0100
662 +++ pythia8309/plugins/python/include/pybind11/buffer_info.h 2023-03-13 09:52:25.450021582 +0100
665 #include "detail/common.h"
667 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
668 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
670 +PYBIND11_NAMESPACE_BEGIN(detail)
672 +// Default, C-style strides
673 +inline std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
674 + auto ndim = shape.size();
675 + std::vector<ssize_t> strides(ndim, itemsize);
677 + for (size_t i = ndim - 1; i > 0; --i) {
678 + strides[i - 1] = strides[i] * shape[i];
684 +// F-style strides; default when constructing an array_t with `ExtraFlags & f_style`
685 +inline std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
686 + auto ndim = shape.size();
687 + std::vector<ssize_t> strides(ndim, itemsize);
688 + for (size_t i = 1; i < ndim; ++i) {
689 + strides[i] = strides[i - 1] * shape[i - 1];
694 +PYBIND11_NAMESPACE_END(detail)
696 /// Information record describing a Python buffer object
698 void *ptr = nullptr; // Pointer to the underlying storage
699 ssize_t itemsize = 0; // Size of individual items in bytes
700 ssize_t size = 0; // Total number of entries
701 - std::string format; // For homogeneous buffers, this should be set to format_descriptor<T>::format()
702 + std::string format; // For homogeneous buffers, this should be set to
703 + // format_descriptor<T>::format()
704 ssize_t ndim = 0; // Number of dimensions
705 std::vector<ssize_t> shape; // Shape of the tensor (1 entry per dimension)
706 - std::vector<ssize_t> strides; // Number of entries between adjacent entries (for each per dimension)
710 - buffer_info(void *ptr, ssize_t itemsize, const std::string &format, ssize_t ndim,
711 - detail::any_container<ssize_t> shape_in, detail::any_container<ssize_t> strides_in)
712 - : ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim),
713 - shape(std::move(shape_in)), strides(std::move(strides_in)) {
714 - if (ndim != (ssize_t) shape.size() || ndim != (ssize_t) strides.size())
715 + std::vector<ssize_t> strides; // Number of bytes between adjacent entries
716 + // (for each per dimension)
717 + bool readonly = false; // flag to indicate if the underlying storage may be written to
719 + buffer_info() = default;
721 + buffer_info(void *ptr,
723 + const std::string &format,
725 + detail::any_container<ssize_t> shape_in,
726 + detail::any_container<ssize_t> strides_in,
727 + bool readonly = false)
728 + : ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim),
729 + shape(std::move(shape_in)), strides(std::move(strides_in)), readonly(readonly) {
730 + if (ndim != (ssize_t) shape.size() || ndim != (ssize_t) strides.size()) {
731 pybind11_fail("buffer_info: ndim doesn't match shape and/or strides length");
732 - for (size_t i = 0; i < (size_t) ndim; ++i)
734 + for (size_t i = 0; i < (size_t) ndim; ++i) {
739 template <typename T>
740 - buffer_info(T *ptr, detail::any_container<ssize_t> shape_in, detail::any_container<ssize_t> strides_in)
741 - : buffer_info(private_ctr_tag(), ptr, sizeof(T), format_descriptor<T>::format(), static_cast<ssize_t>(shape_in->size()), std::move(shape_in), std::move(strides_in)) { }
742 + buffer_info(T *ptr,
743 + detail::any_container<ssize_t> shape_in,
744 + detail::any_container<ssize_t> strides_in,
745 + bool readonly = false)
746 + : buffer_info(private_ctr_tag(),
749 + format_descriptor<T>::format(),
750 + static_cast<ssize_t>(shape_in->size()),
751 + std::move(shape_in),
752 + std::move(strides_in),
755 + buffer_info(void *ptr,
757 + const std::string &format,
759 + bool readonly = false)
760 + : buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}, readonly) {}
762 - buffer_info(void *ptr, ssize_t itemsize, const std::string &format, ssize_t size)
763 - : buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}) { }
764 + template <typename T>
765 + buffer_info(T *ptr, ssize_t size, bool readonly = false)
766 + : buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size, readonly) {}
768 template <typename T>
769 - buffer_info(T *ptr, ssize_t size)
770 - : buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size) { }
771 + buffer_info(const T *ptr, ssize_t size, bool readonly = true)
773 + const_cast<T *>(ptr), sizeof(T), format_descriptor<T>::format(), size, readonly) {}
775 explicit buffer_info(Py_buffer *view, bool ownview = true)
776 - : buffer_info(view->buf, view->itemsize, view->format, view->ndim,
777 - {view->shape, view->shape + view->ndim}, {view->strides, view->strides + view->ndim}) {
784 + {view->shape, view->shape + view->ndim},
785 + /* Though buffer::request() requests PyBUF_STRIDES, ctypes objects
786 + * ignore this flag and return a view with NULL strides.
787 + * When strides are NULL, build them manually. */
789 + ? std::vector<ssize_t>(view->strides, view->strides + view->ndim)
790 + : detail::c_strides({view->shape, view->shape + view->ndim}, view->itemsize),
791 + (view->readonly != 0)) {
792 + // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
793 + this->m_view = view;
794 + // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
795 this->ownview = ownview;
798 buffer_info(const buffer_info &) = delete;
799 - buffer_info& operator=(const buffer_info &) = delete;
800 + buffer_info &operator=(const buffer_info &) = delete;
802 - buffer_info(buffer_info &&other) {
803 - (*this) = std::move(other);
805 + buffer_info(buffer_info &&other) noexcept { (*this) = std::move(other); }
807 - buffer_info& operator=(buffer_info &&rhs) {
808 + buffer_info &operator=(buffer_info &&rhs) noexcept {
810 itemsize = rhs.itemsize;
814 shape = std::move(rhs.shape);
815 strides = std::move(rhs.strides);
816 - std::swap(view, rhs.view);
817 + std::swap(m_view, rhs.m_view);
818 std::swap(ownview, rhs.ownview);
819 + readonly = rhs.readonly;
824 - if (view && ownview) { PyBuffer_Release(view); delete view; }
825 + if (m_view && ownview) {
826 + PyBuffer_Release(m_view);
831 + Py_buffer *view() const { return m_view; }
832 + Py_buffer *&view() { return m_view; }
835 - struct private_ctr_tag { };
836 + struct private_ctr_tag {};
838 - buffer_info(private_ctr_tag, void *ptr, ssize_t itemsize, const std::string &format, ssize_t ndim,
839 - detail::any_container<ssize_t> &&shape_in, detail::any_container<ssize_t> &&strides_in)
840 - : buffer_info(ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in)) { }
841 + buffer_info(private_ctr_tag,
844 + const std::string &format,
846 + detail::any_container<ssize_t> &&shape_in,
847 + detail::any_container<ssize_t> &&strides_in,
850 + ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in), readonly) {}
852 - Py_buffer *view = nullptr;
853 + Py_buffer *m_view = nullptr;
854 bool ownview = false;
857 -NAMESPACE_BEGIN(detail)
858 +PYBIND11_NAMESPACE_BEGIN(detail)
860 -template <typename T, typename SFINAE = void> struct compare_buffer_info {
861 - static bool compare(const buffer_info& b) {
862 +template <typename T, typename SFINAE = void>
863 +struct compare_buffer_info {
864 + static bool compare(const buffer_info &b) {
865 return b.format == format_descriptor<T>::format() && b.itemsize == (ssize_t) sizeof(T);
869 -template <typename T> struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> {
870 - static bool compare(const buffer_info& b) {
871 - return (size_t) b.itemsize == sizeof(T) && (b.format == format_descriptor<T>::value ||
872 - ((sizeof(T) == sizeof(long)) && b.format == (std::is_unsigned<T>::value ? "L" : "l")) ||
873 - ((sizeof(T) == sizeof(size_t)) && b.format == (std::is_unsigned<T>::value ? "N" : "n")));
874 +template <typename T>
875 +struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> {
876 + static bool compare(const buffer_info &b) {
877 + return (size_t) b.itemsize == sizeof(T)
878 + && (b.format == format_descriptor<T>::value
879 + || ((sizeof(T) == sizeof(long))
880 + && b.format == (std::is_unsigned<T>::value ? "L" : "l"))
881 + || ((sizeof(T) == sizeof(size_t))
882 + && b.format == (std::is_unsigned<T>::value ? "N" : "n")));
886 -NAMESPACE_END(detail)
887 -NAMESPACE_END(PYBIND11_NAMESPACE)
888 +PYBIND11_NAMESPACE_END(detail)
889 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
890 diff -Nur pythia8309.orig/plugins/python/include/pybind11/cast.h pythia8309/plugins/python/include/pybind11/cast.h
891 --- pythia8309.orig/plugins/python/include/pybind11/cast.h 2023-02-16 18:12:45.000000000 +0100
892 +++ pythia8309/plugins/python/include/pybind11/cast.h 2023-03-13 09:52:25.452021587 +0100
893 @@ -10,1006 +10,183 @@
897 -#include "pytypes.h"
898 -#include "detail/typeid.h"
899 +#include "detail/common.h"
900 #include "detail/descr.h"
901 -#include "detail/internals.h"
902 +#include "detail/type_caster_base.h"
903 +#include "detail/typeid.h"
904 +#include "pytypes.h"
909 +#include <functional>
915 #include <type_traits>
919 -#if defined(PYBIND11_CPP17)
920 -# if defined(__has_include)
921 -# if __has_include(<string_view>)
922 -# define PYBIND11_HAS_STRING_VIEW
924 -# elif defined(_MSC_VER)
925 -# define PYBIND11_HAS_STRING_VIEW
928 -#ifdef PYBIND11_HAS_STRING_VIEW
929 -#include <string_view>
932 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
933 -NAMESPACE_BEGIN(detail)
935 -/// A life support system for temporary objects created by `type_caster::load()`.
936 -/// Adding a patient will keep it alive up until the enclosing function returns.
937 -class loader_life_support {
939 - /// A new patient frame is created when a function is entered
940 - loader_life_support() {
941 - get_internals().loader_patient_stack.push_back(nullptr);
944 - /// ... and destroyed after it returns
945 - ~loader_life_support() {
946 - auto &stack = get_internals().loader_patient_stack;
948 - pybind11_fail("loader_life_support: internal error");
950 - auto ptr = stack.back();
954 - // A heuristic to reduce the stack's capacity (e.g. after long recursive calls)
955 - if (stack.capacity() > 16 && stack.size() != 0 && stack.capacity() / stack.size() > 2)
956 - stack.shrink_to_fit();
959 - /// This can only be used inside a pybind11-bound function, either by `argument_loader`
960 - /// at argument preparation time or by `py::cast()` at execution time.
961 - PYBIND11_NOINLINE static void add_patient(handle h) {
962 - auto &stack = get_internals().loader_patient_stack;
964 - throw cast_error("When called outside a bound function, py::cast() cannot "
965 - "do Python -> C++ conversions which require the creation "
966 - "of temporary values");
968 - auto &list_ptr = stack.back();
969 - if (list_ptr == nullptr) {
970 - list_ptr = PyList_New(1);
972 - pybind11_fail("loader_life_support: error allocating list");
973 - PyList_SET_ITEM(list_ptr, 0, h.inc_ref().ptr());
975 - auto result = PyList_Append(list_ptr, h.ptr());
977 - pybind11_fail("loader_life_support: error adding patient");
982 -// Gets the cache entry for the given type, creating it if necessary. The return value is the pair
983 -// returned by emplace, i.e. an iterator for the entry and a bool set to `true` if the entry was
985 -inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type);
987 -// Populates a just-created cache entry.
988 -PYBIND11_NOINLINE inline void all_type_info_populate(PyTypeObject *t, std::vector<type_info *> &bases) {
989 - std::vector<PyTypeObject *> check;
990 - for (handle parent : reinterpret_borrow<tuple>(t->tp_bases))
991 - check.push_back((PyTypeObject *) parent.ptr());
993 - auto const &type_dict = get_internals().registered_types_py;
994 - for (size_t i = 0; i < check.size(); i++) {
995 - auto type = check[i];
996 - // Ignore Python2 old-style class super type:
997 - if (!PyType_Check((PyObject *) type)) continue;
999 - // Check `type` in the current set of registered python types:
1000 - auto it = type_dict.find(type);
1001 - if (it != type_dict.end()) {
1002 - // We found a cache entry for it, so it's either pybind-registered or has pre-computed
1003 - // pybind bases, but we have to make sure we haven't already seen the type(s) before: we
1004 - // want to follow Python/virtual C++ rules that there should only be one instance of a
1006 - for (auto *tinfo : it->second) {
1007 - // NB: Could use a second set here, rather than doing a linear search, but since
1008 - // having a large number of immediate pybind11-registered types seems fairly
1009 - // unlikely, that probably isn't worthwhile.
1010 - bool found = false;
1011 - for (auto *known : bases) {
1012 - if (known == tinfo) { found = true; break; }
1014 - if (!found) bases.push_back(tinfo);
1017 - else if (type->tp_bases) {
1018 - // It's some python type, so keep follow its bases classes to look for one or more
1019 - // registered types
1020 - if (i + 1 == check.size()) {
1021 - // When we're at the end, we can pop off the current element to avoid growing
1022 - // `check` when adding just one base (which is typical--i.e. when there is no
1023 - // multiple inheritance)
1027 - for (handle parent : reinterpret_borrow<tuple>(type->tp_bases))
1028 - check.push_back((PyTypeObject *) parent.ptr());
1034 - * Extracts vector of type_info pointers of pybind-registered roots of the given Python type. Will
1035 - * be just 1 pybind type for the Python type of a pybind-registered class, or for any Python-side
1036 - * derived class that uses single inheritance. Will contain as many types as required for a Python
1037 - * class that uses multiple inheritance to inherit (directly or indirectly) from multiple
1038 - * pybind-registered classes. Will be empty if neither the type nor any base classes are
1039 - * pybind-registered.
1041 - * The value is cached for the lifetime of the Python type.
1043 -inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {
1044 - auto ins = all_type_info_get_cache(type);
1046 - // New cache entry: populate it
1047 - all_type_info_populate(type, ins.first->second);
1049 - return ins.first->second;
1053 - * Gets a single pybind11 type info for a python type. Returns nullptr if neither the type nor any
1054 - * ancestors are pybind11-registered. Throws an exception if there are multiple bases--use
1055 - * `all_type_info` instead if you want to support multiple bases.
1057 -PYBIND11_NOINLINE inline detail::type_info* get_type_info(PyTypeObject *type) {
1058 - auto &bases = all_type_info(type);
1059 - if (bases.size() == 0)
1061 - if (bases.size() > 1)
1062 - pybind11_fail("pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
1063 - return bases.front();
1066 -inline detail::type_info *get_local_type_info(const std::type_index &tp) {
1067 - auto &locals = registered_local_types_cpp();
1068 - auto it = locals.find(tp);
1069 - if (it != locals.end())
1070 - return it->second;
1074 -inline detail::type_info *get_global_type_info(const std::type_index &tp) {
1075 - auto &types = get_internals().registered_types_cpp;
1076 - auto it = types.find(tp);
1077 - if (it != types.end())
1078 - return it->second;
1082 -/// Return the type info for a given C++ type; on lookup failure can either throw or return nullptr.
1083 -PYBIND11_NOINLINE inline detail::type_info *get_type_info(const std::type_index &tp,
1084 - bool throw_if_missing = false) {
1085 - if (auto ltype = get_local_type_info(tp))
1087 - if (auto gtype = get_global_type_info(tp))
1090 - if (throw_if_missing) {
1091 - std::string tname = tp.name();
1092 - detail::clean_type_id(tname);
1093 - pybind11_fail("pybind11::detail::get_type_info: unable to find type info for \"" + tname + "\"");
1098 -PYBIND11_NOINLINE inline handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
1099 - detail::type_info *type_info = get_type_info(tp, throw_if_missing);
1100 - return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
1103 -struct value_and_holder {
1106 - const detail::type_info *type;
1109 - // Main constructor for a found value/holder:
1110 - value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index) :
1111 - inst{i}, index{index}, type{type},
1112 - vh{inst->simple_layout ? inst->simple_value_holder : &inst->nonsimple.values_and_holders[vpos]}
1115 - // Default constructor (used to signal a value-and-holder not found by get_value_and_holder())
1116 - value_and_holder() : inst{nullptr} {}
1118 - // Used for past-the-end iterator
1119 - value_and_holder(size_t index) : index{index} {}
1121 - template <typename V = void> V *&value_ptr() const {
1122 - return reinterpret_cast<V *&>(vh[0]);
1124 - // True if this `value_and_holder` has a non-null value pointer
1125 - explicit operator bool() const { return value_ptr(); }
1127 - template <typename H> H &holder() const {
1128 - return reinterpret_cast<H &>(vh[1]);
1130 - bool holder_constructed() const {
1131 - return inst->simple_layout
1132 - ? inst->simple_holder_constructed
1133 - : inst->nonsimple.status[index] & instance::status_holder_constructed;
1135 - void set_holder_constructed(bool v = true) {
1136 - if (inst->simple_layout)
1137 - inst->simple_holder_constructed = v;
1139 - inst->nonsimple.status[index] |= instance::status_holder_constructed;
1141 - inst->nonsimple.status[index] &= (uint8_t) ~instance::status_holder_constructed;
1143 - bool instance_registered() const {
1144 - return inst->simple_layout
1145 - ? inst->simple_instance_registered
1146 - : inst->nonsimple.status[index] & instance::status_instance_registered;
1148 - void set_instance_registered(bool v = true) {
1149 - if (inst->simple_layout)
1150 - inst->simple_instance_registered = v;
1152 - inst->nonsimple.status[index] |= instance::status_instance_registered;
1154 - inst->nonsimple.status[index] &= (uint8_t) ~instance::status_instance_registered;
1158 -// Container for accessing and iterating over an instance's values/holders
1159 -struct values_and_holders {
1162 - using type_vec = std::vector<detail::type_info *>;
1163 - const type_vec &tinfo;
1166 - values_and_holders(instance *inst) : inst{inst}, tinfo(all_type_info(Py_TYPE(inst))) {}
1171 - const type_vec *types;
1172 - value_and_holder curr;
1173 - friend struct values_and_holders;
1174 - iterator(instance *inst, const type_vec *tinfo)
1175 - : inst{inst}, types{tinfo},
1176 - curr(inst /* instance */,
1177 - types->empty() ? nullptr : (*types)[0] /* type info */,
1178 - 0, /* vpos: (non-simple types only): the first vptr comes first */
1181 - // Past-the-end iterator:
1182 - iterator(size_t end) : curr(end) {}
1184 - bool operator==(const iterator &other) { return curr.index == other.curr.index; }
1185 - bool operator!=(const iterator &other) { return curr.index != other.curr.index; }
1186 - iterator &operator++() {
1187 - if (!inst->simple_layout)
1188 - curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;
1190 - curr.type = curr.index < types->size() ? (*types)[curr.index] : nullptr;
1193 - value_and_holder &operator*() { return curr; }
1194 - value_and_holder *operator->() { return &curr; }
1197 - iterator begin() { return iterator(inst, &tinfo); }
1198 - iterator end() { return iterator(tinfo.size()); }
1200 - iterator find(const type_info *find_type) {
1201 - auto it = begin(), endit = end();
1202 - while (it != endit && it->type != find_type) ++it;
1206 - size_t size() { return tinfo.size(); }
1210 - * Extracts C++ value and holder pointer references from an instance (which may contain multiple
1211 - * values/holders for python-side multiple inheritance) that match the given type. Throws an error
1212 - * if the given type (or ValueType, if omitted) is not a pybind11 base of the given instance. If
1213 - * `find_type` is omitted (or explicitly specified as nullptr) the first value/holder are returned,
1214 - * regardless of type (and the resulting .type will be nullptr).
1216 - * The returned object should be short-lived: in particular, it must not outlive the called-upon
1219 -PYBIND11_NOINLINE inline value_and_holder instance::get_value_and_holder(const type_info *find_type /*= nullptr default in common.h*/, bool throw_if_missing /*= true in common.h*/) {
1220 - // Optimize common case:
1221 - if (!find_type || Py_TYPE(this) == find_type->type)
1222 - return value_and_holder(this, find_type, 0, 0);
1224 - detail::values_and_holders vhs(this);
1225 - auto it = vhs.find(find_type);
1226 - if (it != vhs.end())
1229 - if (!throw_if_missing)
1230 - return value_and_holder();
1232 -#if defined(NDEBUG)
1233 - pybind11_fail("pybind11::detail::instance::get_value_and_holder: "
1234 - "type is not a pybind11 base of the given instance "
1235 - "(compile in debug mode for type details)");
1237 - pybind11_fail("pybind11::detail::instance::get_value_and_holder: `" +
1238 - std::string(find_type->type->tp_name) + "' is not a pybind11 base of the given `" +
1239 - std::string(Py_TYPE(this)->tp_name) + "' instance");
1243 -PYBIND11_NOINLINE inline void instance::allocate_layout() {
1244 - auto &tinfo = all_type_info(Py_TYPE(this));
1246 - const size_t n_types = tinfo.size();
1249 - pybind11_fail("instance allocation failed: new instance has no pybind11-registered base types");
1252 - n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
1254 - // Simple path: no python-side multiple inheritance, and a small-enough holder
1255 - if (simple_layout) {
1256 - simple_value_holder[0] = nullptr;
1257 - simple_holder_constructed = false;
1258 - simple_instance_registered = false;
1260 - else { // multiple base types or a too-large holder
1261 - // Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
1262 - // [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
1263 - // values that tracks whether each associated holder has been initialized. Each [block] is
1264 - // padded, if necessary, to an integer multiple of sizeof(void *).
1266 - for (auto t : tinfo) {
1267 - space += 1; // value pointer
1268 - space += t->holder_size_in_ptrs; // holder instance
1270 - size_t flags_at = space;
1271 - space += size_in_ptrs(n_types); // status bytes (holder_constructed and instance_registered)
1273 - // Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
1274 - // in particular, need to be 0). Use Python's memory allocation functions: in Python 3.6
1275 - // they default to using pymalloc, which is designed to be efficient for small allocations
1276 - // like the one we're doing here; in earlier versions (and for larger allocations) they are
1277 - // just wrappers around malloc.
1278 -#if PY_VERSION_HEX >= 0x03050000
1279 - nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
1280 - if (!nonsimple.values_and_holders) throw std::bad_alloc();
1282 - nonsimple.values_and_holders = (void **) PyMem_New(void *, space);
1283 - if (!nonsimple.values_and_holders) throw std::bad_alloc();
1284 - std::memset(nonsimple.values_and_holders, 0, space * sizeof(void *));
1286 - nonsimple.status = reinterpret_cast<uint8_t *>(&nonsimple.values_and_holders[flags_at]);
1291 -PYBIND11_NOINLINE inline void instance::deallocate_layout() {
1292 - if (!simple_layout)
1293 - PyMem_Free(nonsimple.values_and_holders);
1296 -PYBIND11_NOINLINE inline bool isinstance_generic(handle obj, const std::type_info &tp) {
1297 - handle type = detail::get_type_handle(tp, false);
1300 - return isinstance(obj, type);
1303 -PYBIND11_NOINLINE inline std::string error_string() {
1304 - if (!PyErr_Occurred()) {
1305 - PyErr_SetString(PyExc_RuntimeError, "Unknown internal error occurred");
1306 - return "Unknown internal error occurred";
1309 - error_scope scope; // Preserve error state
1311 - std::string errorString;
1313 - errorString += handle(scope.type).attr("__name__").cast<std::string>();
1314 - errorString += ": ";
1317 - errorString += (std::string) str(scope.value);
1318 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
1319 +PYBIND11_NAMESPACE_BEGIN(detail)
1321 - PyErr_NormalizeException(&scope.type, &scope.value, &scope.trace);
1323 -#if PY_MAJOR_VERSION >= 3
1324 - if (scope.trace != nullptr)
1325 - PyException_SetTraceback(scope.value, scope.trace);
1328 -#if !defined(PYPY_VERSION)
1329 - if (scope.trace) {
1330 - PyTracebackObject *trace = (PyTracebackObject *) scope.trace;
1332 - /* Get the deepest trace possible */
1333 - while (trace->tb_next)
1334 - trace = trace->tb_next;
1336 - PyFrameObject *frame = trace->tb_frame;
1337 - errorString += "\n\nAt:\n";
1339 - int lineno = PyFrame_GetLineNumber(frame);
1341 - " " + handle(frame->f_code->co_filename).cast<std::string>() +
1342 - "(" + std::to_string(lineno) + "): " +
1343 - handle(frame->f_code->co_name).cast<std::string>() + "\n";
1344 - frame = frame->f_back;
1349 - return errorString;
1352 -PYBIND11_NOINLINE inline handle get_object_handle(const void *ptr, const detail::type_info *type ) {
1353 - auto &instances = get_internals().registered_instances;
1354 - auto range = instances.equal_range(ptr);
1355 - for (auto it = range.first; it != range.second; ++it) {
1356 - for (auto vh : values_and_holders(it->second)) {
1357 - if (vh.type == type)
1358 - return handle((PyObject *) it->second);
1364 -inline PyThreadState *get_thread_state_unchecked() {
1365 -#if defined(PYPY_VERSION)
1366 - return PyThreadState_GET();
1367 -#elif PY_VERSION_HEX < 0x03000000
1368 - return _PyThreadState_Current;
1369 -#elif PY_VERSION_HEX < 0x03050000
1370 - return (PyThreadState*) _Py_atomic_load_relaxed(&_PyThreadState_Current);
1371 -#elif PY_VERSION_HEX < 0x03050200
1372 - return (PyThreadState*) _PyThreadState_Current.value;
1374 - return _PyThreadState_UncheckedGet();
1378 -// Forward declarations
1379 -inline void keep_alive_impl(handle nurse, handle patient);
1380 -inline PyObject *make_new_instance(PyTypeObject *type);
1382 -class type_caster_generic {
1384 - PYBIND11_NOINLINE type_caster_generic(const std::type_info &type_info)
1385 - : typeinfo(get_type_info(type_info)), cpptype(&type_info) { }
1387 - type_caster_generic(const type_info *typeinfo)
1388 - : typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) { }
1390 - bool load(handle src, bool convert) {
1391 - return load_impl<type_caster_generic>(src, convert);
1394 - PYBIND11_NOINLINE static handle cast(const void *_src, return_value_policy policy, handle parent,
1395 - const detail::type_info *tinfo,
1396 - void *(*copy_constructor)(const void *),
1397 - void *(*move_constructor)(const void *),
1398 - const void *existing_holder = nullptr) {
1399 - if (!tinfo) // no type info: error will be set already
1402 - void *src = const_cast<void *>(_src);
1403 - if (src == nullptr)
1404 - return none().release();
1406 - auto it_instances = get_internals().registered_instances.equal_range(src);
1407 - for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
1408 - for (auto instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
1409 - if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype))
1410 - return handle((PyObject *) it_i->second).inc_ref();
1414 - auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
1415 - auto wrapper = reinterpret_cast<instance *>(inst.ptr());
1416 - wrapper->owned = false;
1417 - void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
1420 - case return_value_policy::automatic:
1421 - case return_value_policy::take_ownership:
1423 - wrapper->owned = true;
1426 - case return_value_policy::automatic_reference:
1427 - case return_value_policy::reference:
1429 - wrapper->owned = false;
1432 - case return_value_policy::copy:
1433 - if (copy_constructor)
1434 - valueptr = copy_constructor(src);
1436 - throw cast_error("return_value_policy = copy, but the "
1437 - "object is non-copyable!");
1438 - wrapper->owned = true;
1441 - case return_value_policy::move:
1442 - if (move_constructor)
1443 - valueptr = move_constructor(src);
1444 - else if (copy_constructor)
1445 - valueptr = copy_constructor(src);
1447 - throw cast_error("return_value_policy = move, but the "
1448 - "object is neither movable nor copyable!");
1449 - wrapper->owned = true;
1452 - case return_value_policy::reference_internal:
1454 - wrapper->owned = false;
1455 - keep_alive_impl(inst, parent);
1459 - throw cast_error("unhandled return_value_policy: should not happen!");
1462 - tinfo->init_instance(wrapper, existing_holder);
1464 - return inst.release();
1467 - // Base methods for generic caster; there are overridden in copyable_holder_caster
1468 - void load_value(value_and_holder &&v_h) {
1469 - auto *&vptr = v_h.value_ptr();
1470 - // Lazy allocation for unallocated values:
1471 - if (vptr == nullptr) {
1472 - auto *type = v_h.type ? v_h.type : typeinfo;
1473 - if (type->operator_new) {
1474 - vptr = type->operator_new(type->type_size);
1476 - #if defined(PYBIND11_CPP17)
1477 - if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
1478 - vptr = ::operator new(type->type_size,
1479 - (std::align_val_t) type->type_align);
1482 - vptr = ::operator new(type->type_size);
1487 - bool try_implicit_casts(handle src, bool convert) {
1488 - for (auto &cast : typeinfo->implicit_casts) {
1489 - type_caster_generic sub_caster(*cast.first);
1490 - if (sub_caster.load(src, convert)) {
1491 - value = cast.second(sub_caster.value);
1497 - bool try_direct_conversions(handle src) {
1498 - for (auto &converter : *typeinfo->direct_conversions) {
1499 - if (converter(src.ptr(), value))
1504 - void check_holder_compat() {}
1506 - PYBIND11_NOINLINE static void *local_load(PyObject *src, const type_info *ti) {
1507 - auto caster = type_caster_generic(ti);
1508 - if (caster.load(src, false))
1509 - return caster.value;
1513 - /// Try to load with foreign typeinfo, if available. Used when there is no
1514 - /// native typeinfo, or when the native one wasn't able to produce a value.
1515 - PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) {
1516 - constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;
1517 - const auto pytype = src.get_type();
1518 - if (!hasattr(pytype, local_key))
1521 - type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
1522 - // Only consider this foreign loader if actually foreign and is a loader of the correct cpp type
1523 - if (foreign_typeinfo->module_local_load == &local_load
1524 - || (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype)))
1527 - if (auto result = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo)) {
1534 - // Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant
1535 - // bits of code between here and copyable_holder_caster where the two classes need different
1536 - // logic (without having to resort to virtual inheritance).
1537 - template <typename ThisT>
1538 - PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
1539 - if (!src) return false;
1540 - if (!typeinfo) return try_load_foreign_module_local(src);
1541 - if (src.is_none()) {
1542 - // Defer accepting None to other overloads (if we aren't in convert mode):
1543 - if (!convert) return false;
1548 - auto &this_ = static_cast<ThisT &>(*this);
1549 - this_.check_holder_compat();
1551 - PyTypeObject *srctype = Py_TYPE(src.ptr());
1553 - // Case 1: If src is an exact type match for the target type then we can reinterpret_cast
1554 - // the instance's value pointer to the target type:
1555 - if (srctype == typeinfo->type) {
1556 - this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
1559 - // Case 2: We have a derived class
1560 - else if (PyType_IsSubtype(srctype, typeinfo->type)) {
1561 - auto &bases = all_type_info(srctype);
1562 - bool no_cpp_mi = typeinfo->simple_type;
1564 - // Case 2a: the python type is a Python-inherited derived class that inherits from just
1565 - // one simple (no MI) pybind11 class, or is an exact match, so the C++ instance is of
1566 - // the right type and we can use reinterpret_cast.
1567 - // (This is essentially the same as case 2b, but because not using multiple inheritance
1568 - // is extremely common, we handle it specially to avoid the loop iterator and type
1569 - // pointer lookup overhead)
1570 - if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
1571 - this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
1574 - // Case 2b: the python type inherits from multiple C++ bases. Check the bases to see if
1575 - // we can find an exact match (or, for a simple C++ type, an inherited match); if so, we
1576 - // can safely reinterpret_cast to the relevant pointer.
1577 - else if (bases.size() > 1) {
1578 - for (auto base : bases) {
1579 - if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type) : base->type == typeinfo->type) {
1580 - this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
1586 - // Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type match
1587 - // in the registered bases, above, so try implicit casting (needed for proper C++ casting
1588 - // when MI is involved).
1589 - if (this_.try_implicit_casts(src, convert))
1593 - // Perform an implicit conversion
1595 - for (auto &converter : typeinfo->implicit_conversions) {
1596 - auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
1597 - if (load_impl<ThisT>(temp, false)) {
1598 - loader_life_support::add_patient(temp);
1602 - if (this_.try_direct_conversions(src))
1606 - // Failed to match local typeinfo. Try again with global.
1607 - if (typeinfo->module_local) {
1608 - if (auto gtype = get_global_type_info(*typeinfo->cpptype)) {
1610 - return load(src, false);
1614 - // Global typeinfo has precedence over foreign module_local
1615 - return try_load_foreign_module_local(src);
1619 - // Called to do type lookup and wrap the pointer and type in a pair when a dynamic_cast
1620 - // isn't needed or can't be used. If the type is unknown, sets the error and returns a pair
1621 - // with .second = nullptr. (p.first = nullptr is not an error: it becomes None).
1622 - PYBIND11_NOINLINE static std::pair<const void *, const type_info *> src_and_type(
1623 - const void *src, const std::type_info &cast_type, const std::type_info *rtti_type = nullptr) {
1624 - if (auto *tpi = get_type_info(cast_type))
1625 - return {src, const_cast<const type_info *>(tpi)};
1627 - // Not found, set error:
1628 - std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
1629 - detail::clean_type_id(tname);
1630 - std::string msg = "Unregistered type : " + tname;
1631 - PyErr_SetString(PyExc_TypeError, msg.c_str());
1632 - return {nullptr, nullptr};
1635 - const type_info *typeinfo = nullptr;
1636 - const std::type_info *cpptype = nullptr;
1637 - void *value = nullptr;
1641 - * Determine suitable casting operator for pointer-or-lvalue-casting type casters. The type caster
1642 - * needs to provide `operator T*()` and `operator T&()` operators.
1644 - * If the type supports moving the value away via an `operator T&&() &&` method, it should use
1645 - * `movable_cast_op_type` instead.
1647 -template <typename T>
1648 -using cast_op_type =
1649 - conditional_t<std::is_pointer<remove_reference_t<T>>::value,
1650 - typename std::add_pointer<intrinsic_t<T>>::type,
1651 - typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
1654 - * Determine suitable casting operator for a type caster with a movable value. Such a type caster
1655 - * needs to provide `operator T*()`, `operator T&()`, and `operator T&&() &&`. The latter will be
1656 - * called in appropriate contexts where the value can be moved rather than copied.
1658 - * These operator are automatically provided when using the PYBIND11_TYPE_CASTER macro.
1660 -template <typename T>
1661 -using movable_cast_op_type =
1662 - conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,
1663 - typename std::add_pointer<intrinsic_t<T>>::type,
1664 - conditional_t<std::is_rvalue_reference<T>::value,
1665 - typename std::add_rvalue_reference<intrinsic_t<T>>::type,
1666 - typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
1668 -// std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when
1669 -// T is non-copyable, but code containing such a copy constructor fails to actually compile.
1670 -template <typename T, typename SFINAE = void> struct is_copy_constructible : std::is_copy_constructible<T> {};
1672 -// Specialization for types that appear to be copy constructible but also look like stl containers
1673 -// (we specifically check for: has `value_type` and `reference` with `reference = value_type&`): if
1674 -// so, copy constructability depends on whether the value_type is copy constructible.
1675 -template <typename Container> struct is_copy_constructible<Container, enable_if_t<all_of<
1676 - std::is_copy_constructible<Container>,
1677 - std::is_same<typename Container::value_type &, typename Container::reference>
1678 - >::value>> : is_copy_constructible<typename Container::value_type> {};
1680 -#if !defined(PYBIND11_CPP17)
1681 -// Likewise for std::pair before C++17 (which mandates that the copy constructor not exist when the
1682 -// two types aren't themselves copy constructible).
1683 -template <typename T1, typename T2> struct is_copy_constructible<std::pair<T1, T2>>
1684 - : all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
1687 -NAMESPACE_END(detail)
1689 -// polymorphic_type_hook<itype>::get(src, tinfo) determines whether the object pointed
1690 -// to by `src` actually is an instance of some class derived from `itype`.
1691 -// If so, it sets `tinfo` to point to the std::type_info representing that derived
1692 -// type, and returns a pointer to the start of the most-derived object of that type
1693 -// (in which `src` is a subobject; this will be the same address as `src` in most
1694 -// single inheritance cases). If not, or if `src` is nullptr, it simply returns `src`
1695 -// and leaves `tinfo` at its default value of nullptr.
1697 -// The default polymorphic_type_hook just returns src. A specialization for polymorphic
1698 -// types determines the runtime type of the passed object and adjusts the this-pointer
1699 -// appropriately via dynamic_cast<void*>. This is what enables a C++ Animal* to appear
1700 -// to Python as a Dog (if Dog inherits from Animal, Animal is polymorphic, Dog is
1701 -// registered with pybind11, and this Animal is in fact a Dog).
1703 -// You may specialize polymorphic_type_hook yourself for types that want to appear
1704 -// polymorphic to Python but do not use C++ RTTI. (This is a not uncommon pattern
1705 -// in performance-sensitive applications, used most notably in LLVM.)
1706 -template <typename itype, typename SFINAE = void>
1707 -struct polymorphic_type_hook
1709 - static const void *get(const itype *src, const std::type_info*&) { return src; }
1711 -template <typename itype>
1712 -struct polymorphic_type_hook<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>>
1714 - static const void *get(const itype *src, const std::type_info*& type) {
1715 - type = src ? &typeid(*src) : nullptr;
1716 - return dynamic_cast<const void*>(src);
1720 -NAMESPACE_BEGIN(detail)
1722 -/// Generic type caster for objects stored on the heap
1723 -template <typename type> class type_caster_base : public type_caster_generic {
1724 - using itype = intrinsic_t<type>;
1727 - static constexpr auto name = _<type>();
1729 - type_caster_base() : type_caster_base(typeid(type)) { }
1730 - explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) { }
1732 - static handle cast(const itype &src, return_value_policy policy, handle parent) {
1733 - if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
1734 - policy = return_value_policy::copy;
1735 - return cast(&src, policy, parent);
1738 - static handle cast(itype &&src, return_value_policy, handle parent) {
1739 - return cast(&src, return_value_policy::move, parent);
1742 - // Returns a (pointer, type_info) pair taking care of necessary type lookup for a
1743 - // polymorphic type (using RTTI by default, but can be overridden by specializing
1744 - // polymorphic_type_hook). If the instance isn't derived, returns the base version.
1745 - static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
1746 - auto &cast_type = typeid(itype);
1747 - const std::type_info *instance_type = nullptr;
1748 - const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
1749 - if (instance_type && !same_type(cast_type, *instance_type)) {
1750 - // This is a base pointer to a derived type. If the derived type is registered
1751 - // with pybind11, we want to make the full derived object available.
1752 - // In the typical case where itype is polymorphic, we get the correct
1753 - // derived pointer (which may be != base pointer) by a dynamic_cast to
1754 - // most derived type. If itype is not polymorphic, we won't get here
1755 - // except via a user-provided specialization of polymorphic_type_hook,
1756 - // and the user has promised that no this-pointer adjustment is
1757 - // required in that case, so it's OK to use static_cast.
1758 - if (const auto *tpi = get_type_info(*instance_type))
1759 - return {vsrc, tpi};
1761 - // Otherwise we have either a nullptr, an `itype` pointer, or an unknown derived pointer, so
1762 - // don't do a cast
1763 - return type_caster_generic::src_and_type(src, cast_type, instance_type);
1766 - static handle cast(const itype *src, return_value_policy policy, handle parent) {
1767 - auto st = src_and_type(src);
1768 - return type_caster_generic::cast(
1769 - st.first, policy, parent, st.second,
1770 - make_copy_constructor(src), make_move_constructor(src));
1773 - static handle cast_holder(const itype *src, const void *holder) {
1774 - auto st = src_and_type(src);
1775 - return type_caster_generic::cast(
1776 - st.first, return_value_policy::take_ownership, {}, st.second,
1777 - nullptr, nullptr, holder);
1780 - template <typename T> using cast_op_type = detail::cast_op_type<T>;
1782 - operator itype*() { return (type *) value; }
1783 - operator itype&() { if (!value) throw reference_cast_error(); return *((itype *) value); }
1786 - using Constructor = void *(*)(const void *);
1788 - /* Only enabled when the types are {copy,move}-constructible *and* when the type
1789 - does not have a private operator new implementation. */
1790 - template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
1791 - static auto make_copy_constructor(const T *x) -> decltype(new T(*x), Constructor{}) {
1792 - return [](const void *arg) -> void * {
1793 - return new T(*reinterpret_cast<const T *>(arg));
1797 - template <typename T, typename = enable_if_t<std::is_move_constructible<T>::value>>
1798 - static auto make_move_constructor(const T *x) -> decltype(new T(std::move(*const_cast<T *>(x))), Constructor{}) {
1799 - return [](const void *arg) -> void * {
1800 - return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
1804 - static Constructor make_copy_constructor(...) { return nullptr; }
1805 - static Constructor make_move_constructor(...) { return nullptr; }
1808 -template <typename type, typename SFINAE = void> class type_caster : public type_caster_base<type> { };
1809 -template <typename type> using make_caster = type_caster<intrinsic_t<type>>;
1810 +template <typename type, typename SFINAE = void>
1811 +class type_caster : public type_caster_base<type> {};
1812 +template <typename type>
1813 +using make_caster = type_caster<intrinsic_t<type>>;
1815 // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
1816 -template <typename T> typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
1817 +template <typename T>
1818 +typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
1819 return caster.operator typename make_caster<T>::template cast_op_type<T>();
1821 -template <typename T> typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
1822 +template <typename T>
1823 +typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
1824 cast_op(make_caster<T> &&caster) {
1825 - return std::move(caster).operator
1826 - typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>();
1827 + return std::move(caster).operator typename make_caster<T>::
1828 + template cast_op_type<typename std::add_rvalue_reference<T>::type>();
1831 -template <typename type> class type_caster<std::reference_wrapper<type>> {
1832 +template <typename type>
1833 +class type_caster<std::reference_wrapper<type>> {
1835 using caster_t = make_caster<type>;
1837 - using subcaster_cast_op_type = typename caster_t::template cast_op_type<type>;
1838 - static_assert(std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value,
1839 - "std::reference_wrapper<T> caster requires T to have a caster with an `T &` operator");
1840 + using reference_t = type &;
1841 + using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
1844 + std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
1845 + || std::is_same<reference_t, subcaster_cast_op_type>::value,
1846 + "std::reference_wrapper<T> caster requires T to have a caster with an "
1847 + "`operator T &()` or `operator const T &()`");
1850 bool load(handle src, bool convert) { return subcaster.load(src, convert); }
1851 static constexpr auto name = caster_t::name;
1852 - static handle cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
1854 + cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
1855 // It is definitely wrong to take ownership of this pointer, so mask that rvp
1856 - if (policy == return_value_policy::take_ownership || policy == return_value_policy::automatic)
1857 + if (policy == return_value_policy::take_ownership
1858 + || policy == return_value_policy::automatic) {
1859 policy = return_value_policy::automatic_reference;
1861 return caster_t::cast(&src.get(), policy, parent);
1863 - template <typename T> using cast_op_type = std::reference_wrapper<type>;
1864 - operator std::reference_wrapper<type>() { return subcaster.operator subcaster_cast_op_type&(); }
1865 + template <typename T>
1866 + using cast_op_type = std::reference_wrapper<type>;
1867 + explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
1870 -#define PYBIND11_TYPE_CASTER(type, py_name) \
1874 - static constexpr auto name = py_name; \
1875 - template <typename T_, enable_if_t<std::is_same<type, remove_cv_t<T_>>::value, int> = 0> \
1876 - static handle cast(T_ *src, return_value_policy policy, handle parent) { \
1877 - if (!src) return none().release(); \
1878 - if (policy == return_value_policy::take_ownership) { \
1879 - auto h = cast(std::move(*src), policy, parent); delete src; return h; \
1881 - return cast(*src, policy, parent); \
1884 - operator type*() { return &value; } \
1885 - operator type&() { return value; } \
1886 - operator type&&() && { return std::move(value); } \
1887 - template <typename T_> using cast_op_type = pybind11::detail::movable_cast_op_type<T_>
1890 -template <typename CharT> using is_std_char_type = any_of<
1891 - std::is_same<CharT, char>, /* std::string */
1892 - std::is_same<CharT, char16_t>, /* std::u16string */
1893 - std::is_same<CharT, char32_t>, /* std::u32string */
1894 - std::is_same<CharT, wchar_t> /* std::wstring */
1896 +#define PYBIND11_TYPE_CASTER(type, py_name) \
1901 + static constexpr auto name = py_name; \
1902 + template <typename T_, \
1903 + ::pybind11::detail::enable_if_t< \
1904 + std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value, \
1906 + static ::pybind11::handle cast( \
1907 + T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) { \
1909 + return ::pybind11::none().release(); \
1910 + if (policy == ::pybind11::return_value_policy::take_ownership) { \
1911 + auto h = cast(std::move(*src), policy, parent); \
1915 + return cast(*src, policy, parent); \
1917 + operator type *() { return &value; } /* NOLINT(bugprone-macro-parentheses) */ \
1918 + operator type &() { return value; } /* NOLINT(bugprone-macro-parentheses) */ \
1919 + operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */ \
1920 + template <typename T_> \
1921 + using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
1923 +template <typename CharT>
1924 +using is_std_char_type = any_of<std::is_same<CharT, char>, /* std::string */
1925 +#if defined(PYBIND11_HAS_U8STRING)
1926 + std::is_same<CharT, char8_t>, /* std::u8string */
1928 + std::is_same<CharT, char16_t>, /* std::u16string */
1929 + std::is_same<CharT, char32_t>, /* std::u32string */
1930 + std::is_same<CharT, wchar_t> /* std::wstring */
1933 template <typename T>
1934 struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
1935 using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
1936 - using _py_type_1 = conditional_t<std::is_signed<T>::value, _py_type_0, typename std::make_unsigned<_py_type_0>::type>;
1937 + using _py_type_1 = conditional_t<std::is_signed<T>::value,
1939 + typename std::make_unsigned<_py_type_0>::type>;
1940 using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
1944 bool load(handle src, bool convert) {
1952 +#if !defined(PYPY_VERSION)
1953 + auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
1955 + // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
1956 + // while CPython only considers the existence of `nb_index`/`__index__`.
1957 + auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
1960 if (std::is_floating_point<T>::value) {
1961 - if (convert || PyFloat_Check(src.ptr()))
1962 + if (convert || PyFloat_Check(src.ptr())) {
1963 py_value = (py_type) PyFloat_AsDouble(src.ptr());
1967 - } else if (PyFloat_Check(src.ptr())) {
1969 + } else if (PyFloat_Check(src.ptr())
1970 + || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
1972 - } else if (std::is_unsigned<py_type>::value) {
1973 - py_value = as_unsigned<py_type>(src.ptr());
1974 - } else { // signed integer:
1975 - py_value = sizeof(T) <= sizeof(long)
1976 - ? (py_type) PyLong_AsLong(src.ptr())
1977 - : (py_type) PYBIND11_LONG_AS_LONGLONG(src.ptr());
1979 + handle src_or_index = src;
1980 + // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
1981 +#if PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
1983 + if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
1984 + index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
1990 + src_or_index = index;
1994 + if (std::is_unsigned<py_type>::value) {
1995 + py_value = as_unsigned<py_type>(src_or_index.ptr());
1996 + } else { // signed integer:
1997 + py_value = sizeof(T) <= sizeof(long)
1998 + ? (py_type) PyLong_AsLong(src_or_index.ptr())
1999 + : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
2003 + // Python API reported an error
2004 bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
2005 - if (py_err || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T) &&
2006 - (py_value < (py_type) std::numeric_limits<T>::min() ||
2007 - py_value > (py_type) std::numeric_limits<T>::max()))) {
2008 - bool type_error = py_err && PyErr_ExceptionMatches(
2009 -#if PY_VERSION_HEX < 0x03000000 && !defined(PYPY_VERSION)
2016 + // Check to see if the conversion is valid (integers should match exactly)
2017 + // Signed/unsigned checks happen elsewhere
2019 + || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
2020 + && py_value != (py_type) (T) py_value)) {
2022 - if (type_error && convert && PyNumber_Check(src.ptr())) {
2023 + if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
2024 auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
2025 - ? PyNumber_Float(src.ptr())
2026 - : PyNumber_Long(src.ptr()));
2027 + ? PyNumber_Float(src.ptr())
2028 + : PyNumber_Long(src.ptr()));
2030 return load(tmp, false);
2032 @@ -1020,62 +197,75 @@
2036 - template<typename U = T>
2037 + template <typename U = T>
2038 static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
2039 cast(U src, return_value_policy /* policy */, handle /* parent */) {
2040 return PyFloat_FromDouble((double) src);
2043 - template<typename U = T>
2044 - static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (sizeof(U) <= sizeof(long)), handle>::type
2045 + template <typename U = T>
2046 + static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
2047 + && (sizeof(U) <= sizeof(long)),
2049 cast(U src, return_value_policy /* policy */, handle /* parent */) {
2050 return PYBIND11_LONG_FROM_SIGNED((long) src);
2053 - template<typename U = T>
2054 - static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (sizeof(U) <= sizeof(unsigned long)), handle>::type
2055 + template <typename U = T>
2056 + static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
2057 + && (sizeof(U) <= sizeof(unsigned long)),
2059 cast(U src, return_value_policy /* policy */, handle /* parent */) {
2060 return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
2063 - template<typename U = T>
2064 - static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (sizeof(U) > sizeof(long)), handle>::type
2065 + template <typename U = T>
2066 + static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
2067 + && (sizeof(U) > sizeof(long)),
2069 cast(U src, return_value_policy /* policy */, handle /* parent */) {
2070 return PyLong_FromLongLong((long long) src);
2073 - template<typename U = T>
2074 - static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (sizeof(U) > sizeof(unsigned long)), handle>::type
2075 + template <typename U = T>
2076 + static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
2077 + && (sizeof(U) > sizeof(unsigned long)),
2079 cast(U src, return_value_policy /* policy */, handle /* parent */) {
2080 return PyLong_FromUnsignedLongLong((unsigned long long) src);
2083 - PYBIND11_TYPE_CASTER(T, _<std::is_integral<T>::value>("int", "float"));
2084 + PYBIND11_TYPE_CASTER(T, const_name<std::is_integral<T>::value>("int", "float"));
2087 -template<typename T> struct void_caster {
2088 +template <typename T>
2089 +struct void_caster {
2091 bool load(handle src, bool) {
2092 - if (src && src.is_none())
2093 + if (src && src.is_none()) {
2098 static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
2099 return none().inc_ref();
2101 - PYBIND11_TYPE_CASTER(T, _("None"));
2102 + PYBIND11_TYPE_CASTER(T, const_name("None"));
2105 -template <> class type_caster<void_type> : public void_caster<void_type> {};
2107 +class type_caster<void_type> : public void_caster<void_type> {};
2109 -template <> class type_caster<void> : public type_caster<void_type> {
2111 +class type_caster<void> : public type_caster<void_type> {
2113 using type_caster<void_type>::cast;
2115 bool load(handle h, bool) {
2118 - } else if (h.is_none()) {
2120 + if (h.is_none()) {
2124 @@ -1087,7 +277,7 @@
2127 /* Check if this is a C++ type */
2128 - auto &bases = all_type_info((PyTypeObject *) h.get_type().ptr());
2129 + const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
2130 if (bases.size() == 1) { // Only allowing loading from a single-value type
2131 value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
2133 @@ -1098,73 +288,94 @@
2136 static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
2139 return capsule(ptr).release();
2141 - return none().inc_ref();
2143 + return none().inc_ref();
2146 - template <typename T> using cast_op_type = void*&;
2147 - operator void *&() { return value; }
2148 - static constexpr auto name = _("capsule");
2149 + template <typename T>
2150 + using cast_op_type = void *&;
2151 + explicit operator void *&() { return value; }
2152 + static constexpr auto name = const_name("capsule");
2155 void *value = nullptr;
2158 -template <> class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> { };
2160 +class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
2162 -template <> class type_caster<bool> {
2164 +class type_caster<bool> {
2166 bool load(handle src, bool convert) {
2167 - if (!src) return false;
2168 - else if (src.ptr() == Py_True) { value = true; return true; }
2169 - else if (src.ptr() == Py_False) { value = false; return true; }
2170 - else if (convert || !strcmp("numpy.bool_", Py_TYPE(src.ptr())->tp_name)) {
2174 + if (src.ptr() == Py_True) {
2178 + if (src.ptr() == Py_False) {
2182 + if (convert || (std::strcmp("numpy.bool_", Py_TYPE(src.ptr())->tp_name) == 0)) {
2183 // (allow non-implicit conversion for numpy booleans)
2185 Py_ssize_t res = -1;
2186 if (src.is_none()) {
2187 - res = 0; // None is implicitly converted to False
2188 + res = 0; // None is implicitly converted to False
2190 - #if defined(PYPY_VERSION)
2191 +#if defined(PYPY_VERSION)
2192 // On PyPy, check that "__bool__" (or "__nonzero__" on Python 2.7) attr exists
2193 else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
2194 res = PyObject_IsTrue(src.ptr());
2198 // Alternate approach for CPython: this does the same as the above, but optimized
2199 // using the CPython API so as to avoid an unneeded attribute lookup.
2200 - else if (auto tp_as_number = src.ptr()->ob_type->tp_as_number) {
2201 + else if (auto *tp_as_number = src.ptr()->ob_type->tp_as_number) {
2202 if (PYBIND11_NB_BOOL(tp_as_number)) {
2203 res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
2208 if (res == 0 || res == 1) {
2209 - value = (bool) res;
2210 + value = (res != 0);
2217 static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
2218 return handle(src ? Py_True : Py_False).inc_ref();
2220 - PYBIND11_TYPE_CASTER(bool, _("bool"));
2221 + PYBIND11_TYPE_CASTER(bool, const_name("bool"));
2224 // Helper class for UTF-{8,16,32} C++ stl strings:
2225 -template <typename StringType, bool IsView = false> struct string_caster {
2226 +template <typename StringType, bool IsView = false>
2227 +struct string_caster {
2228 using CharT = typename StringType::value_type;
2230 // Simplify life by being able to assume standard char sizes (the standard only guarantees
2231 // minimums, but Python requires exact sizes)
2232 - static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1, "Unsupported char size != 1");
2233 - static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2, "Unsupported char16_t size != 2");
2234 - static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4, "Unsupported char32_t size != 4");
2235 + static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
2236 + "Unsupported char size != 1");
2237 +#if defined(PYBIND11_HAS_U8STRING)
2238 + static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
2239 + "Unsupported char8_t size != 1");
2241 + static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
2242 + "Unsupported char16_t size != 2");
2243 + static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
2244 + "Unsupported char32_t size != 4");
2245 // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
2246 static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
2247 - "Unsupported wchar_t size != 2/4");
2248 + "Unsupported wchar_t size != 2/4");
2249 static constexpr size_t UTF_N = 8 * sizeof(CharT);
2251 bool load(handle src, bool) {
2252 @@ -1174,11 +385,12 @@
2253 handle load_src = src;
2256 - } else if (!PyUnicode_Check(load_src.ptr())) {
2258 + if (!PyUnicode_Check(load_src.ptr())) {
2259 #if PY_MAJOR_VERSION >= 3
2260 return load_bytes(load_src);
2262 - if (sizeof(CharT) == 1) {
2263 + if (std::is_same<CharT, char>::value) {
2264 return load_bytes(load_src);
2267 @@ -1187,50 +399,88 @@
2270 temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.ptr()));
2271 - if (!temp) { PyErr_Clear(); return false; }
2280 - object utfNbytes = reinterpret_steal<object>(PyUnicode_AsEncodedString(
2281 - load_src.ptr(), UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr));
2282 - if (!utfNbytes) { PyErr_Clear(); return false; }
2283 +#if PY_VERSION_HEX >= 0x03030000
2284 + // On Python >= 3.3, for UTF-8 we avoid the need for a temporary `bytes`
2285 + // object by using `PyUnicode_AsUTF8AndSize`.
2286 + if (PYBIND11_SILENCE_MSVC_C4127(UTF_N == 8)) {
2287 + Py_ssize_t size = -1;
2288 + const auto *buffer
2289 + = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
2294 + value = StringType(buffer, static_cast<size_t>(size));
2300 + = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
2301 + UTF_N == 8 ? "utf-8"
2302 + : UTF_N == 16 ? "utf-16"
2310 - const CharT *buffer = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
2311 + const auto *buffer
2312 + = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
2313 size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
2314 - if (UTF_N > 8) { buffer++; length--; } // Skip BOM for UTF-16/32
2315 + // Skip BOM for UTF-16/32
2316 + if (PYBIND11_SILENCE_MSVC_C4127(UTF_N > 8)) {
2320 value = StringType(buffer, length);
2322 // If we're loading a string_view we need to keep the encoded Python object alive:
2325 loader_life_support::add_patient(utfNbytes);
2331 - static handle cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
2333 + cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
2334 const char *buffer = reinterpret_cast<const char *>(src.data());
2335 - ssize_t nbytes = ssize_t(src.size() * sizeof(CharT));
2336 + auto nbytes = ssize_t(src.size() * sizeof(CharT));
2337 handle s = decode_utfN(buffer, nbytes);
2338 - if (!s) throw error_already_set();
2340 + throw error_already_set();
2345 - PYBIND11_TYPE_CASTER(StringType, _(PYBIND11_STRING_NAME));
2346 + PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
2349 static handle decode_utfN(const char *buffer, ssize_t nbytes) {
2350 #if !defined(PYPY_VERSION)
2352 - UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr) :
2353 - UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr) :
2354 - PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
2355 + return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
2356 + : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
2357 + : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
2359 - // PyPy seems to have multiple problems related to PyUnicode_UTF*: the UTF8 version
2360 - // sometimes segfaults for unknown reasons, while the UTF16 and 32 versions require a
2361 - // non-const char * arguments, which is also a nuisance, so bypass the whole thing by just
2362 - // passing the encoding as a string value, which works properly:
2363 - return PyUnicode_Decode(buffer, nbytes, UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr);
2364 + // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
2365 + // well), so bypass the whole thing by just passing the encoding as a string value, which
2366 + // works properly:
2367 + return PyUnicode_Decode(buffer,
2369 + UTF_N == 8 ? "utf-8"
2370 + : UTF_N == 16 ? "utf-16"
2376 @@ -1238,7 +488,7 @@
2377 // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
2378 // which supports loading a unicode from a str, doesn't take this path.
2379 template <typename C = CharT>
2380 - bool load_bytes(enable_if_t<sizeof(C) == 1, handle> src) {
2381 + bool load_bytes(enable_if_t<std::is_same<C, char>::value, handle> src) {
2382 if (PYBIND11_BYTES_CHECK(src.ptr())) {
2383 // We were passed a Python 3 raw bytes; accept it into a std::string or char*
2384 // without any encoding attempt.
2385 @@ -1253,33 +503,43 @@
2388 template <typename C = CharT>
2389 - bool load_bytes(enable_if_t<sizeof(C) != 1, handle>) { return false; }
2390 + bool load_bytes(enable_if_t<!std::is_same<C, char>::value, handle>) {
2395 template <typename CharT, class Traits, class Allocator>
2396 -struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_std_char_type<CharT>::value>>
2397 +struct type_caster<std::basic_string<CharT, Traits, Allocator>,
2398 + enable_if_t<is_std_char_type<CharT>::value>>
2399 : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
2401 #ifdef PYBIND11_HAS_STRING_VIEW
2402 template <typename CharT, class Traits>
2403 -struct type_caster<std::basic_string_view<CharT, Traits>, enable_if_t<is_std_char_type<CharT>::value>>
2404 +struct type_caster<std::basic_string_view<CharT, Traits>,
2405 + enable_if_t<is_std_char_type<CharT>::value>>
2406 : string_caster<std::basic_string_view<CharT, Traits>, true> {};
2409 // Type caster for C-style strings. We basically use a std::string type caster, but also add the
2410 // ability to use None as a nullptr char* (which the string caster doesn't allow).
2411 -template <typename CharT> struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
2412 +template <typename CharT>
2413 +struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
2414 using StringType = std::basic_string<CharT>;
2415 using StringCaster = type_caster<StringType>;
2416 StringCaster str_caster;
2421 bool load(handle src, bool convert) {
2422 - if (!src) return false;
2426 if (src.is_none()) {
2427 // Defer accepting None to other overloads (if we aren't in convert mode):
2428 - if (!convert) return false;
2435 @@ -1287,45 +547,58 @@
2438 static handle cast(const CharT *src, return_value_policy policy, handle parent) {
2439 - if (src == nullptr) return pybind11::none().inc_ref();
2440 + if (src == nullptr) {
2441 + return pybind11::none().inc_ref();
2443 return StringCaster::cast(StringType(src), policy, parent);
2446 static handle cast(CharT src, return_value_policy policy, handle parent) {
2447 if (std::is_same<char, CharT>::value) {
2448 handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
2449 - if (!s) throw error_already_set();
2451 + throw error_already_set();
2455 return StringCaster::cast(StringType(1, src), policy, parent);
2458 - operator CharT*() { return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str()); }
2459 - operator CharT&() {
2461 + explicit operator CharT *() {
2462 + return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
2464 + explicit operator CharT &() {
2466 throw value_error("Cannot convert None to a character");
2469 auto &value = static_cast<StringType &>(str_caster);
2470 size_t str_len = value.size();
2472 + if (str_len == 0) {
2473 throw value_error("Cannot convert empty string to a character");
2476 // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
2477 - // is too high, and one for multiple unicode characters (caught later), so we need to figure
2478 - // out how long the first encoded character is in bytes to distinguish between these two
2479 - // errors. We also allow want to allow unicode characters U+0080 through U+00FF, as those
2480 - // can fit into a single char value.
2481 - if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
2482 - unsigned char v0 = static_cast<unsigned char>(value[0]);
2483 - size_t char0_bytes = !(v0 & 0x80) ? 1 : // low bits only: 0-127
2484 - (v0 & 0xE0) == 0xC0 ? 2 : // 0b110xxxxx - start of 2-byte sequence
2485 - (v0 & 0xF0) == 0xE0 ? 3 : // 0b1110xxxx - start of 3-byte sequence
2486 - 4; // 0b11110xxx - start of 4-byte sequence
2487 + // is too high, and one for multiple unicode characters (caught later), so we need to
2488 + // figure out how long the first encoded character is in bytes to distinguish between these
2489 + // two errors. We also allow want to allow unicode characters U+0080 through U+00FF, as
2490 + // those can fit into a single char value.
2491 + if (PYBIND11_SILENCE_MSVC_C4127(StringCaster::UTF_N == 8) && str_len > 1 && str_len <= 4) {
2492 + auto v0 = static_cast<unsigned char>(value[0]);
2493 + // low bits only: 0-127
2494 + // 0b110xxxxx - start of 2-byte sequence
2495 + // 0b1110xxxx - start of 3-byte sequence
2496 + // 0b11110xxx - start of 4-byte sequence
2497 + size_t char0_bytes = (v0 & 0x80) == 0 ? 1
2498 + : (v0 & 0xE0) == 0xC0 ? 2
2499 + : (v0 & 0xF0) == 0xE0 ? 3
2502 if (char0_bytes == str_len) {
2503 // If we have a 128-255 value, we can decode it into a single char:
2504 if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
2505 - one_char = static_cast<CharT>(((v0 & 3) << 6) + (static_cast<unsigned char>(value[1]) & 0x3F));
2506 + one_char = static_cast<CharT>(((v0 & 3) << 6)
2507 + + (static_cast<unsigned char>(value[1]) & 0x3F));
2510 // Otherwise we have a single character, but it's > U+00FF
2511 @@ -1336,36 +609,42 @@
2512 // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
2513 // surrogate pair with total length 2 instantly indicates a range error (but not a "your
2514 // string was too long" error).
2515 - else if (StringCaster::UTF_N == 16 && str_len == 2) {
2516 + else if (PYBIND11_SILENCE_MSVC_C4127(StringCaster::UTF_N == 16) && str_len == 2) {
2517 one_char = static_cast<CharT>(value[0]);
2518 - if (one_char >= 0xD800 && one_char < 0xE000)
2519 + if (one_char >= 0xD800 && one_char < 0xE000) {
2520 throw value_error("Character code point not in range(0x10000)");
2525 + if (str_len != 1) {
2526 throw value_error("Expected a character, but multi-character string found");
2529 one_char = value[0];
2533 - static constexpr auto name = _(PYBIND11_STRING_NAME);
2534 - template <typename _T> using cast_op_type = pybind11::detail::cast_op_type<_T>;
2535 + static constexpr auto name = const_name(PYBIND11_STRING_NAME);
2536 + template <typename _T>
2537 + using cast_op_type = pybind11::detail::cast_op_type<_T>;
2540 // Base implementation for std::tuple and std::pair
2541 -template <template<typename...> class Tuple, typename... Ts> class tuple_caster {
2542 +template <template <typename...> class Tuple, typename... Ts>
2543 +class tuple_caster {
2544 using type = Tuple<Ts...>;
2545 static constexpr auto size = sizeof...(Ts);
2546 using indices = make_index_sequence<size>;
2550 bool load(handle src, bool convert) {
2551 - if (!isinstance<sequence>(src))
2552 + if (!isinstance<sequence>(src)) {
2555 const auto seq = reinterpret_borrow<sequence>(src);
2556 - if (seq.size() != size)
2557 + if (seq.size() != size) {
2560 return load_impl(seq, convert, indices{});
2563 @@ -1374,53 +653,86 @@
2564 return cast_impl(std::forward<T>(src), policy, parent, indices{});
2567 - static constexpr auto name = _("Tuple[") + concat(make_caster<Ts>::name...) + _("]");
2568 + // copied from the PYBIND11_TYPE_CASTER macro
2569 + template <typename T>
2570 + static handle cast(T *src, return_value_policy policy, handle parent) {
2572 + return none().release();
2574 + if (policy == return_value_policy::take_ownership) {
2575 + auto h = cast(std::move(*src), policy, parent);
2579 + return cast(*src, policy, parent);
2582 - template <typename T> using cast_op_type = type;
2583 + static constexpr auto name
2584 + = const_name("Tuple[") + concat(make_caster<Ts>::name...) + const_name("]");
2586 - operator type() & { return implicit_cast(indices{}); }
2587 - operator type() && { return std::move(*this).implicit_cast(indices{}); }
2588 + template <typename T>
2589 + using cast_op_type = type;
2591 + explicit operator type() & { return implicit_cast(indices{}); }
2592 + explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
2595 template <size_t... Is>
2596 - type implicit_cast(index_sequence<Is...>) & { return type(cast_op<Ts>(std::get<Is>(subcasters))...); }
2597 + type implicit_cast(index_sequence<Is...>) & {
2598 + return type(cast_op<Ts>(std::get<Is>(subcasters))...);
2600 template <size_t... Is>
2601 - type implicit_cast(index_sequence<Is...>) && { return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...); }
2602 + type implicit_cast(index_sequence<Is...>) && {
2603 + return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
2606 static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
2608 template <size_t... Is>
2609 bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
2610 - for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...})
2612 +#ifdef __cpp_fold_expressions
2613 + if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
2617 + for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
2626 /* Implementation: Convert a C++ tuple into a Python tuple */
2627 template <typename T, size_t... Is>
2628 - static handle cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
2629 - std::array<object, size> entries{{
2630 - reinterpret_steal<object>(make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...
2632 - for (const auto &entry: entries)
2635 + cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
2636 + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
2637 + PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
2638 + std::array<object, size> entries{{reinterpret_steal<object>(
2639 + make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
2640 + for (const auto &entry : entries) {
2647 - for (auto & entry: entries)
2648 + for (auto &entry : entries) {
2649 PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
2651 return result.release();
2654 Tuple<make_caster<Ts>...> subcasters;
2657 -template <typename T1, typename T2> class type_caster<std::pair<T1, T2>>
2658 - : public tuple_caster<std::pair, T1, T2> {};
2659 +template <typename T1, typename T2>
2660 +class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
2662 -template <typename... Ts> class type_caster<std::tuple<Ts...>>
2663 - : public tuple_caster<std::tuple, Ts...> {};
2664 +template <typename... Ts>
2665 +class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
2667 /// Helper class which abstracts away certain actions. Users can provide specializations for
2668 /// custom holders, but it's only necessary if the type has a non-standard interface.
2669 @@ -1430,12 +742,16 @@
2672 /// Type caster for holder types like std::shared_ptr, etc.
2673 -template <typename type, typename holder_type>
2674 +/// The SFINAE hook is provided to help work around the current lack of support
2675 +/// for smart-pointer interoperability. Please consider it an implementation
2676 +/// detail that may change in the future, as formal support for smart-pointer
2677 +/// interoperability is added into pybind11.
2678 +template <typename type, typename holder_type, typename SFINAE = void>
2679 struct copyable_holder_caster : public type_caster_base<type> {
2681 using base = type_caster_base<type>;
2682 static_assert(std::is_base_of<base, type_caster<type>>::value,
2683 - "Holder classes are only supported for custom types");
2684 + "Holder classes are only supported for custom types");
2687 using base::typeinfo;
2688 @@ -1445,17 +761,12 @@
2689 return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
2692 - explicit operator type*() { return this->value; }
2693 - explicit operator type&() { return *(this->value); }
2694 - explicit operator holder_type*() { return std::addressof(holder); }
2696 - // Workaround for Intel compiler bug
2697 - // see pybind11 issue 94
2698 - #if defined(__ICC) || defined(__INTEL_COMPILER)
2699 - operator holder_type&() { return holder; }
2701 - explicit operator holder_type&() { return holder; }
2703 + explicit operator type *() { return this->value; }
2704 + // static_cast works around compiler error with MSVC 17 and CUDA 10.2
2705 + // see issue #2180
2706 + explicit operator type &() { return *(static_cast<type *>(this->value)); }
2707 + explicit operator holder_type *() { return std::addressof(holder); }
2708 + explicit operator holder_type &() { return holder; }
2710 static handle cast(const holder_type &src, return_value_policy, handle) {
2711 const auto *ptr = holder_helper<holder_type>::get(src);
2712 @@ -1465,8 +776,9 @@
2714 friend class type_caster_generic;
2715 void check_holder_compat() {
2716 - if (typeinfo->default_holder)
2717 + if (typeinfo->default_holder) {
2718 throw cast_error("Unable to load a custom holder type from a default-holder instance");
2722 bool load_value(value_and_holder &&v_h) {
2723 @@ -1474,20 +786,24 @@
2724 value = v_h.value_ptr();
2725 holder = v_h.template holder<holder_type>();
2728 - throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
2730 + throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
2732 - "(compile in debug mode for type information)");
2733 + "(compile in debug mode for type information)");
2735 - "of type '" + type_id<holder_type>() + "''");
2737 + + type_id<holder_type>() + "''");
2742 - template <typename T = holder_type, detail::enable_if_t<!std::is_constructible<T, const T &, type*>::value, int> = 0>
2743 - bool try_implicit_casts(handle, bool) { return false; }
2744 + template <typename T = holder_type,
2745 + detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
2746 + bool try_implicit_casts(handle, bool) {
2750 - template <typename T = holder_type, detail::enable_if_t<std::is_constructible<T, const T &, type*>::value, int> = 0>
2751 + template <typename T = holder_type,
2752 + detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
2753 bool try_implicit_casts(handle src, bool convert) {
2754 for (auto &cast : typeinfo->implicit_casts) {
2755 copyable_holder_caster sub_caster(*cast.first);
2756 @@ -1502,18 +818,20 @@
2758 static bool try_direct_conversions(handle) { return false; }
2764 /// Specialize for the common std::shared_ptr, so users don't need to
2765 template <typename T>
2766 -class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> { };
2767 +class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
2769 -template <typename type, typename holder_type>
2770 +/// Type caster for holder types like std::unique_ptr.
2771 +/// Please consider the SFINAE hook an implementation detail, as explained
2772 +/// in the comment for the copyable_holder_caster.
2773 +template <typename type, typename holder_type, typename SFINAE = void>
2774 struct move_only_holder_caster {
2775 static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
2776 - "Holder classes are only supported for custom types");
2777 + "Holder classes are only supported for custom types");
2779 static handle cast(holder_type &&src, return_value_policy, handle) {
2780 auto *ptr = holder_helper<holder_type>::get(src);
2781 @@ -1524,46 +842,105 @@
2783 template <typename type, typename deleter>
2784 class type_caster<std::unique_ptr<type, deleter>>
2785 - : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> { };
2786 + : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
2788 template <typename type, typename holder_type>
2789 using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
2790 copyable_holder_caster<type, holder_type>,
2791 move_only_holder_caster<type, holder_type>>;
2793 -template <typename T, bool Value = false> struct always_construct_holder { static constexpr bool value = Value; };
2794 +template <typename T, bool Value = false>
2795 +struct always_construct_holder {
2796 + static constexpr bool value = Value;
2799 /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
2800 -#define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
2801 - namespace pybind11 { namespace detail { \
2802 - template <typename type> \
2803 - struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { }; \
2804 - template <typename type> \
2805 - class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
2806 - : public type_caster_holder<type, holder_type> { }; \
2808 +#define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
2809 + namespace pybind11 { \
2810 + namespace detail { \
2811 + template <typename type> \
2812 + struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { \
2814 + template <typename type> \
2815 + class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
2816 + : public type_caster_holder<type, holder_type> {}; \
2820 // PYBIND11_DECLARE_HOLDER_TYPE holder types:
2821 -template <typename base, typename holder> struct is_holder_type :
2822 - std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
2823 +template <typename base, typename holder>
2824 +struct is_holder_type
2825 + : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
2826 // Specialization for always-supported unique_ptr holders:
2827 -template <typename base, typename deleter> struct is_holder_type<base, std::unique_ptr<base, deleter>> :
2828 - std::true_type {};
2829 +template <typename base, typename deleter>
2830 +struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
2832 -template <typename T> struct handle_type_name { static constexpr auto name = _<T>(); };
2833 -template <> struct handle_type_name<bytes> { static constexpr auto name = _(PYBIND11_BYTES_NAME); };
2834 -template <> struct handle_type_name<args> { static constexpr auto name = _("*args"); };
2835 -template <> struct handle_type_name<kwargs> { static constexpr auto name = _("**kwargs"); };
2836 +template <typename T>
2837 +struct handle_type_name {
2838 + static constexpr auto name = const_name<T>();
2841 +struct handle_type_name<bool_> {
2842 + static constexpr auto name = const_name("bool");
2845 +struct handle_type_name<bytes> {
2846 + static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
2849 +struct handle_type_name<int_> {
2850 + static constexpr auto name = const_name("int");
2853 +struct handle_type_name<iterable> {
2854 + static constexpr auto name = const_name("Iterable");
2857 +struct handle_type_name<iterator> {
2858 + static constexpr auto name = const_name("Iterator");
2861 +struct handle_type_name<float_> {
2862 + static constexpr auto name = const_name("float");
2865 +struct handle_type_name<none> {
2866 + static constexpr auto name = const_name("None");
2869 +struct handle_type_name<args> {
2870 + static constexpr auto name = const_name("*args");
2873 +struct handle_type_name<kwargs> {
2874 + static constexpr auto name = const_name("**kwargs");
2877 template <typename type>
2878 struct pyobject_caster {
2879 template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
2880 - bool load(handle src, bool /* convert */) { value = src; return static_cast<bool>(value); }
2881 + bool load(handle src, bool /* convert */) {
2883 + return static_cast<bool>(value);
2886 template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
2887 bool load(handle src, bool /* convert */) {
2888 - if (!isinstance<type>(src))
2889 +#if PY_MAJOR_VERSION < 3 && !defined(PYBIND11_STR_LEGACY_PERMISSIVE)
2890 + // For Python 2, without this implicit conversion, Python code would
2891 + // need to be cluttered with six.ensure_text() or similar, only to be
2892 + // un-cluttered later after Python 2 support is dropped.
2893 + if (PYBIND11_SILENCE_MSVC_C4127(std::is_same<T, str>::value) && isinstance<bytes>(src)) {
2894 + PyObject *str_from_bytes = PyUnicode_FromEncodedObject(src.ptr(), "utf-8", nullptr);
2895 + if (!str_from_bytes)
2896 + throw error_already_set();
2897 + value = reinterpret_steal<type>(str_from_bytes);
2901 + if (!isinstance<type>(src)) {
2904 value = reinterpret_borrow<type>(src);
2907 @@ -1575,7 +952,7 @@
2910 template <typename T>
2911 -class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> { };
2912 +class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
2914 // Our conditions for enabling moving are quite restrictive:
2916 @@ -1586,210 +963,301 @@
2917 // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
2918 // must have ref_count() == 1)h
2919 // If any of the above are not satisfied, we fall back to copying.
2920 -template <typename T> using move_is_plain_type = satisfies_none_of<T,
2921 - std::is_void, std::is_pointer, std::is_reference, std::is_const
2923 -template <typename T, typename SFINAE = void> struct move_always : std::false_type {};
2924 -template <typename T> struct move_always<T, enable_if_t<all_of<
2925 - move_is_plain_type<T>,
2926 - negation<is_copy_constructible<T>>,
2927 - std::is_move_constructible<T>,
2928 - std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
2929 ->::value>> : std::true_type {};
2930 -template <typename T, typename SFINAE = void> struct move_if_unreferenced : std::false_type {};
2931 -template <typename T> struct move_if_unreferenced<T, enable_if_t<all_of<
2932 - move_is_plain_type<T>,
2933 - negation<move_always<T>>,
2934 - std::is_move_constructible<T>,
2935 - std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
2936 ->::value>> : std::true_type {};
2937 -template <typename T> using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
2938 +template <typename T>
2939 +using move_is_plain_type
2940 + = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
2941 +template <typename T, typename SFINAE = void>
2942 +struct move_always : std::false_type {};
2943 +template <typename T>
2944 +struct move_always<
2947 + all_of<move_is_plain_type<T>,
2948 + negation<is_copy_constructible<T>>,
2949 + std::is_move_constructible<T>,
2950 + std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
2951 + : std::true_type {};
2952 +template <typename T, typename SFINAE = void>
2953 +struct move_if_unreferenced : std::false_type {};
2954 +template <typename T>
2955 +struct move_if_unreferenced<
2958 + all_of<move_is_plain_type<T>,
2959 + negation<move_always<T>>,
2960 + std::is_move_constructible<T>,
2961 + std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
2962 + : std::true_type {};
2963 +template <typename T>
2964 +using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
2966 // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
2967 // reference or pointer to a local variable of the type_caster. Basically, only
2968 // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
2969 // everything else returns a reference/pointer to a local variable.
2970 -template <typename type> using cast_is_temporary_value_reference = bool_constant<
2971 - (std::is_reference<type>::value || std::is_pointer<type>::value) &&
2972 - !std::is_base_of<type_caster_generic, make_caster<type>>::value &&
2973 - !std::is_same<intrinsic_t<type>, void>::value
2975 +template <typename type>
2976 +using cast_is_temporary_value_reference
2977 + = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
2978 + && !std::is_base_of<type_caster_generic, make_caster<type>>::value
2979 + && !std::is_same<intrinsic_t<type>, void>::value>;
2981 // When a value returned from a C++ function is being cast back to Python, we almost always want to
2982 // force `policy = move`, regardless of the return value policy the function/method was declared
2984 -template <typename Return, typename SFINAE = void> struct return_value_policy_override {
2985 +template <typename Return, typename SFINAE = void>
2986 +struct return_value_policy_override {
2987 static return_value_policy policy(return_value_policy p) { return p; }
2990 -template <typename Return> struct return_value_policy_override<Return,
2991 - detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
2992 +template <typename Return>
2993 +struct return_value_policy_override<
2995 + detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
2996 static return_value_policy policy(return_value_policy p) {
2997 - return !std::is_lvalue_reference<Return>::value &&
2998 - !std::is_pointer<Return>::value
2999 - ? return_value_policy::move : p;
3000 + return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
3001 + ? return_value_policy::move
3006 // Basic python -> C++ casting; throws if casting fails
3007 -template <typename T, typename SFINAE> type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
3008 +template <typename T, typename SFINAE>
3009 +type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
3010 if (!conv.load(handle, true)) {
3012 - throw cast_error("Unable to cast Python instance to C++ type (compile in debug mode for details)");
3014 + "Unable to cast Python instance to C++ type (compile in debug mode for details)");
3016 - throw cast_error("Unable to cast Python instance of type " +
3017 - (std::string) str(handle.get_type()) + " to C++ type '" + type_id<T>() + "'");
3018 + throw cast_error("Unable to cast Python instance of type "
3019 + + (std::string) str(type::handle_of(handle)) + " to C++ type '"
3020 + + type_id<T>() + "'");
3025 // Wrapper around the above that also constructs and returns a type_caster
3026 -template <typename T> make_caster<T> load_type(const handle &handle) {
3027 +template <typename T>
3028 +make_caster<T> load_type(const handle &handle) {
3029 make_caster<T> conv;
3030 load_type(conv, handle);
3034 -NAMESPACE_END(detail)
3035 +PYBIND11_NAMESPACE_END(detail)
3037 // pytype -> C++ type
3038 template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
3039 T cast(const handle &handle) {
3040 using namespace detail;
3041 static_assert(!cast_is_temporary_value_reference<T>::value,
3042 - "Unable to cast type to reference: value is local to type caster");
3043 + "Unable to cast type to reference: value is local to type caster");
3044 return cast_op<T>(load_type<T>(handle));
3047 // pytype -> pytype (calls converting constructor)
3048 template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
3049 -T cast(const handle &handle) { return T(reinterpret_borrow<object>(handle)); }
3050 +T cast(const handle &handle) {
3051 + return T(reinterpret_borrow<object>(handle));
3054 // C++ type -> py::object
3055 template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
3056 -object cast(const T &value, return_value_policy policy = return_value_policy::automatic_reference,
3057 +object cast(T &&value,
3058 + return_value_policy policy = return_value_policy::automatic_reference,
3059 handle parent = handle()) {
3060 - if (policy == return_value_policy::automatic)
3061 - policy = std::is_pointer<T>::value ? return_value_policy::take_ownership : return_value_policy::copy;
3062 - else if (policy == return_value_policy::automatic_reference)
3063 - policy = std::is_pointer<T>::value ? return_value_policy::reference : return_value_policy::copy;
3064 - return reinterpret_steal<object>(detail::make_caster<T>::cast(value, policy, parent));
3065 + using no_ref_T = typename std::remove_reference<T>::type;
3066 + if (policy == return_value_policy::automatic) {
3067 + policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
3068 + : std::is_lvalue_reference<T>::value ? return_value_policy::copy
3069 + : return_value_policy::move;
3070 + } else if (policy == return_value_policy::automatic_reference) {
3071 + policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
3072 + : std::is_lvalue_reference<T>::value ? return_value_policy::copy
3073 + : return_value_policy::move;
3075 + return reinterpret_steal<object>(
3076 + detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
3079 -template <typename T> T handle::cast() const { return pybind11::cast<T>(*this); }
3080 -template <> inline void handle::cast() const { return; }
3081 +template <typename T>
3082 +T handle::cast() const {
3083 + return pybind11::cast<T>(*this);
3086 +inline void handle::cast() const {
3090 template <typename T>
3091 detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
3092 - if (obj.ref_count() > 1)
3093 + if (obj.ref_count() > 1) {
3095 - throw cast_error("Unable to cast Python instance to C++ rvalue: instance has multiple references"
3097 + "Unable to cast Python instance to C++ rvalue: instance has multiple references"
3098 " (compile in debug mode for details)");
3100 - throw cast_error("Unable to move from Python " + (std::string) str(obj.get_type()) +
3101 - " instance to C++ " + type_id<T>() + " instance: instance has multiple references");
3102 + throw cast_error("Unable to move from Python " + (std::string) str(type::handle_of(obj))
3103 + + " instance to C++ " + type_id<T>()
3104 + + " instance: instance has multiple references");
3108 // Move into a temporary and return that, because the reference may be a local value of `conv`
3109 - T ret = std::move(detail::load_type<T>(obj).operator T&());
3110 + T ret = std::move(detail::load_type<T>(obj).operator T &());
3114 -// Calling cast() on an rvalue calls pybind::cast with the object rvalue, which does:
3115 +// Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
3116 // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
3117 // object has multiple references, but trying to copy will fail to compile.
3118 // - If both movable and copyable, check ref count: if 1, move; otherwise copy
3119 // - Otherwise (not movable), copy.
3120 -template <typename T> detail::enable_if_t<detail::move_always<T>::value, T> cast(object &&object) {
3121 +template <typename T>
3122 +detail::enable_if_t<detail::move_always<T>::value, T> cast(object &&object) {
3123 return move<T>(std::move(object));
3125 -template <typename T> detail::enable_if_t<detail::move_if_unreferenced<T>::value, T> cast(object &&object) {
3126 - if (object.ref_count() > 1)
3127 +template <typename T>
3128 +detail::enable_if_t<detail::move_if_unreferenced<T>::value, T> cast(object &&object) {
3129 + if (object.ref_count() > 1) {
3130 return cast<T>(object);
3132 - return move<T>(std::move(object));
3134 + return move<T>(std::move(object));
3136 -template <typename T> detail::enable_if_t<detail::move_never<T>::value, T> cast(object &&object) {
3137 +template <typename T>
3138 +detail::enable_if_t<detail::move_never<T>::value, T> cast(object &&object) {
3139 return cast<T>(object);
3142 -template <typename T> T object::cast() const & { return pybind11::cast<T>(*this); }
3143 -template <typename T> T object::cast() && { return pybind11::cast<T>(std::move(*this)); }
3144 -template <> inline void object::cast() const & { return; }
3145 -template <> inline void object::cast() && { return; }
3146 +template <typename T>
3147 +T object::cast() const & {
3148 + return pybind11::cast<T>(*this);
3150 +template <typename T>
3151 +T object::cast() && {
3152 + return pybind11::cast<T>(std::move(*this));
3155 +inline void object::cast() const & {
3159 +inline void object::cast() && {
3163 -NAMESPACE_BEGIN(detail)
3164 +PYBIND11_NAMESPACE_BEGIN(detail)
3166 // Declared in pytypes.h:
3167 template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
3168 -object object_or_cast(T &&o) { return pybind11::cast(std::forward<T>(o)); }
3169 +object object_or_cast(T &&o) {
3170 + return pybind11::cast(std::forward<T>(o));
3173 -struct overload_unused {}; // Placeholder type for the unneeded (and dead code) static variable in the OVERLOAD_INT macro
3174 -template <typename ret_type> using overload_caster_t = conditional_t<
3175 - cast_is_temporary_value_reference<ret_type>::value, make_caster<ret_type>, overload_unused>;
3176 +// Placeholder type for the unneeded (and dead code) static variable in the
3177 +// PYBIND11_OVERRIDE_OVERRIDE macro
3178 +struct override_unused {};
3179 +template <typename ret_type>
3180 +using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
3181 + make_caster<ret_type>,
3184 // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
3185 // store the result in the given variable. For other types, this is a no-op.
3186 -template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o, make_caster<T> &caster) {
3187 +template <typename T>
3188 +enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
3189 + make_caster<T> &caster) {
3190 return cast_op<T>(load_type(caster, o));
3192 -template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&, overload_unused &) {
3193 - pybind11_fail("Internal error: cast_ref fallback invoked"); }
3194 +template <typename T>
3195 +enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
3196 + override_unused &) {
3197 + pybind11_fail("Internal error: cast_ref fallback invoked");
3200 -// Trampoline use: Having a pybind11::cast with an invalid reference type is going to static_assert, even
3201 -// though if it's in dead code, so we provide a "trampoline" to pybind11::cast that only does anything in
3202 -// cases where pybind11::cast is valid.
3203 -template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&o) {
3204 - return pybind11::cast<T>(std::move(o)); }
3205 -template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
3206 - pybind11_fail("Internal error: cast_safe fallback invoked"); }
3207 -template <> inline void cast_safe<void>(object &&) {}
3208 +// Trampoline use: Having a pybind11::cast with an invalid reference type is going to
3209 +// static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
3210 +// that only does anything in cases where pybind11::cast is valid.
3211 +template <typename T>
3212 +enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&o) {
3213 + return pybind11::cast<T>(std::move(o));
3215 +template <typename T>
3216 +enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
3217 + pybind11_fail("Internal error: cast_safe fallback invoked");
3220 +inline void cast_safe<void>(object &&) {}
3222 -NAMESPACE_END(detail)
3223 +PYBIND11_NAMESPACE_END(detail)
3225 +// The overloads could coexist, i.e. the #if is not strictly speaking needed,
3226 +// but it is an easy minor optimization.
3227 +#if defined(NDEBUG)
3228 +inline cast_error cast_error_unable_to_convert_call_arg() {
3229 + return cast_error(
3230 + "Unable to convert call argument to Python object (compile in debug mode for details)");
3233 +inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
3234 + const std::string &type) {
3235 + return cast_error("Unable to convert call argument '" + name + "' of type '" + type
3236 + + "' to Python object");
3240 template <return_value_policy policy = return_value_policy::automatic_reference>
3241 -tuple make_tuple() { return tuple(0); }
3242 +tuple make_tuple() {
3246 -template <return_value_policy policy = return_value_policy::automatic_reference,
3247 - typename... Args> tuple make_tuple(Args&&... args_) {
3248 +template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
3249 +tuple make_tuple(Args &&...args_) {
3250 constexpr size_t size = sizeof...(Args);
3251 - std::array<object, size> args {
3252 - { reinterpret_steal<object>(detail::make_caster<Args>::cast(
3253 - std::forward<Args>(args_), policy, nullptr))... }
3255 + std::array<object, size> args{{reinterpret_steal<object>(
3256 + detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
3257 for (size_t i = 0; i < args.size(); i++) {
3260 - throw cast_error("make_tuple(): unable to convert arguments to Python object (compile in debug mode for details)");
3261 + throw cast_error_unable_to_convert_call_arg();
3263 - std::array<std::string, size> argtypes { {type_id<Args>()...} };
3264 - throw cast_error("make_tuple(): unable to convert argument of type '" +
3265 - argtypes[i] + "' to Python object");
3266 + std::array<std::string, size> argtypes{{type_id<Args>()...}};
3267 + throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
3273 - for (auto &arg_value : args)
3274 + for (auto &arg_value : args) {
3275 PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
3280 /// \ingroup annotations
3281 /// Annotation for arguments
3283 - /// Constructs an argument with the name of the argument; if null or omitted, this is a positional argument.
3284 - constexpr explicit arg(const char *name = nullptr) : name(name), flag_noconvert(false), flag_none(true) { }
3285 + /// Constructs an argument with the name of the argument; if null or omitted, this is a
3286 + /// positional argument.
3287 + constexpr explicit arg(const char *name = nullptr)
3288 + : name(name), flag_noconvert(false), flag_none(true) {}
3289 /// Assign a value to this argument
3290 - template <typename T> arg_v operator=(T &&value) const;
3291 + template <typename T>
3292 + arg_v operator=(T &&value) const;
3293 /// Indicate that the type should not be converted in the type caster
3294 - arg &noconvert(bool flag = true) { flag_noconvert = flag; return *this; }
3295 + arg &noconvert(bool flag = true) {
3296 + flag_noconvert = flag;
3299 /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
3300 - arg &none(bool flag = true) { flag_none = flag; return *this; }
3301 + arg &none(bool flag = true) {
3306 - const char *name; ///< If non-null, this is a named kwargs argument
3307 - bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type caster!)
3308 - bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
3309 + const char *name; ///< If non-null, this is a named kwargs argument
3310 + bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type
3312 + bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
3315 /// \ingroup annotations
3316 @@ -1798,32 +1266,44 @@
3318 template <typename T>
3319 arg_v(arg &&base, T &&x, const char *descr = nullptr)
3321 - value(reinterpret_steal<object>(
3322 - detail::make_caster<T>::cast(x, return_value_policy::automatic, {})
3324 + : arg(base), value(reinterpret_steal<object>(
3325 + detail::make_caster<T>::cast(x, return_value_policy::automatic, {}))),
3327 #if !defined(NDEBUG)
3328 - , type(type_id<T>())
3330 + type(type_id<T>())
3334 + // Workaround! See:
3335 + // https://github.com/pybind/pybind11/issues/2336
3336 + // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
3337 + if (PyErr_Occurred()) {
3343 /// Direct construction with name, default, and description
3344 template <typename T>
3345 arg_v(const char *name, T &&x, const char *descr = nullptr)
3346 - : arg_v(arg(name), std::forward<T>(x), descr) { }
3347 + : arg_v(arg(name), std::forward<T>(x), descr) {}
3349 /// Called internally when invoking `py::arg("a") = value`
3350 template <typename T>
3351 arg_v(const arg &base, T &&x, const char *descr = nullptr)
3352 - : arg_v(arg(base), std::forward<T>(x), descr) { }
3353 + : arg_v(arg(base), std::forward<T>(x), descr) {}
3355 /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
3356 - arg_v &noconvert(bool flag = true) { arg::noconvert(flag); return *this; }
3357 + arg_v &noconvert(bool flag = true) {
3358 + arg::noconvert(flag);
3362 /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
3363 - arg_v &none(bool flag = true) { arg::none(flag); return *this; }
3364 + arg_v &none(bool flag = true) {
3369 /// The default value
3371 @@ -1835,20 +1315,38 @@
3375 +/// \ingroup annotations
3376 +/// Annotation indicating that all following arguments are keyword-only; the is the equivalent of
3377 +/// an unnamed '*' argument (in Python 3)
3380 +/// \ingroup annotations
3381 +/// Annotation indicating that all previous arguments are positional-only; the is the equivalent of
3382 +/// an unnamed '/' argument (in Python 3.8)
3383 +struct pos_only {};
3385 template <typename T>
3386 -arg_v arg::operator=(T &&value) const { return {std::move(*this), std::forward<T>(value)}; }
3387 +arg_v arg::operator=(T &&value) const {
3388 + return {*this, std::forward<T>(value)};
3391 /// Alias for backward compatibility -- to be removed in version 2.0
3392 -template <typename /*unused*/> using arg_t = arg_v;
3393 +template <typename /*unused*/>
3394 +using arg_t = arg_v;
3396 inline namespace literals {
3398 String literal version of `arg`
3400 constexpr arg operator"" _a(const char *name, size_t) { return arg(name); }
3402 +} // namespace literals
3404 -NAMESPACE_BEGIN(detail)
3405 +PYBIND11_NAMESPACE_BEGIN(detail)
3407 +template <typename T>
3408 +using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
3409 +template <typename T>
3410 +using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
3412 // forward declaration (definition in attr.h)
3413 struct function_record;
3414 @@ -1877,57 +1375,69 @@
3419 /// Helper class which loads arguments for C++ functions called from Python
3420 template <typename... Args>
3421 class argument_loader {
3422 using indices = make_index_sequence<sizeof...(Args)>;
3424 - template <typename Arg> using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
3425 - template <typename Arg> using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
3426 - // Get args/kwargs argument positions relative to the end of the argument list:
3427 - static constexpr auto args_pos = constexpr_first<argument_is_args, Args...>() - (int) sizeof...(Args),
3428 - kwargs_pos = constexpr_first<argument_is_kwargs, Args...>() - (int) sizeof...(Args);
3430 - static constexpr bool args_kwargs_are_last = kwargs_pos >= - 1 && args_pos >= kwargs_pos - 1;
3431 + template <typename Arg>
3432 + using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
3433 + template <typename Arg>
3434 + using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
3435 + // Get kwargs argument position, or -1 if not present:
3436 + static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
3438 - static_assert(args_kwargs_are_last, "py::args/py::kwargs are only permitted as the last argument(s) of a function");
3439 + static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
3440 + "py::kwargs is only permitted as the last argument of a function");
3443 - static constexpr bool has_kwargs = kwargs_pos < 0;
3444 - static constexpr bool has_args = args_pos < 0;
3445 + static constexpr bool has_kwargs = kwargs_pos != -1;
3447 + // py::args argument position; -1 if not present.
3448 + static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
3450 + static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
3451 + "py::args cannot be specified more than once");
3453 static constexpr auto arg_names = concat(type_descr(make_caster<Args>::name)...);
3455 - bool load_args(function_call &call) {
3456 - return load_impl_sequence(call, indices{});
3458 + bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
3460 template <typename Return, typename Guard, typename Func>
3461 + // NOLINTNEXTLINE(readability-const-return-type)
3462 enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
3463 - return std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
3464 + return std::move(*this).template call_impl<remove_cv_t<Return>>(
3465 + std::forward<Func>(f), indices{}, Guard{});
3468 template <typename Return, typename Guard, typename Func>
3469 enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
3470 - std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
3471 + std::move(*this).template call_impl<remove_cv_t<Return>>(
3472 + std::forward<Func>(f), indices{}, Guard{});
3478 static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
3480 template <size_t... Is>
3481 bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
3482 - for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...})
3484 +#ifdef __cpp_fold_expressions
3485 + if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
3489 + for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
3498 template <typename Return, typename Func, size_t... Is, typename Guard>
3499 - Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) {
3500 + Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
3501 return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
3504 @@ -1941,7 +1451,7 @@
3506 template <typename... Ts>
3507 explicit simple_collector(Ts &&...values)
3508 - : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) { }
3509 + : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) {}
3511 const tuple &args() const & { return m_args; }
3512 dict kwargs() const { return {}; }
3513 @@ -1951,8 +1461,9 @@
3514 /// Call a Python function and pass the collected arguments
3515 object call(PyObject *ptr) const {
3516 PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
3519 throw error_already_set();
3521 return reinterpret_steal<object>(result);
3524 @@ -1969,8 +1480,8 @@
3525 // Tuples aren't (easily) resizable so a list is needed for collection,
3526 // but the actual function call strictly requires a tuple.
3527 auto args_list = list();
3528 - int _[] = { 0, (process(args_list, std::forward<Ts>(values)), 0)... };
3530 + using expander = int[];
3531 + (void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...};
3533 m_args = std::move(args_list);
3535 @@ -1984,38 +1495,42 @@
3536 /// Call a Python function and pass the collected arguments
3537 object call(PyObject *ptr) const {
3538 PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
3541 throw error_already_set();
3543 return reinterpret_steal<object>(result);
3547 template <typename T>
3548 void process(list &args_list, T &&x) {
3549 - auto o = reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
3550 + auto o = reinterpret_steal<object>(
3551 + detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
3554 - argument_cast_error();
3555 + throw cast_error_unable_to_convert_call_arg();
3557 - argument_cast_error(std::to_string(args_list.size()), type_id<T>());
3558 + throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()),
3562 args_list.append(o);
3565 void process(list &args_list, detail::args_proxy ap) {
3566 - for (const auto &a : ap)
3567 + for (auto a : ap) {
3568 args_list.append(a);
3572 - void process(list &/*args_list*/, arg_v a) {
3574 + void process(list & /*args_list*/, arg_v a) {
3577 nameless_argument_error();
3579 nameless_argument_error(a.type);
3583 if (m_kwargs.contains(a.name)) {
3585 multiple_values_error();
3586 @@ -2025,18 +1540,19 @@
3590 - argument_cast_error();
3591 + throw cast_error_unable_to_convert_call_arg();
3593 - argument_cast_error(a.name, a.type);
3594 + throw cast_error_unable_to_convert_call_arg(a.name, a.type);
3597 m_kwargs[a.name] = a.value;
3600 - void process(list &/*args_list*/, detail::kwargs_proxy kp) {
3602 + void process(list & /*args_list*/, detail::kwargs_proxy kp) {
3605 - for (const auto &k : reinterpret_borrow<dict>(kp)) {
3607 + for (auto k : reinterpret_borrow<dict>(kp)) {
3608 if (m_kwargs.contains(k.first)) {
3610 multiple_values_error();
3611 @@ -2053,58 +1569,65 @@
3612 "may be passed via py::arg() to a python function call. "
3613 "(compile in debug mode for details)");
3615 - [[noreturn]] static void nameless_argument_error(std::string type) {
3616 - throw type_error("Got kwargs without a name of type '" + type + "'; only named "
3617 - "arguments may be passed via py::arg() to a python function call. ");
3618 + [[noreturn]] static void nameless_argument_error(const std::string &type) {
3619 + throw type_error("Got kwargs without a name of type '" + type
3620 + + "'; only named "
3621 + "arguments may be passed via py::arg() to a python function call. ");
3623 [[noreturn]] static void multiple_values_error() {
3624 throw type_error("Got multiple values for keyword argument "
3625 "(compile in debug mode for details)");
3628 - [[noreturn]] static void multiple_values_error(std::string name) {
3629 + [[noreturn]] static void multiple_values_error(const std::string &name) {
3630 throw type_error("Got multiple values for keyword argument '" + name + "'");
3633 - [[noreturn]] static void argument_cast_error() {
3634 - throw cast_error("Unable to convert call argument to Python object "
3635 - "(compile in debug mode for details)");
3638 - [[noreturn]] static void argument_cast_error(std::string name, std::string type) {
3639 - throw cast_error("Unable to convert call argument '" + name
3640 - + "' of type '" + type + "' to Python object");
3648 +// [workaround(intel)] Separate function required here
3649 +// We need to put this into a separate function because the Intel compiler
3650 +// fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
3651 +// (tested with ICC 2021.1 Beta 20200827).
3652 +template <typename... Args>
3653 +constexpr bool args_are_all_positional() {
3654 + return all_of<is_positional<Args>...>::value;
3657 /// Collect only positional arguments for a Python function call
3658 -template <return_value_policy policy, typename... Args,
3659 - typename = enable_if_t<all_of<is_positional<Args>...>::value>>
3660 +template <return_value_policy policy,
3662 + typename = enable_if_t<args_are_all_positional<Args...>()>>
3663 simple_collector<policy> collect_arguments(Args &&...args) {
3664 return simple_collector<policy>(std::forward<Args>(args)...);
3667 /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
3668 -template <return_value_policy policy, typename... Args,
3669 - typename = enable_if_t<!all_of<is_positional<Args>...>::value>>
3670 +template <return_value_policy policy,
3672 + typename = enable_if_t<!args_are_all_positional<Args...>()>>
3673 unpacking_collector<policy> collect_arguments(Args &&...args) {
3674 // Following argument order rules for generalized unpacking according to PEP 448
3676 - constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>()
3677 - && constexpr_last<is_s_unpacking, Args...>() < constexpr_first<is_ds_unpacking, Args...>(),
3678 - "Invalid function call: positional args must precede keywords and ** unpacking; "
3679 - "* unpacking must precede ** unpacking"
3681 + static_assert(constexpr_last<is_positional, Args...>()
3682 + < constexpr_first<is_keyword_or_ds, Args...>()
3683 + && constexpr_last<is_s_unpacking, Args...>()
3684 + < constexpr_first<is_ds_unpacking, Args...>(),
3685 + "Invalid function call: positional args must precede keywords and ** unpacking; "
3686 + "* unpacking must precede ** unpacking");
3687 return unpacking_collector<policy>(std::forward<Args>(args)...);
3690 template <typename Derived>
3691 template <return_value_policy policy, typename... Args>
3692 object object_api<Derived>::operator()(Args &&...args) const {
3693 +#if !defined(NDEBUG) && PY_VERSION_HEX >= 0x03060000
3694 + if (!PyGILState_Check()) {
3695 + pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
3698 return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
3701 @@ -2114,15 +1637,27 @@
3702 return operator()<policy>(std::forward<Args>(args)...);
3705 -NAMESPACE_END(detail)
3706 +PYBIND11_NAMESPACE_END(detail)
3708 -#define PYBIND11_MAKE_OPAQUE(...) \
3709 - namespace pybind11 { namespace detail { \
3710 - template<> class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> { }; \
3712 +template <typename T>
3713 +handle type::handle_of() {
3714 + static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
3715 + "py::type::of<T> only supports the case where T is a registered C++ types.");
3717 + return detail::get_type_handle(typeid(T), true);
3720 +#define PYBIND11_MAKE_OPAQUE(...) \
3721 + namespace pybind11 { \
3722 + namespace detail { \
3724 + class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
3728 /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
3729 -/// typedef, e.g.: `PYBIND11_OVERLOAD(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
3731 +/// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
3732 #define PYBIND11_TYPE(...) __VA_ARGS__
3734 -NAMESPACE_END(PYBIND11_NAMESPACE)
3735 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
3736 diff -Nur pythia8309.orig/plugins/python/include/pybind11/chrono.h pythia8309/plugins/python/include/pybind11/chrono.h
3737 --- pythia8309.orig/plugins/python/include/pybind11/chrono.h 2023-02-16 18:12:45.000000000 +0100
3738 +++ pythia8309/plugins/python/include/pybind11/chrono.h 2023-03-13 09:52:25.453021589 +0100
3742 #include "pybind11.h"
3748 #include <datetime.h>
3751 // Backport the PyDateTime_DELTA functions from Python3.3 if required
3752 #ifndef PyDateTime_DELTA_GET_DAYS
3753 -#define PyDateTime_DELTA_GET_DAYS(o) (((PyDateTime_Delta*)o)->days)
3754 +# define PyDateTime_DELTA_GET_DAYS(o) (((PyDateTime_Delta *) o)->days)
3756 #ifndef PyDateTime_DELTA_GET_SECONDS
3757 -#define PyDateTime_DELTA_GET_SECONDS(o) (((PyDateTime_Delta*)o)->seconds)
3758 +# define PyDateTime_DELTA_GET_SECONDS(o) (((PyDateTime_Delta *) o)->seconds)
3760 #ifndef PyDateTime_DELTA_GET_MICROSECONDS
3761 -#define PyDateTime_DELTA_GET_MICROSECONDS(o) (((PyDateTime_Delta*)o)->microseconds)
3762 +# define PyDateTime_DELTA_GET_MICROSECONDS(o) (((PyDateTime_Delta *) o)->microseconds)
3765 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
3766 -NAMESPACE_BEGIN(detail)
3767 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
3768 +PYBIND11_NAMESPACE_BEGIN(detail)
3770 -template <typename type> class duration_caster {
3771 +template <typename type>
3772 +class duration_caster {
3774 - typedef typename type::rep rep;
3775 - typedef typename type::period period;
3776 + using rep = typename type::rep;
3777 + using period = typename type::period;
3779 - typedef std::chrono::duration<uint_fast32_t, std::ratio<86400>> days;
3780 + // signed 25 bits required by the standard.
3781 + using days = std::chrono::duration<int_least32_t, std::ratio<86400>>;
3783 bool load(handle src, bool) {
3784 using namespace std::chrono;
3786 // Lazy initialise the PyDateTime import
3787 - if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
3788 + if (!PyDateTimeAPI) {
3789 + PyDateTime_IMPORT;
3792 - if (!src) return false;
3796 // If invoked with datetime.delta object
3797 if (PyDelta_Check(src.ptr())) {
3798 value = type(duration_cast<duration<rep, period>>(
3799 - days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
3800 + days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
3801 + seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))
3802 + microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));
3805 // If invoked with a float we assume it is seconds and convert
3806 - else if (PyFloat_Check(src.ptr())) {
3807 - value = type(duration_cast<duration<rep, period>>(duration<double>(PyFloat_AsDouble(src.ptr()))));
3808 + if (PyFloat_Check(src.ptr())) {
3809 + value = type(duration_cast<duration<rep, period>>(
3810 + duration<double>(PyFloat_AsDouble(src.ptr()))));
3813 - else return false;
3817 // If this is a duration just return it back
3818 - static const std::chrono::duration<rep, period>& get_duration(const std::chrono::duration<rep, period> &src) {
3819 + static const std::chrono::duration<rep, period> &
3820 + get_duration(const std::chrono::duration<rep, period> &src) {
3824 // If this is a time_point get the time_since_epoch
3825 - template <typename Clock> static std::chrono::duration<rep, period> get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
3826 + template <typename Clock>
3827 + static std::chrono::duration<rep, period>
3828 + get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
3829 return src.time_since_epoch();
3833 auto d = get_duration(src);
3835 // Lazy initialise the PyDateTime import
3836 - if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
3837 + if (!PyDateTimeAPI) {
3838 + PyDateTime_IMPORT;
3841 - // Declare these special duration types so the conversions happen with the correct primitive types (int)
3842 + // Declare these special duration types so the conversions happen with the correct
3843 + // primitive types (int)
3844 using dd_t = duration<int, std::ratio<86400>>;
3845 using ss_t = duration<int, std::ratio<1>>;
3846 using us_t = duration<int, std::micro>;
3847 @@ -92,71 +107,130 @@
3848 return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
3851 - PYBIND11_TYPE_CASTER(type, _("datetime.timedelta"));
3852 + PYBIND11_TYPE_CASTER(type, const_name("datetime.timedelta"));
3855 +inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) {
3856 +#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER)
3857 + if (localtime_s(buf, time))
3861 + static std::mutex mtx;
3862 + std::lock_guard<std::mutex> lock(mtx);
3863 + std::tm *tm_ptr = std::localtime(time);
3864 + if (tm_ptr != nullptr) {
3871 // This is for casting times on the system clock into datetime.datetime instances
3872 -template <typename Duration> class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
3873 +template <typename Duration>
3874 +class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
3876 - typedef std::chrono::time_point<std::chrono::system_clock, Duration> type;
3877 + using type = std::chrono::time_point<std::chrono::system_clock, Duration>;
3878 bool load(handle src, bool) {
3879 using namespace std::chrono;
3881 // Lazy initialise the PyDateTime import
3882 - if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
3883 + if (!PyDateTimeAPI) {
3884 + PyDateTime_IMPORT;
3892 + microseconds msecs;
3894 - if (!src) return false;
3895 if (PyDateTime_Check(src.ptr())) {
3897 - cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
3898 - cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
3899 - cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
3900 - cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
3901 - cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
3902 - cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
3903 + cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
3904 + cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
3905 + cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
3906 + cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
3907 + cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
3908 + cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
3911 - value = system_clock::from_time_t(std::mktime(&cal)) + microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
3913 + msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
3914 + } else if (PyDate_Check(src.ptr())) {
3918 + cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
3919 + cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
3920 + cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
3921 + cal.tm_isdst = -1;
3922 + msecs = microseconds(0);
3923 + } else if (PyTime_Check(src.ptr())) {
3924 + cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
3925 + cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
3926 + cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
3927 + cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
3928 + cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
3929 + cal.tm_year = 70; // earliest available date for Python's datetime
3930 + cal.tm_isdst = -1;
3931 + msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
3935 - else return false;
3937 + value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);
3941 - static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src, return_value_policy /* policy */, handle /* parent */) {
3942 + static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src,
3943 + return_value_policy /* policy */,
3944 + handle /* parent */) {
3945 using namespace std::chrono;
3947 // Lazy initialise the PyDateTime import
3948 - if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
3950 - std::time_t tt = system_clock::to_time_t(src);
3951 - // this function uses static memory so it's best to copy it out asap just in case
3952 - // otherwise other code that is using localtime may break this (not just python code)
3953 - std::tm localtime = *std::localtime(&tt);
3954 + if (!PyDateTimeAPI) {
3955 + PyDateTime_IMPORT;
3958 - // Declare these special duration types so the conversions happen with the correct primitive types (int)
3959 + // Get out microseconds, and make sure they are positive, to avoid bug in eastern
3960 + // hemisphere time zones (cfr. https://github.com/pybind/pybind11/issues/2417)
3961 using us_t = duration<int, std::micro>;
3962 + auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
3963 + if (us.count() < 0) {
3967 + // Subtract microseconds BEFORE `system_clock::to_time_t`, because:
3968 + // > If std::time_t has lower precision, it is implementation-defined whether the value is
3969 + // rounded or truncated. (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
3971 + = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
3973 + std::tm localtime;
3974 + std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime);
3975 + if (!localtime_ptr) {
3976 + throw cast_error("Unable to represent system_clock in local time");
3978 return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
3979 localtime.tm_mon + 1,
3984 - (duration_cast<us_t>(src.time_since_epoch() % seconds(1))).count());
3987 - PYBIND11_TYPE_CASTER(type, _("datetime.datetime"));
3988 + PYBIND11_TYPE_CASTER(type, const_name("datetime.datetime"));
3991 // Other clocks that are not the system clock are not measured as datetime.datetime objects
3992 // since they are not measured on calendar time. So instead we just make them timedeltas
3993 // Or if they have passed us a time as a float we convert that
3994 -template <typename Clock, typename Duration> class type_caster<std::chrono::time_point<Clock, Duration>>
3995 -: public duration_caster<std::chrono::time_point<Clock, Duration>> {
3998 -template <typename Rep, typename Period> class type_caster<std::chrono::duration<Rep, Period>>
3999 -: public duration_caster<std::chrono::duration<Rep, Period>> {
4001 +template <typename Clock, typename Duration>
4002 +class type_caster<std::chrono::time_point<Clock, Duration>>
4003 + : public duration_caster<std::chrono::time_point<Clock, Duration>> {};
4005 +template <typename Rep, typename Period>
4006 +class type_caster<std::chrono::duration<Rep, Period>>
4007 + : public duration_caster<std::chrono::duration<Rep, Period>> {};
4009 -NAMESPACE_END(detail)
4010 -NAMESPACE_END(PYBIND11_NAMESPACE)
4011 +PYBIND11_NAMESPACE_END(detail)
4012 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
4013 diff -Nur pythia8309.orig/plugins/python/include/pybind11/complex.h pythia8309/plugins/python/include/pybind11/complex.h
4014 --- pythia8309.orig/plugins/python/include/pybind11/complex.h 2023-02-16 18:12:45.000000000 +0100
4015 +++ pythia8309/plugins/python/include/pybind11/complex.h 2023-03-13 09:52:25.453021589 +0100
4019 #include "pybind11.h"
4023 /// glibc defines I as a macro which breaks things, e.g., boost template names
4029 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
4030 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
4032 -template <typename T> struct format_descriptor<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
4033 +template <typename T>
4034 +struct format_descriptor<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
4035 static constexpr const char c = format_descriptor<T>::c;
4036 - static constexpr const char value[3] = { 'Z', c, '\0' };
4037 + static constexpr const char value[3] = {'Z', c, '\0'};
4038 static std::string format() { return std::string(value); }
4041 #ifndef PYBIND11_CPP17
4043 -template <typename T> constexpr const char format_descriptor<
4044 - std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>>::value[3];
4045 +template <typename T>
4046 +constexpr const char
4047 + format_descriptor<std::complex<T>,
4048 + detail::enable_if_t<std::is_floating_point<T>::value>>::value[3];
4052 -NAMESPACE_BEGIN(detail)
4053 +PYBIND11_NAMESPACE_BEGIN(detail)
4055 -template <typename T> struct is_fmt_numeric<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
4056 +template <typename T>
4057 +struct is_fmt_numeric<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
4058 static constexpr bool value = true;
4059 static constexpr int index = is_fmt_numeric<T>::index + 3;
4062 -template <typename T> class type_caster<std::complex<T>> {
4063 +template <typename T>
4064 +class type_caster<std::complex<T>> {
4066 bool load(handle src, bool convert) {
4070 - if (!convert && !PyComplex_Check(src.ptr()))
4072 + if (!convert && !PyComplex_Check(src.ptr())) {
4075 Py_complex result = PyComplex_AsCComplex(src.ptr());
4076 if (result.real == -1.0 && PyErr_Occurred()) {
4082 - static handle cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {
4084 + cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {
4085 return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
4088 - PYBIND11_TYPE_CASTER(std::complex<T>, _("complex"));
4089 + PYBIND11_TYPE_CASTER(std::complex<T>, const_name("complex"));
4091 -NAMESPACE_END(detail)
4092 -NAMESPACE_END(PYBIND11_NAMESPACE)
4093 +PYBIND11_NAMESPACE_END(detail)
4094 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
4095 diff -Nur pythia8309.orig/plugins/python/include/pybind11/detail/class.h pythia8309/plugins/python/include/pybind11/detail/class.h
4096 --- pythia8309.orig/plugins/python/include/pybind11/detail/class.h 2023-02-16 18:12:45.000000000 +0100
4097 +++ pythia8309/plugins/python/include/pybind11/detail/class.h 2023-03-13 09:52:25.454021591 +0100
4101 #include "../attr.h"
4102 +#include "../options.h"
4104 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
4105 -NAMESPACE_BEGIN(detail)
4106 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
4107 +PYBIND11_NAMESPACE_BEGIN(detail)
4109 -#if PY_VERSION_HEX >= 0x03030000
4110 -# define PYBIND11_BUILTIN_QUALNAME
4111 -# define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
4112 +#if PY_VERSION_HEX >= 0x03030000 && !defined(PYPY_VERSION)
4113 +# define PYBIND11_BUILTIN_QUALNAME
4114 +# define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
4116 // In pre-3.3 Python, we still set __qualname__ so that we can produce reliable function type
4117 // signatures; in 3.3+ this macro expands to nothing:
4118 -# define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) setattr((PyObject *) obj, "__qualname__", nameobj)
4119 +# define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) \
4120 + setattr((PyObject *) obj, "__qualname__", nameobj)
4123 +inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
4124 +#if !defined(PYPY_VERSION)
4125 + return type->tp_name;
4127 + auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
4128 + if (module_name == PYBIND11_BUILTINS_MODULE)
4129 + return type->tp_name;
4131 + return std::move(module_name) + "." + type->tp_name;
4135 inline PyTypeObject *type_incref(PyTypeObject *type) {
4139 issue no Python C API calls which could potentially invoke the
4140 garbage collector (the GC will call type_traverse(), which will in
4141 turn find the newly constructed type in an invalid state) */
4142 - auto heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
4144 + auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
4146 pybind11_fail("make_static_property_type(): error allocating type!");
4149 heap_type->ht_name = name_obj.inc_ref().ptr();
4150 -#ifdef PYBIND11_BUILTIN_QUALNAME
4151 +# ifdef PYBIND11_BUILTIN_QUALNAME
4152 heap_type->ht_qualname = name_obj.inc_ref().ptr();
4156 - auto type = &heap_type->ht_type;
4157 + auto *type = &heap_type->ht_type;
4158 type->tp_name = name;
4159 type->tp_base = type_incref(&PyProperty_Type);
4160 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
4161 type->tp_descr_get = pybind11_static_get;
4162 type->tp_descr_set = pybind11_static_set;
4164 - if (PyType_Ready(type) < 0)
4165 + if (PyType_Ready(type) < 0) {
4166 pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
4169 setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
4170 PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
4171 @@ -85,15 +101,17 @@
4172 inline PyTypeObject *make_static_property_type() {
4174 PyObject *result = PyRun_String(R"(\
4175 - class pybind11_static_property(property):
4176 - def __get__(self, obj, cls):
4177 - return property.__get__(self, cls, cls)
4179 - def __set__(self, obj, value):
4180 - cls = obj if isinstance(obj, type) else type(obj)
4181 - property.__set__(self, cls, value)
4182 - )", Py_file_input, d.ptr(), d.ptr()
4184 +class pybind11_static_property(property):
4185 + def __get__(self, obj, cls):
4186 + return property.__get__(self, cls, cls)
4188 + def __set__(self, obj, value):
4189 + cls = obj if isinstance(obj, type) else type(obj)
4190 + property.__set__(self, cls, value)
4195 if (result == nullptr)
4196 throw error_already_set();
4199 By default, Python replaces the `static_property` itself, but for wrapped C++ types
4200 we need to call `static_property.__set__()` in order to propagate the new value to
4201 the underlying C++ data structure. */
4202 -extern "C" inline int pybind11_meta_setattro(PyObject* obj, PyObject* name, PyObject* value) {
4203 +extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
4204 // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
4205 // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
4206 PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
4207 @@ -115,9 +133,10 @@
4208 // 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
4209 // 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
4210 // 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
4211 - const auto static_prop = (PyObject *) get_internals().static_property_type;
4212 - const auto call_descr_set = descr && PyObject_IsInstance(descr, static_prop)
4213 - && !PyObject_IsInstance(value, static_prop);
4214 + auto *const static_prop = (PyObject *) get_internals().static_property_type;
4215 + const auto call_descr_set = (descr != nullptr) && (value != nullptr)
4216 + && (PyObject_IsInstance(descr, static_prop) != 0)
4217 + && (PyObject_IsInstance(value, static_prop) == 0);
4218 if (call_descr_set) {
4219 // Call `static_property.__set__()` instead of replacing the `static_property`.
4220 #if !defined(PYPY_VERSION)
4221 @@ -149,16 +168,79 @@
4226 - return PyType_Type.tp_getattro(obj, name);
4228 + return PyType_Type.tp_getattro(obj, name);
4232 +/// metaclass `__call__` function that is used to create all pybind11 objects.
4233 +extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
4235 + // use the default metaclass call to create/initialize the object
4236 + PyObject *self = PyType_Type.tp_call(type, args, kwargs);
4237 + if (self == nullptr) {
4241 + // This must be a pybind11 instance
4242 + auto *instance = reinterpret_cast<detail::instance *>(self);
4244 + // Ensure that the base __init__ function(s) were called
4245 + for (const auto &vh : values_and_holders(instance)) {
4246 + if (!vh.holder_constructed()) {
4247 + PyErr_Format(PyExc_TypeError,
4248 + "%.200s.__init__() must be called when overriding __init__",
4249 + get_fully_qualified_tp_name(vh.type->type).c_str());
4258 +/// Cleanup the type-info for a pybind11-registered type.
4259 +extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
4260 + auto *type = (PyTypeObject *) obj;
4261 + auto &internals = get_internals();
4263 + // A pybind11-registered type will:
4264 + // 1) be found in internals.registered_types_py
4265 + // 2) have exactly one associated `detail::type_info`
4266 + auto found_type = internals.registered_types_py.find(type);
4267 + if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
4268 + && found_type->second[0]->type == type) {
4270 + auto *tinfo = found_type->second[0];
4271 + auto tindex = std::type_index(*tinfo->cpptype);
4272 + internals.direct_conversions.erase(tindex);
4274 + if (tinfo->module_local) {
4275 + get_local_internals().registered_types_cpp.erase(tindex);
4277 + internals.registered_types_cpp.erase(tindex);
4279 + internals.registered_types_py.erase(tinfo->type);
4281 + // Actually just `std::erase_if`, but that's only available in C++20
4282 + auto &cache = internals.inactive_override_cache;
4283 + for (auto it = cache.begin(), last = cache.end(); it != last;) {
4284 + if (it->first == (PyObject *) tinfo->type) {
4285 + it = cache.erase(it);
4294 + PyType_Type.tp_dealloc(obj);
4297 /** This metaclass is assigned by default to all pybind11 types and is required in order
4298 for static properties to function correctly. Users may override this using `py::metaclass`.
4299 Return value: New reference. */
4300 -inline PyTypeObject* make_default_metaclass() {
4301 +inline PyTypeObject *make_default_metaclass() {
4302 constexpr auto *name = "pybind11_type";
4303 auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
4305 @@ -166,27 +248,33 @@
4306 issue no Python C API calls which could potentially invoke the
4307 garbage collector (the GC will call type_traverse(), which will in
4308 turn find the newly constructed type in an invalid state) */
4309 - auto heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
4311 + auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
4313 pybind11_fail("make_default_metaclass(): error allocating metaclass!");
4316 heap_type->ht_name = name_obj.inc_ref().ptr();
4317 #ifdef PYBIND11_BUILTIN_QUALNAME
4318 heap_type->ht_qualname = name_obj.inc_ref().ptr();
4321 - auto type = &heap_type->ht_type;
4322 + auto *type = &heap_type->ht_type;
4323 type->tp_name = name;
4324 type->tp_base = type_incref(&PyType_Type);
4325 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
4327 + type->tp_call = pybind11_meta_call;
4329 type->tp_setattro = pybind11_meta_setattro;
4330 #if PY_MAJOR_VERSION >= 3
4331 type->tp_getattro = pybind11_meta_getattro;
4334 - if (PyType_Ready(type) < 0)
4335 + type->tp_dealloc = pybind11_meta_dealloc;
4337 + if (PyType_Ready(type) < 0) {
4338 pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
4341 setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
4342 PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
4343 @@ -196,16 +284,20 @@
4345 /// For multiple inheritance types we need to recursively register/deregister base pointers for any
4346 /// base classes with pointers that are difference from the instance value pointer so that we can
4347 -/// correctly recognize an offset base class pointer. This calls a function with any offset base ptrs.
4348 -inline void traverse_offset_bases(void *valueptr, const detail::type_info *tinfo, instance *self,
4349 - bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
4350 +/// correctly recognize an offset base class pointer. This calls a function with any offset base
4352 +inline void traverse_offset_bases(void *valueptr,
4353 + const detail::type_info *tinfo,
4355 + bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
4356 for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
4357 - if (auto parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
4358 + if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
4359 for (auto &c : parent_tinfo->implicit_casts) {
4360 if (c.first == tinfo->cpptype) {
4361 auto *parentptr = c.second(valueptr);
4362 - if (parentptr != valueptr)
4363 + if (parentptr != valueptr) {
4366 traverse_offset_bases(parentptr, parent_tinfo, self, f);
4370 auto ®istered_instances = get_internals().registered_instances;
4371 auto range = registered_instances.equal_range(ptr);
4372 for (auto it = range.first; it != range.second; ++it) {
4373 - if (Py_TYPE(self) == Py_TYPE(it->second)) {
4374 + if (self == it->second) {
4375 registered_instances.erase(it);
4378 @@ -232,36 +324,36 @@
4380 inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
4381 register_instance_impl(valptr, self);
4382 - if (!tinfo->simple_ancestors)
4383 + if (!tinfo->simple_ancestors) {
4384 traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
4388 inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
4389 bool ret = deregister_instance_impl(valptr, self);
4390 - if (!tinfo->simple_ancestors)
4391 + if (!tinfo->simple_ancestors) {
4392 traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
4397 -/// Instance creation function for all pybind11 types. It allocates the internal instance layout for
4398 -/// holding C++ objects and holders. Allocation is done lazily (the first time the instance is cast
4399 -/// to a reference or pointer), and initialization is done by an `__init__` function.
4400 +/// Instance creation function for all pybind11 types. It allocates the internal instance layout
4401 +/// for holding C++ objects and holders. Allocation is done lazily (the first time the instance is
4402 +/// cast to a reference or pointer), and initialization is done by an `__init__` function.
4403 inline PyObject *make_new_instance(PyTypeObject *type) {
4404 #if defined(PYPY_VERSION)
4405 - // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first inherited
4406 - // object is a a plain Python type (i.e. not derived from an extension type). Fix it.
4407 + // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
4408 + // inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
4409 ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
4410 if (type->tp_basicsize < instance_size) {
4411 type->tp_basicsize = instance_size;
4414 PyObject *self = type->tp_alloc(type, 0);
4415 - auto inst = reinterpret_cast<instance *>(self);
4416 + auto *inst = reinterpret_cast<instance *>(self);
4417 // Allocate the value/holder internals:
4418 inst->allocate_layout();
4420 - inst->owned = true;
4425 @@ -276,26 +368,21 @@
4426 /// following default function will be used which simply throws an exception.
4427 extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
4428 PyTypeObject *type = Py_TYPE(self);
4430 -#if defined(PYPY_VERSION)
4431 - msg += handle((PyObject *) type).attr("__module__").cast<std::string>() + ".";
4433 - msg += type->tp_name;
4434 - msg += ": No constructor defined!";
4435 + std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
4436 PyErr_SetString(PyExc_TypeError, msg.c_str());
4440 inline void add_patient(PyObject *nurse, PyObject *patient) {
4441 auto &internals = get_internals();
4442 - auto instance = reinterpret_cast<detail::instance *>(nurse);
4443 + auto *instance = reinterpret_cast<detail::instance *>(nurse);
4444 instance->has_patients = true;
4446 internals.patients[nurse].push_back(patient);
4449 inline void clear_patients(PyObject *self) {
4450 - auto instance = reinterpret_cast<detail::instance *>(self);
4451 + auto *instance = reinterpret_cast<detail::instance *>(self);
4452 auto &internals = get_internals();
4453 auto pos = internals.patients.find(self);
4454 assert(pos != internals.patients.end());
4455 @@ -305,14 +392,15 @@
4456 auto patients = std::move(pos->second);
4457 internals.patients.erase(pos);
4458 instance->has_patients = false;
4459 - for (PyObject *&patient : patients)
4460 + for (PyObject *&patient : patients) {
4465 /// Clears all internal data from the instance and removes it from registered instances in
4466 /// preparation for deallocation.
4467 inline void clear_instance(PyObject *self) {
4468 - auto instance = reinterpret_cast<detail::instance *>(self);
4469 + auto *instance = reinterpret_cast<detail::instance *>(self);
4471 // Deallocate any values/holders, if present:
4472 for (auto &v_h : values_and_holders(instance)) {
4473 @@ -320,25 +408,32 @@
4475 // We have to deregister before we call dealloc because, for virtual MI types, we still
4476 // need to be able to get the parent pointers.
4477 - if (v_h.instance_registered() && !deregister_instance(instance, v_h.value_ptr(), v_h.type))
4478 - pybind11_fail("pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
4479 + if (v_h.instance_registered()
4480 + && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
4482 + "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
4485 - if (instance->owned || v_h.holder_constructed())
4486 + if (instance->owned || v_h.holder_constructed()) {
4487 v_h.type->dealloc(v_h);
4491 // Deallocate the value/holder layout internals:
4492 instance->deallocate_layout();
4494 - if (instance->weakrefs)
4495 + if (instance->weakrefs) {
4496 PyObject_ClearWeakRefs(self);
4499 PyObject **dict_ptr = _PyObject_GetDictPtr(self);
4502 Py_CLEAR(*dict_ptr);
4505 - if (instance->has_patients)
4506 + if (instance->has_patients) {
4507 clear_patients(self);
4511 /// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
4512 @@ -346,9 +441,10 @@
4513 extern "C" inline void pybind11_object_dealloc(PyObject *self) {
4514 clear_instance(self);
4516 - auto type = Py_TYPE(self);
4517 + auto *type = Py_TYPE(self);
4518 type->tp_free(self);
4520 +#if PY_VERSION_HEX < 0x03080000
4521 // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
4522 // as part of a derived type's dealloc, in which case we're not allowed to decref
4523 // the type here. For cross-module compatibility, we shouldn't compare directly
4524 @@ -356,6 +452,11 @@
4525 auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
4526 if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
4529 + // This was not needed before Python 3.8 (Python issue 35810)
4530 + // https://github.com/pybind/pybind11/issues/1946
4535 /** Create the type which can be used as a common base for all classes. This is
4536 @@ -369,16 +470,17 @@
4537 issue no Python C API calls which could potentially invoke the
4538 garbage collector (the GC will call type_traverse(), which will in
4539 turn find the newly constructed type in an invalid state) */
4540 - auto heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
4542 + auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
4544 pybind11_fail("make_object_base_type(): error allocating type!");
4547 heap_type->ht_name = name_obj.inc_ref().ptr();
4548 #ifdef PYBIND11_BUILTIN_QUALNAME
4549 heap_type->ht_qualname = name_obj.inc_ref().ptr();
4552 - auto type = &heap_type->ht_type;
4553 + auto *type = &heap_type->ht_type;
4554 type->tp_name = name;
4555 type->tp_base = type_incref(&PyBaseObject_Type);
4556 type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
4558 /* Support weak references (needed for the keep_alive feature) */
4559 type->tp_weaklistoffset = offsetof(instance, weakrefs);
4561 - if (PyType_Ready(type) < 0)
4562 + if (PyType_Ready(type) < 0) {
4563 pybind11_fail("PyType_Ready failed in make_object_base_type():" + error_string());
4566 setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
4567 PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
4569 /// dynamic_attr: Support for `d = instance.__dict__`.
4570 extern "C" inline PyObject *pybind11_get_dict(PyObject *self, void *) {
4571 PyObject *&dict = *_PyObject_GetDictPtr(self);
4574 dict = PyDict_New();
4580 /// dynamic_attr: Support for `instance.__dict__ = dict()`.
4581 extern "C" inline int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *) {
4582 if (!PyDict_Check(new_dict)) {
4583 - PyErr_Format(PyExc_TypeError, "__dict__ must be set to a dictionary, not a '%.200s'",
4584 - Py_TYPE(new_dict)->tp_name);
4585 + PyErr_Format(PyExc_TypeError,
4586 + "__dict__ must be set to a dictionary, not a '%.200s'",
4587 + get_fully_qualified_tp_name(Py_TYPE(new_dict)).c_str());
4590 PyObject *&dict = *_PyObject_GetDictPtr(self);
4591 @@ -440,22 +545,16 @@
4593 /// Give instances of this type a `__dict__` and opt into garbage collection.
4594 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
4595 - auto type = &heap_type->ht_type;
4596 -#if defined(PYPY_VERSION)
4597 - pybind11_fail(std::string(type->tp_name) + ": dynamic attributes are "
4598 - "currently not supported in "
4599 - "conjunction with PyPy!");
4601 + auto *type = &heap_type->ht_type;
4602 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
4603 - type->tp_dictoffset = type->tp_basicsize; // place dict at the end
4604 - type->tp_basicsize += (ssize_t)sizeof(PyObject *); // and allocate enough space for it
4605 + type->tp_dictoffset = type->tp_basicsize; // place dict at the end
4606 + type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
4607 type->tp_traverse = pybind11_traverse;
4608 type->tp_clear = pybind11_clear;
4610 static PyGetSetDef getset[] = {
4611 - {const_cast<char*>("__dict__"), pybind11_get_dict, pybind11_set_dict, nullptr, nullptr},
4612 - {nullptr, nullptr, nullptr, nullptr, nullptr}
4614 + {const_cast<char *>("__dict__"), pybind11_get_dict, pybind11_set_dict, nullptr, nullptr},
4615 + {nullptr, nullptr, nullptr, nullptr, nullptr}};
4616 type->tp_getset = getset;
4619 @@ -465,31 +564,42 @@
4620 type_info *tinfo = nullptr;
4621 for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
4622 tinfo = get_type_info((PyTypeObject *) type.ptr());
4623 - if (tinfo && tinfo->get_buffer)
4624 + if (tinfo && tinfo->get_buffer) {
4628 - if (view == nullptr || obj == nullptr || !tinfo || !tinfo->get_buffer) {
4630 + if (view == nullptr || !tinfo || !tinfo->get_buffer) {
4632 view->obj = nullptr;
4634 PyErr_SetString(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
4637 std::memset(view, 0, sizeof(Py_buffer));
4638 buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
4639 + if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
4641 + // view->obj = nullptr; // Was just memset to 0, so not necessary
4642 + PyErr_SetString(PyExc_BufferError, "Writable buffer requested for readonly storage");
4647 view->internal = info;
4648 view->buf = info->ptr;
4649 view->itemsize = info->itemsize;
4650 view->len = view->itemsize;
4651 - for (auto s : info->shape)
4652 + for (auto s : info->shape) {
4654 - if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
4656 + view->readonly = static_cast<int>(info->readonly);
4657 + if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
4658 view->format = const_cast<char *>(info->format.c_str());
4660 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
4661 view->ndim = (int) info->ndim;
4662 - view->strides = &info->strides[0];
4663 - view->shape = &info->shape[0];
4664 + view->strides = info->strides.data();
4665 + view->shape = info->shape.data();
4667 Py_INCREF(view->obj);
4671 /** Create a brand new Python type according to the `type_record` specification.
4672 Return value: New reference. */
4673 -inline PyObject* make_new_python_type(const type_record &rec) {
4674 +inline PyObject *make_new_python_type(const type_record &rec) {
4675 auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
4677 auto qualname = name;
4678 @@ -526,57 +636,59 @@
4685 - if (hasattr(rec.scope, "__module__"))
4686 - module = rec.scope.attr("__module__");
4687 - else if (hasattr(rec.scope, "__name__"))
4688 - module = rec.scope.attr("__name__");
4689 + if (hasattr(rec.scope, "__module__")) {
4690 + module_ = rec.scope.attr("__module__");
4691 + } else if (hasattr(rec.scope, "__name__")) {
4692 + module_ = rec.scope.attr("__name__");
4696 - auto full_name = c_str(
4697 + const auto *full_name = c_str(
4698 #if !defined(PYPY_VERSION)
4699 - module ? str(module).cast<std::string>() + "." + rec.name :
4700 + module_ ? str(module_).cast<std::string>() + "." + rec.name :
4705 char *tp_doc = nullptr;
4706 if (rec.doc && options::show_user_defined_docstrings()) {
4707 /* Allocate memory for docstring (using PyObject_MALLOC, since
4708 Python will free this later on) */
4709 - size_t size = strlen(rec.doc) + 1;
4710 + size_t size = std::strlen(rec.doc) + 1;
4711 tp_doc = (char *) PyObject_MALLOC(size);
4712 - memcpy((void *) tp_doc, rec.doc, size);
4713 + std::memcpy((void *) tp_doc, rec.doc, size);
4716 auto &internals = get_internals();
4717 auto bases = tuple(rec.bases);
4718 - auto base = (bases.size() == 0) ? internals.instance_base
4720 + auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
4722 /* Danger zone: from now (and until PyType_Ready), make sure to
4723 issue no Python C API calls which could potentially invoke the
4724 garbage collector (the GC will call type_traverse(), which will in
4725 turn find the newly constructed type in an invalid state) */
4726 - auto metaclass = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr()
4727 - : internals.default_metaclass;
4729 + = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
4731 - auto heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
4733 + auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
4735 pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
4738 heap_type->ht_name = name.release().ptr();
4739 #ifdef PYBIND11_BUILTIN_QUALNAME
4740 heap_type->ht_qualname = qualname.inc_ref().ptr();
4743 - auto type = &heap_type->ht_type;
4744 + auto *type = &heap_type->ht_type;
4745 type->tp_name = full_name;
4746 type->tp_doc = tp_doc;
4747 - type->tp_base = type_incref((PyTypeObject *)base);
4748 + type->tp_base = type_incref((PyTypeObject *) base);
4749 type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
4750 - if (bases.size() > 0)
4751 + if (!bases.empty()) {
4752 type->tp_bases = bases.release().ptr();
4755 /* Don't inherit base __init__ */
4756 type->tp_init = pybind11_object_init;
4757 @@ -585,38 +697,52 @@
4758 type->tp_as_number = &heap_type->as_number;
4759 type->tp_as_sequence = &heap_type->as_sequence;
4760 type->tp_as_mapping = &heap_type->as_mapping;
4761 +#if PY_VERSION_HEX >= 0x03050000
4762 + type->tp_as_async = &heap_type->as_async;
4766 - type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
4767 + type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
4768 #if PY_MAJOR_VERSION < 3
4769 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
4771 + if (!rec.is_final) {
4772 + type->tp_flags |= Py_TPFLAGS_BASETYPE;
4775 - if (rec.dynamic_attr)
4776 + if (rec.dynamic_attr) {
4777 enable_dynamic_attributes(heap_type);
4780 - if (rec.buffer_protocol)
4781 + if (rec.buffer_protocol) {
4782 enable_buffer_protocol(heap_type);
4785 + if (rec.custom_type_setup_callback) {
4786 + rec.custom_type_setup_callback(heap_type);
4789 - if (PyType_Ready(type) < 0)
4790 + if (PyType_Ready(type) < 0) {
4791 pybind11_fail(std::string(rec.name) + ": PyType_Ready failed (" + error_string() + ")!");
4794 - assert(rec.dynamic_attr ? PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC)
4795 - : !PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
4796 + assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
4798 /* Register type with the parent scope */
4801 setattr(rec.scope, rec.name, (PyObject *) type);
4804 Py_INCREF(type); // Keep it alive forever (reference leak)
4807 - if (module) // Needed by pydoc
4808 - setattr((PyObject *) type, "__module__", module);
4809 + if (module_) { // Needed by pydoc
4810 + setattr((PyObject *) type, "__module__", module_);
4813 PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
4815 return (PyObject *) type;
4818 -NAMESPACE_END(detail)
4819 -NAMESPACE_END(PYBIND11_NAMESPACE)
4820 +PYBIND11_NAMESPACE_END(detail)
4821 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
4822 diff -Nur pythia8309.orig/plugins/python/include/pybind11/detail/common.h pythia8309/plugins/python/include/pybind11/detail/common.h
4823 --- pythia8309.orig/plugins/python/include/pybind11/detail/common.h 2023-02-16 18:12:45.000000000 +0100
4824 +++ pythia8309/plugins/python/include/pybind11/detail/common.h 2023-03-13 09:52:25.456021595 +0100
4829 -#if !defined(NAMESPACE_BEGIN)
4830 -# define NAMESPACE_BEGIN(name) namespace name {
4832 -#if !defined(NAMESPACE_END)
4833 -# define NAMESPACE_END(name) }
4835 +#define PYBIND11_VERSION_MAJOR 2
4836 +#define PYBIND11_VERSION_MINOR 9
4837 +#define PYBIND11_VERSION_PATCH 2
4839 +// Similar to Python's convention: https://docs.python.org/3/c-api/apiabiversion.html
4840 +// Additional convention: 0xD = dev
4841 +#define PYBIND11_VERSION_HEX 0x02090200
4843 +#define PYBIND11_NAMESPACE_BEGIN(name) namespace name {
4844 +#define PYBIND11_NAMESPACE_END(name) }
4846 // Robust support for some features and loading modules compiled against different pybind versions
4847 -// requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute on
4848 -// the main `pybind11` namespace.
4849 +// requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute
4850 +// on the main `pybind11` namespace.
4851 #if !defined(PYBIND11_NAMESPACE)
4853 -# define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
4855 -# define PYBIND11_NAMESPACE pybind11
4858 +# define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
4860 +# define PYBIND11_NAMESPACE pybind11
4864 -#if !(defined(_MSC_VER) && __cplusplus == 199711L) && !defined(__INTEL_COMPILER)
4865 -# if __cplusplus >= 201402L
4866 -# define PYBIND11_CPP14
4867 -# if __cplusplus >= 201703L
4868 -# define PYBIND11_CPP17
4869 +#if !(defined(_MSC_VER) && __cplusplus == 199711L)
4870 +# if __cplusplus >= 201402L
4871 +# define PYBIND11_CPP14
4872 +# if __cplusplus >= 201703L
4873 +# define PYBIND11_CPP17
4874 +# if __cplusplus >= 202002L
4875 +# define PYBIND11_CPP20
4880 #elif defined(_MSC_VER) && __cplusplus == 199711L
4881 -// MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully implemented)
4882 -// Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3 or newer
4883 -# if _MSVC_LANG >= 201402L
4884 -# define PYBIND11_CPP14
4885 -# if _MSVC_LANG > 201402L && _MSC_VER >= 1910
4886 -# define PYBIND11_CPP17
4887 +// MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully
4888 +// implemented). Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3
4890 +# if _MSVC_LANG >= 201402L
4891 +# define PYBIND11_CPP14
4892 +# if _MSVC_LANG > 201402L && _MSC_VER >= 1910
4893 +# define PYBIND11_CPP17
4894 +# if _MSVC_LANG >= 202002L
4895 +# define PYBIND11_CPP20
4902 // Compiler version assertions
4903 #if defined(__INTEL_COMPILER)
4904 -# if __INTEL_COMPILER < 1700
4905 -# error pybind11 requires Intel C++ compiler v17 or newer
4907 +# if __INTEL_COMPILER < 1800
4908 +# error pybind11 requires Intel C++ compiler v18 or newer
4909 +# elif __INTEL_COMPILER < 1900 && defined(PYBIND11_CPP14)
4910 +# error pybind11 supports only C++11 with Intel C++ compiler v18. Use v19 or newer for C++14.
4912 +/* The following pragma cannot be pop'ed:
4913 + https://community.intel.com/t5/Intel-C-Compiler/Inline-and-no-inline-warning/td-p/1216764 */
4914 +# pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
4915 #elif defined(__clang__) && !defined(__apple_build_version__)
4916 -# if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
4917 -# error pybind11 requires clang 3.3 or newer
4919 +# if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
4920 +# error pybind11 requires clang 3.3 or newer
4922 #elif defined(__clang__)
4923 // Apple changes clang version macros to its Xcode version; the first Xcode release based on
4924 // (upstream) clang 3.3 was Xcode 5:
4925 -# if __clang_major__ < 5
4926 -# error pybind11 requires Xcode/clang 5.0 or newer
4928 +# if __clang_major__ < 5
4929 +# error pybind11 requires Xcode/clang 5.0 or newer
4931 #elif defined(__GNUG__)
4932 -# if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
4933 -# error pybind11 requires gcc 4.8 or newer
4935 +# if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
4936 +# error pybind11 requires gcc 4.8 or newer
4938 #elif defined(_MSC_VER)
4939 // Pybind hits various compiler bugs in 2015u2 and earlier, and also makes use of some stl features
4940 // (e.g. std::negation) added in 2015u3:
4941 -# if _MSC_FULL_VER < 190024210
4942 -# error pybind11 requires MSVC 2015 update 3 or newer
4944 +# if _MSC_FULL_VER < 190024210
4945 +# error pybind11 requires MSVC 2015 update 3 or newer
4949 #if !defined(PYBIND11_EXPORT)
4950 -# if defined(WIN32) || defined(_WIN32)
4951 -# define PYBIND11_EXPORT __declspec(dllexport)
4953 -# define PYBIND11_EXPORT __attribute__ ((visibility("default")))
4955 +# if defined(WIN32) || defined(_WIN32)
4956 +# define PYBIND11_EXPORT __declspec(dllexport)
4958 +# define PYBIND11_EXPORT __attribute__((visibility("default")))
4962 -#if defined(_MSC_VER)
4963 -# define PYBIND11_NOINLINE __declspec(noinline)
4964 +#if !defined(PYBIND11_EXPORT_EXCEPTION)
4965 +# ifdef __MINGW32__
4967 +// error: 'dllexport' implies default visibility, but xxx has already been declared with a
4968 +// different visibility
4969 +# define PYBIND11_EXPORT_EXCEPTION
4971 +# define PYBIND11_EXPORT_EXCEPTION PYBIND11_EXPORT
4975 +// For CUDA, GCC7, GCC8:
4976 +// PYBIND11_NOINLINE_FORCED is incompatible with `-Wattributes -Werror`.
4977 +// When defining PYBIND11_NOINLINE_FORCED, it is best to also use `-Wno-attributes`.
4978 +// However, the measured shared-library size saving when using noinline are only
4979 +// 1.7% for CUDA, -0.2% for GCC7, and 0.0% for GCC8 (using -DCMAKE_BUILD_TYPE=MinSizeRel,
4980 +// the default under pybind11/tests).
4981 +#if !defined(PYBIND11_NOINLINE_FORCED) \
4982 + && (defined(__CUDACC__) || (defined(__GNUC__) && (__GNUC__ == 7 || __GNUC__ == 8)))
4983 +# define PYBIND11_NOINLINE_DISABLED
4986 +// The PYBIND11_NOINLINE macro is for function DEFINITIONS.
4987 +// In contrast, FORWARD DECLARATIONS should never use this macro:
4988 +// https://stackoverflow.com/questions/9317473/forward-declaration-of-inline-functions
4989 +#if defined(PYBIND11_NOINLINE_DISABLED) // Option for maximum portability and experimentation.
4990 +# define PYBIND11_NOINLINE inline
4991 +#elif defined(_MSC_VER)
4992 +# define PYBIND11_NOINLINE __declspec(noinline) inline
4994 -# define PYBIND11_NOINLINE __attribute__ ((noinline))
4995 +# define PYBIND11_NOINLINE __attribute__((noinline)) inline
4998 -#if defined(PYBIND11_CPP14)
4999 -# define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
5000 +#if defined(__MINGW32__)
5001 +// For unknown reasons all PYBIND11_DEPRECATED member trigger a warning when declared
5002 +// whether it is used or not
5003 +# define PYBIND11_DEPRECATED(reason)
5004 +#elif defined(PYBIND11_CPP14)
5005 +# define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
5007 -# define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
5008 +# define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
5011 -#define PYBIND11_VERSION_MAJOR 2
5012 -#define PYBIND11_VERSION_MINOR 3
5013 -#define PYBIND11_VERSION_PATCH dev0
5014 +#if defined(PYBIND11_CPP17)
5015 +# define PYBIND11_MAYBE_UNUSED [[maybe_unused]]
5016 +#elif defined(_MSC_VER) && !defined(__clang__)
5017 +# define PYBIND11_MAYBE_UNUSED
5019 +# define PYBIND11_MAYBE_UNUSED __attribute__((__unused__))
5022 +/* Don't let Python.h #define (v)snprintf as macro because they are implemented
5023 + properly in Visual Studio since 2015. */
5024 +#if defined(_MSC_VER) && _MSC_VER >= 1900
5025 +# define HAVE_SNPRINTF 1
5028 /// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
5029 #if defined(_MSC_VER)
5030 -# if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 4)
5031 -# define HAVE_ROUND 1
5033 -# pragma warning(push)
5034 -# pragma warning(disable: 4510 4610 4512 4005)
5035 -# if defined(_DEBUG)
5036 -# define PYBIND11_DEBUG_MARKER
5039 +# pragma warning(push)
5040 +// C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
5041 +# pragma warning(disable : 4505)
5042 +# if defined(_DEBUG) && !defined(Py_DEBUG)
5043 +// Workaround for a VS 2022 issue.
5044 +// NOTE: This workaround knowingly violates the Python.h include order requirement:
5045 +// https://docs.python.org/3/c-api/intro.html#include-files
5046 +// See https://github.com/pybind/pybind11/pull/3497 for full context.
5047 +# include <yvals.h>
5048 +# if _MSVC_STL_VERSION >= 143
5049 +# include <crtdefs.h>
5051 +# define PYBIND11_DEBUG_MARKER
5056 +// https://en.cppreference.com/w/c/chrono/localtime
5057 +#if defined(__STDC_LIB_EXT1__) && !defined(__STDC_WANT_LIB_EXT1__)
5058 +# define __STDC_WANT_LIB_EXT1__
5061 +#ifdef __has_include
5062 +// std::optional (but including it in c++14 mode isn't allowed)
5063 +# if defined(PYBIND11_CPP17) && __has_include(<optional>)
5064 +# define PYBIND11_HAS_OPTIONAL 1
5066 +// std::experimental::optional (but not allowed in c++11 mode)
5067 +# if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
5068 + !__has_include(<optional>))
5069 +# define PYBIND11_HAS_EXP_OPTIONAL 1
5072 +# if defined(PYBIND11_CPP17) && __has_include(<variant>)
5073 +# define PYBIND11_HAS_VARIANT 1
5075 +#elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
5076 +# define PYBIND11_HAS_OPTIONAL 1
5077 +# define PYBIND11_HAS_VARIANT 1
5080 +#if defined(PYBIND11_CPP17)
5081 +# if defined(__has_include)
5082 +# if __has_include(<string_view>)
5083 +# define PYBIND11_HAS_STRING_VIEW
5085 +# elif defined(_MSC_VER)
5086 +# define PYBIND11_HAS_STRING_VIEW
5090 +#if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
5091 +# define PYBIND11_HAS_U8STRING
5095 #include <frameobject.h>
5096 #include <pythread.h>
5098 -#if defined(_WIN32) && (defined(min) || defined(max))
5099 -# error Macro clash with min and max -- define NOMINMAX when compiling your program on Windows
5100 +/* Python #defines overrides on all sorts of core functions, which
5101 + tends to weak havok in C++ codebases that expect these to work
5102 + like regular functions (potentially with several overloads) */
5103 +#if defined(isalnum)
5113 -#if defined(isalnum)
5121 +#if defined(copysign)
5125 #if defined(_MSC_VER)
5126 -# if defined(PYBIND11_DEBUG_MARKER)
5128 -# undef PYBIND11_DEBUG_MARKER
5130 -# pragma warning(pop)
5131 +# if defined(PYBIND11_DEBUG_MARKER)
5133 +# undef PYBIND11_DEBUG_MARKER
5135 +# pragma warning(pop)
5140 +#include <exception>
5141 #include <forward_list>
5144 -#include <stdexcept>
5145 -#include <unordered_set>
5146 -#include <unordered_map>
5148 -#include <typeindex>
5149 +#include <stdexcept>
5151 #include <type_traits>
5152 +#include <typeindex>
5153 +#include <unordered_map>
5154 +#include <unordered_set>
5156 +#if defined(__has_include)
5157 +# if __has_include(<version>)
5158 +# include <version>
5162 +// #define PYBIND11_STR_LEGACY_PERMISSIVE
5163 +// If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
5164 +// (probably surprising and never documented, but this was the
5165 +// legacy behavior until and including v2.6.x). As a side-effect,
5166 +// pybind11::isinstance<str>() is true for both pybind11::str and
5167 +// pybind11::bytes.
5168 +// If UNDEFINED, pybind11::str can only hold PyUnicodeObject, and
5169 +// pybind11::isinstance<str>() is true only for pybind11::str.
5170 +// However, for Python 2 only (!), the pybind11::str caster
5171 +// implicitly decodes bytes to PyUnicodeObject. This is to ease
5172 +// the transition from the legacy behavior to the non-permissive
5175 #if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
5176 -#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
5177 -#define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
5178 -#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
5179 -#define PYBIND11_BYTES_CHECK PyBytes_Check
5180 -#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
5181 -#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
5182 -#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
5183 -#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
5184 -#define PYBIND11_BYTES_SIZE PyBytes_Size
5185 -#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
5186 -#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
5187 -#define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) o)
5188 -#define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) o)
5189 -#define PYBIND11_BYTES_NAME "bytes"
5190 -#define PYBIND11_STRING_NAME "str"
5191 -#define PYBIND11_SLICE_OBJECT PyObject
5192 -#define PYBIND11_FROM_STRING PyUnicode_FromString
5193 -#define PYBIND11_STR_TYPE ::pybind11::str
5194 -#define PYBIND11_BOOL_ATTR "__bool__"
5195 -#define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
5196 -#define PYBIND11_PLUGIN_IMPL(name) \
5197 - extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
5200 -#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
5201 -#define PYBIND11_INSTANCE_METHOD_CHECK PyMethod_Check
5202 -#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyMethod_GET_FUNCTION
5203 -#define PYBIND11_BYTES_CHECK PyString_Check
5204 -#define PYBIND11_BYTES_FROM_STRING PyString_FromString
5205 -#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
5206 -#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
5207 -#define PYBIND11_BYTES_AS_STRING PyString_AsString
5208 -#define PYBIND11_BYTES_SIZE PyString_Size
5209 -#define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
5210 -#define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
5211 -#define PYBIND11_LONG_FROM_SIGNED(o) PyInt_FromSsize_t((ssize_t) o) // Returns long if needed.
5212 -#define PYBIND11_LONG_FROM_UNSIGNED(o) PyInt_FromSize_t((size_t) o) // Returns long if needed.
5213 -#define PYBIND11_BYTES_NAME "str"
5214 -#define PYBIND11_STRING_NAME "unicode"
5215 -#define PYBIND11_SLICE_OBJECT PySliceObject
5216 -#define PYBIND11_FROM_STRING PyString_FromString
5217 -#define PYBIND11_STR_TYPE ::pybind11::bytes
5218 -#define PYBIND11_BOOL_ATTR "__nonzero__"
5219 -#define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_nonzero)
5220 -#define PYBIND11_PLUGIN_IMPL(name) \
5221 - static PyObject *pybind11_init_wrapper(); \
5222 - extern "C" PYBIND11_EXPORT void init##name() { \
5223 - (void)pybind11_init_wrapper(); \
5225 - PyObject *pybind11_init_wrapper()
5226 +# define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
5227 +# define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
5228 +# define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
5229 +# define PYBIND11_BYTES_CHECK PyBytes_Check
5230 +# define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
5231 +# define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
5232 +# define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
5233 +# define PYBIND11_BYTES_AS_STRING PyBytes_AsString
5234 +# define PYBIND11_BYTES_SIZE PyBytes_Size
5235 +# define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
5236 +# define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
5237 +# define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) (o))
5238 +# define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) (o))
5239 +# define PYBIND11_BYTES_NAME "bytes"
5240 +# define PYBIND11_STRING_NAME "str"
5241 +# define PYBIND11_SLICE_OBJECT PyObject
5242 +# define PYBIND11_FROM_STRING PyUnicode_FromString
5243 +# define PYBIND11_STR_TYPE ::pybind11::str
5244 +# define PYBIND11_BOOL_ATTR "__bool__"
5245 +# define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
5246 +# define PYBIND11_BUILTINS_MODULE "builtins"
5247 +// Providing a separate declaration to make Clang's -Wmissing-prototypes happy.
5248 +// See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
5249 +# define PYBIND11_PLUGIN_IMPL(name) \
5250 + extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT PyObject *PyInit_##name(); \
5251 + extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
5254 +# define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
5255 +# define PYBIND11_INSTANCE_METHOD_CHECK PyMethod_Check
5256 +# define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyMethod_GET_FUNCTION
5257 +# define PYBIND11_BYTES_CHECK PyString_Check
5258 +# define PYBIND11_BYTES_FROM_STRING PyString_FromString
5259 +# define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
5260 +# define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
5261 +# define PYBIND11_BYTES_AS_STRING PyString_AsString
5262 +# define PYBIND11_BYTES_SIZE PyString_Size
5263 +# define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
5264 +# define PYBIND11_LONG_AS_LONGLONG(o) \
5265 + (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
5266 +# define PYBIND11_LONG_FROM_SIGNED(o) PyInt_FromSsize_t((ssize_t) o) // Returns long if needed.
5267 +# define PYBIND11_LONG_FROM_UNSIGNED(o) PyInt_FromSize_t((size_t) o) // Returns long if needed.
5268 +# define PYBIND11_BYTES_NAME "str"
5269 +# define PYBIND11_STRING_NAME "unicode"
5270 +# define PYBIND11_SLICE_OBJECT PySliceObject
5271 +# define PYBIND11_FROM_STRING PyString_FromString
5272 +# define PYBIND11_STR_TYPE ::pybind11::bytes
5273 +# define PYBIND11_BOOL_ATTR "__nonzero__"
5274 +# define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_nonzero)
5275 +# define PYBIND11_BUILTINS_MODULE "__builtin__"
5276 +// Providing a separate PyInit decl to make Clang's -Wmissing-prototypes happy.
5277 +// See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
5278 +# define PYBIND11_PLUGIN_IMPL(name) \
5279 + static PyObject *pybind11_init_wrapper(); \
5280 + extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT void init##name(); \
5281 + extern "C" PYBIND11_EXPORT void init##name() { (void) pybind11_init_wrapper(); } \
5282 + PyObject *pybind11_init_wrapper()
5285 #if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
5287 - struct _Py_atomic_address { void *value; };
5288 - PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
5289 +struct _Py_atomic_address {
5292 +PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
5296 @@ -211,63 +343,88 @@
5297 #define PYBIND11_STRINGIFY(x) #x
5298 #define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
5299 #define PYBIND11_CONCAT(first, second) first##second
5300 +#define PYBIND11_ENSURE_INTERNALS_READY pybind11::detail::get_internals();
5302 -#define PYBIND11_CHECK_PYTHON_VERSION \
5304 - const char *compiled_ver = PYBIND11_TOSTRING(PY_MAJOR_VERSION) \
5305 - "." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
5306 - const char *runtime_ver = Py_GetVersion(); \
5307 - size_t len = std::strlen(compiled_ver); \
5308 - if (std::strncmp(runtime_ver, compiled_ver, len) != 0 \
5309 - || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) { \
5310 - PyErr_Format(PyExc_ImportError, \
5311 - "Python version mismatch: module was compiled for Python %s, " \
5312 - "but the interpreter version is incompatible: %s.", \
5313 - compiled_ver, runtime_ver); \
5316 +#define PYBIND11_CHECK_PYTHON_VERSION \
5318 + const char *compiled_ver \
5319 + = PYBIND11_TOSTRING(PY_MAJOR_VERSION) "." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
5320 + const char *runtime_ver = Py_GetVersion(); \
5321 + size_t len = std::strlen(compiled_ver); \
5322 + if (std::strncmp(runtime_ver, compiled_ver, len) != 0 \
5323 + || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) { \
5324 + PyErr_Format(PyExc_ImportError, \
5325 + "Python version mismatch: module was compiled for Python %s, " \
5326 + "but the interpreter version is incompatible: %s.", \
5333 -#define PYBIND11_CATCH_INIT_EXCEPTIONS \
5334 - catch (pybind11::error_already_set &e) { \
5335 - PyErr_SetString(PyExc_ImportError, e.what()); \
5337 - } catch (const std::exception &e) { \
5338 - PyErr_SetString(PyExc_ImportError, e.what()); \
5341 +#if PY_VERSION_HEX >= 0x03030000
5343 +# define PYBIND11_CATCH_INIT_EXCEPTIONS \
5344 + catch (pybind11::error_already_set & e) { \
5345 + pybind11::raise_from(e, PyExc_ImportError, "initialization failed"); \
5348 + catch (const std::exception &e) { \
5349 + PyErr_SetString(PyExc_ImportError, e.what()); \
5355 +# define PYBIND11_CATCH_INIT_EXCEPTIONS \
5356 + catch (pybind11::error_already_set & e) { \
5357 + PyErr_SetString(PyExc_ImportError, e.what()); \
5360 + catch (const std::exception &e) { \
5361 + PyErr_SetString(PyExc_ImportError, e.what()); \
5368 ***Deprecated in favor of PYBIND11_MODULE***
5370 This macro creates the entry point that will be invoked when the Python interpreter
5371 - imports a plugin library. Please create a `module` in the function body and return
5372 + imports a plugin library. Please create a `module_` in the function body and return
5373 the pointer to its underlying Python object at the end.
5377 PYBIND11_PLUGIN(example) {
5378 - pybind11::module m("example", "pybind11 example plugin");
5379 + pybind11::module_ m("example", "pybind11 example plugin");
5380 /// Set up bindings here
5384 -#define PYBIND11_PLUGIN(name) \
5385 - PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE") \
5386 - static PyObject *pybind11_init(); \
5387 - PYBIND11_PLUGIN_IMPL(name) { \
5388 - PYBIND11_CHECK_PYTHON_VERSION \
5390 - return pybind11_init(); \
5391 - } PYBIND11_CATCH_INIT_EXCEPTIONS \
5393 +#define PYBIND11_PLUGIN(name) \
5394 + PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE") \
5395 + static PyObject *pybind11_init(); \
5396 + PYBIND11_PLUGIN_IMPL(name) { \
5397 + PYBIND11_CHECK_PYTHON_VERSION \
5398 + PYBIND11_ENSURE_INTERNALS_READY \
5400 + return pybind11_init(); \
5402 + PYBIND11_CATCH_INIT_EXCEPTIONS \
5404 PyObject *pybind11_init()
5407 This macro creates the entry point that will be invoked when the Python interpreter
5408 imports an extension module. The module name is given as the fist argument and it
5409 should not be in quotes. The second macro argument defines a variable of type
5410 - `py::module` which can be used to initialize the module.
5411 + `py::module_` which can be used to initialize the module.
5413 + The entry point is marked as "maybe unused" to aid dead-code detection analysis:
5414 + since the entry point is typically only looked up at runtime and not referenced
5415 + during translation, it would otherwise appear as unused ("dead") code.
5419 @@ -280,23 +437,34 @@
5423 -#define PYBIND11_MODULE(name, variable) \
5424 - static void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &); \
5425 - PYBIND11_PLUGIN_IMPL(name) { \
5426 - PYBIND11_CHECK_PYTHON_VERSION \
5427 - auto m = pybind11::module(PYBIND11_TOSTRING(name)); \
5429 - PYBIND11_CONCAT(pybind11_init_, name)(m); \
5431 - } PYBIND11_CATCH_INIT_EXCEPTIONS \
5433 - void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &variable)
5435 +#define PYBIND11_MODULE(name, variable) \
5436 + static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name) \
5437 + PYBIND11_MAYBE_UNUSED; \
5438 + PYBIND11_MAYBE_UNUSED \
5439 + static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
5440 + PYBIND11_PLUGIN_IMPL(name) { \
5441 + PYBIND11_CHECK_PYTHON_VERSION \
5442 + PYBIND11_ENSURE_INTERNALS_READY \
5443 + auto m = ::pybind11::module_::create_extension_module( \
5444 + PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \
5446 + PYBIND11_CONCAT(pybind11_init_, name)(m); \
5449 + PYBIND11_CATCH_INIT_EXCEPTIONS \
5451 + void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ & (variable))
5453 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
5454 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
5456 using ssize_t = Py_ssize_t;
5457 -using size_t = std::size_t;
5458 +using size_t = std::size_t;
5460 +template <typename IntType>
5461 +inline ssize_t ssize_t_cast(const IntType &val) {
5462 + static_assert(sizeof(IntType) <= sizeof(ssize_t), "Implicit narrowing is not permitted.");
5463 + return static_cast<ssize_t>(val);
5466 /// Approach used to cast a previously unknown C++ instance into a Python object
5467 enum class return_value_policy : uint8_t {
5468 @@ -350,12 +518,16 @@
5472 -NAMESPACE_BEGIN(detail)
5473 +PYBIND11_NAMESPACE_BEGIN(detail)
5475 -inline static constexpr int log2(size_t n, int k = 0) { return (n <= 1) ? k : log2(n >> 1, k + 1); }
5476 +inline static constexpr int log2(size_t n, int k = 0) {
5477 + return (n <= 1) ? k : log2(n >> 1, k + 1);
5480 // Returns the size as a multiple of sizeof(void *), rounded up.
5481 -inline static constexpr size_t size_in_ptrs(size_t s) { return 1 + ((s - 1) >> log2(sizeof(void *))); }
5482 +inline static constexpr size_t size_in_ptrs(size_t s) {
5483 + return 1 + ((s - 1) >> log2(sizeof(void *)));
5487 * The space to allocate for simple layout instance holders (see below) in multiple of the size of
5490 constexpr size_t instance_simple_holder_in_ptrs() {
5491 static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
5492 - "pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
5493 + "pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
5494 return size_in_ptrs(sizeof(std::shared_ptr<int>));
5497 @@ -393,21 +565,21 @@
5499 * An instance has two possible value/holder layouts.
5501 - * Simple layout (when this flag is true), means the `simple_value_holder` is set with a pointer
5502 - * and the holder object governing that pointer, i.e. [val1*][holder]. This layout is applied
5503 - * whenever there is no python-side multiple inheritance of bound C++ types *and* the type's
5504 - * holder will fit in the default space (which is large enough to hold either a std::unique_ptr
5505 - * or std::shared_ptr).
5506 + * Simple layout (when this flag is true), means the `simple_value_holder` is set with a
5507 + * pointer and the holder object governing that pointer, i.e. [val1*][holder]. This layout is
5508 + * applied whenever there is no python-side multiple inheritance of bound C++ types *and* the
5509 + * type's holder will fit in the default space (which is large enough to hold either a
5510 + * std::unique_ptr or std::shared_ptr).
5512 - * Non-simple layout applies when using custom holders that require more space than `shared_ptr`
5513 - * (which is typically the size of two pointers), or when multiple inheritance is used on the
5514 - * python side. Non-simple layout allocates the required amount of memory to have multiple
5515 - * bound C++ classes as parents. Under this layout, `nonsimple.values_and_holders` is set to a
5516 - * pointer to allocated space of the required space to hold a sequence of value pointers and
5517 - * holders followed `status`, a set of bit flags (1 byte each), i.e.
5518 - * [val1*][holder1][val2*][holder2]...[bb...] where each [block] is rounded up to a multiple of
5519 - * `sizeof(void *)`. `nonsimple.status` is, for convenience, a pointer to the
5520 - * beginning of the [bb...] block (but not independently allocated).
5521 + * Non-simple layout applies when using custom holders that require more space than
5522 + * `shared_ptr` (which is typically the size of two pointers), or when multiple inheritance is
5523 + * used on the python side. Non-simple layout allocates the required amount of memory to have
5524 + * multiple bound C++ classes as parents. Under this layout, `nonsimple.values_and_holders` is
5525 + * set to a pointer to allocated space of the required space to hold a sequence of value
5526 + * pointers and holders followed `status`, a set of bit flags (1 byte each), i.e.
5527 + * [val1*][holder1][val2*][holder2]...[bb...] where each [block] is rounded up to a multiple
5528 + * of `sizeof(void *)`. `nonsimple.status` is, for convenience, a pointer to the beginning of
5529 + * the [bb...] block (but not independently allocated).
5531 * Status bits indicate whether the associated holder is constructed (&
5532 * status_holder_constructed) and whether the value pointer is registered (&
5534 /// If true, get_internals().patients has an entry for this object
5535 bool has_patients : 1;
5537 - /// Initializes all of the above type/values/holders data (but not the instance values themselves)
5538 + /// Initializes all of the above type/values/holders data (but not the instance values
5540 void allocate_layout();
5542 /// Destroys/deallocates all of the above
5543 @@ -430,26 +603,44 @@
5544 /// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
5545 /// omitted). Returns a default-constructed (with `.inst = nullptr`) object on failure if
5546 /// `throw_if_missing` is false.
5547 - value_and_holder get_value_and_holder(const type_info *find_type = nullptr, bool throw_if_missing = true);
5548 + value_and_holder get_value_and_holder(const type_info *find_type = nullptr,
5549 + bool throw_if_missing = true);
5551 /// Bit values for the non-simple status flags
5552 - static constexpr uint8_t status_holder_constructed = 1;
5553 + static constexpr uint8_t status_holder_constructed = 1;
5554 static constexpr uint8_t status_instance_registered = 2;
5557 -static_assert(std::is_standard_layout<instance>::value, "Internal error: `pybind11::detail::instance` is not standard layout!");
5558 +static_assert(std::is_standard_layout<instance>::value,
5559 + "Internal error: `pybind11::detail::instance` is not standard layout!");
5561 /// from __cpp_future__ import (convenient aliases from C++14/17)
5562 #if defined(PYBIND11_CPP14) && (!defined(_MSC_VER) || _MSC_VER >= 1910)
5563 -using std::enable_if_t;
5564 using std::conditional_t;
5565 +using std::enable_if_t;
5566 using std::remove_cv_t;
5567 using std::remove_reference_t;
5569 -template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
5570 -template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
5571 -template <typename T> using remove_cv_t = typename std::remove_cv<T>::type;
5572 -template <typename T> using remove_reference_t = typename std::remove_reference<T>::type;
5573 +template <bool B, typename T = void>
5574 +using enable_if_t = typename std::enable_if<B, T>::type;
5575 +template <bool B, typename T, typename F>
5576 +using conditional_t = typename std::conditional<B, T, F>::type;
5577 +template <typename T>
5578 +using remove_cv_t = typename std::remove_cv<T>::type;
5579 +template <typename T>
5580 +using remove_reference_t = typename std::remove_reference<T>::type;
5583 +#if defined(PYBIND11_CPP20)
5584 +using std::remove_cvref;
5585 +using std::remove_cvref_t;
5588 +struct remove_cvref {
5589 + using type = remove_cv_t<remove_reference_t<T>>;
5592 +using remove_cvref_t = typename remove_cvref<T>::type;
5596 @@ -457,106 +648,189 @@
5597 using std::index_sequence;
5598 using std::make_index_sequence;
5600 -template<size_t ...> struct index_sequence { };
5601 -template<size_t N, size_t ...S> struct make_index_sequence_impl : make_index_sequence_impl <N - 1, N - 1, S...> { };
5602 -template<size_t ...S> struct make_index_sequence_impl <0, S...> { typedef index_sequence<S...> type; };
5603 -template<size_t N> using make_index_sequence = typename make_index_sequence_impl<N>::type;
5604 +template <size_t...>
5605 +struct index_sequence {};
5606 +template <size_t N, size_t... S>
5607 +struct make_index_sequence_impl : make_index_sequence_impl<N - 1, N - 1, S...> {};
5608 +template <size_t... S>
5609 +struct make_index_sequence_impl<0, S...> {
5610 + using type = index_sequence<S...>;
5612 +template <size_t N>
5613 +using make_index_sequence = typename make_index_sequence_impl<N>::type;
5616 /// Make an index sequence of the indices of true arguments
5617 -template <typename ISeq, size_t, bool...> struct select_indices_impl { using type = ISeq; };
5618 -template <size_t... IPrev, size_t I, bool B, bool... Bs> struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
5619 - : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>, I + 1, Bs...> {};
5620 -template <bool... Bs> using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
5621 +template <typename ISeq, size_t, bool...>
5622 +struct select_indices_impl {
5623 + using type = ISeq;
5625 +template <size_t... IPrev, size_t I, bool B, bool... Bs>
5626 +struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
5627 + : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>,
5630 +template <bool... Bs>
5631 +using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
5633 /// Backports of std::bool_constant and std::negation to accommodate older compilers
5634 -template <bool B> using bool_constant = std::integral_constant<bool, B>;
5635 -template <typename T> struct negation : bool_constant<!T::value> { };
5637 +using bool_constant = std::integral_constant<bool, B>;
5638 +template <typename T>
5639 +struct negation : bool_constant<!T::value> {};
5641 -template <typename...> struct void_t_impl { using type = void; };
5642 -template <typename... Ts> using void_t = typename void_t_impl<Ts...>::type;
5643 +// PGI/Intel cannot detect operator delete with the "compatible" void_t impl, so
5644 +// using the new one (C++14 defect, so generally works on newer compilers, even
5645 +// if not in C++17 mode)
5646 +#if defined(__PGIC__) || defined(__INTEL_COMPILER)
5647 +template <typename...>
5648 +using void_t = void;
5650 +template <typename...>
5651 +struct void_t_impl {
5652 + using type = void;
5654 +template <typename... Ts>
5655 +using void_t = typename void_t_impl<Ts...>::type;
5658 /// Compile-time all/any/none of that check the boolean value of all template types
5659 #if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
5660 -template <class... Ts> using all_of = bool_constant<(Ts::value && ...)>;
5661 -template <class... Ts> using any_of = bool_constant<(Ts::value || ...)>;
5662 +template <class... Ts>
5663 +using all_of = bool_constant<(Ts::value && ...)>;
5664 +template <class... Ts>
5665 +using any_of = bool_constant<(Ts::value || ...)>;
5666 #elif !defined(_MSC_VER)
5667 -template <bool...> struct bools {};
5668 -template <class... Ts> using all_of = std::is_same<
5669 - bools<Ts::value..., true>,
5670 - bools<true, Ts::value...>>;
5671 -template <class... Ts> using any_of = negation<all_of<negation<Ts>...>>;
5674 +template <class... Ts>
5675 +using all_of = std::is_same<bools<Ts::value..., true>, bools<true, Ts::value...>>;
5676 +template <class... Ts>
5677 +using any_of = negation<all_of<negation<Ts>...>>;
5679 // MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
5680 // at a slight loss of compilation efficiency).
5681 -template <class... Ts> using all_of = std::conjunction<Ts...>;
5682 -template <class... Ts> using any_of = std::disjunction<Ts...>;
5684 -template <class... Ts> using none_of = negation<any_of<Ts...>>;
5686 -template <class T, template<class> class... Predicates> using satisfies_all_of = all_of<Predicates<T>...>;
5687 -template <class T, template<class> class... Predicates> using satisfies_any_of = any_of<Predicates<T>...>;
5688 -template <class T, template<class> class... Predicates> using satisfies_none_of = none_of<Predicates<T>...>;
5689 +template <class... Ts>
5690 +using all_of = std::conjunction<Ts...>;
5691 +template <class... Ts>
5692 +using any_of = std::disjunction<Ts...>;
5694 +template <class... Ts>
5695 +using none_of = negation<any_of<Ts...>>;
5697 +template <class T, template <class> class... Predicates>
5698 +using satisfies_all_of = all_of<Predicates<T>...>;
5699 +template <class T, template <class> class... Predicates>
5700 +using satisfies_any_of = any_of<Predicates<T>...>;
5701 +template <class T, template <class> class... Predicates>
5702 +using satisfies_none_of = none_of<Predicates<T>...>;
5704 /// Strip the class from a method type
5705 -template <typename T> struct remove_class { };
5706 -template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
5707 -template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
5708 +template <typename T>
5709 +struct remove_class {};
5710 +template <typename C, typename R, typename... A>
5711 +struct remove_class<R (C::*)(A...)> {
5712 + using type = R(A...);
5714 +template <typename C, typename R, typename... A>
5715 +struct remove_class<R (C::*)(A...) const> {
5716 + using type = R(A...);
5719 /// Helper template to strip away type modifiers
5720 -template <typename T> struct intrinsic_type { typedef T type; };
5721 -template <typename T> struct intrinsic_type<const T> { typedef typename intrinsic_type<T>::type type; };
5722 -template <typename T> struct intrinsic_type<T*> { typedef typename intrinsic_type<T>::type type; };
5723 -template <typename T> struct intrinsic_type<T&> { typedef typename intrinsic_type<T>::type type; };
5724 -template <typename T> struct intrinsic_type<T&&> { typedef typename intrinsic_type<T>::type type; };
5725 -template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
5726 -template <typename T, size_t N> struct intrinsic_type<T[N]> { typedef typename intrinsic_type<T>::type type; };
5727 -template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
5728 +template <typename T>
5729 +struct intrinsic_type {
5732 +template <typename T>
5733 +struct intrinsic_type<const T> {
5734 + using type = typename intrinsic_type<T>::type;
5736 +template <typename T>
5737 +struct intrinsic_type<T *> {
5738 + using type = typename intrinsic_type<T>::type;
5740 +template <typename T>
5741 +struct intrinsic_type<T &> {
5742 + using type = typename intrinsic_type<T>::type;
5744 +template <typename T>
5745 +struct intrinsic_type<T &&> {
5746 + using type = typename intrinsic_type<T>::type;
5748 +template <typename T, size_t N>
5749 +struct intrinsic_type<const T[N]> {
5750 + using type = typename intrinsic_type<T>::type;
5752 +template <typename T, size_t N>
5753 +struct intrinsic_type<T[N]> {
5754 + using type = typename intrinsic_type<T>::type;
5756 +template <typename T>
5757 +using intrinsic_t = typename intrinsic_type<T>::type;
5759 /// Helper type to replace 'void' in some expressions
5760 -struct void_type { };
5761 +struct void_type {};
5763 /// Helper template which holds a list of types
5764 -template <typename...> struct type_list { };
5765 +template <typename...>
5766 +struct type_list {};
5768 /// Compile-time integer sum
5769 #ifdef __cpp_fold_expressions
5770 -template <typename... Ts> constexpr size_t constexpr_sum(Ts... ns) { return (0 + ... + size_t{ns}); }
5771 +template <typename... Ts>
5772 +constexpr size_t constexpr_sum(Ts... ns) {
5773 + return (0 + ... + size_t{ns});
5776 constexpr size_t constexpr_sum() { return 0; }
5777 template <typename T, typename... Ts>
5778 -constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
5779 +constexpr size_t constexpr_sum(T n, Ts... ns) {
5780 + return size_t{n} + constexpr_sum(ns...);
5784 -NAMESPACE_BEGIN(constexpr_impl)
5785 +PYBIND11_NAMESPACE_BEGIN(constexpr_impl)
5786 /// Implementation details for constexpr functions
5787 constexpr int first(int i) { return i; }
5788 template <typename T, typename... Ts>
5789 -constexpr int first(int i, T v, Ts... vs) { return v ? i : first(i + 1, vs...); }
5790 +constexpr int first(int i, T v, Ts... vs) {
5791 + return v ? i : first(i + 1, vs...);
5794 constexpr int last(int /*i*/, int result) { return result; }
5795 template <typename T, typename... Ts>
5796 -constexpr int last(int i, int result, T v, Ts... vs) { return last(i + 1, v ? i : result, vs...); }
5797 -NAMESPACE_END(constexpr_impl)
5798 +constexpr int last(int i, int result, T v, Ts... vs) {
5799 + return last(i + 1, v ? i : result, vs...);
5801 +PYBIND11_NAMESPACE_END(constexpr_impl)
5803 -/// Return the index of the first type in Ts which satisfies Predicate<T>. Returns sizeof...(Ts) if
5805 -template <template<typename> class Predicate, typename... Ts>
5806 -constexpr int constexpr_first() { return constexpr_impl::first(0, Predicate<Ts>::value...); }
5807 +/// Return the index of the first type in Ts which satisfies Predicate<T>.
5808 +/// Returns sizeof...(Ts) if none match.
5809 +template <template <typename> class Predicate, typename... Ts>
5810 +constexpr int constexpr_first() {
5811 + return constexpr_impl::first(0, Predicate<Ts>::value...);
5814 /// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
5815 -template <template<typename> class Predicate, typename... Ts>
5816 -constexpr int constexpr_last() { return constexpr_impl::last(0, -1, Predicate<Ts>::value...); }
5817 +template <template <typename> class Predicate, typename... Ts>
5818 +constexpr int constexpr_last() {
5819 + return constexpr_impl::last(0, -1, Predicate<Ts>::value...);
5822 /// Return the Nth element from the parameter pack
5823 template <size_t N, typename T, typename... Ts>
5824 -struct pack_element { using type = typename pack_element<N - 1, Ts...>::type; };
5825 +struct pack_element {
5826 + using type = typename pack_element<N - 1, Ts...>::type;
5828 template <typename T, typename... Ts>
5829 -struct pack_element<0, T, Ts...> { using type = T; };
5830 +struct pack_element<0, T, Ts...> {
5834 /// Return the one and only type which matches the predicate, or Default if none match.
5835 /// If more than one type matches the predicate, fail at compile-time.
5836 -template <template<typename> class Predicate, typename Default, typename... Ts>
5837 +template <template <typename> class Predicate, typename Default, typename... Ts>
5838 struct exactly_one {
5839 static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
5840 static_assert(found <= 1, "Found more than one type matching the predicate");
5841 @@ -564,61 +838,85 @@
5842 static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
5843 using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
5845 -template <template<typename> class P, typename Default>
5846 -struct exactly_one<P, Default> { using type = Default; };
5847 +template <template <typename> class P, typename Default>
5848 +struct exactly_one<P, Default> {
5849 + using type = Default;
5852 -template <template<typename> class Predicate, typename Default, typename... Ts>
5853 +template <template <typename> class Predicate, typename Default, typename... Ts>
5854 using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
5856 /// Defer the evaluation of type T until types Us are instantiated
5857 -template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
5858 -template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
5859 +template <typename T, typename... /*Us*/>
5860 +struct deferred_type {
5863 +template <typename T, typename... Us>
5864 +using deferred_t = typename deferred_type<T, Us...>::type;
5866 /// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
5867 /// unlike `std::is_base_of`)
5868 -template <typename Base, typename Derived> using is_strict_base_of = bool_constant<
5869 - std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
5870 +template <typename Base, typename Derived>
5871 +using is_strict_base_of
5872 + = bool_constant<std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
5874 +/// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived
5875 +/// pointer can be converted to a Base pointer) For unions, `is_base_of<T, T>::value` is False, so
5876 +/// we need to check `is_same` as well.
5877 +template <typename Base, typename Derived>
5878 +using is_accessible_base_of
5879 + = bool_constant<(std::is_same<Base, Derived>::value || std::is_base_of<Base, Derived>::value)
5880 + && std::is_convertible<Derived *, Base *>::value>;
5882 -/// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived pointer
5883 -/// can be converted to a Base pointer)
5884 -template <typename Base, typename Derived> using is_accessible_base_of = bool_constant<
5885 - std::is_base_of<Base, Derived>::value && std::is_convertible<Derived *, Base *>::value>;
5887 -template <template<typename...> class Base>
5888 +template <template <typename...> class Base>
5889 struct is_template_base_of_impl {
5890 - template <typename... Us> static std::true_type check(Base<Us...> *);
5891 + template <typename... Us>
5892 + static std::true_type check(Base<Us...> *);
5893 static std::false_type check(...);
5896 /// Check if a template is the base of a type. For example:
5897 /// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
5898 -template <template<typename...> class Base, typename T>
5899 +template <template <typename...> class Base, typename T>
5900 #if !defined(_MSC_VER)
5901 -using is_template_base_of = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr));
5902 +using is_template_base_of
5903 + = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr));
5904 #else // MSVC2015 has trouble with decltype in template aliases
5905 -struct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr)) { };
5906 +struct is_template_base_of
5907 + : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)) {
5911 /// Check if T is an instantiation of the template `Class`. For example:
5912 /// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
5913 -template <template<typename...> class Class, typename T>
5914 -struct is_instantiation : std::false_type { };
5915 -template <template<typename...> class Class, typename... Us>
5916 -struct is_instantiation<Class, Class<Us...>> : std::true_type { };
5917 +template <template <typename...> class Class, typename T>
5918 +struct is_instantiation : std::false_type {};
5919 +template <template <typename...> class Class, typename... Us>
5920 +struct is_instantiation<Class, Class<Us...>> : std::true_type {};
5922 /// Check if T is std::shared_ptr<U> where U can be anything
5923 -template <typename T> using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
5924 +template <typename T>
5925 +using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
5927 /// Check if T looks like an input iterator
5928 -template <typename T, typename = void> struct is_input_iterator : std::false_type {};
5929 +template <typename T, typename = void>
5930 +struct is_input_iterator : std::false_type {};
5931 template <typename T>
5932 -struct is_input_iterator<T, void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
5933 +struct is_input_iterator<T,
5934 + void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
5935 : std::true_type {};
5937 -template <typename T> using is_function_pointer = bool_constant<
5938 - std::is_pointer<T>::value && std::is_function<typename std::remove_pointer<T>::type>::value>;
5940 -template <typename F> struct strip_function_object {
5941 +template <typename T>
5942 +using is_function_pointer
5943 + = bool_constant<std::is_pointer<T>::value
5944 + && std::is_function<typename std::remove_pointer<T>::type>::value>;
5946 +template <typename F>
5947 +struct strip_function_object {
5948 + // If you are encountering an
5949 + // 'error: name followed by "::" must be a class or namespace name'
5950 + // with the Intel compiler and a noexcept function here,
5951 + // try to use noexcept(true) instead of plain noexcept.
5952 using type = typename remove_class<decltype(&F::operator())>::type;
5955 @@ -627,45 +925,55 @@
5956 using function_signature_t = conditional_t<
5957 std::is_function<F>::value,
5959 - typename conditional_t<
5960 - std::is_pointer<F>::value || std::is_member_pointer<F>::value,
5961 - std::remove_pointer<F>,
5962 - strip_function_object<F>
5965 + typename conditional_t<std::is_pointer<F>::value || std::is_member_pointer<F>::value,
5966 + std::remove_pointer<F>,
5967 + strip_function_object<F>>::type>;
5969 /// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
5970 /// pointer. Note that this can catch all sorts of other things, too; this is intended to be used
5971 /// in a place where passing a lambda makes sense.
5972 -template <typename T> using is_lambda = satisfies_none_of<remove_reference_t<T>,
5973 - std::is_function, std::is_pointer, std::is_member_pointer>;
5975 -/// Ignore that a variable is unused in compiler warnings
5976 -inline void ignore_unused(const int *) { }
5977 +template <typename T>
5978 +using is_lambda = satisfies_none_of<remove_reference_t<T>,
5981 + std::is_member_pointer>;
5983 +// [workaround(intel)] Internal error on fold expression
5984 /// Apply a function over each element of a parameter pack
5985 -#ifdef __cpp_fold_expressions
5986 -#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
5987 +#if defined(__cpp_fold_expressions) && !defined(__INTEL_COMPILER)
5988 +// Intel compiler produces an internal error on this fold expression (tested with ICC 19.0.2)
5989 +# define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
5991 using expand_side_effects = bool[];
5992 -#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) pybind11::detail::expand_side_effects{ ((PATTERN), void(), false)..., false }
5993 +# define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) \
5994 + (void) pybind11::detail::expand_side_effects { ((PATTERN), void(), false)..., false }
5997 -NAMESPACE_END(detail)
5998 +PYBIND11_NAMESPACE_END(detail)
6000 +#if defined(_MSC_VER)
6001 +# pragma warning(push)
6002 +# pragma warning(disable : 4275)
6003 +// warning C4275: An exported class was derived from a class that wasn't exported.
6004 +// Can be ignored when derived from a STL class.
6006 /// C++ bindings of builtin Python exceptions
6007 -class builtin_exception : public std::runtime_error {
6008 +class PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error {
6010 using std::runtime_error::runtime_error;
6011 /// Set the error using the Python C API
6012 virtual void set_error() const = 0;
6014 +#if defined(_MSC_VER)
6015 +# pragma warning(pop)
6018 -#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
6019 - class name : public builtin_exception { public: \
6020 - using builtin_exception::builtin_exception; \
6021 - name() : name("") { } \
6022 - void set_error() const override { PyErr_SetString(type, what()); } \
6023 +#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
6024 + class PYBIND11_EXPORT_EXCEPTION name : public builtin_exception { \
6026 + using builtin_exception::builtin_exception; \
6027 + name() : name("") {} \
6028 + void set_error() const override { PyErr_SetString(type, what()); } \
6031 PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
6032 @@ -673,39 +981,62 @@
6033 PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
6034 PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
6035 PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
6036 -PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
6037 +PYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)
6038 +PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
6039 +PYBIND11_RUNTIME_EXCEPTION(attribute_error, PyExc_AttributeError)
6040 +PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or
6041 + /// handle::call fail due to a type
6043 PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
6045 -[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
6046 -[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
6047 +[[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason) {
6048 + throw std::runtime_error(reason);
6050 +[[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const std::string &reason) {
6051 + throw std::runtime_error(reason);
6054 -template <typename T, typename SFINAE = void> struct format_descriptor { };
6055 +template <typename T, typename SFINAE = void>
6056 +struct format_descriptor {};
6058 -NAMESPACE_BEGIN(detail)
6059 +PYBIND11_NAMESPACE_BEGIN(detail)
6060 // Returns the index of the given type in the type char array below, and in the list in numpy.h
6061 // The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
6062 // complex float,double,long double. Note that the long double types only participate when long
6063 // double is actually longer than double (it isn't under MSVC).
6064 // NB: not only the string below but also complex.h and numpy.h rely on this order.
6065 -template <typename T, typename SFINAE = void> struct is_fmt_numeric { static constexpr bool value = false; };
6066 -template <typename T> struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
6067 +template <typename T, typename SFINAE = void>
6068 +struct is_fmt_numeric {
6069 + static constexpr bool value = false;
6071 +template <typename T>
6072 +struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
6073 static constexpr bool value = true;
6074 - static constexpr int index = std::is_same<T, bool>::value ? 0 : 1 + (
6075 - std::is_integral<T>::value ? detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value : 8 + (
6076 - std::is_same<T, double>::value ? 1 : std::is_same<T, long double>::value ? 2 : 0));
6077 + static constexpr int index
6078 + = std::is_same<T, bool>::value
6081 + + (std::is_integral<T>::value
6082 + ? detail::log2(sizeof(T)) * 2 + std::is_unsigned<T>::value
6084 + + (std::is_same<T, double>::value ? 1
6085 + : std::is_same<T, long double>::value ? 2
6088 -NAMESPACE_END(detail)
6089 +PYBIND11_NAMESPACE_END(detail)
6091 -template <typename T> struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
6092 +template <typename T>
6093 +struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
6094 static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
6095 - static constexpr const char value[2] = { c, '\0' };
6096 + static constexpr const char value[2] = {c, '\0'};
6097 static std::string format() { return std::string(1, c); }
6100 #if !defined(PYBIND11_CPP17)
6102 -template <typename T> constexpr const char format_descriptor<
6103 - T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
6104 +template <typename T>
6105 +constexpr const char
6106 + format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
6110 @@ -717,51 +1048,61 @@
6113 /// Dummy destructor wrapper that can be used to expose classes with a private destructor
6114 -struct nodelete { template <typename T> void operator()(T*) { } };
6116 -// overload_cast requires variable templates: C++14
6117 -#if defined(PYBIND11_CPP14)
6118 -#define PYBIND11_OVERLOAD_CAST 1
6120 + template <typename T>
6121 + void operator()(T *) {}
6124 -NAMESPACE_BEGIN(detail)
6125 +PYBIND11_NAMESPACE_BEGIN(detail)
6126 template <typename... Args>
6127 struct overload_cast_impl {
6128 - constexpr overload_cast_impl() {} // MSVC 2015 needs this
6129 + // NOLINTNEXTLINE(modernize-use-equals-default): MSVC 2015 needs this
6130 + constexpr overload_cast_impl() {}
6132 template <typename Return>
6133 - constexpr auto operator()(Return (*pf)(Args...)) const noexcept
6134 - -> decltype(pf) { return pf; }
6135 + constexpr auto operator()(Return (*pf)(Args...)) const noexcept -> decltype(pf) {
6139 template <typename Return, typename Class>
6140 constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
6141 - -> decltype(pmf) { return pmf; }
6142 + -> decltype(pmf) {
6146 template <typename Return, typename Class>
6147 constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
6148 - -> decltype(pmf) { return pmf; }
6149 + -> decltype(pmf) {
6153 -NAMESPACE_END(detail)
6154 +PYBIND11_NAMESPACE_END(detail)
6156 +// overload_cast requires variable templates: C++14
6157 +#if defined(PYBIND11_CPP14)
6158 +# define PYBIND11_OVERLOAD_CAST 1
6159 /// Syntax sugar for resolving overloaded function pointers:
6160 /// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
6161 /// - sweet: overload_cast<Arg0, Arg1, Arg2>(&Class::func)
6162 template <typename... Args>
6163 static constexpr detail::overload_cast_impl<Args...> overload_cast = {};
6164 // MSVC 2015 only accepts this particular initialization syntax for this variable template.
6167 /// Const member function selector for overload_cast
6168 /// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
6169 /// - sweet: overload_cast<Arg>(&Class::func, const_)
6170 static constexpr auto const_ = std::true_type{};
6172 -#else // no overload_cast: providing something that static_assert-fails:
6173 -template <typename... Args> struct overload_cast {
6174 +#if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:
6175 +template <typename... Args>
6176 +struct overload_cast {
6177 static_assert(detail::deferred_t<std::false_type, Args...>::value,
6178 "pybind11::overload_cast<...> requires compiling in C++14 mode");
6180 #endif // overload_cast
6182 -NAMESPACE_BEGIN(detail)
6183 +PYBIND11_NAMESPACE_BEGIN(detail)
6185 // Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
6186 // any standard container (or C-style array) supporting std::begin/std::end, any singleton
6187 @@ -769,26 +1110,34 @@
6188 template <typename T>
6189 class any_container {
6193 any_container() = default;
6195 // Can construct from a pair of iterators
6196 template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
6197 - any_container(It first, It last) : v(first, last) { }
6198 + any_container(It first, It last) : v(first, last) {}
6200 - // Implicit conversion constructor from any arbitrary container type with values convertible to T
6201 - template <typename Container, typename = enable_if_t<std::is_convertible<decltype(*std::begin(std::declval<const Container &>())), T>::value>>
6202 - any_container(const Container &c) : any_container(std::begin(c), std::end(c)) { }
6203 + // Implicit conversion constructor from any arbitrary container type
6204 + // with values convertible to T
6205 + template <typename Container,
6206 + typename = enable_if_t<
6207 + std::is_convertible<decltype(*std::begin(std::declval<const Container &>())),
6209 + // NOLINTNEXTLINE(google-explicit-constructor)
6210 + any_container(const Container &c) : any_container(std::begin(c), std::end(c)) {}
6212 - // initializer_list's aren't deducible, so don't get matched by the above template; we need this
6213 - // to explicitly allow implicit conversion from one:
6214 + // initializer_list's aren't deducible, so don't get matched by the above template;
6215 + // we need this to explicitly allow implicit conversion from one:
6216 template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
6217 - any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) { }
6218 + any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) {}
6220 // Avoid copying if given an rvalue vector of the correct type.
6221 - any_container(std::vector<T> &&v) : v(std::move(v)) { }
6222 + // NOLINTNEXTLINE(google-explicit-constructor)
6223 + any_container(std::vector<T> &&v) : v(std::move(v)) {}
6225 // Moves the vector out of an rvalue any_container
6226 + // NOLINTNEXTLINE(google-explicit-constructor)
6227 operator std::vector<T> &&() && { return std::move(v); }
6229 // Dereferencing obtains a reference to the underlying vector
6230 @@ -800,8 +1149,62 @@
6231 const std::vector<T> *operator->() const { return &v; }
6234 -NAMESPACE_END(detail)
6235 +// Forward-declaration; see detail/class.h
6236 +std::string get_fully_qualified_tp_name(PyTypeObject *);
6238 +template <typename T>
6239 +inline static std::shared_ptr<T>
6240 +try_get_shared_from_this(std::enable_shared_from_this<T> *holder_value_ptr) {
6241 +// Pre C++17, this code path exploits undefined behavior, but is known to work on many platforms.
6242 +// Use at your own risk!
6243 +// See also https://en.cppreference.com/w/cpp/memory/enable_shared_from_this, and in particular
6244 +// the `std::shared_ptr<Good> gp1 = not_so_good.getptr();` and `try`-`catch` parts of the example.
6245 +#if defined(__cpp_lib_enable_shared_from_this) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
6246 + return holder_value_ptr->weak_from_this().lock();
6249 + return holder_value_ptr->shared_from_this();
6250 + } catch (const std::bad_weak_ptr &) {
6256 +// For silencing "unused" compiler warnings in special situations.
6257 +template <typename... Args>
6258 +#if defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER < 1920 // MSVC 2017
6262 + silence_unused_warnings(Args &&...) {
6265 +// MSVC warning C4100: Unreferenced formal parameter
6266 +#if defined(_MSC_VER) && _MSC_VER <= 1916
6267 +# define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...) \
6268 + detail::silence_unused_warnings(__VA_ARGS__)
6270 +# define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
6273 +// GCC -Wunused-but-set-parameter All GCC versions (as of July 2021).
6274 +#if defined(__GNUG__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
6275 +# define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...) \
6276 + detail::silence_unused_warnings(__VA_ARGS__)
6278 +# define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)
6281 +#if defined(_MSC_VER) // All versions (as of July 2021).
6283 +// warning C4127: Conditional expression is constant
6284 +constexpr inline bool silence_msvc_c4127(bool cond) { return cond; }
6286 +# define PYBIND11_SILENCE_MSVC_C4127(...) ::pybind11::detail::silence_msvc_c4127(__VA_ARGS__)
6289 +# define PYBIND11_SILENCE_MSVC_C4127(...) __VA_ARGS__
6292 -NAMESPACE_END(PYBIND11_NAMESPACE)
6293 +PYBIND11_NAMESPACE_END(detail)
6294 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
6295 diff -Nur pythia8309.orig/plugins/python/include/pybind11/detail/descr.h pythia8309/plugins/python/include/pybind11/detail/descr.h
6296 --- pythia8309.orig/plugins/python/include/pybind11/detail/descr.h 2023-02-16 18:12:45.000000000 +0100
6297 +++ pythia8309/plugins/python/include/pybind11/detail/descr.h 2023-03-13 09:52:25.456021595 +0100
6302 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
6303 -NAMESPACE_BEGIN(detail)
6304 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
6305 +PYBIND11_NAMESPACE_BEGIN(detail)
6307 #if !defined(_MSC_VER)
6308 -# define PYBIND11_DESCR_CONSTEXPR static constexpr
6309 +# define PYBIND11_DESCR_CONSTEXPR static constexpr
6311 -# define PYBIND11_DESCR_CONSTEXPR const
6312 +# define PYBIND11_DESCR_CONSTEXPR const
6315 /* Concatenate type signatures at compile time */
6316 template <size_t N, typename... Ts>
6319 + char text[N + 1]{'\0'};
6321 - constexpr descr() : text{'\0'} { }
6322 - constexpr descr(char const (&s)[N+1]) : descr(s, make_index_sequence<N>()) { }
6323 + constexpr descr() = default;
6324 + // NOLINTNEXTLINE(google-explicit-constructor)
6325 + constexpr descr(char const (&s)[N + 1]) : descr(s, make_index_sequence<N>()) {}
6327 template <size_t... Is>
6328 - constexpr descr(char const (&s)[N+1], index_sequence<Is...>) : text{s[Is]..., '\0'} { }
6329 + constexpr descr(char const (&s)[N + 1], index_sequence<Is...>) : text{s[Is]..., '\0'} {}
6331 template <typename... Chars>
6332 - constexpr descr(char c, Chars... cs) : text{c, static_cast<char>(cs)..., '\0'} { }
6333 + // NOLINTNEXTLINE(google-explicit-constructor)
6334 + constexpr descr(char c, Chars... cs) : text{c, static_cast<char>(cs)..., '\0'} {}
6336 static constexpr std::array<const std::type_info *, sizeof...(Ts) + 1> types() {
6337 return {{&typeid(Ts)..., nullptr}};
6338 @@ -40,61 +42,117 @@
6341 template <size_t N1, size_t N2, typename... Ts1, typename... Ts2, size_t... Is1, size_t... Is2>
6342 -constexpr descr<N1 + N2, Ts1..., Ts2...> plus_impl(const descr<N1, Ts1...> &a, const descr<N2, Ts2...> &b,
6343 - index_sequence<Is1...>, index_sequence<Is2...>) {
6344 +constexpr descr<N1 + N2, Ts1..., Ts2...> plus_impl(const descr<N1, Ts1...> &a,
6345 + const descr<N2, Ts2...> &b,
6346 + index_sequence<Is1...>,
6347 + index_sequence<Is2...>) {
6348 + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(b);
6349 return {a.text[Is1]..., b.text[Is2]...};
6352 template <size_t N1, size_t N2, typename... Ts1, typename... Ts2>
6353 -constexpr descr<N1 + N2, Ts1..., Ts2...> operator+(const descr<N1, Ts1...> &a, const descr<N2, Ts2...> &b) {
6354 +constexpr descr<N1 + N2, Ts1..., Ts2...> operator+(const descr<N1, Ts1...> &a,
6355 + const descr<N2, Ts2...> &b) {
6356 return plus_impl(a, b, make_index_sequence<N1>(), make_index_sequence<N2>());
6360 -constexpr descr<N - 1> _(char const(&text)[N]) { return descr<N - 1>(text); }
6361 -constexpr descr<0> _(char const(&)[1]) { return {}; }
6362 +constexpr descr<N - 1> const_name(char const (&text)[N]) {
6363 + return descr<N - 1>(text);
6365 +constexpr descr<0> const_name(char const (&)[1]) { return {}; }
6367 -template <size_t Rem, size_t... Digits> struct int_to_str : int_to_str<Rem/10, Rem%10, Digits...> { };
6368 -template <size_t...Digits> struct int_to_str<0, Digits...> {
6369 +template <size_t Rem, size_t... Digits>
6370 +struct int_to_str : int_to_str<Rem / 10, Rem % 10, Digits...> {};
6371 +template <size_t... Digits>
6372 +struct int_to_str<0, Digits...> {
6373 + // WARNING: This only works with C++17 or higher.
6374 static constexpr auto digits = descr<sizeof...(Digits)>(('0' + Digits)...);
6377 // Ternary description (like std::conditional)
6378 template <bool B, size_t N1, size_t N2>
6379 -constexpr enable_if_t<B, descr<N1 - 1>> _(char const(&text1)[N1], char const(&)[N2]) {
6381 +constexpr enable_if_t<B, descr<N1 - 1>> const_name(char const (&text1)[N1], char const (&)[N2]) {
6382 + return const_name(text1);
6384 template <bool B, size_t N1, size_t N2>
6385 -constexpr enable_if_t<!B, descr<N2 - 1>> _(char const(&)[N1], char const(&text2)[N2]) {
6387 +constexpr enable_if_t<!B, descr<N2 - 1>> const_name(char const (&)[N1], char const (&text2)[N2]) {
6388 + return const_name(text2);
6391 template <bool B, typename T1, typename T2>
6392 -constexpr enable_if_t<B, T1> _(const T1 &d, const T2 &) { return d; }
6393 +constexpr enable_if_t<B, T1> const_name(const T1 &d, const T2 &) {
6396 template <bool B, typename T1, typename T2>
6397 -constexpr enable_if_t<!B, T2> _(const T1 &, const T2 &d) { return d; }
6398 +constexpr enable_if_t<!B, T2> const_name(const T1 &, const T2 &d) {
6402 -template <size_t Size> auto constexpr _() -> decltype(int_to_str<Size / 10, Size % 10>::digits) {
6403 +template <size_t Size>
6404 +auto constexpr const_name() -> remove_cv_t<decltype(int_to_str<Size / 10, Size % 10>::digits)> {
6405 return int_to_str<Size / 10, Size % 10>::digits;
6408 -template <typename Type> constexpr descr<1, Type> _() { return {'%'}; }
6409 +template <typename Type>
6410 +constexpr descr<1, Type> const_name() {
6414 +// If "_" is defined as a macro, py::detail::_ cannot be provided.
6415 +// It is therefore best to use py::detail::const_name universally.
6416 +// This block is for backward compatibility only.
6417 +// (The const_name code is repeated to avoid introducing a "_" #define ourselves.)
6419 +# define PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY
6420 +template <size_t N>
6421 +constexpr descr<N - 1> _(char const (&text)[N]) {
6422 + return const_name<N>(text);
6424 +template <bool B, size_t N1, size_t N2>
6425 +constexpr enable_if_t<B, descr<N1 - 1>> _(char const (&text1)[N1], char const (&text2)[N2]) {
6426 + return const_name<B, N1, N2>(text1, text2);
6428 +template <bool B, size_t N1, size_t N2>
6429 +constexpr enable_if_t<!B, descr<N2 - 1>> _(char const (&text1)[N1], char const (&text2)[N2]) {
6430 + return const_name<B, N1, N2>(text1, text2);
6432 +template <bool B, typename T1, typename T2>
6433 +constexpr enable_if_t<B, T1> _(const T1 &d1, const T2 &d2) {
6434 + return const_name<B, T1, T2>(d1, d2);
6436 +template <bool B, typename T1, typename T2>
6437 +constexpr enable_if_t<!B, T2> _(const T1 &d1, const T2 &d2) {
6438 + return const_name<B, T1, T2>(d1, d2);
6441 +template <size_t Size>
6442 +auto constexpr _() -> remove_cv_t<decltype(int_to_str<Size / 10, Size % 10>::digits)> {
6443 + return const_name<Size>();
6445 +template <typename Type>
6446 +constexpr descr<1, Type> _() {
6447 + return const_name<Type>();
6449 +#endif // #ifndef _
6451 constexpr descr<0> concat() { return {}; }
6453 template <size_t N, typename... Ts>
6454 -constexpr descr<N, Ts...> concat(const descr<N, Ts...> &descr) { return descr; }
6455 +constexpr descr<N, Ts...> concat(const descr<N, Ts...> &descr) {
6459 template <size_t N, typename... Ts, typename... Args>
6460 constexpr auto concat(const descr<N, Ts...> &d, const Args &...args)
6461 -> decltype(std::declval<descr<N + 2, Ts...>>() + concat(args...)) {
6462 - return d + _(", ") + concat(args...);
6463 + return d + const_name(", ") + concat(args...);
6466 template <size_t N, typename... Ts>
6467 constexpr descr<N + 2, Ts...> type_descr(const descr<N, Ts...> &descr) {
6468 - return _("{") + descr + _("}");
6469 + return const_name("{") + descr + const_name("}");
6472 -NAMESPACE_END(detail)
6473 -NAMESPACE_END(PYBIND11_NAMESPACE)
6474 +PYBIND11_NAMESPACE_END(detail)
6475 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
6476 diff -Nur pythia8309.orig/plugins/python/include/pybind11/detail/init.h pythia8309/plugins/python/include/pybind11/detail/init.h
6477 --- pythia8309.orig/plugins/python/include/pybind11/detail/init.h 2023-02-16 18:12:45.000000000 +0100
6478 +++ pythia8309/plugins/python/include/pybind11/detail/init.h 2023-03-13 09:52:25.457021597 +0100
6483 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
6484 -NAMESPACE_BEGIN(detail)
6485 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
6486 +PYBIND11_NAMESPACE_BEGIN(detail)
6489 class type_caster<value_and_holder> {
6494 - template <typename> using cast_op_type = value_and_holder &;
6495 - operator value_and_holder &() { return *value; }
6496 - static constexpr auto name = _<value_and_holder>();
6497 + template <typename>
6498 + using cast_op_type = value_and_holder &;
6499 + explicit operator value_and_holder &() { return *value; }
6500 + static constexpr auto name = const_name<value_and_holder>();
6503 value_and_holder *value = nullptr;
6506 -NAMESPACE_BEGIN(initimpl)
6507 +PYBIND11_NAMESPACE_BEGIN(initimpl)
6509 inline void no_nullptr(void *ptr) {
6510 - if (!ptr) throw type_error("pybind11::init(): factory function returned nullptr");
6512 + throw type_error("pybind11::init(): factory function returned nullptr");
6516 // Implementing functions for all forms of py::init<...> and py::init(...)
6517 -template <typename Class> using Cpp = typename Class::type;
6518 -template <typename Class> using Alias = typename Class::type_alias;
6519 -template <typename Class> using Holder = typename Class::holder_type;
6520 +template <typename Class>
6521 +using Cpp = typename Class::type;
6522 +template <typename Class>
6523 +using Alias = typename Class::type_alias;
6524 +template <typename Class>
6525 +using Holder = typename Class::holder_type;
6527 -template <typename Class> using is_alias_constructible = std::is_constructible<Alias<Class>, Cpp<Class> &&>;
6528 +template <typename Class>
6529 +using is_alias_constructible = std::is_constructible<Alias<Class>, Cpp<Class> &&>;
6531 // Takes a Cpp pointer and returns true if it actually is a polymorphic Alias instance.
6532 template <typename Class, enable_if_t<Class::has_alias, int> = 0>
6535 // Failing fallback version of the above for a no-alias class (always returns false)
6536 template <typename /*Class*/>
6537 -constexpr bool is_alias(void *) { return false; }
6538 +constexpr bool is_alias(void *) {
6542 // Constructs and returns a new object; if the given arguments don't map to a constructor, we fall
6543 // back to brace aggregate initiailization so that for aggregate initialization can be used with
6544 // py::init, e.g. `py::init<int, int>` to initialize a `struct T { int a; int b; }`. For
6545 // non-aggregate types, we need to use an ordinary T(...) constructor (invoking as `T{...}` usually
6546 // works, but will not do the expected thing when `T` has an `initializer_list<T>` constructor).
6547 -template <typename Class, typename... Args, detail::enable_if_t<std::is_constructible<Class, Args...>::value, int> = 0>
6548 -inline Class *construct_or_initialize(Args &&...args) { return new Class(std::forward<Args>(args)...); }
6549 -template <typename Class, typename... Args, detail::enable_if_t<!std::is_constructible<Class, Args...>::value, int> = 0>
6550 -inline Class *construct_or_initialize(Args &&...args) { return new Class{std::forward<Args>(args)...}; }
6551 +template <typename Class,
6553 + detail::enable_if_t<std::is_constructible<Class, Args...>::value, int> = 0>
6554 +inline Class *construct_or_initialize(Args &&...args) {
6555 + return new Class(std::forward<Args>(args)...);
6557 +template <typename Class,
6559 + detail::enable_if_t<!std::is_constructible<Class, Args...>::value, int> = 0>
6560 +inline Class *construct_or_initialize(Args &&...args) {
6561 + return new Class{std::forward<Args>(args)...};
6564 // Attempts to constructs an alias using a `Alias(Cpp &&)` constructor. This allows types with
6565 // an alias to provide only a single Cpp factory function as long as the Alias can be
6567 // inherit all the base class constructors.
6568 template <typename Class>
6569 void construct_alias_from_cpp(std::true_type /*is_alias_constructible*/,
6570 - value_and_holder &v_h, Cpp<Class> &&base) {
6571 + value_and_holder &v_h,
6572 + Cpp<Class> &&base) {
6573 v_h.value_ptr() = new Alias<Class>(std::move(base));
6575 template <typename Class>
6576 [[noreturn]] void construct_alias_from_cpp(std::false_type /*!is_alias_constructible*/,
6577 - value_and_holder &, Cpp<Class> &&) {
6578 + value_and_holder &,
6580 throw type_error("pybind11::init(): unable to convert returned instance to required "
6581 "alias class: no `Alias<Class>(Class &&)` constructor available");
6584 template <typename Class>
6585 void construct(...) {
6586 static_assert(!std::is_same<Class, Class>::value /* always false */,
6587 - "pybind11::init(): init function must return a compatible pointer, "
6588 - "holder, or value");
6589 + "pybind11::init(): init function must return a compatible pointer, "
6590 + "holder, or value");
6593 // Pointer return v1: the factory function returns a class pointer for a registered class.
6595 // construct an Alias from the returned base instance.
6596 template <typename Class>
6597 void construct(value_and_holder &v_h, Cpp<Class> *ptr, bool need_alias) {
6598 + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
6600 - if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {
6601 + if (PYBIND11_SILENCE_MSVC_C4127(Class::has_alias) && need_alias && !is_alias<Class>(ptr)) {
6602 // We're going to try to construct an alias by moving the cpp type. Whether or not
6603 // that succeeds, we still need to destroy the original cpp pointer (either the
6604 // moved away leftover, if the alias construction works, or the value itself if we
6606 // the holder and destruction happens when we leave the C++ scope, and the holder
6607 // class gets to handle the destruction however it likes.
6608 v_h.value_ptr() = ptr;
6609 - v_h.set_instance_registered(true); // To prevent init_instance from registering it
6610 + v_h.set_instance_registered(true); // To prevent init_instance from registering it
6611 v_h.type->init_instance(v_h.inst, nullptr); // Set up the holder
6612 Holder<Class> temp_holder(std::move(v_h.holder<Holder<Class>>())); // Steal the holder
6613 v_h.type->dealloc(v_h); // Destroys the moved-out holder remains, resets value ptr to null
6614 @@ -128,14 +148,18 @@
6616 // Holder return: copy its pointer, and move or copy the returned holder into the new instance's
6617 // holder. This also handles types like std::shared_ptr<T> and std::unique_ptr<T> where T is a
6618 -// derived type (through those holder's implicit conversion from derived class holder constructors).
6619 +// derived type (through those holder's implicit conversion from derived class holder
6621 template <typename Class>
6622 void construct(value_and_holder &v_h, Holder<Class> holder, bool need_alias) {
6623 + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
6624 auto *ptr = holder_helper<Holder<Class>>::get(holder);
6626 // If we need an alias, check that the held pointer is actually an alias instance
6627 - if (Class::has_alias && need_alias && !is_alias<Class>(ptr))
6628 + if (PYBIND11_SILENCE_MSVC_C4127(Class::has_alias) && need_alias && !is_alias<Class>(ptr)) {
6629 throw type_error("pybind11::init(): construction failed: returned holder-wrapped instance "
6630 "is not an alias instance");
6633 v_h.value_ptr() = ptr;
6634 v_h.type->init_instance(v_h.inst, &holder);
6635 @@ -147,12 +171,14 @@
6636 // need it, we simply move-construct the cpp value into a new instance.
6637 template <typename Class>
6638 void construct(value_and_holder &v_h, Cpp<Class> &&result, bool need_alias) {
6639 + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
6640 static_assert(std::is_move_constructible<Cpp<Class>>::value,
6641 - "pybind11::init() return-by-value factory function requires a movable class");
6642 - if (Class::has_alias && need_alias)
6643 + "pybind11::init() return-by-value factory function requires a movable class");
6644 + if (PYBIND11_SILENCE_MSVC_C4127(Class::has_alias) && need_alias) {
6645 construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(result));
6648 v_h.value_ptr() = new Cpp<Class>(std::move(result));
6652 // return-by-value version 2: returning a value of the alias type itself. We move-construct an
6654 // cases where Alias initialization is always desired.
6655 template <typename Class>
6656 void construct(value_and_holder &v_h, Alias<Class> &&result, bool) {
6657 - static_assert(std::is_move_constructible<Alias<Class>>::value,
6659 + std::is_move_constructible<Alias<Class>>::value,
6660 "pybind11::init() return-by-alias-value factory function requires a movable alias class");
6661 v_h.value_ptr() = new Alias<Class>(std::move(result));
6663 @@ -169,48 +196,76 @@
6664 template <typename... Args>
6665 struct constructor {
6666 template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
6667 - static void execute(Class &cl, const Extra&... extra) {
6668 - cl.def("__init__", [](value_and_holder &v_h, Args... args) {
6669 - v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
6670 - }, is_new_style_constructor(), extra...);
6671 + static void execute(Class &cl, const Extra &...extra) {
6674 + [](value_and_holder &v_h, Args... args) {
6675 + v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
6677 + is_new_style_constructor(),
6681 - template <typename Class, typename... Extra,
6682 - enable_if_t<Class::has_alias &&
6683 - std::is_constructible<Cpp<Class>, Args...>::value, int> = 0>
6684 - static void execute(Class &cl, const Extra&... extra) {
6685 - cl.def("__init__", [](value_and_holder &v_h, Args... args) {
6686 - if (Py_TYPE(v_h.inst) == v_h.type->type)
6687 - v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
6689 - v_h.value_ptr() = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
6690 - }, is_new_style_constructor(), extra...);
6691 + template <typename Class,
6692 + typename... Extra,
6693 + enable_if_t<Class::has_alias && std::is_constructible<Cpp<Class>, Args...>::value,
6695 + static void execute(Class &cl, const Extra &...extra) {
6698 + [](value_and_holder &v_h, Args... args) {
6699 + if (Py_TYPE(v_h.inst) == v_h.type->type) {
6701 + = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
6704 + = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
6707 + is_new_style_constructor(),
6711 - template <typename Class, typename... Extra,
6712 - enable_if_t<Class::has_alias &&
6713 - !std::is_constructible<Cpp<Class>, Args...>::value, int> = 0>
6714 - static void execute(Class &cl, const Extra&... extra) {
6715 - cl.def("__init__", [](value_and_holder &v_h, Args... args) {
6716 - v_h.value_ptr() = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
6717 - }, is_new_style_constructor(), extra...);
6718 + template <typename Class,
6719 + typename... Extra,
6720 + enable_if_t<Class::has_alias && !std::is_constructible<Cpp<Class>, Args...>::value,
6722 + static void execute(Class &cl, const Extra &...extra) {
6725 + [](value_and_holder &v_h, Args... args) {
6727 + = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
6729 + is_new_style_constructor(),
6734 // Implementing class for py::init_alias<...>()
6735 -template <typename... Args> struct alias_constructor {
6736 - template <typename Class, typename... Extra,
6737 - enable_if_t<Class::has_alias && std::is_constructible<Alias<Class>, Args...>::value, int> = 0>
6738 - static void execute(Class &cl, const Extra&... extra) {
6739 - cl.def("__init__", [](value_and_holder &v_h, Args... args) {
6740 - v_h.value_ptr() = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
6741 - }, is_new_style_constructor(), extra...);
6742 +template <typename... Args>
6743 +struct alias_constructor {
6744 + template <typename Class,
6745 + typename... Extra,
6746 + enable_if_t<Class::has_alias && std::is_constructible<Alias<Class>, Args...>::value,
6748 + static void execute(Class &cl, const Extra &...extra) {
6751 + [](value_and_holder &v_h, Args... args) {
6753 + = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
6755 + is_new_style_constructor(),
6760 // Implementation class for py::init(Func) and py::init(Func, AliasFunc)
6761 -template <typename CFunc, typename AFunc = void_type (*)(),
6762 - typename = function_signature_t<CFunc>, typename = function_signature_t<AFunc>>
6763 +template <typename CFunc,
6764 + typename AFunc = void_type (*)(),
6765 + typename = function_signature_t<CFunc>,
6766 + typename = function_signature_t<AFunc>>
6769 // Specialization for py::init(Func)
6771 struct factory<Func, void_type (*)(), Return(Args...)> {
6772 remove_reference_t<Func> class_factory;
6774 - factory(Func &&f) : class_factory(std::forward<Func>(f)) { }
6775 + // NOLINTNEXTLINE(google-explicit-constructor)
6776 + factory(Func &&f) : class_factory(std::forward<Func>(f)) {}
6778 // The given class either has no alias or has no separate alias factory;
6779 // this always constructs the class itself. If the class is registered with an alias
6780 @@ -227,22 +283,32 @@
6781 // instance, or the alias needs to be constructible from a `Class &&` argument.
6782 template <typename Class, typename... Extra>
6783 void execute(Class &cl, const Extra &...extra) && {
6784 - #if defined(PYBIND11_CPP14)
6785 - cl.def("__init__", [func = std::move(class_factory)]
6787 +#if defined(PYBIND11_CPP14)
6790 + [func = std::move(class_factory)]
6792 auto &func = class_factory;
6793 - cl.def("__init__", [func]
6795 - (value_and_holder &v_h, Args... args) {
6796 - construct<Class>(v_h, func(std::forward<Args>(args)...),
6797 - Py_TYPE(v_h.inst) != v_h.type->type);
6798 - }, is_new_style_constructor(), extra...);
6803 + (value_and_holder &v_h, Args... args) {
6805 + v_h, func(std::forward<Args>(args)...), Py_TYPE(v_h.inst) != v_h.type->type);
6807 + is_new_style_constructor(),
6812 // Specialization for py::init(Func, AliasFunc)
6813 -template <typename CFunc, typename AFunc,
6814 - typename CReturn, typename... CArgs, typename AReturn, typename... AArgs>
6815 +template <typename CFunc,
6818 + typename... CArgs,
6820 + typename... AArgs>
6821 struct factory<CFunc, AFunc, CReturn(CArgs...), AReturn(AArgs...)> {
6822 static_assert(sizeof...(CArgs) == sizeof...(AArgs),
6823 "pybind11::init(class_factory, alias_factory): class and alias factories "
6824 @@ -255,29 +321,37 @@
6825 remove_reference_t<AFunc> alias_factory;
6827 factory(CFunc &&c, AFunc &&a)
6828 - : class_factory(std::forward<CFunc>(c)), alias_factory(std::forward<AFunc>(a)) { }
6829 + : class_factory(std::forward<CFunc>(c)), alias_factory(std::forward<AFunc>(a)) {}
6831 // The class factory is called when the `self` type passed to `__init__` is the direct
6832 // class (i.e. not inherited), the alias factory when `self` is a Python-side subtype.
6833 template <typename Class, typename... Extra>
6834 - void execute(Class &cl, const Extra&... extra) && {
6835 - static_assert(Class::has_alias, "The two-argument version of `py::init()` can "
6836 - "only be used if the class has an alias");
6837 - #if defined(PYBIND11_CPP14)
6838 - cl.def("__init__", [class_func = std::move(class_factory), alias_func = std::move(alias_factory)]
6840 + void execute(Class &cl, const Extra &...extra) && {
6841 + static_assert(Class::has_alias,
6842 + "The two-argument version of `py::init()` can "
6843 + "only be used if the class has an alias");
6844 +#if defined(PYBIND11_CPP14)
6847 + [class_func = std::move(class_factory), alias_func = std::move(alias_factory)]
6849 auto &class_func = class_factory;
6850 auto &alias_func = alias_factory;
6851 - cl.def("__init__", [class_func, alias_func]
6853 - (value_and_holder &v_h, CArgs... args) {
6854 - if (Py_TYPE(v_h.inst) == v_h.type->type)
6855 - // If the instance type equals the registered type we don't have inheritance, so
6856 - // don't need the alias and can construct using the class function:
6857 - construct<Class>(v_h, class_func(std::forward<CArgs>(args)...), false);
6859 - construct<Class>(v_h, alias_func(std::forward<CArgs>(args)...), true);
6860 - }, is_new_style_constructor(), extra...);
6863 + [class_func, alias_func]
6865 + (value_and_holder &v_h, CArgs... args) {
6866 + if (Py_TYPE(v_h.inst) == v_h.type->type) {
6867 + // If the instance type equals the registered type we don't have inheritance,
6868 + // so don't need the alias and can construct using the class function:
6869 + construct<Class>(v_h, class_func(std::forward<CArgs>(args)...), false);
6871 + construct<Class>(v_h, alias_func(std::forward<CArgs>(args)...), true);
6874 + is_new_style_constructor(),
6879 @@ -288,20 +362,34 @@
6882 /// Set both the C++ and Python states
6883 -template <typename Class, typename T, typename O,
6884 +template <typename Class,
6887 enable_if_t<std::is_convertible<O, handle>::value, int> = 0>
6888 void setstate(value_and_holder &v_h, std::pair<T, O> &&result, bool need_alias) {
6889 construct<Class>(v_h, std::move(result.first), need_alias);
6890 - setattr((PyObject *) v_h.inst, "__dict__", result.second);
6891 + auto d = handle(result.second);
6892 + if (PyDict_Check(d.ptr()) && PyDict_Size(d.ptr()) == 0) {
6893 + // Skipping setattr below, to not force use of py::dynamic_attr() for Class unnecessarily.
6894 + // See PR #2972 for details.
6897 + setattr((PyObject *) v_h.inst, "__dict__", d);
6900 /// Implementation for py::pickle(GetState, SetState)
6901 -template <typename Get, typename Set,
6902 - typename = function_signature_t<Get>, typename = function_signature_t<Set>>
6903 +template <typename Get,
6905 + typename = function_signature_t<Get>,
6906 + typename = function_signature_t<Set>>
6907 struct pickle_factory;
6909 -template <typename Get, typename Set,
6910 - typename RetState, typename Self, typename NewInstance, typename ArgState>
6911 +template <typename Get,
6913 + typename RetState,
6915 + typename NewInstance,
6916 + typename ArgState>
6917 struct pickle_factory<Get, Set, RetState(Self), NewInstance(ArgState)> {
6918 static_assert(std::is_same<intrinsic_t<RetState>, intrinsic_t<ArgState>>::value,
6919 "The type returned by `__getstate__` must be the same "
6920 @@ -310,26 +398,31 @@
6921 remove_reference_t<Get> get;
6922 remove_reference_t<Set> set;
6924 - pickle_factory(Get get, Set set)
6925 - : get(std::forward<Get>(get)), set(std::forward<Set>(set)) { }
6926 + pickle_factory(Get get, Set set) : get(std::forward<Get>(get)), set(std::forward<Set>(set)) {}
6928 template <typename Class, typename... Extra>
6929 void execute(Class &cl, const Extra &...extra) && {
6930 cl.def("__getstate__", std::move(get));
6932 #if defined(PYBIND11_CPP14)
6933 - cl.def("__setstate__", [func = std::move(set)]
6936 + [func = std::move(set)]
6939 - cl.def("__setstate__", [func]
6944 - (value_and_holder &v_h, ArgState state) {
6945 - setstate<Class>(v_h, func(std::forward<ArgState>(state)),
6946 - Py_TYPE(v_h.inst) != v_h.type->type);
6947 - }, is_new_style_constructor(), extra...);
6948 + (value_and_holder &v_h, ArgState state) {
6950 + v_h, func(std::forward<ArgState>(state)), Py_TYPE(v_h.inst) != v_h.type->type);
6952 + is_new_style_constructor(),
6957 -NAMESPACE_END(initimpl)
6958 -NAMESPACE_END(detail)
6959 -NAMESPACE_END(pybind11)
6960 +PYBIND11_NAMESPACE_END(initimpl)
6961 +PYBIND11_NAMESPACE_END(detail)
6962 +PYBIND11_NAMESPACE_END(pybind11)
6963 diff -Nur pythia8309.orig/plugins/python/include/pybind11/detail/internals.h pythia8309/plugins/python/include/pybind11/detail/internals.h
6964 --- pythia8309.orig/plugins/python/include/pybind11/detail/internals.h 2023-02-16 18:12:45.000000000 +0100
6965 +++ pythia8309/plugins/python/include/pybind11/detail/internals.h 2023-03-13 09:52:25.458021599 +0100
6968 #include "../pytypes.h"
6970 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
6971 -NAMESPACE_BEGIN(detail)
6972 +#include <exception>
6974 +/// Tracks the `internals` and `type_info` ABI version independent of the main library version.
6976 +/// Some portions of the code use an ABI that is conditional depending on this
6977 +/// version number. That allows ABI-breaking changes to be "pre-implemented".
6978 +/// Once the default version number is incremented, the conditional logic that
6979 +/// no longer applies can be removed. Additionally, users that need not
6980 +/// maintain ABI compatibility can increase the version number in order to take
6981 +/// advantage of any functionality/efficiency improvements that depend on the
6984 +/// WARNING: If you choose to manually increase the ABI version, note that
6985 +/// pybind11 may not be tested as thoroughly with a non-default ABI version, and
6986 +/// further ABI-incompatible changes may be made before the ABI is officially
6987 +/// changed to the new version.
6988 +#ifndef PYBIND11_INTERNALS_VERSION
6989 +# define PYBIND11_INTERNALS_VERSION 4
6992 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
6994 +using ExceptionTranslator = void (*)(std::exception_ptr);
6996 +PYBIND11_NAMESPACE_BEGIN(detail)
6998 // Forward declarations
6999 inline PyTypeObject *make_static_property_type();
7000 inline PyTypeObject *make_default_metaclass();
7002 // The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
7003 // Thread Specific Storage (TSS) API.
7004 #if PY_VERSION_HEX >= 0x03070000
7005 -# define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr
7006 -# define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
7007 -# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (tstate))
7008 -# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
7009 +// Avoid unnecessary allocation of `Py_tss_t`, since we cannot use
7010 +// `Py_LIMITED_API` anyway.
7011 +# if PYBIND11_INTERNALS_VERSION > 4
7012 +# define PYBIND11_TLS_KEY_REF Py_tss_t &
7014 +// Clang on macOS warns due to `Py_tss_NEEDS_INIT` not specifying an initializer
7015 +// for every field.
7016 +# define PYBIND11_TLS_KEY_INIT(var) \
7017 + _Pragma("GCC diagnostic push") /**/ \
7018 + _Pragma("GCC diagnostic ignored \"-Wmissing-field-initializers\"") /**/ \
7020 + = Py_tss_NEEDS_INIT; \
7021 + _Pragma("GCC diagnostic pop")
7023 +# define PYBIND11_TLS_KEY_INIT(var) Py_tss_t var = Py_tss_NEEDS_INIT;
7025 +# define PYBIND11_TLS_KEY_CREATE(var) (PyThread_tss_create(&(var)) == 0)
7026 +# define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get(&(key))
7027 +# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set(&(key), (value))
7028 +# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set(&(key), nullptr)
7029 +# define PYBIND11_TLS_FREE(key) PyThread_tss_delete(&(key))
7031 +# define PYBIND11_TLS_KEY_REF Py_tss_t *
7032 +# define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr;
7033 +# define PYBIND11_TLS_KEY_CREATE(var) \
7034 + (((var) = PyThread_tss_alloc()) != nullptr && (PyThread_tss_create((var)) == 0))
7035 +# define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
7036 +# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (value))
7037 +# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
7038 +# define PYBIND11_TLS_FREE(key) PyThread_tss_free(key)
7041 - // Usually an int but a long on Cygwin64 with Python 3.x
7042 -# define PYBIND11_TLS_KEY_INIT(var) decltype(PyThread_create_key()) var = 0
7043 +// Usually an int but a long on Cygwin64 with Python 3.x
7044 +# define PYBIND11_TLS_KEY_REF decltype(PyThread_create_key())
7045 +# define PYBIND11_TLS_KEY_INIT(var) PYBIND11_TLS_KEY_REF var = 0;
7046 +# define PYBIND11_TLS_KEY_CREATE(var) (((var) = PyThread_create_key()) != -1)
7047 # define PYBIND11_TLS_GET_VALUE(key) PyThread_get_key_value((key))
7048 -# if PY_MAJOR_VERSION < 3
7049 -# define PYBIND11_TLS_DELETE_VALUE(key) \
7050 - PyThread_delete_key_value(key)
7051 -# define PYBIND11_TLS_REPLACE_VALUE(key, value) \
7053 - PyThread_delete_key_value((key)); \
7054 - PyThread_set_key_value((key), (value)); \
7056 +# if PY_MAJOR_VERSION < 3 || defined(PYPY_VERSION)
7057 +// On CPython < 3.4 and on PyPy, `PyThread_set_key_value` strangely does not set
7058 +// the value if it has already been set. Instead, it must first be deleted and
7060 +inline void tls_replace_value(PYBIND11_TLS_KEY_REF key, void *value) {
7061 + PyThread_delete_key_value(key);
7062 + PyThread_set_key_value(key, value);
7064 +# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_delete_key_value(key)
7065 +# define PYBIND11_TLS_REPLACE_VALUE(key, value) \
7066 + ::pybind11::detail::tls_replace_value((key), (value))
7068 -# define PYBIND11_TLS_DELETE_VALUE(key) \
7069 - PyThread_set_key_value((key), nullptr)
7070 -# define PYBIND11_TLS_REPLACE_VALUE(key, value) \
7071 - PyThread_set_key_value((key), (value))
7072 +# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_set_key_value((key), nullptr)
7073 +# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_set_key_value((key), (value))
7075 +# define PYBIND11_TLS_FREE(key) (void) key
7078 // Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly
7080 size_t operator()(const std::type_index &t) const {
7082 const char *ptr = t.name();
7083 - while (auto c = static_cast<unsigned char>(*ptr++))
7084 + while (auto c = static_cast<unsigned char>(*ptr++)) {
7085 hash = (hash * 33) ^ c;
7090 @@ -80,10 +136,10 @@
7091 template <typename value_type>
7092 using type_map = std::unordered_map<std::type_index, value_type, type_hash, type_equal_to>;
7094 -struct overload_hash {
7095 - inline size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
7096 +struct override_hash {
7097 + inline size_t operator()(const std::pair<const PyObject *, const char *> &v) const {
7098 size_t value = std::hash<const void *>()(v.first);
7099 - value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value<<6) + (value>>2);
7100 + value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value << 6) + (value >> 2);
7104 @@ -92,22 +148,46 @@
7105 /// Whenever binary incompatible changes are made to this structure,
7106 /// `PYBIND11_INTERNALS_VERSION` must be incremented.
7108 - type_map<type_info *> registered_types_cpp; // std::type_index -> pybind11's type information
7109 - std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py; // PyTypeObject* -> base type_info(s)
7110 - std::unordered_multimap<const void *, instance*> registered_instances; // void * -> instance*
7111 - std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
7112 + // std::type_index -> pybind11's type information
7113 + type_map<type_info *> registered_types_cpp;
7114 + // PyTypeObject* -> base type_info(s)
7115 + std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py;
7116 + std::unordered_multimap<const void *, instance *> registered_instances; // void * -> instance*
7117 + std::unordered_set<std::pair<const PyObject *, const char *>, override_hash>
7118 + inactive_override_cache;
7119 type_map<std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
7120 std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
7121 - std::forward_list<void (*) (std::exception_ptr)> registered_exception_translators;
7122 - std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions
7123 - std::vector<PyObject *> loader_patient_stack; // Used by `loader_life_support`
7124 - std::forward_list<std::string> static_strings; // Stores the std::strings backing detail::c_str()
7125 + std::forward_list<ExceptionTranslator> registered_exception_translators;
7126 + std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across
7128 +#if PYBIND11_INTERNALS_VERSION == 4
7129 + std::vector<PyObject *> unused_loader_patient_stack_remove_at_v5;
7131 + std::forward_list<std::string> static_strings; // Stores the std::strings backing
7132 + // detail::c_str()
7133 PyTypeObject *static_property_type;
7134 PyTypeObject *default_metaclass;
7135 PyObject *instance_base;
7136 #if defined(WITH_THREAD)
7137 - PYBIND11_TLS_KEY_INIT(tstate);
7138 + PYBIND11_TLS_KEY_INIT(tstate)
7139 +# if PYBIND11_INTERNALS_VERSION > 4
7140 + PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
7141 +# endif // PYBIND11_INTERNALS_VERSION > 4
7142 PyInterpreterState *istate = nullptr;
7144 +# if PYBIND11_INTERNALS_VERSION > 4
7145 + PYBIND11_TLS_FREE(loader_life_support_tls_key);
7146 +# endif // PYBIND11_INTERNALS_VERSION > 4
7148 + // This destructor is called *after* Py_Finalize() in finalize_interpreter().
7149 + // That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is
7150 + // called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does
7151 + // nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
7152 + // PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX).
7153 + // Neither of those have anything to do with CPython internals. PyMem_RawFree *requires*
7154 + // that the `tstate` be allocated with the CPython allocator.
7155 + PYBIND11_TLS_FREE(tstate);
7160 @@ -120,14 +200,16 @@
7161 void *(*operator_new)(size_t);
7162 void (*init_instance)(instance *, const void *);
7163 void (*dealloc)(value_and_holder &v_h);
7164 - std::vector<PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions;
7165 - std::vector<std::pair<const std::type_info *, void *(*)(void *)>> implicit_casts;
7166 + std::vector<PyObject *(*) (PyObject *, PyTypeObject *)> implicit_conversions;
7167 + std::vector<std::pair<const std::type_info *, void *(*) (void *)>> implicit_casts;
7168 std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
7169 buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
7170 void *get_buffer_data = nullptr;
7171 void *(*module_local_load)(PyObject *, const type_info *) = nullptr;
7172 /* A simple type never occurs as a (direct or indirect) parent
7173 - * of a class that makes use of multiple inheritance */
7174 + * of a class that makes use of multiple inheritance.
7175 + * A type can be simple even if it has non-simple ancestors as long as it has no descendants.
7177 bool simple_type : 1;
7178 /* True if there is no multiple inheritance in this type's inheritance tree */
7179 bool simple_ancestors : 1;
7180 @@ -137,26 +219,73 @@
7181 bool module_local : 1;
7184 -/// Tracks the `internals` and `type_info` ABI version independent of the main library version
7185 -#define PYBIND11_INTERNALS_VERSION 3
7187 -#if defined(_DEBUG)
7188 -# define PYBIND11_BUILD_TYPE "_debug"
7189 +/// On MSVC, debug and release builds are not ABI-compatible!
7190 +#if defined(_MSC_VER) && defined(_DEBUG)
7191 +# define PYBIND11_BUILD_TYPE "_debug"
7193 -# define PYBIND11_BUILD_TYPE ""
7194 +# define PYBIND11_BUILD_TYPE ""
7197 -#if defined(WITH_THREAD)
7198 -# define PYBIND11_INTERNALS_KIND ""
7200 -# define PYBIND11_INTERNALS_KIND "_without_thread"
7201 +/// Let's assume that different compilers are ABI-incompatible.
7202 +/// A user can manually set this string if they know their
7203 +/// compiler is compatible.
7204 +#ifndef PYBIND11_COMPILER_TYPE
7205 +# if defined(_MSC_VER)
7206 +# define PYBIND11_COMPILER_TYPE "_msvc"
7207 +# elif defined(__INTEL_COMPILER)
7208 +# define PYBIND11_COMPILER_TYPE "_icc"
7209 +# elif defined(__clang__)
7210 +# define PYBIND11_COMPILER_TYPE "_clang"
7211 +# elif defined(__PGI)
7212 +# define PYBIND11_COMPILER_TYPE "_pgi"
7213 +# elif defined(__MINGW32__)
7214 +# define PYBIND11_COMPILER_TYPE "_mingw"
7215 +# elif defined(__CYGWIN__)
7216 +# define PYBIND11_COMPILER_TYPE "_gcc_cygwin"
7217 +# elif defined(__GNUC__)
7218 +# define PYBIND11_COMPILER_TYPE "_gcc"
7220 +# define PYBIND11_COMPILER_TYPE "_unknown"
7224 -#define PYBIND11_INTERNALS_ID "__pybind11_internals_v" \
7225 - PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) PYBIND11_INTERNALS_KIND PYBIND11_BUILD_TYPE "__"
7226 +/// Also standard libs
7227 +#ifndef PYBIND11_STDLIB
7228 +# if defined(_LIBCPP_VERSION)
7229 +# define PYBIND11_STDLIB "_libcpp"
7230 +# elif defined(__GLIBCXX__) || defined(__GLIBCPP__)
7231 +# define PYBIND11_STDLIB "_libstdcpp"
7233 +# define PYBIND11_STDLIB ""
7237 -#define PYBIND11_MODULE_LOCAL_ID "__pybind11_module_local_v" \
7238 - PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) PYBIND11_INTERNALS_KIND PYBIND11_BUILD_TYPE "__"
7239 +/// On Linux/OSX, changes in __GXX_ABI_VERSION__ indicate ABI incompatibility.
7240 +#ifndef PYBIND11_BUILD_ABI
7241 +# if defined(__GXX_ABI_VERSION)
7242 +# define PYBIND11_BUILD_ABI "_cxxabi" PYBIND11_TOSTRING(__GXX_ABI_VERSION)
7244 +# define PYBIND11_BUILD_ABI ""
7248 +#ifndef PYBIND11_INTERNALS_KIND
7249 +# if defined(WITH_THREAD)
7250 +# define PYBIND11_INTERNALS_KIND ""
7252 +# define PYBIND11_INTERNALS_KIND "_without_thread"
7256 +#define PYBIND11_INTERNALS_ID \
7257 + "__pybind11_internals_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
7258 + PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
7259 + PYBIND11_BUILD_TYPE "__"
7261 +#define PYBIND11_MODULE_LOCAL_ID \
7262 + "__pybind11_module_local_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
7263 + PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
7264 + PYBIND11_BUILD_TYPE "__"
7266 /// Each module locally stores a pointer to the `internals` data. The data
7267 /// itself is shared among modules with the same `PYBIND11_INTERNALS_ID`.
7268 @@ -165,13 +294,140 @@
7269 return internals_pp;
7272 +#if PY_VERSION_HEX >= 0x03030000
7274 +inline void translate_exception(std::exception_ptr);
7277 + enable_if_t<std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
7278 +bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
7279 + std::exception_ptr nested = exc.nested_ptr();
7280 + if (nested != nullptr && nested != p) {
7281 + translate_exception(nested);
7288 + enable_if_t<!std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
7289 +bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
7290 + if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(exc))) {
7291 + return handle_nested_exception(*nep, p);
7299 +bool handle_nested_exception(const T &, std::exception_ptr &) {
7304 +inline bool raise_err(PyObject *exc_type, const char *msg) {
7305 +#if PY_VERSION_HEX >= 0x03030000
7306 + if (PyErr_Occurred()) {
7307 + raise_from(exc_type, msg);
7311 + PyErr_SetString(exc_type, msg);
7315 +inline void translate_exception(std::exception_ptr p) {
7320 + std::rethrow_exception(p);
7321 + } catch (error_already_set &e) {
7322 + handle_nested_exception(e, p);
7325 + } catch (const builtin_exception &e) {
7326 + // Could not use template since it's an abstract class.
7327 + if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(e))) {
7328 + handle_nested_exception(*nep, p);
7332 + } catch (const std::bad_alloc &e) {
7333 + handle_nested_exception(e, p);
7334 + raise_err(PyExc_MemoryError, e.what());
7336 + } catch (const std::domain_error &e) {
7337 + handle_nested_exception(e, p);
7338 + raise_err(PyExc_ValueError, e.what());
7340 + } catch (const std::invalid_argument &e) {
7341 + handle_nested_exception(e, p);
7342 + raise_err(PyExc_ValueError, e.what());
7344 + } catch (const std::length_error &e) {
7345 + handle_nested_exception(e, p);
7346 + raise_err(PyExc_ValueError, e.what());
7348 + } catch (const std::out_of_range &e) {
7349 + handle_nested_exception(e, p);
7350 + raise_err(PyExc_IndexError, e.what());
7352 + } catch (const std::range_error &e) {
7353 + handle_nested_exception(e, p);
7354 + raise_err(PyExc_ValueError, e.what());
7356 + } catch (const std::overflow_error &e) {
7357 + handle_nested_exception(e, p);
7358 + raise_err(PyExc_OverflowError, e.what());
7360 + } catch (const std::exception &e) {
7361 + handle_nested_exception(e, p);
7362 + raise_err(PyExc_RuntimeError, e.what());
7364 + } catch (const std::nested_exception &e) {
7365 + handle_nested_exception(e, p);
7366 + raise_err(PyExc_RuntimeError, "Caught an unknown nested exception!");
7369 + raise_err(PyExc_RuntimeError, "Caught an unknown exception!");
7374 +#if !defined(__GLIBCXX__)
7375 +inline void translate_local_exception(std::exception_ptr p) {
7378 + std::rethrow_exception(p);
7380 + } catch (error_already_set &e) {
7383 + } catch (const builtin_exception &e) {
7390 /// Return a reference to the current `internals` data
7391 -PYBIND11_NOINLINE inline internals &get_internals() {
7392 +PYBIND11_NOINLINE internals &get_internals() {
7393 auto **&internals_pp = get_internals_pp();
7394 - if (internals_pp && *internals_pp)
7395 + if (internals_pp && *internals_pp) {
7396 return **internals_pp;
7399 + // Ensure that the GIL is held since we will need to make Python calls.
7400 + // Cannot use py::gil_scoped_acquire here since that constructor calls get_internals.
7401 + struct gil_scoped_acquire_local {
7402 + gil_scoped_acquire_local() : state(PyGILState_Ensure()) {}
7403 + ~gil_scoped_acquire_local() { PyGILState_Release(state); }
7404 + const PyGILState_STATE state;
7407 - constexpr auto *id = PYBIND11_INTERNALS_ID;
7408 + PYBIND11_STR_TYPE id(PYBIND11_INTERNALS_ID);
7409 auto builtins = handle(PyEval_GetBuiltins());
7410 if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
7411 internals_pp = static_cast<internals **>(capsule(builtins[id]));
7412 @@ -181,57 +437,38 @@
7413 // initial exception translator, below, so add another for our local exception classes.
7415 // libstdc++ doesn't require this (types there are identified only by name)
7416 + // libc++ with CPython doesn't require this (types are explicitly exported)
7417 + // libc++ with PyPy still need it, awaiting further investigation
7418 #if !defined(__GLIBCXX__)
7419 - (*internals_pp)->registered_exception_translators.push_front(
7420 - [](std::exception_ptr p) -> void {
7422 - if (p) std::rethrow_exception(p);
7423 - } catch (error_already_set &e) { e.restore(); return;
7424 - } catch (const builtin_exception &e) { e.set_error(); return;
7428 + (*internals_pp)->registered_exception_translators.push_front(&translate_local_exception);
7431 - if (!internals_pp) internals_pp = new internals*();
7432 + if (!internals_pp) {
7433 + internals_pp = new internals *();
7435 auto *&internals_ptr = *internals_pp;
7436 internals_ptr = new internals();
7437 #if defined(WITH_THREAD)
7439 +# if PY_VERSION_HEX < 0x03090000
7440 PyEval_InitThreads();
7442 PyThreadState *tstate = PyThreadState_Get();
7443 - #if PY_VERSION_HEX >= 0x03070000
7444 - internals_ptr->tstate = PyThread_tss_alloc();
7445 - if (!internals_ptr->tstate || PyThread_tss_create(internals_ptr->tstate))
7446 - pybind11_fail("get_internals: could not successfully initialize the TSS key!");
7447 - PyThread_tss_set(internals_ptr->tstate, tstate);
7449 - internals_ptr->tstate = PyThread_create_key();
7450 - if (internals_ptr->tstate == -1)
7451 - pybind11_fail("get_internals: could not successfully initialize the TLS key!");
7452 - PyThread_set_key_value(internals_ptr->tstate, tstate);
7454 + if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->tstate)) {
7455 + pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
7457 + PYBIND11_TLS_REPLACE_VALUE(internals_ptr->tstate, tstate);
7459 +# if PYBIND11_INTERNALS_VERSION > 4
7460 + if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->loader_life_support_tls_key)) {
7461 + pybind11_fail("get_internals: could not successfully initialize the "
7462 + "loader_life_support TSS key!");
7465 internals_ptr->istate = tstate->interp;
7467 builtins[id] = capsule(internals_pp);
7468 - internals_ptr->registered_exception_translators.push_front(
7469 - [](std::exception_ptr p) -> void {
7471 - if (p) std::rethrow_exception(p);
7472 - } catch (error_already_set &e) { e.restore(); return;
7473 - } catch (const builtin_exception &e) { e.set_error(); return;
7474 - } catch (const std::bad_alloc &e) { PyErr_SetString(PyExc_MemoryError, e.what()); return;
7475 - } catch (const std::domain_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
7476 - } catch (const std::invalid_argument &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
7477 - } catch (const std::length_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
7478 - } catch (const std::out_of_range &e) { PyErr_SetString(PyExc_IndexError, e.what()); return;
7479 - } catch (const std::range_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
7480 - } catch (const std::exception &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return;
7482 - PyErr_SetString(PyExc_RuntimeError, "Caught an unknown exception!");
7487 + internals_ptr->registered_exception_translators.push_front(&translate_exception);
7488 internals_ptr->static_property_type = make_static_property_type();
7489 internals_ptr->default_metaclass = make_default_metaclass();
7490 internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
7491 @@ -239,9 +476,53 @@
7492 return **internals_pp;
7495 -/// Works like `internals.registered_types_cpp`, but for module-local registered types:
7496 -inline type_map<type_info *> ®istered_local_types_cpp() {
7497 - static type_map<type_info *> locals{};
7498 +// the internals struct (above) is shared between all the modules. local_internals are only
7499 +// for a single module. Any changes made to internals may require an update to
7500 +// PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,
7501 +// restricted to a single module. Whether a module has local internals or not should not
7502 +// impact any other modules, because the only things accessing the local internals is the
7503 +// module that contains them.
7504 +struct local_internals {
7505 + type_map<type_info *> registered_types_cpp;
7506 + std::forward_list<ExceptionTranslator> registered_exception_translators;
7507 +#if defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
7509 + // For ABI compatibility, we can't store the loader_life_support TLS key in
7510 + // the `internals` struct directly. Instead, we store it in `shared_data` and
7511 + // cache a copy in `local_internals`. If we allocated a separate TLS key for
7512 + // each instance of `local_internals`, we could end up allocating hundreds of
7513 + // TLS keys if hundreds of different pybind11 modules are loaded (which is a
7514 + // plausible number).
7515 + PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
7517 + // Holds the shared TLS key for the loader_life_support stack.
7518 + struct shared_loader_life_support_data {
7519 + PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
7520 + shared_loader_life_support_data() {
7521 + if (!PYBIND11_TLS_KEY_CREATE(loader_life_support_tls_key)) {
7522 + pybind11_fail("local_internals: could not successfully initialize the "
7523 + "loader_life_support TLS key!");
7526 + // We can't help but leak the TLS key, because Python never unloads extension modules.
7529 + local_internals() {
7530 + auto &internals = get_internals();
7531 + // Get or create the `loader_life_support_stack_key`.
7532 + auto &ptr = internals.shared_data["_life_support"];
7534 + ptr = new shared_loader_life_support_data;
7536 + loader_life_support_tls_key
7537 + = static_cast<shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key;
7539 +#endif // defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
7542 +/// Works like `get_internals`, but for things which are locally registered.
7543 +inline local_internals &get_local_internals() {
7544 + static local_internals locals;
7548 @@ -256,19 +537,19 @@
7549 return strings.front().c_str();
7552 -NAMESPACE_END(detail)
7553 +PYBIND11_NAMESPACE_END(detail)
7555 /// Returns a named pointer that is shared among all extension modules (using the same
7556 /// pybind11 version) running in the current interpreter. Names starting with underscores
7557 /// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
7558 -inline PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
7559 +PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
7560 auto &internals = detail::get_internals();
7561 auto it = internals.shared_data.find(name);
7562 return it != internals.shared_data.end() ? it->second : nullptr;
7565 /// Set the shared data that can be later recovered by `get_shared_data()`.
7566 -inline PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
7567 +PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
7568 detail::get_internals().shared_data[name] = data;
7572 /// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
7573 /// such entry exists. Otherwise, a new object of default-constructible type `T` is
7574 /// added to the shared data under the given name and a reference to it is returned.
7575 -template<typename T>
7576 +template <typename T>
7577 T &get_or_create_shared_data(const std::string &name) {
7578 auto &internals = detail::get_internals();
7579 auto it = internals.shared_data.find(name);
7584 -NAMESPACE_END(PYBIND11_NAMESPACE)
7585 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
7586 diff -Nur pythia8309.orig/plugins/python/include/pybind11/detail/type_caster_base.h pythia8309/plugins/python/include/pybind11/detail/type_caster_base.h
7587 --- pythia8309.orig/plugins/python/include/pybind11/detail/type_caster_base.h 1970-01-01 01:00:00.000000000 +0100
7588 +++ pythia8309/plugins/python/include/pybind11/detail/type_caster_base.h 2023-03-13 09:52:25.459021601 +0100
7591 + pybind11/detail/type_caster_base.h (originally first part of pybind11/cast.h)
7593 + Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
7595 + All rights reserved. Use of this source code is governed by a
7596 + BSD-style license that can be found in the LICENSE file.
7601 +#include "../pytypes.h"
7602 +#include "common.h"
7604 +#include "internals.h"
7605 +#include "typeid.h"
7608 +#include <iterator>
7611 +#include <type_traits>
7612 +#include <typeindex>
7613 +#include <typeinfo>
7614 +#include <unordered_map>
7618 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
7619 +PYBIND11_NAMESPACE_BEGIN(detail)
7621 +/// A life support system for temporary objects created by `type_caster::load()`.
7622 +/// Adding a patient will keep it alive up until the enclosing function returns.
7623 +class loader_life_support {
7625 + loader_life_support *parent = nullptr;
7626 + std::unordered_set<PyObject *> keep_alive;
7628 +#if defined(WITH_THREAD)
7629 + // Store stack pointer in thread-local storage.
7630 + static PYBIND11_TLS_KEY_REF get_stack_tls_key() {
7631 +# if PYBIND11_INTERNALS_VERSION == 4
7632 + return get_local_internals().loader_life_support_tls_key;
7634 + return get_internals().loader_life_support_tls_key;
7637 + static loader_life_support *get_stack_top() {
7638 + return static_cast<loader_life_support *>(PYBIND11_TLS_GET_VALUE(get_stack_tls_key()));
7640 + static void set_stack_top(loader_life_support *value) {
7641 + PYBIND11_TLS_REPLACE_VALUE(get_stack_tls_key(), value);
7644 + // Use single global variable for stack.
7645 + static loader_life_support **get_stack_pp() {
7646 + static loader_life_support *global_stack = nullptr;
7647 + return global_stack;
7649 + static loader_life_support *get_stack_top() { return *get_stack_pp(); }
7650 + static void set_stack_top(loader_life_support *value) { *get_stack_pp() = value; }
7654 + /// A new patient frame is created when a function is entered
7655 + loader_life_support() : parent{get_stack_top()} { set_stack_top(this); }
7657 + /// ... and destroyed after it returns
7658 + ~loader_life_support() {
7659 + if (get_stack_top() != this) {
7660 + pybind11_fail("loader_life_support: internal error");
7662 + set_stack_top(parent);
7663 + for (auto *item : keep_alive) {
7668 + /// This can only be used inside a pybind11-bound function, either by `argument_loader`
7669 + /// at argument preparation time or by `py::cast()` at execution time.
7670 + PYBIND11_NOINLINE static void add_patient(handle h) {
7671 + loader_life_support *frame = get_stack_top();
7673 + // NOTE: It would be nice to include the stack frames here, as this indicates
7674 + // use of pybind11::cast<> outside the normal call framework, finding such
7675 + // a location is challenging. Developers could consider printing out
7676 + // stack frame addresses here using something like __builtin_frame_address(0)
7677 + throw cast_error("When called outside a bound function, py::cast() cannot "
7678 + "do Python -> C++ conversions which require the creation "
7679 + "of temporary values");
7682 + if (frame->keep_alive.insert(h.ptr()).second) {
7683 + Py_INCREF(h.ptr());
7688 +// Gets the cache entry for the given type, creating it if necessary. The return value is the pair
7689 +// returned by emplace, i.e. an iterator for the entry and a bool set to `true` if the entry was
7691 +inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
7692 +all_type_info_get_cache(PyTypeObject *type);
7694 +// Populates a just-created cache entry.
7695 +PYBIND11_NOINLINE void all_type_info_populate(PyTypeObject *t, std::vector<type_info *> &bases) {
7696 + std::vector<PyTypeObject *> check;
7697 + for (handle parent : reinterpret_borrow<tuple>(t->tp_bases)) {
7698 + check.push_back((PyTypeObject *) parent.ptr());
7701 + auto const &type_dict = get_internals().registered_types_py;
7702 + for (size_t i = 0; i < check.size(); i++) {
7703 + auto *type = check[i];
7704 + // Ignore Python2 old-style class super type:
7705 + if (!PyType_Check((PyObject *) type)) {
7709 + // Check `type` in the current set of registered python types:
7710 + auto it = type_dict.find(type);
7711 + if (it != type_dict.end()) {
7712 + // We found a cache entry for it, so it's either pybind-registered or has pre-computed
7713 + // pybind bases, but we have to make sure we haven't already seen the type(s) before:
7714 + // we want to follow Python/virtual C++ rules that there should only be one instance of
7716 + for (auto *tinfo : it->second) {
7717 + // NB: Could use a second set here, rather than doing a linear search, but since
7718 + // having a large number of immediate pybind11-registered types seems fairly
7719 + // unlikely, that probably isn't worthwhile.
7720 + bool found = false;
7721 + for (auto *known : bases) {
7722 + if (known == tinfo) {
7728 + bases.push_back(tinfo);
7731 + } else if (type->tp_bases) {
7732 + // It's some python type, so keep follow its bases classes to look for one or more
7733 + // registered types
7734 + if (i + 1 == check.size()) {
7735 + // When we're at the end, we can pop off the current element to avoid growing
7736 + // `check` when adding just one base (which is typical--i.e. when there is no
7737 + // multiple inheritance)
7741 + for (handle parent : reinterpret_borrow<tuple>(type->tp_bases)) {
7742 + check.push_back((PyTypeObject *) parent.ptr());
7749 + * Extracts vector of type_info pointers of pybind-registered roots of the given Python type. Will
7750 + * be just 1 pybind type for the Python type of a pybind-registered class, or for any Python-side
7751 + * derived class that uses single inheritance. Will contain as many types as required for a Python
7752 + * class that uses multiple inheritance to inherit (directly or indirectly) from multiple
7753 + * pybind-registered classes. Will be empty if neither the type nor any base classes are
7754 + * pybind-registered.
7756 + * The value is cached for the lifetime of the Python type.
7758 +inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {
7759 + auto ins = all_type_info_get_cache(type);
7761 + // New cache entry: populate it
7762 + all_type_info_populate(type, ins.first->second);
7765 + return ins.first->second;
7769 + * Gets a single pybind11 type info for a python type. Returns nullptr if neither the type nor any
7770 + * ancestors are pybind11-registered. Throws an exception if there are multiple bases--use
7771 + * `all_type_info` instead if you want to support multiple bases.
7773 +PYBIND11_NOINLINE detail::type_info *get_type_info(PyTypeObject *type) {
7774 + const auto &bases = all_type_info(type);
7775 + if (bases.empty()) {
7778 + if (bases.size() > 1) {
7780 + "pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
7782 + return bases.front();
7785 +inline detail::type_info *get_local_type_info(const std::type_index &tp) {
7786 + auto &locals = get_local_internals().registered_types_cpp;
7787 + auto it = locals.find(tp);
7788 + if (it != locals.end()) {
7789 + return it->second;
7794 +inline detail::type_info *get_global_type_info(const std::type_index &tp) {
7795 + auto &types = get_internals().registered_types_cpp;
7796 + auto it = types.find(tp);
7797 + if (it != types.end()) {
7798 + return it->second;
7803 +/// Return the type info for a given C++ type; on lookup failure can either throw or return
7805 +PYBIND11_NOINLINE detail::type_info *get_type_info(const std::type_index &tp,
7806 + bool throw_if_missing = false) {
7807 + if (auto *ltype = get_local_type_info(tp)) {
7810 + if (auto *gtype = get_global_type_info(tp)) {
7814 + if (throw_if_missing) {
7815 + std::string tname = tp.name();
7816 + detail::clean_type_id(tname);
7817 + pybind11_fail("pybind11::detail::get_type_info: unable to find type info for \"" + tname
7823 +PYBIND11_NOINLINE handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
7824 + detail::type_info *type_info = get_type_info(tp, throw_if_missing);
7825 + return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
7828 +// Searches the inheritance graph for a registered Python instance, using all_type_info().
7829 +PYBIND11_NOINLINE handle find_registered_python_instance(void *src,
7830 + const detail::type_info *tinfo) {
7831 + auto it_instances = get_internals().registered_instances.equal_range(src);
7832 + for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
7833 + for (auto *instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
7834 + if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype)) {
7835 + return handle((PyObject *) it_i->second).inc_ref();
7842 +struct value_and_holder {
7843 + instance *inst = nullptr;
7844 + size_t index = 0u;
7845 + const detail::type_info *type = nullptr;
7846 + void **vh = nullptr;
7848 + // Main constructor for a found value/holder:
7849 + value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index)
7850 + : inst{i}, index{index}, type{type}, vh{inst->simple_layout
7851 + ? inst->simple_value_holder
7852 + : &inst->nonsimple.values_and_holders[vpos]} {}
7854 + // Default constructor (used to signal a value-and-holder not found by get_value_and_holder())
7855 + value_and_holder() = default;
7857 + // Used for past-the-end iterator
7858 + explicit value_and_holder(size_t index) : index{index} {}
7860 + template <typename V = void>
7861 + V *&value_ptr() const {
7862 + return reinterpret_cast<V *&>(vh[0]);
7864 + // True if this `value_and_holder` has a non-null value pointer
7865 + explicit operator bool() const { return value_ptr() != nullptr; }
7867 + template <typename H>
7868 + H &holder() const {
7869 + return reinterpret_cast<H &>(vh[1]);
7871 + bool holder_constructed() const {
7872 + return inst->simple_layout
7873 + ? inst->simple_holder_constructed
7874 + : (inst->nonsimple.status[index] & instance::status_holder_constructed) != 0u;
7876 + // NOLINTNEXTLINE(readability-make-member-function-const)
7877 + void set_holder_constructed(bool v = true) {
7878 + if (inst->simple_layout) {
7879 + inst->simple_holder_constructed = v;
7881 + inst->nonsimple.status[index] |= instance::status_holder_constructed;
7883 + inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_holder_constructed;
7886 + bool instance_registered() const {
7887 + return inst->simple_layout
7888 + ? inst->simple_instance_registered
7889 + : ((inst->nonsimple.status[index] & instance::status_instance_registered) != 0);
7891 + // NOLINTNEXTLINE(readability-make-member-function-const)
7892 + void set_instance_registered(bool v = true) {
7893 + if (inst->simple_layout) {
7894 + inst->simple_instance_registered = v;
7896 + inst->nonsimple.status[index] |= instance::status_instance_registered;
7898 + inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_instance_registered;
7903 +// Container for accessing and iterating over an instance's values/holders
7904 +struct values_and_holders {
7907 + using type_vec = std::vector<detail::type_info *>;
7908 + const type_vec &tinfo;
7911 + explicit values_and_holders(instance *inst)
7912 + : inst{inst}, tinfo(all_type_info(Py_TYPE(inst))) {}
7916 + instance *inst = nullptr;
7917 + const type_vec *types = nullptr;
7918 + value_and_holder curr;
7919 + friend struct values_and_holders;
7920 + iterator(instance *inst, const type_vec *tinfo)
7921 + : inst{inst}, types{tinfo},
7922 + curr(inst /* instance */,
7923 + types->empty() ? nullptr : (*types)[0] /* type info */,
7924 + 0, /* vpos: (non-simple types only): the first vptr comes first */
7926 + // Past-the-end iterator:
7927 + explicit iterator(size_t end) : curr(end) {}
7930 + bool operator==(const iterator &other) const { return curr.index == other.curr.index; }
7931 + bool operator!=(const iterator &other) const { return curr.index != other.curr.index; }
7932 + iterator &operator++() {
7933 + if (!inst->simple_layout) {
7934 + curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;
7937 + curr.type = curr.index < types->size() ? (*types)[curr.index] : nullptr;
7940 + value_and_holder &operator*() { return curr; }
7941 + value_and_holder *operator->() { return &curr; }
7944 + iterator begin() { return iterator(inst, &tinfo); }
7945 + iterator end() { return iterator(tinfo.size()); }
7947 + iterator find(const type_info *find_type) {
7948 + auto it = begin(), endit = end();
7949 + while (it != endit && it->type != find_type) {
7955 + size_t size() { return tinfo.size(); }
7959 + * Extracts C++ value and holder pointer references from an instance (which may contain multiple
7960 + * values/holders for python-side multiple inheritance) that match the given type. Throws an error
7961 + * if the given type (or ValueType, if omitted) is not a pybind11 base of the given instance. If
7962 + * `find_type` is omitted (or explicitly specified as nullptr) the first value/holder are returned,
7963 + * regardless of type (and the resulting .type will be nullptr).
7965 + * The returned object should be short-lived: in particular, it must not outlive the called-upon
7968 +PYBIND11_NOINLINE value_and_holder
7969 +instance::get_value_and_holder(const type_info *find_type /*= nullptr default in common.h*/,
7970 + bool throw_if_missing /*= true in common.h*/) {
7971 + // Optimize common case:
7972 + if (!find_type || Py_TYPE(this) == find_type->type) {
7973 + return value_and_holder(this, find_type, 0, 0);
7976 + detail::values_and_holders vhs(this);
7977 + auto it = vhs.find(find_type);
7978 + if (it != vhs.end()) {
7982 + if (!throw_if_missing) {
7983 + return value_and_holder();
7986 +#if defined(NDEBUG)
7987 + pybind11_fail("pybind11::detail::instance::get_value_and_holder: "
7988 + "type is not a pybind11 base of the given instance "
7989 + "(compile in debug mode for type details)");
7991 + pybind11_fail("pybind11::detail::instance::get_value_and_holder: `"
7992 + + get_fully_qualified_tp_name(find_type->type)
7993 + + "' is not a pybind11 base of the given `"
7994 + + get_fully_qualified_tp_name(Py_TYPE(this)) + "' instance");
7998 +PYBIND11_NOINLINE void instance::allocate_layout() {
7999 + const auto &tinfo = all_type_info(Py_TYPE(this));
8001 + const size_t n_types = tinfo.size();
8003 + if (n_types == 0) {
8005 + "instance allocation failed: new instance has no pybind11-registered base types");
8009 + = n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
8011 + // Simple path: no python-side multiple inheritance, and a small-enough holder
8012 + if (simple_layout) {
8013 + simple_value_holder[0] = nullptr;
8014 + simple_holder_constructed = false;
8015 + simple_instance_registered = false;
8016 + } else { // multiple base types or a too-large holder
8017 + // Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
8018 + // [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
8019 + // values that tracks whether each associated holder has been initialized. Each [block] is
8020 + // padded, if necessary, to an integer multiple of sizeof(void *).
8022 + for (auto *t : tinfo) {
8023 + space += 1; // value pointer
8024 + space += t->holder_size_in_ptrs; // holder instance
8026 + size_t flags_at = space;
8027 + space += size_in_ptrs(n_types); // status bytes (holder_constructed and
8028 + // instance_registered)
8030 + // Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
8031 + // in particular, need to be 0). Use Python's memory allocation functions: in Python 3.6
8032 + // they default to using pymalloc, which is designed to be efficient for small allocations
8033 + // like the one we're doing here; in earlier versions (and for larger allocations) they are
8034 + // just wrappers around malloc.
8035 +#if PY_VERSION_HEX >= 0x03050000
8036 + nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
8037 + if (!nonsimple.values_and_holders) {
8038 + throw std::bad_alloc();
8041 + nonsimple.values_and_holders = (void **) PyMem_New(void *, space);
8042 + if (!nonsimple.values_and_holders)
8043 + throw std::bad_alloc();
8044 + std::memset(nonsimple.values_and_holders, 0, space * sizeof(void *));
8047 + = reinterpret_cast<std::uint8_t *>(&nonsimple.values_and_holders[flags_at]);
8052 +// NOLINTNEXTLINE(readability-make-member-function-const)
8053 +PYBIND11_NOINLINE void instance::deallocate_layout() {
8054 + if (!simple_layout) {
8055 + PyMem_Free(nonsimple.values_and_holders);
8059 +PYBIND11_NOINLINE bool isinstance_generic(handle obj, const std::type_info &tp) {
8060 + handle type = detail::get_type_handle(tp, false);
8064 + return isinstance(obj, type);
8067 +PYBIND11_NOINLINE std::string error_string() {
8068 + if (!PyErr_Occurred()) {
8069 + PyErr_SetString(PyExc_RuntimeError, "Unknown internal error occurred");
8070 + return "Unknown internal error occurred";
8073 + error_scope scope; // Preserve error state
8075 + std::string errorString;
8077 + errorString += handle(scope.type).attr("__name__").cast<std::string>();
8078 + errorString += ": ";
8080 + if (scope.value) {
8081 + errorString += (std::string) str(scope.value);
8084 + PyErr_NormalizeException(&scope.type, &scope.value, &scope.trace);
8086 +#if PY_MAJOR_VERSION >= 3
8087 + if (scope.trace != nullptr) {
8088 + PyException_SetTraceback(scope.value, scope.trace);
8092 +#if !defined(PYPY_VERSION)
8093 + if (scope.trace) {
8094 + auto *trace = (PyTracebackObject *) scope.trace;
8096 + /* Get the deepest trace possible */
8097 + while (trace->tb_next) {
8098 + trace = trace->tb_next;
8101 + PyFrameObject *frame = trace->tb_frame;
8102 + Py_XINCREF(frame);
8103 + errorString += "\n\nAt:\n";
8105 +# if PY_VERSION_HEX >= 0x030900B1
8106 + PyCodeObject *f_code = PyFrame_GetCode(frame);
8108 + PyCodeObject *f_code = frame->f_code;
8109 + Py_INCREF(f_code);
8111 + int lineno = PyFrame_GetLineNumber(frame);
8112 + errorString += " " + handle(f_code->co_filename).cast<std::string>() + "("
8113 + + std::to_string(lineno)
8114 + + "): " + handle(f_code->co_name).cast<std::string>() + "\n";
8115 + Py_DECREF(f_code);
8116 +# if PY_VERSION_HEX >= 0x030900B1
8117 + auto *b_frame = PyFrame_GetBack(frame);
8119 + auto *b_frame = frame->f_back;
8120 + Py_XINCREF(b_frame);
8128 + return errorString;
8131 +PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type) {
8132 + auto &instances = get_internals().registered_instances;
8133 + auto range = instances.equal_range(ptr);
8134 + for (auto it = range.first; it != range.second; ++it) {
8135 + for (const auto &vh : values_and_holders(it->second)) {
8136 + if (vh.type == type) {
8137 + return handle((PyObject *) it->second);
8144 +inline PyThreadState *get_thread_state_unchecked() {
8145 +#if defined(PYPY_VERSION)
8146 + return PyThreadState_GET();
8147 +#elif PY_VERSION_HEX < 0x03000000
8148 + return _PyThreadState_Current;
8149 +#elif PY_VERSION_HEX < 0x03050000
8150 + return (PyThreadState *) _Py_atomic_load_relaxed(&_PyThreadState_Current);
8151 +#elif PY_VERSION_HEX < 0x03050200
8152 + return (PyThreadState *) _PyThreadState_Current.value;
8154 + return _PyThreadState_UncheckedGet();
8158 +// Forward declarations
8159 +void keep_alive_impl(handle nurse, handle patient);
8160 +inline PyObject *make_new_instance(PyTypeObject *type);
8162 +class type_caster_generic {
8164 + PYBIND11_NOINLINE explicit type_caster_generic(const std::type_info &type_info)
8165 + : typeinfo(get_type_info(type_info)), cpptype(&type_info) {}
8167 + explicit type_caster_generic(const type_info *typeinfo)
8168 + : typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) {}
8170 + bool load(handle src, bool convert) { return load_impl<type_caster_generic>(src, convert); }
8172 + PYBIND11_NOINLINE static handle cast(const void *_src,
8173 + return_value_policy policy,
8175 + const detail::type_info *tinfo,
8176 + void *(*copy_constructor)(const void *),
8177 + void *(*move_constructor)(const void *),
8178 + const void *existing_holder = nullptr) {
8179 + if (!tinfo) { // no type info: error will be set already
8183 + void *src = const_cast<void *>(_src);
8184 + if (src == nullptr) {
8185 + return none().release();
8188 + if (handle registered_inst = find_registered_python_instance(src, tinfo)) {
8189 + return registered_inst;
8192 + auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
8193 + auto *wrapper = reinterpret_cast<instance *>(inst.ptr());
8194 + wrapper->owned = false;
8195 + void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
8198 + case return_value_policy::automatic:
8199 + case return_value_policy::take_ownership:
8201 + wrapper->owned = true;
8204 + case return_value_policy::automatic_reference:
8205 + case return_value_policy::reference:
8207 + wrapper->owned = false;
8210 + case return_value_policy::copy:
8211 + if (copy_constructor) {
8212 + valueptr = copy_constructor(src);
8214 +#if defined(NDEBUG)
8215 + throw cast_error("return_value_policy = copy, but type is "
8216 + "non-copyable! (compile in debug mode for details)");
8218 + std::string type_name(tinfo->cpptype->name());
8219 + detail::clean_type_id(type_name);
8220 + throw cast_error("return_value_policy = copy, but type " + type_name
8221 + + " is non-copyable!");
8224 + wrapper->owned = true;
8227 + case return_value_policy::move:
8228 + if (move_constructor) {
8229 + valueptr = move_constructor(src);
8230 + } else if (copy_constructor) {
8231 + valueptr = copy_constructor(src);
8233 +#if defined(NDEBUG)
8234 + throw cast_error("return_value_policy = move, but type is neither "
8235 + "movable nor copyable! "
8236 + "(compile in debug mode for details)");
8238 + std::string type_name(tinfo->cpptype->name());
8239 + detail::clean_type_id(type_name);
8240 + throw cast_error("return_value_policy = move, but type " + type_name
8241 + + " is neither movable nor copyable!");
8244 + wrapper->owned = true;
8247 + case return_value_policy::reference_internal:
8249 + wrapper->owned = false;
8250 + keep_alive_impl(inst, parent);
8254 + throw cast_error("unhandled return_value_policy: should not happen!");
8257 + tinfo->init_instance(wrapper, existing_holder);
8259 + return inst.release();
8262 + // Base methods for generic caster; there are overridden in copyable_holder_caster
8263 + void load_value(value_and_holder &&v_h) {
8264 + auto *&vptr = v_h.value_ptr();
8265 + // Lazy allocation for unallocated values:
8266 + if (vptr == nullptr) {
8267 + const auto *type = v_h.type ? v_h.type : typeinfo;
8268 + if (type->operator_new) {
8269 + vptr = type->operator_new(type->type_size);
8271 +#if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
8272 + if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
8273 + vptr = ::operator new(type->type_size, std::align_val_t(type->type_align));
8275 + vptr = ::operator new(type->type_size);
8278 + vptr = ::operator new(type->type_size);
8284 + bool try_implicit_casts(handle src, bool convert) {
8285 + for (const auto &cast : typeinfo->implicit_casts) {
8286 + type_caster_generic sub_caster(*cast.first);
8287 + if (sub_caster.load(src, convert)) {
8288 + value = cast.second(sub_caster.value);
8294 + bool try_direct_conversions(handle src) {
8295 + for (auto &converter : *typeinfo->direct_conversions) {
8296 + if (converter(src.ptr(), value)) {
8302 + void check_holder_compat() {}
8304 + PYBIND11_NOINLINE static void *local_load(PyObject *src, const type_info *ti) {
8305 + auto caster = type_caster_generic(ti);
8306 + if (caster.load(src, false)) {
8307 + return caster.value;
8312 + /// Try to load with foreign typeinfo, if available. Used when there is no
8313 + /// native typeinfo, or when the native one wasn't able to produce a value.
8314 + PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) {
8315 + constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;
8316 + const auto pytype = type::handle_of(src);
8317 + if (!hasattr(pytype, local_key)) {
8321 + type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
8322 + // Only consider this foreign loader if actually foreign and is a loader of the correct cpp
8324 + if (foreign_typeinfo->module_local_load == &local_load
8325 + || (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype))) {
8329 + if (auto *result = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo)) {
8336 + // Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant
8337 + // bits of code between here and copyable_holder_caster where the two classes need different
8338 + // logic (without having to resort to virtual inheritance).
8339 + template <typename ThisT>
8340 + PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
8345 + return try_load_foreign_module_local(src);
8348 + auto &this_ = static_cast<ThisT &>(*this);
8349 + this_.check_holder_compat();
8351 + PyTypeObject *srctype = Py_TYPE(src.ptr());
8353 + // Case 1: If src is an exact type match for the target type then we can reinterpret_cast
8354 + // the instance's value pointer to the target type:
8355 + if (srctype == typeinfo->type) {
8356 + this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
8359 + // Case 2: We have a derived class
8360 + if (PyType_IsSubtype(srctype, typeinfo->type)) {
8361 + const auto &bases = all_type_info(srctype);
8362 + bool no_cpp_mi = typeinfo->simple_type;
8364 + // Case 2a: the python type is a Python-inherited derived class that inherits from just
8365 + // one simple (no MI) pybind11 class, or is an exact match, so the C++ instance is of
8366 + // the right type and we can use reinterpret_cast.
8367 + // (This is essentially the same as case 2b, but because not using multiple inheritance
8368 + // is extremely common, we handle it specially to avoid the loop iterator and type
8369 + // pointer lookup overhead)
8370 + if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
8371 + this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
8374 + // Case 2b: the python type inherits from multiple C++ bases. Check the bases to see
8375 + // if we can find an exact match (or, for a simple C++ type, an inherited match); if
8376 + // so, we can safely reinterpret_cast to the relevant pointer.
8377 + if (bases.size() > 1) {
8378 + for (auto *base : bases) {
8379 + if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type)
8380 + : base->type == typeinfo->type) {
8382 + reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
8388 + // Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type
8389 + // match in the registered bases, above, so try implicit casting (needed for proper C++
8390 + // casting when MI is involved).
8391 + if (this_.try_implicit_casts(src, convert)) {
8396 + // Perform an implicit conversion
8398 + for (const auto &converter : typeinfo->implicit_conversions) {
8399 + auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
8400 + if (load_impl<ThisT>(temp, false)) {
8401 + loader_life_support::add_patient(temp);
8405 + if (this_.try_direct_conversions(src)) {
8410 + // Failed to match local typeinfo. Try again with global.
8411 + if (typeinfo->module_local) {
8412 + if (auto *gtype = get_global_type_info(*typeinfo->cpptype)) {
8414 + return load(src, false);
8418 + // Global typeinfo has precedence over foreign module_local
8419 + if (try_load_foreign_module_local(src)) {
8423 + // Custom converters didn't take None, now we convert None to nullptr.
8424 + if (src.is_none()) {
8425 + // Defer accepting None to other overloads (if we aren't in convert mode):
8436 + // Called to do type lookup and wrap the pointer and type in a pair when a dynamic_cast
8437 + // isn't needed or can't be used. If the type is unknown, sets the error and returns a pair
8438 + // with .second = nullptr. (p.first = nullptr is not an error: it becomes None).
8439 + PYBIND11_NOINLINE static std::pair<const void *, const type_info *>
8440 + src_and_type(const void *src,
8441 + const std::type_info &cast_type,
8442 + const std::type_info *rtti_type = nullptr) {
8443 + if (auto *tpi = get_type_info(cast_type)) {
8444 + return {src, const_cast<const type_info *>(tpi)};
8447 + // Not found, set error:
8448 + std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
8449 + detail::clean_type_id(tname);
8450 + std::string msg = "Unregistered type : " + tname;
8451 + PyErr_SetString(PyExc_TypeError, msg.c_str());
8452 + return {nullptr, nullptr};
8455 + const type_info *typeinfo = nullptr;
8456 + const std::type_info *cpptype = nullptr;
8457 + void *value = nullptr;
8461 + * Determine suitable casting operator for pointer-or-lvalue-casting type casters. The type caster
8462 + * needs to provide `operator T*()` and `operator T&()` operators.
8464 + * If the type supports moving the value away via an `operator T&&() &&` method, it should use
8465 + * `movable_cast_op_type` instead.
8467 +template <typename T>
8468 +using cast_op_type = conditional_t<std::is_pointer<remove_reference_t<T>>::value,
8469 + typename std::add_pointer<intrinsic_t<T>>::type,
8470 + typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
8473 + * Determine suitable casting operator for a type caster with a movable value. Such a type caster
8474 + * needs to provide `operator T*()`, `operator T&()`, and `operator T&&() &&`. The latter will be
8475 + * called in appropriate contexts where the value can be moved rather than copied.
8477 + * These operator are automatically provided when using the PYBIND11_TYPE_CASTER macro.
8479 +template <typename T>
8480 +using movable_cast_op_type
8481 + = conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,
8482 + typename std::add_pointer<intrinsic_t<T>>::type,
8483 + conditional_t<std::is_rvalue_reference<T>::value,
8484 + typename std::add_rvalue_reference<intrinsic_t<T>>::type,
8485 + typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
8487 +// std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when
8488 +// T is non-copyable, but code containing such a copy constructor fails to actually compile.
8489 +template <typename T, typename SFINAE = void>
8490 +struct is_copy_constructible : std::is_copy_constructible<T> {};
8492 +// Specialization for types that appear to be copy constructible but also look like stl containers
8493 +// (we specifically check for: has `value_type` and `reference` with `reference = value_type&`): if
8494 +// so, copy constructability depends on whether the value_type is copy constructible.
8495 +template <typename Container>
8496 +struct is_copy_constructible<
8499 + all_of<std::is_copy_constructible<Container>,
8500 + std::is_same<typename Container::value_type &, typename Container::reference>,
8501 + // Avoid infinite recursion
8502 + negation<std::is_same<Container, typename Container::value_type>>>::value>>
8503 + : is_copy_constructible<typename Container::value_type> {};
8505 +// Likewise for std::pair
8506 +// (after C++17 it is mandatory that the copy constructor not exist when the two types aren't
8507 +// themselves copy constructible, but this can not be relied upon when T1 or T2 are themselves
8509 +template <typename T1, typename T2>
8510 +struct is_copy_constructible<std::pair<T1, T2>>
8511 + : all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
8513 +// The same problems arise with std::is_copy_assignable, so we use the same workaround.
8514 +template <typename T, typename SFINAE = void>
8515 +struct is_copy_assignable : std::is_copy_assignable<T> {};
8516 +template <typename Container>
8517 +struct is_copy_assignable<Container,
8518 + enable_if_t<all_of<std::is_copy_assignable<Container>,
8519 + std::is_same<typename Container::value_type &,
8520 + typename Container::reference>>::value>>
8521 + : is_copy_assignable<typename Container::value_type> {};
8522 +template <typename T1, typename T2>
8523 +struct is_copy_assignable<std::pair<T1, T2>>
8524 + : all_of<is_copy_assignable<T1>, is_copy_assignable<T2>> {};
8526 +PYBIND11_NAMESPACE_END(detail)
8528 +// polymorphic_type_hook<itype>::get(src, tinfo) determines whether the object pointed
8529 +// to by `src` actually is an instance of some class derived from `itype`.
8530 +// If so, it sets `tinfo` to point to the std::type_info representing that derived
8531 +// type, and returns a pointer to the start of the most-derived object of that type
8532 +// (in which `src` is a subobject; this will be the same address as `src` in most
8533 +// single inheritance cases). If not, or if `src` is nullptr, it simply returns `src`
8534 +// and leaves `tinfo` at its default value of nullptr.
8536 +// The default polymorphic_type_hook just returns src. A specialization for polymorphic
8537 +// types determines the runtime type of the passed object and adjusts the this-pointer
8538 +// appropriately via dynamic_cast<void*>. This is what enables a C++ Animal* to appear
8539 +// to Python as a Dog (if Dog inherits from Animal, Animal is polymorphic, Dog is
8540 +// registered with pybind11, and this Animal is in fact a Dog).
8542 +// You may specialize polymorphic_type_hook yourself for types that want to appear
8543 +// polymorphic to Python but do not use C++ RTTI. (This is a not uncommon pattern
8544 +// in performance-sensitive applications, used most notably in LLVM.)
8546 +// polymorphic_type_hook_base allows users to specialize polymorphic_type_hook with
8547 +// std::enable_if. User provided specializations will always have higher priority than
8548 +// the default implementation and specialization provided in polymorphic_type_hook_base.
8549 +template <typename itype, typename SFINAE = void>
8550 +struct polymorphic_type_hook_base {
8551 + static const void *get(const itype *src, const std::type_info *&) { return src; }
8553 +template <typename itype>
8554 +struct polymorphic_type_hook_base<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>> {
8555 + static const void *get(const itype *src, const std::type_info *&type) {
8556 + type = src ? &typeid(*src) : nullptr;
8557 + return dynamic_cast<const void *>(src);
8560 +template <typename itype, typename SFINAE = void>
8561 +struct polymorphic_type_hook : public polymorphic_type_hook_base<itype> {};
8563 +PYBIND11_NAMESPACE_BEGIN(detail)
8565 +/// Generic type caster for objects stored on the heap
8566 +template <typename type>
8567 +class type_caster_base : public type_caster_generic {
8568 + using itype = intrinsic_t<type>;
8571 + static constexpr auto name = const_name<type>();
8573 + type_caster_base() : type_caster_base(typeid(type)) {}
8574 + explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) {}
8576 + static handle cast(const itype &src, return_value_policy policy, handle parent) {
8577 + if (policy == return_value_policy::automatic
8578 + || policy == return_value_policy::automatic_reference) {
8579 + policy = return_value_policy::copy;
8581 + return cast(&src, policy, parent);
8584 + static handle cast(itype &&src, return_value_policy, handle parent) {
8585 + return cast(&src, return_value_policy::move, parent);
8588 + // Returns a (pointer, type_info) pair taking care of necessary type lookup for a
8589 + // polymorphic type (using RTTI by default, but can be overridden by specializing
8590 + // polymorphic_type_hook). If the instance isn't derived, returns the base version.
8591 + static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
8592 + const auto &cast_type = typeid(itype);
8593 + const std::type_info *instance_type = nullptr;
8594 + const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
8595 + if (instance_type && !same_type(cast_type, *instance_type)) {
8596 + // This is a base pointer to a derived type. If the derived type is registered
8597 + // with pybind11, we want to make the full derived object available.
8598 + // In the typical case where itype is polymorphic, we get the correct
8599 + // derived pointer (which may be != base pointer) by a dynamic_cast to
8600 + // most derived type. If itype is not polymorphic, we won't get here
8601 + // except via a user-provided specialization of polymorphic_type_hook,
8602 + // and the user has promised that no this-pointer adjustment is
8603 + // required in that case, so it's OK to use static_cast.
8604 + if (const auto *tpi = get_type_info(*instance_type)) {
8605 + return {vsrc, tpi};
8608 + // Otherwise we have either a nullptr, an `itype` pointer, or an unknown derived pointer,
8609 + // so don't do a cast
8610 + return type_caster_generic::src_and_type(src, cast_type, instance_type);
8613 + static handle cast(const itype *src, return_value_policy policy, handle parent) {
8614 + auto st = src_and_type(src);
8615 + return type_caster_generic::cast(st.first,
8619 + make_copy_constructor(src),
8620 + make_move_constructor(src));
8623 + static handle cast_holder(const itype *src, const void *holder) {
8624 + auto st = src_and_type(src);
8625 + return type_caster_generic::cast(st.first,
8626 + return_value_policy::take_ownership,
8634 + template <typename T>
8635 + using cast_op_type = detail::cast_op_type<T>;
8637 + // NOLINTNEXTLINE(google-explicit-constructor)
8638 + operator itype *() { return (type *) value; }
8639 + // NOLINTNEXTLINE(google-explicit-constructor)
8640 + operator itype &() {
8642 + throw reference_cast_error();
8644 + return *((itype *) value);
8648 + using Constructor = void *(*) (const void *);
8650 + /* Only enabled when the types are {copy,move}-constructible *and* when the type
8651 + does not have a private operator new implementation. A comma operator is used in the
8652 + decltype argument to apply SFINAE to the public copy/move constructors.*/
8653 + template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
8654 + static auto make_copy_constructor(const T *)
8655 + -> decltype(new T(std::declval<const T>()), Constructor{}) {
8656 + return [](const void *arg) -> void * { return new T(*reinterpret_cast<const T *>(arg)); };
8659 + template <typename T, typename = enable_if_t<std::is_move_constructible<T>::value>>
8660 + static auto make_move_constructor(const T *)
8661 + -> decltype(new T(std::declval<T &&>()), Constructor{}) {
8662 + return [](const void *arg) -> void * {
8663 + return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
8667 + static Constructor make_copy_constructor(...) { return nullptr; }
8668 + static Constructor make_move_constructor(...) { return nullptr; }
8671 +PYBIND11_NAMESPACE_END(detail)
8672 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
8673 diff -Nur pythia8309.orig/plugins/python/include/pybind11/detail/typeid.h pythia8309/plugins/python/include/pybind11/detail/typeid.h
8674 --- pythia8309.orig/plugins/python/include/pybind11/detail/typeid.h 2023-02-16 18:12:45.000000000 +0100
8675 +++ pythia8309/plugins/python/include/pybind11/detail/typeid.h 2023-03-13 09:52:25.459021601 +0100
8679 #if defined(__GNUG__)
8680 -#include <cxxabi.h>
8681 +# include <cxxabi.h>
8684 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
8685 -NAMESPACE_BEGIN(detail)
8686 +#include "common.h"
8688 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
8689 +PYBIND11_NAMESPACE_BEGIN(detail)
8690 /// Erase all occurrences of a substring
8691 inline void erase_all(std::string &string, const std::string &search) {
8692 for (size_t pos = 0;;) {
8693 pos = string.find(search, pos);
8694 - if (pos == std::string::npos) break;
8695 + if (pos == std::string::npos) {
8698 string.erase(pos, search.length());
8702 -PYBIND11_NOINLINE inline void clean_type_id(std::string &name) {
8703 +PYBIND11_NOINLINE void clean_type_id(std::string &name) {
8704 #if defined(__GNUG__)
8706 - std::unique_ptr<char, void (*)(void *)> res {
8707 - abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status), std::free };
8709 + std::unique_ptr<char, void (*)(void *)> res{
8710 + abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status), std::free};
8711 + if (status == 0) {
8715 detail::erase_all(name, "class ");
8716 detail::erase_all(name, "struct ");
8719 detail::erase_all(name, "pybind11::");
8721 -NAMESPACE_END(detail)
8722 +PYBIND11_NAMESPACE_END(detail)
8724 /// Return a string representation of a C++ type
8725 -template <typename T> static std::string type_id() {
8726 +template <typename T>
8727 +static std::string type_id() {
8728 std::string name(typeid(T).name());
8729 detail::clean_type_id(name);
8733 -NAMESPACE_END(PYBIND11_NAMESPACE)
8734 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
8735 diff -Nur pythia8309.orig/plugins/python/include/pybind11/eigen.h pythia8309/plugins/python/include/pybind11/eigen.h
8736 --- pythia8309.orig/plugins/python/include/pybind11/eigen.h 2023-02-16 18:12:45.000000000 +0100
8737 +++ pythia8309/plugins/python/include/pybind11/eigen.h 2023-03-13 09:52:25.461021606 +0100
8743 +/* HINT: To suppress warnings originating from the Eigen headers, use -isystem.
8745 + https://stackoverflow.com/questions/2579576/i-dir-vs-isystem-dir
8746 + https://stackoverflow.com/questions/1741816/isystem-for-ms-visual-studio-c-compiler
8749 -#if defined(__INTEL_COMPILER)
8750 -# pragma warning(disable: 1682) // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem)
8751 -#elif defined(__GNUG__) || defined(__clang__)
8752 -# pragma GCC diagnostic push
8753 -# pragma GCC diagnostic ignored "-Wconversion"
8754 -# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
8756 -// Eigen generates a bunch of implicit-copy-constructor-is-deprecated warnings with -Wdeprecated
8757 -// under Clang, so disable that warning here:
8758 -# pragma GCC diagnostic ignored "-Wdeprecated"
8761 -# pragma GCC diagnostic ignored "-Wint-in-bool-context"
8766 +// The C4127 suppression was introduced for Eigen 3.4.0. In theory we could
8767 +// make it version specific, or even remove it later, but considering that
8768 +// 1. C4127 is generally far more distracting than useful for modern template code, and
8769 +// 2. we definitely want to ignore any MSVC warnings originating from Eigen code,
8770 +// it is probably best to keep this around indefinitely.
8771 #if defined(_MSC_VER)
8772 -# pragma warning(push)
8773 -# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
8774 -# pragma warning(disable: 4996) // warning C4996: std::unary_negate is deprecated in C++17
8775 +# pragma warning(push)
8776 +# pragma warning(disable : 4127) // C4127: conditional expression is constant
8779 #include <Eigen/Core>
8780 #include <Eigen/SparseCore>
8782 +#if defined(_MSC_VER)
8783 +# pragma warning(pop)
8786 // Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit
8787 // move constructors that break things. We could detect this an explicitly copy, but an extra copy
8788 // of matrices seems highly undesirable.
8789 -static_assert(EIGEN_VERSION_AT_LEAST(3,2,7), "Eigen support in pybind11 requires Eigen >= 3.2.7");
8790 +static_assert(EIGEN_VERSION_AT_LEAST(3, 2, 7),
8791 + "Eigen support in pybind11 requires Eigen >= 3.2.7");
8793 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
8794 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
8796 // Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides:
8797 using EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
8798 -template <typename MatrixType> using EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>;
8799 -template <typename MatrixType> using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>;
8800 +template <typename MatrixType>
8801 +using EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>;
8802 +template <typename MatrixType>
8803 +using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>;
8805 -NAMESPACE_BEGIN(detail)
8806 +PYBIND11_NAMESPACE_BEGIN(detail)
8808 -#if EIGEN_VERSION_AT_LEAST(3,3,0)
8809 +#if EIGEN_VERSION_AT_LEAST(3, 3, 0)
8810 using EigenIndex = Eigen::Index;
8811 +template <typename Scalar, int Flags, typename StorageIndex>
8812 +using EigenMapSparseMatrix = Eigen::Map<Eigen::SparseMatrix<Scalar, Flags, StorageIndex>>;
8814 using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE;
8815 +template <typename Scalar, int Flags, typename StorageIndex>
8816 +using EigenMapSparseMatrix = Eigen::MappedSparseMatrix<Scalar, Flags, StorageIndex>;
8819 // Matches Eigen::Map, Eigen::Ref, blocks, etc:
8820 -template <typename T> using is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>, std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>;
8821 -template <typename T> using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>;
8822 -template <typename T> using is_eigen_dense_plain = all_of<negation<is_eigen_dense_map<T>>, is_template_base_of<Eigen::PlainObjectBase, T>>;
8823 -template <typename T> using is_eigen_sparse = is_template_base_of<Eigen::SparseMatrixBase, T>;
8824 +template <typename T>
8825 +using is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>,
8826 + std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>;
8827 +template <typename T>
8828 +using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>;
8829 +template <typename T>
8830 +using is_eigen_dense_plain
8831 + = all_of<negation<is_eigen_dense_map<T>>, is_template_base_of<Eigen::PlainObjectBase, T>>;
8832 +template <typename T>
8833 +using is_eigen_sparse = is_template_base_of<Eigen::SparseMatrixBase, T>;
8834 // Test for objects inheriting from EigenBase<Derived> that aren't captured by the above. This
8835 // basically covers anything that can be assigned to a dense matrix but that don't have a typical
8836 // matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and
8837 // SelfAdjointView fall into this category.
8838 -template <typename T> using is_eigen_other = all_of<
8839 - is_template_base_of<Eigen::EigenBase, T>,
8840 - negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>>
8842 +template <typename T>
8843 +using is_eigen_other
8844 + = all_of<is_template_base_of<Eigen::EigenBase, T>,
8845 + negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>>>;
8847 // Captures numpy/eigen conformability status (returned by EigenProps::conformable()):
8848 -template <bool EigenRowMajor> struct EigenConformable {
8849 +template <bool EigenRowMajor>
8850 +struct EigenConformable {
8851 bool conformable = false;
8852 EigenIndex rows = 0, cols = 0;
8853 - EigenDStride stride{0, 0}; // Only valid if negativestrides is false!
8854 - bool negativestrides = false; // If true, do not use stride!
8855 + EigenDStride stride{0, 0}; // Only valid if negativestrides is false!
8856 + bool negativestrides = false; // If true, do not use stride!
8858 + // NOLINTNEXTLINE(google-explicit-constructor)
8859 EigenConformable(bool fits = false) : conformable{fits} {}
8861 - EigenConformable(EigenIndex r, EigenIndex c,
8862 - EigenIndex rstride, EigenIndex cstride) :
8863 - conformable{true}, rows{r}, cols{c} {
8864 - // TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity. http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747
8865 - if (rstride < 0 || cstride < 0) {
8866 - negativestrides = true;
8868 - stride = {EigenRowMajor ? rstride : cstride /* outer stride */,
8869 - EigenRowMajor ? cstride : rstride /* inner stride */ };
8872 + EigenConformable(EigenIndex r, EigenIndex c, EigenIndex rstride, EigenIndex cstride)
8873 + : conformable{true}, rows{r}, cols{c},
8874 + // TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity.
8875 + // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747
8876 + stride{EigenRowMajor ? (rstride > 0 ? rstride : 0)
8877 + : (cstride > 0 ? cstride : 0) /* outer stride */,
8878 + EigenRowMajor ? (cstride > 0 ? cstride : 0)
8879 + : (rstride > 0 ? rstride : 0) /* inner stride */},
8880 + negativestrides{rstride < 0 || cstride < 0} {}
8882 EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride)
8883 - : EigenConformable(r, c, r == 1 ? c*stride : stride, c == 1 ? r : r*stride) {}
8884 + : EigenConformable(r, c, r == 1 ? c * stride : stride, c == 1 ? r : r * stride) {}
8886 - template <typename props> bool stride_compatible() const {
8887 + template <typename props>
8888 + bool stride_compatible() const {
8889 // To have compatible strides, we need (on both dimensions) one of fully dynamic strides,
8890 - // matching strides, or a dimension size of 1 (in which case the stride value is irrelevant)
8892 - !negativestrides &&
8893 - (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner() ||
8894 - (EigenRowMajor ? cols : rows) == 1) &&
8895 - (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer() ||
8896 - (EigenRowMajor ? rows : cols) == 1);
8897 + // matching strides, or a dimension size of 1 (in which case the stride value is
8899 + return !negativestrides
8900 + && (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner()
8901 + || (EigenRowMajor ? cols : rows) == 1)
8902 + && (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer()
8903 + || (EigenRowMajor ? rows : cols) == 1);
8905 + // NOLINTNEXTLINE(google-explicit-constructor)
8906 operator bool() const { return conformable; }
8909 -template <typename Type> struct eigen_extract_stride { using type = Type; };
8910 +template <typename Type>
8911 +struct eigen_extract_stride {
8912 + using type = Type;
8914 template <typename PlainObjectType, int MapOptions, typename StrideType>
8915 -struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> { using type = StrideType; };
8916 +struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> {
8917 + using type = StrideType;
8919 template <typename PlainObjectType, int Options, typename StrideType>
8920 -struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> { using type = StrideType; };
8921 +struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> {
8922 + using type = StrideType;
8925 // Helper struct for extracting information from an Eigen type
8926 -template <typename Type_> struct EigenProps {
8927 +template <typename Type_>
8928 +struct EigenProps {
8930 using Scalar = typename Type::Scalar;
8931 using StrideType = typename eigen_extract_stride<Type>::type;
8932 - static constexpr EigenIndex
8933 - rows = Type::RowsAtCompileTime,
8934 - cols = Type::ColsAtCompileTime,
8935 - size = Type::SizeAtCompileTime;
8936 - static constexpr bool
8937 - row_major = Type::IsRowMajor,
8938 - vector = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
8939 - fixed_rows = rows != Eigen::Dynamic,
8940 - fixed_cols = cols != Eigen::Dynamic,
8941 - fixed = size != Eigen::Dynamic, // Fully-fixed size
8942 - dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size
8944 - template <EigenIndex i, EigenIndex ifzero> using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;
8945 - static constexpr EigenIndex inner_stride = if_zero<StrideType::InnerStrideAtCompileTime, 1>::value,
8946 - outer_stride = if_zero<StrideType::OuterStrideAtCompileTime,
8947 - vector ? size : row_major ? cols : rows>::value;
8948 - static constexpr bool dynamic_stride = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
8949 - static constexpr bool requires_row_major = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
8950 - static constexpr bool requires_col_major = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
8951 + static constexpr EigenIndex rows = Type::RowsAtCompileTime, cols = Type::ColsAtCompileTime,
8952 + size = Type::SizeAtCompileTime;
8953 + static constexpr bool row_major = Type::IsRowMajor,
8955 + = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
8956 + fixed_rows = rows != Eigen::Dynamic, fixed_cols = cols != Eigen::Dynamic,
8957 + fixed = size != Eigen::Dynamic, // Fully-fixed size
8958 + dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size
8960 + template <EigenIndex i, EigenIndex ifzero>
8961 + using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;
8962 + static constexpr EigenIndex inner_stride
8963 + = if_zero<StrideType::InnerStrideAtCompileTime, 1>::value,
8964 + outer_stride = if_zero < StrideType::OuterStrideAtCompileTime,
8966 + : row_major ? cols
8968 + static constexpr bool dynamic_stride
8969 + = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
8970 + static constexpr bool requires_row_major
8971 + = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
8972 + static constexpr bool requires_col_major
8973 + = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
8975 // Takes an input array and determines whether we can make it fit into the Eigen type. If
8976 // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector
8977 // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).
8978 static EigenConformable<row_major> conformable(const array &a) {
8979 const auto dims = a.ndim();
8980 - if (dims < 1 || dims > 2)
8981 + if (dims < 1 || dims > 2) {
8985 if (dims == 2) { // Matrix type: require exact match (or dynamic)
8988 - np_rows = a.shape(0),
8989 - np_cols = a.shape(1),
8990 - np_rstride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)),
8991 - np_cstride = a.strides(1) / static_cast<ssize_t>(sizeof(Scalar));
8992 - if ((fixed_rows && np_rows != rows) || (fixed_cols && np_cols != cols))
8993 + EigenIndex np_rows = a.shape(0), np_cols = a.shape(1),
8994 + np_rstride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)),
8995 + np_cstride = a.strides(1) / static_cast<ssize_t>(sizeof(Scalar));
8996 + if ((PYBIND11_SILENCE_MSVC_C4127(fixed_rows) && np_rows != rows)
8997 + || (PYBIND11_SILENCE_MSVC_C4127(fixed_cols) && np_cols != cols)) {
9001 return {np_rows, np_cols, np_rstride, np_cstride};
9004 - // Otherwise we're storing an n-vector. Only one of the strides will be used, but whichever
9005 - // is used, we want the (single) numpy stride value.
9006 + // Otherwise we're storing an n-vector. Only one of the strides will be used, but
9007 + // whichever is used, we want the (single) numpy stride value.
9008 const EigenIndex n = a.shape(0),
9009 - stride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar));
9010 + stride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar));
9012 if (vector) { // Eigen type is a compile-time vector
9013 - if (fixed && size != n)
9014 + if (PYBIND11_SILENCE_MSVC_C4127(fixed) && size != n) {
9015 return false; // Vector size mismatch
9017 return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};
9021 // The type has a fixed size, but is not a vector: abort
9024 - else if (fixed_cols) {
9026 // Since this isn't a vector, cols must be != 1. We allow this only if it exactly
9027 // equals the number of elements (rows is Dynamic, and so 1 row is allowed).
9028 - if (cols != n) return false;
9032 return {1, n, stride};
9033 + } // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
9034 + if (PYBIND11_SILENCE_MSVC_C4127(fixed_rows) && rows != n) {
9038 - // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
9039 - if (fixed_rows && rows != n) return false;
9040 - return {n, 1, stride};
9042 + return {n, 1, stride};
9045 - static constexpr bool show_writeable = is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value;
9046 + static constexpr bool show_writeable
9047 + = is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value;
9048 static constexpr bool show_order = is_eigen_dense_map<Type>::value;
9049 static constexpr bool show_c_contiguous = show_order && requires_row_major;
9050 - static constexpr bool show_f_contiguous = !show_c_contiguous && show_order && requires_col_major;
9051 + static constexpr bool show_f_contiguous
9052 + = !show_c_contiguous && show_order && requires_col_major;
9054 - static constexpr auto descriptor =
9055 - _("numpy.ndarray[") + npy_format_descriptor<Scalar>::name +
9056 - _("[") + _<fixed_rows>(_<(size_t) rows>(), _("m")) +
9057 - _(", ") + _<fixed_cols>(_<(size_t) cols>(), _("n")) +
9059 - // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to be
9060 - // satisfied: writeable=True (for a mutable reference), and, depending on the map's stride
9061 - // options, possibly f_contiguous or c_contiguous. We include them in the descriptor output
9062 - // to provide some hint as to why a TypeError is occurring (otherwise it can be confusing to
9063 - // see that a function accepts a 'numpy.ndarray[float64[3,2]]' and an error message that you
9064 - // *gave* a numpy.ndarray of the right type and dimensions.
9065 - _<show_writeable>(", flags.writeable", "") +
9066 - _<show_c_contiguous>(", flags.c_contiguous", "") +
9067 - _<show_f_contiguous>(", flags.f_contiguous", "") +
9069 + static constexpr auto descriptor
9070 + = const_name("numpy.ndarray[") + npy_format_descriptor<Scalar>::name + const_name("[")
9071 + + const_name<fixed_rows>(const_name<(size_t) rows>(), const_name("m")) + const_name(", ")
9072 + + const_name<fixed_cols>(const_name<(size_t) cols>(), const_name("n")) + const_name("]")
9074 + // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to
9075 + // be satisfied: writeable=True (for a mutable reference), and, depending on the map's
9076 + // stride options, possibly f_contiguous or c_contiguous. We include them in the
9077 + // descriptor output to provide some hint as to why a TypeError is occurring (otherwise
9078 + // it can be confusing to see that a function accepts a 'numpy.ndarray[float64[3,2]]' and
9079 + // an error message that you *gave* a numpy.ndarray of the right type and dimensions.
9080 + const_name<show_writeable>(", flags.writeable", "")
9081 + + const_name<show_c_contiguous>(", flags.c_contiguous", "")
9082 + + const_name<show_f_contiguous>(", flags.f_contiguous", "") + const_name("]");
9085 // Casts an Eigen type to numpy array. If given a base, the numpy array references the src data,
9086 // otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array.
9087 -template <typename props> handle eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
9088 +template <typename props>
9090 +eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
9091 constexpr ssize_t elem_size = sizeof(typename props::Scalar);
9093 - if (props::vector)
9094 - a = array({ src.size() }, { elem_size * src.innerStride() }, src.data(), base);
9096 - a = array({ src.rows(), src.cols() }, { elem_size * src.rowStride(), elem_size * src.colStride() },
9097 - src.data(), base);
9098 + if (props::vector) {
9099 + a = array({src.size()}, {elem_size * src.innerStride()}, src.data(), base);
9101 + a = array({src.rows(), src.cols()},
9102 + {elem_size * src.rowStride(), elem_size * src.colStride()},
9109 array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
9114 @@ -236,10 +271,10 @@
9115 return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value);
9118 -// Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a numpy
9119 -// array that references the encapsulated data with a python-side reference to the capsule to tie
9120 -// its destruction to that of any dependent python objects. Const-ness is determined by whether or
9121 -// not the Type of the pointer given is const.
9122 +// Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a
9123 +// numpy array that references the encapsulated data with a python-side reference to the capsule to
9124 +// tie its destruction to that of any dependent python objects. Const-ness is determined by
9125 +// whether or not the Type of the pointer given is const.
9126 template <typename props, typename Type, typename = enable_if_t<is_eigen_dense_plain<Type>::value>>
9127 handle eigen_encapsulate(Type *src) {
9128 capsule base(src, [](void *o) { delete static_cast<Type *>(o); });
9129 @@ -248,35 +283,42 @@
9131 // Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense
9133 -template<typename Type>
9134 +template <typename Type>
9135 struct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> {
9136 using Scalar = typename Type::Scalar;
9137 using props = EigenProps<Type>;
9139 bool load(handle src, bool convert) {
9140 // If we're in no-convert mode, only load if given an array of the correct type
9141 - if (!convert && !isinstance<array_t<Scalar>>(src))
9142 + if (!convert && !isinstance<array_t<Scalar>>(src)) {
9146 // Coerce into an array, but don't do type conversion yet; the copy below handles it.
9147 auto buf = array::ensure(src);
9154 auto dims = buf.ndim();
9155 - if (dims < 1 || dims > 2)
9156 + if (dims < 1 || dims > 2) {
9160 auto fits = props::conformable(buf);
9166 // Allocate the new type, then build a numpy reference into it
9167 value = Type(fits.rows, fits.cols);
9168 auto ref = reinterpret_steal<array>(eigen_ref_array<props>(value));
9169 - if (dims == 1) ref = ref.squeeze();
9170 - else if (ref.ndim() == 1) buf = buf.squeeze();
9172 + ref = ref.squeeze();
9173 + } else if (ref.ndim() == 1) {
9174 + buf = buf.squeeze();
9177 int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr());
9184 // Cast implementation
9185 template <typename CType>
9186 static handle cast_impl(CType *src, return_value_policy policy, handle parent) {
9192 // Normal returned non-reference, non-const value:
9193 static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {
9194 return cast_impl(&src, return_value_policy::move, parent);
9195 @@ -323,14 +363,18 @@
9197 // lvalue reference return; default (automatic) becomes copy
9198 static handle cast(Type &src, return_value_policy policy, handle parent) {
9199 - if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
9200 + if (policy == return_value_policy::automatic
9201 + || policy == return_value_policy::automatic_reference) {
9202 policy = return_value_policy::copy;
9204 return cast_impl(&src, policy, parent);
9206 // const lvalue reference return; default (automatic) becomes copy
9207 static handle cast(const Type &src, return_value_policy policy, handle parent) {
9208 - if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
9209 + if (policy == return_value_policy::automatic
9210 + || policy == return_value_policy::automatic_reference) {
9211 policy = return_value_policy::copy;
9213 return cast(&src, policy, parent);
9215 // non-const pointer return
9216 @@ -344,28 +388,32 @@
9218 static constexpr auto name = props::descriptor;
9220 - operator Type*() { return &value; }
9221 - operator Type&() { return value; }
9222 - operator Type&&() && { return std::move(value); }
9223 - template <typename T> using cast_op_type = movable_cast_op_type<T>;
9224 + // NOLINTNEXTLINE(google-explicit-constructor)
9225 + operator Type *() { return &value; }
9226 + // NOLINTNEXTLINE(google-explicit-constructor)
9227 + operator Type &() { return value; }
9228 + // NOLINTNEXTLINE(google-explicit-constructor)
9229 + operator Type &&() && { return std::move(value); }
9230 + template <typename T>
9231 + using cast_op_type = movable_cast_op_type<T>;
9237 // Base class for casting reference/map/block/etc. objects back to python.
9238 -template <typename MapType> struct eigen_map_caster {
9239 +template <typename MapType>
9240 +struct eigen_map_caster {
9242 using props = EigenProps<MapType>;
9246 // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has
9247 - // to stay around), but we'll allow it under the assumption that you know what you're doing (and
9248 - // have an appropriate keep_alive in place). We return a numpy array pointing directly at the
9249 - // ref's data (The numpy array ends up read-only if the ref was to a const matrix type.) Note
9250 - // that this means you need to ensure you don't destroy the object in some other way (e.g. with
9251 - // an appropriate keep_alive, or with a reference to a statically allocated matrix).
9252 + // to stay around), but we'll allow it under the assumption that you know what you're doing
9253 + // (and have an appropriate keep_alive in place). We return a numpy array pointing directly at
9254 + // the ref's data (The numpy array ends up read-only if the ref was to a const matrix type.)
9255 + // Note that this means you need to ensure you don't destroy the object in some other way (e.g.
9256 + // with an appropriate keep_alive, or with a reference to a statically allocated matrix).
9257 static handle cast(const MapType &src, return_value_policy policy, handle parent) {
9259 case return_value_policy::copy:
9260 @@ -389,60 +437,69 @@
9261 // you end up here if you try anyway.
9262 bool load(handle, bool) = delete;
9263 operator MapType() = delete;
9264 - template <typename> using cast_op_type = MapType;
9265 + template <typename>
9266 + using cast_op_type = MapType;
9269 // We can return any map-like object (but can only load Refs, specialized next):
9270 -template <typename Type> struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>>
9271 - : eigen_map_caster<Type> {};
9272 +template <typename Type>
9273 +struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>> : eigen_map_caster<Type> {};
9275 // Loader for Ref<...> arguments. See the documentation for info on how to make this work without
9276 // copying (it requires some extra effort in many cases).
9277 template <typename PlainObjectType, typename StrideType>
9279 Eigen::Ref<PlainObjectType, 0, StrideType>,
9280 - enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value>
9281 -> : public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> {
9282 + enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value>>
9283 + : public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> {
9285 using Type = Eigen::Ref<PlainObjectType, 0, StrideType>;
9286 using props = EigenProps<Type>;
9287 using Scalar = typename props::Scalar;
9288 using MapType = Eigen::Map<PlainObjectType, 0, StrideType>;
9289 - using Array = array_t<Scalar, array::forcecast |
9290 - ((props::row_major ? props::inner_stride : props::outer_stride) == 1 ? array::c_style :
9291 - (props::row_major ? props::outer_stride : props::inner_stride) == 1 ? array::f_style : 0)>;
9295 + | ((props::row_major ? props::inner_stride : props::outer_stride) == 1
9297 + : (props::row_major ? props::outer_stride : props::inner_stride) == 1
9300 static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value;
9301 // Delay construction (these have no default constructor)
9302 std::unique_ptr<MapType> map;
9303 std::unique_ptr<Type> ref;
9304 // Our array. When possible, this is just a numpy array pointing to the source data, but
9305 - // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an incompatible
9306 - // layout, or is an array of a type that needs to be converted). Using a numpy temporary
9307 - // (rather than an Eigen temporary) saves an extra copy when we need both type conversion and
9308 - // storage order conversion. (Note that we refuse to use this temporary copy when loading an
9309 - // argument for a Ref<M> with M non-const, i.e. a read-write reference).
9310 + // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an
9311 + // incompatible layout, or is an array of a type that needs to be converted). Using a numpy
9312 + // temporary (rather than an Eigen temporary) saves an extra copy when we need both type
9313 + // conversion and storage order conversion. (Note that we refuse to use this temporary copy
9314 + // when loading an argument for a Ref<M> with M non-const, i.e. a read-write reference).
9318 bool load(handle src, bool convert) {
9319 - // First check whether what we have is already an array of the right type. If not, we can't
9320 - // avoid a copy (because the copy is also going to do type conversion).
9321 + // First check whether what we have is already an array of the right type. If not, we
9322 + // can't avoid a copy (because the copy is also going to do type conversion).
9323 bool need_copy = !isinstance<Array>(src);
9325 EigenConformable<props::row_major> fits;
9327 // We don't need a converting copy, but we also need to check whether the strides are
9328 // compatible with the Ref's stride requirements
9329 - Array aref = reinterpret_borrow<Array>(src);
9330 + auto aref = reinterpret_borrow<Array>(src);
9332 if (aref && (!need_writeable || aref.writeable())) {
9333 fits = props::conformable(aref);
9334 - if (!fits) return false; // Incompatible dimensions
9335 - if (!fits.template stride_compatible<props>())
9337 + return false; // Incompatible dimensions
9339 + if (!fits.template stride_compatible<props>()) {
9343 copy_or_ref = std::move(aref);
9351 @@ -451,64 +508,93 @@
9352 // We need to copy: If we need a mutable reference, or we're not supposed to convert
9353 // (either because we're in the no-convert overload pass, or because we're explicitly
9354 // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.
9355 - if (!convert || need_writeable) return false;
9356 + if (!convert || need_writeable) {
9360 Array copy = Array::ensure(src);
9361 - if (!copy) return false;
9365 fits = props::conformable(copy);
9366 - if (!fits || !fits.template stride_compatible<props>())
9367 + if (!fits || !fits.template stride_compatible<props>()) {
9370 copy_or_ref = std::move(copy);
9371 loader_life_support::add_patient(copy_or_ref);
9375 - map.reset(new MapType(data(copy_or_ref), fits.rows, fits.cols, make_stride(fits.stride.outer(), fits.stride.inner())));
9376 + map.reset(new MapType(data(copy_or_ref),
9379 + make_stride(fits.stride.outer(), fits.stride.inner())));
9380 ref.reset(new Type(*map));
9385 - operator Type*() { return ref.get(); }
9386 - operator Type&() { return *ref; }
9387 - template <typename _T> using cast_op_type = pybind11::detail::cast_op_type<_T>;
9388 + // NOLINTNEXTLINE(google-explicit-constructor)
9389 + operator Type *() { return ref.get(); }
9390 + // NOLINTNEXTLINE(google-explicit-constructor)
9391 + operator Type &() { return *ref; }
9392 + template <typename _T>
9393 + using cast_op_type = pybind11::detail::cast_op_type<_T>;
9396 template <typename T = Type, enable_if_t<is_eigen_mutable_map<T>::value, int> = 0>
9397 - Scalar *data(Array &a) { return a.mutable_data(); }
9398 + Scalar *data(Array &a) {
9399 + return a.mutable_data();
9402 template <typename T = Type, enable_if_t<!is_eigen_mutable_map<T>::value, int> = 0>
9403 - const Scalar *data(Array &a) { return a.data(); }
9404 + const Scalar *data(Array &a) {
9408 // Attempt to figure out a constructor of `Stride` that will work.
9409 // If both strides are fixed, use a default constructor:
9410 - template <typename S> using stride_ctor_default = bool_constant<
9411 - S::InnerStrideAtCompileTime != Eigen::Dynamic && S::OuterStrideAtCompileTime != Eigen::Dynamic &&
9412 - std::is_default_constructible<S>::value>;
9413 + template <typename S>
9414 + using stride_ctor_default = bool_constant<S::InnerStrideAtCompileTime != Eigen::Dynamic
9415 + && S::OuterStrideAtCompileTime != Eigen::Dynamic
9416 + && std::is_default_constructible<S>::value>;
9417 // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like
9418 // Eigen::Stride, and use it:
9419 - template <typename S> using stride_ctor_dual = bool_constant<
9420 - !stride_ctor_default<S>::value && std::is_constructible<S, EigenIndex, EigenIndex>::value>;
9421 + template <typename S>
9422 + using stride_ctor_dual
9423 + = bool_constant<!stride_ctor_default<S>::value
9424 + && std::is_constructible<S, EigenIndex, EigenIndex>::value>;
9425 // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use
9426 // it (passing whichever stride is dynamic).
9427 - template <typename S> using stride_ctor_outer = bool_constant<
9428 - !any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value &&
9429 - S::OuterStrideAtCompileTime == Eigen::Dynamic && S::InnerStrideAtCompileTime != Eigen::Dynamic &&
9430 - std::is_constructible<S, EigenIndex>::value>;
9431 - template <typename S> using stride_ctor_inner = bool_constant<
9432 - !any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value &&
9433 - S::InnerStrideAtCompileTime == Eigen::Dynamic && S::OuterStrideAtCompileTime != Eigen::Dynamic &&
9434 - std::is_constructible<S, EigenIndex>::value>;
9435 + template <typename S>
9436 + using stride_ctor_outer
9437 + = bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
9438 + && S::OuterStrideAtCompileTime == Eigen::Dynamic
9439 + && S::InnerStrideAtCompileTime != Eigen::Dynamic
9440 + && std::is_constructible<S, EigenIndex>::value>;
9441 + template <typename S>
9442 + using stride_ctor_inner
9443 + = bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
9444 + && S::InnerStrideAtCompileTime == Eigen::Dynamic
9445 + && S::OuterStrideAtCompileTime != Eigen::Dynamic
9446 + && std::is_constructible<S, EigenIndex>::value>;
9448 template <typename S = StrideType, enable_if_t<stride_ctor_default<S>::value, int> = 0>
9449 - static S make_stride(EigenIndex, EigenIndex) { return S(); }
9450 + static S make_stride(EigenIndex, EigenIndex) {
9453 template <typename S = StrideType, enable_if_t<stride_ctor_dual<S>::value, int> = 0>
9454 - static S make_stride(EigenIndex outer, EigenIndex inner) { return S(outer, inner); }
9455 + static S make_stride(EigenIndex outer, EigenIndex inner) {
9456 + return S(outer, inner);
9458 template <typename S = StrideType, enable_if_t<stride_ctor_outer<S>::value, int> = 0>
9459 - static S make_stride(EigenIndex outer, EigenIndex) { return S(outer); }
9460 + static S make_stride(EigenIndex outer, EigenIndex) {
9463 template <typename S = StrideType, enable_if_t<stride_ctor_inner<S>::value, int> = 0>
9464 - static S make_stride(EigenIndex, EigenIndex inner) { return S(inner); }
9466 + static S make_stride(EigenIndex, EigenIndex inner) {
9471 // type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not
9472 @@ -518,14 +604,18 @@
9473 template <typename Type>
9474 struct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> {
9476 - using Matrix = Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>;
9478 + = Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>;
9479 using props = EigenProps<Matrix>;
9482 static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
9483 handle h = eigen_encapsulate<props>(new Matrix(src));
9486 - static handle cast(const Type *src, return_value_policy policy, handle parent) { return cast(*src, policy, parent); }
9487 + static handle cast(const Type *src, return_value_policy policy, handle parent) {
9488 + return cast(*src, policy, parent);
9491 static constexpr auto name = props::descriptor;
9493 @@ -534,26 +624,27 @@
9494 // you end up here if you try anyway.
9495 bool load(handle, bool) = delete;
9496 operator Type() = delete;
9497 - template <typename> using cast_op_type = Type;
9498 + template <typename>
9499 + using cast_op_type = Type;
9502 -template<typename Type>
9503 +template <typename Type>
9504 struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {
9505 - typedef typename Type::Scalar Scalar;
9506 - typedef remove_reference_t<decltype(*std::declval<Type>().outerIndexPtr())> StorageIndex;
9507 - typedef typename Type::Index Index;
9508 + using Scalar = typename Type::Scalar;
9509 + using StorageIndex = remove_reference_t<decltype(*std::declval<Type>().outerIndexPtr())>;
9510 + using Index = typename Type::Index;
9511 static constexpr bool rowMajor = Type::IsRowMajor;
9513 bool load(handle src, bool) {
9519 auto obj = reinterpret_borrow<object>(src);
9520 - object sparse_module = module::import("scipy.sparse");
9521 - object matrix_type = sparse_module.attr(
9522 - rowMajor ? "csr_matrix" : "csc_matrix");
9523 + object sparse_module = module_::import("scipy.sparse");
9524 + object matrix_type = sparse_module.attr(rowMajor ? "csr_matrix" : "csc_matrix");
9526 - if (!obj.get_type().is(matrix_type)) {
9527 + if (!type::handle_of(obj).is(matrix_type)) {
9529 obj = matrix_type(obj);
9530 } catch (const error_already_set &) {
9531 @@ -567,41 +658,42 @@
9532 auto shape = pybind11::tuple((pybind11::object) obj.attr("shape"));
9533 auto nnz = obj.attr("nnz").cast<Index>();
9535 - if (!values || !innerIndices || !outerIndices)
9536 + if (!values || !innerIndices || !outerIndices) {
9540 - value = Eigen::MappedSparseMatrix<Scalar, Type::Flags, StorageIndex>(
9541 - shape[0].cast<Index>(), shape[1].cast<Index>(), nnz,
9542 - outerIndices.mutable_data(), innerIndices.mutable_data(), values.mutable_data());
9543 + value = EigenMapSparseMatrix<Scalar,
9544 + Type::Flags &(Eigen::RowMajor | Eigen::ColMajor),
9545 + StorageIndex>(shape[0].cast<Index>(),
9546 + shape[1].cast<Index>(),
9548 + outerIndices.mutable_data(),
9549 + innerIndices.mutable_data(),
9550 + values.mutable_data());
9555 static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
9556 - const_cast<Type&>(src).makeCompressed();
9557 + const_cast<Type &>(src).makeCompressed();
9559 - object matrix_type = module::import("scipy.sparse").attr(
9560 - rowMajor ? "csr_matrix" : "csc_matrix");
9561 + object matrix_type
9562 + = module_::import("scipy.sparse").attr(rowMajor ? "csr_matrix" : "csc_matrix");
9564 array data(src.nonZeros(), src.valuePtr());
9565 array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());
9566 array innerIndices(src.nonZeros(), src.innerIndexPtr());
9568 - return matrix_type(
9569 - std::make_tuple(data, innerIndices, outerIndices),
9570 - std::make_pair(src.rows(), src.cols())
9572 + return matrix_type(std::make_tuple(data, innerIndices, outerIndices),
9573 + std::make_pair(src.rows(), src.cols()))
9577 - PYBIND11_TYPE_CASTER(Type, _<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[", "scipy.sparse.csc_matrix[")
9578 - + npy_format_descriptor<Scalar>::name + _("]"));
9579 + PYBIND11_TYPE_CASTER(Type,
9580 + const_name<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[",
9581 + "scipy.sparse.csc_matrix[")
9582 + + npy_format_descriptor<Scalar>::name + const_name("]"));
9585 -NAMESPACE_END(detail)
9586 -NAMESPACE_END(PYBIND11_NAMESPACE)
9588 -#if defined(__GNUG__) || defined(__clang__)
9589 -# pragma GCC diagnostic pop
9590 -#elif defined(_MSC_VER)
9591 -# pragma warning(pop)
9593 +PYBIND11_NAMESPACE_END(detail)
9594 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
9595 diff -Nur pythia8309.orig/plugins/python/include/pybind11/embed.h pythia8309/plugins/python/include/pybind11/embed.h
9596 --- pythia8309.orig/plugins/python/include/pybind11/embed.h 2023-02-16 18:12:45.000000000 +0100
9597 +++ pythia8309/plugins/python/include/pybind11/embed.h 2023-03-13 09:52:25.461021606 +0100
9599 #include "pybind11.h"
9605 #if defined(PYPY_VERSION)
9606 -# error Embedding the interpreter is not supported with PyPy
9607 +# error Embedding the interpreter is not supported with PyPy
9610 #if PY_MAJOR_VERSION >= 3
9611 -# define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
9612 - extern "C" PyObject *pybind11_init_impl_##name() { \
9613 - return pybind11_init_wrapper_##name(); \
9615 +# define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
9616 + extern "C" PyObject *pybind11_init_impl_##name(); \
9617 + extern "C" PyObject *pybind11_init_impl_##name() { return pybind11_init_wrapper_##name(); }
9619 -# define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
9620 - extern "C" void pybind11_init_impl_##name() { \
9621 - pybind11_init_wrapper_##name(); \
9623 +# define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
9624 + extern "C" void pybind11_init_impl_##name(); \
9625 + extern "C" void pybind11_init_impl_##name() { pybind11_init_wrapper_##name(); }
9629 @@ -43,70 +44,160 @@
9633 -#define PYBIND11_EMBEDDED_MODULE(name, variable) \
9634 - static void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &); \
9635 - static PyObject PYBIND11_CONCAT(*pybind11_init_wrapper_, name)() { \
9636 - auto m = pybind11::module(PYBIND11_TOSTRING(name)); \
9638 - PYBIND11_CONCAT(pybind11_init_, name)(m); \
9640 - } catch (pybind11::error_already_set &e) { \
9641 - PyErr_SetString(PyExc_ImportError, e.what()); \
9643 - } catch (const std::exception &e) { \
9644 - PyErr_SetString(PyExc_ImportError, e.what()); \
9648 - PYBIND11_EMBEDDED_MODULE_IMPL(name) \
9649 - pybind11::detail::embedded_module name(PYBIND11_TOSTRING(name), \
9650 - PYBIND11_CONCAT(pybind11_init_impl_, name)); \
9651 - void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &variable)
9653 +#define PYBIND11_EMBEDDED_MODULE(name, variable) \
9654 + static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name); \
9655 + static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
9656 + static PyObject PYBIND11_CONCAT(*pybind11_init_wrapper_, name)() { \
9657 + auto m = ::pybind11::module_::create_extension_module( \
9658 + PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \
9660 + PYBIND11_CONCAT(pybind11_init_, name)(m); \
9663 + PYBIND11_CATCH_INIT_EXCEPTIONS \
9665 + PYBIND11_EMBEDDED_MODULE_IMPL(name) \
9666 + ::pybind11::detail::embedded_module PYBIND11_CONCAT(pybind11_module_, name)( \
9667 + PYBIND11_TOSTRING(name), PYBIND11_CONCAT(pybind11_init_impl_, name)); \
9668 + void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ \
9669 + & variable) // NOLINT(bugprone-macro-parentheses)
9671 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
9672 -NAMESPACE_BEGIN(detail)
9673 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
9674 +PYBIND11_NAMESPACE_BEGIN(detail)
9676 /// Python 2.7/3.x compatible version of `PyImport_AppendInittab` and error checks.
9677 struct embedded_module {
9678 #if PY_MAJOR_VERSION >= 3
9679 - using init_t = PyObject *(*)();
9680 + using init_t = PyObject *(*) ();
9682 using init_t = void (*)();
9684 embedded_module(const char *name, init_t init) {
9685 - if (Py_IsInitialized())
9686 + if (Py_IsInitialized() != 0) {
9687 pybind11_fail("Can't add new modules after the interpreter has been initialized");
9690 auto result = PyImport_AppendInittab(name, init);
9692 + if (result == -1) {
9693 pybind11_fail("Insufficient memory to add a new module");
9698 -NAMESPACE_END(detail)
9699 +struct wide_char_arg_deleter {
9700 + void operator()(wchar_t *ptr) const {
9701 +#if PY_VERSION_HEX >= 0x030500f0
9702 + // API docs: https://docs.python.org/3/c-api/sys.html#c.Py_DecodeLocale
9703 + PyMem_RawFree(ptr);
9710 +inline wchar_t *widen_chars(const char *safe_arg) {
9711 +#if PY_VERSION_HEX >= 0x030500f0
9712 + wchar_t *widened_arg = Py_DecodeLocale(safe_arg, nullptr);
9714 + wchar_t *widened_arg = nullptr;
9716 +// warning C4996: 'mbstowcs': This function or variable may be unsafe.
9717 +# if defined(_MSC_VER)
9718 +# pragma warning(push)
9719 +# pragma warning(disable : 4996)
9722 +# if defined(HAVE_BROKEN_MBSTOWCS) && HAVE_BROKEN_MBSTOWCS
9723 + size_t count = std::strlen(safe_arg);
9725 + size_t count = std::mbstowcs(nullptr, safe_arg, 0);
9727 + if (count != static_cast<size_t>(-1)) {
9728 + widened_arg = new wchar_t[count + 1];
9729 + std::mbstowcs(widened_arg, safe_arg, count + 1);
9732 +# if defined(_MSC_VER)
9733 +# pragma warning(pop)
9737 + return widened_arg;
9740 +/// Python 2.x/3.x-compatible version of `PySys_SetArgv`
9741 +inline void set_interpreter_argv(int argc, const char *const *argv, bool add_program_dir_to_path) {
9742 + // Before it was special-cased in python 3.8, passing an empty or null argv
9743 + // caused a segfault, so we have to reimplement the special case ourselves.
9744 + bool special_case = (argv == nullptr || argc <= 0);
9746 + const char *const empty_argv[]{"\0"};
9747 + const char *const *safe_argv = special_case ? empty_argv : argv;
9748 + if (special_case) {
9752 + auto argv_size = static_cast<size_t>(argc);
9753 +#if PY_MAJOR_VERSION >= 3
9754 + // SetArgv* on python 3 takes wchar_t, so we have to convert.
9755 + std::unique_ptr<wchar_t *[]> widened_argv(new wchar_t *[argv_size]);
9756 + std::vector<std::unique_ptr<wchar_t[], wide_char_arg_deleter>> widened_argv_entries;
9757 + widened_argv_entries.reserve(argv_size);
9758 + for (size_t ii = 0; ii < argv_size; ++ii) {
9759 + widened_argv_entries.emplace_back(widen_chars(safe_argv[ii]));
9760 + if (!widened_argv_entries.back()) {
9761 + // A null here indicates a character-encoding failure or the python
9762 + // interpreter out of memory. Give up.
9765 + widened_argv[ii] = widened_argv_entries.back().get();
9768 + auto *pysys_argv = widened_argv.get();
9771 + std::vector<std::string> strings{safe_argv, safe_argv + argv_size};
9772 + std::vector<char *> char_strings{argv_size};
9773 + for (std::size_t i = 0; i < argv_size; ++i)
9774 + char_strings[i] = &strings[i][0];
9775 + char **pysys_argv = char_strings.data();
9778 + PySys_SetArgvEx(argc, pysys_argv, static_cast<int>(add_program_dir_to_path));
9781 +PYBIND11_NAMESPACE_END(detail)
9784 Initialize the Python interpreter. No other pybind11 or CPython API functions can be
9785 called before this is done; with the exception of `PYBIND11_EMBEDDED_MODULE`. The
9786 - optional parameter can be used to skip the registration of signal handlers (see the
9787 - `Python documentation`_ for details). Calling this function again after the interpreter
9788 - has already been initialized is a fatal error.
9789 + optional `init_signal_handlers` parameter can be used to skip the registration of
9790 + signal handlers (see the `Python documentation`_ for details). Calling this function
9791 + again after the interpreter has already been initialized is a fatal error.
9793 If initializing the Python interpreter fails, then the program is terminated. (This
9794 is controlled by the CPython runtime and is an exception to pybind11's normal behavior
9795 of throwing exceptions on errors.)
9797 + The remaining optional parameters, `argc`, `argv`, and `add_program_dir_to_path` are
9798 + used to populate ``sys.argv`` and ``sys.path``.
9799 + See the |PySys_SetArgvEx documentation|_ for details.
9801 .. _Python documentation: https://docs.python.org/3/c-api/init.html#c.Py_InitializeEx
9802 + .. |PySys_SetArgvEx documentation| replace:: ``PySys_SetArgvEx`` documentation
9803 + .. _PySys_SetArgvEx documentation: https://docs.python.org/3/c-api/init.html#c.PySys_SetArgvEx
9805 -inline void initialize_interpreter(bool init_signal_handlers = true) {
9806 - if (Py_IsInitialized())
9807 +inline void initialize_interpreter(bool init_signal_handlers = true,
9809 + const char *const *argv = nullptr,
9810 + bool add_program_dir_to_path = true) {
9811 + if (Py_IsInitialized() != 0) {
9812 pybind11_fail("The interpreter is already running");
9815 Py_InitializeEx(init_signal_handlers ? 1 : 0);
9817 - // Make .py files in the working directory available by default
9818 - module::import("sys").attr("path").cast<list>().append(".");
9819 + detail::set_interpreter_argv(argc, argv, add_program_dir_to_path);
9823 @@ -153,8 +244,13 @@
9824 // during destruction), so we get the pointer-pointer here and check it after Py_Finalize().
9825 detail::internals **internals_ptr_ptr = detail::get_internals_pp();
9826 // It could also be stashed in builtins, so look there too:
9827 - if (builtins.contains(id) && isinstance<capsule>(builtins[id]))
9828 + if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
9829 internals_ptr_ptr = capsule(builtins[id]);
9831 + // Local internals contains data managed by the current interpreter, so we must clear them to
9832 + // avoid undefined behaviors when initializing another interpreter
9833 + detail::get_local_internals().registered_types_cpp.clear();
9834 + detail::get_local_internals().registered_exception_translators.clear();
9839 Scope guard version of `initialize_interpreter` and `finalize_interpreter`.
9840 This a move-only guard and only a single instance can exist.
9842 + See `initialize_interpreter` for a discussion of its constructor arguments.
9846 #include <pybind11/embed.h>
9847 @@ -179,8 +277,11 @@
9849 class scoped_interpreter {
9851 - scoped_interpreter(bool init_signal_handlers = true) {
9852 - initialize_interpreter(init_signal_handlers);
9853 + explicit scoped_interpreter(bool init_signal_handlers = true,
9855 + const char *const *argv = nullptr,
9856 + bool add_program_dir_to_path = true) {
9857 + initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path);
9860 scoped_interpreter(const scoped_interpreter &) = delete;
9861 @@ -189,12 +290,13 @@
9862 scoped_interpreter &operator=(scoped_interpreter &&) = delete;
9864 ~scoped_interpreter() {
9867 finalize_interpreter();
9872 bool is_valid = true;
9875 -NAMESPACE_END(PYBIND11_NAMESPACE)
9876 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
9877 diff -Nur pythia8309.orig/plugins/python/include/pybind11/eval.h pythia8309/plugins/python/include/pybind11/eval.h
9878 --- pythia8309.orig/plugins/python/include/pybind11/eval.h 2023-02-16 18:12:45.000000000 +0100
9879 +++ pythia8309/plugins/python/include/pybind11/eval.h 2023-03-13 09:52:25.462021608 +0100
9882 - pybind11/exec.h: Support for evaluating Python expressions and statements
9883 + pybind11/eval.h: Support for evaluating Python expressions and statements
9884 from strings and files
9886 Copyright (c) 2016 Klemens Morgenstern <klemens.morgenstern@ed-chemnitz.de> and
9889 #include "pybind11.h"
9891 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
9894 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
9895 +PYBIND11_NAMESPACE_BEGIN(detail)
9897 +inline void ensure_builtins_in_globals(object &global) {
9898 +#if defined(PYPY_VERSION) || PY_VERSION_HEX < 0x03080000
9899 + // Running exec and eval on Python 2 and 3 adds `builtins` module under
9900 + // `__builtins__` key to globals if not yet present.
9901 + // Python 3.8 made PyRun_String behave similarly. Let's also do that for
9902 + // older versions, for consistency. This was missing from PyPy3.8 7.3.7.
9903 + if (!global.contains("__builtins__"))
9904 + global["__builtins__"] = module_::import(PYBIND11_BUILTINS_MODULE);
9910 +PYBIND11_NAMESPACE_END(detail)
9913 /// Evaluate a string containing an isolated expression
9914 @@ -27,91 +45,134 @@
9917 template <eval_mode mode = eval_expr>
9918 -object eval(str expr, object global = globals(), object local = object()) {
9920 +object eval(const str &expr, object global = globals(), object local = object()) {
9925 + detail::ensure_builtins_in_globals(global);
9927 /* PyRun_String does not accept a PyObject / encoding specifier,
9928 this seems to be the only alternative */
9929 std::string buffer = "# -*- coding: utf-8 -*-\n" + (std::string) expr;
9934 - case eval_expr: start = Py_eval_input; break;
9935 - case eval_single_statement: start = Py_single_input; break;
9936 - case eval_statements: start = Py_file_input; break;
9937 - default: pybind11_fail("invalid evaluation mode");
9939 + start = Py_eval_input;
9941 + case eval_single_statement:
9942 + start = Py_single_input;
9944 + case eval_statements:
9945 + start = Py_file_input;
9948 + pybind11_fail("invalid evaluation mode");
9951 PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr());
9954 throw error_already_set();
9956 return reinterpret_steal<object>(result);
9959 template <eval_mode mode = eval_expr, size_t N>
9960 object eval(const char (&s)[N], object global = globals(), object local = object()) {
9961 /* Support raw string literals by removing common leading whitespace */
9962 - auto expr = (s[0] == '\n') ? str(module::import("textwrap").attr("dedent")(s))
9964 - return eval<mode>(expr, global, local);
9965 + auto expr = (s[0] == '\n') ? str(module_::import("textwrap").attr("dedent")(s)) : str(s);
9966 + return eval<mode>(expr, std::move(global), std::move(local));
9969 -inline void exec(str expr, object global = globals(), object local = object()) {
9970 - eval<eval_statements>(expr, global, local);
9971 +inline void exec(const str &expr, object global = globals(), object local = object()) {
9972 + eval<eval_statements>(expr, std::move(global), std::move(local));
9976 void exec(const char (&s)[N], object global = globals(), object local = object()) {
9977 - eval<eval_statements>(s, global, local);
9978 + eval<eval_statements>(s, std::move(global), std::move(local));
9981 +#if defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x03000000
9982 +template <eval_mode mode = eval_statements>
9983 +object eval_file(str, object, object) {
9984 + pybind11_fail("eval_file not supported in PyPy3. Use eval");
9986 +template <eval_mode mode = eval_statements>
9987 +object eval_file(str, object) {
9988 + pybind11_fail("eval_file not supported in PyPy3. Use eval");
9990 +template <eval_mode mode = eval_statements>
9991 +object eval_file(str) {
9992 + pybind11_fail("eval_file not supported in PyPy3. Use eval");
9995 template <eval_mode mode = eval_statements>
9996 object eval_file(str fname, object global = globals(), object local = object()) {
10003 + detail::ensure_builtins_in_globals(global);
10007 - case eval_expr: start = Py_eval_input; break;
10008 - case eval_single_statement: start = Py_single_input; break;
10009 - case eval_statements: start = Py_file_input; break;
10010 - default: pybind11_fail("invalid evaluation mode");
10012 + start = Py_eval_input;
10014 + case eval_single_statement:
10015 + start = Py_single_input;
10017 + case eval_statements:
10018 + start = Py_file_input;
10021 + pybind11_fail("invalid evaluation mode");
10025 std::string fname_str = (std::string) fname;
10026 -#if PY_VERSION_HEX >= 0x03040000
10027 +# if PY_VERSION_HEX >= 0x03040000
10028 FILE *f = _Py_fopen_obj(fname.ptr(), "r");
10029 -#elif PY_VERSION_HEX >= 0x03000000
10030 +# elif PY_VERSION_HEX >= 0x03000000
10031 FILE *f = _Py_fopen(fname.ptr(), "r");
10034 /* No unicode support in open() :( */
10035 - auto fobj = reinterpret_steal<object>(PyFile_FromString(
10036 - const_cast<char *>(fname_str.c_str()),
10037 - const_cast<char*>("r")));
10038 + auto fobj = reinterpret_steal<object>(
10039 + PyFile_FromString(const_cast<char *>(fname_str.c_str()), const_cast<char *>("r")));
10042 f = PyFile_AsFile(fobj.ptr());
10048 pybind11_fail("File \"" + fname_str + "\" could not be opened!");
10051 -#if PY_VERSION_HEX < 0x03000000 && defined(PYPY_VERSION)
10052 - PyObject *result = PyRun_File(f, fname_str.c_str(), start, global.ptr(),
10054 + // In Python2, this should be encoded by getfilesystemencoding.
10055 + // We don't boher setting it since Python2 is past EOL anyway.
10057 +# if PY_VERSION_HEX >= 0x03000000
10058 + if (!global.contains("__file__")) {
10059 + global["__file__"] = std::move(fname);
10063 +# if PY_VERSION_HEX < 0x03000000 && defined(PYPY_VERSION)
10064 + PyObject *result = PyRun_File(f, fname_str.c_str(), start, global.ptr(), local.ptr());
10067 - PyObject *result = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(),
10068 - local.ptr(), closeFile);
10072 + = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(), local.ptr(), closeFile);
10077 throw error_already_set();
10079 return reinterpret_steal<object>(result);
10083 -NAMESPACE_END(PYBIND11_NAMESPACE)
10084 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
10085 diff -Nur pythia8309.orig/plugins/python/include/pybind11/functional.h pythia8309/plugins/python/include/pybind11/functional.h
10086 --- pythia8309.orig/plugins/python/include/pybind11/functional.h 2023-02-16 18:12:45.000000000 +0100
10087 +++ pythia8309/plugins/python/include/pybind11/functional.h 2023-03-13 09:52:25.462021608 +0100
10088 @@ -10,27 +10,31 @@
10091 #include "pybind11.h"
10093 #include <functional>
10095 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
10096 -NAMESPACE_BEGIN(detail)
10097 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
10098 +PYBIND11_NAMESPACE_BEGIN(detail)
10100 template <typename Return, typename... Args>
10101 struct type_caster<std::function<Return(Args...)>> {
10102 using type = std::function<Return(Args...)>;
10103 using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;
10104 - using function_type = Return (*) (Args...);
10105 + using function_type = Return (*)(Args...);
10108 bool load(handle src, bool convert) {
10109 if (src.is_none()) {
10110 // Defer accepting None to other overloads (if we aren't in convert mode):
10111 - if (!convert) return false;
10118 - if (!isinstance<function>(src))
10119 + if (!isinstance<function>(src)) {
10123 auto func = reinterpret_borrow<function>(src);
10125 @@ -43,41 +47,85 @@
10126 captured variables), in which case the roundtrip can be avoided.
10128 if (auto cfunc = func.cpp_function()) {
10129 - auto c = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(cfunc.ptr()));
10130 - auto rec = (function_record *) c;
10132 - if (rec && rec->is_stateless &&
10133 - same_type(typeid(function_type), *reinterpret_cast<const std::type_info *>(rec->data[1]))) {
10134 - struct capture { function_type f; };
10135 - value = ((capture *) &rec->data)->f;
10137 + auto *cfunc_self = PyCFunction_GET_SELF(cfunc.ptr());
10138 + if (isinstance<capsule>(cfunc_self)) {
10139 + auto c = reinterpret_borrow<capsule>(cfunc_self);
10140 + auto *rec = (function_record *) c;
10142 + while (rec != nullptr) {
10143 + if (rec->is_stateless
10144 + && same_type(typeid(function_type),
10145 + *reinterpret_cast<const std::type_info *>(rec->data[1]))) {
10149 + value = ((capture *) &rec->data)->f;
10155 + // PYPY segfaults here when passing builtin function like sum.
10156 + // Raising an fail exception here works to prevent the segfault, but only on gcc.
10157 + // See PR #1413 for full details
10160 - value = [func](Args... args) -> Return {
10161 - gil_scoped_acquire acq;
10162 - object retval(func(std::forward<Args>(args)...));
10163 - /* Visual studio 2015 parser issue: need parentheses around this expression */
10164 - return (retval.template cast<Return>());
10165 + // ensure GIL is held during functor destruction
10166 + struct func_handle {
10168 +#if !(defined(_MSC_VER) && _MSC_VER == 1916 && defined(PYBIND11_CPP17))
10169 + // This triggers a syntax error under very special conditions (very weird indeed).
10172 + func_handle(function &&f_) noexcept
10173 + : f(std::move(f_)) {
10175 + func_handle(const func_handle &f_) { operator=(f_); }
10176 + func_handle &operator=(const func_handle &f_) {
10177 + gil_scoped_acquire acq;
10182 + gil_scoped_acquire acq;
10183 + function kill_f(std::move(f));
10187 + // to emulate 'move initialization capture' in C++11
10188 + struct func_wrapper {
10189 + func_handle hfunc;
10190 + explicit func_wrapper(func_handle &&hf) noexcept : hfunc(std::move(hf)) {}
10191 + Return operator()(Args... args) const {
10192 + gil_scoped_acquire acq;
10193 + object retval(hfunc.f(std::forward<Args>(args)...));
10194 + /* Visual studio 2015 parser issue: need parentheses around this expression */
10195 + return (retval.template cast<Return>());
10199 + value = func_wrapper(func_handle(std::move(func)));
10203 template <typename Func>
10204 static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) {
10207 return none().inc_ref();
10210 auto result = f_.template target<function_type>();
10213 return cpp_function(*result, policy).release();
10215 - return cpp_function(std::forward<Func>(f_), policy).release();
10217 + return cpp_function(std::forward<Func>(f_), policy).release();
10220 - PYBIND11_TYPE_CASTER(type, _("Callable[[") + concat(make_caster<Args>::name...) + _("], ")
10221 - + make_caster<retval_type>::name + _("]"));
10222 + PYBIND11_TYPE_CASTER(type,
10223 + const_name("Callable[[") + concat(make_caster<Args>::name...)
10224 + + const_name("], ") + make_caster<retval_type>::name
10225 + + const_name("]"));
10228 -NAMESPACE_END(detail)
10229 -NAMESPACE_END(PYBIND11_NAMESPACE)
10230 +PYBIND11_NAMESPACE_END(detail)
10231 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
10232 diff -Nur pythia8309.orig/plugins/python/include/pybind11/gil.h pythia8309/plugins/python/include/pybind11/gil.h
10233 --- pythia8309.orig/plugins/python/include/pybind11/gil.h 1970-01-01 01:00:00.000000000 +0100
10234 +++ pythia8309/plugins/python/include/pybind11/gil.h 2023-03-13 09:52:25.463021610 +0100
10237 + pybind11/gil.h: RAII helpers for managing the GIL
10239 + Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
10241 + All rights reserved. Use of this source code is governed by a
10242 + BSD-style license that can be found in the LICENSE file.
10247 +#include "detail/common.h"
10248 +#include "detail/internals.h"
10250 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
10252 +PYBIND11_NAMESPACE_BEGIN(detail)
10254 +// forward declarations
10255 +PyThreadState *get_thread_state_unchecked();
10257 +PYBIND11_NAMESPACE_END(detail)
10259 +#if defined(WITH_THREAD) && !defined(PYPY_VERSION)
10261 +/* The functions below essentially reproduce the PyGILState_* API using a RAII
10262 + * pattern, but there are a few important differences:
10264 + * 1. When acquiring the GIL from an non-main thread during the finalization
10265 + * phase, the GILState API blindly terminates the calling thread, which
10266 + * is often not what is wanted. This API does not do this.
10268 + * 2. The gil_scoped_release function can optionally cut the relationship
10269 + * of a PyThreadState and its associated thread, which allows moving it to
10270 + * another thread (this is a fairly rare/advanced use case).
10272 + * 3. The reference count of an acquired thread state can be controlled. This
10273 + * can be handy to prevent cases where callbacks issued from an external
10274 + * thread would otherwise constantly construct and destroy thread state data
10277 + * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
10278 + * example which uses features 2 and 3 to migrate the Python thread of
10279 + * execution to another thread (to run the event loop on the original thread,
10283 +class gil_scoped_acquire {
10285 + PYBIND11_NOINLINE gil_scoped_acquire() {
10286 + auto &internals = detail::get_internals();
10287 + tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
10290 + /* Check if the GIL was acquired using the PyGILState_* API instead (e.g. if
10291 + calling from a Python thread). Since we use a different key, this ensures
10292 + we don't create a new thread state and deadlock in PyEval_AcquireThread
10293 + below. Note we don't save this state with internals.tstate, since we don't
10294 + create it we would fail to clear it (its reference count should be > 0). */
10295 + tstate = PyGILState_GetThisThreadState();
10299 + tstate = PyThreadState_New(internals.istate);
10300 +# if !defined(NDEBUG)
10302 + pybind11_fail("scoped_acquire: could not create thread state!");
10305 + tstate->gilstate_counter = 0;
10306 + PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
10308 + release = detail::get_thread_state_unchecked() != tstate;
10312 + PyEval_AcquireThread(tstate);
10318 + void inc_ref() { ++tstate->gilstate_counter; }
10320 + PYBIND11_NOINLINE void dec_ref() {
10321 + --tstate->gilstate_counter;
10322 +# if !defined(NDEBUG)
10323 + if (detail::get_thread_state_unchecked() != tstate) {
10324 + pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
10326 + if (tstate->gilstate_counter < 0) {
10327 + pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
10330 + if (tstate->gilstate_counter == 0) {
10331 +# if !defined(NDEBUG)
10333 + pybind11_fail("scoped_acquire::dec_ref(): internal error!");
10336 + PyThreadState_Clear(tstate);
10338 + PyThreadState_DeleteCurrent();
10340 + PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
10345 + /// This method will disable the PyThreadState_DeleteCurrent call and the
10346 + /// GIL won't be acquired. This method should be used if the interpreter
10347 + /// could be shutting down when this is called, as thread deletion is not
10348 + /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and
10349 + /// protect subsequent code.
10350 + PYBIND11_NOINLINE void disarm() { active = false; }
10352 + PYBIND11_NOINLINE ~gil_scoped_acquire() {
10355 + PyEval_SaveThread();
10360 + PyThreadState *tstate = nullptr;
10361 + bool release = true;
10362 + bool active = true;
10365 +class gil_scoped_release {
10367 + explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
10368 + // `get_internals()` must be called here unconditionally in order to initialize
10369 + // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
10370 + // initialization race could occur as multiple threads try `gil_scoped_acquire`.
10371 + auto &internals = detail::get_internals();
10372 + // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
10373 + tstate = PyEval_SaveThread();
10375 + // Python >= 3.7 can remove this, it's an int before 3.7
10376 + // NOLINTNEXTLINE(readability-qualified-auto)
10377 + auto key = internals.tstate;
10378 + PYBIND11_TLS_DELETE_VALUE(key);
10382 + /// This method will disable the PyThreadState_DeleteCurrent call and the
10383 + /// GIL won't be acquired. This method should be used if the interpreter
10384 + /// could be shutting down when this is called, as thread deletion is not
10385 + /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and
10386 + /// protect subsequent code.
10387 + PYBIND11_NOINLINE void disarm() { active = false; }
10389 + ~gil_scoped_release() {
10393 + // `PyEval_RestoreThread()` should not be called if runtime is finalizing
10395 + PyEval_RestoreThread(tstate);
10398 + // Python >= 3.7 can remove this, it's an int before 3.7
10399 + // NOLINTNEXTLINE(readability-qualified-auto)
10400 + auto key = detail::get_internals().tstate;
10401 + PYBIND11_TLS_REPLACE_VALUE(key, tstate);
10406 + PyThreadState *tstate;
10408 + bool active = true;
10410 +#elif defined(PYPY_VERSION)
10411 +class gil_scoped_acquire {
10412 + PyGILState_STATE state;
10415 + gil_scoped_acquire() { state = PyGILState_Ensure(); }
10416 + ~gil_scoped_acquire() { PyGILState_Release(state); }
10420 +class gil_scoped_release {
10421 + PyThreadState *state;
10424 + gil_scoped_release() { state = PyEval_SaveThread(); }
10425 + ~gil_scoped_release() { PyEval_RestoreThread(state); }
10429 +class gil_scoped_acquire {
10432 +class gil_scoped_release {
10437 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
10438 diff -Nur pythia8309.orig/plugins/python/include/pybind11/iostream.h pythia8309/plugins/python/include/pybind11/iostream.h
10439 --- pythia8309.orig/plugins/python/include/pybind11/iostream.h 2023-02-16 18:12:45.000000000 +0100
10440 +++ pythia8309/plugins/python/include/pybind11/iostream.h 2023-03-13 09:52:25.463021610 +0100
10443 All rights reserved. Use of this source code is governed by a
10444 BSD-style license that can be found in the LICENSE file.
10446 + WARNING: The implementation in this file is NOT thread safe. Multiple
10447 + threads writing to a redirected ostream concurrently cause data races
10448 + and potentially buffer overflows. Therefore it is currently a requirement
10449 + that all (possibly) concurrent redirected ostream writes are protected by
10451 + #HelpAppreciated: Work on iostream.h thread safety.
10452 + For more background see the discussions under
10453 + https://github.com/pybind/pybind11/pull/2982 and
10454 + https://github.com/pybind/pybind11/pull/2995.
10459 #include "pybind11.h"
10461 -#include <streambuf>
10462 +#include <algorithm>
10463 +#include <cstring>
10464 +#include <iostream>
10465 +#include <iterator>
10468 +#include <streambuf>
10471 -#include <iostream>
10472 +#include <utility>
10474 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
10475 -NAMESPACE_BEGIN(detail)
10476 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
10477 +PYBIND11_NAMESPACE_BEGIN(detail)
10479 // Buffer that writes to Python instead of C++
10480 class pythonbuf : public std::streambuf {
10482 using traits_type = std::streambuf::traits_type;
10484 - char d_buffer[1024];
10485 + const size_t buf_size;
10486 + std::unique_ptr<char[]> d_buffer;
10490 - int overflow(int c) {
10491 + int overflow(int c) override {
10492 if (!traits_type::eq_int_type(c, traits_type::eof())) {
10493 *pptr() = traits_type::to_char_type(c);
10495 @@ -37,34 +52,84 @@
10496 return sync() == 0 ? traits_type::not_eof(c) : traits_type::eof();
10500 - if (pbase() != pptr()) {
10501 - // This subtraction cannot be negative, so dropping the sign
10502 - str line(pbase(), static_cast<size_t>(pptr() - pbase()));
10503 + // Computes how many bytes at the end of the buffer are part of an
10504 + // incomplete sequence of UTF-8 bytes.
10505 + // Precondition: pbase() < pptr()
10506 + size_t utf8_remainder() const {
10507 + const auto rbase = std::reverse_iterator<char *>(pbase());
10508 + const auto rpptr = std::reverse_iterator<char *>(pptr());
10509 + auto is_ascii = [](char c) { return (static_cast<unsigned char>(c) & 0x80) == 0x00; };
10510 + auto is_leading = [](char c) { return (static_cast<unsigned char>(c) & 0xC0) == 0xC0; };
10511 + auto is_leading_2b = [](char c) { return static_cast<unsigned char>(c) <= 0xDF; };
10512 + auto is_leading_3b = [](char c) { return static_cast<unsigned char>(c) <= 0xEF; };
10513 + // If the last character is ASCII, there are no incomplete code points
10514 + if (is_ascii(*rpptr)) {
10517 + // Otherwise, work back from the end of the buffer and find the first
10518 + // UTF-8 leading byte
10519 + const auto rpend = rbase - rpptr >= 3 ? rpptr + 3 : rbase;
10520 + const auto leading = std::find_if(rpptr, rpend, is_leading);
10521 + if (leading == rbase) {
10524 + const auto dist = static_cast<size_t>(leading - rpptr);
10525 + size_t remainder = 0;
10530 + remainder = 1; // 1-byte code point is impossible
10531 + } else if (dist == 1) {
10532 + remainder = is_leading_2b(*leading) ? 0 : dist + 1;
10533 + } else if (dist == 2) {
10534 + remainder = is_leading_3b(*leading) ? 0 : dist + 1;
10536 + // else if (dist >= 3), at least 4 bytes before encountering an UTF-8
10537 + // leading byte, either no remainder or invalid UTF-8.
10538 + // Invalid UTF-8 will cause an exception later when converting
10539 + // to a Python string, so that's not handled here.
10540 + return remainder;
10543 + // This function must be non-virtual to be called in a destructor.
10545 + if (pbase() != pptr()) { // If buffer is not empty
10546 + gil_scoped_acquire tmp;
10547 + // This subtraction cannot be negative, so dropping the sign.
10548 + auto size = static_cast<size_t>(pptr() - pbase());
10549 + size_t remainder = utf8_remainder();
10551 + if (size > remainder) {
10552 + str line(pbase(), size - remainder);
10557 + // Copy the remainder at the end of the buffer to the beginning:
10558 + if (remainder > 0) {
10559 + std::memmove(pbase(), pptr() - remainder, remainder);
10561 setp(pbase(), epptr());
10562 + pbump(static_cast<int>(remainder));
10567 + int sync() override { return _sync(); }
10570 - pythonbuf(object pyostream)
10571 - : pywrite(pyostream.attr("write")),
10572 + explicit pythonbuf(const object &pyostream, size_t buffer_size = 1024)
10573 + : buf_size(buffer_size), d_buffer(new char[buf_size]), pywrite(pyostream.attr("write")),
10574 pyflush(pyostream.attr("flush")) {
10575 - setp(d_buffer, d_buffer + sizeof(d_buffer) - 1);
10576 + setp(d_buffer.get(), d_buffer.get() + buf_size - 1);
10579 + pythonbuf(pythonbuf &&) = default;
10581 /// Sync before destroy
10585 + ~pythonbuf() override { _sync(); }
10588 -NAMESPACE_END(detail)
10590 +PYBIND11_NAMESPACE_END(detail)
10593 This a move-only guard that redirects output.
10595 .. code-block:: cpp
10598 - py::scoped_ostream_redirect output{std::cerr, py::module::import("sys").attr("stderr")};
10599 - std::cerr << "Hello, World!";
10600 + py::scoped_ostream_redirect output{
10601 + std::cerr, py::module::import("sys").attr("stderr")};
10602 + std::cout << "Hello, World!";
10605 class scoped_ostream_redirect {
10606 @@ -97,16 +163,14 @@
10607 detail::pythonbuf buffer;
10610 - scoped_ostream_redirect(
10611 - std::ostream &costream = std::cout,
10612 - object pyostream = module::import("sys").attr("stdout"))
10613 + explicit scoped_ostream_redirect(std::ostream &costream = std::cout,
10614 + const object &pyostream
10615 + = module_::import("sys").attr("stdout"))
10616 : costream(costream), buffer(pyostream) {
10617 old = costream.rdbuf(&buffer);
10620 - ~scoped_ostream_redirect() {
10621 - costream.rdbuf(old);
10623 + ~scoped_ostream_redirect() { costream.rdbuf(old); }
10625 scoped_ostream_redirect(const scoped_ostream_redirect &) = delete;
10626 scoped_ostream_redirect(scoped_ostream_redirect &&other) = default;
10627 @@ -114,7 +178,6 @@
10628 scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete;
10633 Like `scoped_ostream_redirect`, but redirects cerr by default. This class
10634 is provided primary to make ``py::call_guard`` easier to make.
10635 @@ -128,14 +191,13 @@
10637 class scoped_estream_redirect : public scoped_ostream_redirect {
10639 - scoped_estream_redirect(
10640 - std::ostream &costream = std::cerr,
10641 - object pyostream = module::import("sys").attr("stderr"))
10642 - : scoped_ostream_redirect(costream,pyostream) {}
10643 + explicit scoped_estream_redirect(std::ostream &costream = std::cerr,
10644 + const object &pyostream
10645 + = module_::import("sys").attr("stderr"))
10646 + : scoped_ostream_redirect(costream, pyostream) {}
10650 -NAMESPACE_BEGIN(detail)
10651 +PYBIND11_NAMESPACE_BEGIN(detail)
10653 // Class to redirect output as a context manager. C++ backend.
10654 class OstreamRedirect {
10655 @@ -145,14 +207,16 @@
10656 std::unique_ptr<scoped_estream_redirect> redirect_stderr;
10659 - OstreamRedirect(bool do_stdout = true, bool do_stderr = true)
10660 + explicit OstreamRedirect(bool do_stdout = true, bool do_stderr = true)
10661 : do_stdout_(do_stdout), do_stderr_(do_stderr) {}
10665 + if (do_stdout_) {
10666 redirect_stdout.reset(new scoped_ostream_redirect());
10669 + if (do_stderr_) {
10670 redirect_stderr.reset(new scoped_estream_redirect());
10675 @@ -161,7 +225,7 @@
10679 -NAMESPACE_END(detail)
10680 +PYBIND11_NAMESPACE_END(detail)
10683 This is a helper function to add a C++ redirect context manager to Python
10684 @@ -190,11 +254,12 @@
10685 m.noisy_function_with_error_printing()
10688 -inline class_<detail::OstreamRedirect> add_ostream_redirect(module m, std::string name = "ostream_redirect") {
10689 - return class_<detail::OstreamRedirect>(m, name.c_str(), module_local())
10690 - .def(init<bool,bool>(), arg("stdout")=true, arg("stderr")=true)
10691 +inline class_<detail::OstreamRedirect>
10692 +add_ostream_redirect(module_ m, const std::string &name = "ostream_redirect") {
10693 + return class_<detail::OstreamRedirect>(std::move(m), name.c_str(), module_local())
10694 + .def(init<bool, bool>(), arg("stdout") = true, arg("stderr") = true)
10695 .def("__enter__", &detail::OstreamRedirect::enter)
10696 - .def("__exit__", [](detail::OstreamRedirect &self_, args) { self_.exit(); });
10697 + .def("__exit__", [](detail::OstreamRedirect &self_, const args &) { self_.exit(); });
10700 -NAMESPACE_END(PYBIND11_NAMESPACE)
10701 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
10702 diff -Nur pythia8309.orig/plugins/python/include/pybind11/numpy.h pythia8309/plugins/python/include/pybind11/numpy.h
10703 --- pythia8309.orig/plugins/python/include/pybind11/numpy.h 2023-02-16 18:12:45.000000000 +0100
10704 +++ pythia8309/plugins/python/include/pybind11/numpy.h 2023-03-13 09:52:25.465021614 +0100
10705 @@ -11,35 +11,42 @@
10707 #include "pybind11.h"
10708 #include "complex.h"
10709 -#include <numeric>
10711 #include <algorithm>
10713 +#include <cstdint>
10716 +#include <functional>
10717 +#include <numeric>
10720 -#include <functional>
10721 +#include <type_traits>
10722 +#include <typeindex>
10725 -#include <typeindex>
10727 -#if defined(_MSC_VER)
10728 -# pragma warning(push)
10729 -# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
10732 /* This will be true on all flat address space platforms and allows us to reduce the
10733 whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size
10734 and dimension types (e.g. shape, strides, indexing), instead of inflicting this
10735 upon the library user. */
10736 -static_assert(sizeof(ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t");
10737 +static_assert(sizeof(::pybind11::ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t");
10738 +static_assert(std::is_signed<Py_intptr_t>::value, "Py_intptr_t must be signed");
10739 +// We now can reinterpret_cast between py::ssize_t and Py_intptr_t (MSVC + PyPy cares)
10741 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
10742 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
10744 class array; // Forward declaration
10746 -NAMESPACE_BEGIN(detail)
10747 -template <typename type, typename SFINAE = void> struct npy_format_descriptor;
10748 +PYBIND11_NAMESPACE_BEGIN(detail)
10751 +struct handle_type_name<array> {
10752 + static constexpr auto name = const_name("numpy.ndarray");
10755 +template <typename type, typename SFINAE = void>
10756 +struct npy_format_descriptor;
10758 struct PyArrayDescr_Proxy {
10760 @@ -68,46 +75,66 @@
10763 struct PyVoidScalarObject_Proxy {
10764 - PyObject_VAR_HEAD
10766 + PyObject_VAR_HEAD char *obval;
10767 PyArrayDescr_Proxy *descr;
10772 struct numpy_type_info {
10773 - PyObject* dtype_ptr;
10774 + PyObject *dtype_ptr;
10775 std::string format_str;
10778 struct numpy_internals {
10779 std::unordered_map<std::type_index, numpy_type_info> registered_dtypes;
10781 - numpy_type_info *get_type_info(const std::type_info& tinfo, bool throw_if_missing = true) {
10782 + numpy_type_info *get_type_info(const std::type_info &tinfo, bool throw_if_missing = true) {
10783 auto it = registered_dtypes.find(std::type_index(tinfo));
10784 - if (it != registered_dtypes.end())
10785 + if (it != registered_dtypes.end()) {
10786 return &(it->second);
10787 - if (throw_if_missing)
10789 + if (throw_if_missing) {
10790 pybind11_fail(std::string("NumPy type info missing for ") + tinfo.name());
10795 - template<typename T> numpy_type_info *get_type_info(bool throw_if_missing = true) {
10796 + template <typename T>
10797 + numpy_type_info *get_type_info(bool throw_if_missing = true) {
10798 return get_type_info(typeid(typename std::remove_cv<T>::type), throw_if_missing);
10802 -inline PYBIND11_NOINLINE void load_numpy_internals(numpy_internals* &ptr) {
10803 +PYBIND11_NOINLINE void load_numpy_internals(numpy_internals *&ptr) {
10804 ptr = &get_or_create_shared_data<numpy_internals>("_numpy_internals");
10807 -inline numpy_internals& get_numpy_internals() {
10808 - static numpy_internals* ptr = nullptr;
10810 +inline numpy_internals &get_numpy_internals() {
10811 + static numpy_internals *ptr = nullptr;
10813 load_numpy_internals(ptr);
10818 +template <typename T>
10819 +struct same_size {
10820 + template <typename U>
10821 + using as = bool_constant<sizeof(T) == sizeof(U)>;
10824 +template <typename Concrete>
10825 +constexpr int platform_lookup() {
10829 +// Lookup a type according to its size, and return a value corresponding to the NumPy typenum.
10830 +template <typename Concrete, typename T, typename... Ts, typename... Ints>
10831 +constexpr int platform_lookup(int I, Ints... Is) {
10832 + return sizeof(Concrete) == sizeof(T) ? I : platform_lookup<Concrete, Ts...>(Is...);
10837 NPY_ARRAY_C_CONTIGUOUS_ = 0x0001,
10838 @@ -118,39 +145,73 @@
10839 NPY_ARRAY_ALIGNED_ = 0x0100,
10840 NPY_ARRAY_WRITEABLE_ = 0x0400,
10842 - NPY_BYTE_, NPY_UBYTE_,
10843 - NPY_SHORT_, NPY_USHORT_,
10844 - NPY_INT_, NPY_UINT_,
10845 - NPY_LONG_, NPY_ULONG_,
10846 - NPY_LONGLONG_, NPY_ULONGLONG_,
10847 - NPY_FLOAT_, NPY_DOUBLE_, NPY_LONGDOUBLE_,
10848 - NPY_CFLOAT_, NPY_CDOUBLE_, NPY_CLONGDOUBLE_,
10864 + NPY_CLONGDOUBLE_,
10866 - NPY_STRING_, NPY_UNICODE_, NPY_VOID_
10870 + // Platform-dependent normalization
10871 + NPY_INT8_ = NPY_BYTE_,
10872 + NPY_UINT8_ = NPY_UBYTE_,
10873 + NPY_INT16_ = NPY_SHORT_,
10874 + NPY_UINT16_ = NPY_USHORT_,
10875 + // `npy_common.h` defines the integer aliases. In order, it checks:
10876 + // NPY_BITSOF_LONG, NPY_BITSOF_LONGLONG, NPY_BITSOF_INT, NPY_BITSOF_SHORT, NPY_BITSOF_CHAR
10877 + // and assigns the alias to the first matching size, so we should check in this order.
10879 + = platform_lookup<std::int32_t, long, int, short>(NPY_LONG_, NPY_INT_, NPY_SHORT_),
10880 + NPY_UINT32_ = platform_lookup<std::uint32_t, unsigned long, unsigned int, unsigned short>(
10881 + NPY_ULONG_, NPY_UINT_, NPY_USHORT_),
10883 + = platform_lookup<std::int64_t, long, long long, int>(NPY_LONG_, NPY_LONGLONG_, NPY_INT_),
10885 + = platform_lookup<std::uint64_t, unsigned long, unsigned long long, unsigned int>(
10886 + NPY_ULONG_, NPY_ULONGLONG_, NPY_UINT_),
10890 + struct PyArray_Dims {
10896 - static npy_api& get() {
10897 + static npy_api &get() {
10898 static npy_api api = lookup();
10902 bool PyArray_Check_(PyObject *obj) const {
10903 - return (bool) PyObject_TypeCheck(obj, PyArray_Type_);
10904 + return PyObject_TypeCheck(obj, PyArray_Type_) != 0;
10906 bool PyArrayDescr_Check_(PyObject *obj) const {
10907 - return (bool) PyObject_TypeCheck(obj, PyArrayDescr_Type_);
10908 + return PyObject_TypeCheck(obj, PyArrayDescr_Type_) != 0;
10911 unsigned int (*PyArray_GetNDArrayCFeatureVersion_)();
10912 PyObject *(*PyArray_DescrFromType_)(int);
10913 - PyObject *(*PyArray_NewFromDescr_)
10914 - (PyTypeObject *, PyObject *, int, Py_intptr_t *,
10915 - Py_intptr_t *, void *, int, PyObject *);
10916 + PyObject *(*PyArray_NewFromDescr_)(PyTypeObject *,
10919 + Py_intptr_t const *,
10920 + Py_intptr_t const *,
10924 + // Unused. Not removed because that affects ABI of the class.
10925 PyObject *(*PyArray_DescrNewFromType_)(int);
10926 int (*PyArray_CopyInto_)(PyObject *, PyObject *);
10927 PyObject *(*PyArray_NewCopy_)(PyObject *, int);
10928 @@ -158,14 +219,24 @@
10929 PyTypeObject *PyVoidArrType_Type_;
10930 PyTypeObject *PyArrayDescr_Type_;
10931 PyObject *(*PyArray_DescrFromScalar_)(PyObject *);
10932 - PyObject *(*PyArray_FromAny_) (PyObject *, PyObject *, int, int, int, PyObject *);
10933 - int (*PyArray_DescrConverter_) (PyObject *, PyObject **);
10934 - bool (*PyArray_EquivTypes_) (PyObject *, PyObject *);
10935 - int (*PyArray_GetArrayParamsFromObject_)(PyObject *, PyObject *, char, PyObject **, int *,
10936 - Py_ssize_t *, PyObject **, PyObject *);
10937 + PyObject *(*PyArray_FromAny_)(PyObject *, PyObject *, int, int, int, PyObject *);
10938 + int (*PyArray_DescrConverter_)(PyObject *, PyObject **);
10939 + bool (*PyArray_EquivTypes_)(PyObject *, PyObject *);
10940 + int (*PyArray_GetArrayParamsFromObject_)(PyObject *,
10948 PyObject *(*PyArray_Squeeze_)(PyObject *);
10949 + // Unused. Not removed because that affects ABI of the class.
10950 int (*PyArray_SetBaseObject_)(PyObject *, PyObject *);
10951 - PyObject* (*PyArray_Resize_)(PyObject*, PyArray_Dims*, int, int);
10952 + PyObject *(*PyArray_Resize_)(PyObject *, PyArray_Dims *, int, int);
10953 + PyObject *(*PyArray_Newshape_)(PyObject *, PyArray_Dims *, int);
10954 + PyObject *(*PyArray_View_)(PyObject *, PyObject *, PyObject *);
10958 API_PyArray_GetNDArrayCFeatureVersion = 211,
10959 @@ -179,16 +250,18 @@
10960 API_PyArray_CopyInto = 82,
10961 API_PyArray_NewCopy = 85,
10962 API_PyArray_NewFromDescr = 94,
10963 - API_PyArray_DescrNewFromType = 9,
10964 + API_PyArray_DescrNewFromType = 96,
10965 + API_PyArray_Newshape = 135,
10966 + API_PyArray_Squeeze = 136,
10967 + API_PyArray_View = 137,
10968 API_PyArray_DescrConverter = 174,
10969 API_PyArray_EquivTypes = 182,
10970 API_PyArray_GetArrayParamsFromObject = 278,
10971 - API_PyArray_Squeeze = 136,
10972 API_PyArray_SetBaseObject = 282
10975 static npy_api lookup() {
10976 - module m = module::import("numpy.core.multiarray");
10977 + module_ m = module_::import("numpy.core.multiarray");
10978 auto c = m.attr("_ARRAY_API");
10979 #if PY_MAJOR_VERSION >= 3
10980 void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), NULL);
10981 @@ -198,8 +271,9 @@
10983 #define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func];
10984 DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion);
10985 - if (api.PyArray_GetNDArrayCFeatureVersion_() < 0x7)
10986 + if (api.PyArray_GetNDArrayCFeatureVersion_() < 0x7) {
10987 pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0");
10989 DECL_NPY_API(PyArray_Type);
10990 DECL_NPY_API(PyVoidArrType_Type);
10991 DECL_NPY_API(PyArrayDescr_Type);
10992 @@ -211,90 +285,116 @@
10993 DECL_NPY_API(PyArray_NewCopy);
10994 DECL_NPY_API(PyArray_NewFromDescr);
10995 DECL_NPY_API(PyArray_DescrNewFromType);
10996 + DECL_NPY_API(PyArray_Newshape);
10997 + DECL_NPY_API(PyArray_Squeeze);
10998 + DECL_NPY_API(PyArray_View);
10999 DECL_NPY_API(PyArray_DescrConverter);
11000 DECL_NPY_API(PyArray_EquivTypes);
11001 DECL_NPY_API(PyArray_GetArrayParamsFromObject);
11002 - DECL_NPY_API(PyArray_Squeeze);
11003 DECL_NPY_API(PyArray_SetBaseObject);
11005 #undef DECL_NPY_API
11010 -inline PyArray_Proxy* array_proxy(void* ptr) {
11011 - return reinterpret_cast<PyArray_Proxy*>(ptr);
11013 +inline PyArray_Proxy *array_proxy(void *ptr) { return reinterpret_cast<PyArray_Proxy *>(ptr); }
11015 -inline const PyArray_Proxy* array_proxy(const void* ptr) {
11016 - return reinterpret_cast<const PyArray_Proxy*>(ptr);
11017 +inline const PyArray_Proxy *array_proxy(const void *ptr) {
11018 + return reinterpret_cast<const PyArray_Proxy *>(ptr);
11021 -inline PyArrayDescr_Proxy* array_descriptor_proxy(PyObject* ptr) {
11022 - return reinterpret_cast<PyArrayDescr_Proxy*>(ptr);
11023 +inline PyArrayDescr_Proxy *array_descriptor_proxy(PyObject *ptr) {
11024 + return reinterpret_cast<PyArrayDescr_Proxy *>(ptr);
11027 -inline const PyArrayDescr_Proxy* array_descriptor_proxy(const PyObject* ptr) {
11028 - return reinterpret_cast<const PyArrayDescr_Proxy*>(ptr);
11029 +inline const PyArrayDescr_Proxy *array_descriptor_proxy(const PyObject *ptr) {
11030 + return reinterpret_cast<const PyArrayDescr_Proxy *>(ptr);
11033 -inline bool check_flags(const void* ptr, int flag) {
11034 +inline bool check_flags(const void *ptr, int flag) {
11035 return (flag == (array_proxy(ptr)->flags & flag));
11038 -template <typename T> struct is_std_array : std::false_type { };
11039 -template <typename T, size_t N> struct is_std_array<std::array<T, N>> : std::true_type { };
11040 -template <typename T> struct is_complex : std::false_type { };
11041 -template <typename T> struct is_complex<std::complex<T>> : std::true_type { };
11042 +template <typename T>
11043 +struct is_std_array : std::false_type {};
11044 +template <typename T, size_t N>
11045 +struct is_std_array<std::array<T, N>> : std::true_type {};
11046 +template <typename T>
11047 +struct is_complex : std::false_type {};
11048 +template <typename T>
11049 +struct is_complex<std::complex<T>> : std::true_type {};
11051 -template <typename T> struct array_info_scalar {
11053 +template <typename T>
11054 +struct array_info_scalar {
11056 static constexpr bool is_array = false;
11057 static constexpr bool is_empty = false;
11058 - static constexpr auto extents = _("");
11059 - static void append_extents(list& /* shape */) { }
11060 + static constexpr auto extents = const_name("");
11061 + static void append_extents(list & /* shape */) {}
11063 // Computes underlying type and a comma-separated list of extents for array
11064 // types (any mix of std::array and built-in arrays). An array of char is
11065 // treated as scalar because it gets special handling.
11066 -template <typename T> struct array_info : array_info_scalar<T> { };
11067 -template <typename T, size_t N> struct array_info<std::array<T, N>> {
11068 +template <typename T>
11069 +struct array_info : array_info_scalar<T> {};
11070 +template <typename T, size_t N>
11071 +struct array_info<std::array<T, N>> {
11072 using type = typename array_info<T>::type;
11073 static constexpr bool is_array = true;
11074 static constexpr bool is_empty = (N == 0) || array_info<T>::is_empty;
11075 static constexpr size_t extent = N;
11077 // appends the extents to shape
11078 - static void append_extents(list& shape) {
11079 + static void append_extents(list &shape) {
11081 array_info<T>::append_extents(shape);
11084 - static constexpr auto extents = _<array_info<T>::is_array>(
11085 - concat(_<N>(), array_info<T>::extents), _<N>()
11087 + static constexpr auto extents = const_name<array_info<T>::is_array>(
11088 + concat(const_name<N>(), array_info<T>::extents), const_name<N>());
11090 // For numpy we have special handling for arrays of characters, so we don't include
11091 // the size in the array extents.
11092 -template <size_t N> struct array_info<char[N]> : array_info_scalar<char[N]> { };
11093 -template <size_t N> struct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> { };
11094 -template <typename T, size_t N> struct array_info<T[N]> : array_info<std::array<T, N>> { };
11095 -template <typename T> using remove_all_extents_t = typename array_info<T>::type;
11097 -template <typename T> using is_pod_struct = all_of<
11098 - std::is_standard_layout<T>, // since we're accessing directly in memory we need a standard layout type
11099 -#if !defined(__GNUG__) || defined(_LIBCPP_VERSION) || defined(_GLIBCXX_USE_CXX11_ABI)
11100 - // _GLIBCXX_USE_CXX11_ABI indicates that we're using libstdc++ from GCC 5 or newer, independent
11101 - // of the actual compiler (Clang can also use libstdc++, but it always defines __GNUC__ == 4).
11102 - std::is_trivially_copyable<T>,
11103 +template <size_t N>
11104 +struct array_info<char[N]> : array_info_scalar<char[N]> {};
11105 +template <size_t N>
11106 +struct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> {};
11107 +template <typename T, size_t N>
11108 +struct array_info<T[N]> : array_info<std::array<T, N>> {};
11109 +template <typename T>
11110 +using remove_all_extents_t = typename array_info<T>::type;
11112 +template <typename T>
11113 +using is_pod_struct
11114 + = all_of<std::is_standard_layout<T>, // since we're accessing directly in memory
11115 + // we need a standard layout type
11116 +#if defined(__GLIBCXX__) \
11117 + && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150426 || __GLIBCXX__ == 20150623 \
11118 + || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)
11119 + // libstdc++ < 5 (including versions 4.8.5, 4.9.3 and 4.9.4 which were released after
11120 + // 5) don't implement is_trivially_copyable, so approximate it
11121 + std::is_trivially_destructible<T>,
11122 + satisfies_any_of<T, std::has_trivial_copy_constructor, std::has_trivial_copy_assign>,
11124 - // GCC 4 doesn't implement is_trivially_copyable, so approximate it
11125 - std::is_trivially_destructible<T>,
11126 - satisfies_any_of<T, std::has_trivial_copy_constructor, std::has_trivial_copy_assign>,
11127 + std::is_trivially_copyable<T>,
11129 - satisfies_none_of<T, std::is_reference, std::is_array, is_std_array, std::is_arithmetic, is_complex, std::is_enum>
11131 + satisfies_none_of<T,
11132 + std::is_reference,
11135 + std::is_arithmetic,
11139 -template <ssize_t Dim = 0, typename Strides> ssize_t byte_offset_unsafe(const Strides &) { return 0; }
11140 +// Replacement for std::is_pod (deprecated in C++20)
11141 +template <typename T>
11142 +using is_pod = all_of<std::is_standard_layout<T>, std::is_trivial<T>>;
11144 +template <ssize_t Dim = 0, typename Strides>
11145 +ssize_t byte_offset_unsafe(const Strides &) {
11148 template <ssize_t Dim = 0, typename Strides, typename... Ix>
11149 ssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) {
11150 return i * strides[Dim] + byte_offset_unsafe<Dim + 1>(strides, index...);
11151 @@ -302,7 +402,7 @@
11154 * Proxy class providing unsafe, unchecked const access to array data. This is constructed through
11155 - * the `unchecked<T, N>()` method of `array` or the `unchecked<N>()` method of `array_t<T>`. `Dims`
11156 + * the `unchecked<T, N>()` method of `array` or the `unchecked<N>()` method of `array_t<T>`. `Dims`
11157 * will be -1 for dimensions determined at runtime.
11159 template <typename T, ssize_t Dims>
11160 @@ -312,15 +412,17 @@
11161 const unsigned char *data_;
11162 // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to
11163 // make large performance gains on big, nested loops, but requires compile-time dimensions
11164 - conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>>
11165 - shape_, strides_;
11166 + conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>> shape_, strides_;
11167 const ssize_t dims_;
11169 friend class pybind11::array;
11170 // Constructor for compile-time dimensions:
11171 template <bool Dyn = Dynamic>
11172 - unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<!Dyn, ssize_t>)
11173 - : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} {
11174 + unchecked_reference(const void *data,
11175 + const ssize_t *shape,
11176 + const ssize_t *strides,
11177 + enable_if_t<!Dyn, ssize_t>)
11178 + : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} {
11179 for (size_t i = 0; i < (size_t) dims_; i++) {
11180 shape_[i] = shape[i];
11181 strides_[i] = strides[i];
11182 @@ -328,8 +430,12 @@
11184 // Constructor for runtime dimensions:
11185 template <bool Dyn = Dynamic>
11186 - unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<Dyn, ssize_t> dims)
11187 - : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides}, dims_{dims} {}
11188 + unchecked_reference(const void *data,
11189 + const ssize_t *shape,
11190 + const ssize_t *strides,
11191 + enable_if_t<Dyn, ssize_t> dims)
11192 + : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides},
11197 @@ -337,20 +443,27 @@
11198 * number of dimensions, this requires the correct number of arguments; for run-time
11199 * dimensionality, this is not checked (and so is up to the caller to use safely).
11201 - template <typename... Ix> const T &operator()(Ix... index) const {
11202 + template <typename... Ix>
11203 + const T &operator()(Ix... index) const {
11204 static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
11205 - "Invalid number of indices for unchecked array reference");
11206 - return *reinterpret_cast<const T *>(data_ + byte_offset_unsafe(strides_, ssize_t(index)...));
11207 + "Invalid number of indices for unchecked array reference");
11208 + return *reinterpret_cast<const T *>(data_
11209 + + byte_offset_unsafe(strides_, ssize_t(index)...));
11212 * Unchecked const reference access to data; this operator only participates if the reference
11213 * is to a 1-dimensional array. When present, this is exactly equivalent to `obj(index)`.
11215 template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
11216 - const T &operator[](ssize_t index) const { return operator()(index); }
11217 + const T &operator[](ssize_t index) const {
11218 + return operator()(index);
11221 /// Pointer access to the data at the given indices.
11222 - template <typename... Ix> const T *data(Ix... ix) const { return &operator()(ssize_t(ix)...); }
11223 + template <typename... Ix>
11224 + const T *data(Ix... ix) const {
11225 + return &operator()(ssize_t(ix)...);
11228 /// Returns the item size, i.e. sizeof(T)
11229 constexpr static ssize_t itemsize() { return sizeof(T); }
11230 @@ -361,21 +474,22 @@
11231 /// Returns the number of dimensions of the array
11232 ssize_t ndim() const { return dims_; }
11234 - /// Returns the total number of elements in the referenced array, i.e. the product of the shapes
11235 + /// Returns the total number of elements in the referenced array, i.e. the product of the
11237 template <bool Dyn = Dynamic>
11238 enable_if_t<!Dyn, ssize_t> size() const {
11239 - return std::accumulate(shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>());
11240 + return std::accumulate(
11241 + shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>());
11243 template <bool Dyn = Dynamic>
11244 enable_if_t<Dyn, ssize_t> size() const {
11245 return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
11248 - /// Returns the total number of bytes used by the referenced data. Note that the actual span in
11249 - /// memory may be larger if the referenced array has non-contiguous strides (e.g. for a slice).
11250 - ssize_t nbytes() const {
11251 - return size() * itemsize();
11253 + /// Returns the total number of bytes used by the referenced data. Note that the actual span
11254 + /// in memory may be larger if the referenced array has non-contiguous strides (e.g. for a
11256 + ssize_t nbytes() const { return size() * itemsize(); }
11259 template <typename T, ssize_t Dims>
11260 @@ -384,11 +498,17 @@
11261 using ConstBase = unchecked_reference<T, Dims>;
11262 using ConstBase::ConstBase;
11263 using ConstBase::Dynamic;
11266 + // Bring in const-qualified versions from base class
11267 + using ConstBase::operator();
11268 + using ConstBase::operator[];
11270 /// Mutable, unchecked access to data at the given indices.
11271 - template <typename... Ix> T& operator()(Ix... index) {
11272 + template <typename... Ix>
11273 + T &operator()(Ix... index) {
11274 static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
11275 - "Invalid number of indices for unchecked array reference");
11276 + "Invalid number of indices for unchecked array reference");
11277 return const_cast<T &>(ConstBase::operator()(index...));
11280 @@ -397,20 +517,27 @@
11281 * exactly equivalent to `obj(index)`.
11283 template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
11284 - T &operator[](ssize_t index) { return operator()(index); }
11285 + T &operator[](ssize_t index) {
11286 + return operator()(index);
11289 /// Mutable pointer access to the data at the given indices.
11290 - template <typename... Ix> T *mutable_data(Ix... ix) { return &operator()(ssize_t(ix)...); }
11291 + template <typename... Ix>
11292 + T *mutable_data(Ix... ix) {
11293 + return &operator()(ssize_t(ix)...);
11297 template <typename T, ssize_t Dim>
11298 struct type_caster<unchecked_reference<T, Dim>> {
11299 - static_assert(Dim == 0 && Dim > 0 /* always fail */, "unchecked array proxy object is not castable");
11300 + static_assert(Dim == 0 && Dim > 0 /* always fail */,
11301 + "unchecked array proxy object is not castable");
11303 template <typename T, ssize_t Dim>
11304 -struct type_caster<unchecked_mutable_reference<T, Dim>> : type_caster<unchecked_reference<T, Dim>> {};
11305 +struct type_caster<unchecked_mutable_reference<T, Dim>>
11306 + : type_caster<unchecked_reference<T, Dim>> {};
11308 -NAMESPACE_END(detail)
11309 +PYBIND11_NAMESPACE_END(detail)
11311 class dtype : public object {
11313 @@ -419,66 +546,82 @@
11314 explicit dtype(const buffer_info &info) {
11315 dtype descr(_dtype_from_pep3118()(PYBIND11_STR_TYPE(info.format)));
11316 // If info.itemsize == 0, use the value calculated from the format string
11317 - m_ptr = descr.strip_padding(info.itemsize ? info.itemsize : descr.itemsize()).release().ptr();
11318 + m_ptr = descr.strip_padding(info.itemsize != 0 ? info.itemsize : descr.itemsize())
11323 explicit dtype(const std::string &format) {
11324 m_ptr = from_args(pybind11::str(format)).release().ptr();
11327 - dtype(const char *format) : dtype(std::string(format)) { }
11328 + explicit dtype(const char *format) : dtype(std::string(format)) {}
11330 dtype(list names, list formats, list offsets, ssize_t itemsize) {
11332 - args["names"] = names;
11333 - args["formats"] = formats;
11334 - args["offsets"] = offsets;
11335 + args["names"] = std::move(names);
11336 + args["formats"] = std::move(formats);
11337 + args["offsets"] = std::move(offsets);
11338 args["itemsize"] = pybind11::int_(itemsize);
11339 - m_ptr = from_args(args).release().ptr();
11340 + m_ptr = from_args(std::move(args)).release().ptr();
11343 /// This is essentially the same as calling numpy.dtype(args) in Python.
11344 static dtype from_args(object args) {
11345 PyObject *ptr = nullptr;
11346 - if (!detail::npy_api::get().PyArray_DescrConverter_(args.ptr(), &ptr) || !ptr)
11347 + if ((detail::npy_api::get().PyArray_DescrConverter_(args.ptr(), &ptr) == 0) || !ptr) {
11348 throw error_already_set();
11350 return reinterpret_steal<dtype>(ptr);
11353 /// Return dtype associated with a C++ type.
11354 - template <typename T> static dtype of() {
11355 + template <typename T>
11356 + static dtype of() {
11357 return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype();
11360 /// Size of the data type in bytes.
11361 - ssize_t itemsize() const {
11362 - return detail::array_descriptor_proxy(m_ptr)->elsize;
11364 + ssize_t itemsize() const { return detail::array_descriptor_proxy(m_ptr)->elsize; }
11366 /// Returns true for structured data types.
11367 - bool has_fields() const {
11368 - return detail::array_descriptor_proxy(m_ptr)->names != nullptr;
11370 + bool has_fields() const { return detail::array_descriptor_proxy(m_ptr)->names != nullptr; }
11372 - /// Single-character type code.
11373 - char kind() const {
11374 - return detail::array_descriptor_proxy(m_ptr)->kind;
11375 + /// Single-character code for dtype's kind.
11376 + /// For example, floating point types are 'f' and integral types are 'i'.
11377 + char kind() const { return detail::array_descriptor_proxy(m_ptr)->kind; }
11379 + /// Single-character for dtype's type.
11380 + /// For example, ``float`` is 'f', ``double`` 'd', ``int`` 'i', and ``long`` 'l'.
11381 + char char_() const {
11382 + // Note: The signature, `dtype::char_` follows the naming of NumPy's
11383 + // public Python API (i.e., ``dtype.char``), rather than its internal
11384 + // C API (``PyArray_Descr::type``).
11385 + return detail::array_descriptor_proxy(m_ptr)->type;
11389 static object _dtype_from_pep3118() {
11390 - static PyObject *obj = module::import("numpy.core._internal")
11391 - .attr("_dtype_from_pep3118").cast<object>().release().ptr();
11392 + static PyObject *obj = module_::import("numpy.core._internal")
11393 + .attr("_dtype_from_pep3118")
11397 return reinterpret_borrow<object>(obj);
11400 dtype strip_padding(ssize_t itemsize) {
11401 // Recursively strip all void fields with empty names that are generated for
11402 // padding fields (as of NumPy v1.11).
11403 - if (!has_fields())
11404 + if (!has_fields()) {
11408 - struct field_descr { PYBIND11_STR_TYPE name; object format; pybind11::int_ offset; };
11409 + struct field_descr {
11410 + PYBIND11_STR_TYPE name;
11412 + pybind11::int_ offset;
11414 std::vector<field_descr> field_descriptors;
11416 for (auto field : attr("fields").attr("items")()) {
11417 @@ -486,23 +629,26 @@
11418 auto name = spec[0].cast<pybind11::str>();
11419 auto format = spec[1].cast<tuple>()[0].cast<dtype>();
11420 auto offset = spec[1].cast<tuple>()[1].cast<pybind11::int_>();
11421 - if (!len(name) && format.kind() == 'V')
11422 + if ((len(name) == 0u) && format.kind() == 'V') {
11424 - field_descriptors.push_back({(PYBIND11_STR_TYPE) name, format.strip_padding(format.itemsize()), offset});
11426 + field_descriptors.push_back(
11427 + {(PYBIND11_STR_TYPE) name, format.strip_padding(format.itemsize()), offset});
11430 - std::sort(field_descriptors.begin(), field_descriptors.end(),
11431 - [](const field_descr& a, const field_descr& b) {
11432 + std::sort(field_descriptors.begin(),
11433 + field_descriptors.end(),
11434 + [](const field_descr &a, const field_descr &b) {
11435 return a.offset.cast<int>() < b.offset.cast<int>();
11438 list names, formats, offsets;
11439 - for (auto& descr : field_descriptors) {
11440 + for (auto &descr : field_descriptors) {
11441 names.append(descr.name);
11442 formats.append(descr.format);
11443 offsets.append(descr.offset);
11445 - return dtype(names, formats, offsets, itemsize);
11446 + return dtype(std::move(names), std::move(formats), std::move(offsets), itemsize);
11450 @@ -516,69 +662,91 @@
11451 forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_
11454 - array() : array({{0}}, static_cast<const double *>(nullptr)) {}
11455 + array() : array(0, static_cast<const double *>(nullptr)) {}
11457 using ShapeContainer = detail::any_container<ssize_t>;
11458 using StridesContainer = detail::any_container<ssize_t>;
11460 // Constructs an array taking shape/strides from arbitrary container types
11461 - array(const pybind11::dtype &dt, ShapeContainer shape, StridesContainer strides,
11462 - const void *ptr = nullptr, handle base = handle()) {
11463 + array(const pybind11::dtype &dt,
11464 + ShapeContainer shape,
11465 + StridesContainer strides,
11466 + const void *ptr = nullptr,
11467 + handle base = handle()) {
11469 - if (strides->empty())
11470 - *strides = c_strides(*shape, dt.itemsize());
11471 + if (strides->empty()) {
11472 + *strides = detail::c_strides(*shape, dt.itemsize());
11475 auto ndim = shape->size();
11476 - if (ndim != strides->size())
11477 + if (ndim != strides->size()) {
11478 pybind11_fail("NumPy: shape ndim doesn't match strides ndim");
11484 - if (isinstance<array>(base))
11485 + if (isinstance<array>(base)) {
11486 /* Copy flags from base (except ownership bit) */
11487 - flags = reinterpret_borrow<array>(base).flags() & ~detail::npy_api::NPY_ARRAY_OWNDATA_;
11489 + flags = reinterpret_borrow<array>(base).flags()
11490 + & ~detail::npy_api::NPY_ARRAY_OWNDATA_;
11492 /* Writable by default, easy to downgrade later on if needed */
11493 flags = detail::npy_api::NPY_ARRAY_WRITEABLE_;
11497 auto &api = detail::npy_api::get();
11498 auto tmp = reinterpret_steal<object>(api.PyArray_NewFromDescr_(
11499 - api.PyArray_Type_, descr.release().ptr(), (int) ndim, shape->data(), strides->data(),
11500 - const_cast<void *>(ptr), flags, nullptr));
11502 + api.PyArray_Type_,
11503 + descr.release().ptr(),
11505 + // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
11506 + reinterpret_cast<Py_intptr_t *>(shape->data()),
11507 + reinterpret_cast<Py_intptr_t *>(strides->data()),
11508 + const_cast<void *>(ptr),
11512 throw error_already_set();
11516 api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr());
11518 - tmp = reinterpret_steal<object>(api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */));
11519 + tmp = reinterpret_steal<object>(
11520 + api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */));
11523 m_ptr = tmp.release().ptr();
11526 - array(const pybind11::dtype &dt, ShapeContainer shape, const void *ptr = nullptr, handle base = handle())
11527 - : array(dt, std::move(shape), {}, ptr, base) { }
11529 - template <typename T, typename = detail::enable_if_t<std::is_integral<T>::value && !std::is_same<bool, T>::value>>
11530 + array(const pybind11::dtype &dt,
11531 + ShapeContainer shape,
11532 + const void *ptr = nullptr,
11533 + handle base = handle())
11534 + : array(dt, std::move(shape), {}, ptr, base) {}
11536 + template <typename T,
11538 + = detail::enable_if_t<std::is_integral<T>::value && !std::is_same<bool, T>::value>>
11539 array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle())
11540 - : array(dt, {{count}}, ptr, base) { }
11541 + : array(dt, {{count}}, ptr, base) {}
11543 template <typename T>
11544 array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base = handle())
11545 - : array(pybind11::dtype::of<T>(), std::move(shape), std::move(strides), ptr, base) { }
11546 + : array(pybind11::dtype::of<T>(), std::move(shape), std::move(strides), ptr, base) {}
11548 template <typename T>
11549 array(ShapeContainer shape, const T *ptr, handle base = handle())
11550 - : array(std::move(shape), {}, ptr, base) { }
11551 + : array(std::move(shape), {}, ptr, base) {}
11553 template <typename T>
11554 - explicit array(ssize_t count, const T *ptr, handle base = handle()) : array({count}, {}, ptr, base) { }
11555 + explicit array(ssize_t count, const T *ptr, handle base = handle())
11556 + : array({count}, {}, ptr, base) {}
11558 - explicit array(const buffer_info &info)
11559 - : array(pybind11::dtype(info), info.shape, info.strides, info.ptr) { }
11560 + explicit array(const buffer_info &info, handle base = handle())
11561 + : array(pybind11::dtype(info), info.shape, info.strides, info.ptr, base) {}
11563 /// Array descriptor (dtype)
11564 pybind11::dtype dtype() const {
11565 @@ -596,48 +764,38 @@
11568 /// Total number of bytes
11569 - ssize_t nbytes() const {
11570 - return size() * itemsize();
11572 + ssize_t nbytes() const { return size() * itemsize(); }
11574 /// Number of dimensions
11575 - ssize_t ndim() const {
11576 - return detail::array_proxy(m_ptr)->nd;
11578 + ssize_t ndim() const { return detail::array_proxy(m_ptr)->nd; }
11581 - object base() const {
11582 - return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base);
11584 + object base() const { return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base); }
11586 /// Dimensions of the array
11587 - const ssize_t* shape() const {
11588 - return detail::array_proxy(m_ptr)->dimensions;
11590 + const ssize_t *shape() const { return detail::array_proxy(m_ptr)->dimensions; }
11592 /// Dimension along a given axis
11593 ssize_t shape(ssize_t dim) const {
11594 - if (dim >= ndim())
11595 + if (dim >= ndim()) {
11596 fail_dim_check(dim, "invalid axis");
11598 return shape()[dim];
11601 /// Strides of the array
11602 - const ssize_t* strides() const {
11603 - return detail::array_proxy(m_ptr)->strides;
11605 + const ssize_t *strides() const { return detail::array_proxy(m_ptr)->strides; }
11607 /// Stride along a given axis
11608 ssize_t strides(ssize_t dim) const {
11609 - if (dim >= ndim())
11610 + if (dim >= ndim()) {
11611 fail_dim_check(dim, "invalid axis");
11613 return strides()[dim];
11616 /// Return the NumPy array flags
11617 - int flags() const {
11618 - return detail::array_proxy(m_ptr)->flags;
11620 + int flags() const { return detail::array_proxy(m_ptr)->flags; }
11622 /// If set, the array is writeable (otherwise the buffer is read-only)
11623 bool writeable() const {
11624 @@ -651,23 +809,27 @@
11626 /// Pointer to the contained data. If index is not provided, points to the
11627 /// beginning of the buffer. May throw if the index would lead to out of bounds access.
11628 - template<typename... Ix> const void* data(Ix... index) const {
11629 + template <typename... Ix>
11630 + const void *data(Ix... index) const {
11631 return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
11634 /// Mutable pointer to the contained data. If index is not provided, points to the
11635 /// beginning of the buffer. May throw if the index would lead to out of bounds access.
11636 /// May throw if the array is not writeable.
11637 - template<typename... Ix> void* mutable_data(Ix... index) {
11638 + template <typename... Ix>
11639 + void *mutable_data(Ix... index) {
11641 return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
11644 /// Byte offset from beginning of the array to a given index (full or partial).
11645 /// May throw if the index would lead to out of bounds access.
11646 - template<typename... Ix> ssize_t offset_at(Ix... index) const {
11647 - if ((ssize_t) sizeof...(index) > ndim())
11648 + template <typename... Ix>
11649 + ssize_t offset_at(Ix... index) const {
11650 + if ((ssize_t) sizeof...(index) > ndim()) {
11651 fail_dim_check(sizeof...(index), "too many indices for an array");
11653 return byte_offset(ssize_t(index)...);
11656 @@ -675,7 +837,8 @@
11658 /// Item count from beginning of the array to a given index (full or partial).
11659 /// May throw if the index would lead to out of bounds access.
11660 - template<typename... Ix> ssize_t index_at(Ix... index) const {
11661 + template <typename... Ix>
11662 + ssize_t index_at(Ix... index) const {
11663 return offset_at(index...) / itemsize();
11666 @@ -685,30 +848,37 @@
11667 * care: the array must not be destroyed or reshaped for the duration of the returned object,
11668 * and the caller must take care not to access invalid dimensions or dimension indices.
11670 - template <typename T, ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
11671 - if (Dims >= 0 && ndim() != Dims)
11672 - throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) +
11673 - "; expected " + std::to_string(Dims));
11674 - return detail::unchecked_mutable_reference<T, Dims>(mutable_data(), shape(), strides(), ndim());
11675 + template <typename T, ssize_t Dims = -1>
11676 + detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
11677 + if (PYBIND11_SILENCE_MSVC_C4127(Dims >= 0) && ndim() != Dims) {
11678 + throw std::domain_error("array has incorrect number of dimensions: "
11679 + + std::to_string(ndim()) + "; expected "
11680 + + std::to_string(Dims));
11682 + return detail::unchecked_mutable_reference<T, Dims>(
11683 + mutable_data(), shape(), strides(), ndim());
11687 * Returns a proxy object that provides const access to the array's data without bounds or
11688 * dimensionality checking. Unlike `mutable_unchecked()`, this does not require that the
11689 - * underlying array have the `writable` flag. Use with care: the array must not be destroyed or
11690 - * reshaped for the duration of the returned object, and the caller must take care not to access
11691 - * invalid dimensions or dimension indices.
11692 + * underlying array have the `writable` flag. Use with care: the array must not be destroyed
11693 + * or reshaped for the duration of the returned object, and the caller must take care not to
11694 + * access invalid dimensions or dimension indices.
11696 - template <typename T, ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & {
11697 - if (Dims >= 0 && ndim() != Dims)
11698 - throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) +
11699 - "; expected " + std::to_string(Dims));
11700 + template <typename T, ssize_t Dims = -1>
11701 + detail::unchecked_reference<T, Dims> unchecked() const & {
11702 + if (PYBIND11_SILENCE_MSVC_C4127(Dims >= 0) && ndim() != Dims) {
11703 + throw std::domain_error("array has incorrect number of dimensions: "
11704 + + std::to_string(ndim()) + "; expected "
11705 + + std::to_string(Dims));
11707 return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim());
11710 /// Return a new view with all of the dimensions of length 1 removed
11712 - auto& api = detail::npy_api::get();
11713 + auto &api = detail::npy_api::get();
11714 return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr));
11717 @@ -716,74 +886,92 @@
11718 /// If refcheck is true and more that one reference exist to this array
11719 /// then resize will succeed only if it makes a reshape, i.e. original size doesn't change
11720 void resize(ShapeContainer new_shape, bool refcheck = true) {
11721 - detail::npy_api::PyArray_Dims d = {
11722 - new_shape->data(), int(new_shape->size())
11724 + detail::npy_api::PyArray_Dims d
11725 + = {// Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
11726 + reinterpret_cast<Py_intptr_t *>(new_shape->data()),
11727 + int(new_shape->size())};
11728 // try to resize, set ordering param to -1 cause it's not used anyway
11729 - object new_array = reinterpret_steal<object>(
11730 - detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1)
11732 - if (!new_array) throw error_already_set();
11733 - if (isinstance<array>(new_array)) { *this = std::move(new_array); }
11734 + auto new_array = reinterpret_steal<object>(
11735 + detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1));
11736 + if (!new_array) {
11737 + throw error_already_set();
11739 + if (isinstance<array>(new_array)) {
11740 + *this = std::move(new_array);
11744 + /// Optional `order` parameter omitted, to be added as needed.
11745 + array reshape(ShapeContainer new_shape) {
11746 + detail::npy_api::PyArray_Dims d
11747 + = {reinterpret_cast<Py_intptr_t *>(new_shape->data()), int(new_shape->size())};
11749 + = reinterpret_steal<array>(detail::npy_api::get().PyArray_Newshape_(m_ptr, &d, 0));
11750 + if (!new_array) {
11751 + throw error_already_set();
11753 + return new_array;
11756 + /// Create a view of an array in a different data type.
11757 + /// This function may fundamentally reinterpret the data in the array.
11758 + /// It is the responsibility of the caller to ensure that this is safe.
11759 + /// Only supports the `dtype` argument, the `type` argument is omitted,
11760 + /// to be added as needed.
11761 + array view(const std::string &dtype) {
11762 + auto &api = detail::npy_api::get();
11763 + auto new_view = reinterpret_steal<array>(api.PyArray_View_(
11764 + m_ptr, dtype::from_args(pybind11::str(dtype)).release().ptr(), nullptr));
11766 + throw error_already_set();
11771 /// Ensure that the argument is a NumPy array
11772 /// In case of an error, nullptr is returned and the Python error is cleared.
11773 static array ensure(handle h, int ExtraFlags = 0) {
11774 auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags));
11783 - template<typename, typename> friend struct detail::npy_format_descriptor;
11784 + template <typename, typename>
11785 + friend struct detail::npy_format_descriptor;
11787 - void fail_dim_check(ssize_t dim, const std::string& msg) const {
11788 - throw index_error(msg + ": " + std::to_string(dim) +
11789 - " (ndim = " + std::to_string(ndim()) + ")");
11790 + void fail_dim_check(ssize_t dim, const std::string &msg) const {
11791 + throw index_error(msg + ": " + std::to_string(dim) + " (ndim = " + std::to_string(ndim())
11795 - template<typename... Ix> ssize_t byte_offset(Ix... index) const {
11796 + template <typename... Ix>
11797 + ssize_t byte_offset(Ix... index) const {
11798 check_dimensions(index...);
11799 return detail::byte_offset_unsafe(strides(), ssize_t(index)...);
11802 void check_writeable() const {
11803 - if (!writeable())
11804 + if (!writeable()) {
11805 throw std::domain_error("array is not writeable");
11809 - // Default, C-style strides
11810 - static std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
11811 - auto ndim = shape.size();
11812 - std::vector<ssize_t> strides(ndim, itemsize);
11814 - for (size_t i = ndim - 1; i > 0; --i)
11815 - strides[i - 1] = strides[i] * shape[i];
11819 - // F-style strides; default when constructing an array_t with `ExtraFlags & f_style`
11820 - static std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
11821 - auto ndim = shape.size();
11822 - std::vector<ssize_t> strides(ndim, itemsize);
11823 - for (size_t i = 1; i < ndim; ++i)
11824 - strides[i] = strides[i - 1] * shape[i - 1];
11828 - template<typename... Ix> void check_dimensions(Ix... index) const {
11829 + template <typename... Ix>
11830 + void check_dimensions(Ix... index) const {
11831 check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...);
11834 - void check_dimensions_impl(ssize_t, const ssize_t*) const { }
11835 + void check_dimensions_impl(ssize_t, const ssize_t *) const {}
11837 - template<typename... Ix> void check_dimensions_impl(ssize_t axis, const ssize_t* shape, ssize_t i, Ix... index) const {
11838 + template <typename... Ix>
11839 + void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const {
11841 - throw index_error(std::string("index ") + std::to_string(i) +
11842 - " is out of bounds for axis " + std::to_string(axis) +
11843 - " with size " + std::to_string(*shape));
11844 + throw index_error(std::string("index ") + std::to_string(i)
11845 + + " is out of bounds for axis " + std::to_string(axis)
11846 + + " with size " + std::to_string(*shape));
11848 check_dimensions_impl(axis + 1, shape + 1, index...);
11850 @@ -799,72 +987,98 @@
11854 -template <typename T, int ExtraFlags = array::forcecast> class array_t : public array {
11855 +template <typename T, int ExtraFlags = array::forcecast>
11856 +class array_t : public array {
11858 struct private_ctor {};
11859 // Delegating constructor needed when both moving and accessing in the same constructor
11860 - array_t(private_ctor, ShapeContainer &&shape, StridesContainer &&strides, const T *ptr, handle base)
11861 + array_t(private_ctor,
11862 + ShapeContainer &&shape,
11863 + StridesContainer &&strides,
11866 : array(std::move(shape), std::move(strides), ptr, base) {}
11869 static_assert(!detail::array_info<T>::is_array, "Array types cannot be used with array_t");
11871 using value_type = T;
11873 array_t() : array(0, static_cast<const T *>(nullptr)) {}
11874 - array_t(handle h, borrowed_t) : array(h, borrowed_t{}) { }
11875 - array_t(handle h, stolen_t) : array(h, stolen_t{}) { }
11876 + array_t(handle h, borrowed_t) : array(h, borrowed_t{}) {}
11877 + array_t(handle h, stolen_t) : array(h, stolen_t{}) {}
11879 PYBIND11_DEPRECATED("Use array_t<T>::ensure() instead")
11880 array_t(handle h, bool is_borrowed) : array(raw_array_t(h.ptr()), stolen_t{}) {
11881 - if (!m_ptr) PyErr_Clear();
11882 - if (!is_borrowed) Py_XDECREF(h.ptr());
11886 + if (!is_borrowed) {
11887 + Py_XDECREF(h.ptr());
11891 + // NOLINTNEXTLINE(google-explicit-constructor)
11892 array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) {
11893 - if (!m_ptr) throw error_already_set();
11895 + throw error_already_set();
11899 - explicit array_t(const buffer_info& info) : array(info) { }
11900 + explicit array_t(const buffer_info &info, handle base = handle()) : array(info, base) {}
11902 - array_t(ShapeContainer shape, StridesContainer strides, const T *ptr = nullptr, handle base = handle())
11903 - : array(std::move(shape), std::move(strides), ptr, base) { }
11904 + array_t(ShapeContainer shape,
11905 + StridesContainer strides,
11906 + const T *ptr = nullptr,
11907 + handle base = handle())
11908 + : array(std::move(shape), std::move(strides), ptr, base) {}
11910 explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())
11911 - : array_t(private_ctor{}, std::move(shape),
11912 - ExtraFlags & f_style ? f_strides(*shape, itemsize()) : c_strides(*shape, itemsize()),
11914 + : array_t(private_ctor{},
11915 + std::move(shape),
11916 + (ExtraFlags & f_style) != 0 ? detail::f_strides(*shape, itemsize())
11917 + : detail::c_strides(*shape, itemsize()),
11921 - explicit array_t(size_t count, const T *ptr = nullptr, handle base = handle())
11922 - : array({count}, {}, ptr, base) { }
11923 + explicit array_t(ssize_t count, const T *ptr = nullptr, handle base = handle())
11924 + : array({count}, {}, ptr, base) {}
11926 - constexpr ssize_t itemsize() const {
11927 - return sizeof(T);
11929 + constexpr ssize_t itemsize() const { return sizeof(T); }
11931 - template<typename... Ix> ssize_t index_at(Ix... index) const {
11932 + template <typename... Ix>
11933 + ssize_t index_at(Ix... index) const {
11934 return offset_at(index...) / itemsize();
11937 - template<typename... Ix> const T* data(Ix... index) const {
11938 - return static_cast<const T*>(array::data(index...));
11939 + template <typename... Ix>
11940 + const T *data(Ix... index) const {
11941 + return static_cast<const T *>(array::data(index...));
11944 - template<typename... Ix> T* mutable_data(Ix... index) {
11945 - return static_cast<T*>(array::mutable_data(index...));
11946 + template <typename... Ix>
11947 + T *mutable_data(Ix... index) {
11948 + return static_cast<T *>(array::mutable_data(index...));
11951 // Reference to element at a given index
11952 - template<typename... Ix> const T& at(Ix... index) const {
11953 - if ((ssize_t) sizeof...(index) != ndim())
11954 + template <typename... Ix>
11955 + const T &at(Ix... index) const {
11956 + if ((ssize_t) sizeof...(index) != ndim()) {
11957 fail_dim_check(sizeof...(index), "index dimension mismatch");
11958 - return *(static_cast<const T*>(array::data()) + byte_offset(ssize_t(index)...) / itemsize());
11960 + return *(static_cast<const T *>(array::data())
11961 + + byte_offset(ssize_t(index)...) / itemsize());
11964 // Mutable reference to element at a given index
11965 - template<typename... Ix> T& mutable_at(Ix... index) {
11966 - if ((ssize_t) sizeof...(index) != ndim())
11967 + template <typename... Ix>
11968 + T &mutable_at(Ix... index) {
11969 + if ((ssize_t) sizeof...(index) != ndim()) {
11970 fail_dim_check(sizeof...(index), "index dimension mismatch");
11971 - return *(static_cast<T*>(array::mutable_data()) + byte_offset(ssize_t(index)...) / itemsize());
11973 + return *(static_cast<T *>(array::mutable_data())
11974 + + byte_offset(ssize_t(index)...) / itemsize());
11978 @@ -873,7 +1087,8 @@
11979 * care: the array must not be destroyed or reshaped for the duration of the returned object,
11980 * and the caller must take care not to access invalid dimensions or dimension indices.
11982 - template <ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
11983 + template <ssize_t Dims = -1>
11984 + detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
11985 return array::mutable_unchecked<T, Dims>();
11988 @@ -884,7 +1099,8 @@
11989 * for the duration of the returned object, and the caller must take care not to access invalid
11990 * dimensions or dimension indices.
11992 - template <ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & {
11993 + template <ssize_t Dims = -1>
11994 + detail::unchecked_reference<T, Dims> unchecked() const & {
11995 return array::unchecked<T, Dims>();
11998 @@ -892,15 +1108,18 @@
11999 /// it). In case of an error, nullptr is returned and the Python error is cleared.
12000 static array_t ensure(handle h) {
12001 auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr()));
12009 static bool check_(handle h) {
12010 const auto &api = detail::npy_api::get();
12011 return api.PyArray_Check_(h.ptr())
12012 - && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr, dtype::of<T>().ptr());
12013 + && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr,
12014 + dtype::of<T>().ptr())
12015 + && detail::check_flags(h.ptr(), ExtraFlags & (array::c_style | array::f_style));
12019 @@ -910,9 +1129,13 @@
12020 PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr");
12023 - return detail::npy_api::get().PyArray_FromAny_(
12024 - ptr, dtype::of<T>().release().ptr(), 0, 0,
12025 - detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
12026 + return detail::npy_api::get().PyArray_FromAny_(ptr,
12027 + dtype::of<T>().release().ptr(),
12030 + detail::npy_api::NPY_ARRAY_ENSUREARRAY_
12036 @@ -923,10 +1146,12 @@
12040 -template <size_t N> struct format_descriptor<char[N]> {
12041 +template <size_t N>
12042 +struct format_descriptor<char[N]> {
12043 static std::string format() { return std::to_string(N) + "s"; }
12045 -template <size_t N> struct format_descriptor<std::array<char, N>> {
12046 +template <size_t N>
12047 +struct format_descriptor<std::array<char, N>> {
12048 static std::string format() { return std::to_string(N) + "s"; }
12051 @@ -942,19 +1167,20 @@
12052 struct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> {
12053 static std::string format() {
12054 using namespace detail;
12055 - static constexpr auto extents = _("(") + array_info<T>::extents + _(")");
12056 + static constexpr auto extents = const_name("(") + array_info<T>::extents + const_name(")");
12057 return extents.text + format_descriptor<remove_all_extents_t<T>>::format();
12061 -NAMESPACE_BEGIN(detail)
12062 +PYBIND11_NAMESPACE_BEGIN(detail)
12063 template <typename T, int ExtraFlags>
12064 struct pyobject_caster<array_t<T, ExtraFlags>> {
12065 using type = array_t<T, ExtraFlags>;
12067 bool load(handle src, bool convert) {
12068 - if (!convert && !type::check_(src))
12069 + if (!convert && !type::check_(src)) {
12072 value = type::ensure(src);
12073 return static_cast<bool>(value);
12075 @@ -967,7 +1193,7 @@
12077 template <typename T>
12078 struct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
12079 - static bool compare(const buffer_info& b) {
12080 + static bool compare(const buffer_info &b) {
12081 return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr());
12084 @@ -977,63 +1203,92 @@
12086 template <typename T>
12087 struct npy_format_descriptor_name<T, enable_if_t<std::is_integral<T>::value>> {
12088 - static constexpr auto name = _<std::is_same<T, bool>::value>(
12089 - _("bool"), _<std::is_signed<T>::value>("int", "uint") + _<sizeof(T)*8>()
12091 + static constexpr auto name = const_name<std::is_same<T, bool>::value>(
12092 + const_name("bool"),
12093 + const_name<std::is_signed<T>::value>("numpy.int", "numpy.uint")
12094 + + const_name<sizeof(T) * 8>());
12097 template <typename T>
12098 struct npy_format_descriptor_name<T, enable_if_t<std::is_floating_point<T>::value>> {
12099 - static constexpr auto name = _<std::is_same<T, float>::value || std::is_same<T, double>::value>(
12100 - _("float") + _<sizeof(T)*8>(), _("longdouble")
12102 + static constexpr auto name = const_name < std::is_same<T, float>::value
12103 + || std::is_same<T, const float>::value
12104 + || std::is_same<T, double>::value
12105 + || std::is_same<T, const double>::value
12106 + > (const_name("numpy.float") + const_name<sizeof(T) * 8>(),
12107 + const_name("numpy.longdouble"));
12110 template <typename T>
12111 struct npy_format_descriptor_name<T, enable_if_t<is_complex<T>::value>> {
12112 - static constexpr auto name = _<std::is_same<typename T::value_type, float>::value
12113 - || std::is_same<typename T::value_type, double>::value>(
12114 - _("complex") + _<sizeof(typename T::value_type)*16>(), _("longcomplex")
12116 + static constexpr auto name = const_name < std::is_same<typename T::value_type, float>::value
12117 + || std::is_same<typename T::value_type, const float>::value
12118 + || std::is_same<typename T::value_type, double>::value
12119 + || std::is_same<typename T::value_type, const double>::value
12120 + > (const_name("numpy.complex")
12121 + + const_name<sizeof(typename T::value_type) * 16>(),
12122 + const_name("numpy.longcomplex"));
12125 template <typename T>
12126 -struct npy_format_descriptor<T, enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>>
12127 +struct npy_format_descriptor<
12129 + enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>>
12130 : npy_format_descriptor_name<T> {
12132 // NB: the order here must match the one in common.h
12133 - constexpr static const int values[15] = {
12134 - npy_api::NPY_BOOL_,
12135 - npy_api::NPY_BYTE_, npy_api::NPY_UBYTE_, npy_api::NPY_SHORT_, npy_api::NPY_USHORT_,
12136 - npy_api::NPY_INT_, npy_api::NPY_UINT_, npy_api::NPY_LONGLONG_, npy_api::NPY_ULONGLONG_,
12137 - npy_api::NPY_FLOAT_, npy_api::NPY_DOUBLE_, npy_api::NPY_LONGDOUBLE_,
12138 - npy_api::NPY_CFLOAT_, npy_api::NPY_CDOUBLE_, npy_api::NPY_CLONGDOUBLE_
12140 + constexpr static const int values[15] = {npy_api::NPY_BOOL_,
12141 + npy_api::NPY_BYTE_,
12142 + npy_api::NPY_UBYTE_,
12143 + npy_api::NPY_INT16_,
12144 + npy_api::NPY_UINT16_,
12145 + npy_api::NPY_INT32_,
12146 + npy_api::NPY_UINT32_,
12147 + npy_api::NPY_INT64_,
12148 + npy_api::NPY_UINT64_,
12149 + npy_api::NPY_FLOAT_,
12150 + npy_api::NPY_DOUBLE_,
12151 + npy_api::NPY_LONGDOUBLE_,
12152 + npy_api::NPY_CFLOAT_,
12153 + npy_api::NPY_CDOUBLE_,
12154 + npy_api::NPY_CLONGDOUBLE_};
12157 static constexpr int value = values[detail::is_fmt_numeric<T>::index];
12159 static pybind11::dtype dtype() {
12160 - if (auto ptr = npy_api::get().PyArray_DescrFromType_(value))
12161 - return reinterpret_borrow<pybind11::dtype>(ptr);
12162 + if (auto *ptr = npy_api::get().PyArray_DescrFromType_(value)) {
12163 + return reinterpret_steal<pybind11::dtype>(ptr);
12165 pybind11_fail("Unsupported buffer format!");
12169 -#define PYBIND11_DECL_CHAR_FMT \
12170 - static constexpr auto name = _("S") + _<N>(); \
12171 - static pybind11::dtype dtype() { return pybind11::dtype(std::string("S") + std::to_string(N)); }
12172 -template <size_t N> struct npy_format_descriptor<char[N]> { PYBIND11_DECL_CHAR_FMT };
12173 -template <size_t N> struct npy_format_descriptor<std::array<char, N>> { PYBIND11_DECL_CHAR_FMT };
12174 +#define PYBIND11_DECL_CHAR_FMT \
12175 + static constexpr auto name = const_name("S") + const_name<N>(); \
12176 + static pybind11::dtype dtype() { \
12177 + return pybind11::dtype(std::string("S") + std::to_string(N)); \
12179 +template <size_t N>
12180 +struct npy_format_descriptor<char[N]> {
12181 + PYBIND11_DECL_CHAR_FMT
12183 +template <size_t N>
12184 +struct npy_format_descriptor<std::array<char, N>> {
12185 + PYBIND11_DECL_CHAR_FMT
12187 #undef PYBIND11_DECL_CHAR_FMT
12189 -template<typename T> struct npy_format_descriptor<T, enable_if_t<array_info<T>::is_array>> {
12190 +template <typename T>
12191 +struct npy_format_descriptor<T, enable_if_t<array_info<T>::is_array>> {
12193 using base_descr = npy_format_descriptor<typename array_info<T>::type>;
12196 static_assert(!array_info<T>::is_empty, "Zero-sized arrays are not supported");
12198 - static constexpr auto name = _("(") + array_info<T>::extents + _(")") + base_descr::name;
12199 + static constexpr auto name
12200 + = const_name("(") + array_info<T>::extents + const_name(")") + base_descr::name;
12201 static pybind11::dtype dtype() {
12203 array_info<T>::append_extents(shape);
12204 @@ -1041,9 +1296,11 @@
12208 -template<typename T> struct npy_format_descriptor<T, enable_if_t<std::is_enum<T>::value>> {
12209 +template <typename T>
12210 +struct npy_format_descriptor<T, enable_if_t<std::is_enum<T>::value>> {
12212 using base_descr = npy_format_descriptor<typename std::underlying_type<T>::type>;
12215 static constexpr auto name = base_descr::name;
12216 static pybind11::dtype dtype() { return base_descr::dtype(); }
12217 @@ -1057,25 +1314,38 @@
12221 -inline PYBIND11_NOINLINE void register_structured_dtype(
12222 - any_container<field_descriptor> fields,
12223 - const std::type_info& tinfo, ssize_t itemsize,
12224 - bool (*direct_converter)(PyObject *, void *&)) {
12225 +PYBIND11_NOINLINE void register_structured_dtype(any_container<field_descriptor> fields,
12226 + const std::type_info &tinfo,
12227 + ssize_t itemsize,
12228 + bool (*direct_converter)(PyObject *, void *&)) {
12230 - auto& numpy_internals = get_numpy_internals();
12231 - if (numpy_internals.get_type_info(tinfo, false))
12232 + auto &numpy_internals = get_numpy_internals();
12233 + if (numpy_internals.get_type_info(tinfo, false)) {
12234 pybind11_fail("NumPy: dtype is already registered");
12237 + // Use ordered fields because order matters as of NumPy 1.14:
12238 + // https://docs.scipy.org/doc/numpy/release.html#multiple-field-indexing-assignment-of-structured-arrays
12239 + std::vector<field_descriptor> ordered_fields(std::move(fields));
12241 + ordered_fields.begin(),
12242 + ordered_fields.end(),
12243 + [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; });
12245 list names, formats, offsets;
12246 - for (auto field : *fields) {
12247 - if (!field.descr)
12248 - pybind11_fail(std::string("NumPy: unsupported field dtype: `") +
12249 - field.name + "` @ " + tinfo.name());
12250 + for (auto &field : ordered_fields) {
12251 + if (!field.descr) {
12252 + pybind11_fail(std::string("NumPy: unsupported field dtype: `") + field.name + "` @ "
12255 names.append(PYBIND11_STR_TYPE(field.name));
12256 formats.append(field.descr);
12257 offsets.append(pybind11::int_(field.offset));
12259 - auto dtype_ptr = pybind11::dtype(names, formats, offsets, itemsize).release().ptr();
12261 + = pybind11::dtype(std::move(names), std::move(formats), std::move(offsets), itemsize)
12265 // There is an existing bug in NumPy (as of v1.11): trailing bytes are
12266 // not encoded explicitly into the format string. This will supposedly
12267 @@ -1084,9 +1354,6 @@
12268 // - https://github.com/numpy/numpy/pull/7798
12269 // Because of this, we won't use numpy's logic to generate buffer format
12270 // strings and will just do it ourselves.
12271 - std::vector<field_descriptor> ordered_fields(std::move(fields));
12272 - std::sort(ordered_fields.begin(), ordered_fields.end(),
12273 - [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; });
12274 ssize_t offset = 0;
12275 std::ostringstream oss;
12276 // mark the structure as unaligned with '^', because numpy and C++ don't
12277 @@ -1095,36 +1362,39 @@
12278 // overriding the endianness. Putting the ^ in front of individual fields
12279 // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049
12281 - for (auto& field : ordered_fields) {
12282 - if (field.offset > offset)
12283 + for (auto &field : ordered_fields) {
12284 + if (field.offset > offset) {
12285 oss << (field.offset - offset) << 'x';
12287 oss << field.format << ':' << field.name << ':';
12288 offset = field.offset + field.size;
12290 - if (itemsize > offset)
12291 + if (itemsize > offset) {
12292 oss << (itemsize - offset) << 'x';
12295 auto format_str = oss.str();
12297 // Sanity check: verify that NumPy properly parses our buffer format string
12298 - auto& api = npy_api::get();
12299 - auto arr = array(buffer_info(nullptr, itemsize, format_str, 1));
12300 - if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr()))
12301 + auto &api = npy_api::get();
12302 + auto arr = array(buffer_info(nullptr, itemsize, format_str, 1));
12303 + if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr())) {
12304 pybind11_fail("NumPy: invalid buffer descriptor!");
12307 auto tindex = std::type_index(tinfo);
12308 - numpy_internals.registered_dtypes[tindex] = { dtype_ptr, format_str };
12309 + numpy_internals.registered_dtypes[tindex] = {dtype_ptr, format_str};
12310 get_internals().direct_conversions[tindex].push_back(direct_converter);
12313 -template <typename T, typename SFINAE> struct npy_format_descriptor {
12314 - static_assert(is_pod_struct<T>::value, "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
12315 +template <typename T, typename SFINAE>
12316 +struct npy_format_descriptor {
12317 + static_assert(is_pod_struct<T>::value,
12318 + "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
12320 static constexpr auto name = make_caster<T>::name;
12322 - static pybind11::dtype dtype() {
12323 - return reinterpret_borrow<pybind11::dtype>(dtype_ptr());
12325 + static pybind11::dtype dtype() { return reinterpret_borrow<pybind11::dtype>(dtype_ptr()); }
12327 static std::string format() {
12328 static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str;
12329 @@ -1132,20 +1402,23 @@
12332 static void register_dtype(any_container<field_descriptor> fields) {
12333 - register_structured_dtype(std::move(fields), typeid(typename std::remove_cv<T>::type),
12334 - sizeof(T), &direct_converter);
12335 + register_structured_dtype(std::move(fields),
12336 + typeid(typename std::remove_cv<T>::type),
12338 + &direct_converter);
12342 - static PyObject* dtype_ptr() {
12343 - static PyObject* ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr;
12344 + static PyObject *dtype_ptr() {
12345 + static PyObject *ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr;
12349 - static bool direct_converter(PyObject *obj, void*& value) {
12350 - auto& api = npy_api::get();
12351 - if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_))
12352 + static bool direct_converter(PyObject *obj, void *&value) {
12353 + auto &api = npy_api::get();
12354 + if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_)) {
12357 if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) {
12358 if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) {
12359 value = ((PyVoidScalarObject_Proxy *) obj)->obval;
12360 @@ -1157,162 +1430,147 @@
12363 #ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
12364 -# define PYBIND11_NUMPY_DTYPE(Type, ...) ((void)0)
12365 -# define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void)0)
12366 +# define PYBIND11_NUMPY_DTYPE(Type, ...) ((void) 0)
12367 +# define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void) 0)
12370 -#define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \
12371 - ::pybind11::detail::field_descriptor { \
12372 - Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \
12373 - ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \
12374 - ::pybind11::detail::npy_format_descriptor<decltype(std::declval<T>().Field)>::dtype() \
12376 +# define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \
12377 + ::pybind11::detail::field_descriptor { \
12378 + Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \
12379 + ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \
12380 + ::pybind11::detail::npy_format_descriptor< \
12381 + decltype(std::declval<T>().Field)>::dtype() \
12384 // Extract name, offset and format descriptor for a struct field
12385 -#define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field)
12386 +# define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, # Field)
12388 // The main idea of this macro is borrowed from https://github.com/swansontec/map-macro
12389 // (C) William Swanson, Paul Fultz
12390 -#define PYBIND11_EVAL0(...) __VA_ARGS__
12391 -#define PYBIND11_EVAL1(...) PYBIND11_EVAL0 (PYBIND11_EVAL0 (PYBIND11_EVAL0 (__VA_ARGS__)))
12392 -#define PYBIND11_EVAL2(...) PYBIND11_EVAL1 (PYBIND11_EVAL1 (PYBIND11_EVAL1 (__VA_ARGS__)))
12393 -#define PYBIND11_EVAL3(...) PYBIND11_EVAL2 (PYBIND11_EVAL2 (PYBIND11_EVAL2 (__VA_ARGS__)))
12394 -#define PYBIND11_EVAL4(...) PYBIND11_EVAL3 (PYBIND11_EVAL3 (PYBIND11_EVAL3 (__VA_ARGS__)))
12395 -#define PYBIND11_EVAL(...) PYBIND11_EVAL4 (PYBIND11_EVAL4 (PYBIND11_EVAL4 (__VA_ARGS__)))
12396 -#define PYBIND11_MAP_END(...)
12397 -#define PYBIND11_MAP_OUT
12398 -#define PYBIND11_MAP_COMMA ,
12399 -#define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
12400 -#define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
12401 -#define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0 (test, next, 0)
12402 -#define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1 (PYBIND11_MAP_GET_END test, next)
12403 -#ifdef _MSC_VER // MSVC is not as eager to expand macros, hence this workaround
12404 -#define PYBIND11_MAP_LIST_NEXT1(test, next) \
12405 - PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0))
12407 -#define PYBIND11_MAP_LIST_NEXT1(test, next) \
12408 - PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)
12410 -#define PYBIND11_MAP_LIST_NEXT(test, next) \
12411 - PYBIND11_MAP_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next)
12412 -#define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
12413 - f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST1) (f, t, peek, __VA_ARGS__)
12414 -#define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
12415 - f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST0) (f, t, peek, __VA_ARGS__)
12416 +# define PYBIND11_EVAL0(...) __VA_ARGS__
12417 +# define PYBIND11_EVAL1(...) PYBIND11_EVAL0(PYBIND11_EVAL0(PYBIND11_EVAL0(__VA_ARGS__)))
12418 +# define PYBIND11_EVAL2(...) PYBIND11_EVAL1(PYBIND11_EVAL1(PYBIND11_EVAL1(__VA_ARGS__)))
12419 +# define PYBIND11_EVAL3(...) PYBIND11_EVAL2(PYBIND11_EVAL2(PYBIND11_EVAL2(__VA_ARGS__)))
12420 +# define PYBIND11_EVAL4(...) PYBIND11_EVAL3(PYBIND11_EVAL3(PYBIND11_EVAL3(__VA_ARGS__)))
12421 +# define PYBIND11_EVAL(...) PYBIND11_EVAL4(PYBIND11_EVAL4(PYBIND11_EVAL4(__VA_ARGS__)))
12422 +# define PYBIND11_MAP_END(...)
12423 +# define PYBIND11_MAP_OUT
12424 +# define PYBIND11_MAP_COMMA ,
12425 +# define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
12426 +# define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
12427 +# define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0(test, next, 0)
12428 +# define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1(PYBIND11_MAP_GET_END test, next)
12429 +# if defined(_MSC_VER) \
12430 + && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround
12431 +# define PYBIND11_MAP_LIST_NEXT1(test, next) \
12432 + PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
12434 +# define PYBIND11_MAP_LIST_NEXT1(test, next) \
12435 + PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
12437 +# define PYBIND11_MAP_LIST_NEXT(test, next) \
12438 + PYBIND11_MAP_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
12439 +# define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
12440 + f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST1)(f, t, peek, __VA_ARGS__)
12441 +# define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
12442 + f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST0)(f, t, peek, __VA_ARGS__)
12443 // PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ...
12444 -#define PYBIND11_MAP_LIST(f, t, ...) \
12445 - PYBIND11_EVAL (PYBIND11_MAP_LIST1 (f, t, __VA_ARGS__, (), 0))
12446 +# define PYBIND11_MAP_LIST(f, t, ...) \
12447 + PYBIND11_EVAL(PYBIND11_MAP_LIST1(f, t, __VA_ARGS__, (), 0))
12449 -#define PYBIND11_NUMPY_DTYPE(Type, ...) \
12450 - ::pybind11::detail::npy_format_descriptor<Type>::register_dtype \
12451 - (::std::vector<::pybind11::detail::field_descriptor> \
12452 - {PYBIND11_MAP_LIST (PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
12455 -#define PYBIND11_MAP2_LIST_NEXT1(test, next) \
12456 - PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0))
12458 -#define PYBIND11_MAP2_LIST_NEXT1(test, next) \
12459 - PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)
12461 -#define PYBIND11_MAP2_LIST_NEXT(test, next) \
12462 - PYBIND11_MAP2_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next)
12463 -#define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
12464 - f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST1) (f, t, peek, __VA_ARGS__)
12465 -#define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
12466 - f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST0) (f, t, peek, __VA_ARGS__)
12467 +# define PYBIND11_NUMPY_DTYPE(Type, ...) \
12468 + ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
12469 + ::std::vector<::pybind11::detail::field_descriptor>{ \
12470 + PYBIND11_MAP_LIST(PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
12472 +# if defined(_MSC_VER) && !defined(__clang__)
12473 +# define PYBIND11_MAP2_LIST_NEXT1(test, next) \
12474 + PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
12476 +# define PYBIND11_MAP2_LIST_NEXT1(test, next) \
12477 + PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
12479 +# define PYBIND11_MAP2_LIST_NEXT(test, next) \
12480 + PYBIND11_MAP2_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
12481 +# define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
12482 + f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST1)(f, t, peek, __VA_ARGS__)
12483 +# define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
12484 + f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST0)(f, t, peek, __VA_ARGS__)
12485 // PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ...
12486 -#define PYBIND11_MAP2_LIST(f, t, ...) \
12487 - PYBIND11_EVAL (PYBIND11_MAP2_LIST1 (f, t, __VA_ARGS__, (), 0))
12488 +# define PYBIND11_MAP2_LIST(f, t, ...) \
12489 + PYBIND11_EVAL(PYBIND11_MAP2_LIST1(f, t, __VA_ARGS__, (), 0))
12491 -#define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
12492 - ::pybind11::detail::npy_format_descriptor<Type>::register_dtype \
12493 - (::std::vector<::pybind11::detail::field_descriptor> \
12494 - {PYBIND11_MAP2_LIST (PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
12495 +# define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
12496 + ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
12497 + ::std::vector<::pybind11::detail::field_descriptor>{ \
12498 + PYBIND11_MAP2_LIST(PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
12500 #endif // __CLION_IDE__
12502 -template <class T>
12503 -using array_iterator = typename std::add_pointer<T>::type;
12505 -template <class T>
12506 -array_iterator<T> array_begin(const buffer_info& buffer) {
12507 - return array_iterator<T>(reinterpret_cast<T*>(buffer.ptr));
12510 -template <class T>
12511 -array_iterator<T> array_end(const buffer_info& buffer) {
12512 - return array_iterator<T>(reinterpret_cast<T*>(buffer.ptr) + buffer.size);
12515 class common_iterator {
12517 using container_type = std::vector<ssize_t>;
12518 using value_type = container_type::value_type;
12519 using size_type = container_type::size_type;
12521 - common_iterator() : p_ptr(0), m_strides() {}
12522 + common_iterator() : m_strides() {}
12524 - common_iterator(void* ptr, const container_type& strides, const container_type& shape)
12525 - : p_ptr(reinterpret_cast<char*>(ptr)), m_strides(strides.size()) {
12526 + common_iterator(void *ptr, const container_type &strides, const container_type &shape)
12527 + : p_ptr(reinterpret_cast<char *>(ptr)), m_strides(strides.size()) {
12528 m_strides.back() = static_cast<value_type>(strides.back());
12529 for (size_type i = m_strides.size() - 1; i != 0; --i) {
12530 size_type j = i - 1;
12531 - value_type s = static_cast<value_type>(shape[i]);
12532 + auto s = static_cast<value_type>(shape[i]);
12533 m_strides[j] = strides[j] + m_strides[i] - strides[i] * s;
12537 - void increment(size_type dim) {
12538 - p_ptr += m_strides[dim];
12540 + void increment(size_type dim) { p_ptr += m_strides[dim]; }
12542 - void* data() const {
12545 + void *data() const { return p_ptr; }
12550 container_type m_strides;
12553 -template <size_t N> class multi_array_iterator {
12554 +template <size_t N>
12555 +class multi_array_iterator {
12557 using container_type = std::vector<ssize_t>;
12559 - multi_array_iterator(const std::array<buffer_info, N> &buffers,
12560 - const container_type &shape)
12561 - : m_shape(shape.size()), m_index(shape.size(), 0),
12562 - m_common_iterator() {
12563 + multi_array_iterator(const std::array<buffer_info, N> &buffers, const container_type &shape)
12564 + : m_shape(shape.size()), m_index(shape.size(), 0), m_common_iterator() {
12566 // Manual copy to avoid conversion warning if using std::copy
12567 - for (size_t i = 0; i < shape.size(); ++i)
12568 + for (size_t i = 0; i < shape.size(); ++i) {
12569 m_shape[i] = shape[i];
12572 container_type strides(shape.size());
12573 - for (size_t i = 0; i < N; ++i)
12574 + for (size_t i = 0; i < N; ++i) {
12575 init_common_iterator(buffers[i], shape, m_common_iterator[i], strides);
12579 - multi_array_iterator& operator++() {
12580 + multi_array_iterator &operator++() {
12581 for (size_t j = m_index.size(); j != 0; --j) {
12583 if (++m_index[i] != m_shape[i]) {
12584 increment_common_iterator(i);
12594 - template <size_t K, class T = void> T* data() const {
12595 - return reinterpret_cast<T*>(m_common_iterator[K].data());
12596 + template <size_t K, class T = void>
12597 + T *data() const {
12598 + return reinterpret_cast<T *>(m_common_iterator[K].data());
12603 using common_iter = common_iterator;
12605 void init_common_iterator(const buffer_info &buffer,
12606 @@ -1325,10 +1583,11 @@
12607 auto strides_iter = strides.rbegin();
12609 while (buffer_shape_iter != buffer.shape.rend()) {
12610 - if (*shape_iter == *buffer_shape_iter)
12611 + if (*shape_iter == *buffer_shape_iter) {
12612 *strides_iter = *buffer_strides_iter;
12618 ++buffer_shape_iter;
12619 ++buffer_strides_iter;
12620 @@ -1341,8 +1600,9 @@
12623 void increment_common_iterator(size_t dim) {
12624 - for (auto &iter : m_common_iterator)
12625 + for (auto &iter : m_common_iterator) {
12626 iter.increment(dim);
12630 container_type m_shape;
12631 @@ -1352,60 +1612,71 @@
12633 enum class broadcast_trivial { non_trivial, c_trivial, f_trivial };
12635 -// Populates the shape and number of dimensions for the set of buffers. Returns a broadcast_trivial
12636 -// enum value indicating whether the broadcast is "trivial"--that is, has each buffer being either a
12637 -// singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous (`f_trivial`) storage
12638 -// buffer; returns `non_trivial` otherwise.
12639 +// Populates the shape and number of dimensions for the set of buffers. Returns a
12640 +// broadcast_trivial enum value indicating whether the broadcast is "trivial"--that is, has each
12641 +// buffer being either a singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous
12642 +// (`f_trivial`) storage buffer; returns `non_trivial` otherwise.
12643 template <size_t N>
12644 -broadcast_trivial broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) {
12645 - ndim = std::accumulate(buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) {
12646 - return std::max(res, buf.ndim);
12649 +broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) {
12650 + ndim = std::accumulate(
12651 + buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) {
12652 + return std::max(res, buf.ndim);
12656 shape.resize((size_t) ndim, 1);
12658 - // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1 or
12659 - // the full size).
12660 + // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1
12661 + // or the full size).
12662 for (size_t i = 0; i < N; ++i) {
12663 auto res_iter = shape.rbegin();
12664 auto end = buffers[i].shape.rend();
12665 - for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end; ++shape_iter, ++res_iter) {
12666 + for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end;
12667 + ++shape_iter, ++res_iter) {
12668 const auto &dim_size_in = *shape_iter;
12669 auto &dim_size_out = *res_iter;
12671 - // Each input dimension can either be 1 or `n`, but `n` values must match across buffers
12672 - if (dim_size_out == 1)
12673 + // Each input dimension can either be 1 or `n`, but `n` values must match across
12675 + if (dim_size_out == 1) {
12676 dim_size_out = dim_size_in;
12677 - else if (dim_size_in != 1 && dim_size_in != dim_size_out)
12678 + } else if (dim_size_in != 1 && dim_size_in != dim_size_out) {
12679 pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!");
12684 bool trivial_broadcast_c = true;
12685 bool trivial_broadcast_f = true;
12686 for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) {
12687 - if (buffers[i].size == 1)
12688 + if (buffers[i].size == 1) {
12692 // Require the same number of dimensions:
12693 - if (buffers[i].ndim != ndim)
12694 + if (buffers[i].ndim != ndim) {
12695 return broadcast_trivial::non_trivial;
12698 // Require all dimensions be full-size:
12699 - if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin()))
12700 + if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin())) {
12701 return broadcast_trivial::non_trivial;
12704 // Check for C contiguity (but only if previous inputs were also C contiguous)
12705 if (trivial_broadcast_c) {
12706 ssize_t expect_stride = buffers[i].itemsize;
12707 auto end = buffers[i].shape.crend();
12708 - for (auto shape_iter = buffers[i].shape.crbegin(), stride_iter = buffers[i].strides.crbegin();
12709 - trivial_broadcast_c && shape_iter != end; ++shape_iter, ++stride_iter) {
12710 - if (expect_stride == *stride_iter)
12711 + for (auto shape_iter = buffers[i].shape.crbegin(),
12712 + stride_iter = buffers[i].strides.crbegin();
12713 + trivial_broadcast_c && shape_iter != end;
12714 + ++shape_iter, ++stride_iter) {
12715 + if (expect_stride == *stride_iter) {
12716 expect_stride *= *shape_iter;
12719 trivial_broadcast_c = false;
12724 @@ -1413,48 +1684,102 @@
12725 if (trivial_broadcast_f) {
12726 ssize_t expect_stride = buffers[i].itemsize;
12727 auto end = buffers[i].shape.cend();
12728 - for (auto shape_iter = buffers[i].shape.cbegin(), stride_iter = buffers[i].strides.cbegin();
12729 - trivial_broadcast_f && shape_iter != end; ++shape_iter, ++stride_iter) {
12730 - if (expect_stride == *stride_iter)
12731 + for (auto shape_iter = buffers[i].shape.cbegin(),
12732 + stride_iter = buffers[i].strides.cbegin();
12733 + trivial_broadcast_f && shape_iter != end;
12734 + ++shape_iter, ++stride_iter) {
12735 + if (expect_stride == *stride_iter) {
12736 expect_stride *= *shape_iter;
12739 trivial_broadcast_f = false;
12746 - trivial_broadcast_c ? broadcast_trivial::c_trivial :
12747 - trivial_broadcast_f ? broadcast_trivial::f_trivial :
12748 - broadcast_trivial::non_trivial;
12749 + return trivial_broadcast_c ? broadcast_trivial::c_trivial
12750 + : trivial_broadcast_f ? broadcast_trivial::f_trivial
12751 + : broadcast_trivial::non_trivial;
12754 template <typename T>
12755 struct vectorize_arg {
12756 - static_assert(!std::is_rvalue_reference<T>::value, "Functions with rvalue reference arguments cannot be vectorized");
12757 + static_assert(!std::is_rvalue_reference<T>::value,
12758 + "Functions with rvalue reference arguments cannot be vectorized");
12759 // The wrapped function gets called with this type:
12760 using call_type = remove_reference_t<T>;
12761 // Is this a vectorized argument?
12762 - static constexpr bool vectorize =
12763 - satisfies_any_of<call_type, std::is_arithmetic, is_complex, std::is_pod>::value &&
12764 - satisfies_none_of<call_type, std::is_pointer, std::is_array, is_std_array, std::is_enum>::value &&
12765 - (!std::is_reference<T>::value ||
12766 - (std::is_lvalue_reference<T>::value && std::is_const<call_type>::value));
12767 + static constexpr bool vectorize
12768 + = satisfies_any_of<call_type, std::is_arithmetic, is_complex, is_pod>::value
12769 + && satisfies_none_of<call_type,
12773 + std::is_enum>::value
12774 + && (!std::is_reference<T>::value
12775 + || (std::is_lvalue_reference<T>::value && std::is_const<call_type>::value));
12776 // Accept this type: an array for vectorized types, otherwise the type as-is:
12777 using type = conditional_t<vectorize, array_t<remove_cv_t<call_type>, array::forcecast>, T>;
12780 +// py::vectorize when a return type is present
12781 +template <typename Func, typename Return, typename... Args>
12782 +struct vectorize_returned_array {
12783 + using Type = array_t<Return>;
12785 + static Type create(broadcast_trivial trivial, const std::vector<ssize_t> &shape) {
12786 + if (trivial == broadcast_trivial::f_trivial) {
12787 + return array_t<Return, array::f_style>(shape);
12789 + return array_t<Return>(shape);
12792 + static Return *mutable_data(Type &array) { return array.mutable_data(); }
12794 + static Return call(Func &f, Args &...args) { return f(args...); }
12796 + static void call(Return *out, size_t i, Func &f, Args &...args) { out[i] = f(args...); }
12799 +// py::vectorize when a return type is not present
12800 +template <typename Func, typename... Args>
12801 +struct vectorize_returned_array<Func, void, Args...> {
12802 + using Type = none;
12804 + static Type create(broadcast_trivial, const std::vector<ssize_t> &) { return none(); }
12806 + static void *mutable_data(Type &) { return nullptr; }
12808 + static detail::void_type call(Func &f, Args &...args) {
12813 + static void call(void *, size_t, Func &f, Args &...args) { f(args...); }
12816 template <typename Func, typename Return, typename... Args>
12817 struct vectorize_helper {
12819 +// NVCC for some reason breaks if NVectorized is private
12826 static constexpr size_t N = sizeof...(Args);
12827 static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...);
12828 - static_assert(NVectorized >= 1,
12829 - "pybind11::vectorize(...) requires a function with at least one vectorizable argument");
12831 + NVectorized >= 1,
12832 + "pybind11::vectorize(...) requires a function with at least one vectorizable argument");
12835 - template <typename T>
12836 - explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) { }
12837 + template <typename T,
12838 + // SFINAE to prevent shadowing the copy constructor.
12839 + typename = detail::enable_if_t<
12840 + !std::is_same<vectorize_helper, typename std::decay<T>::type>::value>>
12841 + explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) {}
12843 object operator()(typename vectorize_arg<Args>::type... args) {
12844 return run(args...,
12845 @@ -1466,10 +1791,13 @@
12847 remove_reference_t<Func> f;
12849 - // Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling with "/permissive-" flag
12850 - // when arg_call_types is manually inlined.
12851 + // Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling
12852 + // with "/permissive-" flag when arg_call_types is manually inlined.
12853 using arg_call_types = std::tuple<typename vectorize_arg<Args>::call_type...>;
12854 - template <size_t Index> using param_n_t = typename std::tuple_element<Index, arg_call_types>::type;
12855 + template <size_t Index>
12856 + using param_n_t = typename std::tuple_element<Index, arg_call_types>::type;
12858 + using returned_array = vectorize_returned_array<Func, Return, Args...>;
12860 // Runs a vectorized function given arguments tuple and three index sequences:
12861 // - Index is the full set of 0 ... (N-1) argument indices;
12862 @@ -1478,44 +1806,51 @@
12863 // - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that
12864 // we can store vectorized buffer_infos in an array (argument VIndex has its buffer at
12865 // index BIndex in the array).
12866 - template <size_t... Index, size_t... VIndex, size_t... BIndex> object run(
12867 - typename vectorize_arg<Args>::type &...args,
12868 - index_sequence<Index...> i_seq, index_sequence<VIndex...> vi_seq, index_sequence<BIndex...> bi_seq) {
12869 + template <size_t... Index, size_t... VIndex, size_t... BIndex>
12870 + object run(typename vectorize_arg<Args>::type &...args,
12871 + index_sequence<Index...> i_seq,
12872 + index_sequence<VIndex...> vi_seq,
12873 + index_sequence<BIndex...> bi_seq) {
12875 // Pointers to values the function was called with; the vectorized ones set here will start
12876 // out as array_t<T> pointers, but they will be changed them to T pointers before we make
12877 // call the wrapped function. Non-vectorized pointers are left as-is.
12878 - std::array<void *, N> params{{ &args... }};
12879 + std::array<void *, N> params{{&args...}};
12881 // The array of `buffer_info`s of vectorized arguments:
12882 - std::array<buffer_info, NVectorized> buffers{{ reinterpret_cast<array *>(params[VIndex])->request()... }};
12883 + std::array<buffer_info, NVectorized> buffers{
12884 + {reinterpret_cast<array *>(params[VIndex])->request()...}};
12886 /* Determine dimensions parameters of output array */
12888 std::vector<ssize_t> shape(0);
12889 auto trivial = broadcast(buffers, nd, shape);
12890 - size_t ndim = (size_t) nd;
12891 + auto ndim = (size_t) nd;
12893 - size_t size = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>());
12895 + = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>());
12897 // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e.
12898 // not wrapped in an array).
12899 if (size == 1 && ndim == 0) {
12900 PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr);
12901 - return cast(f(*reinterpret_cast<param_n_t<Index> *>(params[Index])...));
12903 + returned_array::call(f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...));
12906 - array_t<Return> result;
12907 - if (trivial == broadcast_trivial::f_trivial) result = array_t<Return, array::f_style>(shape);
12908 - else result = array_t<Return>(shape);
12909 + auto result = returned_array::create(trivial, shape);
12911 - if (size == 0) return std::move(result);
12913 + return std::move(result);
12916 /* Call the function */
12917 - if (trivial == broadcast_trivial::non_trivial)
12918 - apply_broadcast(buffers, params, result, i_seq, vi_seq, bi_seq);
12920 - apply_trivial(buffers, params, result.mutable_data(), size, i_seq, vi_seq, bi_seq);
12921 + auto *mutable_data = returned_array::mutable_data(result);
12922 + if (trivial == broadcast_trivial::non_trivial) {
12923 + apply_broadcast(buffers, params, mutable_data, size, shape, i_seq, vi_seq, bi_seq);
12925 + apply_trivial(buffers, params, mutable_data, size, i_seq, vi_seq, bi_seq);
12928 return std::move(result);
12930 @@ -1525,86 +1860,99 @@
12931 std::array<void *, N> ¶ms,
12934 - index_sequence<Index...>, index_sequence<VIndex...>, index_sequence<BIndex...>) {
12935 + index_sequence<Index...>,
12936 + index_sequence<VIndex...>,
12937 + index_sequence<BIndex...>) {
12939 // Initialize an array of mutable byte references and sizes with references set to the
12940 // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size
12941 // (except for singletons, which get an increment of 0).
12942 - std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{{
12943 - std::pair<unsigned char *&, const size_t>(
12944 - reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr),
12945 - buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>)
12948 + std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{
12949 + {std::pair<unsigned char *&, const size_t>(
12950 + reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr),
12951 + buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>))...}};
12953 for (size_t i = 0; i < size; ++i) {
12954 - out[i] = f(*reinterpret_cast<param_n_t<Index> *>(params[Index])...);
12955 - for (auto &x : vecparams) x.first += x.second;
12956 + returned_array::call(
12957 + out, i, f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...);
12958 + for (auto &x : vecparams) {
12959 + x.first += x.second;
12964 template <size_t... Index, size_t... VIndex, size_t... BIndex>
12965 void apply_broadcast(std::array<buffer_info, NVectorized> &buffers,
12966 std::array<void *, N> ¶ms,
12967 - array_t<Return> &output_array,
12968 - index_sequence<Index...>, index_sequence<VIndex...>, index_sequence<BIndex...>) {
12970 - buffer_info output = output_array.request();
12971 - multi_array_iterator<NVectorized> input_iter(buffers, output.shape);
12973 - for (array_iterator<Return> iter = array_begin<Return>(output), end = array_end<Return>(output);
12975 - ++iter, ++input_iter) {
12976 - PYBIND11_EXPAND_SIDE_EFFECTS((
12977 - params[VIndex] = input_iter.template data<BIndex>()
12979 - *iter = f(*reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...);
12982 + const std::vector<ssize_t> &output_shape,
12983 + index_sequence<Index...>,
12984 + index_sequence<VIndex...>,
12985 + index_sequence<BIndex...>) {
12987 + multi_array_iterator<NVectorized> input_iter(buffers, output_shape);
12989 + for (size_t i = 0; i < size; ++i, ++input_iter) {
12990 + PYBIND11_EXPAND_SIDE_EFFECTS((params[VIndex] = input_iter.template data<BIndex>()));
12991 + returned_array::call(
12992 + out, i, f, *reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...);
12997 template <typename Func, typename Return, typename... Args>
12998 -vectorize_helper<Func, Return, Args...>
12999 -vectorize_extractor(const Func &f, Return (*) (Args ...)) {
13000 +vectorize_helper<Func, Return, Args...> vectorize_extractor(const Func &f, Return (*)(Args...)) {
13001 return detail::vectorize_helper<Func, Return, Args...>(f);
13004 -template <typename T, int Flags> struct handle_type_name<array_t<T, Flags>> {
13005 - static constexpr auto name = _("numpy.ndarray[") + npy_format_descriptor<T>::name + _("]");
13006 +template <typename T, int Flags>
13007 +struct handle_type_name<array_t<T, Flags>> {
13008 + static constexpr auto name
13009 + = const_name("numpy.ndarray[") + npy_format_descriptor<T>::name + const_name("]");
13012 -NAMESPACE_END(detail)
13013 +PYBIND11_NAMESPACE_END(detail)
13015 // Vanilla pointer vectorizer:
13016 template <typename Return, typename... Args>
13017 -detail::vectorize_helper<Return (*)(Args...), Return, Args...>
13018 -vectorize(Return (*f) (Args ...)) {
13019 +detail::vectorize_helper<Return (*)(Args...), Return, Args...> vectorize(Return (*f)(Args...)) {
13020 return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f);
13023 // lambda vectorizer:
13024 template <typename Func, detail::enable_if_t<detail::is_lambda<Func>::value, int> = 0>
13025 -auto vectorize(Func &&f) -> decltype(
13026 - detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr)) {
13027 - return detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr);
13028 +auto vectorize(Func &&f)
13029 + -> decltype(detail::vectorize_extractor(std::forward<Func>(f),
13030 + (detail::function_signature_t<Func> *) nullptr)) {
13031 + return detail::vectorize_extractor(std::forward<Func>(f),
13032 + (detail::function_signature_t<Func> *) nullptr);
13035 // Vectorize a class method (non-const):
13036 -template <typename Return, typename Class, typename... Args,
13037 - typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())), Return, Class *, Args...>>
13038 +template <typename Return,
13040 + typename... Args,
13041 + typename Helper = detail::vectorize_helper<
13042 + decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())),
13046 Helper vectorize(Return (Class::*f)(Args...)) {
13047 return Helper(std::mem_fn(f));
13050 // Vectorize a class method (const):
13051 -template <typename Return, typename Class, typename... Args,
13052 - typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())), Return, const Class *, Args...>>
13053 +template <typename Return,
13055 + typename... Args,
13056 + typename Helper = detail::vectorize_helper<
13057 + decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())),
13061 Helper vectorize(Return (Class::*f)(Args...) const) {
13062 return Helper(std::mem_fn(f));
13065 -NAMESPACE_END(PYBIND11_NAMESPACE)
13067 -#if defined(_MSC_VER)
13068 -#pragma warning(pop)
13070 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
13071 diff -Nur pythia8309.orig/plugins/python/include/pybind11/operators.h pythia8309/plugins/python/include/pybind11/operators.h
13072 --- pythia8309.orig/plugins/python/include/pybind11/operators.h 2023-02-16 18:12:45.000000000 +0100
13073 +++ pythia8309/plugins/python/include/pybind11/operators.h 2023-03-13 09:52:25.466021616 +0100
13074 @@ -11,24 +11,55 @@
13076 #include "pybind11.h"
13078 -#if defined(__clang__) && !defined(__INTEL_COMPILER)
13079 -# pragma clang diagnostic ignored "-Wunsequenced" // multiple unsequenced modifications to 'self' (when using def(py::self OP Type()))
13080 -#elif defined(_MSC_VER)
13081 -# pragma warning(push)
13082 -# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
13085 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
13086 -NAMESPACE_BEGIN(detail)
13087 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
13088 +PYBIND11_NAMESPACE_BEGIN(detail)
13090 /// Enumeration with all supported operator types
13092 - op_add, op_sub, op_mul, op_div, op_mod, op_divmod, op_pow, op_lshift,
13093 - op_rshift, op_and, op_xor, op_or, op_neg, op_pos, op_abs, op_invert,
13094 - op_int, op_long, op_float, op_str, op_cmp, op_gt, op_ge, op_lt, op_le,
13095 - op_eq, op_ne, op_iadd, op_isub, op_imul, op_idiv, op_imod, op_ilshift,
13096 - op_irshift, op_iand, op_ixor, op_ior, op_complex, op_bool, op_nonzero,
13097 - op_repr, op_truediv, op_itruediv, op_hash
13144 enum op_type : int {
13145 @@ -37,132 +68,153 @@
13146 op_u /* unary operator */
13149 -struct self_t { };
13151 static const self_t self = self_t();
13153 /// Type for an unused type slot
13154 -struct undefined_t { };
13155 +struct undefined_t {};
13157 /// Don't warn about an unused variable
13158 inline self_t __self() { return self; }
13160 /// base template of operator implementations
13161 -template <op_id, op_type, typename B, typename L, typename R> struct op_impl { };
13162 +template <op_id, op_type, typename B, typename L, typename R>
13163 +struct op_impl {};
13165 /// Operator implementation generator
13166 -template <op_id id, op_type ot, typename L, typename R> struct op_ {
13167 - template <typename Class, typename... Extra> void execute(Class &cl, const Extra&... extra) const {
13168 +template <op_id id, op_type ot, typename L, typename R>
13170 + template <typename Class, typename... Extra>
13171 + void execute(Class &cl, const Extra &...extra) const {
13172 using Base = typename Class::type;
13173 using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>;
13174 using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>;
13175 using op = op_impl<id, ot, Base, L_type, R_type>;
13176 cl.def(op::name(), &op::execute, is_operator(), extra...);
13177 - #if PY_MAJOR_VERSION < 3
13178 - if (id == op_truediv || id == op_itruediv)
13179 - cl.def(id == op_itruediv ? "__idiv__" : ot == op_l ? "__div__" : "__rdiv__",
13180 - &op::execute, is_operator(), extra...);
13182 +#if PY_MAJOR_VERSION < 3
13183 + if (PYBIND11_SILENCE_MSVC_C4127(id == op_truediv)
13184 + || PYBIND11_SILENCE_MSVC_C4127(id == op_itruediv))
13185 + cl.def(id == op_itruediv ? "__idiv__"
13186 + : ot == op_l ? "__div__"
13193 - template <typename Class, typename... Extra> void execute_cast(Class &cl, const Extra&... extra) const {
13194 + template <typename Class, typename... Extra>
13195 + void execute_cast(Class &cl, const Extra &...extra) const {
13196 using Base = typename Class::type;
13197 using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>;
13198 using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>;
13199 using op = op_impl<id, ot, Base, L_type, R_type>;
13200 cl.def(op::name(), &op::execute_cast, is_operator(), extra...);
13201 - #if PY_MAJOR_VERSION < 3
13202 +#if PY_MAJOR_VERSION < 3
13203 if (id == op_truediv || id == op_itruediv)
13204 - cl.def(id == op_itruediv ? "__idiv__" : ot == op_l ? "__div__" : "__rdiv__",
13205 - &op::execute, is_operator(), extra...);
13207 + cl.def(id == op_itruediv ? "__idiv__"
13208 + : ot == op_l ? "__div__"
13217 -#define PYBIND11_BINARY_OPERATOR(id, rid, op, expr) \
13218 -template <typename B, typename L, typename R> struct op_impl<op_##id, op_l, B, L, R> { \
13219 - static char const* name() { return "__" #id "__"; } \
13220 - static auto execute(const L &l, const R &r) -> decltype(expr) { return (expr); } \
13221 - static B execute_cast(const L &l, const R &r) { return B(expr); } \
13223 -template <typename B, typename L, typename R> struct op_impl<op_##id, op_r, B, L, R> { \
13224 - static char const* name() { return "__" #rid "__"; } \
13225 - static auto execute(const R &r, const L &l) -> decltype(expr) { return (expr); } \
13226 - static B execute_cast(const R &r, const L &l) { return B(expr); } \
13228 -inline op_<op_##id, op_l, self_t, self_t> op(const self_t &, const self_t &) { \
13229 - return op_<op_##id, op_l, self_t, self_t>(); \
13231 -template <typename T> op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \
13232 - return op_<op_##id, op_l, self_t, T>(); \
13234 -template <typename T> op_<op_##id, op_r, T, self_t> op(const T &, const self_t &) { \
13235 - return op_<op_##id, op_r, T, self_t>(); \
13238 -#define PYBIND11_INPLACE_OPERATOR(id, op, expr) \
13239 -template <typename B, typename L, typename R> struct op_impl<op_##id, op_l, B, L, R> { \
13240 - static char const* name() { return "__" #id "__"; } \
13241 - static auto execute(L &l, const R &r) -> decltype(expr) { return expr; } \
13242 - static B execute_cast(L &l, const R &r) { return B(expr); } \
13244 -template <typename T> op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \
13245 - return op_<op_##id, op_l, self_t, T>(); \
13248 -#define PYBIND11_UNARY_OPERATOR(id, op, expr) \
13249 -template <typename B, typename L> struct op_impl<op_##id, op_u, B, L, undefined_t> { \
13250 - static char const* name() { return "__" #id "__"; } \
13251 - static auto execute(const L &l) -> decltype(expr) { return expr; } \
13252 - static B execute_cast(const L &l) { return B(expr); } \
13254 -inline op_<op_##id, op_u, self_t, undefined_t> op(const self_t &) { \
13255 - return op_<op_##id, op_u, self_t, undefined_t>(); \
13258 -PYBIND11_BINARY_OPERATOR(sub, rsub, operator-, l - r)
13259 -PYBIND11_BINARY_OPERATOR(add, radd, operator+, l + r)
13260 -PYBIND11_BINARY_OPERATOR(mul, rmul, operator*, l * r)
13261 -PYBIND11_BINARY_OPERATOR(truediv, rtruediv, operator/, l / r)
13262 -PYBIND11_BINARY_OPERATOR(mod, rmod, operator%, l % r)
13263 -PYBIND11_BINARY_OPERATOR(lshift, rlshift, operator<<, l << r)
13264 -PYBIND11_BINARY_OPERATOR(rshift, rrshift, operator>>, l >> r)
13265 -PYBIND11_BINARY_OPERATOR(and, rand, operator&, l & r)
13266 -PYBIND11_BINARY_OPERATOR(xor, rxor, operator^, l ^ r)
13267 -PYBIND11_BINARY_OPERATOR(eq, eq, operator==, l == r)
13268 -PYBIND11_BINARY_OPERATOR(ne, ne, operator!=, l != r)
13269 -PYBIND11_BINARY_OPERATOR(or, ror, operator|, l | r)
13270 -PYBIND11_BINARY_OPERATOR(gt, lt, operator>, l > r)
13271 -PYBIND11_BINARY_OPERATOR(ge, le, operator>=, l >= r)
13272 -PYBIND11_BINARY_OPERATOR(lt, gt, operator<, l < r)
13273 -PYBIND11_BINARY_OPERATOR(le, ge, operator<=, l <= r)
13274 -//PYBIND11_BINARY_OPERATOR(pow, rpow, pow, std::pow(l, r))
13275 -PYBIND11_INPLACE_OPERATOR(iadd, operator+=, l += r)
13276 -PYBIND11_INPLACE_OPERATOR(isub, operator-=, l -= r)
13277 -PYBIND11_INPLACE_OPERATOR(imul, operator*=, l *= r)
13278 -PYBIND11_INPLACE_OPERATOR(itruediv, operator/=, l /= r)
13279 -PYBIND11_INPLACE_OPERATOR(imod, operator%=, l %= r)
13280 -PYBIND11_INPLACE_OPERATOR(ilshift, operator<<=, l <<= r)
13281 -PYBIND11_INPLACE_OPERATOR(irshift, operator>>=, l >>= r)
13282 -PYBIND11_INPLACE_OPERATOR(iand, operator&=, l &= r)
13283 -PYBIND11_INPLACE_OPERATOR(ixor, operator^=, l ^= r)
13284 -PYBIND11_INPLACE_OPERATOR(ior, operator|=, l |= r)
13285 -PYBIND11_UNARY_OPERATOR(neg, operator-, -l)
13286 -PYBIND11_UNARY_OPERATOR(pos, operator+, +l)
13287 -PYBIND11_UNARY_OPERATOR(abs, abs, std::abs(l))
13288 -PYBIND11_UNARY_OPERATOR(hash, hash, std::hash<L>()(l))
13289 -PYBIND11_UNARY_OPERATOR(invert, operator~, (~l))
13290 -PYBIND11_UNARY_OPERATOR(bool, operator!, !!l)
13291 -PYBIND11_UNARY_OPERATOR(int, int_, (int) l)
13292 -PYBIND11_UNARY_OPERATOR(float, float_, (double) l)
13293 +#define PYBIND11_BINARY_OPERATOR(id, rid, op, expr) \
13294 + template <typename B, typename L, typename R> \
13295 + struct op_impl<op_##id, op_l, B, L, R> { \
13296 + static char const *name() { return "__" #id "__"; } \
13297 + static auto execute(const L &l, const R &r) -> decltype(expr) { return (expr); } \
13298 + static B execute_cast(const L &l, const R &r) { return B(expr); } \
13300 + template <typename B, typename L, typename R> \
13301 + struct op_impl<op_##id, op_r, B, L, R> { \
13302 + static char const *name() { return "__" #rid "__"; } \
13303 + static auto execute(const R &r, const L &l) -> decltype(expr) { return (expr); } \
13304 + static B execute_cast(const R &r, const L &l) { return B(expr); } \
13306 + inline op_<op_##id, op_l, self_t, self_t> op(const self_t &, const self_t &) { \
13307 + return op_<op_##id, op_l, self_t, self_t>(); \
13309 + template <typename T> \
13310 + op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \
13311 + return op_<op_##id, op_l, self_t, T>(); \
13313 + template <typename T> \
13314 + op_<op_##id, op_r, T, self_t> op(const T &, const self_t &) { \
13315 + return op_<op_##id, op_r, T, self_t>(); \
13318 +#define PYBIND11_INPLACE_OPERATOR(id, op, expr) \
13319 + template <typename B, typename L, typename R> \
13320 + struct op_impl<op_##id, op_l, B, L, R> { \
13321 + static char const *name() { return "__" #id "__"; } \
13322 + static auto execute(L &l, const R &r) -> decltype(expr) { return expr; } \
13323 + static B execute_cast(L &l, const R &r) { return B(expr); } \
13325 + template <typename T> \
13326 + op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \
13327 + return op_<op_##id, op_l, self_t, T>(); \
13330 +#define PYBIND11_UNARY_OPERATOR(id, op, expr) \
13331 + template <typename B, typename L> \
13332 + struct op_impl<op_##id, op_u, B, L, undefined_t> { \
13333 + static char const *name() { return "__" #id "__"; } \
13334 + static auto execute(const L &l) -> decltype(expr) { return expr; } \
13335 + static B execute_cast(const L &l) { return B(expr); } \
13337 + inline op_<op_##id, op_u, self_t, undefined_t> op(const self_t &) { \
13338 + return op_<op_##id, op_u, self_t, undefined_t>(); \
13341 +PYBIND11_BINARY_OPERATOR(sub, rsub, operator-, l - r)
13342 +PYBIND11_BINARY_OPERATOR(add, radd, operator+, l + r)
13343 +PYBIND11_BINARY_OPERATOR(mul, rmul, operator*, l *r)
13344 +PYBIND11_BINARY_OPERATOR(truediv, rtruediv, operator/, l / r)
13345 +PYBIND11_BINARY_OPERATOR(mod, rmod, operator%, l % r)
13346 +PYBIND11_BINARY_OPERATOR(lshift, rlshift, operator<<, l << r)
13347 +PYBIND11_BINARY_OPERATOR(rshift, rrshift, operator>>, l >> r)
13348 +PYBIND11_BINARY_OPERATOR(and, rand, operator&, l &r)
13349 +PYBIND11_BINARY_OPERATOR(xor, rxor, operator^, l ^ r)
13350 +PYBIND11_BINARY_OPERATOR(eq, eq, operator==, l == r)
13351 +PYBIND11_BINARY_OPERATOR(ne, ne, operator!=, l != r)
13352 +PYBIND11_BINARY_OPERATOR(or, ror, operator|, l | r)
13353 +PYBIND11_BINARY_OPERATOR(gt, lt, operator>, l > r)
13354 +PYBIND11_BINARY_OPERATOR(ge, le, operator>=, l >= r)
13355 +PYBIND11_BINARY_OPERATOR(lt, gt, operator<, l < r)
13356 +PYBIND11_BINARY_OPERATOR(le, ge, operator<=, l <= r)
13357 +// PYBIND11_BINARY_OPERATOR(pow, rpow, pow, std::pow(l, r))
13358 +PYBIND11_INPLACE_OPERATOR(iadd, operator+=, l += r)
13359 +PYBIND11_INPLACE_OPERATOR(isub, operator-=, l -= r)
13360 +PYBIND11_INPLACE_OPERATOR(imul, operator*=, l *= r)
13361 +PYBIND11_INPLACE_OPERATOR(itruediv, operator/=, l /= r)
13362 +PYBIND11_INPLACE_OPERATOR(imod, operator%=, l %= r)
13363 +PYBIND11_INPLACE_OPERATOR(ilshift, operator<<=, l <<= r)
13364 +PYBIND11_INPLACE_OPERATOR(irshift, operator>>=, l >>= r)
13365 +PYBIND11_INPLACE_OPERATOR(iand, operator&=, l &= r)
13366 +PYBIND11_INPLACE_OPERATOR(ixor, operator^=, l ^= r)
13367 +PYBIND11_INPLACE_OPERATOR(ior, operator|=, l |= r)
13368 +PYBIND11_UNARY_OPERATOR(neg, operator-, -l)
13369 +PYBIND11_UNARY_OPERATOR(pos, operator+, +l)
13370 +// WARNING: This usage of `abs` should only be done for existing STL overloads.
13371 +// Adding overloads directly in to the `std::` namespace is advised against:
13372 +// https://en.cppreference.com/w/cpp/language/extending_std
13373 +PYBIND11_UNARY_OPERATOR(abs, abs, std::abs(l))
13374 +PYBIND11_UNARY_OPERATOR(hash, hash, std::hash<L>()(l))
13375 +PYBIND11_UNARY_OPERATOR(invert, operator~, (~l))
13376 +PYBIND11_UNARY_OPERATOR(bool, operator!, !!l)
13377 +PYBIND11_UNARY_OPERATOR(int, int_, (int) l)
13378 +PYBIND11_UNARY_OPERATOR(float, float_, (double) l)
13380 #undef PYBIND11_BINARY_OPERATOR
13381 #undef PYBIND11_INPLACE_OPERATOR
13382 #undef PYBIND11_UNARY_OPERATOR
13383 -NAMESPACE_END(detail)
13384 +PYBIND11_NAMESPACE_END(detail)
13386 using detail::self;
13387 +// Add named operators so that they are accessible via `py::`.
13388 +using detail::hash;
13390 -NAMESPACE_END(PYBIND11_NAMESPACE)
13392 -#if defined(_MSC_VER)
13393 -# pragma warning(pop)
13395 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
13396 diff -Nur pythia8309.orig/plugins/python/include/pybind11/options.h pythia8309/plugins/python/include/pybind11/options.h
13397 --- pythia8309.orig/plugins/python/include/pybind11/options.h 2023-02-16 18:12:45.000000000 +0100
13398 +++ pythia8309/plugins/python/include/pybind11/options.h 2023-03-13 09:52:25.466021616 +0100
13399 @@ -11,47 +11,58 @@
13401 #include "detail/common.h"
13403 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
13404 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
13409 // Default RAII constructor, which leaves settings as they currently are.
13410 options() : previous_state(global_state()) {}
13412 // Class is non-copyable.
13413 - options(const options&) = delete;
13414 - options& operator=(const options&) = delete;
13415 + options(const options &) = delete;
13416 + options &operator=(const options &) = delete;
13418 // Destructor, which restores settings that were in effect before.
13420 - global_state() = previous_state;
13422 + ~options() { global_state() = previous_state; }
13424 // Setter methods (affect the global state):
13426 - options& disable_user_defined_docstrings() & { global_state().show_user_defined_docstrings = false; return *this; }
13427 + options &disable_user_defined_docstrings() & {
13428 + global_state().show_user_defined_docstrings = false;
13432 - options& enable_user_defined_docstrings() & { global_state().show_user_defined_docstrings = true; return *this; }
13433 + options &enable_user_defined_docstrings() & {
13434 + global_state().show_user_defined_docstrings = true;
13438 - options& disable_function_signatures() & { global_state().show_function_signatures = false; return *this; }
13439 + options &disable_function_signatures() & {
13440 + global_state().show_function_signatures = false;
13444 - options& enable_function_signatures() & { global_state().show_function_signatures = true; return *this; }
13445 + options &enable_function_signatures() & {
13446 + global_state().show_function_signatures = true;
13450 // Getter methods (return the global state):
13452 - static bool show_user_defined_docstrings() { return global_state().show_user_defined_docstrings; }
13453 + static bool show_user_defined_docstrings() {
13454 + return global_state().show_user_defined_docstrings;
13457 static bool show_function_signatures() { return global_state().show_function_signatures; }
13459 // This type is not meant to be allocated on the heap.
13460 - void* operator new(size_t) = delete;
13461 + void *operator new(size_t) = delete;
13466 - bool show_user_defined_docstrings = true; //< Include user-supplied texts in docstrings.
13467 - bool show_function_signatures = true; //< Include auto-generated function signatures in docstrings.
13468 + bool show_user_defined_docstrings = true; //< Include user-supplied texts in docstrings.
13469 + bool show_function_signatures = true; //< Include auto-generated function signatures
13470 + // in docstrings.
13473 static state &global_state() {
13475 state previous_state;
13478 -NAMESPACE_END(PYBIND11_NAMESPACE)
13479 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
13480 diff -Nur pythia8309.orig/plugins/python/include/pybind11/pybind11.h pythia8309/plugins/python/include/pybind11/pybind11.h
13481 --- pythia8309.orig/plugins/python/include/pybind11/pybind11.h 2023-02-16 18:12:45.000000000 +0100
13482 +++ pythia8309/plugins/python/include/pybind11/pybind11.h 2023-03-13 09:52:25.470021625 +0100
13483 @@ -10,150 +10,245 @@
13487 -#if defined(__INTEL_COMPILER)
13488 -# pragma warning push
13489 -# pragma warning disable 68 // integer conversion resulted in a change of sign
13490 -# pragma warning disable 186 // pointless comparison of unsigned integer with zero
13491 -# pragma warning disable 878 // incompatible exception specifications
13492 -# pragma warning disable 1334 // the "template" keyword used for syntactic disambiguation may only be used within a template
13493 -# pragma warning disable 1682 // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem)
13494 -# pragma warning disable 1786 // function "strdup" was declared deprecated
13495 -# pragma warning disable 1875 // offsetof applied to non-POD (Plain Old Data) types is nonstandard
13496 -# pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
13497 -#elif defined(_MSC_VER)
13498 -# pragma warning(push)
13499 -# pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
13500 -# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
13501 -# pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
13502 -# pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
13503 -# pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
13504 -# pragma warning(disable: 4702) // warning C4702: unreachable code
13505 -# pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
13506 -#elif defined(__GNUG__) && !defined(__clang__)
13507 -# pragma GCC diagnostic push
13508 -# pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
13509 -# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
13510 -# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
13511 -# pragma GCC diagnostic ignored "-Wstrict-aliasing"
13512 -# pragma GCC diagnostic ignored "-Wattributes"
13513 -# if __GNUC__ >= 7
13514 +#include "detail/class.h"
13515 +#include "detail/init.h"
13518 +#include "options.h"
13520 +#include <cstdlib>
13521 +#include <cstring>
13525 +#include <utility>
13528 +#if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914))
13529 +# define PYBIND11_STD_LAUNDER std::launder
13530 +# define PYBIND11_HAS_STD_LAUNDER 1
13532 +# define PYBIND11_STD_LAUNDER
13533 +# define PYBIND11_HAS_STD_LAUNDER 0
13535 +#if defined(__GNUG__) && !defined(__clang__)
13536 +# include <cxxabi.h>
13539 +/* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning
13540 + This warning is about ABI compatibility, not code health.
13541 + It is only actually needed in a couple places, but apparently GCC 7 "generates this warning if
13542 + and only if the first template instantiation ... involves noexcept" [stackoverflow], therefore
13543 + it could get triggered from seemingly random places, depending on user code.
13544 + No other GCC version generates this warning.
13546 +#if defined(__GNUC__) && __GNUC__ == 7
13547 +# pragma GCC diagnostic push
13548 # pragma GCC diagnostic ignored "-Wnoexcept-type"
13553 -#include "options.h"
13554 -#include "detail/class.h"
13555 -#include "detail/init.h"
13556 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
13558 +PYBIND11_NAMESPACE_BEGIN(detail)
13560 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
13561 +// Apply all the extensions translators from a list
13562 +// Return true if one of the translators completed without raising an exception
13563 +// itself. Return of false indicates that if there are other translators
13564 +// available, they should be tried.
13565 +inline bool apply_exception_translators(std::forward_list<ExceptionTranslator> &translators) {
13566 + auto last_exception = std::current_exception();
13568 + for (auto &translator : translators) {
13570 + translator(last_exception);
13573 + last_exception = std::current_exception();
13579 +#if defined(_MSC_VER)
13580 +# define PYBIND11_COMPAT_STRDUP _strdup
13582 +# define PYBIND11_COMPAT_STRDUP strdup
13585 +PYBIND11_NAMESPACE_END(detail)
13587 /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
13588 class cpp_function : public function {
13590 - cpp_function() { }
13591 - cpp_function(std::nullptr_t) { }
13592 + cpp_function() = default;
13593 + // NOLINTNEXTLINE(google-explicit-constructor)
13594 + cpp_function(std::nullptr_t) {}
13596 /// Construct a cpp_function from a vanilla function pointer
13597 template <typename Return, typename... Args, typename... Extra>
13598 - cpp_function(Return (*f)(Args...), const Extra&... extra) {
13599 + // NOLINTNEXTLINE(google-explicit-constructor)
13600 + cpp_function(Return (*f)(Args...), const Extra &...extra) {
13601 initialize(f, f, extra...);
13604 /// Construct a cpp_function from a lambda function (possibly with internal state)
13605 - template <typename Func, typename... Extra,
13606 + template <typename Func,
13607 + typename... Extra,
13608 typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
13609 - cpp_function(Func &&f, const Extra&... extra) {
13610 - initialize(std::forward<Func>(f),
13611 - (detail::function_signature_t<Func> *) nullptr, extra...);
13612 + // NOLINTNEXTLINE(google-explicit-constructor)
13613 + cpp_function(Func &&f, const Extra &...extra) {
13615 + std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...);
13618 - /// Construct a cpp_function from a class method (non-const)
13619 + /// Construct a cpp_function from a class method (non-const, no ref-qualifier)
13620 template <typename Return, typename Class, typename... Arg, typename... Extra>
13621 - cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
13622 - initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
13623 - (Return (*) (Class *, Arg...)) nullptr, extra...);
13624 + // NOLINTNEXTLINE(google-explicit-constructor)
13625 + cpp_function(Return (Class::*f)(Arg...), const Extra &...extra) {
13627 + [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
13628 + (Return(*)(Class *, Arg...)) nullptr,
13632 - /// Construct a cpp_function from a class method (const)
13633 + /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier)
13634 + /// A copy of the overload for non-const functions without explicit ref-qualifier
13635 + /// but with an added `&`.
13636 template <typename Return, typename Class, typename... Arg, typename... Extra>
13637 - cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
13638 - initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
13639 - (Return (*)(const Class *, Arg ...)) nullptr, extra...);
13640 + // NOLINTNEXTLINE(google-explicit-constructor)
13641 + cpp_function(Return (Class::*f)(Arg...) &, const Extra &...extra) {
13643 + [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
13644 + (Return(*)(Class *, Arg...)) nullptr,
13648 + /// Construct a cpp_function from a class method (const, no ref-qualifier)
13649 + template <typename Return, typename Class, typename... Arg, typename... Extra>
13650 + // NOLINTNEXTLINE(google-explicit-constructor)
13651 + cpp_function(Return (Class::*f)(Arg...) const, const Extra &...extra) {
13652 + initialize([f](const Class *c,
13653 + Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
13654 + (Return(*)(const Class *, Arg...)) nullptr,
13658 + /// Construct a cpp_function from a class method (const, lvalue ref-qualifier)
13659 + /// A copy of the overload for const functions without explicit ref-qualifier
13660 + /// but with an added `&`.
13661 + template <typename Return, typename Class, typename... Arg, typename... Extra>
13662 + // NOLINTNEXTLINE(google-explicit-constructor)
13663 + cpp_function(Return (Class::*f)(Arg...) const &, const Extra &...extra) {
13664 + initialize([f](const Class *c,
13665 + Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
13666 + (Return(*)(const Class *, Arg...)) nullptr,
13670 /// Return the function name
13671 object name() const { return attr("__name__"); }
13674 + struct InitializingFunctionRecordDeleter {
13675 + // `destruct(function_record, false)`: `initialize_generic` copies strings and
13676 + // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`.
13677 + void operator()(detail::function_record *rec) { destruct(rec, false); }
13679 + using unique_function_record
13680 + = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
13682 /// Space optimization: don't inline this frequently instantiated fragment
13683 - PYBIND11_NOINLINE detail::function_record *make_function_record() {
13684 - return new detail::function_record();
13685 + PYBIND11_NOINLINE unique_function_record make_function_record() {
13686 + return unique_function_record(new detail::function_record());
13689 /// Special internal constructor for functors, lambda functions, etc.
13690 template <typename Func, typename Return, typename... Args, typename... Extra>
13691 - void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
13692 + void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) {
13693 using namespace detail;
13694 - struct capture { remove_reference_t<Func> f; };
13696 + remove_reference_t<Func> f;
13699 - /* Store the function including any extra state it might have (e.g. a lambda capture object) */
13700 - auto rec = make_function_record();
13701 + /* Store the function including any extra state it might have (e.g. a lambda capture
13703 + // The unique_ptr makes sure nothing is leaked in case of an exception.
13704 + auto unique_rec = make_function_record();
13705 + auto *rec = unique_rec.get();
13707 /* Store the capture object directly in the function record if there is enough space */
13708 - if (sizeof(capture) <= sizeof(rec->data)) {
13709 + if (PYBIND11_SILENCE_MSVC_C4127(sizeof(capture) <= sizeof(rec->data))) {
13710 /* Without these pragmas, GCC warns that there might not be
13711 enough space to use the placement new operator. However, the
13712 'if' statement above ensures that this is the case. */
13713 -#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
13714 -# pragma GCC diagnostic push
13715 -# pragma GCC diagnostic ignored "-Wplacement-new"
13717 - new ((capture *) &rec->data) capture { std::forward<Func>(f) };
13718 -#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
13719 -# pragma GCC diagnostic pop
13720 +#if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER)
13721 +# pragma GCC diagnostic push
13722 +# pragma GCC diagnostic ignored "-Wplacement-new"
13724 + new ((capture *) &rec->data) capture{std::forward<Func>(f)};
13725 +#if defined(__GNUG__) && __GNUC__ >= 6 && !defined(__clang__) && !defined(__INTEL_COMPILER)
13726 +# pragma GCC diagnostic pop
13728 +#if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER)
13729 +# pragma GCC diagnostic push
13730 +# pragma GCC diagnostic ignored "-Wstrict-aliasing"
13732 + // UB without std::launder, but without breaking ABI and/or
13733 + // a significant refactoring it's "impossible" to solve.
13734 + if (!std::is_trivially_destructible<capture>::value) {
13735 + rec->free_data = [](function_record *r) {
13736 + auto data = PYBIND11_STD_LAUNDER((capture *) &r->data);
13738 + data->~capture();
13741 +#if defined(__GNUG__) && !PYBIND11_HAS_STD_LAUNDER && !defined(__INTEL_COMPILER)
13742 +# pragma GCC diagnostic pop
13744 - if (!std::is_trivially_destructible<Func>::value)
13745 - rec->free_data = [](function_record *r) { ((capture *) &r->data)->~capture(); };
13747 - rec->data[0] = new capture { std::forward<Func>(f) };
13748 + rec->data[0] = new capture{std::forward<Func>(f)};
13749 rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
13752 /* Type casters for the function arguments and return value */
13753 using cast_in = argument_loader<Args...>;
13754 - using cast_out = make_caster<
13755 - conditional_t<std::is_void<Return>::value, void_type, Return>
13758 + = make_caster<conditional_t<std::is_void<Return>::value, void_type, Return>>;
13760 - static_assert(expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
13761 - "The number of argument annotations does not match the number of function arguments");
13763 + expected_num_args<Extra...>(
13764 + sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
13765 + "The number of argument annotations does not match the number of function arguments");
13767 /* Dispatch code which converts function arguments and performs the actual function call */
13768 rec->impl = [](function_call &call) -> handle {
13769 cast_in args_converter;
13771 /* Try to cast the function arguments into the C++ domain */
13772 - if (!args_converter.load_args(call))
13773 + if (!args_converter.load_args(call)) {
13774 return PYBIND11_TRY_NEXT_OVERLOAD;
13777 /* Invoke call policy pre-call hook */
13778 process_attributes<Extra...>::precall(call);
13780 /* Get a pointer to the capture object */
13781 - auto data = (sizeof(capture) <= sizeof(call.func.data)
13782 - ? &call.func.data : call.func.data[0]);
13783 - capture *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
13784 + const auto *data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data
13785 + : call.func.data[0]);
13786 + auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
13788 /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
13789 - return_value_policy policy = return_value_policy_override<Return>::policy(call.func.policy);
13790 + return_value_policy policy
13791 + = return_value_policy_override<Return>::policy(call.func.policy);
13793 /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
13794 using Guard = extract_guard_t<Extra...>;
13796 /* Perform the function call */
13797 - handle result = cast_out::cast(
13798 - std::move(args_converter).template call<Return, Guard>(cap->f), policy, call.parent);
13800 + = cast_out::cast(std::move(args_converter).template call<Return, Guard>(cap->f),
13804 /* Invoke call policy post-call hook */
13805 process_attributes<Extra...>::postcall(call, result);
13806 @@ -161,73 +256,152 @@
13810 + rec->nargs_pos = cast_in::args_pos >= 0
13811 + ? static_cast<std::uint16_t>(cast_in::args_pos)
13812 + : sizeof...(Args) - cast_in::has_kwargs; // Will get reduced more if
13813 + // we have a kw_only
13814 + rec->has_args = cast_in::args_pos >= 0;
13815 + rec->has_kwargs = cast_in::has_kwargs;
13817 /* Process any user-provided function attributes */
13818 process_attributes<Extra...>::init(extra..., rec);
13820 - /* Generate a readable signature describing the function's arguments and return value types */
13821 - static constexpr auto signature = _("(") + cast_in::arg_names + _(") -> ") + cast_out::name;
13823 + constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
13824 + has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
13825 + has_arg_annotations = any_of<is_keyword<Extra>...>::value;
13826 + static_assert(has_arg_annotations || !has_kw_only_args,
13827 + "py::kw_only requires the use of argument annotations");
13828 + static_assert(has_arg_annotations || !has_pos_only_args,
13829 + "py::pos_only requires the use of argument annotations (for docstrings "
13830 + "and aligning the annotations to the argument)");
13832 + static_assert(constexpr_sum(is_kw_only<Extra>::value...) <= 1,
13833 + "py::kw_only may be specified only once");
13834 + static_assert(constexpr_sum(is_pos_only<Extra>::value...) <= 1,
13835 + "py::pos_only may be specified only once");
13836 + constexpr auto kw_only_pos = constexpr_first<is_kw_only, Extra...>();
13837 + constexpr auto pos_only_pos = constexpr_first<is_pos_only, Extra...>();
13838 + static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
13839 + "py::pos_only must come before py::kw_only");
13842 + /* Generate a readable signature describing the function's arguments and return
13844 + static constexpr auto signature
13845 + = const_name("(") + cast_in::arg_names + const_name(") -> ") + cast_out::name;
13846 PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
13848 /* Register the function with Python from generic (non-templated) code */
13849 - initialize_generic(rec, signature.text, types.data(), sizeof...(Args));
13851 - if (cast_in::has_args) rec->has_args = true;
13852 - if (cast_in::has_kwargs) rec->has_kwargs = true;
13853 + // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid.
13854 + initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));
13856 /* Stash some additional information used by an important optimization in 'functional.h' */
13857 using FunctionType = Return (*)(Args...);
13858 - constexpr bool is_function_ptr =
13859 - std::is_convertible<Func, FunctionType>::value &&
13860 - sizeof(capture) == sizeof(void *);
13861 + constexpr bool is_function_ptr
13862 + = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *);
13863 if (is_function_ptr) {
13864 rec->is_stateless = true;
13865 - rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
13867 + = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
13871 + // Utility class that keeps track of all duplicated strings, and cleans them up in its
13872 + // destructor, unless they are released. Basically a RAII-solution to deal with exceptions
13873 + // along the way.
13874 + class strdup_guard {
13876 + ~strdup_guard() {
13877 + for (auto *s : strings) {
13881 + char *operator()(const char *s) {
13882 + auto *t = PYBIND11_COMPAT_STRDUP(s);
13883 + strings.push_back(t);
13886 + void release() { strings.clear(); }
13889 + std::vector<char *> strings;
13892 /// Register a function call with Python (generic non-templated code goes here)
13893 - void initialize_generic(detail::function_record *rec, const char *text,
13894 - const std::type_info *const *types, size_t args) {
13895 + void initialize_generic(unique_function_record &&unique_rec,
13896 + const char *text,
13897 + const std::type_info *const *types,
13899 + // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr,
13900 + // we do not want this to destruct the pointer. `initialize` (the caller) still relies on
13901 + // the pointee being alive after this call. Only move out if a `capsule` is going to keep
13903 + auto *rec = unique_rec.get();
13905 + // Keep track of strdup'ed strings, and clean them up as long as the function's capsule
13906 + // has not taken ownership yet (when `unique_rec.release()` is called).
13907 + // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the
13908 + // strings are only referenced before strdup'ing. So only *after* the following block could
13909 + // `destruct` safely be called, but even then, `repr` could still throw in the middle of
13910 + // copying all strings.
13911 + strdup_guard guarded_strdup;
13913 /* Create copies of all referenced C-style strings */
13914 - rec->name = strdup(rec->name ? rec->name : "");
13915 - if (rec->doc) rec->doc = strdup(rec->doc);
13916 - for (auto &a: rec->args) {
13918 - a.name = strdup(a.name);
13920 - a.descr = strdup(a.descr);
13921 - else if (a.value)
13922 - a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
13923 + rec->name = guarded_strdup(rec->name ? rec->name : "");
13925 + rec->doc = guarded_strdup(rec->doc);
13927 + for (auto &a : rec->args) {
13929 + a.name = guarded_strdup(a.name);
13932 + a.descr = guarded_strdup(a.descr);
13933 + } else if (a.value) {
13934 + a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());
13938 - rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
13939 + rec->is_constructor = (std::strcmp(rec->name, "__init__") == 0)
13940 + || (std::strcmp(rec->name, "__setstate__") == 0);
13942 #if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
13943 if (rec->is_constructor && !rec->is_new_style_constructor) {
13944 - const auto class_name = std::string(((PyTypeObject *) rec->scope.ptr())->tp_name);
13945 + const auto class_name
13946 + = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
13947 const auto func_name = std::string(rec->name);
13949 - PyExc_FutureWarning,
13950 - ("pybind11-bound class '" + class_name + "' is using an old-style "
13951 - "placement-new '" + func_name + "' which has been deprecated. See "
13952 - "the upgrade guide in pybind11's docs. This message is only visible "
13953 - "when compiled in debug mode.").c_str(), 0
13955 + PyErr_WarnEx(PyExc_FutureWarning,
13956 + ("pybind11-bound class '" + class_name
13957 + + "' is using an old-style "
13958 + "placement-new '"
13960 + + "' which has been deprecated. See "
13961 + "the upgrade guide in pybind11's docs. This message is only visible "
13962 + "when compiled in debug mode.")
13968 /* Generate a proper function signature */
13969 std::string signature;
13970 size_t type_index = 0, arg_index = 0;
13971 - for (auto *pc = text; *pc != '\0'; ++pc) {
13972 + bool is_starred = false;
13973 + for (const auto *pc = text; *pc != '\0'; ++pc) {
13974 const auto c = *pc;
13977 // Write arg name for everything except *args and **kwargs.
13978 - if (*(pc + 1) == '*')
13979 + is_starred = *(pc + 1) == '*';
13980 + if (is_starred) {
13984 + // Separator for keyword-only arguments, placed before the kw
13985 + // arguments start (unless we are already putting an *args)
13986 + if (!rec->has_args && arg_index == rec->nargs_pos) {
13987 + signature += "*, ";
13989 if (arg_index < rec->args.size() && rec->args[arg_index].name) {
13990 signature += rec->args[arg_index].name;
13991 } else if (arg_index == 0 && rec->is_method) {
13992 @@ -238,26 +412,33 @@
13994 } else if (c == '}') {
13995 // Write default value if available.
13996 - if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
13997 + if (!is_starred && arg_index < rec->args.size() && rec->args[arg_index].descr) {
13998 signature += " = ";
13999 signature += rec->args[arg_index].descr;
14002 + // Separator for positional-only arguments (placed after the
14003 + // argument, rather than before like *
14004 + if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
14005 + signature += ", /";
14007 + if (!is_starred) {
14010 } else if (c == '%') {
14011 const std::type_info *t = types[type_index++];
14014 pybind11_fail("Internal error while parsing type signature (1)");
14015 - if (auto tinfo = detail::get_type_info(*t)) {
14017 + if (auto *tinfo = detail::get_type_info(*t)) {
14018 handle th((PyObject *) tinfo->type);
14020 - th.attr("__module__").cast<std::string>() + "." +
14021 - th.attr("__qualname__").cast<std::string>(); // Python 3.3+, but we backport it to earlier versions
14022 + signature += th.attr("__module__").cast<std::string>() + "." +
14023 + // Python 3.3+, but we backport it to earlier versions
14024 + th.attr("__qualname__").cast<std::string>();
14025 } else if (rec->is_new_style_constructor && arg_index == 0) {
14026 // A new-style `__init__` takes `self` as `value_and_holder`.
14027 // Rewrite it to the proper class type.
14029 - rec->scope.attr("__module__").cast<std::string>() + "." +
14030 - rec->scope.attr("__qualname__").cast<std::string>();
14031 + signature += rec->scope.attr("__module__").cast<std::string>() + "."
14032 + + rec->scope.attr("__qualname__").cast<std::string>();
14034 std::string tname(t->name());
14035 detail::clean_type_id(tname);
14036 @@ -267,39 +448,47 @@
14040 - if (arg_index != args || types[type_index] != nullptr)
14042 + if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] != nullptr) {
14043 pybind11_fail("Internal error while parsing type signature (2)");
14046 #if PY_MAJOR_VERSION < 3
14047 - if (strcmp(rec->name, "__next__") == 0) {
14048 + if (std::strcmp(rec->name, "__next__") == 0) {
14049 std::free(rec->name);
14050 - rec->name = strdup("next");
14051 - } else if (strcmp(rec->name, "__bool__") == 0) {
14052 + rec->name = guarded_strdup("next");
14053 + } else if (std::strcmp(rec->name, "__bool__") == 0) {
14054 std::free(rec->name);
14055 - rec->name = strdup("__nonzero__");
14056 + rec->name = guarded_strdup("__nonzero__");
14059 - rec->signature = strdup(signature.c_str());
14060 + rec->signature = guarded_strdup(signature.c_str());
14061 rec->args.shrink_to_fit();
14062 rec->nargs = (std::uint16_t) args;
14064 - if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr()))
14065 + if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) {
14066 rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
14069 detail::function_record *chain = nullptr, *chain_start = rec;
14070 if (rec->sibling) {
14071 if (PyCFunction_Check(rec->sibling.ptr())) {
14072 - auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
14073 + auto *self = PyCFunction_GET_SELF(rec->sibling.ptr());
14074 + capsule rec_capsule = isinstance<capsule>(self) ? reinterpret_borrow<capsule>(self)
14076 chain = (detail::function_record *) rec_capsule;
14077 /* Never append a method to an overload chain of a parent class;
14078 instead, hide the parent's overloads in this case */
14079 - if (!chain->scope.is(rec->scope))
14080 + if (!chain->scope.is(rec->scope)) {
14084 + // Don't trigger for things like the default __init__, which are wrapper_descriptors
14085 + // that we are intentionally replacing
14086 + else if (!rec->sibling.is_none() && rec->name[0] != '_') {
14087 + pybind11_fail("Cannot overload existing non-function object \""
14088 + + std::string(rec->name) + "\" with a function of the same name");
14090 - // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
14091 - else if (!rec->sibling.is_none() && rec->name[0] != '_')
14092 - pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
14093 - "\" with a function of the same name");
14097 @@ -307,12 +496,13 @@
14098 rec->def = new PyMethodDef();
14099 std::memset(rec->def, 0, sizeof(PyMethodDef));
14100 rec->def->ml_name = rec->name;
14101 - rec->def->ml_meth = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(*dispatcher));
14102 + rec->def->ml_meth
14103 + = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher));
14104 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
14106 - capsule rec_capsule(rec, [](void *ptr) {
14107 - destruct((detail::function_record *) ptr);
14109 + capsule rec_capsule(unique_rec.release(),
14110 + [](void *ptr) { destruct((detail::function_record *) ptr); });
14111 + guarded_strdup.release();
14113 object scope_module;
14115 @@ -324,25 +514,46 @@
14118 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
14121 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
14124 - /* Append at the end of the overload chain */
14125 + /* Append at the beginning or end of the overload chain */
14126 m_ptr = rec->sibling.ptr();
14128 - chain_start = chain;
14129 - if (chain->is_method != rec->is_method)
14130 - pybind11_fail("overloading a method with both static and instance methods is not supported; "
14131 - #if defined(NDEBUG)
14132 - "compile in debug mode for more details"
14134 - "error while attempting to bind " + std::string(rec->is_method ? "instance" : "static") + " method " +
14135 - std::string(pybind11::str(rec->scope.attr("__name__"))) + "." + std::string(rec->name) + signature
14137 + if (chain->is_method != rec->is_method) {
14139 + "overloading a method with both static and instance methods is not supported; "
14140 +#if defined(NDEBUG)
14141 + "compile in debug mode for more details"
14143 + "error while attempting to bind "
14144 + + std::string(rec->is_method ? "instance" : "static") + " method "
14145 + + std::string(pybind11::str(rec->scope.attr("__name__"))) + "."
14146 + + std::string(rec->name) + signature
14149 - while (chain->next)
14150 - chain = chain->next;
14151 - chain->next = rec;
14154 + if (rec->prepend) {
14155 + // Beginning of chain; we need to replace the capsule's current head-of-the-chain
14156 + // pointer with this one, then make this one point to the previous head of the
14158 + chain_start = rec;
14159 + rec->next = chain;
14161 + = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self);
14162 + rec_capsule.set_pointer(unique_rec.release());
14163 + guarded_strdup.release();
14165 + // Or end of chain (normal behavior)
14166 + chain_start = chain;
14167 + while (chain->next) {
14168 + chain = chain->next;
14170 + chain->next = unique_rec.release();
14171 + guarded_strdup.release();
14175 std::string signatures;
14176 @@ -357,59 +568,95 @@
14178 // Then specific overload signatures
14179 bool first_user_def = true;
14180 - for (auto it = chain_start; it != nullptr; it = it->next) {
14181 + for (auto *it = chain_start; it != nullptr; it = it->next) {
14182 if (options::show_function_signatures()) {
14183 - if (index > 0) signatures += "\n";
14186 + signatures += "\n";
14189 signatures += std::to_string(++index) + ". ";
14191 signatures += rec->name;
14192 signatures += it->signature;
14193 signatures += "\n";
14195 - if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
14196 - // If we're appending another docstring, and aren't printing function signatures, we
14197 - // need to append a newline first:
14198 + if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) {
14199 + // If we're appending another docstring, and aren't printing function signatures,
14200 + // we need to append a newline first:
14201 if (!options::show_function_signatures()) {
14202 - if (first_user_def) first_user_def = false;
14203 - else signatures += "\n";
14204 + if (first_user_def) {
14205 + first_user_def = false;
14207 + signatures += "\n";
14210 + if (options::show_function_signatures()) {
14211 + signatures += "\n";
14213 - if (options::show_function_signatures()) signatures += "\n";
14214 signatures += it->doc;
14215 - if (options::show_function_signatures()) signatures += "\n";
14216 + if (options::show_function_signatures()) {
14217 + signatures += "\n";
14222 /* Install docstring */
14223 - PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
14224 - if (func->m_ml->ml_doc)
14225 - std::free(const_cast<char *>(func->m_ml->ml_doc));
14226 - func->m_ml->ml_doc = strdup(signatures.c_str());
14227 + auto *func = (PyCFunctionObject *) m_ptr;
14228 + std::free(const_cast<char *>(func->m_ml->ml_doc));
14229 + // Install docstring if it's non-empty (when at least one option is enabled)
14230 + func->m_ml->ml_doc
14231 + = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());
14233 if (rec->is_method) {
14234 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
14236 - pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
14239 + "cpp_function::cpp_function(): Could not allocate instance method object");
14245 /// When a cpp_function is GCed, release any memory allocated by pybind11
14246 - static void destruct(detail::function_record *rec) {
14247 + static void destruct(detail::function_record *rec, bool free_strings = true) {
14248 +// If on Python 3.9, check the interpreter "MICRO" (patch) version.
14249 +// If this is running on 3.9.0, we have to work around a bug.
14250 +#if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
14251 + static bool is_zero = Py_GetVersion()[4] == '0';
14255 detail::function_record *next = rec->next;
14256 - if (rec->free_data)
14257 + if (rec->free_data) {
14258 rec->free_data(rec);
14259 - std::free((char *) rec->name);
14260 - std::free((char *) rec->doc);
14261 - std::free((char *) rec->signature);
14262 - for (auto &arg: rec->args) {
14263 - std::free(const_cast<char *>(arg.name));
14264 - std::free(const_cast<char *>(arg.descr));
14266 + // During initialization, these strings might not have been copied yet,
14267 + // so they cannot be freed. Once the function has been created, they can.
14268 + // Check `make_function_record` for more details.
14269 + if (free_strings) {
14270 + std::free((char *) rec->name);
14271 + std::free((char *) rec->doc);
14272 + std::free((char *) rec->signature);
14273 + for (auto &arg : rec->args) {
14274 + std::free(const_cast<char *>(arg.name));
14275 + std::free(const_cast<char *>(arg.descr));
14278 + for (auto &arg : rec->args) {
14279 arg.value.dec_ref();
14282 std::free(const_cast<char *>(rec->def->ml_doc));
14283 +// Python 3.9.0 decref's these in the wrong order; rec->def
14284 +// If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)
14285 +// See https://github.com/python/cpython/pull/22670
14286 +#if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
14296 @@ -424,27 +671,32 @@
14297 const function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
14300 - /* Need to know how many arguments + keyword arguments there are to pick the right overload */
14301 - const size_t n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
14302 + /* Need to know how many arguments + keyword arguments there are to pick the right
14304 + const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
14306 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
14307 result = PYBIND11_TRY_NEXT_OVERLOAD;
14309 auto self_value_and_holder = value_and_holder();
14310 if (overloads->is_constructor) {
14311 - const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
14312 - const auto pi = reinterpret_cast<instance *>(parent.ptr());
14313 - self_value_and_holder = pi->get_value_and_holder(tinfo, false);
14315 - if (!self_value_and_holder.type || !self_value_and_holder.inst) {
14316 - PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid `self` argument");
14318 + || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
14321 + "__init__(self, ...) called with invalid or missing `self` argument");
14325 + auto *const tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
14326 + auto *const pi = reinterpret_cast<instance *>(parent.ptr());
14327 + self_value_and_holder = pi->get_value_and_holder(tinfo, true);
14329 // If this value is already registered it must mean __init__ is invoked multiple times;
14330 // we really can't support that in C++, so just ignore the second __init__.
14331 - if (self_value_and_holder.instance_registered())
14332 + if (self_value_and_holder.instance_registered()) {
14333 return none().release().ptr();
14338 @@ -463,46 +715,56 @@
14339 1. Copy all positional arguments we were given, also checking to make sure that
14340 named positional arguments weren't *also* specified via kwarg.
14341 2. If we weren't given enough, try to make up the omitted ones by checking
14342 - whether they were provided by a kwarg matching the `py::arg("name")` name. If
14343 - so, use it (and remove it from kwargs; if not, see if the function binding
14344 + whether they were provided by a kwarg matching the `py::arg("name")` name. If
14345 + so, use it (and remove it from kwargs); if not, see if the function binding
14346 provided a default that we can use.
14347 - 3. Ensure that either all keyword arguments were "consumed", or that the function
14348 - takes a kwargs argument to accept unconsumed kwargs.
14349 + 3. Ensure that either all keyword arguments were "consumed", or that the
14350 + function takes a kwargs argument to accept unconsumed kwargs.
14351 4. Any positional arguments still left get put into a tuple (for args), and any
14352 leftover kwargs get put into a dict.
14353 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
14354 extra tuple or dict at the end of the positional arguments.
14355 6. Call the function call dispatcher (function_record::impl)
14357 - If one of these fail, move on to the next overload and keep trying until we get a
14358 - result other than PYBIND11_TRY_NEXT_OVERLOAD.
14359 + If one of these fail, move on to the next overload and keep trying until we get
14360 + a result other than PYBIND11_TRY_NEXT_OVERLOAD.
14363 const function_record &func = *it;
14364 - size_t pos_args = func.nargs; // Number of positional arguments that we need
14365 - if (func.has_args) --pos_args; // (but don't count py::args
14366 - if (func.has_kwargs) --pos_args; // or py::kwargs)
14367 + size_t num_args = func.nargs; // Number of positional arguments that we need
14368 + if (func.has_args) {
14369 + --num_args; // (but don't count py::args
14371 + if (func.has_kwargs) {
14372 + --num_args; // or py::kwargs)
14374 + size_t pos_args = func.nargs_pos;
14376 - if (!func.has_args && n_args_in > pos_args)
14377 - continue; // Too many arguments for this overload
14378 + if (!func.has_args && n_args_in > pos_args) {
14379 + continue; // Too many positional arguments for this overload
14382 - if (n_args_in < pos_args && func.args.size() < pos_args)
14383 - continue; // Not enough arguments given, and not enough defaults to fill in the blanks
14384 + if (n_args_in < pos_args && func.args.size() < pos_args) {
14385 + continue; // Not enough positional arguments given, and not enough defaults to
14386 + // fill in the blanks
14389 function_call call(func, parent);
14391 - size_t args_to_copy = std::min(pos_args, n_args_in);
14392 + // Protect std::min with parentheses
14393 + size_t args_to_copy = (std::min)(pos_args, n_args_in);
14394 size_t args_copied = 0;
14396 // 0. Inject new-style `self` argument
14397 if (func.is_new_style_constructor) {
14398 // The `value` may have been preallocated by an old-style `__init__`
14399 // if it was a preceding candidate for overload resolution.
14400 - if (self_value_and_holder)
14401 + if (self_value_and_holder) {
14402 self_value_and_holder.type->dealloc(self_value_and_holder);
14405 call.init_self = PyTuple_GET_ITEM(args_in, 0);
14406 - call.args.push_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
14407 + call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
14408 call.args_convert.push_back(false);
14411 @@ -510,8 +772,10 @@
14412 // 1. Copy any position arguments given.
14413 bool bad_arg = false;
14414 for (; args_copied < args_to_copy; ++args_copied) {
14415 - const argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
14416 - if (kwargs_in && arg_rec && arg_rec->name && PyDict_GetItemString(kwargs_in, arg_rec->name)) {
14417 + const argument_record *arg_rec
14418 + = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
14419 + if (kwargs_in && arg_rec && arg_rec->name
14420 + && dict_getitemstring(kwargs_in, arg_rec->name)) {
14424 @@ -524,22 +788,50 @@
14425 call.args.push_back(arg);
14426 call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
14430 continue; // Maybe it was meant for another overload (issue #688)
14433 + // Keep track of how many position args we copied out in case we need to come back
14434 + // to copy the rest into a py::args argument.
14435 + size_t positional_args_copied = args_copied;
14437 // We'll need to copy this if we steal some kwargs for defaults
14438 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
14440 + // 1.5. Fill in any missing pos_only args from defaults if they exist
14441 + if (args_copied < func.nargs_pos_only) {
14442 + for (; args_copied < func.nargs_pos_only; ++args_copied) {
14443 + const auto &arg_rec = func.args[args_copied];
14446 + if (arg_rec.value) {
14447 + value = arg_rec.value;
14450 + call.args.push_back(value);
14451 + call.args_convert.push_back(arg_rec.convert);
14457 + if (args_copied < func.nargs_pos_only) {
14458 + continue; // Not enough defaults to fill the positional arguments
14462 // 2. Check kwargs and, failing that, defaults that may help complete the list
14463 - if (args_copied < pos_args) {
14464 + if (args_copied < num_args) {
14465 bool copied_kwargs = false;
14467 - for (; args_copied < pos_args; ++args_copied) {
14468 - const auto &arg = func.args[args_copied];
14469 + for (; args_copied < num_args; ++args_copied) {
14470 + const auto &arg_rec = func.args[args_copied];
14473 - if (kwargs_in && arg.name)
14474 - value = PyDict_GetItemString(kwargs.ptr(), arg.name);
14475 + if (kwargs_in && arg_rec.name) {
14476 + value = dict_getitemstring(kwargs.ptr(), arg_rec.name);
14480 // Consume a kwargs value
14481 @@ -547,26 +839,41 @@
14482 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
14483 copied_kwargs = true;
14485 - PyDict_DelItemString(kwargs.ptr(), arg.name);
14486 - } else if (arg.value) {
14487 - value = arg.value;
14488 + if (PyDict_DelItemString(kwargs.ptr(), arg_rec.name) == -1) {
14489 + throw error_already_set();
14491 + } else if (arg_rec.value) {
14492 + value = arg_rec.value;
14495 + if (!arg_rec.none && value.is_none()) {
14500 + // If we're at the py::args index then first insert a stub for it to be
14501 + // replaced later
14502 + if (func.has_args && call.args.size() == func.nargs_pos) {
14503 + call.args.push_back(none());
14506 call.args.push_back(value);
14507 - call.args_convert.push_back(arg.convert);
14510 + call.args_convert.push_back(arg_rec.convert);
14516 - if (args_copied < pos_args)
14517 - continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments
14518 + if (args_copied < num_args) {
14519 + continue; // Not enough arguments, defaults, or kwargs to fill the
14520 + // positional arguments
14524 // 3. Check everything was consumed (unless we have a kwargs arg)
14525 - if (kwargs && kwargs.size() > 0 && !func.has_kwargs)
14526 + if (kwargs && !kwargs.empty() && !func.has_kwargs) {
14527 continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
14530 // 4a. If we have a py::args argument, create a new tuple with leftovers
14531 if (func.has_args) {
14532 @@ -575,35 +882,42 @@
14533 // We didn't copy out any position arguments from the args_in tuple, so we
14534 // can reuse it directly without copying:
14535 extra_args = reinterpret_borrow<tuple>(args_in);
14536 - } else if (args_copied >= n_args_in) {
14537 + } else if (positional_args_copied >= n_args_in) {
14538 extra_args = tuple(0);
14540 - size_t args_size = n_args_in - args_copied;
14541 + size_t args_size = n_args_in - positional_args_copied;
14542 extra_args = tuple(args_size);
14543 for (size_t i = 0; i < args_size; ++i) {
14544 - extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i);
14545 + extra_args[i] = PyTuple_GET_ITEM(args_in, positional_args_copied + i);
14548 - call.args.push_back(extra_args);
14549 + if (call.args.size() <= func.nargs_pos) {
14550 + call.args.push_back(extra_args);
14552 + call.args[func.nargs_pos] = extra_args;
14554 call.args_convert.push_back(false);
14555 call.args_ref = std::move(extra_args);
14558 // 4b. If we have a py::kwargs, pass on any remaining kwargs
14559 if (func.has_kwargs) {
14560 - if (!kwargs.ptr())
14561 + if (!kwargs.ptr()) {
14562 kwargs = dict(); // If we didn't get one, send an empty one
14564 call.args.push_back(kwargs);
14565 call.args_convert.push_back(false);
14566 call.kwargs_ref = std::move(kwargs);
14569 - // 5. Put everything in a vector. Not technically step 5, we've been building it
14570 - // in `call.args` all along.
14571 - #if !defined(NDEBUG)
14572 - if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
14573 - pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
14575 +// 5. Put everything in a vector. Not technically step 5, we've been building it
14576 +// in `call.args` all along.
14577 +#if !defined(NDEBUG)
14578 + if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) {
14579 + pybind11_fail("Internal error: function call dispatcher inserted wrong number "
14580 + "of arguments!");
14584 std::vector<bool> second_pass_convert;
14586 @@ -622,8 +936,9 @@
14587 result = PYBIND11_TRY_NEXT_OVERLOAD;
14590 - if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
14591 + if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
14596 // The (overloaded) call failed; if the call has at least one argument that
14597 @@ -642,7 +957,8 @@
14600 if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
14601 - // The no-conversion pass finished without success, try again with conversion allowed
14602 + // The no-conversion pass finished without success, try again with conversion
14604 for (auto &call : second_pass) {
14606 loader_life_support guard{};
14607 @@ -654,8 +970,9 @@
14608 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
14609 // The error reporting logic below expects 'it' to be valid, as it would be
14610 // if we'd encountered this failure in the first-pass loop.
14618 @@ -663,30 +980,39 @@
14619 } catch (error_already_set &e) {
14622 +#ifdef __GLIBCXX__
14623 + } catch (abi::__forced_unwind &) {
14627 /* When an exception is caught, give each registered exception
14628 - translator a chance to translate it to a Python exception
14629 - in reverse order of registration.
14630 + translator a chance to translate it to a Python exception. First
14631 + all module-local translators will be tried in reverse order of
14632 + registration. If none of the module-locale translators handle
14633 + the exception (or there are no module-locale translators) then
14634 + the global translators will be tried, also in reverse order of
14637 A translator may choose to do one of the following:
14639 - catch the exception and call PyErr_SetString or PyErr_SetObject
14640 to set a standard (or custom) Python exception, or
14641 - do nothing and let the exception fall through to the next translator, or
14642 - - delegate translation to the next translator by throwing a new type of exception. */
14643 + - delegate translation to the next translator by throwing a new type of exception.
14646 - auto last_exception = std::current_exception();
14647 - auto ®istered_exception_translators = get_internals().registered_exception_translators;
14648 - for (auto& translator : registered_exception_translators) {
14650 - translator(last_exception);
14652 - last_exception = std::current_exception();
14655 + auto &local_exception_translators
14656 + = get_local_internals().registered_exception_translators;
14657 + if (detail::apply_exception_translators(local_exception_translators)) {
14660 - PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
14661 + auto &exception_translators = get_internals().registered_exception_translators;
14662 + if (detail::apply_exception_translators(exception_translators)) {
14666 + PyErr_SetString(PyExc_SystemError,
14667 + "Exception escaped from default exception translator!");
14671 @@ -701,20 +1027,22 @@
14674 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
14675 - if (overloads->is_operator)
14676 + if (overloads->is_operator) {
14677 return handle(Py_NotImplemented).inc_ref().ptr();
14680 - std::string msg = std::string(overloads->name) + "(): incompatible " +
14681 - std::string(overloads->is_constructor ? "constructor" : "function") +
14682 - " arguments. The following argument types are supported:\n";
14683 + std::string msg = std::string(overloads->name) + "(): incompatible "
14684 + + std::string(overloads->is_constructor ? "constructor" : "function")
14685 + + " arguments. The following argument types are supported:\n";
14688 for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
14689 - msg += " "+ std::to_string(++ctr) + ". ";
14690 + msg += " " + std::to_string(++ctr) + ". ";
14692 bool wrote_sig = false;
14693 if (overloads->is_constructor) {
14694 - // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
14695 + // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as
14696 + // `Object(arg0, ...)`
14697 std::string sig = it2->signature;
14698 size_t start = sig.find('(') + 7; // skip "(self: "
14699 if (start < sig.size()) {
14700 @@ -722,7 +1050,9 @@
14701 size_t end = sig.find(", "), next = end + 2;
14702 size_t ret = sig.rfind(" -> ");
14703 // Or the ), if there is no comma:
14704 - if (end >= sig.size()) next = end = sig.find(')');
14705 + if (end >= sig.size()) {
14706 + next = end = sig.find(')');
14708 if (start < end && next < sig.size()) {
14709 msg.append(sig, start, end - start);
14711 @@ -731,7 +1061,9 @@
14715 - if (!wrote_sig) msg += it2->signature;
14716 + if (!wrote_sig) {
14717 + msg += it2->signature;
14722 @@ -739,66 +1071,89 @@
14723 auto args_ = reinterpret_borrow<tuple>(args_in);
14724 bool some_args = false;
14725 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
14726 - if (!some_args) some_args = true;
14727 - else msg += ", ";
14728 - msg += pybind11::repr(args_[ti]);
14729 + if (!some_args) {
14730 + some_args = true;
14735 + msg += pybind11::repr(args_[ti]);
14736 + } catch (const error_already_set &) {
14737 + msg += "<repr raised Error>";
14741 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
14742 - if (kwargs.size() > 0) {
14743 - if (some_args) msg += "; ";
14744 + if (!kwargs.empty()) {
14750 for (auto kwarg : kwargs) {
14751 - if (first) first = false;
14752 - else msg += ", ";
14753 - msg += pybind11::str("{}={!r}").format(kwarg.first, kwarg.second);
14759 + msg += pybind11::str("{}=").format(kwarg.first);
14761 + msg += pybind11::repr(kwarg.second);
14762 + } catch (const error_already_set &) {
14763 + msg += "<repr raised Error>";
14769 append_note_if_missing_header_is_suspected(msg);
14770 +#if PY_VERSION_HEX >= 0x03030000
14771 + // Attach additional error info to the exception if supported
14772 + if (PyErr_Occurred()) {
14773 + // #HelpAppreciated: unit test coverage for this branch.
14774 + raise_from(PyExc_TypeError, msg.c_str());
14778 PyErr_SetString(PyExc_TypeError, msg.c_str());
14780 - } else if (!result) {
14783 std::string msg = "Unable to convert function return value to a "
14784 "Python type! The signature was\n\t";
14785 msg += it->signature;
14786 append_note_if_missing_header_is_suspected(msg);
14787 +#if PY_VERSION_HEX >= 0x03030000
14788 + // Attach additional error info to the exception if supported
14789 + if (PyErr_Occurred()) {
14790 + raise_from(PyExc_TypeError, msg.c_str());
14794 PyErr_SetString(PyExc_TypeError, msg.c_str());
14797 - if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
14798 - auto *pi = reinterpret_cast<instance *>(parent.ptr());
14799 - self_value_and_holder.type->init_instance(pi, nullptr);
14801 - return result.ptr();
14803 + if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
14804 + auto *pi = reinterpret_cast<instance *>(parent.ptr());
14805 + self_value_and_holder.type->init_instance(pi, nullptr);
14807 + return result.ptr();
14811 /// Wrapper for Python extension modules
14812 -class module : public object {
14813 +class module_ : public object {
14815 - PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
14816 + PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)
14818 /// Create a new top-level Python module with the given name and docstring
14819 - explicit module(const char *name, const char *doc = nullptr) {
14820 - if (!options::show_user_defined_docstrings()) doc = nullptr;
14821 + PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead")
14822 + explicit module_(const char *name, const char *doc = nullptr) {
14823 #if PY_MAJOR_VERSION >= 3
14824 - PyModuleDef *def = new PyModuleDef();
14825 - std::memset(def, 0, sizeof(PyModuleDef));
14826 - def->m_name = name;
14827 - def->m_doc = doc;
14828 - def->m_size = -1;
14830 - m_ptr = PyModule_Create(def);
14831 + *this = create_extension_module(name, doc, new PyModuleDef());
14833 - m_ptr = Py_InitModule3(name, nullptr, doc);
14834 + *this = create_extension_module(name, doc, nullptr);
14836 - if (m_ptr == nullptr)
14837 - pybind11_fail("Internal error in module::module()");
14842 @@ -807,11 +1162,15 @@
14843 details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
14845 template <typename Func, typename... Extra>
14846 - module &def(const char *name_, Func &&f, const Extra& ... extra) {
14847 - cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
14848 - sibling(getattr(*this, name_, none())), extra...);
14849 + module_ &def(const char *name_, Func &&f, const Extra &...extra) {
14850 + cpp_function func(std::forward<Func>(f),
14853 + sibling(getattr(*this, name_, none())),
14855 // NB: allow overwriting here because cpp_function sets up a chain with the intention of
14856 - // overwriting (and has already checked internally that it isn't overwriting non-functions).
14857 + // overwriting (and has already checked internally that it isn't overwriting
14858 + // non-functions).
14859 add_object(name_, func, true /* overwrite */);
14862 @@ -822,73 +1181,142 @@
14864 .. code-block:: cpp
14866 - py::module m("example", "pybind11 example plugin");
14867 - py::module m2 = m.def_submodule("sub", "A submodule of 'example'");
14868 - py::module m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
14869 + py::module_ m("example", "pybind11 example plugin");
14870 + py::module_ m2 = m.def_submodule("sub", "A submodule of 'example'");
14871 + py::module_ m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
14873 - module def_submodule(const char *name, const char *doc = nullptr) {
14874 - std::string full_name = std::string(PyModule_GetName(m_ptr))
14875 - + std::string(".") + std::string(name);
14876 - auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
14877 - if (doc && options::show_user_defined_docstrings())
14878 + module_ def_submodule(const char *name, const char *doc = nullptr) {
14879 + std::string full_name
14880 + = std::string(PyModule_GetName(m_ptr)) + std::string(".") + std::string(name);
14881 + auto result = reinterpret_borrow<module_>(PyImport_AddModule(full_name.c_str()));
14882 + if (doc && options::show_user_defined_docstrings()) {
14883 result.attr("__doc__") = pybind11::str(doc);
14885 attr(name) = result;
14889 /// Import and return a module or throws `error_already_set`.
14890 - static module import(const char *name) {
14891 + static module_ import(const char *name) {
14892 PyObject *obj = PyImport_ImportModule(name);
14895 throw error_already_set();
14896 - return reinterpret_steal<module>(obj);
14898 + return reinterpret_steal<module_>(obj);
14901 /// Reload the module or throws `error_already_set`.
14903 PyObject *obj = PyImport_ReloadModule(ptr());
14906 throw error_already_set();
14907 - *this = reinterpret_steal<module>(obj);
14909 + *this = reinterpret_steal<module_>(obj);
14912 - // Adds an object to the module using the given name. Throws if an object with the given name
14913 - // already exists.
14915 - // overwrite should almost always be false: attempting to overwrite objects that pybind11 has
14916 - // established will, in most cases, break things.
14918 + Adds an object to the module using the given name. Throws if an object with the given name
14921 + ``overwrite`` should almost always be false: attempting to overwrite objects that pybind11
14922 + has established will, in most cases, break things.
14924 PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
14925 - if (!overwrite && hasattr(*this, name))
14926 - pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
14927 - std::string(name) + "\"");
14928 + if (!overwrite && hasattr(*this, name)) {
14930 + "Error during initialization: multiple incompatible definitions with name \""
14931 + + std::string(name) + "\"");
14934 PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
14937 +#if PY_MAJOR_VERSION >= 3
14938 + using module_def = PyModuleDef;
14940 + struct module_def {};
14944 + Create a new top-level module that can be used as the main module of a C extension.
14946 + For Python 3, ``def`` should point to a statically allocated module_def.
14947 + For Python 2, ``def`` can be a nullptr and is completely ignored.
14949 + static module_ create_extension_module(const char *name, const char *doc, module_def *def) {
14950 +#if PY_MAJOR_VERSION >= 3
14951 + // module_def is PyModuleDef
14952 + // Placement new (not an allocation).
14954 + PyModuleDef{/* m_base */ PyModuleDef_HEAD_INIT,
14955 + /* m_name */ name,
14956 + /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr,
14958 + /* m_methods */ nullptr,
14959 + /* m_slots */ nullptr,
14960 + /* m_traverse */ nullptr,
14961 + /* m_clear */ nullptr,
14962 + /* m_free */ nullptr};
14963 + auto *m = PyModule_Create(def);
14965 + // Ignore module_def *def; only necessary for Python 3
14967 + auto m = Py_InitModule3(
14968 + name, nullptr, options::show_user_defined_docstrings() ? doc : nullptr);
14970 + if (m == nullptr) {
14971 + if (PyErr_Occurred()) {
14972 + throw error_already_set();
14974 + pybind11_fail("Internal error in module_::create_extension_module()");
14976 + // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when
14977 + // returned from PyInit_...
14978 + // For Python 2, reinterpret_borrow is correct.
14979 + return reinterpret_borrow<module_>(m);
14983 +// When inside a namespace (or anywhere as long as it's not the first item on a line),
14984 +// C++20 allows "module" to be used. This is provided for backward compatibility, and for
14985 +// simplicity, if someone wants to use py::module for example, that is perfectly safe.
14986 +using module = module_;
14988 /// \ingroup python_builtins
14989 /// Return a dictionary representing the global variables in the current execution frame,
14990 /// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
14991 inline dict globals() {
14992 PyObject *p = PyEval_GetGlobals();
14993 - return reinterpret_borrow<dict>(p ? p : module::import("__main__").attr("__dict__").ptr());
14994 + return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
14997 +#if PY_VERSION_HEX >= 0x03030000
14998 +template <typename... Args, typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>>
14999 +PYBIND11_DEPRECATED("make_simple_namespace should be replaced with "
15000 + "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
15001 +object make_simple_namespace(Args &&...args_) {
15002 + return module_::import("types").attr("SimpleNamespace")(std::forward<Args>(args_)...);
15006 -NAMESPACE_BEGIN(detail)
15007 +PYBIND11_NAMESPACE_BEGIN(detail)
15008 /// Generic support for creating new Python heap types
15009 class generic_type : public object {
15010 - template <typename...> friend class class_;
15012 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
15014 void initialize(const type_record &rec) {
15015 - if (rec.scope && hasattr(rec.scope, rec.name))
15016 - pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
15017 - "\": an object with that name is already defined");
15019 - if (rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
15020 - pybind11_fail("generic_type: type \"" + std::string(rec.name) +
15021 - "\" is already registered!");
15022 + if (rec.scope && hasattr(rec.scope, "__dict__")
15023 + && rec.scope.attr("__dict__").contains(rec.name)) {
15024 + pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name)
15025 + + "\": an object with that name is already defined");
15028 + if ((rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
15030 + pybind11_fail("generic_type: type \"" + std::string(rec.name)
15031 + + "\" is already registered!");
15034 m_ptr = make_new_python_type(rec);
15036 @@ -910,19 +1338,23 @@
15037 auto &internals = get_internals();
15038 auto tindex = std::type_index(*rec.type);
15039 tinfo->direct_conversions = &internals.direct_conversions[tindex];
15040 - if (rec.module_local)
15041 - registered_local_types_cpp()[tindex] = tinfo;
15043 + if (rec.module_local) {
15044 + get_local_internals().registered_types_cpp[tindex] = tinfo;
15046 internals.registered_types_cpp[tindex] = tinfo;
15047 - internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo };
15049 + internals.registered_types_py[(PyTypeObject *) m_ptr] = {tinfo};
15051 if (rec.bases.size() > 1 || rec.multiple_inheritance) {
15052 mark_parents_nonsimple(tinfo->type);
15053 tinfo->simple_ancestors = false;
15055 - else if (rec.bases.size() == 1) {
15056 - auto parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
15057 - tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
15058 + } else if (rec.bases.size() == 1) {
15059 + auto *parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
15060 + assert(parent_tinfo != nullptr);
15061 + bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
15062 + tinfo->simple_ancestors = parent_simple_ancestors;
15063 + // The parent can no longer be a simple type if it has MI and has a child
15064 + parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
15067 if (rec.module_local) {
15068 @@ -936,25 +1368,25 @@
15069 void mark_parents_nonsimple(PyTypeObject *value) {
15070 auto t = reinterpret_borrow<tuple>(value->tp_bases);
15071 for (handle h : t) {
15072 - auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
15074 + auto *tinfo2 = get_type_info((PyTypeObject *) h.ptr());
15076 tinfo2->simple_type = false;
15078 mark_parents_nonsimple((PyTypeObject *) h.ptr());
15082 - void install_buffer_funcs(
15083 - buffer_info *(*get_buffer)(PyObject *, void *),
15084 - void *get_buffer_data) {
15085 - PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
15086 - auto tinfo = detail::get_type_info(&type->ht_type);
15088 - if (!type->ht_type.tp_as_buffer)
15090 - "To be able to register buffer protocol support for the type '" +
15091 - std::string(tinfo->type->tp_name) +
15092 - "' the associated class<>(..) invocation must "
15093 - "include the pybind11::buffer_protocol() annotation!");
15094 + void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *),
15095 + void *get_buffer_data) {
15096 + auto *type = (PyHeapTypeObject *) m_ptr;
15097 + auto *tinfo = detail::get_type_info(&type->ht_type);
15099 + if (!type->ht_type.tp_as_buffer) {
15100 + pybind11_fail("To be able to register buffer protocol support for the type '"
15101 + + get_fully_qualified_tp_name(tinfo->type)
15102 + + "' the associated class<>(..) invocation must "
15103 + "include the pybind11::buffer_protocol() annotation!");
15106 tinfo->get_buffer = get_buffer;
15107 tinfo->get_buffer_data = get_buffer_data;
15108 @@ -962,78 +1394,118 @@
15110 // rec_func must be set for either fget or fset.
15111 void def_property_static_impl(const char *name,
15112 - handle fget, handle fset,
15115 detail::function_record *rec_func) {
15116 - const auto is_static = rec_func && !(rec_func->is_method && rec_func->scope);
15117 - const auto has_doc = rec_func && rec_func->doc && pybind11::options::show_user_defined_docstrings();
15118 - auto property = handle((PyObject *) (is_static ? get_internals().static_property_type
15119 - : &PyProperty_Type));
15120 + const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);
15121 + const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)
15122 + && pybind11::options::show_user_defined_docstrings();
15123 + auto property = handle(
15124 + (PyObject *) (is_static ? get_internals().static_property_type : &PyProperty_Type));
15125 attr(name) = property(fget.ptr() ? fget : none(),
15126 fset.ptr() ? fset : none(),
15127 - /*deleter*/none(),
15128 + /*deleter*/ none(),
15129 pybind11::str(has_doc ? rec_func->doc : ""));
15133 /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
15134 -template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator new))>>
15135 -void set_operator_new(type_record *r) { r->operator_new = &T::operator new; }
15137 -template <typename> void set_operator_new(...) { }
15139 -template <typename T, typename SFINAE = void> struct has_operator_delete : std::false_type { };
15140 -template <typename T> struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
15141 - : std::true_type { };
15142 -template <typename T, typename SFINAE = void> struct has_operator_delete_size : std::false_type { };
15143 -template <typename T> struct has_operator_delete_size<T, void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>>
15144 - : std::true_type { };
15145 +template <typename T,
15146 + typename = void_t<decltype(static_cast<void *(*) (size_t)>(T::operator new))>>
15147 +void set_operator_new(type_record *r) {
15148 + r->operator_new = &T::operator new;
15151 +template <typename>
15152 +void set_operator_new(...) {}
15154 +template <typename T, typename SFINAE = void>
15155 +struct has_operator_delete : std::false_type {};
15156 +template <typename T>
15157 +struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
15158 + : std::true_type {};
15159 +template <typename T, typename SFINAE = void>
15160 +struct has_operator_delete_size : std::false_type {};
15161 +template <typename T>
15162 +struct has_operator_delete_size<
15164 + void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type {
15166 /// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
15167 template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
15168 -void call_operator_delete(T *p, size_t, size_t) { T::operator delete(p); }
15169 -template <typename T, enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> = 0>
15170 -void call_operator_delete(T *p, size_t s, size_t) { T::operator delete(p, s); }
15171 +void call_operator_delete(T *p, size_t, size_t) {
15172 + T::operator delete(p);
15176 + enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> = 0>
15177 +void call_operator_delete(T *p, size_t s, size_t) {
15178 + T::operator delete(p, s);
15181 inline void call_operator_delete(void *p, size_t s, size_t a) {
15182 - (void)s; (void)a;
15183 -#if defined(PYBIND11_CPP17)
15184 - if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
15187 +#if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
15188 + if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
15189 +# ifdef __cpp_sized_deallocation
15190 ::operator delete(p, s, std::align_val_t(a));
15192 - ::operator delete(p, s);
15194 + ::operator delete(p, std::align_val_t(a));
15199 +#ifdef __cpp_sized_deallocation
15200 + ::operator delete(p, s);
15202 ::operator delete(p);
15206 -NAMESPACE_END(detail)
15207 +inline void add_class_method(object &cls, const char *name_, const cpp_function &cf) {
15208 + cls.attr(cf.name()) = cf;
15209 + if (std::strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) {
15210 + cls.attr("__hash__") = none();
15214 +PYBIND11_NAMESPACE_END(detail)
15216 /// Given a pointer to a member function, cast it to its `Derived` version.
15217 /// Forward everything else unchanged.
15218 template <typename /*Derived*/, typename F>
15219 -auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) { return std::forward<F>(f); }
15220 +auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
15221 + return std::forward<F>(f);
15224 template <typename Derived, typename Return, typename Class, typename... Args>
15225 auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
15226 - static_assert(detail::is_accessible_base_of<Class, Derived>::value,
15228 + detail::is_accessible_base_of<Class, Derived>::value,
15229 "Cannot bind an inaccessible base class method; use a lambda definition instead");
15233 template <typename Derived, typename Return, typename Class, typename... Args>
15234 auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
15235 - static_assert(detail::is_accessible_base_of<Class, Derived>::value,
15237 + detail::is_accessible_base_of<Class, Derived>::value,
15238 "Cannot bind an inaccessible base class method; use a lambda definition instead");
15242 template <typename type_, typename... options>
15243 class class_ : public detail::generic_type {
15244 - template <typename T> using is_holder = detail::is_holder_type<type_, T>;
15245 - template <typename T> using is_subtype = detail::is_strict_base_of<type_, T>;
15246 - template <typename T> using is_base = detail::is_strict_base_of<T, type_>;
15247 + template <typename T>
15248 + using is_holder = detail::is_holder_type<type_, T>;
15249 + template <typename T>
15250 + using is_subtype = detail::is_strict_base_of<type_, T>;
15251 + template <typename T>
15252 + using is_base = detail::is_strict_base_of<T, type_>;
15253 // struct instead of using here to help MSVC:
15254 - template <typename T> struct is_valid_class_option :
15255 - detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
15256 + template <typename T>
15257 + struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
15260 using type = type_;
15261 @@ -1042,23 +1514,24 @@
15262 using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
15264 static_assert(detail::all_of<is_valid_class_option<options>...>::value,
15265 - "Unknown/invalid class_ template parameters provided");
15266 + "Unknown/invalid class_ template parameters provided");
15268 static_assert(!has_alias || std::is_polymorphic<type>::value,
15269 - "Cannot use an alias class with a non-polymorphic type");
15270 + "Cannot use an alias class with a non-polymorphic type");
15272 PYBIND11_OBJECT(class_, generic_type, PyType_Check)
15274 template <typename... Extra>
15275 - class_(handle scope, const char *name, const Extra &... extra) {
15276 + class_(handle scope, const char *name, const Extra &...extra) {
15277 using namespace detail;
15279 // MI can only be specified via class_ template options, not constructor parameters
15281 none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
15282 - ( constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
15283 - constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
15284 - none_of<std::is_same<multiple_inheritance, Extra>...>::value), // no multiple_inheritance attr
15285 + (constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
15286 + constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
15287 + // no multiple_inheritance attr
15288 + none_of<std::is_same<multiple_inheritance, Extra>...>::value),
15289 "Error: multiple inheritance bases must be specified via class_ template options");
15291 type_record record;
15292 @@ -1066,7 +1539,7 @@
15293 record.name = name;
15294 record.type = &typeid(type);
15295 record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
15296 - record.type_align = alignof(conditional_t<has_alias, type_alias, type>&);
15297 + record.type_align = alignof(conditional_t<has_alias, type_alias, type> &);
15298 record.holder_size = sizeof(holder_type);
15299 record.init_instance = init_instance;
15300 record.dealloc = dealloc;
15301 @@ -1083,8 +1556,10 @@
15302 generic_type::initialize(record);
15305 - auto &instances = record.module_local ? registered_local_types_cpp() : get_internals().registered_types_cpp;
15306 - instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
15307 + auto &instances = record.module_local ? get_local_internals().registered_types_cpp
15308 + : get_internals().registered_types_cpp;
15309 + instances[std::type_index(typeid(type_alias))]
15310 + = instances[std::type_index(typeid(type))];
15314 @@ -1096,52 +1571,60 @@
15317 template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
15318 - static void add_base(detail::type_record &) { }
15319 + static void add_base(detail::type_record &) {}
15321 template <typename Func, typename... Extra>
15322 - class_ &def(const char *name_, Func&& f, const Extra&... extra) {
15323 - cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), name(name_), is_method(*this),
15324 - sibling(getattr(*this, name_, none())), extra...);
15325 - attr(cf.name()) = cf;
15326 + class_ &def(const char *name_, Func &&f, const Extra &...extra) {
15327 + cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
15329 + is_method(*this),
15330 + sibling(getattr(*this, name_, none())),
15332 + add_class_method(*this, name_, cf);
15336 - template <typename Func, typename... Extra> class_ &
15337 - def_static(const char *name_, Func &&f, const Extra&... extra) {
15338 + template <typename Func, typename... Extra>
15339 + class_ &def_static(const char *name_, Func &&f, const Extra &...extra) {
15340 static_assert(!std::is_member_function_pointer<Func>::value,
15341 - "def_static(...) called with a non-static member function pointer");
15342 - cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
15343 - sibling(getattr(*this, name_, none())), extra...);
15344 - attr(cf.name()) = cf;
15345 + "def_static(...) called with a non-static member function pointer");
15346 + cpp_function cf(std::forward<Func>(f),
15349 + sibling(getattr(*this, name_, none())),
15351 + attr(cf.name()) = staticmethod(cf);
15355 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
15356 - class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
15357 + class_ &def(const detail::op_<id, ot, L, R> &op, const Extra &...extra) {
15358 op.execute(*this, extra...);
15362 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
15363 - class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
15364 + class_ &def_cast(const detail::op_<id, ot, L, R> &op, const Extra &...extra) {
15365 op.execute_cast(*this, extra...);
15369 template <typename... Args, typename... Extra>
15370 - class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra&... extra) {
15371 + class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra &...extra) {
15372 + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
15373 init.execute(*this, extra...);
15377 template <typename... Args, typename... Extra>
15378 - class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra&... extra) {
15379 + class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra &...extra) {
15380 + PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
15381 init.execute(*this, extra...);
15385 template <typename... Args, typename... Extra>
15386 - class_ &def(detail::initimpl::factory<Args...> &&init, const Extra&... extra) {
15387 + class_ &def(detail::initimpl::factory<Args...> &&init, const Extra &...extra) {
15388 std::move(init).execute(*this, extra...);
15391 @@ -1152,129 +1635,171 @@
15395 - template <typename Func> class_& def_buffer(Func &&func) {
15396 - struct capture { Func func; };
15397 - capture *ptr = new capture { std::forward<Func>(func) };
15398 - install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
15399 - detail::make_caster<type> caster;
15400 - if (!caster.load(obj, false))
15402 - return new buffer_info(((capture *) ptr)->func(caster));
15404 + template <typename Func>
15405 + class_ &def_buffer(Func &&func) {
15409 + auto *ptr = new capture{std::forward<Func>(func)};
15410 + install_buffer_funcs(
15411 + [](PyObject *obj, void *ptr) -> buffer_info * {
15412 + detail::make_caster<type> caster;
15413 + if (!caster.load(obj, false)) {
15416 + return new buffer_info(((capture *) ptr)->func(caster));
15419 + weakref(m_ptr, cpp_function([ptr](handle wr) {
15427 template <typename Return, typename Class, typename... Args>
15428 class_ &def_buffer(Return (Class::*func)(Args...)) {
15429 - return def_buffer([func] (type &obj) { return (obj.*func)(); });
15430 + return def_buffer([func](type &obj) { return (obj.*func)(); });
15433 template <typename Return, typename Class, typename... Args>
15434 class_ &def_buffer(Return (Class::*func)(Args...) const) {
15435 - return def_buffer([func] (const type &obj) { return (obj.*func)(); });
15436 + return def_buffer([func](const type &obj) { return (obj.*func)(); });
15439 template <typename C, typename D, typename... Extra>
15440 - class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
15441 - static_assert(std::is_base_of<C, type>::value, "def_readwrite() requires a class member (or base class member)");
15442 - cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this)),
15443 - fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
15444 + class_ &def_readwrite(const char *name, D C::*pm, const Extra &...extra) {
15445 + static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
15446 + "def_readwrite() requires a class member (or base class member)");
15447 + cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this)),
15448 + fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
15449 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
15453 template <typename C, typename D, typename... Extra>
15454 - class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
15455 - static_assert(std::is_base_of<C, type>::value, "def_readonly() requires a class member (or base class member)");
15456 - cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this));
15457 + class_ &def_readonly(const char *name, const D C::*pm, const Extra &...extra) {
15458 + static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
15459 + "def_readonly() requires a class member (or base class member)");
15460 + cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this));
15461 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
15465 template <typename D, typename... Extra>
15466 - class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
15467 - cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
15468 - fset([pm](object, const D &value) { *pm = value; }, scope(*this));
15469 + class_ &def_readwrite_static(const char *name, D *pm, const Extra &...extra) {
15470 + cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)),
15471 + fset([pm](const object &, const D &value) { *pm = value; }, scope(*this));
15472 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
15476 template <typename D, typename... Extra>
15477 - class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
15478 - cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
15479 + class_ &def_readonly_static(const char *name, const D *pm, const Extra &...extra) {
15480 + cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this));
15481 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
15485 /// Uses return_value_policy::reference_internal by default
15486 template <typename Getter, typename... Extra>
15487 - class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
15488 - return def_property_readonly(name, cpp_function(method_adaptor<type>(fget)),
15489 - return_value_policy::reference_internal, extra...);
15490 + class_ &def_property_readonly(const char *name, const Getter &fget, const Extra &...extra) {
15491 + return def_property_readonly(name,
15492 + cpp_function(method_adaptor<type>(fget)),
15493 + return_value_policy::reference_internal,
15497 /// Uses cpp_function's return_value_policy by default
15498 template <typename... Extra>
15499 - class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
15501 + def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra) {
15502 return def_property(name, fget, nullptr, extra...);
15505 /// Uses return_value_policy::reference by default
15506 template <typename Getter, typename... Extra>
15507 - class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
15508 - return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...);
15510 + def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra) {
15511 + return def_property_readonly_static(
15512 + name, cpp_function(fget), return_value_policy::reference, extra...);
15515 /// Uses cpp_function's return_value_policy by default
15516 template <typename... Extra>
15517 - class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
15518 + class_ &def_property_readonly_static(const char *name,
15519 + const cpp_function &fget,
15520 + const Extra &...extra) {
15521 return def_property_static(name, fget, nullptr, extra...);
15524 /// Uses return_value_policy::reference_internal by default
15525 template <typename Getter, typename Setter, typename... Extra>
15526 - class_ &def_property(const char *name, const Getter &fget, const Setter &fset, const Extra& ...extra) {
15528 + def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) {
15529 return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
15531 template <typename Getter, typename... Extra>
15532 - class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
15533 - return def_property(name, cpp_function(method_adaptor<type>(fget)), fset,
15534 - return_value_policy::reference_internal, extra...);
15535 + class_ &def_property(const char *name,
15536 + const Getter &fget,
15537 + const cpp_function &fset,
15538 + const Extra &...extra) {
15539 + return def_property(name,
15540 + cpp_function(method_adaptor<type>(fget)),
15542 + return_value_policy::reference_internal,
15546 /// Uses cpp_function's return_value_policy by default
15547 template <typename... Extra>
15548 - class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
15549 + class_ &def_property(const char *name,
15550 + const cpp_function &fget,
15551 + const cpp_function &fset,
15552 + const Extra &...extra) {
15553 return def_property_static(name, fget, fset, is_method(*this), extra...);
15556 /// Uses return_value_policy::reference by default
15557 template <typename Getter, typename... Extra>
15558 - class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
15559 - return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
15560 + class_ &def_property_static(const char *name,
15561 + const Getter &fget,
15562 + const cpp_function &fset,
15563 + const Extra &...extra) {
15564 + return def_property_static(
15565 + name, cpp_function(fget), fset, return_value_policy::reference, extra...);
15568 /// Uses cpp_function's return_value_policy by default
15569 template <typename... Extra>
15570 - class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
15571 + class_ &def_property_static(const char *name,
15572 + const cpp_function &fget,
15573 + const cpp_function &fset,
15574 + const Extra &...extra) {
15575 + static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
15576 + "Argument annotations are not allowed for properties");
15577 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
15578 auto *rec_active = rec_fget;
15580 - char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
15581 - detail::process_attributes<Extra...>::init(extra..., rec_fget);
15582 - if (rec_fget->doc && rec_fget->doc != doc_prev) {
15584 - rec_fget->doc = strdup(rec_fget->doc);
15586 + char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific
15587 + documentation string */
15588 + detail::process_attributes<Extra...>::init(extra..., rec_fget);
15589 + if (rec_fget->doc && rec_fget->doc != doc_prev) {
15590 + std::free(doc_prev);
15591 + rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc);
15595 char *doc_prev = rec_fset->doc;
15596 detail::process_attributes<Extra...>::init(extra..., rec_fset);
15597 if (rec_fset->doc && rec_fset->doc != doc_prev) {
15599 - rec_fset->doc = strdup(rec_fset->doc);
15600 + std::free(doc_prev);
15601 + rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc);
15603 + if (!rec_active) {
15604 + rec_active = rec_fset;
15606 - if (! rec_active) rec_active = rec_fset;
15608 def_property_static_impl(name, fget, fset, rec_active);
15610 @@ -1283,16 +1808,17 @@
15612 /// Initialize holder object, variant 1: object derives from enable_shared_from_this
15613 template <typename T>
15614 - static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
15615 - const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
15617 - auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
15618 - v_h.value_ptr<type>()->shared_from_this());
15620 - new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
15621 - v_h.set_holder_constructed();
15623 - } catch (const std::bad_weak_ptr &) {}
15624 + static void init_holder(detail::instance *inst,
15625 + detail::value_and_holder &v_h,
15626 + const holder_type * /* unused */,
15627 + const std::enable_shared_from_this<T> * /* dummy */) {
15629 + auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
15630 + detail::try_get_shared_from_this(v_h.value_ptr<type>()));
15632 + new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
15633 + v_h.set_holder_constructed();
15636 if (!v_h.holder_constructed() && inst->owned) {
15637 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
15638 @@ -1301,18 +1827,25 @@
15641 static void init_holder_from_existing(const detail::value_and_holder &v_h,
15642 - const holder_type *holder_ptr, std::true_type /*is_copy_constructible*/) {
15643 - new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
15644 + const holder_type *holder_ptr,
15645 + std::true_type /*is_copy_constructible*/) {
15646 + new (std::addressof(v_h.holder<holder_type>()))
15647 + holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
15650 static void init_holder_from_existing(const detail::value_and_holder &v_h,
15651 - const holder_type *holder_ptr, std::false_type /*is_copy_constructible*/) {
15652 - new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
15653 + const holder_type *holder_ptr,
15654 + std::false_type /*is_copy_constructible*/) {
15655 + new (std::addressof(v_h.holder<holder_type>()))
15656 + holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
15659 - /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
15660 - static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
15661 - const holder_type *holder_ptr, const void * /* dummy -- not enable_shared_from_this<T>) */) {
15662 + /// Initialize holder object, variant 2: try to construct from existing holder object, if
15664 + static void init_holder(detail::instance *inst,
15665 + detail::value_and_holder &v_h,
15666 + const holder_type *holder_ptr,
15667 + const void * /* dummy -- not enable_shared_from_this<T>) */) {
15669 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
15670 v_h.set_holder_constructed();
15671 @@ -1323,8 +1856,8 @@
15674 /// Performs instance initialization including constructing a holder and registering the known
15675 - /// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes an
15676 - /// optional pointer to an existing holder to use; if not specified and the instance is
15677 + /// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes
15678 + /// an optional pointer to an existing holder to use; if not specified and the instance is
15679 /// `.owned`, a new holder will be constructed to manage the value pointer.
15680 static void init_instance(detail::instance *inst, const void *holder_ptr) {
15681 auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
15682 @@ -1337,38 +1870,52 @@
15684 /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
15685 static void dealloc(detail::value_and_holder &v_h) {
15686 + // We could be deallocating because we are cleaning up after a Python exception.
15687 + // If so, the Python error indicator will be set. We need to clear that before
15688 + // running the destructor, in case the destructor code calls more Python.
15689 + // If we don't, the Python API will exit with an exception, and pybind11 will
15690 + // throw error_already_set from the C++ destructor which is forbidden and triggers
15691 + // std::terminate().
15692 + error_scope scope;
15693 if (v_h.holder_constructed()) {
15694 v_h.holder<holder_type>().~holder_type();
15695 v_h.set_holder_constructed(false);
15698 - detail::call_operator_delete(v_h.value_ptr<type>(),
15699 - v_h.type->type_size,
15700 - v_h.type->type_align
15703 + detail::call_operator_delete(
15704 + v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align);
15706 v_h.value_ptr() = nullptr;
15709 static detail::function_record *get_function_record(handle h) {
15710 h = detail::get_function(h);
15711 - return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
15712 + return h ? (detail::function_record *) reinterpret_borrow<capsule>(
15713 + PyCFunction_GET_SELF(h.ptr()))
15718 /// Binds an existing constructor taking arguments Args...
15719 -template <typename... Args> detail::initimpl::constructor<Args...> init() { return {}; }
15720 +template <typename... Args>
15721 +detail::initimpl::constructor<Args...> init() {
15724 /// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
15725 /// when not inheriting on the Python side).
15726 -template <typename... Args> detail::initimpl::alias_constructor<Args...> init_alias() { return {}; }
15727 +template <typename... Args>
15728 +detail::initimpl::alias_constructor<Args...> init_alias() {
15732 /// Binds a factory function as a constructor
15733 template <typename Func, typename Ret = detail::initimpl::factory<Func>>
15734 -Ret init(Func &&f) { return {std::forward<Func>(f)}; }
15735 +Ret init(Func &&f) {
15736 + return {std::forward<Func>(f)};
15739 -/// Dual-argument factory function: the first function is called when no alias is needed, the second
15740 -/// when an alias is needed (i.e. due to python-side inheritance). Arguments must be identical.
15741 +/// Dual-argument factory function: the first function is called when no alias is needed, the
15742 +/// second when an alias is needed (i.e. due to python-side inheritance). Arguments must be
15744 template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
15745 Ret init(CFunc &&c, AFunc &&a) {
15746 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
15747 @@ -1381,9 +1928,20 @@
15748 return {std::forward<GetState>(g), std::forward<SetState>(s)};
15751 -NAMESPACE_BEGIN(detail)
15752 +PYBIND11_NAMESPACE_BEGIN(detail)
15754 +inline str enum_name(handle arg) {
15755 + dict entries = arg.get_type().attr("__entries");
15756 + for (auto kv : entries) {
15757 + if (handle(kv.second[int_(0)]).equal(arg)) {
15758 + return pybind11::str(kv.first);
15765 - enum_base(handle base, handle parent) : m_base(base), m_parent(parent) { }
15766 + enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) {}
15768 PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
15769 m_base.attr("__entries") = dict();
15770 @@ -1391,120 +1949,145 @@
15771 auto static_property = handle((PyObject *) get_internals().static_property_type);
15773 m_base.attr("__repr__") = cpp_function(
15774 - [](handle arg) -> str {
15775 - handle type = arg.get_type();
15776 + [](const object &arg) -> str {
15777 + handle type = type::handle_of(arg);
15778 object type_name = type.attr("__name__");
15779 - dict entries = type.attr("__entries");
15780 - for (const auto &kv : entries) {
15781 - object other = kv.second[int_(0)];
15782 - if (other.equal(arg))
15783 - return pybind11::str("{}.{}").format(type_name, kv.first);
15785 - return pybind11::str("{}.???").format(type_name);
15786 - }, is_method(m_base)
15788 + return pybind11::str("<{}.{}: {}>").format(type_name, enum_name(arg), int_(arg));
15790 + name("__repr__"),
15791 + is_method(m_base));
15793 + m_base.attr("name") = property(cpp_function(&enum_name, name("name"), is_method(m_base)));
15795 - m_base.attr("name") = property(cpp_function(
15796 + m_base.attr("__str__") = cpp_function(
15797 [](handle arg) -> str {
15798 - dict entries = arg.get_type().attr("__entries");
15799 - for (const auto &kv : entries) {
15800 - if (handle(kv.second[int_(0)]).equal(arg))
15801 - return pybind11::str(kv.first);
15804 - }, is_method(m_base)
15807 - m_base.attr("__doc__") = static_property(cpp_function(
15808 - [](handle arg) -> std::string {
15809 - std::string docstring;
15810 - dict entries = arg.attr("__entries");
15811 - if (((PyTypeObject *) arg.ptr())->tp_doc)
15812 - docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) + "\n\n";
15813 - docstring += "Members:";
15814 - for (const auto &kv : entries) {
15815 - auto key = std::string(pybind11::str(kv.first));
15816 - auto comment = kv.second[int_(1)];
15817 - docstring += "\n\n " + key;
15818 - if (!comment.is_none())
15819 - docstring += " : " + (std::string) pybind11::str(comment);
15821 - return docstring;
15823 - ), none(), none(), "");
15824 + object type_name = type::handle_of(arg).attr("__name__");
15825 + return pybind11::str("{}.{}").format(type_name, enum_name(arg));
15828 + is_method(m_base));
15830 + m_base.attr("__doc__") = static_property(
15832 + [](handle arg) -> std::string {
15833 + std::string docstring;
15834 + dict entries = arg.attr("__entries");
15835 + if (((PyTypeObject *) arg.ptr())->tp_doc) {
15836 + docstring += std::string(((PyTypeObject *) arg.ptr())->tp_doc) + "\n\n";
15838 + docstring += "Members:";
15839 + for (auto kv : entries) {
15840 + auto key = std::string(pybind11::str(kv.first));
15841 + auto comment = kv.second[int_(1)];
15842 + docstring += "\n\n " + key;
15843 + if (!comment.is_none()) {
15844 + docstring += " : " + (std::string) pybind11::str(comment);
15847 + return docstring;
15849 + name("__doc__")),
15854 m_base.attr("__members__") = static_property(cpp_function(
15855 - [](handle arg) -> dict {
15856 - dict entries = arg.attr("__entries"), m;
15857 - for (const auto &kv : entries)
15858 - m[kv.first] = kv.second[int_(0)];
15860 - }), none(), none(), ""
15863 - #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
15864 - m_base.attr(op) = cpp_function( \
15865 - [](object a, object b) { \
15866 - if (!a.get_type().is(b.get_type())) \
15867 - strict_behavior; \
15870 - is_method(m_base))
15872 - #define PYBIND11_ENUM_OP_CONV(op, expr) \
15873 - m_base.attr(op) = cpp_function( \
15874 - [](object a_, object b_) { \
15875 - int_ a(a_), b(b_); \
15878 - is_method(m_base))
15879 + [](handle arg) -> dict {
15880 + dict entries = arg.attr("__entries"),
15882 + for (auto kv : entries) {
15883 + m[kv.first] = kv.second[int_(0)];
15887 + name("__members__")),
15892 +#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
15893 + m_base.attr(op) = cpp_function( \
15894 + [](const object &a, const object &b) { \
15895 + if (!type::handle_of(a).is(type::handle_of(b))) \
15896 + strict_behavior; /* NOLINT(bugprone-macro-parentheses) */ \
15900 + is_method(m_base), \
15903 +#define PYBIND11_ENUM_OP_CONV(op, expr) \
15904 + m_base.attr(op) = cpp_function( \
15905 + [](const object &a_, const object &b_) { \
15906 + int_ a(a_), b(b_); \
15910 + is_method(m_base), \
15913 +#define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
15914 + m_base.attr(op) = cpp_function( \
15915 + [](const object &a_, const object &b) { \
15920 + is_method(m_base), \
15923 if (is_convertible) {
15924 - PYBIND11_ENUM_OP_CONV("__eq__", !b.is_none() && a.equal(b));
15925 - PYBIND11_ENUM_OP_CONV("__ne__", b.is_none() || !a.equal(b));
15926 + PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
15927 + PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
15929 if (is_arithmetic) {
15930 - PYBIND11_ENUM_OP_CONV("__lt__", a < b);
15931 - PYBIND11_ENUM_OP_CONV("__gt__", a > b);
15932 - PYBIND11_ENUM_OP_CONV("__le__", a <= b);
15933 - PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
15934 - PYBIND11_ENUM_OP_CONV("__and__", a & b);
15935 - PYBIND11_ENUM_OP_CONV("__rand__", a & b);
15936 - PYBIND11_ENUM_OP_CONV("__or__", a | b);
15937 - PYBIND11_ENUM_OP_CONV("__ror__", a | b);
15938 - PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
15939 - PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
15940 + PYBIND11_ENUM_OP_CONV("__lt__", a < b);
15941 + PYBIND11_ENUM_OP_CONV("__gt__", a > b);
15942 + PYBIND11_ENUM_OP_CONV("__le__", a <= b);
15943 + PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
15944 + PYBIND11_ENUM_OP_CONV("__and__", a & b);
15945 + PYBIND11_ENUM_OP_CONV("__rand__", a & b);
15946 + PYBIND11_ENUM_OP_CONV("__or__", a | b);
15947 + PYBIND11_ENUM_OP_CONV("__ror__", a | b);
15948 + PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
15949 + PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
15950 + m_base.attr("__invert__")
15951 + = cpp_function([](const object &arg) { return ~(int_(arg)); },
15952 + name("__invert__"),
15953 + is_method(m_base));
15956 - PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
15957 + PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
15958 PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
15960 if (is_arithmetic) {
15961 - #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
15962 - PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
15963 - PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
15964 +#define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
15965 + PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
15966 + PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
15967 PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
15968 PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
15969 - #undef PYBIND11_THROW
15970 +#undef PYBIND11_THROW
15974 - #undef PYBIND11_ENUM_OP_CONV
15975 - #undef PYBIND11_ENUM_OP_STRICT
15976 +#undef PYBIND11_ENUM_OP_CONV_LHS
15977 +#undef PYBIND11_ENUM_OP_CONV
15978 +#undef PYBIND11_ENUM_OP_STRICT
15980 - object getstate = cpp_function(
15981 - [](object arg) { return int_(arg); }, is_method(m_base));
15982 + m_base.attr("__getstate__") = cpp_function(
15983 + [](const object &arg) { return int_(arg); }, name("__getstate__"), is_method(m_base));
15985 - m_base.attr("__getstate__") = getstate;
15986 - m_base.attr("__hash__") = getstate;
15987 + m_base.attr("__hash__") = cpp_function(
15988 + [](const object &arg) { return int_(arg); }, name("__hash__"), is_method(m_base));
15991 - PYBIND11_NOINLINE void value(char const* name_, object value, const char *doc = nullptr) {
15992 + PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc = nullptr) {
15993 dict entries = m_base.attr("__entries");
15995 if (entries.contains(name)) {
15996 std::string type_name = (std::string) str(m_base.attr("__name__"));
15997 - throw value_error(type_name + ": element \"" + std::string(name_) + "\" already exists!");
15998 + throw value_error(type_name + ": element \"" + std::string(name_)
15999 + + "\" already exists!");
16002 entries[name] = std::make_pair(value, doc);
16003 @@ -1513,52 +2096,105 @@
16005 PYBIND11_NOINLINE void export_values() {
16006 dict entries = m_base.attr("__entries");
16007 - for (const auto &kv : entries)
16008 + for (auto kv : entries) {
16009 m_parent.attr(kv.first) = kv.second[int_(0)];
16017 -NAMESPACE_END(detail)
16018 +template <bool is_signed, size_t length>
16019 +struct equivalent_integer {};
16021 +struct equivalent_integer<true, 1> {
16022 + using type = int8_t;
16025 +struct equivalent_integer<false, 1> {
16026 + using type = uint8_t;
16029 +struct equivalent_integer<true, 2> {
16030 + using type = int16_t;
16033 +struct equivalent_integer<false, 2> {
16034 + using type = uint16_t;
16037 +struct equivalent_integer<true, 4> {
16038 + using type = int32_t;
16041 +struct equivalent_integer<false, 4> {
16042 + using type = uint32_t;
16045 +struct equivalent_integer<true, 8> {
16046 + using type = int64_t;
16049 +struct equivalent_integer<false, 8> {
16050 + using type = uint64_t;
16053 +template <typename IntLike>
16054 +using equivalent_integer_t =
16055 + typename equivalent_integer<std::is_signed<IntLike>::value, sizeof(IntLike)>::type;
16057 +PYBIND11_NAMESPACE_END(detail)
16059 /// Binds C++ enumerations and enumeration classes to Python
16060 -template <typename Type> class enum_ : public class_<Type> {
16061 +template <typename Type>
16062 +class enum_ : public class_<Type> {
16064 using Base = class_<Type>;
16068 using Base::def_property_readonly;
16069 using Base::def_property_readonly_static;
16070 - using Scalar = typename std::underlying_type<Type>::type;
16071 + using Underlying = typename std::underlying_type<Type>::type;
16072 + // Scalar is the integer representation of underlying type
16073 + using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
16074 + std::is_same<Underlying, bool>>::value,
16075 + detail::equivalent_integer_t<Underlying>,
16078 template <typename... Extra>
16079 - enum_(const handle &scope, const char *name, const Extra&... extra)
16080 - : class_<Type>(scope, name, extra...), m_base(*this, scope) {
16081 + enum_(const handle &scope, const char *name, const Extra &...extra)
16082 + : class_<Type>(scope, name, extra...), m_base(*this, scope) {
16083 constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
16084 - constexpr bool is_convertible = std::is_convertible<Type, Scalar>::value;
16085 + constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
16086 m_base.init(is_arithmetic, is_convertible);
16088 - def(init([](Scalar i) { return static_cast<Type>(i); }));
16089 + def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
16090 + def_property_readonly("value", [](Type value) { return (Scalar) value; });
16091 def("__int__", [](Type value) { return (Scalar) value; });
16092 - #if PY_MAJOR_VERSION < 3
16093 - def("__long__", [](Type value) { return (Scalar) value; });
16095 - cpp_function setstate(
16096 - [](Type &value, Scalar arg) { value = static_cast<Type>(arg); },
16097 - is_method(*this));
16098 - attr("__setstate__") = setstate;
16099 + def("__index__", [](Type value) { return (Scalar) value; });
16100 +#if PY_MAJOR_VERSION < 3
16101 + def("__long__", [](Type value) { return (Scalar) value; });
16103 + attr("__setstate__") = cpp_function(
16104 + [](detail::value_and_holder &v_h, Scalar arg) {
16105 + detail::initimpl::setstate<Base>(
16106 + v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type);
16108 + detail::is_new_style_constructor(),
16109 + pybind11::name("__setstate__"),
16110 + is_method(*this),
16114 /// Export enumeration entries into the parent scope
16115 - enum_& export_values() {
16116 + enum_ &export_values() {
16117 m_base.export_values();
16121 /// Add an enumeration entry
16122 - enum_& value(char const* name, Type value, const char *doc = nullptr) {
16123 + enum_ &value(char const *name, Type value, const char *doc = nullptr) {
16124 m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
16127 @@ -1567,28 +2203,30 @@
16128 detail::enum_base m_base;
16131 -NAMESPACE_BEGIN(detail)
16132 +PYBIND11_NAMESPACE_BEGIN(detail)
16135 -inline void keep_alive_impl(handle nurse, handle patient) {
16136 - if (!nurse || !patient)
16137 +PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient) {
16138 + if (!nurse || !patient) {
16139 pybind11_fail("Could not activate keep_alive!");
16142 - if (patient.is_none() || nurse.is_none())
16143 + if (patient.is_none() || nurse.is_none()) {
16144 return; /* Nothing to keep alive or nothing to be kept alive by */
16147 auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
16148 if (!tinfo.empty()) {
16149 /* It's a pybind-registered type, so we can store the patient in the
16150 * internal list. */
16151 add_patient(nurse.ptr(), patient.ptr());
16155 /* Fall back to clever approach based on weak references taken from
16156 * Boost.Python. This is not used for pybind-registered types because
16157 * the objects can be destroyed out-of-order in a GC pass. */
16158 - cpp_function disable_lifesupport(
16159 - [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
16160 + cpp_function disable_lifesupport([patient](handle weakref) {
16161 + patient.dec_ref();
16162 + weakref.dec_ref();
16165 weakref wr(nurse, disable_lifesupport);
16167 @@ -1597,153 +2235,278 @@
16171 -PYBIND11_NOINLINE inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
16172 +PYBIND11_NOINLINE void
16173 +keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
16174 auto get_arg = [&](size_t n) {
16178 - else if (n == 1 && call.init_self)
16180 + if (n == 1 && call.init_self) {
16181 return call.init_self;
16182 - else if (n <= call.args.size())
16184 + if (n <= call.args.size()) {
16185 return call.args[n - 1];
16190 keep_alive_impl(get_arg(Nurse), get_arg(Patient));
16193 -inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type) {
16194 - auto res = get_internals().registered_types_py
16195 +inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
16196 +all_type_info_get_cache(PyTypeObject *type) {
16197 + auto res = get_internals()
16198 + .registered_types_py
16199 #ifdef __cpp_lib_unordered_map_try_emplace
16200 - .try_emplace(type);
16201 + .try_emplace(type);
16203 - .emplace(type, std::vector<detail::type_info *>());
16204 + .emplace(type, std::vector<detail::type_info *>());
16207 // New cache entry created; set up a weak reference to automatically remove it if the type
16209 weakref((PyObject *) type, cpp_function([type](handle wr) {
16210 - get_internals().registered_types_py.erase(type);
16213 + get_internals().registered_types_py.erase(type);
16215 + // TODO consolidate the erasure code in pybind11_meta_dealloc() in class.h
16216 + auto &cache = get_internals().inactive_override_cache;
16217 + for (auto it = cache.begin(), last = cache.end(); it != last;) {
16218 + if (it->first == reinterpret_cast<PyObject *>(type)) {
16219 + it = cache.erase(it);
16233 -template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
16234 +/* There are a large number of apparently unused template arguments because
16235 + * each combination requires a separate py::class_ registration.
16237 +template <typename Access,
16238 + return_value_policy Policy,
16239 + typename Iterator,
16240 + typename Sentinel,
16241 + typename ValueType,
16242 + typename... Extra>
16243 struct iterator_state {
16246 bool first_or_done;
16249 -NAMESPACE_END(detail)
16250 +// Note: these helpers take the iterator by non-const reference because some
16251 +// iterators in the wild can't be dereferenced when const. The & after Iterator
16252 +// is required for MSVC < 16.9. SFINAE cannot be reused for result_type due to
16253 +// bugs in ICC, NVCC, and PGI compilers. See PR #3293.
16254 +template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
16255 +struct iterator_access {
16256 + using result_type = decltype(*std::declval<Iterator &>());
16257 + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
16258 + result_type operator()(Iterator &it) const { return *it; }
16261 -/// Makes a python iterator from a first and past-the-end C++ InputIterator.
16262 -template <return_value_policy Policy = return_value_policy::reference_internal,
16263 +template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).first)>
16264 +class iterator_key_access {
16266 + using pair_type = decltype(*std::declval<Iterator &>());
16269 + /* If either the pair itself or the element of the pair is a reference, we
16270 + * want to return a reference, otherwise a value. When the decltype
16271 + * expression is parenthesized it is based on the value category of the
16272 + * expression; otherwise it is the declared type of the pair member.
16273 + * The use of declval<pair_type> in the second branch rather than directly
16274 + * using *std::declval<Iterator &>() is a workaround for nvcc
16275 + * (it's not used in the first branch because going via decltype and back
16276 + * through declval does not perfectly preserve references).
16278 + using result_type
16279 + = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
16280 + decltype(((*std::declval<Iterator &>()).first)),
16281 + decltype(std::declval<pair_type>().first)>;
16282 + result_type operator()(Iterator &it) const { return (*it).first; }
16285 +template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
16286 +class iterator_value_access {
16288 + using pair_type = decltype(*std::declval<Iterator &>());
16291 + using result_type
16292 + = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
16293 + decltype(((*std::declval<Iterator &>()).second)),
16294 + decltype(std::declval<pair_type>().second)>;
16295 + result_type operator()(Iterator &it) const { return (*it).second; }
16298 +template <typename Access,
16299 + return_value_policy Policy,
16302 - typename ValueType = decltype(*std::declval<Iterator>()),
16303 + typename ValueType,
16305 -iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
16306 - typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
16307 +iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra) {
16308 + using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
16309 + // TODO: state captures only the types of Extra, not the values
16311 if (!detail::get_type_info(typeid(state), false)) {
16312 class_<state>(handle(), "iterator", pybind11::module_local())
16313 - .def("__iter__", [](state &s) -> state& { return s; })
16314 - .def("__next__", [](state &s) -> ValueType {
16315 - if (!s.first_or_done)
16318 - s.first_or_done = false;
16319 - if (s.it == s.end) {
16320 - s.first_or_done = true;
16321 - throw stop_iteration();
16324 - }, std::forward<Extra>(extra)..., Policy);
16325 + .def("__iter__", [](state &s) -> state & { return s; })
16328 + [](state &s) -> ValueType {
16329 + if (!s.first_or_done) {
16332 + s.first_or_done = false;
16334 + if (s.it == s.end) {
16335 + s.first_or_done = true;
16336 + throw stop_iteration();
16338 + return Access()(s.it);
16339 + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
16341 + std::forward<Extra>(extra)...,
16345 return cast(state{first, last, true});
16348 -/// Makes an python iterator over the keys (`.first`) of a iterator over pairs from a
16349 -/// first and past-the-end InputIterator.
16350 +PYBIND11_NAMESPACE_END(detail)
16352 +/// Makes a python iterator from a first and past-the-end C++ InputIterator.
16353 template <return_value_policy Policy = return_value_policy::reference_internal,
16356 - typename KeyType = decltype((*std::declval<Iterator>()).first),
16357 + typename ValueType = typename detail::iterator_access<Iterator>::result_type,
16359 -iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
16360 - typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
16361 +iterator make_iterator(Iterator first, Sentinel last, Extra &&...extra) {
16362 + return detail::make_iterator_impl<detail::iterator_access<Iterator>,
16367 + Extra...>(first, last, std::forward<Extra>(extra)...);
16370 - if (!detail::get_type_info(typeid(state), false)) {
16371 - class_<state>(handle(), "iterator", pybind11::module_local())
16372 - .def("__iter__", [](state &s) -> state& { return s; })
16373 - .def("__next__", [](state &s) -> KeyType {
16374 - if (!s.first_or_done)
16377 - s.first_or_done = false;
16378 - if (s.it == s.end) {
16379 - s.first_or_done = true;
16380 - throw stop_iteration();
16382 - return (*s.it).first;
16383 - }, std::forward<Extra>(extra)..., Policy);
16385 +/// Makes a python iterator over the keys (`.first`) of a iterator over pairs from a
16386 +/// first and past-the-end InputIterator.
16387 +template <return_value_policy Policy = return_value_policy::reference_internal,
16388 + typename Iterator,
16389 + typename Sentinel,
16390 + typename KeyType = typename detail::iterator_key_access<Iterator>::result_type,
16391 + typename... Extra>
16392 +iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) {
16393 + return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
16398 + Extra...>(first, last, std::forward<Extra>(extra)...);
16401 - return cast(state{first, last, true});
16402 +/// Makes a python iterator over the values (`.second`) of a iterator over pairs from a
16403 +/// first and past-the-end InputIterator.
16404 +template <return_value_policy Policy = return_value_policy::reference_internal,
16405 + typename Iterator,
16406 + typename Sentinel,
16407 + typename ValueType = typename detail::iterator_value_access<Iterator>::result_type,
16408 + typename... Extra>
16409 +iterator make_value_iterator(Iterator first, Sentinel last, Extra &&...extra) {
16410 + return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
16415 + Extra...>(first, last, std::forward<Extra>(extra)...);
16418 /// Makes an iterator over values of an stl container or other container supporting
16419 /// `std::begin()`/`std::end()`
16420 template <return_value_policy Policy = return_value_policy::reference_internal,
16421 - typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
16423 + typename... Extra>
16424 +iterator make_iterator(Type &value, Extra &&...extra) {
16425 return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
16428 /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
16429 /// `std::begin()`/`std::end()`
16430 template <return_value_policy Policy = return_value_policy::reference_internal,
16431 - typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
16433 + typename... Extra>
16434 +iterator make_key_iterator(Type &value, Extra &&...extra) {
16435 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
16438 -template <typename InputType, typename OutputType> void implicitly_convertible() {
16439 +/// Makes an iterator over the values (`.second`) of a stl map-like container supporting
16440 +/// `std::begin()`/`std::end()`
16441 +template <return_value_policy Policy = return_value_policy::reference_internal,
16443 + typename... Extra>
16444 +iterator make_value_iterator(Type &value, Extra &&...extra) {
16445 + return make_value_iterator<Policy>(std::begin(value), std::end(value), extra...);
16448 +template <typename InputType, typename OutputType>
16449 +void implicitly_convertible() {
16452 - set_flag(bool &flag) : flag(flag) { flag = true; }
16453 + explicit set_flag(bool &flag_) : flag(flag_) { flag_ = true; }
16454 ~set_flag() { flag = false; }
16456 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
16457 static bool currently_used = false;
16458 - if (currently_used) // implicit conversions are non-reentrant
16459 + if (currently_used) { // implicit conversions are non-reentrant
16462 set_flag flag_helper(currently_used);
16463 - if (!detail::make_caster<InputType>().load(obj, false))
16464 + if (!detail::make_caster<InputType>().load(obj, false)) {
16469 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
16470 - if (result == nullptr)
16471 + if (result == nullptr) {
16477 - if (auto tinfo = detail::get_type_info(typeid(OutputType)))
16478 + if (auto *tinfo = detail::get_type_info(typeid(OutputType))) {
16479 tinfo->implicit_conversions.push_back(implicit_caster);
16482 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
16486 -template <typename ExceptionTranslator>
16487 -void register_exception_translator(ExceptionTranslator&& translator) {
16488 +inline void register_exception_translator(ExceptionTranslator &&translator) {
16489 detail::get_internals().registered_exception_translators.push_front(
16490 std::forward<ExceptionTranslator>(translator));
16494 + * Add a new module-local exception translator. Locally registered functions
16495 + * will be tried before any globally registered exception translators, which
16496 + * will only be invoked if the module-local handlers do not deal with
16499 +inline void register_local_exception_translator(ExceptionTranslator &&translator) {
16500 + detail::get_local_internals().registered_exception_translators.push_front(
16501 + std::forward<ExceptionTranslator>(translator));
16505 * Wrapper to generate a new Python exception type.
16507 * This should only be used with PyErr_SetString for now.
16508 @@ -1754,45 +2517,48 @@
16509 class exception : public object {
16511 exception() = default;
16512 - exception(handle scope, const char *name, PyObject *base = PyExc_Exception) {
16513 - std::string full_name = scope.attr("__name__").cast<std::string>() +
16514 - std::string(".") + name;
16515 - m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base, NULL);
16516 - if (hasattr(scope, name))
16517 + exception(handle scope, const char *name, handle base = PyExc_Exception) {
16518 + std::string full_name
16519 + = scope.attr("__name__").cast<std::string>() + std::string(".") + name;
16520 + m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), NULL);
16521 + if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name)) {
16522 pybind11_fail("Error during initialization: multiple incompatible "
16523 - "definitions with name \"" + std::string(name) + "\"");
16524 + "definitions with name \""
16525 + + std::string(name) + "\"");
16527 scope.attr(name) = *this;
16530 // Sets the current python exception to this exception object with the given message
16531 - void operator()(const char *message) {
16532 - PyErr_SetString(m_ptr, message);
16534 + void operator()(const char *message) { PyErr_SetString(m_ptr, message); }
16537 -NAMESPACE_BEGIN(detail)
16538 +PYBIND11_NAMESPACE_BEGIN(detail)
16539 // Returns a reference to a function-local static exception object used in the simple
16540 // register_exception approach below. (It would be simpler to have the static local variable
16541 // directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
16542 template <typename CppException>
16543 -exception<CppException> &get_exception_object() { static exception<CppException> ex; return ex; }
16544 -NAMESPACE_END(detail)
16545 +exception<CppException> &get_exception_object() {
16546 + static exception<CppException> ex;
16551 - * Registers a Python exception in `m` of the given `name` and installs an exception translator to
16552 - * translate the C++ exception to the created Python exception using the exceptions what() method.
16553 - * This is intended for simple exception translations; for more complex translation, register the
16554 - * exception object and translator directly.
16556 +// Helper function for register_exception and register_local_exception
16557 template <typename CppException>
16558 -exception<CppException> ®ister_exception(handle scope,
16559 - const char *name,
16560 - PyObject *base = PyExc_Exception) {
16561 +exception<CppException> &
16562 +register_exception_impl(handle scope, const char *name, handle base, bool isLocal) {
16563 auto &ex = detail::get_exception_object<CppException>();
16564 - if (!ex) ex = exception<CppException>(scope, name, base);
16566 + ex = exception<CppException>(scope, name, base);
16569 - register_exception_translator([](std::exception_ptr p) {
16571 + auto register_func
16572 + = isLocal ? ®ister_local_exception_translator : ®ister_exception_translator;
16574 + register_func([](std::exception_ptr p) {
16579 std::rethrow_exception(p);
16580 } catch (const CppException &e) {
16581 @@ -1802,8 +2568,36 @@
16585 -NAMESPACE_BEGIN(detail)
16586 -PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
16587 +PYBIND11_NAMESPACE_END(detail)
16590 + * Registers a Python exception in `m` of the given `name` and installs a translator to
16591 + * translate the C++ exception to the created Python exception using the what() method.
16592 + * This is intended for simple exception translations; for more complex translation, register the
16593 + * exception object and translator directly.
16595 +template <typename CppException>
16596 +exception<CppException> &
16597 +register_exception(handle scope, const char *name, handle base = PyExc_Exception) {
16598 + return detail::register_exception_impl<CppException>(scope, name, base, false /* isLocal */);
16602 + * Registers a Python exception in `m` of the given `name` and installs a translator to
16603 + * translate the C++ exception to the created Python exception using the what() method.
16604 + * This translator will only be used for exceptions that are thrown in this module and will be
16605 + * tried before global exception translators, including those registered with register_exception.
16606 + * This is intended for simple exception translations; for more complex translation, register the
16607 + * exception object and translator directly.
16609 +template <typename CppException>
16610 +exception<CppException> &
16611 +register_local_exception(handle scope, const char *name, handle base = PyExc_Exception) {
16612 + return detail::register_exception_impl<CppException>(scope, name, base, true /* isLocal */);
16615 +PYBIND11_NAMESPACE_BEGIN(detail)
16616 +PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) {
16617 auto strings = tuple(args.size());
16618 for (size_t i = 0; i < args.size(); ++i) {
16619 strings[i] = str(args[i]);
16620 @@ -1816,7 +2610,7 @@
16621 file = kwargs["file"].cast<object>();
16624 - file = module::import("sys").attr("stdout");
16625 + file = module_::import("sys").attr("stdout");
16626 } catch (const error_already_set &) {
16627 /* If print() is called from code that is executed as
16628 part of garbage collection during interpreter shutdown,
16629 @@ -1830,10 +2624,11 @@
16631 write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
16633 - if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
16634 + if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) {
16635 file.attr("flush")();
16638 -NAMESPACE_END(detail)
16639 +PYBIND11_NAMESPACE_END(detail)
16641 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
16642 void print(Args &&...args) {
16643 @@ -1841,176 +2636,35 @@
16644 detail::print(c.args(), c.kwargs());
16647 -#if defined(WITH_THREAD) && !defined(PYPY_VERSION)
16649 -/* The functions below essentially reproduce the PyGILState_* API using a RAII
16650 - * pattern, but there are a few important differences:
16652 - * 1. When acquiring the GIL from an non-main thread during the finalization
16653 - * phase, the GILState API blindly terminates the calling thread, which
16654 - * is often not what is wanted. This API does not do this.
16656 - * 2. The gil_scoped_release function can optionally cut the relationship
16657 - * of a PyThreadState and its associated thread, which allows moving it to
16658 - * another thread (this is a fairly rare/advanced use case).
16660 - * 3. The reference count of an acquired thread state can be controlled. This
16661 - * can be handy to prevent cases where callbacks issued from an external
16662 - * thread would otherwise constantly construct and destroy thread state data
16665 - * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
16666 - * example which uses features 2 and 3 to migrate the Python thread of
16667 - * execution to another thread (to run the event loop on the original thread,
16671 -class gil_scoped_acquire {
16673 - PYBIND11_NOINLINE gil_scoped_acquire() {
16674 - auto const &internals = detail::get_internals();
16675 - tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
16678 - /* Check if the GIL was acquired using the PyGILState_* API instead (e.g. if
16679 - calling from a Python thread). Since we use a different key, this ensures
16680 - we don't create a new thread state and deadlock in PyEval_AcquireThread
16681 - below. Note we don't save this state with internals.tstate, since we don't
16682 - create it we would fail to clear it (its reference count should be > 0). */
16683 - tstate = PyGILState_GetThisThreadState();
16687 - tstate = PyThreadState_New(internals.istate);
16688 - #if !defined(NDEBUG)
16690 - pybind11_fail("scoped_acquire: could not create thread state!");
16692 - tstate->gilstate_counter = 0;
16693 - PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
16695 - release = detail::get_thread_state_unchecked() != tstate;
16699 - /* Work around an annoying assertion in PyThreadState_Swap */
16700 - #if defined(Py_DEBUG)
16701 - PyInterpreterState *interp = tstate->interp;
16702 - tstate->interp = nullptr;
16704 - PyEval_AcquireThread(tstate);
16705 - #if defined(Py_DEBUG)
16706 - tstate->interp = interp;
16714 - ++tstate->gilstate_counter;
16717 - PYBIND11_NOINLINE void dec_ref() {
16718 - --tstate->gilstate_counter;
16719 - #if !defined(NDEBUG)
16720 - if (detail::get_thread_state_unchecked() != tstate)
16721 - pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
16722 - if (tstate->gilstate_counter < 0)
16723 - pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
16725 - if (tstate->gilstate_counter == 0) {
16726 - #if !defined(NDEBUG)
16728 - pybind11_fail("scoped_acquire::dec_ref(): internal error!");
16730 - PyThreadState_Clear(tstate);
16731 - PyThreadState_DeleteCurrent();
16732 - PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
16737 - PYBIND11_NOINLINE ~gil_scoped_acquire() {
16740 - PyEval_SaveThread();
16743 - PyThreadState *tstate = nullptr;
16744 - bool release = true;
16747 -class gil_scoped_release {
16749 - explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
16750 - // `get_internals()` must be called here unconditionally in order to initialize
16751 - // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
16752 - // initialization race could occur as multiple threads try `gil_scoped_acquire`.
16753 - const auto &internals = detail::get_internals();
16754 - tstate = PyEval_SaveThread();
16756 - auto key = internals.tstate;
16757 - PYBIND11_TLS_DELETE_VALUE(key);
16760 - ~gil_scoped_release() {
16763 - PyEval_RestoreThread(tstate);
16765 - auto key = detail::get_internals().tstate;
16766 - PYBIND11_TLS_REPLACE_VALUE(key, tstate);
16770 - PyThreadState *tstate;
16773 -#elif defined(PYPY_VERSION)
16774 -class gil_scoped_acquire {
16775 - PyGILState_STATE state;
16777 - gil_scoped_acquire() { state = PyGILState_Ensure(); }
16778 - ~gil_scoped_acquire() { PyGILState_Release(state); }
16781 -class gil_scoped_release {
16782 - PyThreadState *state;
16784 - gil_scoped_release() { state = PyEval_SaveThread(); }
16785 - ~gil_scoped_release() { PyEval_RestoreThread(state); }
16788 -class gil_scoped_acquire { };
16789 -class gil_scoped_release { };
16792 error_already_set::~error_already_set() {
16794 - error_scope scope;
16795 gil_scoped_acquire gil;
16796 + error_scope scope;
16797 m_type.release().dec_ref();
16798 m_value.release().dec_ref();
16799 m_trace.release().dec_ref();
16803 -inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
16804 - handle self = detail::get_object_handle(this_ptr, this_type);
16806 +PYBIND11_NAMESPACE_BEGIN(detail)
16808 +get_type_override(const void *this_ptr, const type_info *this_type, const char *name) {
16809 + handle self = get_object_handle(this_ptr, this_type);
16812 - handle type = self.get_type();
16814 + handle type = type::handle_of(self);
16815 auto key = std::make_pair(type.ptr(), name);
16817 - /* Cache functions that aren't overloaded in Python to avoid
16818 + /* Cache functions that aren't overridden in Python to avoid
16819 many costly Python dictionary lookups below */
16820 - auto &cache = detail::get_internals().inactive_overload_cache;
16821 - if (cache.find(key) != cache.end())
16822 + auto &cache = get_internals().inactive_override_cache;
16823 + if (cache.find(key) != cache.end()) {
16827 - function overload = getattr(self, name, function());
16828 - if (overload.is_cpp_function()) {
16829 + function override = getattr(self, name, function());
16830 + if (override.is_cpp_function()) {
16834 @@ -2018,77 +2672,200 @@
16835 /* Don't call dispatch code if invoked from overridden function.
16836 Unfortunately this doesn't work on PyPy. */
16837 #if !defined(PYPY_VERSION)
16838 +# if PY_VERSION_HEX >= 0x03090000
16839 + PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
16840 + if (frame != nullptr) {
16841 + PyCodeObject *f_code = PyFrame_GetCode(frame);
16842 + // f_code is guaranteed to not be NULL
16843 + if ((std::string) str(f_code->co_name) == name && f_code->co_argcount > 0) {
16844 + PyObject *locals = PyEval_GetLocals();
16845 + if (locals != nullptr) {
16846 + PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code, "co_varnames");
16847 + PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
16848 + Py_DECREF(co_varnames);
16849 + PyObject *self_caller = dict_getitem(locals, self_arg);
16850 + if (self_caller == self.ptr()) {
16851 + Py_DECREF(f_code);
16852 + Py_DECREF(frame);
16853 + return function();
16857 + Py_DECREF(f_code);
16858 + Py_DECREF(frame);
16861 PyFrameObject *frame = PyThreadState_Get()->frame;
16862 - if (frame && (std::string) str(frame->f_code->co_name) == name &&
16863 - frame->f_code->co_argcount > 0) {
16864 + if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name
16865 + && frame->f_code->co_argcount > 0) {
16866 PyFrame_FastToLocals(frame);
16867 - PyObject *self_caller = PyDict_GetItem(
16868 - frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
16869 - if (self_caller == self.ptr())
16870 + PyObject *self_caller
16871 + = dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
16872 + if (self_caller == self.ptr()) {
16879 /* PyPy currently doesn't provide a detailed cpyext emulation of
16880 frame objects, so we have to emulate this using Python. This
16881 is going to be slow..*/
16882 - dict d; d["self"] = self; d["name"] = pybind11::str(name);
16883 - PyObject *result = PyRun_String(
16884 - "import inspect\n"
16885 - "frame = inspect.currentframe()\n"
16886 - "if frame is not None:\n"
16887 - " frame = frame.f_back\n"
16888 - " if frame is not None and str(frame.f_code.co_name) == name and "
16889 - "frame.f_code.co_argcount > 0:\n"
16890 - " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
16891 - " if self_caller == self:\n"
16892 - " self = None\n",
16893 - Py_file_input, d.ptr(), d.ptr());
16895 + d["self"] = self;
16896 + d["name"] = pybind11::str(name);
16898 + = PyRun_String("import inspect\n"
16899 + "frame = inspect.currentframe()\n"
16900 + "if frame is not None:\n"
16901 + " frame = frame.f_back\n"
16902 + " if frame is not None and str(frame.f_code.co_name) == name and "
16903 + "frame.f_code.co_argcount > 0:\n"
16904 + " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
16905 + " if self_caller == self:\n"
16906 + " self = None\n",
16910 if (result == nullptr)
16911 throw error_already_set();
16912 + Py_DECREF(result);
16913 if (d["self"].is_none())
16915 - Py_DECREF(result);
16921 -template <class T> function get_overload(const T *this_ptr, const char *name) {
16922 - auto tinfo = detail::get_type_info(typeid(T));
16923 - return tinfo ? get_type_overload(this_ptr, tinfo, name) : function();
16926 +PYBIND11_NAMESPACE_END(detail)
16928 -#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
16929 - pybind11::gil_scoped_acquire gil; \
16930 - pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
16931 - if (overload) { \
16932 - auto o = overload(__VA_ARGS__); \
16933 - if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
16934 - static pybind11::detail::overload_caster_t<ret_type> caster; \
16935 - return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
16937 - else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
16941 -#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
16942 - PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
16943 - return cname::fn(__VA_ARGS__)
16945 -#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
16946 - PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \
16947 - pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\"");
16949 -#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
16950 - PYBIND11_OVERLOAD_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
16952 -#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
16953 - PYBIND11_OVERLOAD_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
16955 + Try to retrieve a python method by the provided name from the instance pointed to by the
16958 + :this_ptr: The pointer to the object the overridden method should be retrieved for. This should
16959 + be the first non-trampoline class encountered in the inheritance chain.
16960 + :name: The name of the overridden Python method to retrieve.
16961 + :return: The Python method by this name from the object or an empty function wrapper.
16963 +template <class T>
16964 +function get_override(const T *this_ptr, const char *name) {
16965 + auto *tinfo = detail::get_type_info(typeid(T));
16966 + return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
16969 +#define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
16971 + pybind11::gil_scoped_acquire gil; \
16972 + pybind11::function override \
16973 + = pybind11::get_override(static_cast<const cname *>(this), name); \
16974 + if (override) { \
16975 + auto o = override(__VA_ARGS__); \
16976 + if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
16977 + static pybind11::detail::override_caster_t<ret_type> caster; \
16978 + return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
16980 + return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
16985 + Macro to populate the virtual method in the trampoline class. This macro tries to look up a
16986 + method named 'fn' from the Python side, deals with the :ref:`gil` and necessary argument
16987 + conversions to call this method and return the appropriate type.
16988 + See :ref:`overriding_virtuals` for more information. This macro should be used when the method
16989 + name in C is not the same as the method name in Python. For example with `__str__`.
16991 + .. code-block:: cpp
16993 + std::string toString() override {
16994 + PYBIND11_OVERRIDE_NAME(
16995 + std::string, // Return type (ret_type)
16996 + Animal, // Parent class (cname)
16997 + "__str__", // Name of method in Python (name)
16998 + toString, // Name of function in C++ (fn)
17002 +#define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
17004 + PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
17005 + return cname::fn(__VA_ARGS__); \
17009 + Macro for pure virtual functions, this function is identical to
17010 + :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it throws if no override can be found.
17012 +#define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
17014 + PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
17015 + pybind11::pybind11_fail( \
17016 + "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
17020 + Macro to populate the virtual method in the trampoline class. This macro tries to look up the
17021 + method from the Python side, deals with the :ref:`gil` and necessary argument conversions to
17022 + call this method and return the appropriate type. This macro should be used if the method name
17023 + in C and in Python are identical.
17024 + See :ref:`overriding_virtuals` for more information.
17026 + .. code-block:: cpp
17028 + class PyAnimal : public Animal {
17030 + // Inherit the constructors
17031 + using Animal::Animal;
17033 + // Trampoline (need one for each virtual function)
17034 + std::string go(int n_times) override {
17035 + PYBIND11_OVERRIDE_PURE(
17036 + std::string, // Return type (ret_type)
17037 + Animal, // Parent class (cname)
17038 + go, // Name of function in C++ (must match Python name) (fn)
17039 + n_times // Argument(s) (...)
17044 +#define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
17045 + PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
17048 + Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`,
17049 + except that it throws if no override can be found.
17051 +#define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
17052 + PYBIND11_OVERRIDE_PURE_NAME( \
17053 + PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
17055 +// Deprecated versions
17057 +PYBIND11_DEPRECATED("get_type_overload has been deprecated")
17059 +get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
17060 + return detail::get_type_override(this_ptr, this_type, name);
17063 +template <class T>
17064 +inline function get_overload(const T *this_ptr, const char *name) {
17065 + return get_override(this_ptr, name);
17068 +#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
17069 + PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
17070 +#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
17071 + PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
17072 +#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
17073 + PYBIND11_OVERRIDE_PURE_NAME( \
17074 + PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
17075 +#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
17076 + PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
17077 +#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
17078 + PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
17080 -NAMESPACE_END(PYBIND11_NAMESPACE)
17081 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
17083 -#if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
17084 -# pragma warning(pop)
17085 -#elif defined(__GNUG__) && !defined(__clang__)
17086 -# pragma GCC diagnostic pop
17087 +#if defined(__GNUC__) && __GNUC__ == 7
17088 +# pragma GCC diagnostic pop // -Wnoexcept-type
17090 diff -Nur pythia8309.orig/plugins/python/include/pybind11/pytypes.h pythia8309/plugins/python/include/pybind11/pytypes.h
17091 --- pythia8309.orig/plugins/python/include/pybind11/pytypes.h 2023-02-16 18:12:45.000000000 +0100
17092 +++ pythia8309/plugins/python/include/pybind11/pytypes.h 2023-03-13 09:52:25.472021629 +0100
17093 @@ -11,30 +11,44 @@
17095 #include "detail/common.h"
17096 #include "buffer_info.h"
17097 -#include <utility>
17099 #include <type_traits>
17100 +#include <utility>
17102 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
17103 +#if defined(PYBIND11_HAS_OPTIONAL)
17104 +# include <optional>
17107 +#ifdef PYBIND11_HAS_STRING_VIEW
17108 +# include <string_view>
17111 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
17113 /* A few forward declarations */
17114 -class handle; class object;
17115 -class str; class iterator;
17116 -struct arg; struct arg_v;
17125 -NAMESPACE_BEGIN(detail)
17126 +PYBIND11_NAMESPACE_BEGIN(detail)
17128 -inline bool isinstance_generic(handle obj, const std::type_info &tp);
17129 +bool isinstance_generic(handle obj, const std::type_info &tp);
17131 // Accessor forward declarations
17132 -template <typename Policy> class accessor;
17133 +template <typename Policy>
17135 namespace accessor_policies {
17138 - struct generic_item;
17139 - struct sequence_item;
17140 - struct list_item;
17141 - struct tuple_item;
17145 +struct generic_item;
17146 +struct sequence_item;
17148 +struct tuple_item;
17149 +} // namespace accessor_policies
17150 using obj_attr_accessor = accessor<accessor_policies::obj_attr>;
17151 using str_attr_accessor = accessor<accessor_policies::str_attr>;
17152 using item_accessor = accessor<accessor_policies::generic_item>;
17154 using tuple_accessor = accessor<accessor_policies::tuple_item>;
17156 /// Tag and check to identify a class which implements the Python object API
17157 -class pyobject_tag { };
17158 -template <typename T> using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
17159 +class pyobject_tag {};
17160 +template <typename T>
17161 +using is_pyobject = std::is_base_of<pyobject_tag, remove_reference_t<T>>;
17164 A mixin class which adds common functions to `handle`, `object` and various accessors.
17166 args_proxy operator*() const;
17168 /// Check if the given item is contained within this object, i.e. ``item in obj``.
17169 - template <typename T> bool contains(T &&item) const;
17170 + template <typename T>
17171 + bool contains(T &&item) const;
17174 Assuming the Python object is a function or implements the ``__call__``
17175 @@ -104,22 +120,24 @@
17176 function will throw a `cast_error` exception. When the Python function
17177 call fails, a `error_already_set` exception is thrown.
17179 - template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
17180 + template <return_value_policy policy = return_value_policy::automatic_reference,
17181 + typename... Args>
17182 object operator()(Args &&...args) const;
17183 - template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
17184 + template <return_value_policy policy = return_value_policy::automatic_reference,
17185 + typename... Args>
17186 PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)")
17187 - object call(Args&&... args) const;
17188 + object call(Args &&...args) const;
17190 /// Equivalent to ``obj is other`` in Python.
17191 - bool is(object_api const& other) const { return derived().ptr() == other.derived().ptr(); }
17192 + bool is(object_api const &other) const { return derived().ptr() == other.derived().ptr(); }
17193 /// Equivalent to ``obj is None`` in Python.
17194 bool is_none() const { return derived().ptr() == Py_None; }
17195 /// Equivalent to obj == other in Python
17196 - bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); }
17197 - bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); }
17198 - bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); }
17199 + bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); }
17200 + bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); }
17201 + bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); }
17202 bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); }
17203 - bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); }
17204 + bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); }
17205 bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); }
17207 object operator-() const;
17208 @@ -151,14 +169,16 @@
17210 /// Return the object's current reference count
17211 int ref_count() const { return static_cast<int>(Py_REFCNT(derived().ptr())); }
17212 - /// Return a handle to the Python type object underlying the instance
17214 + // TODO PYBIND11_DEPRECATED(
17215 + // "Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()")
17216 handle get_type() const;
17219 bool rich_compare(object_api const &other, int value) const;
17222 -NAMESPACE_END(detail)
17223 +PYBIND11_NAMESPACE_END(detail)
17226 Holds a reference to a Python object (no reference counting)
17227 @@ -176,7 +196,8 @@
17228 /// The default constructor creates a handle with a ``nullptr``-valued pointer
17229 handle() = default;
17230 /// Creates a ``handle`` from the given raw Python object pointer
17231 - handle(PyObject *ptr) : m_ptr(ptr) { } // Allow implicit conversion from PyObject*
17232 + // NOLINTNEXTLINE(google-explicit-constructor)
17233 + handle(PyObject *ptr) : m_ptr(ptr) {} // Allow implicit conversion from PyObject*
17235 /// Return the underlying ``PyObject *`` pointer
17236 PyObject *ptr() const { return m_ptr; }
17237 @@ -187,20 +208,27 @@
17238 preferable to use the `object` class which derives from `handle` and calls
17239 this function automatically. Returns a reference to itself.
17241 - const handle& inc_ref() const & { Py_XINCREF(m_ptr); return *this; }
17242 + const handle &inc_ref() const & {
17243 + Py_XINCREF(m_ptr);
17248 Manually decrease the reference count of the Python object. Usually, it is
17249 preferable to use the `object` class which derives from `handle` and calls
17250 this function automatically. Returns a reference to itself.
17252 - const handle& dec_ref() const & { Py_XDECREF(m_ptr); return *this; }
17253 + const handle &dec_ref() const & {
17254 + Py_XDECREF(m_ptr);
17259 Attempt to cast the Python object into the given C++ type. A `cast_error`
17260 will be throw upon failure.
17262 - template <typename T> T cast() const;
17263 + template <typename T>
17265 /// Return ``true`` when the `handle` wraps a valid Python object
17266 explicit operator bool() const { return m_ptr != nullptr; }
17268 @@ -213,6 +241,7 @@
17269 bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }
17270 PYBIND11_DEPRECATED("Use handle::operator bool() instead")
17271 bool check() const { return m_ptr != nullptr; }
17274 PyObject *m_ptr = nullptr;
17276 @@ -231,33 +260,43 @@
17278 object() = default;
17279 PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()")
17280 - object(handle h, bool is_borrowed) : handle(h) { if (is_borrowed) inc_ref(); }
17281 + object(handle h, bool is_borrowed) : handle(h) {
17282 + if (is_borrowed) {
17286 /// Copy constructor; always increases the reference count
17287 object(const object &o) : handle(o) { inc_ref(); }
17288 /// Move constructor; steals the object from ``other`` and preserves its reference count
17289 - object(object &&other) noexcept { m_ptr = other.m_ptr; other.m_ptr = nullptr; }
17290 + object(object &&other) noexcept {
17291 + m_ptr = other.m_ptr;
17292 + other.m_ptr = nullptr;
17294 /// Destructor; automatically calls `handle::dec_ref()`
17295 ~object() { dec_ref(); }
17298 - Resets the internal pointer to ``nullptr`` without without decreasing the
17299 + Resets the internal pointer to ``nullptr`` without decreasing the
17300 object's reference count. The function returns a raw handle to the original
17304 - PyObject *tmp = m_ptr;
17306 - return handle(tmp);
17307 + PyObject *tmp = m_ptr;
17309 + return handle(tmp);
17312 - object& operator=(const object &other) {
17313 + object &operator=(const object &other) {
17316 + // Use temporary variable to ensure `*this` remains valid while
17317 + // `Py_XDECREF` executes, in case `*this` is accessible from Python.
17318 + handle temp(m_ptr);
17319 m_ptr = other.m_ptr;
17324 - object& operator=(object &&other) noexcept {
17325 + object &operator=(object &&other) noexcept {
17326 if (this != &other) {
17327 handle temp(m_ptr);
17328 m_ptr = other.m_ptr;
17329 @@ -268,22 +307,28 @@
17332 // Calling cast() on an object lvalue just copies (via handle::cast)
17333 - template <typename T> T cast() const &;
17334 + template <typename T>
17335 + T cast() const &;
17336 // Calling on an object rvalue does a move, if needed and/or possible
17337 - template <typename T> T cast() &&;
17338 + template <typename T>
17342 // Tags for choosing constructors from raw PyObject *
17343 - struct borrowed_t { };
17344 - struct stolen_t { };
17345 + struct borrowed_t {};
17346 + struct stolen_t {};
17348 - template <typename T> friend T reinterpret_borrow(handle);
17349 - template <typename T> friend T reinterpret_steal(handle);
17351 + template <typename T>
17352 + friend T reinterpret_borrow(handle);
17353 + template <typename T>
17354 + friend T reinterpret_steal(handle);
17358 // Only accessible from derived classes and the reinterpret_* functions
17359 object(handle h, borrowed_t) : handle(h) { inc_ref(); }
17360 - object(handle h, stolen_t) : handle(h) { }
17361 + object(handle h, stolen_t) : handle(h) {}
17365 @@ -299,7 +344,10 @@
17367 py::tuple t = reinterpret_borrow<py::tuple>(p); // <-- `p` must be already be a `tuple`
17369 -template <typename T> T reinterpret_borrow(handle h) { return {h, object::borrowed_t{}}; }
17370 +template <typename T>
17371 +T reinterpret_borrow(handle h) {
17372 + return {h, object::borrowed_t{}};
17376 Like `reinterpret_borrow`, but steals the reference.
17377 @@ -309,17 +357,26 @@
17378 PyObject *p = PyObject_Str(obj);
17379 py::str s = reinterpret_steal<py::str>(p); // <-- `p` must be already be a `str`
17381 -template <typename T> T reinterpret_steal(handle h) { return {h, object::stolen_t{}}; }
17383 -NAMESPACE_BEGIN(detail)
17384 -inline std::string error_string();
17385 -NAMESPACE_END(detail)
17386 +template <typename T>
17387 +T reinterpret_steal(handle h) {
17388 + return {h, object::stolen_t{}};
17391 +PYBIND11_NAMESPACE_BEGIN(detail)
17392 +std::string error_string();
17393 +PYBIND11_NAMESPACE_END(detail)
17395 +#if defined(_MSC_VER)
17396 +# pragma warning(push)
17397 +# pragma warning(disable : 4275 4251)
17398 +// warning C4275: An exported class was derived from a class that wasn't exported.
17399 +// Can be ignored when derived from a STL class.
17401 /// Fetch and hold an error which was already set in Python. An instance of this is typically
17402 /// thrown to propagate python-side errors back through C++ which can either be caught manually or
17403 /// else falls back to the function dispatcher (which then raises the captured error back to
17405 -class error_already_set : public std::runtime_error {
17406 +class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::runtime_error {
17408 /// Constructs a new exception from the current Python error indicator, if any. The current
17409 /// Python error indicator will be cleared.
17410 @@ -330,12 +387,30 @@
17411 error_already_set(const error_already_set &) = default;
17412 error_already_set(error_already_set &&) = default;
17414 - inline ~error_already_set();
17415 + inline ~error_already_set() override;
17417 /// Give the currently-held error back to Python, if any. If there is currently a Python error
17418 /// already set it is cleared first. After this call, the current object no longer stores the
17419 /// error variables (but the `.what()` string is still available).
17420 - void restore() { PyErr_Restore(m_type.release().ptr(), m_value.release().ptr(), m_trace.release().ptr()); }
17422 + PyErr_Restore(m_type.release().ptr(), m_value.release().ptr(), m_trace.release().ptr());
17425 + /// If it is impossible to raise the currently-held error, such as in a destructor, we can
17426 + /// write it out using Python's unraisable hook (`sys.unraisablehook`). The error context
17427 + /// should be some object whose `repr()` helps identify the location of the error. Python
17428 + /// already knows the type and value of the error, so there is no need to repeat that. After
17429 + /// this call, the current object no longer stores the error variables, and neither does
17431 + void discard_as_unraisable(object err_context) {
17433 + PyErr_WriteUnraisable(err_context.ptr());
17435 + /// An alternate version of `discard_as_unraisable()`, where a string provides information on
17436 + /// the location of the error. For example, `__func__` could be helpful.
17437 + void discard_as_unraisable(const char *err_context) {
17438 + discard_as_unraisable(reinterpret_steal<object>(PYBIND11_FROM_STRING(err_context)));
17441 // Does nothing; provided for backwards compatibility.
17442 PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated")
17443 @@ -344,17 +419,63 @@
17444 /// Check if the currently trapped error type matches the given Python exception class (or a
17445 /// subclass thereof). May also be passed a tuple to search for any exception class matches in
17446 /// the given tuple.
17447 - bool matches(handle ex) const { return PyErr_GivenExceptionMatches(ex.ptr(), m_type.ptr()); }
17448 + bool matches(handle exc) const {
17449 + return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0);
17452 - const object& type() const { return m_type; }
17453 - const object& value() const { return m_value; }
17454 - const object& trace() const { return m_trace; }
17455 + const object &type() const { return m_type; }
17456 + const object &value() const { return m_value; }
17457 + const object &trace() const { return m_trace; }
17460 object m_type, m_value, m_trace;
17462 +#if defined(_MSC_VER)
17463 +# pragma warning(pop)
17466 +#if PY_VERSION_HEX >= 0x03030000
17468 +/// Replaces the current Python error indicator with the chosen error, performing a
17469 +/// 'raise from' to indicate that the chosen error was caused by the original error.
17470 +inline void raise_from(PyObject *type, const char *message) {
17471 + // Based on _PyErr_FormatVFromCause:
17472 + // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405
17473 + // See https://github.com/pybind/pybind11/pull/2112 for details.
17474 + PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr;
17476 + assert(PyErr_Occurred());
17477 + PyErr_Fetch(&exc, &val, &tb);
17478 + PyErr_NormalizeException(&exc, &val, &tb);
17479 + if (tb != nullptr) {
17480 + PyException_SetTraceback(val, tb);
17484 + assert(!PyErr_Occurred());
17486 + PyErr_SetString(type, message);
17488 + PyErr_Fetch(&exc, &val2, &tb);
17489 + PyErr_NormalizeException(&exc, &val2, &tb);
17491 + PyException_SetCause(val2, val);
17492 + PyException_SetContext(val2, val);
17493 + PyErr_Restore(exc, val2, tb);
17496 +/// Sets the current Python error indicator with the chosen error, performing a 'raise from'
17497 +/// from the error contained in error_already_set to indicate that the chosen error was
17498 +/// caused by the original error. After this function is called error_already_set will
17499 +/// no longer contain an error.
17500 +inline void raise_from(error_already_set &err, PyObject *type, const char *message) {
17502 + raise_from(type, message);
17505 -/** \defgroup python_builtins _
17508 +/** \defgroup python_builtins const_name
17509 Unless stated otherwise, the following C++ functions behave the same
17510 as their Python counterparts.
17512 @@ -365,20 +486,29 @@
17513 `object` or a class which was exposed to Python as ``py::class_<T>``.
17515 template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0>
17516 -bool isinstance(handle obj) { return T::check_(obj); }
17517 +bool isinstance(handle obj) {
17518 + return T::check_(obj);
17521 template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0>
17522 -bool isinstance(handle obj) { return detail::isinstance_generic(obj, typeid(T)); }
17523 +bool isinstance(handle obj) {
17524 + return detail::isinstance_generic(obj, typeid(T));
17527 -template <> inline bool isinstance<handle>(handle obj) = delete;
17528 -template <> inline bool isinstance<object>(handle obj) { return obj.ptr() != nullptr; }
17530 +inline bool isinstance<handle>(handle) = delete;
17532 +inline bool isinstance<object>(handle obj) {
17533 + return obj.ptr() != nullptr;
17536 /// \ingroup python_builtins
17537 /// Return true if ``obj`` is an instance of the ``type``.
17538 inline bool isinstance(handle obj, handle type) {
17539 const auto result = PyObject_IsInstance(obj.ptr(), type.ptr());
17540 - if (result == -1)
17541 + if (result == -1) {
17542 throw error_already_set();
17544 return result != 0;
17547 @@ -393,124 +523,190 @@
17550 inline void delattr(handle obj, handle name) {
17551 - if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) { throw error_already_set(); }
17552 + if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) {
17553 + throw error_already_set();
17557 inline void delattr(handle obj, const char *name) {
17558 - if (PyObject_DelAttrString(obj.ptr(), name) != 0) { throw error_already_set(); }
17559 + if (PyObject_DelAttrString(obj.ptr(), name) != 0) {
17560 + throw error_already_set();
17564 inline object getattr(handle obj, handle name) {
17565 PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr());
17566 - if (!result) { throw error_already_set(); }
17568 + throw error_already_set();
17570 return reinterpret_steal<object>(result);
17573 inline object getattr(handle obj, const char *name) {
17574 PyObject *result = PyObject_GetAttrString(obj.ptr(), name);
17575 - if (!result) { throw error_already_set(); }
17577 + throw error_already_set();
17579 return reinterpret_steal<object>(result);
17582 inline object getattr(handle obj, handle name, handle default_) {
17583 if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) {
17584 return reinterpret_steal<object>(result);
17587 - return reinterpret_borrow<object>(default_);
17590 + return reinterpret_borrow<object>(default_);
17593 inline object getattr(handle obj, const char *name, handle default_) {
17594 if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) {
17595 return reinterpret_steal<object>(result);
17598 - return reinterpret_borrow<object>(default_);
17601 + return reinterpret_borrow<object>(default_);
17604 inline void setattr(handle obj, handle name, handle value) {
17605 - if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) { throw error_already_set(); }
17606 + if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) {
17607 + throw error_already_set();
17611 inline void setattr(handle obj, const char *name, handle value) {
17612 - if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { throw error_already_set(); }
17613 + if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) {
17614 + throw error_already_set();
17618 inline ssize_t hash(handle obj) {
17619 auto h = PyObject_Hash(obj.ptr());
17620 - if (h == -1) { throw error_already_set(); }
17622 + throw error_already_set();
17627 /// @} python_builtins
17629 -NAMESPACE_BEGIN(detail)
17630 +PYBIND11_NAMESPACE_BEGIN(detail)
17631 inline handle get_function(handle value) {
17633 #if PY_MAJOR_VERSION >= 3
17634 - if (PyInstanceMethod_Check(value.ptr()))
17635 + if (PyInstanceMethod_Check(value.ptr())) {
17636 value = PyInstanceMethod_GET_FUNCTION(value.ptr());
17640 - if (PyMethod_Check(value.ptr()))
17641 + if (PyMethod_Check(value.ptr())) {
17642 value = PyMethod_GET_FUNCTION(value.ptr());
17648 -// Helper aliases/functions to support implicit casting of values given to python accessors/methods.
17649 -// When given a pyobject, this simply returns the pyobject as-is; for other C++ type, the value goes
17650 -// through pybind11::cast(obj) to convert it to an `object`.
17651 +// Reimplementation of python's dict helper functions to ensure that exceptions
17652 +// aren't swallowed (see #2862)
17654 +// copied from cpython _PyDict_GetItemStringWithError
17655 +inline PyObject *dict_getitemstring(PyObject *v, const char *key) {
17656 +#if PY_MAJOR_VERSION >= 3
17657 + PyObject *kv = nullptr, *rv = nullptr;
17658 + kv = PyUnicode_FromString(key);
17659 + if (kv == NULL) {
17660 + throw error_already_set();
17663 + rv = PyDict_GetItemWithError(v, kv);
17665 + if (rv == NULL && PyErr_Occurred()) {
17666 + throw error_already_set();
17670 + return PyDict_GetItemString(v, key);
17674 +inline PyObject *dict_getitem(PyObject *v, PyObject *key) {
17675 +#if PY_MAJOR_VERSION >= 3
17676 + PyObject *rv = PyDict_GetItemWithError(v, key);
17677 + if (rv == NULL && PyErr_Occurred()) {
17678 + throw error_already_set();
17682 + return PyDict_GetItem(v, key);
17686 +// Helper aliases/functions to support implicit casting of values given to python
17687 +// accessors/methods. When given a pyobject, this simply returns the pyobject as-is; for other C++
17688 +// type, the value goes through pybind11::cast(obj) to convert it to an `object`.
17689 template <typename T, enable_if_t<is_pyobject<T>::value, int> = 0>
17690 -auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) { return std::forward<T>(o); }
17691 +auto object_or_cast(T &&o) -> decltype(std::forward<T>(o)) {
17692 + return std::forward<T>(o);
17694 // The following casting version is implemented in cast.h:
17695 template <typename T, enable_if_t<!is_pyobject<T>::value, int> = 0>
17696 object object_or_cast(T &&o);
17697 // Match a PyObject*, which we want to convert directly to handle via its converting constructor
17698 inline handle object_or_cast(PyObject *ptr) { return ptr; }
17700 +#if defined(_MSC_VER) && _MSC_VER < 1920
17701 +# pragma warning(push)
17702 +# pragma warning(disable : 4522) // warning C4522: multiple assignment operators specified
17704 template <typename Policy>
17705 class accessor : public object_api<accessor<Policy>> {
17706 using key_type = typename Policy::key_type;
17709 - accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) { }
17710 + accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) {}
17711 accessor(const accessor &) = default;
17712 - accessor(accessor &&) = default;
17713 + accessor(accessor &&) noexcept = default;
17715 - // accessor overload required to override default assignment operator (templates are not allowed
17716 - // to replace default compiler-generated assignments).
17717 + // accessor overload required to override default assignment operator (templates are not
17718 + // allowed to replace default compiler-generated assignments).
17719 void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); }
17720 void operator=(const accessor &a) & { operator=(handle(a)); }
17722 - template <typename T> void operator=(T &&value) && {
17723 + template <typename T>
17724 + void operator=(T &&value) && {
17725 Policy::set(obj, key, object_or_cast(std::forward<T>(value)));
17727 - template <typename T> void operator=(T &&value) & {
17728 + template <typename T>
17729 + void operator=(T &&value) & {
17730 get_cache() = reinterpret_borrow<object>(object_or_cast(std::forward<T>(value)));
17733 template <typename T = Policy>
17734 - PYBIND11_DEPRECATED("Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
17735 - explicit operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value ||
17736 - std::is_same<T, accessor_policies::obj_attr>::value, bool>() const {
17737 + PYBIND11_DEPRECATED(
17738 + "Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)")
17740 + operator enable_if_t<std::is_same<T, accessor_policies::str_attr>::value
17741 + || std::is_same<T, accessor_policies::obj_attr>::value,
17743 return hasattr(obj, key);
17745 template <typename T = Policy>
17746 PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)")
17747 - explicit operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const {
17749 + operator enable_if_t<std::is_same<T, accessor_policies::generic_item>::value, bool>() const {
17750 return obj.contains(key);
17753 + // NOLINTNEXTLINE(google-explicit-constructor)
17754 operator object() const { return get_cache(); }
17755 PyObject *ptr() const { return get_cache().ptr(); }
17756 - template <typename T> T cast() const { return get_cache().template cast<T>(); }
17757 + template <typename T>
17759 + return get_cache().template cast<T>();
17763 object &get_cache() const {
17764 - if (!cache) { cache = Policy::get(obj, key); }
17766 + cache = Policy::get(obj, key);
17771 @@ -519,8 +715,11 @@
17773 mutable object cache;
17775 +#if defined(_MSC_VER) && _MSC_VER < 1920
17776 +# pragma warning(pop)
17779 -NAMESPACE_BEGIN(accessor_policies)
17780 +PYBIND11_NAMESPACE_BEGIN(accessor_policies)
17782 using key_type = object;
17783 static object get(handle obj, handle key) { return getattr(obj, key); }
17784 @@ -538,27 +737,35 @@
17786 static object get(handle obj, handle key) {
17787 PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr());
17788 - if (!result) { throw error_already_set(); }
17790 + throw error_already_set();
17792 return reinterpret_steal<object>(result);
17795 static void set(handle obj, handle key, handle val) {
17796 - if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) { throw error_already_set(); }
17797 + if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) {
17798 + throw error_already_set();
17803 struct sequence_item {
17804 using key_type = size_t;
17806 - static object get(handle obj, size_t index) {
17807 - PyObject *result = PySequence_GetItem(obj.ptr(), static_cast<ssize_t>(index));
17808 - if (!result) { throw error_already_set(); }
17809 + template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
17810 + static object get(handle obj, const IdxType &index) {
17811 + PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index));
17813 + throw error_already_set();
17815 return reinterpret_steal<object>(result);
17818 - static void set(handle obj, size_t index, handle val) {
17819 + template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
17820 + static void set(handle obj, const IdxType &index, handle val) {
17821 // PySequence_SetItem does not steal a reference to 'val'
17822 - if (PySequence_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.ptr()) != 0) {
17823 + if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) {
17824 throw error_already_set();
17827 @@ -567,15 +774,19 @@
17829 using key_type = size_t;
17831 - static object get(handle obj, size_t index) {
17832 - PyObject *result = PyList_GetItem(obj.ptr(), static_cast<ssize_t>(index));
17833 - if (!result) { throw error_already_set(); }
17834 + template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
17835 + static object get(handle obj, const IdxType &index) {
17836 + PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index));
17838 + throw error_already_set();
17840 return reinterpret_borrow<object>(result);
17843 - static void set(handle obj, size_t index, handle val) {
17844 + template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
17845 + static void set(handle obj, const IdxType &index, handle val) {
17846 // PyList_SetItem steals a reference to 'val'
17847 - if (PyList_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.inc_ref().ptr()) != 0) {
17848 + if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
17849 throw error_already_set();
17852 @@ -584,20 +795,24 @@
17853 struct tuple_item {
17854 using key_type = size_t;
17856 - static object get(handle obj, size_t index) {
17857 - PyObject *result = PyTuple_GetItem(obj.ptr(), static_cast<ssize_t>(index));
17858 - if (!result) { throw error_already_set(); }
17859 + template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
17860 + static object get(handle obj, const IdxType &index) {
17861 + PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index));
17863 + throw error_already_set();
17865 return reinterpret_borrow<object>(result);
17868 - static void set(handle obj, size_t index, handle val) {
17869 + template <typename IdxType, detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
17870 + static void set(handle obj, const IdxType &index, handle val) {
17871 // PyTuple_SetItem steals a reference to 'val'
17872 - if (PyTuple_SetItem(obj.ptr(), static_cast<ssize_t>(index), val.inc_ref().ptr()) != 0) {
17873 + if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) {
17874 throw error_already_set();
17878 -NAMESPACE_END(accessor_policies)
17879 +PYBIND11_NAMESPACE_END(accessor_policies)
17881 /// STL iterator template used for tuple, list, sequence and dict
17882 template <typename Policy>
17883 @@ -612,39 +827,68 @@
17884 using pointer = typename Policy::pointer;
17886 generic_iterator() = default;
17887 - generic_iterator(handle seq, ssize_t index) : Policy(seq, index) { }
17888 + generic_iterator(handle seq, ssize_t index) : Policy(seq, index) {}
17890 + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
17891 reference operator*() const { return Policy::dereference(); }
17892 + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
17893 reference operator[](difference_type n) const { return *(*this + n); }
17894 pointer operator->() const { return **this; }
17896 - It &operator++() { Policy::increment(); return *this; }
17897 - It operator++(int) { auto copy = *this; Policy::increment(); return copy; }
17898 - It &operator--() { Policy::decrement(); return *this; }
17899 - It operator--(int) { auto copy = *this; Policy::decrement(); return copy; }
17900 - It &operator+=(difference_type n) { Policy::advance(n); return *this; }
17901 - It &operator-=(difference_type n) { Policy::advance(-n); return *this; }
17902 + It &operator++() {
17903 + Policy::increment();
17906 + It operator++(int) {
17907 + auto copy = *this;
17908 + Policy::increment();
17911 + It &operator--() {
17912 + Policy::decrement();
17915 + It operator--(int) {
17916 + auto copy = *this;
17917 + Policy::decrement();
17920 + It &operator+=(difference_type n) {
17921 + Policy::advance(n);
17924 + It &operator-=(difference_type n) {
17925 + Policy::advance(-n);
17929 - friend It operator+(const It &a, difference_type n) { auto copy = a; return copy += n; }
17930 + friend It operator+(const It &a, difference_type n) {
17932 + return copy += n;
17934 friend It operator+(difference_type n, const It &b) { return b + n; }
17935 - friend It operator-(const It &a, difference_type n) { auto copy = a; return copy -= n; }
17936 + friend It operator-(const It &a, difference_type n) {
17938 + return copy -= n;
17940 friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); }
17942 friend bool operator==(const It &a, const It &b) { return a.equal(b); }
17943 friend bool operator!=(const It &a, const It &b) { return !(a == b); }
17944 - friend bool operator< (const It &a, const It &b) { return b - a > 0; }
17945 - friend bool operator> (const It &a, const It &b) { return b < a; }
17946 + friend bool operator<(const It &a, const It &b) { return b - a > 0; }
17947 + friend bool operator>(const It &a, const It &b) { return b < a; }
17948 friend bool operator>=(const It &a, const It &b) { return !(a < b); }
17949 friend bool operator<=(const It &a, const It &b) { return !(a > b); }
17952 -NAMESPACE_BEGIN(iterator_policies)
17953 +PYBIND11_NAMESPACE_BEGIN(iterator_policies)
17954 /// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers
17955 template <typename T>
17956 struct arrow_proxy {
17959 - arrow_proxy(T &&value) : value(std::move(value)) { }
17960 + // NOLINTNEXTLINE(google-explicit-constructor)
17961 + arrow_proxy(T &&value) noexcept : value(std::move(value)) {}
17962 T *operator->() const { return &value; }
17965 @@ -653,11 +897,12 @@
17967 using iterator_category = std::random_access_iterator_tag;
17968 using value_type = handle;
17969 - using reference = const handle;
17970 + using reference = const handle; // PR #3263
17971 using pointer = arrow_proxy<const handle>;
17973 - sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) { }
17974 + sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) {}
17976 + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
17977 reference dereference() const { return *ptr; }
17978 void increment() { ++ptr; }
17979 void decrement() { --ptr; }
17980 @@ -677,7 +922,7 @@
17981 using reference = sequence_accessor;
17982 using pointer = arrow_proxy<const sequence_accessor>;
17984 - sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) { }
17985 + sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) {}
17987 reference dereference() const { return {obj, static_cast<size_t>(index)}; }
17988 void increment() { ++index; }
17989 @@ -696,22 +941,27 @@
17991 using iterator_category = std::forward_iterator_tag;
17992 using value_type = std::pair<handle, handle>;
17993 - using reference = const value_type;
17994 + using reference = const value_type; // PR #3263
17995 using pointer = arrow_proxy<const value_type>;
17997 dict_readonly() = default;
17998 dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); }
18000 + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
18001 reference dereference() const { return {key, value}; }
18002 - void increment() { if (!PyDict_Next(obj.ptr(), &pos, &key, &value)) { pos = -1; } }
18003 + void increment() {
18004 + if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) {
18008 bool equal(const dict_readonly &b) const { return pos == b.pos; }
18012 - PyObject *key, *value;
18013 + PyObject *key = nullptr, *value = nullptr;
18016 -NAMESPACE_END(iterator_policies)
18017 +PYBIND11_NAMESPACE_END(iterator_policies)
18019 #if !defined(PYPY_VERSION)
18020 using tuple_iterator = generic_iterator<iterator_policies::sequence_fast_readonly>;
18021 @@ -729,38 +979,47 @@
18033 inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
18034 -#if PY_MAJOR_VERSION >= 3
18035 inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }
18037 +#ifdef PYBIND11_STR_LEGACY_PERMISSIVE
18038 +inline bool PyUnicode_Check_Permissive(PyObject *o) {
18039 + return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o);
18041 +# define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive
18043 +# define PYBIND11_STR_CHECK_FUN PyUnicode_Check
18046 -inline bool PyUnicode_Check_Permissive(PyObject *o) { return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); }
18047 +inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; }
18049 class kwargs_proxy : public handle {
18051 - explicit kwargs_proxy(handle h) : handle(h) { }
18052 + explicit kwargs_proxy(handle h) : handle(h) {}
18055 class args_proxy : public handle {
18057 - explicit args_proxy(handle h) : handle(h) { }
18058 + explicit args_proxy(handle h) : handle(h) {}
18059 kwargs_proxy operator*() const { return kwargs_proxy(*this); }
18062 /// Python argument categories (using PEP 448 terms)
18063 -template <typename T> using is_keyword = std::is_base_of<arg, T>;
18064 -template <typename T> using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking
18065 -template <typename T> using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking
18066 -template <typename T> using is_positional = satisfies_none_of<T,
18067 - is_keyword, is_s_unpacking, is_ds_unpacking
18069 -template <typename T> using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>;
18070 +template <typename T>
18071 +using is_keyword = std::is_base_of<arg, T>;
18072 +template <typename T>
18073 +using is_s_unpacking = std::is_same<args_proxy, T>; // * unpacking
18074 +template <typename T>
18075 +using is_ds_unpacking = std::is_same<kwargs_proxy, T>; // ** unpacking
18076 +template <typename T>
18077 +using is_positional = satisfies_none_of<T, is_keyword, is_s_unpacking, is_ds_unpacking>;
18078 +template <typename T>
18079 +using is_keyword_or_ds = satisfies_any_of<T, is_keyword, is_ds_unpacking>;
18081 // Call argument collector forward declarations
18082 template <return_value_policy policy = return_value_policy::automatic_reference>
18083 @@ -768,43 +1027,66 @@
18084 template <return_value_policy policy = return_value_policy::automatic_reference>
18085 class unpacking_collector;
18087 -NAMESPACE_END(detail)
18088 +PYBIND11_NAMESPACE_END(detail)
18090 // TODO: After the deprecated constructors are removed, this macro can be simplified by
18091 // inheriting ctors: `using Parent::Parent`. It's not an option right now because
18092 // the `using` statement triggers the parent deprecation warning even if the ctor
18093 // isn't even used.
18094 -#define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
18096 - PYBIND11_DEPRECATED("Use reinterpret_borrow<"#Name">() or reinterpret_steal<"#Name">()") \
18097 - Name(handle h, bool is_borrowed) : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) { } \
18098 - Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) { } \
18099 - Name(handle h, stolen_t) : Parent(h, stolen_t{}) { } \
18100 - PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
18101 - bool check() const { return m_ptr != nullptr && (bool) CheckFun(m_ptr); } \
18102 - static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); }
18104 -#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
18105 - PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
18106 - /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
18107 - Name(const object &o) \
18108 - : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) \
18109 - { if (!m_ptr) throw error_already_set(); } \
18110 - Name(object &&o) \
18111 - : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) \
18112 - { if (!m_ptr) throw error_already_set(); } \
18113 - template <typename Policy_> \
18114 - Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) { }
18116 -#define PYBIND11_OBJECT(Name, Parent, CheckFun) \
18117 - PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
18118 - /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
18119 - Name(const object &o) : Parent(o) { } \
18120 - Name(object &&o) : Parent(std::move(o)) { }
18122 -#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
18123 - PYBIND11_OBJECT(Name, Parent, CheckFun) \
18124 - Name() : Parent() { }
18125 +#define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
18127 + PYBIND11_DEPRECATED("Use reinterpret_borrow<" #Name ">() or reinterpret_steal<" #Name ">()") \
18128 + Name(handle h, bool is_borrowed) \
18129 + : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {} \
18130 + Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {} \
18131 + Name(handle h, stolen_t) : Parent(h, stolen_t{}) {} \
18132 + PYBIND11_DEPRECATED("Use py::isinstance<py::python_type>(obj) instead") \
18133 + bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \
18134 + static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \
18135 + template <typename Policy_> /* NOLINTNEXTLINE(google-explicit-constructor) */ \
18136 + Name(const ::pybind11::detail::accessor<Policy_> &a) : Name(object(a)) {}
18138 +#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
18139 + PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
18140 + /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
18141 + /* NOLINTNEXTLINE(google-explicit-constructor) */ \
18142 + Name(const object &o) \
18143 + : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
18145 + throw error_already_set(); \
18147 + /* NOLINTNEXTLINE(google-explicit-constructor) */ \
18148 + Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \
18150 + throw error_already_set(); \
18153 +#define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \
18154 + PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \
18155 + Name() : Parent() {}
18157 +#define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \
18158 + ::pybind11::type_error("Object of type '" \
18159 + + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) \
18160 + + "' is not an instance of '" #Name "'")
18162 +#define PYBIND11_OBJECT(Name, Parent, CheckFun) \
18163 + PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \
18164 + /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \
18165 + /* NOLINTNEXTLINE(google-explicit-constructor) */ \
18166 + Name(const object &o) : Parent(o) { \
18167 + if (m_ptr && !check_(m_ptr)) \
18168 + throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
18170 + /* NOLINTNEXTLINE(google-explicit-constructor) */ \
18171 + Name(object &&o) : Parent(std::move(o)) { \
18172 + if (m_ptr && !check_(m_ptr)) \
18173 + throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \
18176 +#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \
18177 + PYBIND11_OBJECT(Name, Parent, CheckFun) \
18178 + Name() : Parent() {}
18180 /// \addtogroup pytypes
18182 @@ -822,12 +1104,12 @@
18183 using iterator_category = std::input_iterator_tag;
18184 using difference_type = ssize_t;
18185 using value_type = handle;
18186 - using reference = const handle;
18187 + using reference = const handle; // PR #3263
18188 using pointer = const handle *;
18190 PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check)
18192 - iterator& operator++() {
18193 + iterator &operator++() {
18197 @@ -838,15 +1120,19 @@
18201 + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
18202 reference operator*() const {
18203 if (m_ptr && !value.ptr()) {
18204 - auto& self = const_cast<iterator &>(*this);
18205 + auto &self = const_cast<iterator &>(*this);
18211 - pointer operator->() const { operator*(); return &value; }
18212 + pointer operator->() const {
18218 The value which marks the end of the iteration. ``it == iterator::sentinel()``
18219 @@ -869,13 +1155,41 @@
18222 value = reinterpret_steal<object>(PyIter_Next(m_ptr));
18223 - if (PyErr_Occurred()) { throw error_already_set(); }
18224 + if (PyErr_Occurred()) {
18225 + throw error_already_set();
18233 +class type : public object {
18235 + PYBIND11_OBJECT(type, object, PyType_Check)
18237 + /// Return a type handle from a handle or an object
18238 + static handle handle_of(handle h) { return handle((PyObject *) Py_TYPE(h.ptr())); }
18240 + /// Return a type object from a handle or an object
18241 + static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); }
18243 + // Defined in pybind11/cast.h
18244 + /// Convert C++ type to handle if previously registered. Does not convert
18245 + /// standard types, like int, float. etc. yet.
18246 + /// See https://github.com/pybind/pybind11/issues/2486
18247 + template <typename T>
18248 + static handle handle_of();
18250 + /// Convert C++ type to type if previously registered. Does not convert
18251 + /// standard types, like int, float. etc. yet.
18252 + /// See https://github.com/pybind/pybind11/issues/2486
18253 + template <typename T>
18254 + static type of() {
18255 + return type(type::handle_of<T>(), borrowed_t{});
18259 class iterable : public object {
18261 PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check)
18262 @@ -885,20 +1199,41 @@
18264 class str : public object {
18266 - PYBIND11_OBJECT_CVT(str, object, detail::PyUnicode_Check_Permissive, raw_str)
18267 + PYBIND11_OBJECT_CVT(str, object, PYBIND11_STR_CHECK_FUN, raw_str)
18269 - str(const char *c, size_t n)
18270 - : object(PyUnicode_FromStringAndSize(c, (ssize_t) n), stolen_t{}) {
18271 - if (!m_ptr) pybind11_fail("Could not allocate string object!");
18272 + template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
18273 + str(const char *c, const SzType &n)
18274 + : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
18276 + pybind11_fail("Could not allocate string object!");
18280 - // 'explicit' is explicitly omitted from the following constructors to allow implicit conversion to py::str from C++ string-like objects
18281 - str(const char *c = "")
18282 - : object(PyUnicode_FromString(c), stolen_t{}) {
18283 - if (!m_ptr) pybind11_fail("Could not allocate string object!");
18284 + // 'explicit' is explicitly omitted from the following constructors to allow implicit
18285 + // conversion to py::str from C++ string-like objects
18286 + // NOLINTNEXTLINE(google-explicit-constructor)
18287 + str(const char *c = "") : object(PyUnicode_FromString(c), stolen_t{}) {
18289 + pybind11_fail("Could not allocate string object!");
18293 - str(const std::string &s) : str(s.data(), s.size()) { }
18294 + // NOLINTNEXTLINE(google-explicit-constructor)
18295 + str(const std::string &s) : str(s.data(), s.size()) {}
18297 +#ifdef PYBIND11_HAS_STRING_VIEW
18298 + // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
18299 + template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>
18300 + // NOLINTNEXTLINE(google-explicit-constructor)
18301 + str(T s) : str(s.data(), s.size()) {}
18303 +# ifdef PYBIND11_HAS_U8STRING
18304 + // reinterpret_cast here is safe (C++20 guarantees char8_t has the same size/alignment as char)
18305 + // NOLINTNEXTLINE(google-explicit-constructor)
18306 + str(std::u8string_view s) : str(reinterpret_cast<const char *>(s.data()), s.size()) {}
18311 explicit str(const bytes &b);
18313 @@ -906,19 +1241,26 @@
18314 Return a string representation of the object. This is analogous to
18315 the ``str()`` function in Python.
18317 - explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { }
18318 + explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) {
18320 + throw error_already_set();
18324 + // NOLINTNEXTLINE(google-explicit-constructor)
18325 operator std::string() const {
18326 object temp = *this;
18327 if (PyUnicode_Check(m_ptr)) {
18328 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(m_ptr));
18330 - pybind11_fail("Unable to extract string contents! (encoding issue)");
18332 + throw error_already_set();
18337 - if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length))
18338 + char *buffer = nullptr;
18339 + ssize_t length = 0;
18340 + if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length)) {
18341 pybind11_fail("Unable to extract string contents! (invalid type)");
18343 return std::string(buffer, (size_t) length);
18346 @@ -932,9 +1274,11 @@
18347 static PyObject *raw_str(PyObject *op) {
18348 PyObject *str_value = PyObject_Str(op);
18349 #if PY_MAJOR_VERSION < 3
18350 - if (!str_value) throw error_already_set();
18352 + throw error_already_set();
18353 PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
18354 - Py_XDECREF(str_value); str_value = unicode;
18355 + Py_XDECREF(str_value);
18356 + str_value = unicode;
18360 @@ -946,7 +1290,7 @@
18361 String literal version of `str`
18363 inline str operator"" _s(const char *s, size_t size) { return {s, size}; }
18365 +} // namespace literals
18367 /// \addtogroup pytypes
18369 @@ -955,141 +1299,211 @@
18370 PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK)
18372 // Allow implicit conversion:
18373 - bytes(const char *c = "")
18374 - : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) {
18375 - if (!m_ptr) pybind11_fail("Could not allocate bytes object!");
18376 + // NOLINTNEXTLINE(google-explicit-constructor)
18377 + bytes(const char *c = "") : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) {
18379 + pybind11_fail("Could not allocate bytes object!");
18383 - bytes(const char *c, size_t n)
18384 - : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, (ssize_t) n), stolen_t{}) {
18385 - if (!m_ptr) pybind11_fail("Could not allocate bytes object!");
18386 + template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
18387 + bytes(const char *c, const SzType &n)
18388 + : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, ssize_t_cast(n)), stolen_t{}) {
18390 + pybind11_fail("Could not allocate bytes object!");
18394 // Allow implicit conversion:
18395 - bytes(const std::string &s) : bytes(s.data(), s.size()) { }
18396 + // NOLINTNEXTLINE(google-explicit-constructor)
18397 + bytes(const std::string &s) : bytes(s.data(), s.size()) {}
18399 explicit bytes(const pybind11::str &s);
18401 + // NOLINTNEXTLINE(google-explicit-constructor)
18402 operator std::string() const {
18405 - if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length))
18406 + char *buffer = nullptr;
18407 + ssize_t length = 0;
18408 + if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length)) {
18409 pybind11_fail("Unable to extract bytes contents!");
18411 return std::string(buffer, (size_t) length);
18414 +#ifdef PYBIND11_HAS_STRING_VIEW
18415 + // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521).
18416 + template <typename T, detail::enable_if_t<std::is_same<T, std::string_view>::value, int> = 0>
18417 + // NOLINTNEXTLINE(google-explicit-constructor)
18418 + bytes(T s) : bytes(s.data(), s.size()) {}
18420 + // Obtain a string view that views the current `bytes` buffer value. Note that this is only
18421 + // valid so long as the `bytes` instance remains alive and so generally should not outlive the
18422 + // lifetime of the `bytes` instance.
18423 + // NOLINTNEXTLINE(google-explicit-constructor)
18424 + operator std::string_view() const {
18425 + char *buffer = nullptr;
18426 + ssize_t length = 0;
18427 + if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length)) {
18428 + pybind11_fail("Unable to extract bytes contents!");
18430 + return {buffer, static_cast<size_t>(length)};
18434 +// Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
18435 +// are included in the doxygen group; close here and reopen after as a workaround
18438 inline bytes::bytes(const pybind11::str &s) {
18440 if (PyUnicode_Check(s.ptr())) {
18441 temp = reinterpret_steal<object>(PyUnicode_AsUTF8String(s.ptr()));
18444 pybind11_fail("Unable to extract string contents! (encoding issue)");
18449 - if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length))
18450 + char *buffer = nullptr;
18451 + ssize_t length = 0;
18452 + if (PYBIND11_BYTES_AS_STRING_AND_SIZE(temp.ptr(), &buffer, &length)) {
18453 pybind11_fail("Unable to extract string contents! (invalid type)");
18455 auto obj = reinterpret_steal<object>(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length));
18458 pybind11_fail("Could not allocate bytes object!");
18460 m_ptr = obj.release().ptr();
18463 -inline str::str(const bytes& b) {
18466 - if (PYBIND11_BYTES_AS_STRING_AND_SIZE(b.ptr(), &buffer, &length))
18467 +inline str::str(const bytes &b) {
18468 + char *buffer = nullptr;
18469 + ssize_t length = 0;
18470 + if (PYBIND11_BYTES_AS_STRING_AND_SIZE(b.ptr(), &buffer, &length)) {
18471 pybind11_fail("Unable to extract bytes contents!");
18472 - auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, (ssize_t) length));
18475 + auto obj = reinterpret_steal<object>(PyUnicode_FromStringAndSize(buffer, length));
18477 pybind11_fail("Could not allocate string object!");
18479 m_ptr = obj.release().ptr();
18482 +/// \addtogroup pytypes
18484 +class bytearray : public object {
18486 + PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject)
18488 + template <typename SzType, detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
18489 + bytearray(const char *c, const SzType &n)
18490 + : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) {
18492 + pybind11_fail("Could not allocate bytearray object!");
18496 + bytearray() : bytearray("", 0) {}
18498 + explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) {}
18500 + size_t size() const { return static_cast<size_t>(PyByteArray_Size(m_ptr)); }
18502 + explicit operator std::string() const {
18503 + char *buffer = PyByteArray_AS_STRING(m_ptr);
18504 + ssize_t size = PyByteArray_GET_SIZE(m_ptr);
18505 + return std::string(buffer, static_cast<size_t>(size));
18508 +// Note: breathe >= 4.17.0 will fail to build docs if the below two constructors
18509 +// are included in the doxygen group; close here and reopen after as a workaround
18512 +/// \addtogroup pytypes
18514 class none : public object {
18516 PYBIND11_OBJECT(none, object, detail::PyNone_Check)
18517 - none() : object(Py_None, borrowed_t{}) { }
18518 + none() : object(Py_None, borrowed_t{}) {}
18521 -#if PY_MAJOR_VERSION >= 3
18522 class ellipsis : public object {
18524 PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check)
18525 - ellipsis() : object(Py_Ellipsis, borrowed_t{}) { }
18526 + ellipsis() : object(Py_Ellipsis, borrowed_t{}) {}
18530 class bool_ : public object {
18532 PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool)
18533 - bool_() : object(Py_False, borrowed_t{}) { }
18534 + bool_() : object(Py_False, borrowed_t{}) {}
18535 // Allow implicit conversion from and to `bool`:
18536 - bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) { }
18537 - operator bool() const { return m_ptr && PyLong_AsLong(m_ptr) != 0; }
18538 + // NOLINTNEXTLINE(google-explicit-constructor)
18539 + bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) {}
18540 + // NOLINTNEXTLINE(google-explicit-constructor)
18541 + operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; }
18544 /// Return the truth value of an object -- always returns a new reference
18545 static PyObject *raw_bool(PyObject *op) {
18546 const auto value = PyObject_IsTrue(op);
18547 - if (value == -1) return nullptr;
18548 - return handle(value ? Py_True : Py_False).inc_ref().ptr();
18549 + if (value == -1) {
18552 + return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr();
18556 -NAMESPACE_BEGIN(detail)
18557 +PYBIND11_NAMESPACE_BEGIN(detail)
18558 // Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1;
18559 // otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned).
18560 // (The distinction is critically important when casting a returned -1 error value to some other
18561 // unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes).
18562 template <typename Unsigned>
18563 Unsigned as_unsigned(PyObject *o) {
18564 - if (sizeof(Unsigned) <= sizeof(unsigned long)
18565 + if (PYBIND11_SILENCE_MSVC_C4127(sizeof(Unsigned) <= sizeof(unsigned long))
18566 #if PY_VERSION_HEX < 0x03000000
18567 - || PyInt_Check(o)
18568 + || PyInt_Check(o)
18571 unsigned long v = PyLong_AsUnsignedLong(o);
18572 return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
18575 - unsigned long long v = PyLong_AsUnsignedLongLong(o);
18576 - return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
18578 + unsigned long long v = PyLong_AsUnsignedLongLong(o);
18579 + return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
18581 -NAMESPACE_END(detail)
18582 +PYBIND11_NAMESPACE_END(detail)
18584 class int_ : public object {
18586 PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long)
18587 - int_() : object(PyLong_FromLong(0), stolen_t{}) { }
18588 + int_() : object(PyLong_FromLong(0), stolen_t{}) {}
18589 // Allow implicit conversion from C++ integral types:
18590 - template <typename T,
18591 - detail::enable_if_t<std::is_integral<T>::value, int> = 0>
18592 + template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0>
18593 + // NOLINTNEXTLINE(google-explicit-constructor)
18595 - if (sizeof(T) <= sizeof(long)) {
18596 - if (std::is_signed<T>::value)
18597 + if (PYBIND11_SILENCE_MSVC_C4127(sizeof(T) <= sizeof(long))) {
18598 + if (std::is_signed<T>::value) {
18599 m_ptr = PyLong_FromLong((long) value);
18602 m_ptr = PyLong_FromUnsignedLong((unsigned long) value);
18605 - if (std::is_signed<T>::value)
18606 + if (std::is_signed<T>::value) {
18607 m_ptr = PyLong_FromLongLong((long long) value);
18610 m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value);
18614 + pybind11_fail("Could not allocate int object!");
18616 - if (!m_ptr) pybind11_fail("Could not allocate int object!");
18619 - template <typename T,
18620 - detail::enable_if_t<std::is_integral<T>::value, int> = 0>
18621 + template <typename T, detail::enable_if_t<std::is_integral<T>::value, int> = 0>
18622 + // NOLINTNEXTLINE(google-explicit-constructor)
18623 operator T() const {
18624 - return std::is_unsigned<T>::value
18625 - ? detail::as_unsigned<T>(m_ptr)
18626 - : sizeof(T) <= sizeof(long)
18627 - ? (T) PyLong_AsLong(m_ptr)
18628 - : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
18629 + return std::is_unsigned<T>::value ? detail::as_unsigned<T>(m_ptr)
18630 + : sizeof(T) <= sizeof(long) ? (T) PyLong_AsLong(m_ptr)
18631 + : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr);
18635 @@ -1097,39 +1511,77 @@
18637 PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)
18638 // Allow implicit conversion from float/double:
18639 + // NOLINTNEXTLINE(google-explicit-constructor)
18640 float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
18641 - if (!m_ptr) pybind11_fail("Could not allocate float object!");
18643 + pybind11_fail("Could not allocate float object!");
18646 + // NOLINTNEXTLINE(google-explicit-constructor)
18647 float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
18648 - if (!m_ptr) pybind11_fail("Could not allocate float object!");
18650 + pybind11_fail("Could not allocate float object!");
18653 + // NOLINTNEXTLINE(google-explicit-constructor)
18654 operator float() const { return (float) PyFloat_AsDouble(m_ptr); }
18655 + // NOLINTNEXTLINE(google-explicit-constructor)
18656 operator double() const { return (double) PyFloat_AsDouble(m_ptr); }
18659 class weakref : public object {
18661 - PYBIND11_OBJECT_DEFAULT(weakref, object, PyWeakref_Check)
18662 + PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref)
18663 explicit weakref(handle obj, handle callback = {})
18664 : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) {
18665 - if (!m_ptr) pybind11_fail("Could not allocate weak reference!");
18667 + pybind11_fail("Could not allocate weak reference!");
18672 + static PyObject *raw_weakref(PyObject *o) { return PyWeakref_NewRef(o, nullptr); }
18675 class slice : public object {
18677 PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check)
18678 - slice(ssize_t start_, ssize_t stop_, ssize_t step_) {
18679 - int_ start(start_), stop(stop_), step(step_);
18680 + slice(handle start, handle stop, handle step) {
18681 m_ptr = PySlice_New(start.ptr(), stop.ptr(), step.ptr());
18682 - if (!m_ptr) pybind11_fail("Could not allocate slice object!");
18684 + pybind11_fail("Could not allocate slice object!");
18687 - bool compute(size_t length, size_t *start, size_t *stop, size_t *step,
18688 - size_t *slicelength) const {
18690 +#ifdef PYBIND11_HAS_OPTIONAL
18691 + slice(std::optional<ssize_t> start, std::optional<ssize_t> stop, std::optional<ssize_t> step)
18692 + : slice(index_to_object(start), index_to_object(stop), index_to_object(step)) {}
18694 + slice(ssize_t start_, ssize_t stop_, ssize_t step_)
18695 + : slice(int_(start_), int_(stop_), int_(step_)) {}
18699 + compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const {
18700 return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr,
18701 - (ssize_t) length, (ssize_t *) start,
18702 - (ssize_t *) stop, (ssize_t *) step,
18703 - (ssize_t *) slicelength) == 0;
18704 + (ssize_t) length,
18705 + (ssize_t *) start,
18706 + (ssize_t *) stop,
18707 + (ssize_t *) step,
18708 + (ssize_t *) slicelength)
18712 + ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const {
18713 + return PySlice_GetIndicesEx(
18714 + (PYBIND11_SLICE_OBJECT *) m_ptr, length, start, stop, step, slicelength)
18719 + template <typename T>
18720 + static object index_to_object(T index) {
18721 + return index ? object(int_(*index)) : object(none());
18725 @@ -1137,19 +1589,24 @@
18727 PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact)
18728 PYBIND11_DEPRECATED("Use reinterpret_borrow<capsule>() or reinterpret_steal<capsule>()")
18729 - capsule(PyObject *ptr, bool is_borrowed) : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) { }
18730 + capsule(PyObject *ptr, bool is_borrowed)
18731 + : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) {}
18733 - explicit capsule(const void *value, const char *name = nullptr, void (*destructor)(PyObject *) = nullptr)
18734 + explicit capsule(const void *value,
18735 + const char *name = nullptr,
18736 + void (*destructor)(PyObject *) = nullptr)
18737 : object(PyCapsule_New(const_cast<void *>(value), name, destructor), stolen_t{}) {
18740 pybind11_fail("Could not allocate capsule object!");
18744 PYBIND11_DEPRECATED("Please pass a destructor that takes a void pointer as input")
18745 capsule(const void *value, void (*destruct)(PyObject *))
18746 - : object(PyCapsule_New(const_cast<void*>(value), nullptr, destruct), stolen_t{}) {
18748 + : object(PyCapsule_New(const_cast<void *>(value), nullptr, destruct), stolen_t{}) {
18750 pybind11_fail("Could not allocate capsule object!");
18754 capsule(const void *value, void (*destructor)(void *)) {
18755 @@ -1159,70 +1616,112 @@
18761 pybind11_fail("Could not allocate capsule object!");
18764 - if (PyCapsule_SetContext(m_ptr, (void *) destructor) != 0)
18765 + if (PyCapsule_SetContext(m_ptr, (void *) destructor) != 0) {
18766 pybind11_fail("Could not set capsule context!");
18770 - capsule(void (*destructor)()) {
18771 + explicit capsule(void (*destructor)()) {
18772 m_ptr = PyCapsule_New(reinterpret_cast<void *>(destructor), nullptr, [](PyObject *o) {
18773 auto destructor = reinterpret_cast<void (*)()>(PyCapsule_GetPointer(o, nullptr));
18779 pybind11_fail("Could not allocate capsule object!");
18783 + template <typename T>
18784 + operator T *() const { // NOLINT(google-explicit-constructor)
18785 + return get_pointer<T>();
18788 - template <typename T> operator T *() const {
18789 - auto name = this->name();
18790 - T * result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));
18791 - if (!result) pybind11_fail("Unable to extract capsule contents!");
18792 + /// Get the pointer the capsule holds.
18793 + template <typename T = void>
18794 + T *get_pointer() const {
18795 + const auto *name = this->name();
18796 + T *result = static_cast<T *>(PyCapsule_GetPointer(m_ptr, name));
18799 + pybind11_fail("Unable to extract capsule contents!");
18804 + /// Replaces a capsule's pointer *without* calling the destructor on the existing one.
18805 + void set_pointer(const void *value) {
18806 + if (PyCapsule_SetPointer(m_ptr, const_cast<void *>(value)) != 0) {
18808 + pybind11_fail("Could not set capsule pointer");
18812 const char *name() const { return PyCapsule_GetName(m_ptr); }
18815 class tuple : public object {
18817 PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple)
18818 - explicit tuple(size_t size = 0) : object(PyTuple_New((ssize_t) size), stolen_t{}) {
18819 - if (!m_ptr) pybind11_fail("Could not allocate tuple object!");
18820 + template <typename SzType = ssize_t,
18821 + detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
18822 + // Some compilers generate link errors when using `const SzType &` here:
18823 + explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) {
18825 + pybind11_fail("Could not allocate tuple object!");
18828 size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
18829 + bool empty() const { return size() == 0; }
18830 detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }
18831 detail::item_accessor operator[](handle h) const { return object::operator[](h); }
18832 detail::tuple_iterator begin() const { return {*this, 0}; }
18833 detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; }
18836 +// We need to put this into a separate function because the Intel compiler
18837 +// fails to compile enable_if_t<all_of<is_keyword_or_ds<Args>...>::value> part below
18838 +// (tested with ICC 2021.1 Beta 20200827).
18839 +template <typename... Args>
18840 +constexpr bool args_are_all_keyword_or_ds() {
18841 + return detail::all_of<detail::is_keyword_or_ds<Args>...>::value;
18844 class dict : public object {
18846 PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict)
18847 dict() : object(PyDict_New(), stolen_t{}) {
18848 - if (!m_ptr) pybind11_fail("Could not allocate dict object!");
18850 + pybind11_fail("Could not allocate dict object!");
18853 template <typename... Args,
18854 - typename = detail::enable_if_t<detail::all_of<detail::is_keyword_or_ds<Args>...>::value>,
18855 - // MSVC workaround: it can't compile an out-of-line definition, so defer the collector
18856 + typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>,
18857 + // MSVC workaround: it can't compile an out-of-line definition, so defer the
18859 typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
18860 - explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) { }
18861 + explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) {}
18863 size_t size() const { return (size_t) PyDict_Size(m_ptr); }
18864 + bool empty() const { return size() == 0; }
18865 detail::dict_iterator begin() const { return {*this, 0}; }
18866 detail::dict_iterator end() const { return {}; }
18867 - void clear() const { PyDict_Clear(ptr()); }
18868 - bool contains(handle key) const { return PyDict_Contains(ptr(), key.ptr()) == 1; }
18869 - bool contains(const char *key) const { return PyDict_Contains(ptr(), pybind11::str(key).ptr()) == 1; }
18870 + void clear() /* py-non-const */ { PyDict_Clear(ptr()); }
18871 + template <typename T>
18872 + bool contains(T &&key) const {
18873 + return PyDict_Contains(m_ptr, detail::object_or_cast(std::forward<T>(key)).ptr()) == 1;
18877 /// Call the `dict` Python type -- always returns a new reference
18878 static PyObject *raw_dict(PyObject *op) {
18879 - if (PyDict_Check(op))
18880 + if (PyDict_Check(op)) {
18881 return handle(op).inc_ref().ptr();
18883 return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
18886 @@ -1230,7 +1729,14 @@
18887 class sequence : public object {
18889 PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check)
18890 - size_t size() const { return (size_t) PySequence_Size(m_ptr); }
18891 + size_t size() const {
18892 + ssize_t result = PySequence_Size(m_ptr);
18893 + if (result == -1) {
18894 + throw error_already_set();
18896 + return (size_t) result;
18898 + bool empty() const { return size() == 0; }
18899 detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
18900 detail::item_accessor operator[](handle h) const { return object::operator[](h); }
18901 detail::sequence_iterator begin() const { return {*this, 0}; }
18902 @@ -1240,33 +1746,59 @@
18903 class list : public object {
18905 PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List)
18906 - explicit list(size_t size = 0) : object(PyList_New((ssize_t) size), stolen_t{}) {
18907 - if (!m_ptr) pybind11_fail("Could not allocate list object!");
18908 + template <typename SzType = ssize_t,
18909 + detail::enable_if_t<std::is_integral<SzType>::value, int> = 0>
18910 + // Some compilers generate link errors when using `const SzType &` here:
18911 + explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) {
18913 + pybind11_fail("Could not allocate list object!");
18916 size_t size() const { return (size_t) PyList_Size(m_ptr); }
18917 + bool empty() const { return size() == 0; }
18918 detail::list_accessor operator[](size_t index) const { return {*this, index}; }
18919 detail::item_accessor operator[](handle h) const { return object::operator[](h); }
18920 detail::list_iterator begin() const { return {*this, 0}; }
18921 detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; }
18922 - template <typename T> void append(T &&val) const {
18923 + template <typename T>
18924 + void append(T &&val) /* py-non-const */ {
18925 PyList_Append(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr());
18927 + template <typename IdxType,
18928 + typename ValType,
18929 + detail::enable_if_t<std::is_integral<IdxType>::value, int> = 0>
18930 + void insert(const IdxType &index, ValType &&val) /* py-non-const */ {
18932 + m_ptr, ssize_t_cast(index), detail::object_or_cast(std::forward<ValType>(val)).ptr());
18936 -class args : public tuple { PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) };
18937 -class kwargs : public dict { PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check) };
18938 +class args : public tuple {
18939 + PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check)
18941 +class kwargs : public dict {
18942 + PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check)
18945 class set : public object {
18947 PYBIND11_OBJECT_CVT(set, object, PySet_Check, PySet_New)
18948 set() : object(PySet_New(nullptr), stolen_t{}) {
18949 - if (!m_ptr) pybind11_fail("Could not allocate set object!");
18951 + pybind11_fail("Could not allocate set object!");
18954 size_t size() const { return (size_t) PySet_Size(m_ptr); }
18955 - template <typename T> bool add(T &&val) const {
18956 + bool empty() const { return size() == 0; }
18957 + template <typename T>
18958 + bool add(T &&val) /* py-non-const */ {
18959 return PySet_Add(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 0;
18961 - void clear() const { PySet_Clear(m_ptr); }
18962 + void clear() /* py-non-const */ { PySet_Clear(m_ptr); }
18963 + template <typename T>
18964 + bool contains(T &&val) const {
18965 + return PySet_Contains(m_ptr, detail::object_or_cast(std::forward<T>(val)).ptr()) == 1;
18969 class function : public object {
18970 @@ -1274,21 +1806,29 @@
18971 PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check)
18972 handle cpp_function() const {
18973 handle fun = detail::get_function(m_ptr);
18974 - if (fun && PyCFunction_Check(fun.ptr()))
18975 + if (fun && PyCFunction_Check(fun.ptr())) {
18980 bool is_cpp_function() const { return (bool) cpp_function(); }
18983 +class staticmethod : public object {
18985 + PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New)
18988 class buffer : public object {
18990 PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer)
18992 - buffer_info request(bool writable = false) {
18993 + buffer_info request(bool writable = false) const {
18994 int flags = PyBUF_STRIDES | PyBUF_FORMAT;
18995 - if (writable) flags |= PyBUF_WRITABLE;
18996 - Py_buffer *view = new Py_buffer();
18998 + flags |= PyBUF_WRITABLE;
19000 + auto *view = new Py_buffer();
19001 if (PyObject_GetBuffer(m_ptr, view, flags) != 0) {
19003 throw error_already_set();
19004 @@ -1299,144 +1839,315 @@
19006 class memoryview : public object {
19008 - explicit memoryview(const buffer_info& info) {
19009 - static Py_buffer buf { };
19010 - // Py_buffer uses signed sizes, strides and shape!..
19011 - static std::vector<Py_ssize_t> py_strides { };
19012 - static std::vector<Py_ssize_t> py_shape { };
19013 - buf.buf = info.ptr;
19014 - buf.itemsize = info.itemsize;
19015 - buf.format = const_cast<char *>(info.format.c_str());
19016 - buf.ndim = (int) info.ndim;
19017 - buf.len = info.size;
19018 - py_strides.clear();
19019 - py_shape.clear();
19020 - for (size_t i = 0; i < (size_t) info.ndim; ++i) {
19021 - py_strides.push_back(info.strides[i]);
19022 - py_shape.push_back(info.shape[i]);
19024 - buf.strides = py_strides.data();
19025 - buf.shape = py_shape.data();
19026 - buf.suboffsets = nullptr;
19027 - buf.readonly = false;
19028 - buf.internal = nullptr;
19029 + PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
19032 + Creates ``memoryview`` from ``buffer_info``.
19034 - m_ptr = PyMemoryView_FromBuffer(&buf);
19036 + ``buffer_info`` must be created from ``buffer::request()``. Otherwise
19037 + throws an exception.
19039 + For creating a ``memoryview`` from objects that support buffer protocol,
19040 + use ``memoryview(const object& obj)`` instead of this constructor.
19042 + explicit memoryview(const buffer_info &info) {
19043 + if (!info.view()) {
19044 + pybind11_fail("Prohibited to create memoryview without Py_buffer");
19046 + // Note: PyMemoryView_FromBuffer never increments obj reference.
19047 + m_ptr = (info.view()->obj) ? PyMemoryView_FromObject(info.view()->obj)
19048 + : PyMemoryView_FromBuffer(info.view());
19050 pybind11_fail("Unable to create memoryview from buffer descriptor");
19054 - PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject)
19056 + Creates ``memoryview`` from static buffer.
19058 + This method is meant for providing a ``memoryview`` for C/C++ buffer not
19059 + managed by Python. The caller is responsible for managing the lifetime
19060 + of ``ptr`` and ``format``, which MUST outlive the memoryview constructed
19063 + See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
19065 + .. _PyMemoryView_FromBuffer:
19066 + https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer
19068 + :param ptr: Pointer to the buffer.
19069 + :param itemsize: Byte size of an element.
19070 + :param format: Pointer to the null-terminated format string. For
19071 + homogeneous Buffers, this should be set to
19072 + ``format_descriptor<T>::value``.
19073 + :param shape: Shape of the tensor (1 entry per dimension).
19074 + :param strides: Number of bytes between adjacent entries (for each
19076 + :param readonly: Flag to indicate if the underlying storage may be
19079 + static memoryview from_buffer(void *ptr,
19080 + ssize_t itemsize,
19081 + const char *format,
19082 + detail::any_container<ssize_t> shape,
19083 + detail::any_container<ssize_t> strides,
19084 + bool readonly = false);
19086 + static memoryview from_buffer(const void *ptr,
19087 + ssize_t itemsize,
19088 + const char *format,
19089 + detail::any_container<ssize_t> shape,
19090 + detail::any_container<ssize_t> strides) {
19091 + return memoryview::from_buffer(
19092 + const_cast<void *>(ptr), itemsize, format, std::move(shape), std::move(strides), true);
19095 + template <typename T>
19096 + static memoryview from_buffer(T *ptr,
19097 + detail::any_container<ssize_t> shape,
19098 + detail::any_container<ssize_t> strides,
19099 + bool readonly = false) {
19100 + return memoryview::from_buffer(reinterpret_cast<void *>(ptr),
19102 + format_descriptor<T>::value,
19108 + template <typename T>
19109 + static memoryview from_buffer(const T *ptr,
19110 + detail::any_container<ssize_t> shape,
19111 + detail::any_container<ssize_t> strides) {
19112 + return memoryview::from_buffer(const_cast<T *>(ptr), shape, strides, true);
19115 +#if PY_MAJOR_VERSION >= 3
19117 + Creates ``memoryview`` from static memory.
19119 + This method is meant for providing a ``memoryview`` for C/C++ buffer not
19120 + managed by Python. The caller is responsible for managing the lifetime
19121 + of ``mem``, which MUST outlive the memoryview constructed here.
19123 + This method is not available in Python 2.
19125 + See also: Python C API documentation for `PyMemoryView_FromBuffer`_.
19127 + .. _PyMemoryView_FromMemory:
19128 + https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory
19130 + static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) {
19131 + PyObject *ptr = PyMemoryView_FromMemory(
19132 + reinterpret_cast<char *>(mem), size, (readonly) ? PyBUF_READ : PyBUF_WRITE);
19134 + pybind11_fail("Could not allocate memoryview object!");
19136 + return memoryview(object(ptr, stolen_t{}));
19139 + static memoryview from_memory(const void *mem, ssize_t size) {
19140 + return memoryview::from_memory(const_cast<void *>(mem), size, true);
19143 +# ifdef PYBIND11_HAS_STRING_VIEW
19144 + static memoryview from_memory(std::string_view mem) {
19145 + return from_memory(const_cast<char *>(mem.data()), static_cast<ssize_t>(mem.size()), true);
19152 +/// @cond DUPLICATE
19153 +inline memoryview memoryview::from_buffer(void *ptr,
19154 + ssize_t itemsize,
19155 + const char *format,
19156 + detail::any_container<ssize_t> shape,
19157 + detail::any_container<ssize_t> strides,
19159 + size_t ndim = shape->size();
19160 + if (ndim != strides->size()) {
19161 + pybind11_fail("memoryview: shape length doesn't match strides length");
19163 + ssize_t size = ndim != 0u ? 1 : 0;
19164 + for (size_t i = 0; i < ndim; ++i) {
19165 + size *= (*shape)[i];
19169 + view.obj = nullptr;
19170 + view.len = size * itemsize;
19171 + view.readonly = static_cast<int>(readonly);
19172 + view.itemsize = itemsize;
19173 + view.format = const_cast<char *>(format);
19174 + view.ndim = static_cast<int>(ndim);
19175 + view.shape = shape->data();
19176 + view.strides = strides->data();
19177 + view.suboffsets = nullptr;
19178 + view.internal = nullptr;
19179 + PyObject *obj = PyMemoryView_FromBuffer(&view);
19181 + throw error_already_set();
19183 + return memoryview(object(obj, stolen_t{}));
19188 /// \addtogroup python_builtins
19191 +/// Get the length of a Python object.
19192 inline size_t len(handle h) {
19193 ssize_t result = PyObject_Length(h.ptr());
19195 - pybind11_fail("Unable to compute length of object");
19196 + if (result < 0) {
19197 + throw error_already_set();
19199 + return (size_t) result;
19202 +/// Get the length hint of a Python object.
19203 +/// Returns 0 when this cannot be determined.
19204 +inline size_t len_hint(handle h) {
19205 +#if PY_VERSION_HEX >= 0x03040000
19206 + ssize_t result = PyObject_LengthHint(h.ptr(), 0);
19208 + ssize_t result = PyObject_Length(h.ptr());
19210 + if (result < 0) {
19211 + // Sometimes a length can't be determined at all (eg generators)
19212 + // In which case simply return 0
19216 return (size_t) result;
19219 inline str repr(handle h) {
19220 PyObject *str_value = PyObject_Repr(h.ptr());
19221 - if (!str_value) throw error_already_set();
19222 + if (!str_value) {
19223 + throw error_already_set();
19225 #if PY_MAJOR_VERSION < 3
19226 PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
19227 - Py_XDECREF(str_value); str_value = unicode;
19228 - if (!str_value) throw error_already_set();
19229 + Py_XDECREF(str_value);
19230 + str_value = unicode;
19232 + throw error_already_set();
19234 return reinterpret_steal<str>(str_value);
19237 inline iterator iter(handle obj) {
19238 PyObject *result = PyObject_GetIter(obj.ptr());
19239 - if (!result) { throw error_already_set(); }
19241 + throw error_already_set();
19243 return reinterpret_steal<iterator>(result);
19245 /// @} python_builtins
19247 -NAMESPACE_BEGIN(detail)
19248 -template <typename D> iterator object_api<D>::begin() const { return iter(derived()); }
19249 -template <typename D> iterator object_api<D>::end() const { return iterator::sentinel(); }
19250 -template <typename D> item_accessor object_api<D>::operator[](handle key) const {
19251 +PYBIND11_NAMESPACE_BEGIN(detail)
19252 +template <typename D>
19253 +iterator object_api<D>::begin() const {
19254 + return iter(derived());
19256 +template <typename D>
19257 +iterator object_api<D>::end() const {
19258 + return iterator::sentinel();
19260 +template <typename D>
19261 +item_accessor object_api<D>::operator[](handle key) const {
19262 return {derived(), reinterpret_borrow<object>(key)};
19264 -template <typename D> item_accessor object_api<D>::operator[](const char *key) const {
19265 +template <typename D>
19266 +item_accessor object_api<D>::operator[](const char *key) const {
19267 return {derived(), pybind11::str(key)};
19269 -template <typename D> obj_attr_accessor object_api<D>::attr(handle key) const {
19270 +template <typename D>
19271 +obj_attr_accessor object_api<D>::attr(handle key) const {
19272 return {derived(), reinterpret_borrow<object>(key)};
19274 -template <typename D> str_attr_accessor object_api<D>::attr(const char *key) const {
19275 +template <typename D>
19276 +str_attr_accessor object_api<D>::attr(const char *key) const {
19277 return {derived(), key};
19279 -template <typename D> args_proxy object_api<D>::operator*() const {
19280 +template <typename D>
19281 +args_proxy object_api<D>::operator*() const {
19282 return args_proxy(derived().ptr());
19284 -template <typename D> template <typename T> bool object_api<D>::contains(T &&item) const {
19285 +template <typename D>
19286 +template <typename T>
19287 +bool object_api<D>::contains(T &&item) const {
19288 return attr("__contains__")(std::forward<T>(item)).template cast<bool>();
19291 template <typename D>
19292 -pybind11::str object_api<D>::str() const { return pybind11::str(derived()); }
19293 +pybind11::str object_api<D>::str() const {
19294 + return pybind11::str(derived());
19297 template <typename D>
19298 -str_attr_accessor object_api<D>::doc() const { return attr("__doc__"); }
19299 +str_attr_accessor object_api<D>::doc() const {
19300 + return attr("__doc__");
19303 template <typename D>
19304 -handle object_api<D>::get_type() const { return (PyObject *) Py_TYPE(derived().ptr()); }
19305 +handle object_api<D>::get_type() const {
19306 + return type::handle_of(derived());
19309 template <typename D>
19310 bool object_api<D>::rich_compare(object_api const &other, int value) const {
19311 int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value);
19314 throw error_already_set();
19319 -#define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
19320 - template <typename D> object object_api<D>::op() const { \
19321 - object result = reinterpret_steal<object>(fn(derived().ptr())); \
19322 - if (!result.ptr()) \
19323 - throw error_already_set(); \
19327 -#define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
19328 - template <typename D> \
19329 - object object_api<D>::op(object_api const &other) const { \
19330 - object result = reinterpret_steal<object>( \
19331 - fn(derived().ptr(), other.derived().ptr())); \
19332 - if (!result.ptr()) \
19333 - throw error_already_set(); \
19337 -PYBIND11_MATH_OPERATOR_UNARY (operator~, PyNumber_Invert)
19338 -PYBIND11_MATH_OPERATOR_UNARY (operator-, PyNumber_Negative)
19339 -PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)
19340 -PYBIND11_MATH_OPERATOR_BINARY(operator+=, PyNumber_InPlaceAdd)
19341 -PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)
19342 -PYBIND11_MATH_OPERATOR_BINARY(operator-=, PyNumber_InPlaceSubtract)
19343 -PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)
19344 -PYBIND11_MATH_OPERATOR_BINARY(operator*=, PyNumber_InPlaceMultiply)
19345 -PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)
19346 -PYBIND11_MATH_OPERATOR_BINARY(operator/=, PyNumber_InPlaceTrueDivide)
19347 -PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)
19348 -PYBIND11_MATH_OPERATOR_BINARY(operator|=, PyNumber_InPlaceOr)
19349 -PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)
19350 -PYBIND11_MATH_OPERATOR_BINARY(operator&=, PyNumber_InPlaceAnd)
19351 -PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)
19352 -PYBIND11_MATH_OPERATOR_BINARY(operator^=, PyNumber_InPlaceXor)
19353 -PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)
19354 +#define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \
19355 + template <typename D> \
19356 + object object_api<D>::op() const { \
19357 + object result = reinterpret_steal<object>(fn(derived().ptr())); \
19358 + if (!result.ptr()) \
19359 + throw error_already_set(); \
19363 +#define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \
19364 + template <typename D> \
19365 + object object_api<D>::op(object_api const &other) const { \
19366 + object result = reinterpret_steal<object>(fn(derived().ptr(), other.derived().ptr())); \
19367 + if (!result.ptr()) \
19368 + throw error_already_set(); \
19372 +PYBIND11_MATH_OPERATOR_UNARY(operator~, PyNumber_Invert)
19373 +PYBIND11_MATH_OPERATOR_UNARY(operator-, PyNumber_Negative)
19374 +PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add)
19375 +PYBIND11_MATH_OPERATOR_BINARY(operator+=, PyNumber_InPlaceAdd)
19376 +PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract)
19377 +PYBIND11_MATH_OPERATOR_BINARY(operator-=, PyNumber_InPlaceSubtract)
19378 +PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply)
19379 +PYBIND11_MATH_OPERATOR_BINARY(operator*=, PyNumber_InPlaceMultiply)
19380 +PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide)
19381 +PYBIND11_MATH_OPERATOR_BINARY(operator/=, PyNumber_InPlaceTrueDivide)
19382 +PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or)
19383 +PYBIND11_MATH_OPERATOR_BINARY(operator|=, PyNumber_InPlaceOr)
19384 +PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And)
19385 +PYBIND11_MATH_OPERATOR_BINARY(operator&=, PyNumber_InPlaceAnd)
19386 +PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor)
19387 +PYBIND11_MATH_OPERATOR_BINARY(operator^=, PyNumber_InPlaceXor)
19388 +PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift)
19389 PYBIND11_MATH_OPERATOR_BINARY(operator<<=, PyNumber_InPlaceLshift)
19390 -PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)
19391 +PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift)
19392 PYBIND11_MATH_OPERATOR_BINARY(operator>>=, PyNumber_InPlaceRshift)
19394 #undef PYBIND11_MATH_OPERATOR_UNARY
19395 #undef PYBIND11_MATH_OPERATOR_BINARY
19397 -NAMESPACE_END(detail)
19398 -NAMESPACE_END(PYBIND11_NAMESPACE)
19399 +PYBIND11_NAMESPACE_END(detail)
19400 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
19401 diff -Nur pythia8309.orig/plugins/python/include/pybind11/stl/filesystem.h pythia8309/plugins/python/include/pybind11/stl/filesystem.h
19402 --- pythia8309.orig/plugins/python/include/pybind11/stl/filesystem.h 1970-01-01 01:00:00.000000000 +0100
19403 +++ pythia8309/plugins/python/include/pybind11/stl/filesystem.h 2023-03-13 09:52:25.473021631 +0100
19405 +// Copyright (c) 2021 The Pybind Development Team.
19406 +// All rights reserved. Use of this source code is governed by a
19407 +// BSD-style license that can be found in the LICENSE file.
19411 +#include "../pybind11.h"
19412 +#include "../detail/common.h"
19413 +#include "../detail/descr.h"
19414 +#include "../cast.h"
19415 +#include "../pytypes.h"
19419 +#ifdef __has_include
19420 +# if defined(PYBIND11_CPP17) && __has_include(<filesystem>) && \
19421 + PY_VERSION_HEX >= 0x03060000
19422 +# include <filesystem>
19423 +# define PYBIND11_HAS_FILESYSTEM 1
19427 +#if !defined(PYBIND11_HAS_FILESYSTEM) && !defined(PYBIND11_HAS_FILESYSTEM_IS_OPTIONAL)
19429 + "#include <filesystem> is not available. (Use -DPYBIND11_HAS_FILESYSTEM_IS_OPTIONAL to ignore.)"
19432 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
19433 +PYBIND11_NAMESPACE_BEGIN(detail)
19435 +#if defined(PYBIND11_HAS_FILESYSTEM)
19436 +template <typename T>
19437 +struct path_caster {
19440 + static PyObject *unicode_from_fs_native(const std::string &w) {
19441 +# if !defined(PYPY_VERSION)
19442 + return PyUnicode_DecodeFSDefaultAndSize(w.c_str(), ssize_t(w.size()));
19444 + // PyPy mistakenly declares the first parameter as non-const.
19445 + return PyUnicode_DecodeFSDefaultAndSize(const_cast<char *>(w.c_str()), ssize_t(w.size()));
19449 + static PyObject *unicode_from_fs_native(const std::wstring &w) {
19450 + return PyUnicode_FromWideChar(w.c_str(), ssize_t(w.size()));
19454 + static handle cast(const T &path, return_value_policy, handle) {
19455 + if (auto py_str = unicode_from_fs_native(path.native())) {
19456 + return module_::import("pathlib")
19457 + .attr("Path")(reinterpret_steal<object>(py_str))
19463 + bool load(handle handle, bool) {
19464 + // PyUnicode_FSConverter and PyUnicode_FSDecoder normally take care of
19465 + // calling PyOS_FSPath themselves, but that's broken on PyPy (PyPy
19466 + // issue #3168) so we do it ourselves instead.
19467 + PyObject *buf = PyOS_FSPath(handle.ptr());
19472 + PyObject *native = nullptr;
19473 + if constexpr (std::is_same_v<typename T::value_type, char>) {
19474 + if (PyUnicode_FSConverter(buf, &native) != 0) {
19475 + if (auto *c_str = PyBytes_AsString(native)) {
19476 + // AsString returns a pointer to the internal buffer, which
19477 + // must not be free'd.
19481 + } else if constexpr (std::is_same_v<typename T::value_type, wchar_t>) {
19482 + if (PyUnicode_FSDecoder(buf, &native) != 0) {
19483 + if (auto *c_str = PyUnicode_AsWideCharString(native, nullptr)) {
19484 + // AsWideCharString returns a new string that must be free'd.
19485 + value = c_str; // Copies the string.
19486 + PyMem_Free(c_str);
19490 + Py_XDECREF(native);
19492 + if (PyErr_Occurred()) {
19499 + PYBIND11_TYPE_CASTER(T, const_name("os.PathLike"));
19503 +struct type_caster<std::filesystem::path> : public path_caster<std::filesystem::path> {};
19504 +#endif // PYBIND11_HAS_FILESYSTEM
19506 +PYBIND11_NAMESPACE_END(detail)
19507 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
19508 diff -Nur pythia8309.orig/plugins/python/include/pybind11/stl_bind.h pythia8309/plugins/python/include/pybind11/stl_bind.h
19509 --- pythia8309.orig/plugins/python/include/pybind11/stl_bind.h 2023-02-16 18:12:45.000000000 +0100
19510 +++ pythia8309/plugins/python/include/pybind11/stl_bind.h 2023-03-13 09:52:25.474021634 +0100
19511 @@ -15,221 +15,278 @@
19512 #include <algorithm>
19515 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
19516 -NAMESPACE_BEGIN(detail)
19517 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
19518 +PYBIND11_NAMESPACE_BEGIN(detail)
19520 /* SFINAE helper class used by 'is_comparable */
19521 -template <typename T> struct container_traits {
19522 - template <typename T2> static std::true_type test_comparable(decltype(std::declval<const T2 &>() == std::declval<const T2 &>())*);
19523 - template <typename T2> static std::false_type test_comparable(...);
19524 - template <typename T2> static std::true_type test_value(typename T2::value_type *);
19525 - template <typename T2> static std::false_type test_value(...);
19526 - template <typename T2> static std::true_type test_pair(typename T2::first_type *, typename T2::second_type *);
19527 - template <typename T2> static std::false_type test_pair(...);
19529 - static constexpr const bool is_comparable = std::is_same<std::true_type, decltype(test_comparable<T>(nullptr))>::value;
19530 - static constexpr const bool is_pair = std::is_same<std::true_type, decltype(test_pair<T>(nullptr, nullptr))>::value;
19531 - static constexpr const bool is_vector = std::is_same<std::true_type, decltype(test_value<T>(nullptr))>::value;
19532 +template <typename T>
19533 +struct container_traits {
19534 + template <typename T2>
19535 + static std::true_type
19536 + test_comparable(decltype(std::declval<const T2 &>() == std::declval<const T2 &>()) *);
19537 + template <typename T2>
19538 + static std::false_type test_comparable(...);
19539 + template <typename T2>
19540 + static std::true_type test_value(typename T2::value_type *);
19541 + template <typename T2>
19542 + static std::false_type test_value(...);
19543 + template <typename T2>
19544 + static std::true_type test_pair(typename T2::first_type *, typename T2::second_type *);
19545 + template <typename T2>
19546 + static std::false_type test_pair(...);
19548 + static constexpr const bool is_comparable
19549 + = std::is_same<std::true_type, decltype(test_comparable<T>(nullptr))>::value;
19550 + static constexpr const bool is_pair
19551 + = std::is_same<std::true_type, decltype(test_pair<T>(nullptr, nullptr))>::value;
19552 + static constexpr const bool is_vector
19553 + = std::is_same<std::true_type, decltype(test_value<T>(nullptr))>::value;
19554 static constexpr const bool is_element = !is_pair && !is_vector;
19557 /* Default: is_comparable -> std::false_type */
19558 template <typename T, typename SFINAE = void>
19559 -struct is_comparable : std::false_type { };
19560 +struct is_comparable : std::false_type {};
19562 /* For non-map data structures, check whether operator== can be instantiated */
19563 template <typename T>
19564 struct is_comparable<
19565 - T, enable_if_t<container_traits<T>::is_element &&
19566 - container_traits<T>::is_comparable>>
19567 - : std::true_type { };
19569 + enable_if_t<container_traits<T>::is_element && container_traits<T>::is_comparable>>
19570 + : std::true_type {};
19572 -/* For a vector/map data structure, recursively check the value type (which is std::pair for maps) */
19573 +/* For a vector/map data structure, recursively check the value type
19574 + (which is std::pair for maps) */
19575 template <typename T>
19576 struct is_comparable<T, enable_if_t<container_traits<T>::is_vector>> {
19577 - static constexpr const bool value =
19578 - is_comparable<typename T::value_type>::value;
19579 + static constexpr const bool value = is_comparable<typename T::value_type>::value;
19582 /* For pairs, recursively check the two data types */
19583 template <typename T>
19584 struct is_comparable<T, enable_if_t<container_traits<T>::is_pair>> {
19585 - static constexpr const bool value =
19586 - is_comparable<typename T::first_type>::value &&
19587 - is_comparable<typename T::second_type>::value;
19588 + static constexpr const bool value = is_comparable<typename T::first_type>::value
19589 + && is_comparable<typename T::second_type>::value;
19592 /* Fallback functions */
19593 -template <typename, typename, typename... Args> void vector_if_copy_constructible(const Args &...) { }
19594 -template <typename, typename, typename... Args> void vector_if_equal_operator(const Args &...) { }
19595 -template <typename, typename, typename... Args> void vector_if_insertion_operator(const Args &...) { }
19596 -template <typename, typename, typename... Args> void vector_modifiers(const Args &...) { }
19597 +template <typename, typename, typename... Args>
19598 +void vector_if_copy_constructible(const Args &...) {}
19599 +template <typename, typename, typename... Args>
19600 +void vector_if_equal_operator(const Args &...) {}
19601 +template <typename, typename, typename... Args>
19602 +void vector_if_insertion_operator(const Args &...) {}
19603 +template <typename, typename, typename... Args>
19604 +void vector_modifiers(const Args &...) {}
19606 -template<typename Vector, typename Class_>
19607 +template <typename Vector, typename Class_>
19608 void vector_if_copy_constructible(enable_if_t<is_copy_constructible<Vector>::value, Class_> &cl) {
19609 cl.def(init<const Vector &>(), "Copy constructor");
19612 -template<typename Vector, typename Class_>
19613 +template <typename Vector, typename Class_>
19614 void vector_if_equal_operator(enable_if_t<is_comparable<Vector>::value, Class_> &cl) {
19615 using T = typename Vector::value_type;
19617 cl.def(self == self);
19618 cl.def(self != self);
19621 - [](const Vector &v, const T &x) {
19622 - return std::count(v.begin(), v.end(), x);
19626 + [](const Vector &v, const T &x) { return std::count(v.begin(), v.end(), x); },
19628 - "Return the number of times ``x`` appears in the list"
19630 + "Return the number of times ``x`` appears in the list");
19632 - cl.def("remove", [](Vector &v, const T &x) {
19635 + [](Vector &v, const T &x) {
19636 auto p = std::find(v.begin(), v.end(), x);
19637 - if (p != v.end())
19638 + if (p != v.end()) {
19642 throw value_error();
19646 "Remove the first item from the list whose value is x. "
19647 - "It is an error if there is no such item."
19649 + "It is an error if there is no such item.");
19651 - cl.def("__contains__",
19652 - [](const Vector &v, const T &x) {
19653 - return std::find(v.begin(), v.end(), x) != v.end();
19657 + [](const Vector &v, const T &x) { return std::find(v.begin(), v.end(), x) != v.end(); },
19659 - "Return true the container contains ``x``"
19661 + "Return true the container contains ``x``");
19664 // Vector modifiers -- requires a copyable vector_type:
19665 -// (Technically, some of these (pop and __delitem__) don't actually require copyability, but it seems
19666 -// silly to allow deletion but not insertion, so include them here too.)
19667 +// (Technically, some of these (pop and __delitem__) don't actually require copyability, but it
19668 +// seems silly to allow deletion but not insertion, so include them here too.)
19669 template <typename Vector, typename Class_>
19670 -void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_type>::value, Class_> &cl) {
19671 +void vector_modifiers(
19672 + enable_if_t<is_copy_constructible<typename Vector::value_type>::value, Class_> &cl) {
19673 using T = typename Vector::value_type;
19674 using SizeType = typename Vector::size_type;
19675 using DiffType = typename Vector::difference_type;
19678 - [](Vector &v, const T &value) { v.push_back(value); },
19680 - "Add an item to the end of the list");
19681 + auto wrap_i = [](DiffType i, SizeType n) {
19685 + if (i < 0 || (SizeType) i >= n) {
19686 + throw index_error();
19693 + [](Vector &v, const T &value) { v.push_back(value); },
19695 + "Add an item to the end of the list");
19697 - cl.def(init([](iterable it) {
19698 + cl.def(init([](const iterable &it) {
19699 auto v = std::unique_ptr<Vector>(new Vector());
19700 - v->reserve(len(it));
19701 - for (handle h : it)
19702 - v->push_back(h.cast<T>());
19703 + v->reserve(len_hint(it));
19704 + for (handle h : it) {
19705 + v->push_back(h.cast<T>());
19707 return v.release();
19711 - [](Vector &v, const Vector &src) {
19712 - v.insert(v.end(), src.begin(), src.end());
19715 - "Extend the list by appending all the items in the given list"
19718 + "clear", [](Vector &v) { v.clear(); }, "Clear the contents");
19722 + [](Vector &v, const Vector &src) { v.insert(v.end(), src.begin(), src.end()); },
19724 + "Extend the list by appending all the items in the given list");
19728 + [](Vector &v, const iterable &it) {
19729 + const size_t old_size = v.size();
19730 + v.reserve(old_size + len_hint(it));
19732 + for (handle h : it) {
19733 + v.push_back(h.cast<T>());
19735 + } catch (const cast_error &) {
19736 + v.erase(v.begin() + static_cast<typename Vector::difference_type>(old_size),
19739 + v.shrink_to_fit();
19740 + } catch (const std::exception &) {
19747 + "Extend the list by appending all the items in the given list");
19750 - [](Vector &v, SizeType i, const T &x) {
19751 - if (i > v.size())
19754 + [](Vector &v, DiffType i, const T &x) {
19755 + // Can't use wrap_i; i == v.size() is OK
19759 + if (i < 0 || (SizeType) i > v.size()) {
19760 throw index_error();
19761 - v.insert(v.begin() + (DiffType) i, x);
19763 + v.insert(v.begin() + i, x);
19765 - arg("i") , arg("x"),
19766 - "Insert an item at a given position."
19770 + "Insert an item at a given position.");
19778 throw index_error();
19781 + T t = std::move(v.back());
19785 - "Remove and return the last item"
19787 + "Remove and return the last item");
19790 - [](Vector &v, SizeType i) {
19791 - if (i >= v.size())
19792 - throw index_error();
19794 - v.erase(v.begin() + (DiffType) i);
19797 + [wrap_i](Vector &v, DiffType i) {
19798 + i = wrap_i(i, v.size());
19799 + T t = std::move(v[(SizeType) i]);
19800 + v.erase(std::next(v.begin(), i));
19804 - "Remove and return the item at index ``i``"
19806 + "Remove and return the item at index ``i``");
19808 - cl.def("__setitem__",
19809 - [](Vector &v, SizeType i, const T &t) {
19810 - if (i >= v.size())
19811 - throw index_error();
19815 + cl.def("__setitem__", [wrap_i](Vector &v, DiffType i, const T &t) {
19816 + i = wrap_i(i, v.size());
19817 + v[(SizeType) i] = t;
19820 /// Slicing protocol
19821 - cl.def("__getitem__",
19824 [](const Vector &v, slice slice) -> Vector * {
19825 - size_t start, stop, step, slicelength;
19826 + size_t start = 0, stop = 0, step = 0, slicelength = 0;
19828 - if (!slice.compute(v.size(), &start, &stop, &step, &slicelength))
19829 + if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
19830 throw error_already_set();
19833 - Vector *seq = new Vector();
19834 + auto *seq = new Vector();
19835 seq->reserve((size_t) slicelength);
19837 - for (size_t i=0; i<slicelength; ++i) {
19838 + for (size_t i = 0; i < slicelength; ++i) {
19839 seq->push_back(v[start]);
19845 - "Retrieve list elements using a slice object"
19847 + "Retrieve list elements using a slice object");
19849 - cl.def("__setitem__",
19850 - [](Vector &v, slice slice, const Vector &value) {
19851 - size_t start, stop, step, slicelength;
19852 - if (!slice.compute(v.size(), &start, &stop, &step, &slicelength))
19855 + [](Vector &v, slice slice, const Vector &value) {
19856 + size_t start = 0, stop = 0, step = 0, slicelength = 0;
19857 + if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
19858 throw error_already_set();
19861 - if (slicelength != value.size())
19862 - throw std::runtime_error("Left and right hand size of slice assignment have different sizes!");
19863 + if (slicelength != value.size()) {
19864 + throw std::runtime_error(
19865 + "Left and right hand size of slice assignment have different sizes!");
19868 - for (size_t i=0; i<slicelength; ++i) {
19869 + for (size_t i = 0; i < slicelength; ++i) {
19870 v[start] = value[i];
19874 - "Assign list elements using a slice object"
19876 + "Assign list elements using a slice object");
19878 - cl.def("__delitem__",
19879 - [](Vector &v, SizeType i) {
19880 - if (i >= v.size())
19881 - throw index_error();
19882 - v.erase(v.begin() + DiffType(i));
19885 + [wrap_i](Vector &v, DiffType i) {
19886 + i = wrap_i(i, v.size());
19887 + v.erase(v.begin() + i);
19889 - "Delete the list elements at index ``i``"
19891 + "Delete the list elements at index ``i``");
19893 - cl.def("__delitem__",
19896 [](Vector &v, slice slice) {
19897 - size_t start, stop, step, slicelength;
19898 + size_t start = 0, stop = 0, step = 0, slicelength = 0;
19900 - if (!slice.compute(v.size(), &start, &stop, &step, &slicelength))
19901 + if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
19902 throw error_already_set();
19905 if (step == 1 && false) {
19906 v.erase(v.begin() + (DiffType) start, v.begin() + DiffType(start + slicelength));
19907 @@ -240,39 +297,50 @@
19911 - "Delete list elements using a slice object"
19914 + "Delete list elements using a slice object");
19917 // If the type has an operator[] that doesn't return a reference (most notably std::vector<bool>),
19918 // we have to access by copying; otherwise we return by reference.
19919 -template <typename Vector> using vector_needs_copy = negation<
19920 - std::is_same<decltype(std::declval<Vector>()[typename Vector::size_type()]), typename Vector::value_type &>>;
19921 +template <typename Vector>
19922 +using vector_needs_copy
19923 + = negation<std::is_same<decltype(std::declval<Vector>()[typename Vector::size_type()]),
19924 + typename Vector::value_type &>>;
19926 // The usual case: access and iterate by reference
19927 template <typename Vector, typename Class_>
19928 void vector_accessor(enable_if_t<!vector_needs_copy<Vector>::value, Class_> &cl) {
19929 using T = typename Vector::value_type;
19930 using SizeType = typename Vector::size_type;
19931 - using ItType = typename Vector::iterator;
19932 + using DiffType = typename Vector::difference_type;
19933 + using ItType = typename Vector::iterator;
19935 - cl.def("__getitem__",
19936 - [](Vector &v, SizeType i) -> T & {
19937 - if (i >= v.size())
19938 - throw index_error();
19940 + auto wrap_i = [](DiffType i, SizeType n) {
19944 + if (i < 0 || (SizeType) i >= n) {
19945 + throw index_error();
19952 + [wrap_i](Vector &v, DiffType i) -> T & {
19953 + i = wrap_i(i, v.size());
19954 + return v[(SizeType) i];
19956 return_value_policy::reference_internal // ref + keepalive
19959 - cl.def("__iter__",
19961 - return make_iterator<
19962 - return_value_policy::reference_internal, ItType, ItType, T&>(
19963 - v.begin(), v.end());
19965 - keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */
19969 + return make_iterator<return_value_policy::reference_internal, ItType, ItType, T &>(
19970 + v.begin(), v.end());
19972 + keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */
19976 @@ -281,103 +349,144 @@
19977 void vector_accessor(enable_if_t<vector_needs_copy<Vector>::value, Class_> &cl) {
19978 using T = typename Vector::value_type;
19979 using SizeType = typename Vector::size_type;
19980 - using ItType = typename Vector::iterator;
19981 - cl.def("__getitem__",
19982 - [](const Vector &v, SizeType i) -> T {
19983 - if (i >= v.size())
19984 - throw index_error();
19986 + using DiffType = typename Vector::difference_type;
19987 + using ItType = typename Vector::iterator;
19988 + cl.def("__getitem__", [](const Vector &v, DiffType i) -> T {
19989 + if (i < 0 && (i += v.size()) < 0) {
19990 + throw index_error();
19993 + if ((SizeType) i >= v.size()) {
19994 + throw index_error();
19996 + return v[(SizeType) i];
19999 - cl.def("__iter__",
20001 - return make_iterator<
20002 - return_value_policy::copy, ItType, ItType, T>(
20003 - v.begin(), v.end());
20005 - keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */
20009 + return make_iterator<return_value_policy::copy, ItType, ItType, T>(v.begin(), v.end());
20011 + keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */
20015 -template <typename Vector, typename Class_> auto vector_if_insertion_operator(Class_ &cl, std::string const &name)
20016 - -> decltype(std::declval<std::ostream&>() << std::declval<typename Vector::value_type>(), void()) {
20017 +template <typename Vector, typename Class_>
20018 +auto vector_if_insertion_operator(Class_ &cl, std::string const &name)
20019 + -> decltype(std::declval<std::ostream &>() << std::declval<typename Vector::value_type>(),
20021 using size_type = typename Vector::size_type;
20023 - cl.def("__repr__",
20024 - [name](Vector &v) {
20027 + [name](Vector &v) {
20028 std::ostringstream s;
20030 - for (size_type i=0; i < v.size(); ++i) {
20031 + for (size_type i = 0; i < v.size(); ++i) {
20033 - if (i != v.size() - 1)
20034 + if (i != v.size() - 1) {
20041 - "Return the canonical string representation of this list."
20043 + "Return the canonical string representation of this list.");
20046 // Provide the buffer interface for vectors if we have data() and we have a format for it
20047 -// GCC seems to have "void std::vector<bool>::data()" - doing SFINAE on the existence of data() is insufficient, we need to check it returns an appropriate pointer
20048 +// GCC seems to have "void std::vector<bool>::data()" - doing SFINAE on the existence of data()
20049 +// is insufficient, we need to check it returns an appropriate pointer
20050 template <typename Vector, typename = void>
20051 struct vector_has_data_and_format : std::false_type {};
20052 template <typename Vector>
20053 -struct vector_has_data_and_format<Vector, enable_if_t<std::is_same<decltype(format_descriptor<typename Vector::value_type>::format(), std::declval<Vector>().data()), typename Vector::value_type*>::value>> : std::true_type {};
20054 +struct vector_has_data_and_format<
20056 + enable_if_t<std::is_same<decltype(format_descriptor<typename Vector::value_type>::format(),
20057 + std::declval<Vector>().data()),
20058 + typename Vector::value_type *>::value>> : std::true_type {};
20060 +// [workaround(intel)] Separate function required here
20061 +// Workaround as the Intel compiler does not compile the enable_if_t part below
20062 +// (tested with icc (ICC) 2021.1 Beta 20200827)
20063 +template <typename... Args>
20064 +constexpr bool args_any_are_buffer() {
20065 + return detail::any_of<std::is_same<Args, buffer_protocol>...>::value;
20068 +// [workaround(intel)] Separate function required here
20069 +// [workaround(msvc)] Can't use constexpr bool in return type
20071 // Add the buffer interface to a vector
20072 template <typename Vector, typename Class_, typename... Args>
20073 -enable_if_t<detail::any_of<std::is_same<Args, buffer_protocol>...>::value>
20074 -vector_buffer(Class_& cl) {
20075 +void vector_buffer_impl(Class_ &cl, std::true_type) {
20076 using T = typename Vector::value_type;
20078 - static_assert(vector_has_data_and_format<Vector>::value, "There is not an appropriate format descriptor for this vector");
20079 + static_assert(vector_has_data_and_format<Vector>::value,
20080 + "There is not an appropriate format descriptor for this vector");
20082 - // numpy.h declares this for arbitrary types, but it may raise an exception and crash hard at runtime if PYBIND11_NUMPY_DTYPE hasn't been called, so check here
20083 + // numpy.h declares this for arbitrary types, but it may raise an exception and crash hard
20084 + // at runtime if PYBIND11_NUMPY_DTYPE hasn't been called, so check here
20085 format_descriptor<T>::format();
20087 - cl.def_buffer([](Vector& v) -> buffer_info {
20088 - return buffer_info(v.data(), static_cast<ssize_t>(sizeof(T)), format_descriptor<T>::format(), 1, {v.size()}, {sizeof(T)});
20089 + cl.def_buffer([](Vector &v) -> buffer_info {
20090 + return buffer_info(v.data(),
20091 + static_cast<ssize_t>(sizeof(T)),
20092 + format_descriptor<T>::format(),
20098 - cl.def(init([](buffer buf) {
20099 + cl.def(init([](const buffer &buf) {
20100 auto info = buf.request();
20101 - if (info.ndim != 1 || info.strides[0] % static_cast<ssize_t>(sizeof(T)))
20102 + if (info.ndim != 1 || info.strides[0] % static_cast<ssize_t>(sizeof(T))) {
20103 throw type_error("Only valid 1D buffers can be copied to a vector");
20104 - if (!detail::compare_buffer_info<T>::compare(info) || (ssize_t) sizeof(T) != info.itemsize)
20105 - throw type_error("Format mismatch (Python: " + info.format + " C++: " + format_descriptor<T>::format() + ")");
20107 + if (!detail::compare_buffer_info<T>::compare(info)
20108 + || (ssize_t) sizeof(T) != info.itemsize) {
20109 + throw type_error("Format mismatch (Python: " + info.format
20110 + + " C++: " + format_descriptor<T>::format() + ")");
20113 - auto vec = std::unique_ptr<Vector>(new Vector());
20114 - vec->reserve((size_t) info.shape[0]);
20115 - T *p = static_cast<T*>(info.ptr);
20116 + T *p = static_cast<T *>(info.ptr);
20117 ssize_t step = info.strides[0] / static_cast<ssize_t>(sizeof(T));
20118 T *end = p + info.shape[0] * step;
20119 - for (; p != end; p += step)
20120 - vec->push_back(*p);
20121 - return vec.release();
20123 + return Vector(p, end);
20126 + vec.reserve((size_t) info.shape[0]);
20127 + for (; p != end; p += step) {
20128 + vec.push_back(*p);
20136 template <typename Vector, typename Class_, typename... Args>
20137 -enable_if_t<!detail::any_of<std::is_same<Args, buffer_protocol>...>::value> vector_buffer(Class_&) {}
20138 +void vector_buffer_impl(Class_ &, std::false_type) {}
20140 -NAMESPACE_END(detail)
20141 +template <typename Vector, typename Class_, typename... Args>
20142 +void vector_buffer(Class_ &cl) {
20143 + vector_buffer_impl<Vector, Class_, Args...>(
20144 + cl, detail::any_of<std::is_same<Args, buffer_protocol>...>{});
20147 +PYBIND11_NAMESPACE_END(detail)
20152 template <typename Vector, typename holder_type = std::unique_ptr<Vector>, typename... Args>
20153 -class_<Vector, holder_type> bind_vector(handle scope, std::string const &name, Args&&... args) {
20154 +class_<Vector, holder_type> bind_vector(handle scope, std::string const &name, Args &&...args) {
20155 using Class_ = class_<Vector, holder_type>;
20157 // If the value_type is unregistered (e.g. a converting type) or is itself registered
20158 // module-local then make the vector binding module-local as well:
20159 using vtype = typename Vector::value_type;
20160 - auto vtype_info = detail::get_type_info(typeid(vtype));
20161 + auto *vtype_info = detail::get_type_info(typeid(vtype));
20162 bool local = !vtype_info || vtype_info->module_local;
20164 Class_ cl(scope, name.c_str(), pybind11::module_local(local), std::forward<Args>(args)...);
20165 @@ -402,18 +511,13 @@
20166 // Accessor and iterator; return by value if copyable, otherwise we return by ref + keep-alive
20167 detail::vector_accessor<Vector, Class_>(cl);
20169 - cl.def("__bool__",
20170 - [](const Vector &v) -> bool {
20171 - return !v.empty();
20173 - "Check whether the list is nonempty"
20177 + [](const Vector &v) -> bool { return !v.empty(); },
20178 + "Check whether the list is nonempty");
20180 cl.def("__len__", &Vector::size);
20186 // C++ style functions deprecated, leaving it here as an example
20187 cl.def(init<size_type>());
20188 @@ -457,90 +561,111 @@
20195 // std::map, std::unordered_map
20198 -NAMESPACE_BEGIN(detail)
20199 +PYBIND11_NAMESPACE_BEGIN(detail)
20201 /* Fallback functions */
20202 -template <typename, typename, typename... Args> void map_if_insertion_operator(const Args &...) { }
20203 -template <typename, typename, typename... Args> void map_assignment(const Args &...) { }
20204 +template <typename, typename, typename... Args>
20205 +void map_if_insertion_operator(const Args &...) {}
20206 +template <typename, typename, typename... Args>
20207 +void map_assignment(const Args &...) {}
20209 // Map assignment when copy-assignable: just copy the value
20210 template <typename Map, typename Class_>
20211 -void map_assignment(enable_if_t<std::is_copy_assignable<typename Map::mapped_type>::value, Class_> &cl) {
20212 +void map_assignment(
20213 + enable_if_t<is_copy_assignable<typename Map::mapped_type>::value, Class_> &cl) {
20214 using KeyType = typename Map::key_type;
20215 using MappedType = typename Map::mapped_type;
20217 - cl.def("__setitem__",
20218 - [](Map &m, const KeyType &k, const MappedType &v) {
20219 - auto it = m.find(k);
20220 - if (it != m.end()) it->second = v;
20221 - else m.emplace(k, v);
20224 + cl.def("__setitem__", [](Map &m, const KeyType &k, const MappedType &v) {
20225 + auto it = m.find(k);
20226 + if (it != m.end()) {
20234 -// Not copy-assignable, but still copy-constructible: we can update the value by erasing and reinserting
20235 -template<typename Map, typename Class_>
20236 -void map_assignment(enable_if_t<
20237 - !std::is_copy_assignable<typename Map::mapped_type>::value &&
20238 - is_copy_constructible<typename Map::mapped_type>::value,
20240 +// Not copy-assignable, but still copy-constructible: we can update the value by erasing and
20242 +template <typename Map, typename Class_>
20243 +void map_assignment(enable_if_t<!is_copy_assignable<typename Map::mapped_type>::value
20244 + && is_copy_constructible<typename Map::mapped_type>::value,
20246 using KeyType = typename Map::key_type;
20247 using MappedType = typename Map::mapped_type;
20249 - cl.def("__setitem__",
20250 - [](Map &m, const KeyType &k, const MappedType &v) {
20251 - // We can't use m[k] = v; because value type might not be default constructable
20252 - auto r = m.emplace(k, v);
20254 - // value type is not copy assignable so the only way to insert it is to erase it first...
20255 - m.erase(r.first);
20260 + cl.def("__setitem__", [](Map &m, const KeyType &k, const MappedType &v) {
20261 + // We can't use m[k] = v; because value type might not be default constructable
20262 + auto r = m.emplace(k, v);
20264 + // value type is not copy assignable so the only way to insert it is to erase it
20266 + m.erase(r.first);
20273 -template <typename Map, typename Class_> auto map_if_insertion_operator(Class_ &cl, std::string const &name)
20274 --> decltype(std::declval<std::ostream&>() << std::declval<typename Map::key_type>() << std::declval<typename Map::mapped_type>(), void()) {
20276 - cl.def("__repr__",
20278 +template <typename Map, typename Class_>
20279 +auto map_if_insertion_operator(Class_ &cl, std::string const &name)
20280 + -> decltype(std::declval<std::ostream &>() << std::declval<typename Map::key_type>()
20281 + << std::declval<typename Map::mapped_type>(),
20287 std::ostringstream s;
20290 for (auto const &kv : m) {
20295 s << kv.first << ": " << kv.second;
20301 - "Return the canonical string representation of this map."
20303 + "Return the canonical string representation of this map.");
20306 +template <typename Map>
20307 +struct keys_view {
20311 -NAMESPACE_END(detail)
20312 +template <typename Map>
20313 +struct values_view {
20317 +template <typename Map>
20318 +struct items_view {
20322 +PYBIND11_NAMESPACE_END(detail)
20324 template <typename Map, typename holder_type = std::unique_ptr<Map>, typename... Args>
20325 -class_<Map, holder_type> bind_map(handle scope, const std::string &name, Args&&... args) {
20326 +class_<Map, holder_type> bind_map(handle scope, const std::string &name, Args &&...args) {
20327 using KeyType = typename Map::key_type;
20328 using MappedType = typename Map::mapped_type;
20329 + using KeysView = detail::keys_view<Map>;
20330 + using ValuesView = detail::values_view<Map>;
20331 + using ItemsView = detail::items_view<Map>;
20332 using Class_ = class_<Map, holder_type>;
20334 // If either type is a non-module-local bound type then make the map binding non-local as well;
20335 // otherwise (e.g. both types are either module-local or converting) the map will be
20337 - auto tinfo = detail::get_type_info(typeid(MappedType));
20338 + auto *tinfo = detail::get_type_info(typeid(MappedType));
20339 bool local = !tinfo || tinfo->module_local;
20341 tinfo = detail::get_type_info(typeid(KeyType));
20342 @@ -548,52 +673,113 @@
20345 Class_ cl(scope, name.c_str(), pybind11::module_local(local), std::forward<Args>(args)...);
20346 + class_<KeysView> keys_view(
20347 + scope, ("KeysView[" + name + "]").c_str(), pybind11::module_local(local));
20348 + class_<ValuesView> values_view(
20349 + scope, ("ValuesView[" + name + "]").c_str(), pybind11::module_local(local));
20350 + class_<ItemsView> items_view(
20351 + scope, ("ItemsView[" + name + "]").c_str(), pybind11::module_local(local));
20355 // Register stream insertion operator (if possible)
20356 detail::map_if_insertion_operator<Map, Class_>(cl, name);
20358 - cl.def("__bool__",
20361 [](const Map &m) -> bool { return !m.empty(); },
20362 - "Check whether the map is nonempty"
20363 + "Check whether the map is nonempty");
20367 + [](Map &m) { return make_key_iterator(m.begin(), m.end()); },
20368 + keep_alive<0, 1>() /* Essential: keep map alive while iterator exists */
20373 + [](Map &m) { return KeysView{m}; },
20374 + keep_alive<0, 1>() /* Essential: keep map alive while view exists */
20377 - cl.def("__iter__",
20378 - [](Map &m) { return make_key_iterator(m.begin(), m.end()); },
20379 - keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */
20382 + [](Map &m) { return ValuesView{m}; },
20383 + keep_alive<0, 1>() /* Essential: keep map alive while view exists */
20387 - [](Map &m) { return make_iterator(m.begin(), m.end()); },
20388 - keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */
20391 + [](Map &m) { return ItemsView{m}; },
20392 + keep_alive<0, 1>() /* Essential: keep map alive while view exists */
20395 - cl.def("__getitem__",
20398 [](Map &m, const KeyType &k) -> MappedType & {
20399 auto it = m.find(k);
20400 - if (it == m.end())
20401 - throw key_error();
20402 - return it->second;
20403 + if (it == m.end()) {
20404 + throw key_error();
20406 + return it->second;
20408 return_value_policy::reference_internal // ref + keepalive
20411 + cl.def("__contains__", [](Map &m, const KeyType &k) -> bool {
20412 + auto it = m.find(k);
20413 + if (it == m.end()) {
20418 + // Fallback for when the object is not of the key type
20419 + cl.def("__contains__", [](Map &, const object &) -> bool { return false; });
20421 // Assignment provided only if the type is copyable
20422 detail::map_assignment<Map, Class_>(cl);
20424 - cl.def("__delitem__",
20425 - [](Map &m, const KeyType &k) {
20426 - auto it = m.find(k);
20427 - if (it == m.end())
20428 - throw key_error();
20432 + cl.def("__delitem__", [](Map &m, const KeyType &k) {
20433 + auto it = m.find(k);
20434 + if (it == m.end()) {
20435 + throw key_error();
20440 cl.def("__len__", &Map::size);
20442 + keys_view.def("__len__", [](KeysView &view) { return view.map.size(); });
20445 + [](KeysView &view) { return make_key_iterator(view.map.begin(), view.map.end()); },
20446 + keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */
20448 + keys_view.def("__contains__", [](KeysView &view, const KeyType &k) -> bool {
20449 + auto it = view.map.find(k);
20450 + if (it == view.map.end()) {
20455 + // Fallback for when the object is not of the key type
20456 + keys_view.def("__contains__", [](KeysView &, const object &) -> bool { return false; });
20458 + values_view.def("__len__", [](ValuesView &view) { return view.map.size(); });
20461 + [](ValuesView &view) { return make_value_iterator(view.map.begin(), view.map.end()); },
20462 + keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */
20465 + items_view.def("__len__", [](ItemsView &view) { return view.map.size(); });
20468 + [](ItemsView &view) { return make_iterator(view.map.begin(), view.map.end()); },
20469 + keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */
20475 -NAMESPACE_END(PYBIND11_NAMESPACE)
20476 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
20477 diff -Nur pythia8309.orig/plugins/python/include/pybind11/stl.h pythia8309/plugins/python/include/pybind11/stl.h
20478 --- pythia8309.orig/plugins/python/include/pybind11/stl.h 2023-02-16 18:12:45.000000000 +0100
20479 +++ pythia8309/plugins/python/include/pybind11/stl.h 2023-03-13 09:52:25.474021634 +0100
20480 @@ -10,52 +10,37 @@
20483 #include "pybind11.h"
20485 -#include <unordered_set>
20487 -#include <unordered_map>
20488 +#include "detail/common.h"
20491 #include <iostream>
20496 +#include <unordered_map>
20497 +#include <unordered_set>
20498 #include <valarray>
20500 -#if defined(_MSC_VER)
20501 -#pragma warning(push)
20502 -#pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
20505 -#ifdef __has_include
20506 -// std::optional (but including it in c++14 mode isn't allowed)
20507 -# if defined(PYBIND11_CPP17) && __has_include(<optional>)
20508 +// See `detail/common.h` for implementation of these guards.
20509 +#if defined(PYBIND11_HAS_OPTIONAL)
20510 # include <optional>
20511 -# define PYBIND11_HAS_OPTIONAL 1
20513 -// std::experimental::optional (but not allowed in c++11 mode)
20514 -# if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
20515 - !__has_include(<optional>))
20516 +#elif defined(PYBIND11_HAS_EXP_OPTIONAL)
20517 # include <experimental/optional>
20518 -# define PYBIND11_HAS_EXP_OPTIONAL 1
20521 -# if defined(PYBIND11_CPP17) && __has_include(<variant>)
20524 +#if defined(PYBIND11_HAS_VARIANT)
20525 # include <variant>
20526 -# define PYBIND11_HAS_VARIANT 1
20528 -#elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
20529 -# include <optional>
20530 -# include <variant>
20531 -# define PYBIND11_HAS_OPTIONAL 1
20532 -# define PYBIND11_HAS_VARIANT 1
20535 -NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
20536 -NAMESPACE_BEGIN(detail)
20537 +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
20538 +PYBIND11_NAMESPACE_BEGIN(detail)
20540 /// Extracts an const lvalue reference or rvalue reference for U based on the type of T (e.g. for
20541 /// forwarding a container element). Typically used indirect via forwarded_type(), below.
20542 template <typename T, typename U>
20543 -using forwarded_type = conditional_t<
20544 - std::is_lvalue_reference<T>::value, remove_reference_t<U> &, remove_reference_t<U> &&>;
20545 +using forwarded_type = conditional_t<std::is_lvalue_reference<T>::value,
20546 + remove_reference_t<U> &,
20547 + remove_reference_t<U> &&>;
20549 /// Forwards a value U as rvalue or lvalue according to whether T is rvalue or lvalue; typically
20550 /// used for forwarding a container's elements.
20551 @@ -64,19 +49,22 @@
20552 return std::forward<detail::forwarded_type<T, U>>(std::forward<U>(u));
20555 -template <typename Type, typename Key> struct set_caster {
20556 +template <typename Type, typename Key>
20557 +struct set_caster {
20559 using key_conv = make_caster<Key>;
20561 bool load(handle src, bool convert) {
20562 - if (!isinstance<pybind11::set>(src))
20563 + if (!isinstance<pybind11::set>(src)) {
20566 auto s = reinterpret_borrow<pybind11::set>(src);
20568 for (auto entry : s) {
20570 - if (!conv.load(entry, convert))
20571 + if (!conv.load(entry, convert)) {
20574 value.insert(cast_op<Key &&>(std::move(conv)));
20577 @@ -84,35 +72,40 @@
20579 template <typename T>
20580 static handle cast(T &&src, return_value_policy policy, handle parent) {
20581 - if (!std::is_lvalue_reference<T>::value)
20582 + if (!std::is_lvalue_reference<T>::value) {
20583 policy = return_value_policy_override<Key>::policy(policy);
20586 for (auto &&value : src) {
20587 - auto value_ = reinterpret_steal<object>(key_conv::cast(forward_like<T>(value), policy, parent));
20588 - if (!value_ || !s.add(value_))
20589 + auto value_ = reinterpret_steal<object>(
20590 + key_conv::cast(forward_like<T>(value), policy, parent));
20591 + if (!value_ || !s.add(value_)) {
20595 return s.release();
20598 - PYBIND11_TYPE_CASTER(type, _("Set[") + key_conv::name + _("]"));
20599 + PYBIND11_TYPE_CASTER(type, const_name("Set[") + key_conv::name + const_name("]"));
20602 -template <typename Type, typename Key, typename Value> struct map_caster {
20603 - using key_conv = make_caster<Key>;
20604 +template <typename Type, typename Key, typename Value>
20605 +struct map_caster {
20606 + using key_conv = make_caster<Key>;
20607 using value_conv = make_caster<Value>;
20609 bool load(handle src, bool convert) {
20610 - if (!isinstance<dict>(src))
20611 + if (!isinstance<dict>(src)) {
20614 auto d = reinterpret_borrow<dict>(src);
20616 for (auto it : d) {
20619 - if (!kconv.load(it.first.ptr(), convert) ||
20620 - !vconv.load(it.second.ptr(), convert))
20621 + if (!kconv.load(it.first.ptr(), convert) || !vconv.load(it.second.ptr(), convert)) {
20624 value.emplace(cast_op<Key &&>(std::move(kconv)), cast_op<Value &&>(std::move(vconv)));
20627 @@ -128,78 +121,94 @@
20628 policy_value = return_value_policy_override<Value>::policy(policy_value);
20630 for (auto &&kv : src) {
20631 - auto key = reinterpret_steal<object>(key_conv::cast(forward_like<T>(kv.first), policy_key, parent));
20632 - auto value = reinterpret_steal<object>(value_conv::cast(forward_like<T>(kv.second), policy_value, parent));
20633 - if (!key || !value)
20634 + auto key = reinterpret_steal<object>(
20635 + key_conv::cast(forward_like<T>(kv.first), policy_key, parent));
20636 + auto value = reinterpret_steal<object>(
20637 + value_conv::cast(forward_like<T>(kv.second), policy_value, parent));
20638 + if (!key || !value) {
20643 return d.release();
20646 - PYBIND11_TYPE_CASTER(Type, _("Dict[") + key_conv::name + _(", ") + value_conv::name + _("]"));
20647 + PYBIND11_TYPE_CASTER(Type,
20648 + const_name("Dict[") + key_conv::name + const_name(", ") + value_conv::name
20649 + + const_name("]"));
20652 -template <typename Type, typename Value> struct list_caster {
20653 +template <typename Type, typename Value>
20654 +struct list_caster {
20655 using value_conv = make_caster<Value>;
20657 bool load(handle src, bool convert) {
20658 - if (!isinstance<sequence>(src) || isinstance<str>(src))
20659 + if (!isinstance<sequence>(src) || isinstance<bytes>(src) || isinstance<str>(src)) {
20662 auto s = reinterpret_borrow<sequence>(src);
20664 reserve_maybe(s, &value);
20665 for (auto it : s) {
20667 - if (!conv.load(it, convert))
20668 + if (!conv.load(it, convert)) {
20671 value.push_back(cast_op<Value &&>(std::move(conv)));
20677 - template <typename T = Type,
20678 - enable_if_t<std::is_same<decltype(std::declval<T>().reserve(0)), void>::value, int> = 0>
20679 - void reserve_maybe(sequence s, Type *) { value.reserve(s.size()); }
20680 - void reserve_maybe(sequence, void *) { }
20682 + typename T = Type,
20683 + enable_if_t<std::is_same<decltype(std::declval<T>().reserve(0)), void>::value, int> = 0>
20684 + void reserve_maybe(const sequence &s, Type *) {
20685 + value.reserve(s.size());
20687 + void reserve_maybe(const sequence &, void *) {}
20690 template <typename T>
20691 static handle cast(T &&src, return_value_policy policy, handle parent) {
20692 - if (!std::is_lvalue_reference<T>::value)
20693 + if (!std::is_lvalue_reference<T>::value) {
20694 policy = return_value_policy_override<Value>::policy(policy);
20696 list l(src.size());
20697 - size_t index = 0;
20698 + ssize_t index = 0;
20699 for (auto &&value : src) {
20700 - auto value_ = reinterpret_steal<object>(value_conv::cast(forward_like<T>(value), policy, parent));
20702 + auto value_ = reinterpret_steal<object>(
20703 + value_conv::cast(forward_like<T>(value), policy, parent));
20706 - PyList_SET_ITEM(l.ptr(), (ssize_t) index++, value_.release().ptr()); // steals a reference
20708 + PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference
20710 return l.release();
20713 - PYBIND11_TYPE_CASTER(Type, _("List[") + value_conv::name + _("]"));
20714 + PYBIND11_TYPE_CASTER(Type, const_name("List[") + value_conv::name + const_name("]"));
20717 -template <typename Type, typename Alloc> struct type_caster<std::vector<Type, Alloc>>
20718 - : list_caster<std::vector<Type, Alloc>, Type> { };
20719 +template <typename Type, typename Alloc>
20720 +struct type_caster<std::vector<Type, Alloc>> : list_caster<std::vector<Type, Alloc>, Type> {};
20722 -template <typename Type, typename Alloc> struct type_caster<std::deque<Type, Alloc>>
20723 - : list_caster<std::deque<Type, Alloc>, Type> { };
20724 +template <typename Type, typename Alloc>
20725 +struct type_caster<std::deque<Type, Alloc>> : list_caster<std::deque<Type, Alloc>, Type> {};
20727 -template <typename Type, typename Alloc> struct type_caster<std::list<Type, Alloc>>
20728 - : list_caster<std::list<Type, Alloc>, Type> { };
20729 +template <typename Type, typename Alloc>
20730 +struct type_caster<std::list<Type, Alloc>> : list_caster<std::list<Type, Alloc>, Type> {};
20732 -template <typename ArrayType, typename Value, bool Resizable, size_t Size = 0> struct array_caster {
20733 +template <typename ArrayType, typename Value, bool Resizable, size_t Size = 0>
20734 +struct array_caster {
20735 using value_conv = make_caster<Value>;
20738 template <bool R = Resizable>
20739 bool require_size(enable_if_t<R, size_t> size) {
20740 - if (value.size() != size)
20741 + if (value.size() != size) {
20742 value.resize(size);
20746 template <bool R = Resizable>
20747 @@ -209,16 +218,19 @@
20750 bool load(handle src, bool convert) {
20751 - if (!isinstance<sequence>(src))
20752 + if (!isinstance<sequence>(src)) {
20755 auto l = reinterpret_borrow<sequence>(src);
20756 - if (!require_size(l.size()))
20757 + if (!require_size(l.size())) {
20761 for (auto it : l) {
20763 - if (!conv.load(it, convert))
20764 + if (!conv.load(it, convert)) {
20767 value[ctr++] = cast_op<Value &&>(std::move(conv));
20770 @@ -227,79 +239,99 @@
20771 template <typename T>
20772 static handle cast(T &&src, return_value_policy policy, handle parent) {
20773 list l(src.size());
20774 - size_t index = 0;
20775 + ssize_t index = 0;
20776 for (auto &&value : src) {
20777 - auto value_ = reinterpret_steal<object>(value_conv::cast(forward_like<T>(value), policy, parent));
20779 + auto value_ = reinterpret_steal<object>(
20780 + value_conv::cast(forward_like<T>(value), policy, parent));
20783 - PyList_SET_ITEM(l.ptr(), (ssize_t) index++, value_.release().ptr()); // steals a reference
20785 + PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference
20787 return l.release();
20790 - PYBIND11_TYPE_CASTER(ArrayType, _("List[") + value_conv::name + _<Resizable>(_(""), _("[") + _<Size>() + _("]")) + _("]"));
20791 + PYBIND11_TYPE_CASTER(ArrayType,
20792 + const_name("List[") + value_conv::name
20793 + + const_name<Resizable>(const_name(""),
20794 + const_name("[") + const_name<Size>()
20795 + + const_name("]"))
20796 + + const_name("]"));
20799 -template <typename Type, size_t Size> struct type_caster<std::array<Type, Size>>
20800 - : array_caster<std::array<Type, Size>, Type, false, Size> { };
20802 -template <typename Type> struct type_caster<std::valarray<Type>>
20803 - : array_caster<std::valarray<Type>, Type, true> { };
20805 -template <typename Key, typename Compare, typename Alloc> struct type_caster<std::set<Key, Compare, Alloc>>
20806 - : set_caster<std::set<Key, Compare, Alloc>, Key> { };
20808 -template <typename Key, typename Hash, typename Equal, typename Alloc> struct type_caster<std::unordered_set<Key, Hash, Equal, Alloc>>
20809 - : set_caster<std::unordered_set<Key, Hash, Equal, Alloc>, Key> { };
20811 -template <typename Key, typename Value, typename Compare, typename Alloc> struct type_caster<std::map<Key, Value, Compare, Alloc>>
20812 - : map_caster<std::map<Key, Value, Compare, Alloc>, Key, Value> { };
20814 -template <typename Key, typename Value, typename Hash, typename Equal, typename Alloc> struct type_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>>
20815 - : map_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>, Key, Value> { };
20816 +template <typename Type, size_t Size>
20817 +struct type_caster<std::array<Type, Size>>
20818 + : array_caster<std::array<Type, Size>, Type, false, Size> {};
20820 +template <typename Type>
20821 +struct type_caster<std::valarray<Type>> : array_caster<std::valarray<Type>, Type, true> {};
20823 +template <typename Key, typename Compare, typename Alloc>
20824 +struct type_caster<std::set<Key, Compare, Alloc>>
20825 + : set_caster<std::set<Key, Compare, Alloc>, Key> {};
20827 +template <typename Key, typename Hash, typename Equal, typename Alloc>
20828 +struct type_caster<std::unordered_set<Key, Hash, Equal, Alloc>>
20829 + : set_caster<std::unordered_set<Key, Hash, Equal, Alloc>, Key> {};
20831 +template <typename Key, typename Value, typename Compare, typename Alloc>
20832 +struct type_caster<std::map<Key, Value, Compare, Alloc>>
20833 + : map_caster<std::map<Key, Value, Compare, Alloc>, Key, Value> {};
20835 +template <typename Key, typename Value, typename Hash, typename Equal, typename Alloc>
20836 +struct type_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>>
20837 + : map_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>, Key, Value> {};
20839 // This type caster is intended to be used for std::optional and std::experimental::optional
20840 -template<typename T> struct optional_caster {
20841 - using value_conv = make_caster<typename T::value_type>;
20842 +template <typename Type, typename Value = typename Type::value_type>
20843 +struct optional_caster {
20844 + using value_conv = make_caster<Value>;
20846 - template <typename T_>
20847 - static handle cast(T_ &&src, return_value_policy policy, handle parent) {
20849 + template <typename T>
20850 + static handle cast(T &&src, return_value_policy policy, handle parent) {
20852 return none().inc_ref();
20853 - policy = return_value_policy_override<typename T::value_type>::policy(policy);
20854 - return value_conv::cast(*std::forward<T_>(src), policy, parent);
20856 + if (!std::is_lvalue_reference<T>::value) {
20857 + policy = return_value_policy_override<Value>::policy(policy);
20859 + return value_conv::cast(*std::forward<T>(src), policy, parent);
20862 bool load(handle src, bool convert) {
20865 - } else if (src.is_none()) {
20866 - return true; // default-constructed value is already empty
20868 + if (src.is_none()) {
20869 + return true; // default-constructed value is already empty
20871 value_conv inner_caster;
20872 - if (!inner_caster.load(src, convert))
20873 + if (!inner_caster.load(src, convert)) {
20877 - value.emplace(cast_op<typename T::value_type &&>(std::move(inner_caster)));
20878 + value.emplace(cast_op<Value &&>(std::move(inner_caster)));
20882 - PYBIND11_TYPE_CASTER(T, _("Optional[") + value_conv::name + _("]"));
20883 + PYBIND11_TYPE_CASTER(Type, const_name("Optional[") + value_conv::name + const_name("]"));
20886 -#if PYBIND11_HAS_OPTIONAL
20887 -template<typename T> struct type_caster<std::optional<T>>
20888 - : public optional_caster<std::optional<T>> {};
20889 +#if defined(PYBIND11_HAS_OPTIONAL)
20890 +template <typename T>
20891 +struct type_caster<std::optional<T>> : public optional_caster<std::optional<T>> {};
20893 -template<> struct type_caster<std::nullopt_t>
20894 - : public void_caster<std::nullopt_t> {};
20896 +struct type_caster<std::nullopt_t> : public void_caster<std::nullopt_t> {};
20899 -#if PYBIND11_HAS_EXP_OPTIONAL
20900 -template<typename T> struct type_caster<std::experimental::optional<T>>
20901 +#if defined(PYBIND11_HAS_EXP_OPTIONAL)
20902 +template <typename T>
20903 +struct type_caster<std::experimental::optional<T>>
20904 : public optional_caster<std::experimental::optional<T>> {};
20906 -template<> struct type_caster<std::experimental::nullopt_t>
20908 +struct type_caster<std::experimental::nullopt_t>
20909 : public void_caster<std::experimental::nullopt_t> {};
20912 @@ -320,7 +352,7 @@
20913 /// `namespace::variant` types which provide a `namespace::visit()` function are handled here
20914 /// automatically using argument-dependent lookup. Users can provide specializations for other
20915 /// variant-like classes, e.g. `boost::variant` and `boost::apply_visitor`.
20916 -template <template<typename...> class Variant>
20917 +template <template <typename...> class Variant>
20918 struct visit_helper {
20919 template <typename... Args>
20920 static auto call(Args &&...args) -> decltype(visit(std::forward<Args>(args)...)) {
20921 @@ -329,9 +361,10 @@
20924 /// Generic variant caster
20925 -template <typename Variant> struct variant_caster;
20926 +template <typename Variant>
20927 +struct variant_caster;
20929 -template <template<typename...> class V, typename... Ts>
20930 +template <template <typename...> class V, typename... Ts>
20931 struct variant_caster<V<Ts...>> {
20932 static_assert(sizeof...(Ts) > 0, "Variant must consist of at least one alternative.");
20934 @@ -352,8 +385,9 @@
20935 // E.g. `py::int_(1).cast<variant<double, int>>()` needs to fill the `int`
20936 // slot of the variant. Without two-pass loading `double` would be filled
20937 // because it appears first and a conversion is possible.
20938 - if (convert && load_alternative(src, false, type_list<Ts...>{}))
20939 + if (convert && load_alternative(src, false, type_list<Ts...>{})) {
20942 return load_alternative(src, convert, type_list<Ts...>{});
20945 @@ -364,23 +398,25 @@
20948 using Type = V<Ts...>;
20949 - PYBIND11_TYPE_CASTER(Type, _("Union[") + detail::concat(make_caster<Ts>::name...) + _("]"));
20950 + PYBIND11_TYPE_CASTER(Type,
20951 + const_name("Union[") + detail::concat(make_caster<Ts>::name...)
20952 + + const_name("]"));
20955 -#if PYBIND11_HAS_VARIANT
20956 +#if defined(PYBIND11_HAS_VARIANT)
20957 template <typename... Ts>
20958 -struct type_caster<std::variant<Ts...>> : variant_caster<std::variant<Ts...>> { };
20959 +struct type_caster<std::variant<Ts...>> : variant_caster<std::variant<Ts...>> {};
20962 -NAMESPACE_END(detail)
20963 +PYBIND11_NAMESPACE_END(detail)
20965 inline std::ostream &operator<<(std::ostream &os, const handle &obj) {
20966 +#ifdef PYBIND11_HAS_STRING_VIEW
20967 + os << str(obj).cast<std::string_view>();
20969 os << (std::string) str(obj);
20974 -NAMESPACE_END(PYBIND11_NAMESPACE)
20976 -#if defined(_MSC_VER)
20977 -#pragma warning(pop)
20979 +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
20980 diff -Nur pythia8309.orig/plugins/python/src/Analysis.cpp pythia8309/plugins/python/src/Analysis.cpp
20981 --- pythia8309.orig/plugins/python/src/Analysis.cpp 2023-02-16 18:12:45.000000000 +0100
20982 +++ pythia8309/plugins/python/src/Analysis.cpp 2023-03-13 10:37:57.967247361 +0100
20985 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
20986 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
20987 - static pybind11::detail::overload_caster_t<bool> caster;
20988 + static pybind11::detail::override_caster_t<bool> caster;
20989 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
20991 else return pybind11::detail::cast_safe<bool>(std::move(o));
20994 auto o = overload.operator()<pybind11::return_value_policy::reference>();
20995 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
20996 - static pybind11::detail::overload_caster_t<bool> caster;
20997 + static pybind11::detail::override_caster_t<bool> caster;
20998 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21000 else return pybind11::detail::cast_safe<bool>(std::move(o));
21003 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21004 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21005 - static pybind11::detail::overload_caster_t<void> caster;
21006 + static pybind11::detail::override_caster_t<void> caster;
21007 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21009 else return pybind11::detail::cast_safe<void>(std::move(o));
21010 @@ -109,7 +109,7 @@
21012 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21013 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21014 - static pybind11::detail::overload_caster_t<void> caster;
21015 + static pybind11::detail::override_caster_t<void> caster;
21016 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21018 else return pybind11::detail::cast_safe<void>(std::move(o));
21019 @@ -122,7 +122,7 @@
21021 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21022 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21023 - static pybind11::detail::overload_caster_t<void> caster;
21024 + static pybind11::detail::override_caster_t<void> caster;
21025 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21027 else return pybind11::detail::cast_safe<void>(std::move(o));
21028 @@ -135,7 +135,7 @@
21030 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
21031 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21032 - static pybind11::detail::overload_caster_t<bool> caster;
21033 + static pybind11::detail::override_caster_t<bool> caster;
21034 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21036 else return pybind11::detail::cast_safe<bool>(std::move(o));
21037 @@ -148,7 +148,7 @@
21039 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21040 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21041 - static pybind11::detail::overload_caster_t<double> caster;
21042 + static pybind11::detail::override_caster_t<double> caster;
21043 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21045 else return pybind11::detail::cast_safe<double>(std::move(o));
21046 @@ -161,7 +161,7 @@
21048 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21049 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21050 - static pybind11::detail::overload_caster_t<double> caster;
21051 + static pybind11::detail::override_caster_t<double> caster;
21052 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21054 else return pybind11::detail::cast_safe<double>(std::move(o));
21055 @@ -174,7 +174,7 @@
21057 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21058 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
21059 - static pybind11::detail::overload_caster_t<int> caster;
21060 + static pybind11::detail::override_caster_t<int> caster;
21061 return pybind11::detail::cast_ref<int>(std::move(o), caster);
21063 else return pybind11::detail::cast_safe<int>(std::move(o));
21064 @@ -187,7 +187,7 @@
21066 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
21067 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21068 - static pybind11::detail::overload_caster_t<void> caster;
21069 + static pybind11::detail::override_caster_t<void> caster;
21070 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21072 else return pybind11::detail::cast_safe<void>(std::move(o));
21073 @@ -200,7 +200,7 @@
21075 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
21076 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21077 - static pybind11::detail::overload_caster_t<void> caster;
21078 + static pybind11::detail::override_caster_t<void> caster;
21079 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21081 else return pybind11::detail::cast_safe<void>(std::move(o));
21082 @@ -213,7 +213,7 @@
21084 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21085 if (pybind11::detail::cast_is_temporary_value_reference<struct Pythia8::PDF::PDFEnvelope>::value) {
21086 - static pybind11::detail::overload_caster_t<struct Pythia8::PDF::PDFEnvelope> caster;
21087 + static pybind11::detail::override_caster_t<struct Pythia8::PDF::PDFEnvelope> caster;
21088 return pybind11::detail::cast_ref<struct Pythia8::PDF::PDFEnvelope>(std::move(o), caster);
21090 else return pybind11::detail::cast_safe<struct Pythia8::PDF::PDFEnvelope>(std::move(o));
21091 @@ -226,7 +226,7 @@
21093 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
21094 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21095 - static pybind11::detail::overload_caster_t<double> caster;
21096 + static pybind11::detail::override_caster_t<double> caster;
21097 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21099 else return pybind11::detail::cast_safe<double>(std::move(o));
21100 @@ -239,7 +239,7 @@
21102 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21103 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21104 - static pybind11::detail::overload_caster_t<double> caster;
21105 + static pybind11::detail::override_caster_t<double> caster;
21106 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21108 else return pybind11::detail::cast_safe<double>(std::move(o));
21109 @@ -252,7 +252,7 @@
21111 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21112 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
21113 - static pybind11::detail::overload_caster_t<int> caster;
21114 + static pybind11::detail::override_caster_t<int> caster;
21115 return pybind11::detail::cast_ref<int>(std::move(o), caster);
21117 else return pybind11::detail::cast_safe<int>(std::move(o));
21118 @@ -265,7 +265,7 @@
21120 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21121 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21122 - static pybind11::detail::overload_caster_t<double> caster;
21123 + static pybind11::detail::override_caster_t<double> caster;
21124 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21126 else return pybind11::detail::cast_safe<double>(std::move(o));
21127 @@ -278,7 +278,7 @@
21129 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21130 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21131 - static pybind11::detail::overload_caster_t<double> caster;
21132 + static pybind11::detail::override_caster_t<double> caster;
21133 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21135 else return pybind11::detail::cast_safe<double>(std::move(o));
21136 @@ -291,7 +291,7 @@
21138 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21139 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21140 - static pybind11::detail::overload_caster_t<void> caster;
21141 + static pybind11::detail::override_caster_t<void> caster;
21142 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21144 else return pybind11::detail::cast_safe<void>(std::move(o));
21145 @@ -304,7 +304,7 @@
21147 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
21148 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21149 - static pybind11::detail::overload_caster_t<double> caster;
21150 + static pybind11::detail::override_caster_t<double> caster;
21151 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21153 else return pybind11::detail::cast_safe<double>(std::move(o));
21154 @@ -317,7 +317,7 @@
21156 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
21157 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21158 - static pybind11::detail::overload_caster_t<double> caster;
21159 + static pybind11::detail::override_caster_t<double> caster;
21160 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21162 else return pybind11::detail::cast_safe<double>(std::move(o));
21163 @@ -330,7 +330,7 @@
21165 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
21166 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21167 - static pybind11::detail::overload_caster_t<double> caster;
21168 + static pybind11::detail::override_caster_t<double> caster;
21169 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21171 else return pybind11::detail::cast_safe<double>(std::move(o));
21172 @@ -343,7 +343,7 @@
21174 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21175 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21176 - static pybind11::detail::overload_caster_t<double> caster;
21177 + static pybind11::detail::override_caster_t<double> caster;
21178 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21180 else return pybind11::detail::cast_safe<double>(std::move(o));
21181 @@ -356,7 +356,7 @@
21183 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21184 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21185 - static pybind11::detail::overload_caster_t<bool> caster;
21186 + static pybind11::detail::override_caster_t<bool> caster;
21187 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21189 else return pybind11::detail::cast_safe<bool>(std::move(o));
21190 @@ -369,7 +369,7 @@
21192 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21193 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21194 - static pybind11::detail::overload_caster_t<double> caster;
21195 + static pybind11::detail::override_caster_t<double> caster;
21196 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21198 else return pybind11::detail::cast_safe<double>(std::move(o));
21199 @@ -382,7 +382,7 @@
21201 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21202 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21203 - static pybind11::detail::overload_caster_t<double> caster;
21204 + static pybind11::detail::override_caster_t<double> caster;
21205 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21207 else return pybind11::detail::cast_safe<double>(std::move(o));
21208 @@ -395,7 +395,7 @@
21210 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21211 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21212 - static pybind11::detail::overload_caster_t<double> caster;
21213 + static pybind11::detail::override_caster_t<double> caster;
21214 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21216 else return pybind11::detail::cast_safe<double>(std::move(o));
21217 @@ -408,7 +408,7 @@
21219 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21220 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21221 - static pybind11::detail::overload_caster_t<double> caster;
21222 + static pybind11::detail::override_caster_t<double> caster;
21223 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21225 else return pybind11::detail::cast_safe<double>(std::move(o));
21226 @@ -421,7 +421,7 @@
21228 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
21229 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21230 - static pybind11::detail::overload_caster_t<double> caster;
21231 + static pybind11::detail::override_caster_t<double> caster;
21232 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21234 else return pybind11::detail::cast_safe<double>(std::move(o));
21235 @@ -434,7 +434,7 @@
21237 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
21238 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21239 - static pybind11::detail::overload_caster_t<double> caster;
21240 + static pybind11::detail::override_caster_t<double> caster;
21241 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21243 else return pybind11::detail::cast_safe<double>(std::move(o));
21244 @@ -447,7 +447,7 @@
21246 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21247 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21248 - static pybind11::detail::overload_caster_t<void> caster;
21249 + static pybind11::detail::override_caster_t<void> caster;
21250 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21252 else return pybind11::detail::cast_safe<void>(std::move(o));
21253 @@ -460,7 +460,7 @@
21255 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
21256 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21257 - static pybind11::detail::overload_caster_t<void> caster;
21258 + static pybind11::detail::override_caster_t<void> caster;
21259 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21261 else return pybind11::detail::cast_safe<void>(std::move(o));
21262 diff -Nur pythia8309.orig/plugins/python/src/Basics_1.cpp pythia8309/plugins/python/src/Basics_1.cpp
21263 --- pythia8309.orig/plugins/python/src/Basics_1.cpp 2023-02-16 18:12:45.000000000 +0100
21264 +++ pythia8309/plugins/python/src/Basics_1.cpp 2023-03-13 09:52:25.477021640 +0100
21267 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21268 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21269 - static pybind11::detail::overload_caster_t<double> caster;
21270 + static pybind11::detail::override_caster_t<double> caster;
21271 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21273 else return pybind11::detail::cast_safe<double>(std::move(o));
21274 diff -Nur pythia8309.orig/plugins/python/src/Event.cpp pythia8309/plugins/python/src/Event.cpp
21275 --- pythia8309.orig/plugins/python/src/Event.cpp 2023-02-16 18:12:45.000000000 +0100
21276 +++ pythia8309/plugins/python/src/Event.cpp 2023-03-13 09:52:25.477021640 +0100
21279 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21280 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
21281 - static pybind11::detail::overload_caster_t<int> caster;
21282 + static pybind11::detail::override_caster_t<int> caster;
21283 return pybind11::detail::cast_ref<int>(std::move(o), caster);
21285 else return pybind11::detail::cast_safe<int>(std::move(o));
21286 diff -Nur pythia8309.orig/plugins/python/src/exception.cpp pythia8309/plugins/python/src/exception.cpp
21287 --- pythia8309.orig/plugins/python/src/exception.cpp 2023-02-16 18:12:45.000000000 +0100
21288 +++ pythia8309/plugins/python/src/exception.cpp 2023-03-13 09:52:25.477021640 +0100
21291 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21292 if (pybind11::detail::cast_is_temporary_value_reference<const char *>::value) {
21293 - static pybind11::detail::overload_caster_t<const char *> caster;
21294 + static pybind11::detail::override_caster_t<const char *> caster;
21295 return pybind11::detail::cast_ref<const char *>(std::move(o), caster);
21297 else return pybind11::detail::cast_safe<const char *>(std::move(o));
21298 diff -Nur pythia8309.orig/plugins/python/src/PythiaParallel.cpp pythia8309/plugins/python/src/PythiaParallel.cpp
21299 --- pythia8309.orig/plugins/python/src/PythiaParallel.cpp 2023-02-16 18:12:45.000000000 +0100
21300 +++ pythia8309/plugins/python/src/PythiaParallel.cpp 2023-03-13 10:48:16.337668205 +0100
21303 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21304 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21305 - static pybind11::detail::overload_caster_t<bool> caster;
21306 + static pybind11::detail::override_caster_t<bool> caster;
21307 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21309 else return pybind11::detail::cast_safe<bool>(std::move(o));
21312 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21313 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21314 - static pybind11::detail::overload_caster_t<bool> caster;
21315 + static pybind11::detail::override_caster_t<bool> caster;
21316 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21318 else return pybind11::detail::cast_safe<bool>(std::move(o));
21321 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21322 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21323 - static pybind11::detail::overload_caster_t<void> caster;
21324 + static pybind11::detail::override_caster_t<void> caster;
21325 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21327 else return pybind11::detail::cast_safe<void>(std::move(o));
21328 @@ -111,7 +111,7 @@
21330 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21331 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21332 - static pybind11::detail::overload_caster_t<void> caster;
21333 + static pybind11::detail::override_caster_t<void> caster;
21334 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21336 else return pybind11::detail::cast_safe<void>(std::move(o));
21337 @@ -124,7 +124,7 @@
21339 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21340 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21341 - static pybind11::detail::overload_caster_t<void> caster;
21342 + static pybind11::detail::override_caster_t<void> caster;
21343 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21345 else return pybind11::detail::cast_safe<void>(std::move(o));
21346 @@ -137,7 +137,7 @@
21348 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21349 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21350 - static pybind11::detail::overload_caster_t<void> caster;
21351 + static pybind11::detail::override_caster_t<void> caster;
21352 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21354 else return pybind11::detail::cast_safe<void>(std::move(o));
21355 @@ -150,7 +150,7 @@
21357 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21358 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21359 - static pybind11::detail::overload_caster_t<void> caster;
21360 + static pybind11::detail::override_caster_t<void> caster;
21361 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21363 else return pybind11::detail::cast_safe<void>(std::move(o));
21364 @@ -169,7 +169,7 @@
21366 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21367 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21368 - static pybind11::detail::overload_caster_t<bool> caster;
21369 + static pybind11::detail::override_caster_t<bool> caster;
21370 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21372 else return pybind11::detail::cast_safe<bool>(std::move(o));
21373 @@ -182,7 +182,7 @@
21375 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21376 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21377 - static pybind11::detail::overload_caster_t<bool> caster;
21378 + static pybind11::detail::override_caster_t<bool> caster;
21379 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21381 else return pybind11::detail::cast_safe<bool>(std::move(o));
21382 @@ -195,7 +195,7 @@
21384 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21385 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21386 - static pybind11::detail::overload_caster_t<bool> caster;
21387 + static pybind11::detail::override_caster_t<bool> caster;
21388 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21390 else return pybind11::detail::cast_safe<bool>(std::move(o));
21391 @@ -208,7 +208,7 @@
21393 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21394 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21395 - static pybind11::detail::overload_caster_t<double> caster;
21396 + static pybind11::detail::override_caster_t<double> caster;
21397 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21399 else return pybind11::detail::cast_safe<double>(std::move(o));
21400 @@ -221,7 +221,7 @@
21402 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21403 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21404 - static pybind11::detail::overload_caster_t<bool> caster;
21405 + static pybind11::detail::override_caster_t<bool> caster;
21406 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21408 else return pybind11::detail::cast_safe<bool>(std::move(o));
21409 @@ -234,7 +234,7 @@
21411 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21412 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21413 - static pybind11::detail::overload_caster_t<bool> caster;
21414 + static pybind11::detail::override_caster_t<bool> caster;
21415 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21417 else return pybind11::detail::cast_safe<bool>(std::move(o));
21418 @@ -247,7 +247,7 @@
21420 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21421 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21422 - static pybind11::detail::overload_caster_t<bool> caster;
21423 + static pybind11::detail::override_caster_t<bool> caster;
21424 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21426 else return pybind11::detail::cast_safe<bool>(std::move(o));
21427 @@ -260,7 +260,7 @@
21429 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21430 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21431 - static pybind11::detail::overload_caster_t<bool> caster;
21432 + static pybind11::detail::override_caster_t<bool> caster;
21433 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21435 else return pybind11::detail::cast_safe<bool>(std::move(o));
21436 @@ -273,7 +273,7 @@
21438 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21439 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21440 - static pybind11::detail::overload_caster_t<bool> caster;
21441 + static pybind11::detail::override_caster_t<bool> caster;
21442 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21444 else return pybind11::detail::cast_safe<bool>(std::move(o));
21445 @@ -286,7 +286,7 @@
21447 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21448 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21449 - static pybind11::detail::overload_caster_t<double> caster;
21450 + static pybind11::detail::override_caster_t<double> caster;
21451 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21453 else return pybind11::detail::cast_safe<double>(std::move(o));
21454 @@ -299,7 +299,7 @@
21456 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
21457 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21458 - static pybind11::detail::overload_caster_t<bool> caster;
21459 + static pybind11::detail::override_caster_t<bool> caster;
21460 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21462 else return pybind11::detail::cast_safe<bool>(std::move(o));
21463 @@ -312,7 +312,7 @@
21465 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21466 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21467 - static pybind11::detail::overload_caster_t<bool> caster;
21468 + static pybind11::detail::override_caster_t<bool> caster;
21469 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21471 else return pybind11::detail::cast_safe<bool>(std::move(o));
21472 @@ -325,7 +325,7 @@
21474 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21475 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
21476 - static pybind11::detail::overload_caster_t<int> caster;
21477 + static pybind11::detail::override_caster_t<int> caster;
21478 return pybind11::detail::cast_ref<int>(std::move(o), caster);
21480 else return pybind11::detail::cast_safe<int>(std::move(o));
21481 @@ -338,7 +338,7 @@
21483 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
21484 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21485 - static pybind11::detail::overload_caster_t<bool> caster;
21486 + static pybind11::detail::override_caster_t<bool> caster;
21487 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21489 else return pybind11::detail::cast_safe<bool>(std::move(o));
21490 @@ -351,7 +351,7 @@
21492 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21493 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21494 - static pybind11::detail::overload_caster_t<bool> caster;
21495 + static pybind11::detail::override_caster_t<bool> caster;
21496 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21498 else return pybind11::detail::cast_safe<bool>(std::move(o));
21499 @@ -364,7 +364,7 @@
21501 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21502 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
21503 - static pybind11::detail::overload_caster_t<int> caster;
21504 + static pybind11::detail::override_caster_t<int> caster;
21505 return pybind11::detail::cast_ref<int>(std::move(o), caster);
21507 else return pybind11::detail::cast_safe<int>(std::move(o));
21508 @@ -377,7 +377,7 @@
21510 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
21511 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21512 - static pybind11::detail::overload_caster_t<bool> caster;
21513 + static pybind11::detail::override_caster_t<bool> caster;
21514 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21516 else return pybind11::detail::cast_safe<bool>(std::move(o));
21517 @@ -390,7 +390,7 @@
21519 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21520 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21521 - static pybind11::detail::overload_caster_t<bool> caster;
21522 + static pybind11::detail::override_caster_t<bool> caster;
21523 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21525 else return pybind11::detail::cast_safe<bool>(std::move(o));
21526 @@ -403,7 +403,7 @@
21528 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21529 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21530 - static pybind11::detail::overload_caster_t<bool> caster;
21531 + static pybind11::detail::override_caster_t<bool> caster;
21532 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21534 else return pybind11::detail::cast_safe<bool>(std::move(o));
21535 @@ -416,7 +416,7 @@
21537 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21538 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21539 - static pybind11::detail::overload_caster_t<bool> caster;
21540 + static pybind11::detail::override_caster_t<bool> caster;
21541 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21543 else return pybind11::detail::cast_safe<bool>(std::move(o));
21544 @@ -429,7 +429,7 @@
21546 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21547 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21548 - static pybind11::detail::overload_caster_t<bool> caster;
21549 + static pybind11::detail::override_caster_t<bool> caster;
21550 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21552 else return pybind11::detail::cast_safe<bool>(std::move(o));
21553 @@ -442,7 +442,7 @@
21555 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21556 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21557 - static pybind11::detail::overload_caster_t<bool> caster;
21558 + static pybind11::detail::override_caster_t<bool> caster;
21559 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21561 else return pybind11::detail::cast_safe<bool>(std::move(o));
21562 @@ -455,7 +455,7 @@
21564 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21565 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21566 - static pybind11::detail::overload_caster_t<bool> caster;
21567 + static pybind11::detail::override_caster_t<bool> caster;
21568 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21570 else return pybind11::detail::cast_safe<bool>(std::move(o));
21571 @@ -468,7 +468,7 @@
21573 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
21574 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21575 - static pybind11::detail::overload_caster_t<double> caster;
21576 + static pybind11::detail::override_caster_t<double> caster;
21577 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21579 else return pybind11::detail::cast_safe<double>(std::move(o));
21580 @@ -481,7 +481,7 @@
21582 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21583 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21584 - static pybind11::detail::overload_caster_t<bool> caster;
21585 + static pybind11::detail::override_caster_t<bool> caster;
21586 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21588 else return pybind11::detail::cast_safe<bool>(std::move(o));
21589 @@ -494,7 +494,7 @@
21591 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
21592 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21593 - static pybind11::detail::overload_caster_t<bool> caster;
21594 + static pybind11::detail::override_caster_t<bool> caster;
21595 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21597 else return pybind11::detail::cast_safe<bool>(std::move(o));
21598 @@ -507,7 +507,7 @@
21600 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21601 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21602 - static pybind11::detail::overload_caster_t<bool> caster;
21603 + static pybind11::detail::override_caster_t<bool> caster;
21604 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21606 else return pybind11::detail::cast_safe<bool>(std::move(o));
21607 @@ -520,7 +520,7 @@
21609 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
21610 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21611 - static pybind11::detail::overload_caster_t<bool> caster;
21612 + static pybind11::detail::override_caster_t<bool> caster;
21613 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21615 else return pybind11::detail::cast_safe<bool>(std::move(o));
21616 @@ -533,7 +533,7 @@
21618 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21619 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21620 - static pybind11::detail::overload_caster_t<bool> caster;
21621 + static pybind11::detail::override_caster_t<bool> caster;
21622 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21624 else return pybind11::detail::cast_safe<bool>(std::move(o));
21625 @@ -546,7 +546,7 @@
21627 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
21628 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21629 - static pybind11::detail::overload_caster_t<bool> caster;
21630 + static pybind11::detail::override_caster_t<bool> caster;
21631 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21633 else return pybind11::detail::cast_safe<bool>(std::move(o));
21634 @@ -559,7 +559,7 @@
21636 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21637 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21638 - static pybind11::detail::overload_caster_t<bool> caster;
21639 + static pybind11::detail::override_caster_t<bool> caster;
21640 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21642 else return pybind11::detail::cast_safe<bool>(std::move(o));
21643 @@ -572,7 +572,7 @@
21645 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
21646 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21647 - static pybind11::detail::overload_caster_t<bool> caster;
21648 + static pybind11::detail::override_caster_t<bool> caster;
21649 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21651 else return pybind11::detail::cast_safe<bool>(std::move(o));
21652 @@ -585,7 +585,7 @@
21654 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21655 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21656 - static pybind11::detail::overload_caster_t<bool> caster;
21657 + static pybind11::detail::override_caster_t<bool> caster;
21658 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21660 else return pybind11::detail::cast_safe<bool>(std::move(o));
21661 @@ -598,7 +598,7 @@
21663 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21664 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21665 - static pybind11::detail::overload_caster_t<bool> caster;
21666 + static pybind11::detail::override_caster_t<bool> caster;
21667 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21669 else return pybind11::detail::cast_safe<bool>(std::move(o));
21670 @@ -611,7 +611,7 @@
21672 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21673 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21674 - static pybind11::detail::overload_caster_t<bool> caster;
21675 + static pybind11::detail::override_caster_t<bool> caster;
21676 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21678 else return pybind11::detail::cast_safe<bool>(std::move(o));
21679 @@ -624,7 +624,7 @@
21681 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21682 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21683 - static pybind11::detail::overload_caster_t<bool> caster;
21684 + static pybind11::detail::override_caster_t<bool> caster;
21685 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21687 else return pybind11::detail::cast_safe<bool>(std::move(o));
21688 @@ -637,7 +637,7 @@
21690 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21691 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21692 - static pybind11::detail::overload_caster_t<double> caster;
21693 + static pybind11::detail::override_caster_t<double> caster;
21694 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21696 else return pybind11::detail::cast_safe<double>(std::move(o));
21697 @@ -650,7 +650,7 @@
21699 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21700 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21701 - static pybind11::detail::overload_caster_t<void> caster;
21702 + static pybind11::detail::override_caster_t<void> caster;
21703 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21705 else return pybind11::detail::cast_safe<void>(std::move(o));
21706 @@ -663,7 +663,7 @@
21708 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21709 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21710 - static pybind11::detail::overload_caster_t<void> caster;
21711 + static pybind11::detail::override_caster_t<void> caster;
21712 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21714 else return pybind11::detail::cast_safe<void>(std::move(o));
21715 @@ -676,7 +676,7 @@
21717 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21718 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21719 - static pybind11::detail::overload_caster_t<void> caster;
21720 + static pybind11::detail::override_caster_t<void> caster;
21721 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21723 else return pybind11::detail::cast_safe<void>(std::move(o));
21724 @@ -689,7 +689,7 @@
21726 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21727 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21728 - static pybind11::detail::overload_caster_t<void> caster;
21729 + static pybind11::detail::override_caster_t<void> caster;
21730 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21732 else return pybind11::detail::cast_safe<void>(std::move(o));
21733 diff -Nur pythia8309.orig/plugins/python/src/SigmaProcess.cpp pythia8309/plugins/python/src/SigmaProcess.cpp
21734 --- pythia8309.orig/plugins/python/src/SigmaProcess.cpp 2023-02-16 18:12:45.000000000 +0100
21735 +++ pythia8309/plugins/python/src/SigmaProcess.cpp 2023-03-13 09:53:00.001095384 +0100
21738 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21739 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21740 - static pybind11::detail::overload_caster_t<void> caster;
21741 + static pybind11::detail::override_caster_t<void> caster;
21742 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21744 else return pybind11::detail::cast_safe<void>(std::move(o));
21747 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21748 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21749 - static pybind11::detail::overload_caster_t<bool> caster;
21750 + static pybind11::detail::override_caster_t<bool> caster;
21751 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21753 else return pybind11::detail::cast_safe<bool>(std::move(o));
21756 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
21757 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21758 - static pybind11::detail::overload_caster_t<void> caster;
21759 + static pybind11::detail::override_caster_t<void> caster;
21760 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21762 else return pybind11::detail::cast_safe<void>(std::move(o));
21765 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4, a5, a6, a7);
21766 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21767 - static pybind11::detail::overload_caster_t<void> caster;
21768 + static pybind11::detail::override_caster_t<void> caster;
21769 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21771 else return pybind11::detail::cast_safe<void>(std::move(o));
21772 @@ -101,7 +101,7 @@
21774 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
21775 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21776 - static pybind11::detail::overload_caster_t<void> caster;
21777 + static pybind11::detail::override_caster_t<void> caster;
21778 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21780 else return pybind11::detail::cast_safe<void>(std::move(o));
21781 @@ -114,7 +114,7 @@
21783 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11);
21784 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21785 - static pybind11::detail::overload_caster_t<void> caster;
21786 + static pybind11::detail::override_caster_t<void> caster;
21787 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21789 else return pybind11::detail::cast_safe<void>(std::move(o));
21790 @@ -127,7 +127,7 @@
21792 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21793 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21794 - static pybind11::detail::overload_caster_t<void> caster;
21795 + static pybind11::detail::override_caster_t<void> caster;
21796 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21798 else return pybind11::detail::cast_safe<void>(std::move(o));
21799 @@ -140,7 +140,7 @@
21801 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21802 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21803 - static pybind11::detail::overload_caster_t<double> caster;
21804 + static pybind11::detail::override_caster_t<double> caster;
21805 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21807 else return pybind11::detail::cast_safe<double>(std::move(o));
21808 @@ -153,7 +153,7 @@
21810 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
21811 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21812 - static pybind11::detail::overload_caster_t<double> caster;
21813 + static pybind11::detail::override_caster_t<double> caster;
21814 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21816 else return pybind11::detail::cast_safe<double>(std::move(o));
21817 @@ -166,7 +166,7 @@
21819 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
21820 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21821 - static pybind11::detail::overload_caster_t<double> caster;
21822 + static pybind11::detail::override_caster_t<double> caster;
21823 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21825 else return pybind11::detail::cast_safe<double>(std::move(o));
21826 @@ -179,7 +179,7 @@
21828 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21829 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21830 - static pybind11::detail::overload_caster_t<void> caster;
21831 + static pybind11::detail::override_caster_t<void> caster;
21832 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21834 else return pybind11::detail::cast_safe<void>(std::move(o));
21835 @@ -192,7 +192,7 @@
21837 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4, a5);
21838 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21839 - static pybind11::detail::overload_caster_t<bool> caster;
21840 + static pybind11::detail::override_caster_t<bool> caster;
21841 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21843 else return pybind11::detail::cast_safe<bool>(std::move(o));
21844 @@ -205,7 +205,7 @@
21846 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
21847 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21848 - static pybind11::detail::overload_caster_t<double> caster;
21849 + static pybind11::detail::override_caster_t<double> caster;
21850 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21852 else return pybind11::detail::cast_safe<double>(std::move(o));
21853 @@ -218,7 +218,7 @@
21855 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
21856 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
21857 - static pybind11::detail::overload_caster_t<double> caster;
21858 + static pybind11::detail::override_caster_t<double> caster;
21859 return pybind11::detail::cast_ref<double>(std::move(o), caster);
21861 else return pybind11::detail::cast_safe<double>(std::move(o));
21862 @@ -231,7 +231,7 @@
21864 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21865 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
21866 - static pybind11::detail::overload_caster_t<void> caster;
21867 + static pybind11::detail::override_caster_t<void> caster;
21868 return pybind11::detail::cast_ref<void>(std::move(o), caster);
21870 else return pybind11::detail::cast_safe<void>(std::move(o));
21871 @@ -244,7 +244,7 @@
21873 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21874 if (pybind11::detail::cast_is_temporary_value_reference<class std::basic_string<char>>::value) {
21875 - static pybind11::detail::overload_caster_t<class std::basic_string<char>> caster;
21876 + static pybind11::detail::override_caster_t<class std::basic_string<char>> caster;
21877 return pybind11::detail::cast_ref<class std::basic_string<char>>(std::move(o), caster);
21879 else return pybind11::detail::cast_safe<class std::basic_string<char>>(std::move(o));
21880 @@ -257,7 +257,7 @@
21882 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21883 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
21884 - static pybind11::detail::overload_caster_t<int> caster;
21885 + static pybind11::detail::override_caster_t<int> caster;
21886 return pybind11::detail::cast_ref<int>(std::move(o), caster);
21888 else return pybind11::detail::cast_safe<int>(std::move(o));
21889 @@ -270,7 +270,7 @@
21891 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21892 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
21893 - static pybind11::detail::overload_caster_t<int> caster;
21894 + static pybind11::detail::override_caster_t<int> caster;
21895 return pybind11::detail::cast_ref<int>(std::move(o), caster);
21897 else return pybind11::detail::cast_safe<int>(std::move(o));
21898 @@ -283,7 +283,7 @@
21900 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21901 if (pybind11::detail::cast_is_temporary_value_reference<class std::basic_string<char>>::value) {
21902 - static pybind11::detail::overload_caster_t<class std::basic_string<char>> caster;
21903 + static pybind11::detail::override_caster_t<class std::basic_string<char>> caster;
21904 return pybind11::detail::cast_ref<class std::basic_string<char>>(std::move(o), caster);
21906 else return pybind11::detail::cast_safe<class std::basic_string<char>>(std::move(o));
21907 @@ -296,7 +296,7 @@
21909 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21910 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21911 - static pybind11::detail::overload_caster_t<bool> caster;
21912 + static pybind11::detail::override_caster_t<bool> caster;
21913 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21915 else return pybind11::detail::cast_safe<bool>(std::move(o));
21916 @@ -309,7 +309,7 @@
21918 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21919 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21920 - static pybind11::detail::overload_caster_t<bool> caster;
21921 + static pybind11::detail::override_caster_t<bool> caster;
21922 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21924 else return pybind11::detail::cast_safe<bool>(std::move(o));
21925 @@ -322,7 +322,7 @@
21927 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21928 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21929 - static pybind11::detail::overload_caster_t<bool> caster;
21930 + static pybind11::detail::override_caster_t<bool> caster;
21931 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21933 else return pybind11::detail::cast_safe<bool>(std::move(o));
21934 @@ -335,7 +335,7 @@
21936 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21937 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21938 - static pybind11::detail::overload_caster_t<bool> caster;
21939 + static pybind11::detail::override_caster_t<bool> caster;
21940 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21942 else return pybind11::detail::cast_safe<bool>(std::move(o));
21943 @@ -348,7 +348,7 @@
21945 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21946 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21947 - static pybind11::detail::overload_caster_t<bool> caster;
21948 + static pybind11::detail::override_caster_t<bool> caster;
21949 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21951 else return pybind11::detail::cast_safe<bool>(std::move(o));
21952 @@ -361,7 +361,7 @@
21954 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21955 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21956 - static pybind11::detail::overload_caster_t<bool> caster;
21957 + static pybind11::detail::override_caster_t<bool> caster;
21958 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21960 else return pybind11::detail::cast_safe<bool>(std::move(o));
21961 @@ -374,7 +374,7 @@
21963 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21964 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21965 - static pybind11::detail::overload_caster_t<bool> caster;
21966 + static pybind11::detail::override_caster_t<bool> caster;
21967 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21969 else return pybind11::detail::cast_safe<bool>(std::move(o));
21970 @@ -387,7 +387,7 @@
21972 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21973 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21974 - static pybind11::detail::overload_caster_t<bool> caster;
21975 + static pybind11::detail::override_caster_t<bool> caster;
21976 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21978 else return pybind11::detail::cast_safe<bool>(std::move(o));
21979 @@ -400,7 +400,7 @@
21981 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21982 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21983 - static pybind11::detail::overload_caster_t<bool> caster;
21984 + static pybind11::detail::override_caster_t<bool> caster;
21985 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21987 else return pybind11::detail::cast_safe<bool>(std::move(o));
21988 @@ -413,7 +413,7 @@
21990 auto o = overload.operator()<pybind11::return_value_policy::reference>();
21991 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
21992 - static pybind11::detail::overload_caster_t<bool> caster;
21993 + static pybind11::detail::override_caster_t<bool> caster;
21994 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
21996 else return pybind11::detail::cast_safe<bool>(std::move(o));
21997 @@ -426,7 +426,7 @@
21999 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22000 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22001 - static pybind11::detail::overload_caster_t<int> caster;
22002 + static pybind11::detail::override_caster_t<int> caster;
22003 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22005 else return pybind11::detail::cast_safe<int>(std::move(o));
22006 @@ -439,7 +439,7 @@
22008 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22009 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22010 - static pybind11::detail::overload_caster_t<int> caster;
22011 + static pybind11::detail::override_caster_t<int> caster;
22012 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22014 else return pybind11::detail::cast_safe<int>(std::move(o));
22015 @@ -452,7 +452,7 @@
22017 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22018 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22019 - static pybind11::detail::overload_caster_t<int> caster;
22020 + static pybind11::detail::override_caster_t<int> caster;
22021 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22023 else return pybind11::detail::cast_safe<int>(std::move(o));
22024 @@ -465,7 +465,7 @@
22026 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22027 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22028 - static pybind11::detail::overload_caster_t<int> caster;
22029 + static pybind11::detail::override_caster_t<int> caster;
22030 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22032 else return pybind11::detail::cast_safe<int>(std::move(o));
22033 @@ -478,7 +478,7 @@
22035 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22036 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22037 - static pybind11::detail::overload_caster_t<int> caster;
22038 + static pybind11::detail::override_caster_t<int> caster;
22039 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22041 else return pybind11::detail::cast_safe<int>(std::move(o));
22042 @@ -491,7 +491,7 @@
22044 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22045 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22046 - static pybind11::detail::overload_caster_t<bool> caster;
22047 + static pybind11::detail::override_caster_t<bool> caster;
22048 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22050 else return pybind11::detail::cast_safe<bool>(std::move(o));
22051 @@ -504,7 +504,7 @@
22053 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22054 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22055 - static pybind11::detail::overload_caster_t<int> caster;
22056 + static pybind11::detail::override_caster_t<int> caster;
22057 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22059 else return pybind11::detail::cast_safe<int>(std::move(o));
22060 @@ -517,7 +517,7 @@
22062 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22063 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22064 - static pybind11::detail::overload_caster_t<bool> caster;
22065 + static pybind11::detail::override_caster_t<bool> caster;
22066 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22068 else return pybind11::detail::cast_safe<bool>(std::move(o));
22069 @@ -530,7 +530,7 @@
22071 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22072 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22073 - static pybind11::detail::overload_caster_t<int> caster;
22074 + static pybind11::detail::override_caster_t<int> caster;
22075 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22077 else return pybind11::detail::cast_safe<int>(std::move(o));
22078 @@ -543,7 +543,7 @@
22080 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22081 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22082 - static pybind11::detail::overload_caster_t<int> caster;
22083 + static pybind11::detail::override_caster_t<int> caster;
22084 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22086 else return pybind11::detail::cast_safe<int>(std::move(o));
22087 @@ -556,7 +556,7 @@
22089 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22090 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22091 - static pybind11::detail::overload_caster_t<double> caster;
22092 + static pybind11::detail::override_caster_t<double> caster;
22093 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22095 else return pybind11::detail::cast_safe<double>(std::move(o));
22096 @@ -569,7 +569,7 @@
22098 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22099 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22100 - static pybind11::detail::overload_caster_t<double> caster;
22101 + static pybind11::detail::override_caster_t<double> caster;
22102 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22104 else return pybind11::detail::cast_safe<double>(std::move(o));
22105 @@ -582,7 +582,7 @@
22107 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22108 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22109 - static pybind11::detail::overload_caster_t<bool> caster;
22110 + static pybind11::detail::override_caster_t<bool> caster;
22111 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22113 else return pybind11::detail::cast_safe<bool>(std::move(o));
22114 @@ -595,7 +595,7 @@
22116 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22117 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22118 - static pybind11::detail::overload_caster_t<int> caster;
22119 + static pybind11::detail::override_caster_t<int> caster;
22120 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22122 else return pybind11::detail::cast_safe<int>(std::move(o));
22123 @@ -608,7 +608,7 @@
22125 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
22126 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22127 - static pybind11::detail::overload_caster_t<void> caster;
22128 + static pybind11::detail::override_caster_t<void> caster;
22129 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22131 else return pybind11::detail::cast_safe<void>(std::move(o));
22132 @@ -621,7 +621,7 @@
22134 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22135 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22136 - static pybind11::detail::overload_caster_t<bool> caster;
22137 + static pybind11::detail::override_caster_t<bool> caster;
22138 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22140 else return pybind11::detail::cast_safe<bool>(std::move(o));
22141 @@ -634,7 +634,7 @@
22143 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22144 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22145 - static pybind11::detail::overload_caster_t<void> caster;
22146 + static pybind11::detail::override_caster_t<void> caster;
22147 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22149 else return pybind11::detail::cast_safe<void>(std::move(o));
22150 @@ -647,7 +647,7 @@
22152 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22153 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22154 - static pybind11::detail::overload_caster_t<void> caster;
22155 + static pybind11::detail::override_caster_t<void> caster;
22156 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22158 else return pybind11::detail::cast_safe<void>(std::move(o));
22159 @@ -660,7 +660,7 @@
22161 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
22162 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22163 - static pybind11::detail::overload_caster_t<void> caster;
22164 + static pybind11::detail::override_caster_t<void> caster;
22165 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22167 else return pybind11::detail::cast_safe<void>(std::move(o));
22168 @@ -673,7 +673,7 @@
22170 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22171 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22172 - static pybind11::detail::overload_caster_t<void> caster;
22173 + static pybind11::detail::override_caster_t<void> caster;
22174 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22176 else return pybind11::detail::cast_safe<void>(std::move(o));
22177 diff -Nur pythia8309.orig/plugins/python/src/stdexcept.cpp pythia8309/plugins/python/src/stdexcept.cpp
22178 --- pythia8309.orig/plugins/python/src/stdexcept.cpp 2023-02-16 18:12:45.000000000 +0100
22179 +++ pythia8309/plugins/python/src/stdexcept.cpp 2023-03-13 09:53:00.001095384 +0100
22182 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22183 if (pybind11::detail::cast_is_temporary_value_reference<const char *>::value) {
22184 - static pybind11::detail::overload_caster_t<const char *> caster;
22185 + static pybind11::detail::override_caster_t<const char *> caster;
22186 return pybind11::detail::cast_ref<const char *>(std::move(o), caster);
22188 else return pybind11::detail::cast_safe<const char *>(std::move(o));
22189 diff -Nur pythia8309.orig/plugins/python/src/TimeShower.cpp pythia8309/plugins/python/src/TimeShower.cpp
22190 --- pythia8309.orig/plugins/python/src/TimeShower.cpp 2023-02-16 18:12:45.000000000 +0100
22191 +++ pythia8309/plugins/python/src/TimeShower.cpp 2023-03-13 10:47:16.344533440 +0100
22194 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
22195 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22196 - static pybind11::detail::overload_caster_t<bool> caster;
22197 + static pybind11::detail::override_caster_t<bool> caster;
22198 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22200 else return pybind11::detail::cast_safe<bool>(std::move(o));
22203 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
22204 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22205 - static pybind11::detail::overload_caster_t<int> caster;
22206 + static pybind11::detail::override_caster_t<int> caster;
22207 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22209 else return pybind11::detail::cast_safe<int>(std::move(o));
22210 @@ -101,7 +101,7 @@
22212 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
22213 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22214 - static pybind11::detail::overload_caster_t<int> caster;
22215 + static pybind11::detail::override_caster_t<int> caster;
22216 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22218 else return pybind11::detail::cast_safe<int>(std::move(o));
22219 @@ -114,7 +114,7 @@
22221 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
22222 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22223 - static pybind11::detail::overload_caster_t<int> caster;
22224 + static pybind11::detail::override_caster_t<int> caster;
22225 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22227 else return pybind11::detail::cast_safe<int>(std::move(o));
22228 @@ -127,7 +127,7 @@
22230 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
22231 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22232 - static pybind11::detail::overload_caster_t<void> caster;
22233 + static pybind11::detail::override_caster_t<void> caster;
22234 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22236 else return pybind11::detail::cast_safe<void>(std::move(o));
22237 @@ -140,7 +140,7 @@
22239 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
22240 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22241 - static pybind11::detail::overload_caster_t<void> caster;
22242 + static pybind11::detail::override_caster_t<void> caster;
22243 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22245 else return pybind11::detail::cast_safe<void>(std::move(o));
22246 @@ -153,7 +153,7 @@
22248 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
22249 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22250 - static pybind11::detail::overload_caster_t<void> caster;
22251 + static pybind11::detail::override_caster_t<void> caster;
22252 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22254 else return pybind11::detail::cast_safe<void>(std::move(o));
22255 @@ -166,7 +166,7 @@
22257 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
22258 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22259 - static pybind11::detail::overload_caster_t<void> caster;
22260 + static pybind11::detail::override_caster_t<void> caster;
22261 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22263 else return pybind11::detail::cast_safe<void>(std::move(o));
22264 @@ -179,7 +179,7 @@
22266 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
22267 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22268 - static pybind11::detail::overload_caster_t<void> caster;
22269 + static pybind11::detail::override_caster_t<void> caster;
22270 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22272 else return pybind11::detail::cast_safe<void>(std::move(o));
22273 @@ -192,7 +192,7 @@
22275 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
22276 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22277 - static pybind11::detail::overload_caster_t<double> caster;
22278 + static pybind11::detail::override_caster_t<double> caster;
22279 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22281 else return pybind11::detail::cast_safe<double>(std::move(o));
22282 @@ -205,7 +205,7 @@
22284 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22285 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22286 - static pybind11::detail::overload_caster_t<double> caster;
22287 + static pybind11::detail::override_caster_t<double> caster;
22288 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22290 else return pybind11::detail::cast_safe<double>(std::move(o));
22291 @@ -218,7 +218,7 @@
22293 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
22294 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22295 - static pybind11::detail::overload_caster_t<bool> caster;
22296 + static pybind11::detail::override_caster_t<bool> caster;
22297 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22299 else return pybind11::detail::cast_safe<bool>(std::move(o));
22300 @@ -231,7 +231,7 @@
22302 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
22303 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22304 - static pybind11::detail::overload_caster_t<bool> caster;
22305 + static pybind11::detail::override_caster_t<bool> caster;
22306 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22308 else return pybind11::detail::cast_safe<bool>(std::move(o));
22309 @@ -244,7 +244,7 @@
22311 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22312 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22313 - static pybind11::detail::overload_caster_t<void> caster;
22314 + static pybind11::detail::override_caster_t<void> caster;
22315 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22317 else return pybind11::detail::cast_safe<void>(std::move(o));
22318 @@ -257,7 +257,7 @@
22320 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22321 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22322 - static pybind11::detail::overload_caster_t<bool> caster;
22323 + static pybind11::detail::override_caster_t<bool> caster;
22324 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22326 else return pybind11::detail::cast_safe<bool>(std::move(o));
22327 @@ -270,7 +270,7 @@
22329 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22330 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22331 - static pybind11::detail::overload_caster_t<bool> caster;
22332 + static pybind11::detail::override_caster_t<bool> caster;
22333 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22335 else return pybind11::detail::cast_safe<bool>(std::move(o));
22336 @@ -283,7 +283,7 @@
22338 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22339 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22340 - static pybind11::detail::overload_caster_t<bool> caster;
22341 + static pybind11::detail::override_caster_t<bool> caster;
22342 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22344 else return pybind11::detail::cast_safe<bool>(std::move(o));
22345 @@ -296,7 +296,7 @@
22347 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22348 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22349 - static pybind11::detail::overload_caster_t<int> caster;
22350 + static pybind11::detail::override_caster_t<int> caster;
22351 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22353 else return pybind11::detail::cast_safe<int>(std::move(o));
22354 @@ -309,7 +309,7 @@
22356 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22357 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22358 - static pybind11::detail::overload_caster_t<double> caster;
22359 + static pybind11::detail::override_caster_t<double> caster;
22360 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22362 else return pybind11::detail::cast_safe<double>(std::move(o));
22363 @@ -322,7 +322,7 @@
22365 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22366 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22367 - static pybind11::detail::overload_caster_t<double> caster;
22368 + static pybind11::detail::override_caster_t<double> caster;
22369 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22371 else return pybind11::detail::cast_safe<double>(std::move(o));
22372 @@ -335,7 +335,7 @@
22374 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
22375 if (pybind11::detail::cast_is_temporary_value_reference<class Pythia8::Event>::value) {
22376 - static pybind11::detail::overload_caster_t<class Pythia8::Event> caster;
22377 + static pybind11::detail::override_caster_t<class Pythia8::Event> caster;
22378 return pybind11::detail::cast_ref<class Pythia8::Event>(std::move(o), caster);
22380 else return pybind11::detail::cast_safe<class Pythia8::Event>(std::move(o));
22381 @@ -349,7 +349,7 @@
22383 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
22384 if (pybind11::detail::cast_is_temporary_value_reference<_binder_ret_0>::value) {
22385 - static pybind11::detail::overload_caster_t<_binder_ret_0> caster;
22386 + static pybind11::detail::override_caster_t<_binder_ret_0> caster;
22387 return pybind11::detail::cast_ref<_binder_ret_0>(std::move(o), caster);
22389 else return pybind11::detail::cast_safe<_binder_ret_0>(std::move(o));
22390 @@ -362,7 +362,7 @@
22392 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
22393 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22394 - static pybind11::detail::overload_caster_t<bool> caster;
22395 + static pybind11::detail::override_caster_t<bool> caster;
22396 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22398 else return pybind11::detail::cast_safe<bool>(std::move(o));
22399 @@ -376,7 +376,7 @@
22401 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
22402 if (pybind11::detail::cast_is_temporary_value_reference<_binder_ret_1>::value) {
22403 - static pybind11::detail::overload_caster_t<_binder_ret_1> caster;
22404 + static pybind11::detail::override_caster_t<_binder_ret_1> caster;
22405 return pybind11::detail::cast_ref<_binder_ret_1>(std::move(o), caster);
22407 else return pybind11::detail::cast_safe<_binder_ret_1>(std::move(o));
22408 @@ -389,7 +389,7 @@
22410 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
22411 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22412 - static pybind11::detail::overload_caster_t<double> caster;
22413 + static pybind11::detail::override_caster_t<double> caster;
22414 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22416 else return pybind11::detail::cast_safe<double>(std::move(o));
22417 @@ -402,7 +402,7 @@
22419 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
22420 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22421 - static pybind11::detail::overload_caster_t<bool> caster;
22422 + static pybind11::detail::override_caster_t<bool> caster;
22423 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22425 else return pybind11::detail::cast_safe<bool>(std::move(o));
22426 @@ -416,7 +416,7 @@
22428 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
22429 if (pybind11::detail::cast_is_temporary_value_reference<_binder_ret_2>::value) {
22430 - static pybind11::detail::overload_caster_t<_binder_ret_2> caster;
22431 + static pybind11::detail::override_caster_t<_binder_ret_2> caster;
22432 return pybind11::detail::cast_ref<_binder_ret_2>(std::move(o), caster);
22434 else return pybind11::detail::cast_safe<_binder_ret_2>(std::move(o));
22435 @@ -429,7 +429,7 @@
22437 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
22438 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22439 - static pybind11::detail::overload_caster_t<double> caster;
22440 + static pybind11::detail::override_caster_t<double> caster;
22441 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22443 else return pybind11::detail::cast_safe<double>(std::move(o));
22444 @@ -442,7 +442,7 @@
22446 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4, a5, a6);
22447 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22448 - static pybind11::detail::overload_caster_t<double> caster;
22449 + static pybind11::detail::override_caster_t<double> caster;
22450 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22452 else return pybind11::detail::cast_safe<double>(std::move(o));
22453 @@ -455,7 +455,7 @@
22455 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22456 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22457 - static pybind11::detail::overload_caster_t<void> caster;
22458 + static pybind11::detail::override_caster_t<void> caster;
22459 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22461 else return pybind11::detail::cast_safe<void>(std::move(o));
22462 @@ -468,7 +468,7 @@
22464 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22465 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22466 - static pybind11::detail::overload_caster_t<void> caster;
22467 + static pybind11::detail::override_caster_t<void> caster;
22468 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22470 else return pybind11::detail::cast_safe<void>(std::move(o));
22471 @@ -481,7 +481,7 @@
22473 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
22474 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22475 - static pybind11::detail::overload_caster_t<void> caster;
22476 + static pybind11::detail::override_caster_t<void> caster;
22477 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22479 else return pybind11::detail::cast_safe<void>(std::move(o));
22480 @@ -494,7 +494,7 @@
22482 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22483 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22484 - static pybind11::detail::overload_caster_t<void> caster;
22485 + static pybind11::detail::override_caster_t<void> caster;
22486 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22488 else return pybind11::detail::cast_safe<void>(std::move(o));
22489 @@ -513,7 +513,7 @@
22491 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
22492 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22493 - static pybind11::detail::overload_caster_t<bool> caster;
22494 + static pybind11::detail::override_caster_t<bool> caster;
22495 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22497 else return pybind11::detail::cast_safe<bool>(std::move(o));
22498 @@ -526,7 +526,7 @@
22500 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4, a5);
22501 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22502 - static pybind11::detail::overload_caster_t<bool> caster;
22503 + static pybind11::detail::override_caster_t<bool> caster;
22504 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22506 else return pybind11::detail::cast_safe<bool>(std::move(o));
22507 @@ -545,7 +545,7 @@
22509 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
22510 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22511 - static pybind11::detail::overload_caster_t<bool> caster;
22512 + static pybind11::detail::override_caster_t<bool> caster;
22513 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22515 else return pybind11::detail::cast_safe<bool>(std::move(o));
22516 @@ -558,7 +558,7 @@
22518 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
22519 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22520 - static pybind11::detail::overload_caster_t<void> caster;
22521 + static pybind11::detail::override_caster_t<void> caster;
22522 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22524 else return pybind11::detail::cast_safe<void>(std::move(o));
22525 @@ -571,7 +571,7 @@
22527 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
22528 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22529 - static pybind11::detail::overload_caster_t<void> caster;
22530 + static pybind11::detail::override_caster_t<void> caster;
22531 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22533 else return pybind11::detail::cast_safe<void>(std::move(o));
22534 @@ -584,7 +584,7 @@
22536 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
22537 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22538 - static pybind11::detail::overload_caster_t<double> caster;
22539 + static pybind11::detail::override_caster_t<double> caster;
22540 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22542 else return pybind11::detail::cast_safe<double>(std::move(o));
22543 @@ -597,7 +597,7 @@
22545 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
22546 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22547 - static pybind11::detail::overload_caster_t<bool> caster;
22548 + static pybind11::detail::override_caster_t<bool> caster;
22549 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22551 else return pybind11::detail::cast_safe<bool>(std::move(o));
22552 @@ -610,7 +610,7 @@
22554 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22555 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22556 - static pybind11::detail::overload_caster_t<void> caster;
22557 + static pybind11::detail::override_caster_t<void> caster;
22558 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22560 else return pybind11::detail::cast_safe<void>(std::move(o));
22561 @@ -623,7 +623,7 @@
22563 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22564 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22565 - static pybind11::detail::overload_caster_t<bool> caster;
22566 + static pybind11::detail::override_caster_t<bool> caster;
22567 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22569 else return pybind11::detail::cast_safe<bool>(std::move(o));
22570 @@ -636,7 +636,7 @@
22572 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22573 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22574 - static pybind11::detail::overload_caster_t<bool> caster;
22575 + static pybind11::detail::override_caster_t<bool> caster;
22576 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22578 else return pybind11::detail::cast_safe<bool>(std::move(o));
22579 @@ -649,7 +649,7 @@
22581 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22582 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22583 - static pybind11::detail::overload_caster_t<bool> caster;
22584 + static pybind11::detail::override_caster_t<bool> caster;
22585 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22587 else return pybind11::detail::cast_safe<bool>(std::move(o));
22588 @@ -662,7 +662,7 @@
22590 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22591 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22592 - static pybind11::detail::overload_caster_t<bool> caster;
22593 + static pybind11::detail::override_caster_t<bool> caster;
22594 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22596 else return pybind11::detail::cast_safe<bool>(std::move(o));
22597 @@ -675,7 +675,7 @@
22599 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22600 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22601 - static pybind11::detail::overload_caster_t<bool> caster;
22602 + static pybind11::detail::override_caster_t<bool> caster;
22603 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22605 else return pybind11::detail::cast_safe<bool>(std::move(o));
22606 @@ -688,7 +688,7 @@
22608 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22609 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22610 - static pybind11::detail::overload_caster_t<int> caster;
22611 + static pybind11::detail::override_caster_t<int> caster;
22612 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22614 else return pybind11::detail::cast_safe<int>(std::move(o));
22615 @@ -701,7 +701,7 @@
22617 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22618 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22619 - static pybind11::detail::overload_caster_t<double> caster;
22620 + static pybind11::detail::override_caster_t<double> caster;
22621 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22623 else return pybind11::detail::cast_safe<double>(std::move(o));
22624 @@ -714,7 +714,7 @@
22626 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
22627 if (pybind11::detail::cast_is_temporary_value_reference<class Pythia8::Event>::value) {
22628 - static pybind11::detail::overload_caster_t<class Pythia8::Event> caster;
22629 + static pybind11::detail::override_caster_t<class Pythia8::Event> caster;
22630 return pybind11::detail::cast_ref<class Pythia8::Event>(std::move(o), caster);
22632 else return pybind11::detail::cast_safe<class Pythia8::Event>(std::move(o));
22633 @@ -728,7 +728,7 @@
22635 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
22636 if (pybind11::detail::cast_is_temporary_value_reference<_binder_ret_0>::value) {
22637 - static pybind11::detail::overload_caster_t<_binder_ret_0> caster;
22638 + static pybind11::detail::override_caster_t<_binder_ret_0> caster;
22639 return pybind11::detail::cast_ref<_binder_ret_0>(std::move(o), caster);
22641 else return pybind11::detail::cast_safe<_binder_ret_0>(std::move(o));
22642 @@ -741,7 +741,7 @@
22644 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
22645 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22646 - static pybind11::detail::overload_caster_t<bool> caster;
22647 + static pybind11::detail::override_caster_t<bool> caster;
22648 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22650 else return pybind11::detail::cast_safe<bool>(std::move(o));
22651 @@ -755,7 +755,7 @@
22653 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
22654 if (pybind11::detail::cast_is_temporary_value_reference<_binder_ret_1>::value) {
22655 - static pybind11::detail::overload_caster_t<_binder_ret_1> caster;
22656 + static pybind11::detail::override_caster_t<_binder_ret_1> caster;
22657 return pybind11::detail::cast_ref<_binder_ret_1>(std::move(o), caster);
22659 else return pybind11::detail::cast_safe<_binder_ret_1>(std::move(o));
22660 @@ -768,7 +768,7 @@
22662 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4);
22663 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22664 - static pybind11::detail::overload_caster_t<double> caster;
22665 + static pybind11::detail::override_caster_t<double> caster;
22666 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22668 else return pybind11::detail::cast_safe<double>(std::move(o));
22669 @@ -781,7 +781,7 @@
22671 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
22672 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22673 - static pybind11::detail::overload_caster_t<bool> caster;
22674 + static pybind11::detail::override_caster_t<bool> caster;
22675 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22677 else return pybind11::detail::cast_safe<bool>(std::move(o));
22678 @@ -795,7 +795,7 @@
22680 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
22681 if (pybind11::detail::cast_is_temporary_value_reference<_binder_ret_2>::value) {
22682 - static pybind11::detail::overload_caster_t<_binder_ret_2> caster;
22683 + static pybind11::detail::override_caster_t<_binder_ret_2> caster;
22684 return pybind11::detail::cast_ref<_binder_ret_2>(std::move(o), caster);
22686 else return pybind11::detail::cast_safe<_binder_ret_2>(std::move(o));
22687 @@ -808,7 +808,7 @@
22689 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
22690 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22691 - static pybind11::detail::overload_caster_t<double> caster;
22692 + static pybind11::detail::override_caster_t<double> caster;
22693 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22695 else return pybind11::detail::cast_safe<double>(std::move(o));
22696 @@ -821,7 +821,7 @@
22698 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4, a5, a6);
22699 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22700 - static pybind11::detail::overload_caster_t<double> caster;
22701 + static pybind11::detail::override_caster_t<double> caster;
22702 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22704 else return pybind11::detail::cast_safe<double>(std::move(o));
22705 @@ -834,7 +834,7 @@
22707 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22708 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22709 - static pybind11::detail::overload_caster_t<void> caster;
22710 + static pybind11::detail::override_caster_t<void> caster;
22711 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22713 else return pybind11::detail::cast_safe<void>(std::move(o));
22714 @@ -847,7 +847,7 @@
22716 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22717 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22718 - static pybind11::detail::overload_caster_t<void> caster;
22719 + static pybind11::detail::override_caster_t<void> caster;
22720 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22722 else return pybind11::detail::cast_safe<void>(std::move(o));
22723 @@ -860,7 +860,7 @@
22725 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
22726 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22727 - static pybind11::detail::overload_caster_t<void> caster;
22728 + static pybind11::detail::override_caster_t<void> caster;
22729 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22731 else return pybind11::detail::cast_safe<void>(std::move(o));
22732 @@ -873,7 +873,7 @@
22734 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22735 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
22736 - static pybind11::detail::overload_caster_t<void> caster;
22737 + static pybind11::detail::override_caster_t<void> caster;
22738 return pybind11::detail::cast_ref<void>(std::move(o), caster);
22740 else return pybind11::detail::cast_safe<void>(std::move(o));
22741 diff -Nur pythia8309.orig/plugins/python/src/UserHooks.cpp pythia8309/plugins/python/src/UserHooks.cpp
22742 --- pythia8309.orig/plugins/python/src/UserHooks.cpp 2023-02-16 18:12:45.000000000 +0100
22743 +++ pythia8309/plugins/python/src/UserHooks.cpp 2023-03-13 09:53:00.006095395 +0100
22746 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22747 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22748 - static pybind11::detail::overload_caster_t<bool> caster;
22749 + static pybind11::detail::override_caster_t<bool> caster;
22750 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22752 else return pybind11::detail::cast_safe<bool>(std::move(o));
22755 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22756 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22757 - static pybind11::detail::overload_caster_t<bool> caster;
22758 + static pybind11::detail::override_caster_t<bool> caster;
22759 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22761 else return pybind11::detail::cast_safe<bool>(std::move(o));
22762 @@ -104,7 +104,7 @@
22764 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22765 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22766 - static pybind11::detail::overload_caster_t<bool> caster;
22767 + static pybind11::detail::override_caster_t<bool> caster;
22768 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22770 else return pybind11::detail::cast_safe<bool>(std::move(o));
22771 @@ -117,7 +117,7 @@
22773 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22774 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22775 - static pybind11::detail::overload_caster_t<double> caster;
22776 + static pybind11::detail::override_caster_t<double> caster;
22777 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22779 else return pybind11::detail::cast_safe<double>(std::move(o));
22780 @@ -130,7 +130,7 @@
22782 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22783 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22784 - static pybind11::detail::overload_caster_t<bool> caster;
22785 + static pybind11::detail::override_caster_t<bool> caster;
22786 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22788 else return pybind11::detail::cast_safe<bool>(std::move(o));
22789 @@ -143,7 +143,7 @@
22791 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
22792 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22793 - static pybind11::detail::overload_caster_t<bool> caster;
22794 + static pybind11::detail::override_caster_t<bool> caster;
22795 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22797 else return pybind11::detail::cast_safe<bool>(std::move(o));
22798 @@ -156,7 +156,7 @@
22800 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22801 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22802 - static pybind11::detail::overload_caster_t<bool> caster;
22803 + static pybind11::detail::override_caster_t<bool> caster;
22804 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22806 else return pybind11::detail::cast_safe<bool>(std::move(o));
22807 @@ -169,7 +169,7 @@
22809 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
22810 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22811 - static pybind11::detail::overload_caster_t<bool> caster;
22812 + static pybind11::detail::override_caster_t<bool> caster;
22813 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22815 else return pybind11::detail::cast_safe<bool>(std::move(o));
22816 @@ -182,7 +182,7 @@
22818 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22819 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22820 - static pybind11::detail::overload_caster_t<bool> caster;
22821 + static pybind11::detail::override_caster_t<bool> caster;
22822 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22824 else return pybind11::detail::cast_safe<bool>(std::move(o));
22825 @@ -195,7 +195,7 @@
22827 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22828 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22829 - static pybind11::detail::overload_caster_t<double> caster;
22830 + static pybind11::detail::override_caster_t<double> caster;
22831 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22833 else return pybind11::detail::cast_safe<double>(std::move(o));
22834 @@ -208,7 +208,7 @@
22836 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
22837 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22838 - static pybind11::detail::overload_caster_t<bool> caster;
22839 + static pybind11::detail::override_caster_t<bool> caster;
22840 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22842 else return pybind11::detail::cast_safe<bool>(std::move(o));
22843 @@ -221,7 +221,7 @@
22845 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22846 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22847 - static pybind11::detail::overload_caster_t<bool> caster;
22848 + static pybind11::detail::override_caster_t<bool> caster;
22849 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22851 else return pybind11::detail::cast_safe<bool>(std::move(o));
22852 @@ -234,7 +234,7 @@
22854 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22855 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22856 - static pybind11::detail::overload_caster_t<int> caster;
22857 + static pybind11::detail::override_caster_t<int> caster;
22858 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22860 else return pybind11::detail::cast_safe<int>(std::move(o));
22861 @@ -247,7 +247,7 @@
22863 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
22864 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22865 - static pybind11::detail::overload_caster_t<bool> caster;
22866 + static pybind11::detail::override_caster_t<bool> caster;
22867 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22869 else return pybind11::detail::cast_safe<bool>(std::move(o));
22870 @@ -260,7 +260,7 @@
22872 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22873 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22874 - static pybind11::detail::overload_caster_t<bool> caster;
22875 + static pybind11::detail::override_caster_t<bool> caster;
22876 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22878 else return pybind11::detail::cast_safe<bool>(std::move(o));
22879 @@ -273,7 +273,7 @@
22881 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22882 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
22883 - static pybind11::detail::overload_caster_t<int> caster;
22884 + static pybind11::detail::override_caster_t<int> caster;
22885 return pybind11::detail::cast_ref<int>(std::move(o), caster);
22887 else return pybind11::detail::cast_safe<int>(std::move(o));
22888 @@ -286,7 +286,7 @@
22890 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
22891 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22892 - static pybind11::detail::overload_caster_t<bool> caster;
22893 + static pybind11::detail::override_caster_t<bool> caster;
22894 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22896 else return pybind11::detail::cast_safe<bool>(std::move(o));
22897 @@ -299,7 +299,7 @@
22899 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22900 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22901 - static pybind11::detail::overload_caster_t<bool> caster;
22902 + static pybind11::detail::override_caster_t<bool> caster;
22903 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22905 else return pybind11::detail::cast_safe<bool>(std::move(o));
22906 @@ -312,7 +312,7 @@
22908 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
22909 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22910 - static pybind11::detail::overload_caster_t<bool> caster;
22911 + static pybind11::detail::override_caster_t<bool> caster;
22912 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22914 else return pybind11::detail::cast_safe<bool>(std::move(o));
22915 @@ -325,7 +325,7 @@
22917 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22918 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22919 - static pybind11::detail::overload_caster_t<bool> caster;
22920 + static pybind11::detail::override_caster_t<bool> caster;
22921 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22923 else return pybind11::detail::cast_safe<bool>(std::move(o));
22924 @@ -338,7 +338,7 @@
22926 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22927 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22928 - static pybind11::detail::overload_caster_t<bool> caster;
22929 + static pybind11::detail::override_caster_t<bool> caster;
22930 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22932 else return pybind11::detail::cast_safe<bool>(std::move(o));
22933 @@ -351,7 +351,7 @@
22935 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
22936 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22937 - static pybind11::detail::overload_caster_t<bool> caster;
22938 + static pybind11::detail::override_caster_t<bool> caster;
22939 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22941 else return pybind11::detail::cast_safe<bool>(std::move(o));
22942 @@ -364,7 +364,7 @@
22944 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22945 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22946 - static pybind11::detail::overload_caster_t<bool> caster;
22947 + static pybind11::detail::override_caster_t<bool> caster;
22948 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22950 else return pybind11::detail::cast_safe<bool>(std::move(o));
22951 @@ -377,7 +377,7 @@
22953 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
22954 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
22955 - static pybind11::detail::overload_caster_t<double> caster;
22956 + static pybind11::detail::override_caster_t<double> caster;
22957 return pybind11::detail::cast_ref<double>(std::move(o), caster);
22959 else return pybind11::detail::cast_safe<double>(std::move(o));
22960 @@ -390,7 +390,7 @@
22962 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22963 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22964 - static pybind11::detail::overload_caster_t<bool> caster;
22965 + static pybind11::detail::override_caster_t<bool> caster;
22966 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22968 else return pybind11::detail::cast_safe<bool>(std::move(o));
22969 @@ -403,7 +403,7 @@
22971 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
22972 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22973 - static pybind11::detail::overload_caster_t<bool> caster;
22974 + static pybind11::detail::override_caster_t<bool> caster;
22975 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22977 else return pybind11::detail::cast_safe<bool>(std::move(o));
22978 @@ -416,7 +416,7 @@
22980 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22981 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22982 - static pybind11::detail::overload_caster_t<bool> caster;
22983 + static pybind11::detail::override_caster_t<bool> caster;
22984 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22986 else return pybind11::detail::cast_safe<bool>(std::move(o));
22987 @@ -429,7 +429,7 @@
22989 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
22990 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
22991 - static pybind11::detail::overload_caster_t<bool> caster;
22992 + static pybind11::detail::override_caster_t<bool> caster;
22993 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
22995 else return pybind11::detail::cast_safe<bool>(std::move(o));
22996 @@ -442,7 +442,7 @@
22998 auto o = overload.operator()<pybind11::return_value_policy::reference>();
22999 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23000 - static pybind11::detail::overload_caster_t<bool> caster;
23001 + static pybind11::detail::override_caster_t<bool> caster;
23002 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23004 else return pybind11::detail::cast_safe<bool>(std::move(o));
23005 @@ -455,7 +455,7 @@
23007 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
23008 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23009 - static pybind11::detail::overload_caster_t<bool> caster;
23010 + static pybind11::detail::override_caster_t<bool> caster;
23011 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23013 else return pybind11::detail::cast_safe<bool>(std::move(o));
23014 @@ -468,7 +468,7 @@
23016 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23017 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23018 - static pybind11::detail::overload_caster_t<bool> caster;
23019 + static pybind11::detail::override_caster_t<bool> caster;
23020 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23022 else return pybind11::detail::cast_safe<bool>(std::move(o));
23023 @@ -481,7 +481,7 @@
23025 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
23026 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23027 - static pybind11::detail::overload_caster_t<bool> caster;
23028 + static pybind11::detail::override_caster_t<bool> caster;
23029 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23031 else return pybind11::detail::cast_safe<bool>(std::move(o));
23032 @@ -494,7 +494,7 @@
23034 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23035 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23036 - static pybind11::detail::overload_caster_t<bool> caster;
23037 + static pybind11::detail::override_caster_t<bool> caster;
23038 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23040 else return pybind11::detail::cast_safe<bool>(std::move(o));
23041 @@ -507,7 +507,7 @@
23043 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23044 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23045 - static pybind11::detail::overload_caster_t<bool> caster;
23046 + static pybind11::detail::override_caster_t<bool> caster;
23047 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23049 else return pybind11::detail::cast_safe<bool>(std::move(o));
23050 @@ -520,7 +520,7 @@
23052 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
23053 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23054 - static pybind11::detail::overload_caster_t<bool> caster;
23055 + static pybind11::detail::override_caster_t<bool> caster;
23056 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23058 else return pybind11::detail::cast_safe<bool>(std::move(o));
23059 @@ -533,7 +533,7 @@
23061 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23062 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23063 - static pybind11::detail::overload_caster_t<bool> caster;
23064 + static pybind11::detail::override_caster_t<bool> caster;
23065 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23067 else return pybind11::detail::cast_safe<bool>(std::move(o));
23068 @@ -546,7 +546,7 @@
23070 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23071 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
23072 - static pybind11::detail::overload_caster_t<double> caster;
23073 + static pybind11::detail::override_caster_t<double> caster;
23074 return pybind11::detail::cast_ref<double>(std::move(o), caster);
23076 else return pybind11::detail::cast_safe<double>(std::move(o));
23077 @@ -559,7 +559,7 @@
23079 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23080 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23081 - static pybind11::detail::overload_caster_t<void> caster;
23082 + static pybind11::detail::override_caster_t<void> caster;
23083 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23085 else return pybind11::detail::cast_safe<void>(std::move(o));
23086 @@ -572,7 +572,7 @@
23088 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23089 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23090 - static pybind11::detail::overload_caster_t<void> caster;
23091 + static pybind11::detail::override_caster_t<void> caster;
23092 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23094 else return pybind11::detail::cast_safe<void>(std::move(o));
23095 @@ -585,7 +585,7 @@
23097 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
23098 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23099 - static pybind11::detail::overload_caster_t<void> caster;
23100 + static pybind11::detail::override_caster_t<void> caster;
23101 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23103 else return pybind11::detail::cast_safe<void>(std::move(o));
23104 @@ -598,7 +598,7 @@
23106 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23107 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23108 - static pybind11::detail::overload_caster_t<void> caster;
23109 + static pybind11::detail::override_caster_t<void> caster;
23110 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23112 else return pybind11::detail::cast_safe<void>(std::move(o));
23113 @@ -617,7 +617,7 @@
23115 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23116 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23117 - static pybind11::detail::overload_caster_t<void> caster;
23118 + static pybind11::detail::override_caster_t<void> caster;
23119 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23121 else return pybind11::detail::cast_safe<void>(std::move(o));
23122 @@ -630,7 +630,7 @@
23124 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
23125 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23126 - static pybind11::detail::overload_caster_t<void> caster;
23127 + static pybind11::detail::override_caster_t<void> caster;
23128 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23130 else return pybind11::detail::cast_safe<void>(std::move(o));
23131 @@ -643,7 +643,7 @@
23133 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3);
23134 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23135 - static pybind11::detail::overload_caster_t<void> caster;
23136 + static pybind11::detail::override_caster_t<void> caster;
23137 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23139 else return pybind11::detail::cast_safe<void>(std::move(o));
23140 @@ -656,7 +656,7 @@
23142 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
23143 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23144 - static pybind11::detail::overload_caster_t<void> caster;
23145 + static pybind11::detail::override_caster_t<void> caster;
23146 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23148 else return pybind11::detail::cast_safe<void>(std::move(o));
23149 @@ -669,7 +669,7 @@
23151 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
23152 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23153 - static pybind11::detail::overload_caster_t<void> caster;
23154 + static pybind11::detail::override_caster_t<void> caster;
23155 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23157 else return pybind11::detail::cast_safe<void>(std::move(o));
23158 @@ -682,7 +682,7 @@
23160 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
23161 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23162 - static pybind11::detail::overload_caster_t<void> caster;
23163 + static pybind11::detail::override_caster_t<void> caster;
23164 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23166 else return pybind11::detail::cast_safe<void>(std::move(o));
23167 @@ -695,7 +695,7 @@
23169 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23170 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23171 - static pybind11::detail::overload_caster_t<void> caster;
23172 + static pybind11::detail::override_caster_t<void> caster;
23173 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23175 else return pybind11::detail::cast_safe<void>(std::move(o));
23176 @@ -708,7 +708,7 @@
23178 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23179 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23180 - static pybind11::detail::overload_caster_t<void> caster;
23181 + static pybind11::detail::override_caster_t<void> caster;
23182 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23184 else return pybind11::detail::cast_safe<void>(std::move(o));
23185 @@ -721,7 +721,7 @@
23187 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
23188 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23189 - static pybind11::detail::overload_caster_t<void> caster;
23190 + static pybind11::detail::override_caster_t<void> caster;
23191 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23193 else return pybind11::detail::cast_safe<void>(std::move(o));
23194 @@ -734,7 +734,7 @@
23196 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23197 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23198 - static pybind11::detail::overload_caster_t<void> caster;
23199 + static pybind11::detail::override_caster_t<void> caster;
23200 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23202 else return pybind11::detail::cast_safe<void>(std::move(o));
23203 @@ -753,7 +753,7 @@
23205 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
23206 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
23207 - static pybind11::detail::overload_caster_t<double> caster;
23208 + static pybind11::detail::override_caster_t<double> caster;
23209 return pybind11::detail::cast_ref<double>(std::move(o), caster);
23211 else return pybind11::detail::cast_safe<double>(std::move(o));
23212 @@ -766,7 +766,7 @@
23214 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
23215 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
23216 - static pybind11::detail::overload_caster_t<double> caster;
23217 + static pybind11::detail::override_caster_t<double> caster;
23218 return pybind11::detail::cast_ref<double>(std::move(o), caster);
23220 else return pybind11::detail::cast_safe<double>(std::move(o));
23221 @@ -779,7 +779,7 @@
23223 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23224 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23225 - static pybind11::detail::overload_caster_t<bool> caster;
23226 + static pybind11::detail::override_caster_t<bool> caster;
23227 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23229 else return pybind11::detail::cast_safe<bool>(std::move(o));
23230 @@ -792,7 +792,7 @@
23232 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
23233 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23234 - static pybind11::detail::overload_caster_t<bool> caster;
23235 + static pybind11::detail::override_caster_t<bool> caster;
23236 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23238 else return pybind11::detail::cast_safe<bool>(std::move(o));
23239 @@ -805,7 +805,7 @@
23241 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23242 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23243 - static pybind11::detail::overload_caster_t<bool> caster;
23244 + static pybind11::detail::override_caster_t<bool> caster;
23245 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23247 else return pybind11::detail::cast_safe<bool>(std::move(o));
23248 @@ -818,7 +818,7 @@
23250 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
23251 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23252 - static pybind11::detail::overload_caster_t<bool> caster;
23253 + static pybind11::detail::override_caster_t<bool> caster;
23254 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23256 else return pybind11::detail::cast_safe<bool>(std::move(o));
23257 @@ -831,7 +831,7 @@
23259 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
23260 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
23261 - static pybind11::detail::overload_caster_t<double> caster;
23262 + static pybind11::detail::override_caster_t<double> caster;
23263 return pybind11::detail::cast_ref<double>(std::move(o), caster);
23265 else return pybind11::detail::cast_safe<double>(std::move(o));
23266 @@ -844,7 +844,7 @@
23268 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23269 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23270 - static pybind11::detail::overload_caster_t<void> caster;
23271 + static pybind11::detail::override_caster_t<void> caster;
23272 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23274 else return pybind11::detail::cast_safe<void>(std::move(o));
23275 @@ -857,7 +857,7 @@
23277 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1);
23278 if (pybind11::detail::cast_is_temporary_value_reference<int>::value) {
23279 - static pybind11::detail::overload_caster_t<int> caster;
23280 + static pybind11::detail::override_caster_t<int> caster;
23281 return pybind11::detail::cast_ref<int>(std::move(o), caster);
23283 else return pybind11::detail::cast_safe<int>(std::move(o));
23284 @@ -870,7 +870,7 @@
23286 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
23287 if (pybind11::detail::cast_is_temporary_value_reference<double>::value) {
23288 - static pybind11::detail::overload_caster_t<double> caster;
23289 + static pybind11::detail::override_caster_t<double> caster;
23290 return pybind11::detail::cast_ref<double>(std::move(o), caster);
23292 else return pybind11::detail::cast_safe<double>(std::move(o));
23293 @@ -883,7 +883,7 @@
23295 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23296 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23297 - static pybind11::detail::overload_caster_t<bool> caster;
23298 + static pybind11::detail::override_caster_t<bool> caster;
23299 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23301 else return pybind11::detail::cast_safe<bool>(std::move(o));
23302 @@ -896,7 +896,7 @@
23304 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
23305 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23306 - static pybind11::detail::overload_caster_t<bool> caster;
23307 + static pybind11::detail::override_caster_t<bool> caster;
23308 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23310 else return pybind11::detail::cast_safe<bool>(std::move(o));
23311 @@ -909,7 +909,7 @@
23313 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23314 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23315 - static pybind11::detail::overload_caster_t<bool> caster;
23316 + static pybind11::detail::override_caster_t<bool> caster;
23317 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23319 else return pybind11::detail::cast_safe<bool>(std::move(o));
23320 @@ -922,7 +922,7 @@
23322 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23323 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23324 - static pybind11::detail::overload_caster_t<bool> caster;
23325 + static pybind11::detail::override_caster_t<bool> caster;
23326 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23328 else return pybind11::detail::cast_safe<bool>(std::move(o));
23329 @@ -935,7 +935,7 @@
23331 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23332 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23333 - static pybind11::detail::overload_caster_t<bool> caster;
23334 + static pybind11::detail::override_caster_t<bool> caster;
23335 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23337 else return pybind11::detail::cast_safe<bool>(std::move(o));
23338 @@ -948,7 +948,7 @@
23340 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2);
23341 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23342 - static pybind11::detail::overload_caster_t<bool> caster;
23343 + static pybind11::detail::override_caster_t<bool> caster;
23344 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23346 else return pybind11::detail::cast_safe<bool>(std::move(o));
23347 @@ -961,7 +961,7 @@
23349 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
23350 if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) {
23351 - static pybind11::detail::overload_caster_t<bool> caster;
23352 + static pybind11::detail::override_caster_t<bool> caster;
23353 return pybind11::detail::cast_ref<bool>(std::move(o), caster);
23355 else return pybind11::detail::cast_safe<bool>(std::move(o));
23356 @@ -974,7 +974,7 @@
23358 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23359 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23360 - static pybind11::detail::overload_caster_t<void> caster;
23361 + static pybind11::detail::override_caster_t<void> caster;
23362 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23364 else return pybind11::detail::cast_safe<void>(std::move(o));
23365 @@ -987,7 +987,7 @@
23367 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23368 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23369 - static pybind11::detail::overload_caster_t<void> caster;
23370 + static pybind11::detail::override_caster_t<void> caster;
23371 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23373 else return pybind11::detail::cast_safe<void>(std::move(o));
23374 @@ -1000,7 +1000,7 @@
23376 auto o = overload.operator()<pybind11::return_value_policy::reference>(a0);
23377 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23378 - static pybind11::detail::overload_caster_t<void> caster;
23379 + static pybind11::detail::override_caster_t<void> caster;
23380 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23382 else return pybind11::detail::cast_safe<void>(std::move(o));
23383 @@ -1013,7 +1013,7 @@
23385 auto o = overload.operator()<pybind11::return_value_policy::reference>();
23386 if (pybind11::detail::cast_is_temporary_value_reference<void>::value) {
23387 - static pybind11::detail::overload_caster_t<void> caster;
23388 + static pybind11::detail::override_caster_t<void> caster;
23389 return pybind11::detail::cast_ref<void>(std::move(o), caster);
23391 else return pybind11::detail::cast_safe<void>(std::move(o));