File indexing completed on 2026-05-03 08:27:21
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011 #pragma once
0012 #include "detail/class.h"
0013 #include "detail/dynamic_raw_ptr_cast_if_possible.h"
0014 #include "detail/exception_translation.h"
0015 #include "detail/function_record_pyobject.h"
0016 #include "detail/init.h"
0017 #include "detail/native_enum_data.h"
0018 #include "detail/using_smart_holder.h"
0019 #include "attr.h"
0020 #include "gil.h"
0021 #include "gil_safe_call_once.h"
0022 #include "options.h"
0023 #include "trampoline_self_life_support.h"
0024 #include "typing.h"
0025
0026 #include <cassert>
0027 #include <cstdlib>
0028 #include <cstring>
0029 #include <memory>
0030 #include <new>
0031 #include <stack>
0032 #include <string>
0033 #include <utility>
0034 #include <vector>
0035
0036
0037
0038 #if defined(__clang_major__) && __clang_major__ < 14
0039 PYBIND11_WARNING_DISABLE_CLANG("-Wgnu-zero-variadic-macro-arguments")
0040 #endif
0041
0042 #if defined(__GNUG__) && !defined(__clang__)
0043 # include <cxxabi.h>
0044 #endif
0045
0046 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0047
0048
0049
0050
0051
0052
0053
0054
0055 #if defined(__GNUC__) && __GNUC__ == 7
0056 PYBIND11_WARNING_DISABLE_GCC("-Wnoexcept-type")
0057 #endif
0058
0059 PYBIND11_WARNING_DISABLE_MSVC(4127)
0060
0061 PYBIND11_NAMESPACE_BEGIN(detail)
0062
0063 inline std::string replace_newlines_and_squash(const char *text) {
0064 const char *whitespaces = " \t\n\r\f\v";
0065 std::string result(text);
0066 bool previous_is_whitespace = false;
0067
0068 if (result.size() >= 2) {
0069
0070 char first_char = result[0];
0071 char last_char = result[result.size() - 1];
0072 if (first_char == last_char && first_char == '\'') {
0073 return result;
0074 }
0075 }
0076 result.clear();
0077
0078
0079 while (*text != '\0') {
0080 if (std::strchr(whitespaces, *text)) {
0081 if (!previous_is_whitespace) {
0082 result += ' ';
0083 previous_is_whitespace = true;
0084 }
0085 } else {
0086 result += *text;
0087 previous_is_whitespace = false;
0088 }
0089 ++text;
0090 }
0091
0092
0093 const size_t str_begin = result.find_first_not_of(whitespaces);
0094 if (str_begin == std::string::npos) {
0095 return "";
0096 }
0097
0098 const size_t str_end = result.find_last_not_of(whitespaces);
0099 const size_t str_range = str_end - str_begin + 1;
0100
0101 return result.substr(str_begin, str_range);
0102 }
0103
0104
0105 inline std::string generate_function_signature(const char *type_caster_name_field,
0106 detail::function_record *func_rec,
0107 const std::type_info *const *types,
0108 size_t &type_index,
0109 size_t &arg_index) {
0110 std::string signature;
0111 bool is_starred = false;
0112
0113
0114
0115 std::stack<bool> is_return_value({false});
0116
0117
0118 std::string special_chars("!@%{}-");
0119 for (const auto *pc = type_caster_name_field; *pc != '\0'; ++pc) {
0120 const auto c = *pc;
0121 if (c == '{') {
0122
0123 is_starred = *(pc + 1) == '*';
0124 if (is_starred) {
0125 continue;
0126 }
0127
0128
0129 if (!func_rec->has_args && arg_index == func_rec->nargs_pos) {
0130 signature += "*, ";
0131 }
0132 if (arg_index < func_rec->args.size() && func_rec->args[arg_index].name) {
0133 signature += func_rec->args[arg_index].name;
0134 } else if (arg_index == 0 && func_rec->is_method) {
0135 signature += "self";
0136 } else {
0137 signature += "arg" + std::to_string(arg_index - (func_rec->is_method ? 1 : 0));
0138 }
0139 signature += ": ";
0140 } else if (c == '}') {
0141
0142 if (!is_starred && arg_index < func_rec->args.size()
0143 && func_rec->args[arg_index].descr) {
0144 signature += " = ";
0145 signature += detail::replace_newlines_and_squash(func_rec->args[arg_index].descr);
0146 }
0147
0148
0149 if (func_rec->nargs_pos_only > 0 && (arg_index + 1) == func_rec->nargs_pos_only) {
0150 signature += ", /";
0151 }
0152 if (!is_starred) {
0153 arg_index++;
0154 }
0155 } else if (c == '%') {
0156 const std::type_info *t = types[type_index++];
0157 if (!t) {
0158 pybind11_fail("Internal error while parsing type signature (1)");
0159 }
0160 if (auto *tinfo = detail::get_type_info(*t)) {
0161 handle th((PyObject *) tinfo->type);
0162 signature += th.attr("__module__").cast<std::string>() + "."
0163 + th.attr("__qualname__").cast<std::string>();
0164 } else if (auto th = detail::global_internals_native_enum_type_map_get_item(*t)) {
0165 signature += th.attr("__module__").cast<std::string>() + "."
0166 + th.attr("__qualname__").cast<std::string>();
0167 } else if (func_rec->is_new_style_constructor && arg_index == 0) {
0168
0169
0170 signature += func_rec->scope.attr("__module__").cast<std::string>() + "."
0171 + func_rec->scope.attr("__qualname__").cast<std::string>();
0172 } else {
0173 signature += detail::quote_cpp_type_name(detail::clean_type_id(t->name()));
0174 }
0175 } else if (c == '!' && special_chars.find(*(pc + 1)) != std::string::npos) {
0176
0177 signature += *++pc;
0178 } else if (c == '@') {
0179
0180
0181 if (*(pc + 1) == '^') {
0182 is_return_value.emplace(false);
0183 ++pc;
0184 continue;
0185 }
0186 if (*(pc + 1) == '$') {
0187 is_return_value.emplace(true);
0188 ++pc;
0189 continue;
0190 }
0191 if (*(pc + 1) == '!') {
0192 is_return_value.pop();
0193 ++pc;
0194 continue;
0195 }
0196
0197
0198
0199 ++pc;
0200 if (!is_return_value.top()
0201 && (!(arg_index < func_rec->args.size() && !func_rec->args[arg_index].convert))) {
0202 while (*pc != '\0' && *pc != '@') {
0203 signature += *pc++;
0204 }
0205 if (*pc == '@') {
0206 ++pc;
0207 }
0208 while (*pc != '\0' && *pc != '@') {
0209 ++pc;
0210 }
0211 } else {
0212 while (*pc != '\0' && *pc != '@') {
0213 ++pc;
0214 }
0215 if (*pc == '@') {
0216 ++pc;
0217 }
0218 while (*pc != '\0' && *pc != '@') {
0219 signature += *pc++;
0220 }
0221 }
0222 } else {
0223 if (c == '-' && *(pc + 1) == '>') {
0224 is_return_value.emplace(true);
0225 }
0226 signature += c;
0227 }
0228 }
0229 return signature;
0230 }
0231
0232 template <typename T>
0233 inline std::string generate_type_signature() {
0234 static constexpr auto caster_name_field = make_caster<T>::name;
0235 PYBIND11_DESCR_CONSTEXPR auto descr_types = decltype(caster_name_field)::types();
0236
0237
0238 auto func_rec = function_record();
0239 size_t type_index = 0;
0240 size_t arg_index = 0;
0241 return generate_function_signature(
0242 caster_name_field.text, &func_rec, descr_types.data(), type_index, arg_index);
0243 }
0244
0245 #if defined(_MSC_VER)
0246 # define PYBIND11_COMPAT_STRDUP _strdup
0247 #else
0248 # define PYBIND11_COMPAT_STRDUP strdup
0249 #endif
0250
0251 PYBIND11_NAMESPACE_END(detail)
0252
0253
0254 class cpp_function : public function {
0255 public:
0256 cpp_function() = default;
0257
0258 cpp_function(std::nullptr_t) {}
0259 cpp_function(std::nullptr_t, const is_setter &) {}
0260
0261
0262 template <typename Return, typename... Args, typename... Extra>
0263
0264 cpp_function(Return (*f)(Args...), const Extra &...extra) {
0265 initialize(f, f, extra...);
0266 }
0267
0268
0269 template <typename Func,
0270 typename... Extra,
0271 typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
0272
0273 cpp_function(Func &&f, const Extra &...extra) {
0274 initialize(
0275 std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...);
0276 }
0277
0278
0279 template <typename Return, typename Class, typename... Arg, typename... Extra>
0280
0281 cpp_function(Return (Class::*f)(Arg...), const Extra &...extra) {
0282 initialize(
0283 [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0284 (Return (*)(Class *, Arg...)) nullptr,
0285 extra...);
0286 }
0287
0288
0289
0290
0291 template <typename Return, typename Class, typename... Arg, typename... Extra>
0292
0293 cpp_function(Return (Class::*f)(Arg...) &, const Extra &...extra) {
0294 initialize(
0295 [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0296 (Return (*)(Class *, Arg...)) nullptr,
0297 extra...);
0298 }
0299
0300
0301 template <typename Return, typename Class, typename... Arg, typename... Extra>
0302
0303 cpp_function(Return (Class::*f)(Arg...) const, const Extra &...extra) {
0304 initialize([f](const Class *c,
0305 Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0306 (Return (*)(const Class *, Arg...)) nullptr,
0307 extra...);
0308 }
0309
0310
0311
0312
0313 template <typename Return, typename Class, typename... Arg, typename... Extra>
0314
0315 cpp_function(Return (Class::*f)(Arg...) const &, const Extra &...extra) {
0316 initialize([f](const Class *c,
0317 Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
0318 (Return (*)(const Class *, Arg...)) nullptr,
0319 extra...);
0320 }
0321
0322
0323 object name() const { return attr("__name__"); }
0324
0325 protected:
0326 struct InitializingFunctionRecordDeleter {
0327
0328
0329 void operator()(detail::function_record *rec) { destruct(rec, false); }
0330 };
0331 using unique_function_record
0332 = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
0333
0334
0335 PYBIND11_NOINLINE unique_function_record make_function_record() {
0336 return unique_function_record(new detail::function_record());
0337 }
0338
0339
0340 template <typename Func, typename Return, typename... Args, typename... Extra>
0341 void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) {
0342 using namespace detail;
0343 struct capture {
0344 remove_reference_t<Func> f;
0345
0346 static capture *from_data(void **data) {
0347 return PYBIND11_STD_LAUNDER(reinterpret_cast<capture *>(data));
0348 }
0349 };
0350
0351
0352
0353
0354 auto unique_rec = make_function_record();
0355 auto *rec = unique_rec.get();
0356
0357
0358 if (sizeof(capture) <= sizeof(rec->data)) {
0359
0360
0361
0362 PYBIND11_WARNING_PUSH
0363
0364 #if defined(__GNUG__) && __GNUC__ >= 6
0365 PYBIND11_WARNING_DISABLE_GCC("-Wplacement-new")
0366 #endif
0367
0368 new (capture::from_data(rec->data)) capture{std::forward<Func>(f)};
0369
0370 #if !PYBIND11_HAS_STD_LAUNDER
0371 PYBIND11_WARNING_DISABLE_GCC("-Wstrict-aliasing")
0372 #endif
0373
0374
0375
0376 if (!std::is_trivially_destructible<capture>::value) {
0377 rec->free_data = [](function_record *r) {
0378 auto data = capture::from_data(r->data);
0379 (void) data;
0380 data->~capture();
0381 };
0382 }
0383 PYBIND11_WARNING_POP
0384 } else {
0385 rec->data[0] = new capture{std::forward<Func>(f)};
0386 rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
0387 }
0388
0389
0390 using cast_in = argument_loader<Args...>;
0391 using cast_out
0392 = make_caster<conditional_t<std::is_void<Return>::value, void_type, Return>>;
0393
0394 static_assert(
0395 expected_num_args<Extra...>(
0396 sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
0397 "The number of argument annotations does not match the number of function arguments");
0398
0399
0400 rec->impl = [](function_call &call) -> handle {
0401 cast_in args_converter;
0402
0403
0404 if (!args_converter.load_args(call)) {
0405 return PYBIND11_TRY_NEXT_OVERLOAD;
0406 }
0407
0408
0409 process_attributes<Extra...>::precall(call);
0410
0411
0412 const auto *data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data
0413 : call.func.data[0]);
0414 auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
0415
0416
0417 return_value_policy policy
0418 = return_value_policy_override<Return>::policy(call.func.policy);
0419
0420
0421 using Guard = extract_guard_t<Extra...>;
0422
0423
0424 handle result;
0425 if (call.func.is_setter) {
0426 (void) std::move(args_converter).template call<Return, Guard>(cap->f);
0427 result = none().release();
0428 } else {
0429 result = cast_out::cast(
0430 std::move(args_converter).template call<Return, Guard>(cap->f),
0431 policy,
0432 call.parent);
0433 }
0434
0435
0436 process_attributes<Extra...>::postcall(call, result);
0437
0438 return result;
0439 };
0440
0441 rec->nargs_pos = cast_in::args_pos >= 0
0442 ? static_cast<std::uint16_t>(cast_in::args_pos)
0443 : sizeof...(Args) - cast_in::has_kwargs;
0444
0445 rec->has_args = cast_in::args_pos >= 0;
0446 rec->has_kwargs = cast_in::has_kwargs;
0447
0448
0449 process_attributes<Extra...>::init(extra..., rec);
0450
0451 {
0452 constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
0453 has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
0454 has_arg_annotations = any_of<is_keyword<Extra>...>::value;
0455 constexpr bool has_is_method = any_of<std::is_same<is_method, Extra>...>::value;
0456
0457 constexpr bool has_args = cast_in::args_pos >= 0;
0458 constexpr bool is_method_with_self_arg_only = has_is_method && !has_args;
0459 static_assert(has_arg_annotations || !has_kw_only_args,
0460 "py::kw_only requires the use of argument annotations");
0461 static_assert(((
0462 has_arg_annotations)
0463 || (
0464
0465
0466
0467 is_method_with_self_arg_only))
0468 || !has_pos_only_args,
0469 "py::pos_only requires the use of argument annotations (for docstrings "
0470 "and aligning the annotations to the argument)");
0471
0472 static_assert(constexpr_sum(is_kw_only<Extra>::value...) <= 1,
0473 "py::kw_only may be specified only once");
0474 static_assert(constexpr_sum(is_pos_only<Extra>::value...) <= 1,
0475 "py::pos_only may be specified only once");
0476 constexpr auto kw_only_pos = constexpr_first<is_kw_only, Extra...>();
0477 constexpr auto pos_only_pos = constexpr_first<is_pos_only, Extra...>();
0478 static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
0479 "py::pos_only must come before py::kw_only");
0480 }
0481
0482
0483
0484 static constexpr auto signature
0485 = const_name("(") + cast_in::arg_names + const_name(") -> ") + cast_out::name;
0486 PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
0487
0488
0489
0490 initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));
0491
0492
0493 using FunctionType = Return (*)(Args...);
0494 constexpr bool is_function_ptr
0495 = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *);
0496 PYBIND11_ENSURE_PRECONDITION_FOR_FUNCTIONAL_H_PERFORMANCE_OPTIMIZATIONS(
0497 !is_function_ptr || std::is_standard_layout<capture>::value);
0498 if (is_function_ptr) {
0499 rec->is_stateless = true;
0500 rec->data[1]
0501 = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
0502 }
0503 }
0504
0505
0506
0507
0508 class strdup_guard {
0509 public:
0510 strdup_guard() = default;
0511 strdup_guard(const strdup_guard &) = delete;
0512 strdup_guard &operator=(const strdup_guard &) = delete;
0513
0514 ~strdup_guard() {
0515 for (auto *s : strings) {
0516 std::free(s);
0517 }
0518 }
0519 char *operator()(const char *s) {
0520 auto *t = PYBIND11_COMPAT_STRDUP(s);
0521 strings.push_back(t);
0522 return t;
0523 }
0524 void release() { strings.clear(); }
0525
0526 private:
0527 std::vector<char *> strings;
0528 };
0529
0530
0531 void initialize_generic(unique_function_record &&unique_rec,
0532 const char *text,
0533 const std::type_info *const *types,
0534 size_t args) {
0535
0536
0537
0538
0539 auto *rec = unique_rec.get();
0540
0541
0542
0543
0544
0545
0546
0547 strdup_guard guarded_strdup;
0548
0549
0550 rec->name = guarded_strdup(rec->name ? rec->name : "");
0551 if (rec->doc) {
0552 rec->doc = guarded_strdup(rec->doc);
0553 }
0554 for (auto &a : rec->args) {
0555 if (a.name) {
0556 a.name = guarded_strdup(a.name);
0557 }
0558 if (a.descr) {
0559 a.descr = guarded_strdup(a.descr);
0560 } else if (a.value) {
0561 a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());
0562 }
0563 }
0564
0565 rec->is_constructor = (std::strcmp(rec->name, "__init__") == 0)
0566 || (std::strcmp(rec->name, "__setstate__") == 0);
0567
0568 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
0569 if (rec->is_constructor && !rec->is_new_style_constructor) {
0570 const auto class_name
0571 = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
0572 const auto func_name = std::string(rec->name);
0573 PyErr_WarnEx(PyExc_FutureWarning,
0574 ("pybind11-bound class '" + class_name
0575 + "' is using an old-style "
0576 "placement-new '"
0577 + func_name
0578 + "' which has been deprecated. See "
0579 "the upgrade guide in pybind11's docs. This message is only visible "
0580 "when compiled in debug mode.")
0581 .c_str(),
0582 0);
0583 }
0584 #endif
0585
0586 size_t type_index = 0, arg_index = 0;
0587 std::string signature
0588 = detail::generate_function_signature(text, rec, types, type_index, arg_index);
0589
0590 if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] != nullptr) {
0591 pybind11_fail("Internal error while parsing type signature (2)");
0592 }
0593
0594 rec->signature = guarded_strdup(signature.c_str());
0595 rec->args.shrink_to_fit();
0596 rec->nargs = (std::uint16_t) args;
0597
0598 if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) {
0599 rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
0600 }
0601
0602 detail::function_record *chain = nullptr, *chain_start = rec;
0603 if (rec->sibling) {
0604 if (PyCFunction_Check(rec->sibling.ptr())) {
0605 auto *self = PyCFunction_GET_SELF(rec->sibling.ptr());
0606 if (self == nullptr) {
0607 pybind11_fail(
0608 "initialize_generic: Unexpected nullptr from PyCFunction_GET_SELF");
0609 }
0610 chain = detail::function_record_ptr_from_PyObject(self);
0611 if (chain && !chain->scope.is(rec->scope)) {
0612
0613
0614 chain = nullptr;
0615 }
0616 }
0617
0618
0619 else if (!rec->sibling.is_none() && rec->name[0] != '_') {
0620 pybind11_fail("Cannot overload existing non-function object \""
0621 + std::string(rec->name) + "\" with a function of the same name");
0622 }
0623 }
0624
0625 if (!chain) {
0626
0627 rec->def = new PyMethodDef();
0628 std::memset(rec->def, 0, sizeof(PyMethodDef));
0629 rec->def->ml_name = rec->name;
0630 rec->def->ml_meth
0631 = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher));
0632 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
0633
0634 object py_func_rec = detail::function_record_PyObject_New();
0635 ((detail::function_record_PyObject *) py_func_rec.ptr())->cpp_func_rec
0636 = unique_rec.release();
0637 guarded_strdup.release();
0638
0639 object scope_module = detail::get_scope_module(rec->scope);
0640 m_ptr = PyCFunction_NewEx(rec->def, py_func_rec.ptr(), scope_module.ptr());
0641 if (!m_ptr) {
0642 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
0643 }
0644 } else {
0645
0646 m_ptr = rec->sibling.ptr();
0647 inc_ref();
0648 if (chain->is_method != rec->is_method) {
0649 pybind11_fail(
0650 "overloading a method with both static and instance methods is not supported; "
0651 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
0652 "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more "
0653 "details"
0654 #else
0655 "error while attempting to bind "
0656 + std::string(rec->is_method ? "instance" : "static") + " method "
0657 + std::string(pybind11::str(rec->scope.attr("__name__"))) + "."
0658 + std::string(rec->name) + signature
0659 #endif
0660 );
0661 }
0662
0663 if (rec->prepend) {
0664
0665
0666
0667 chain_start = rec;
0668 rec->next = chain;
0669 auto *py_func_rec
0670 = (detail::function_record_PyObject *) PyCFunction_GET_SELF(m_ptr);
0671 py_func_rec->cpp_func_rec = unique_rec.release();
0672 guarded_strdup.release();
0673 } else {
0674
0675 chain_start = chain;
0676 while (chain->next) {
0677 chain = chain->next;
0678 }
0679 chain->next = unique_rec.release();
0680 guarded_strdup.release();
0681 }
0682 }
0683
0684 std::string signatures;
0685 int index = 0;
0686
0687
0688 if (chain && options::show_function_signatures()
0689 && std::strcmp(rec->name, "_pybind11_conduit_v1_") != 0) {
0690
0691 signatures += rec->name;
0692 signatures += "(*args, **kwargs)\n";
0693 signatures += "Overloaded function.\n\n";
0694 }
0695
0696 bool first_user_def = true;
0697 for (auto *it = chain_start; it != nullptr; it = it->next) {
0698 if (options::show_function_signatures()
0699 && std::strcmp(rec->name, "_pybind11_conduit_v1_") != 0) {
0700 if (index > 0) {
0701 signatures += '\n';
0702 }
0703 if (chain) {
0704 signatures += std::to_string(++index) + ". ";
0705 }
0706 signatures += rec->name;
0707 signatures += it->signature;
0708 signatures += '\n';
0709 }
0710 if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) {
0711
0712
0713 if (!options::show_function_signatures()) {
0714 if (first_user_def) {
0715 first_user_def = false;
0716 } else {
0717 signatures += '\n';
0718 }
0719 }
0720 if (options::show_function_signatures()) {
0721 signatures += '\n';
0722 }
0723 signatures += it->doc;
0724 if (options::show_function_signatures()) {
0725 signatures += '\n';
0726 }
0727 }
0728 }
0729
0730 auto *func = (PyCFunctionObject *) m_ptr;
0731
0732 auto *doc = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());
0733 std::free(const_cast<char *>(PYBIND11_PYCFUNCTION_GET_DOC(func)));
0734 PYBIND11_PYCFUNCTION_SET_DOC(func, doc);
0735
0736 if (rec->is_method) {
0737 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
0738 if (!m_ptr) {
0739 pybind11_fail(
0740 "cpp_function::cpp_function(): Could not allocate instance method object");
0741 }
0742 Py_DECREF(func);
0743 }
0744 }
0745
0746 friend void detail::function_record_PyTypeObject_methods::tp_dealloc_impl(PyObject *);
0747
0748
0749 static void destruct(detail::function_record *rec, bool free_strings = true) {
0750
0751
0752 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
0753 static bool is_zero = Py_GetVersion()[4] == '0';
0754 #endif
0755
0756 while (rec) {
0757 detail::function_record *next = rec->next;
0758 if (rec->free_data) {
0759 rec->free_data(rec);
0760 }
0761
0762
0763
0764 if (free_strings) {
0765 std::free((char *) rec->name);
0766 std::free((char *) rec->doc);
0767 std::free((char *) rec->signature);
0768 for (auto &arg : rec->args) {
0769 std::free(const_cast<char *>(arg.name));
0770 std::free(const_cast<char *>(arg.descr));
0771 }
0772 }
0773 for (auto &arg : rec->args) {
0774 arg.value.dec_ref();
0775 }
0776 if (rec->def) {
0777 std::free(const_cast<char *>(rec->def->ml_doc));
0778
0779
0780
0781 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
0782 if (!is_zero) {
0783 delete rec->def;
0784 }
0785 #else
0786 delete rec->def;
0787 #endif
0788 }
0789 delete rec;
0790 rec = next;
0791 }
0792 }
0793
0794
0795 static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
0796 using namespace detail;
0797 const function_record *overloads = function_record_ptr_from_PyObject(self);
0798 assert(overloads != nullptr);
0799
0800
0801 const function_record *current_overload = overloads;
0802
0803
0804
0805 const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
0806
0807 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
0808 result = PYBIND11_TRY_NEXT_OVERLOAD;
0809
0810 auto self_value_and_holder = value_and_holder();
0811 if (overloads->is_constructor) {
0812 if (!parent
0813 || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
0814 set_error(PyExc_TypeError,
0815 "__init__(self, ...) called with invalid or missing `self` argument");
0816 return nullptr;
0817 }
0818
0819 auto *const tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
0820 auto *const pi = reinterpret_cast<instance *>(parent.ptr());
0821 self_value_and_holder = pi->get_value_and_holder(tinfo, true);
0822
0823
0824
0825 if (self_value_and_holder.instance_registered()) {
0826 return none().release().ptr();
0827 }
0828 }
0829
0830 try {
0831
0832
0833
0834
0835 std::vector<function_call> second_pass;
0836
0837
0838 const bool overloaded
0839 = current_overload != nullptr && current_overload->next != nullptr;
0840
0841 for (; current_overload != nullptr; current_overload = current_overload->next) {
0842
0843
0844
0845
0846
0847
0848
0849
0850
0851
0852
0853
0854
0855
0856
0857
0858
0859
0860
0861
0862 const function_record &func = *current_overload;
0863 size_t num_args = func.nargs;
0864 if (func.has_args) {
0865 --num_args;
0866 }
0867 if (func.has_kwargs) {
0868 --num_args;
0869 }
0870 size_t pos_args = func.nargs_pos;
0871
0872 if (!func.has_args && n_args_in > pos_args) {
0873 continue;
0874 }
0875
0876 if (n_args_in < pos_args && func.args.size() < pos_args) {
0877 continue;
0878
0879 }
0880
0881 function_call call(func, parent);
0882
0883
0884 size_t args_to_copy = (std::min) (pos_args, n_args_in);
0885 size_t args_copied = 0;
0886
0887
0888 if (func.is_new_style_constructor) {
0889
0890
0891 if (self_value_and_holder) {
0892 self_value_and_holder.type->dealloc(self_value_and_holder);
0893 }
0894
0895 call.init_self = PyTuple_GET_ITEM(args_in, 0);
0896 call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
0897 call.args_convert.push_back(false);
0898 ++args_copied;
0899 }
0900
0901
0902 bool bad_arg = false;
0903 for (; args_copied < args_to_copy; ++args_copied) {
0904 const argument_record *arg_rec
0905 = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
0906 if (kwargs_in && arg_rec && arg_rec->name
0907 && dict_getitemstring(kwargs_in, arg_rec->name)) {
0908 bad_arg = true;
0909 break;
0910 }
0911
0912 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
0913 if (arg_rec && !arg_rec->none && arg.is_none()) {
0914 bad_arg = true;
0915 break;
0916 }
0917 call.args.push_back(arg);
0918 call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
0919 }
0920 if (bad_arg) {
0921 continue;
0922 }
0923
0924
0925
0926 size_t positional_args_copied = args_copied;
0927
0928
0929 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
0930
0931
0932 if (args_copied < func.nargs_pos_only) {
0933 for (; args_copied < func.nargs_pos_only; ++args_copied) {
0934 const auto &arg_rec = func.args[args_copied];
0935 handle value;
0936
0937 if (arg_rec.value) {
0938 value = arg_rec.value;
0939 }
0940 if (value) {
0941 call.args.push_back(value);
0942 call.args_convert.push_back(arg_rec.convert);
0943 } else {
0944 break;
0945 }
0946 }
0947
0948 if (args_copied < func.nargs_pos_only) {
0949 continue;
0950 }
0951 }
0952
0953
0954 if (args_copied < num_args) {
0955 bool copied_kwargs = false;
0956
0957 for (; args_copied < num_args; ++args_copied) {
0958 const auto &arg_rec = func.args[args_copied];
0959
0960 handle value;
0961 if (kwargs_in && arg_rec.name) {
0962 value = dict_getitemstring(kwargs.ptr(), arg_rec.name);
0963 }
0964
0965 if (value) {
0966
0967 if (!copied_kwargs) {
0968 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
0969 copied_kwargs = true;
0970 }
0971 if (PyDict_DelItemString(kwargs.ptr(), arg_rec.name) == -1) {
0972 throw error_already_set();
0973 }
0974 } else if (arg_rec.value) {
0975 value = arg_rec.value;
0976 }
0977
0978 if (!arg_rec.none && value.is_none()) {
0979 break;
0980 }
0981
0982 if (value) {
0983
0984
0985 if (func.has_args && call.args.size() == func.nargs_pos) {
0986 call.args.push_back(none());
0987 }
0988
0989 call.args.push_back(value);
0990 call.args_convert.push_back(arg_rec.convert);
0991 } else {
0992 break;
0993 }
0994 }
0995
0996 if (args_copied < num_args) {
0997 continue;
0998
0999 }
1000 }
1001
1002
1003 if (kwargs && !kwargs.empty() && !func.has_kwargs) {
1004 continue;
1005 }
1006
1007
1008 if (func.has_args) {
1009 tuple extra_args;
1010 if (args_to_copy == 0) {
1011
1012
1013 extra_args = reinterpret_borrow<tuple>(args_in);
1014 } else if (positional_args_copied >= n_args_in) {
1015 extra_args = tuple(0);
1016 } else {
1017 size_t args_size = n_args_in - positional_args_copied;
1018 extra_args = tuple(args_size);
1019 for (size_t i = 0; i < args_size; ++i) {
1020 extra_args[i] = PyTuple_GET_ITEM(args_in, positional_args_copied + i);
1021 }
1022 }
1023 if (call.args.size() <= func.nargs_pos) {
1024 call.args.push_back(extra_args);
1025 } else {
1026 call.args[func.nargs_pos] = extra_args;
1027 }
1028 call.args_convert.push_back(false);
1029 call.args_ref = std::move(extra_args);
1030 }
1031
1032
1033 if (func.has_kwargs) {
1034 if (!kwargs.ptr()) {
1035 kwargs = dict();
1036 }
1037 call.args.push_back(kwargs);
1038 call.args_convert.push_back(false);
1039 call.kwargs_ref = std::move(kwargs);
1040 }
1041
1042
1043
1044 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1045 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) {
1046 pybind11_fail("Internal error: function call dispatcher inserted wrong number "
1047 "of arguments!");
1048 }
1049 #endif
1050
1051 std::vector<bool> second_pass_convert;
1052 if (overloaded) {
1053
1054
1055
1056 second_pass_convert.resize(func.nargs, false);
1057 call.args_convert.swap(second_pass_convert);
1058 }
1059
1060
1061 try {
1062 loader_life_support guard{};
1063 result = func.impl(call);
1064 } catch (reference_cast_error &) {
1065 result = PYBIND11_TRY_NEXT_OVERLOAD;
1066 }
1067
1068 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
1069 break;
1070 }
1071
1072 if (overloaded) {
1073
1074
1075
1076 for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
1077 if (second_pass_convert[i]) {
1078
1079
1080 call.args_convert.swap(second_pass_convert);
1081 second_pass.push_back(std::move(call));
1082 break;
1083 }
1084 }
1085 }
1086 }
1087
1088 if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
1089
1090
1091 for (auto &call : second_pass) {
1092 try {
1093 loader_life_support guard{};
1094 result = call.func.impl(call);
1095 } catch (reference_cast_error &) {
1096 result = PYBIND11_TRY_NEXT_OVERLOAD;
1097 }
1098
1099 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
1100
1101
1102 if (!result) {
1103 current_overload = &call.func;
1104 }
1105 break;
1106 }
1107 }
1108 }
1109 } catch (error_already_set &e) {
1110 e.restore();
1111 return nullptr;
1112 #ifdef __GLIBCXX__
1113 } catch (abi::__forced_unwind &) {
1114 throw;
1115 #endif
1116 } catch (...) {
1117 try_translate_exceptions();
1118 return nullptr;
1119 }
1120
1121 auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
1122 if (msg.find("std::") != std::string::npos) {
1123 msg += "\n\n"
1124 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1125 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1126 "conversions are optional and require extra headers to be included\n"
1127 "when compiling your pybind11 module.";
1128 }
1129 };
1130
1131 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
1132 if (overloads->is_operator) {
1133 return handle(Py_NotImplemented).inc_ref().ptr();
1134 }
1135
1136 std::string msg = std::string(overloads->name) + "(): incompatible "
1137 + std::string(overloads->is_constructor ? "constructor" : "function")
1138 + " arguments. The following argument types are supported:\n";
1139
1140 int ctr = 0;
1141 for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
1142 msg += " " + std::to_string(++ctr) + ". ";
1143
1144 bool wrote_sig = false;
1145 if (overloads->is_constructor) {
1146
1147
1148 std::string sig = it2->signature;
1149 size_t start = sig.find('(') + 7;
1150 if (start < sig.size()) {
1151
1152 size_t end = sig.find(", "), next = end + 2;
1153 size_t ret = sig.rfind(" -> ");
1154
1155 if (end >= sig.size()) {
1156 next = end = sig.find(')');
1157 }
1158 if (start < end && next < sig.size()) {
1159 msg.append(sig, start, end - start);
1160 msg += '(';
1161 msg.append(sig, next, ret - next);
1162 wrote_sig = true;
1163 }
1164 }
1165 }
1166 if (!wrote_sig) {
1167 msg += it2->signature;
1168 }
1169
1170 msg += '\n';
1171 }
1172 msg += "\nInvoked with: ";
1173 auto args_ = reinterpret_borrow<tuple>(args_in);
1174 bool some_args = false;
1175 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
1176 if (!some_args) {
1177 some_args = true;
1178 } else {
1179 msg += ", ";
1180 }
1181 try {
1182 msg += pybind11::repr(args_[ti]);
1183 } catch (const error_already_set &) {
1184 msg += "<repr raised Error>";
1185 }
1186 }
1187 if (kwargs_in) {
1188 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
1189 if (!kwargs.empty()) {
1190 if (some_args) {
1191 msg += "; ";
1192 }
1193 msg += "kwargs: ";
1194 bool first = true;
1195 for (const auto &kwarg : kwargs) {
1196 if (first) {
1197 first = false;
1198 } else {
1199 msg += ", ";
1200 }
1201 msg += pybind11::str("{}=").format(kwarg.first);
1202 try {
1203 msg += pybind11::repr(kwarg.second);
1204 } catch (const error_already_set &) {
1205 msg += "<repr raised Error>";
1206 }
1207 }
1208 }
1209 }
1210
1211 append_note_if_missing_header_is_suspected(msg);
1212
1213 if (PyErr_Occurred()) {
1214
1215 raise_from(PyExc_TypeError, msg.c_str());
1216 return nullptr;
1217 }
1218 set_error(PyExc_TypeError, msg.c_str());
1219 return nullptr;
1220 }
1221 if (!result) {
1222 std::string msg = "Unable to convert function return value to a "
1223 "Python type! The signature was\n\t";
1224 assert(current_overload != nullptr);
1225 msg += current_overload->signature;
1226 append_note_if_missing_header_is_suspected(msg);
1227
1228 if (PyErr_Occurred()) {
1229 raise_from(PyExc_TypeError, msg.c_str());
1230 return nullptr;
1231 }
1232 set_error(PyExc_TypeError, msg.c_str());
1233 return nullptr;
1234 }
1235 if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
1236 auto *pi = reinterpret_cast<instance *>(parent.ptr());
1237 self_value_and_holder.type->init_instance(pi, nullptr);
1238 }
1239 return result.ptr();
1240 }
1241 };
1242
1243 PYBIND11_NAMESPACE_BEGIN(detail)
1244
1245 PYBIND11_NAMESPACE_BEGIN(function_record_PyTypeObject_methods)
1246
1247
1248 inline void tp_dealloc_impl(PyObject *self) {
1249 auto *py_func_rec = (function_record_PyObject *) self;
1250 cpp_function::destruct(py_func_rec->cpp_func_rec);
1251 py_func_rec->cpp_func_rec = nullptr;
1252 }
1253
1254 PYBIND11_NAMESPACE_END(function_record_PyTypeObject_methods)
1255
1256 template <>
1257 struct handle_type_name<cpp_function> {
1258 static constexpr auto name = const_name("collections.abc.Callable");
1259 };
1260
1261 PYBIND11_NAMESPACE_END(detail)
1262
1263
1264 class mod_gil_not_used {
1265 public:
1266 explicit mod_gil_not_used(bool flag = true) : flag_(flag) {}
1267 bool flag() const { return flag_; }
1268
1269 private:
1270 bool flag_;
1271 };
1272
1273 class multiple_interpreters {
1274 public:
1275 enum class level {
1276 not_supported,
1277 shared_gil,
1278 per_interpreter_gil
1279 };
1280
1281 static multiple_interpreters not_supported() {
1282 return multiple_interpreters(level::not_supported);
1283 }
1284 static multiple_interpreters shared_gil() { return multiple_interpreters(level::shared_gil); }
1285 static multiple_interpreters per_interpreter_gil() {
1286 return multiple_interpreters(level::per_interpreter_gil);
1287 }
1288
1289 explicit constexpr multiple_interpreters(level l) : level_(l) {}
1290 level value() const { return level_; }
1291
1292 private:
1293 level level_;
1294 };
1295
1296 PYBIND11_NAMESPACE_BEGIN(detail)
1297
1298 inline bool gil_not_used_option() { return false; }
1299 template <typename F, typename... O>
1300 bool gil_not_used_option(F &&, O &&...o);
1301 template <typename... O>
1302 inline bool gil_not_used_option(mod_gil_not_used f, O &&...o) {
1303 return f.flag() || gil_not_used_option(o...);
1304 }
1305 template <typename F, typename... O>
1306 inline bool gil_not_used_option(F &&, O &&...o) {
1307 return gil_not_used_option(o...);
1308 }
1309
1310 #ifdef Py_mod_multiple_interpreters
1311 inline void *multi_interp_slot() { return Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED; }
1312 template <typename... O>
1313 inline void *multi_interp_slot(multiple_interpreters mi, O &&...o) {
1314 switch (mi.value()) {
1315 case multiple_interpreters::level::per_interpreter_gil:
1316 return Py_MOD_PER_INTERPRETER_GIL_SUPPORTED;
1317 case multiple_interpreters::level::shared_gil:
1318 return Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED;
1319 case multiple_interpreters::level::not_supported:
1320 return Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED;
1321 }
1322
1323 return multi_interp_slot(o...);
1324 }
1325 template <typename F, typename... O>
1326 inline void *multi_interp_slot(F &&, O &&...o) {
1327 return multi_interp_slot(o...);
1328 }
1329 #endif
1330
1331
1332
1333
1334
1335 inline PyObject *get_cached_module(pybind11::str const &nameobj) {
1336 dict state = detail::get_python_state_dict();
1337 if (!state.contains("__pybind11_module_cache")) {
1338 return nullptr;
1339 }
1340 dict cache = state["__pybind11_module_cache"];
1341 if (!cache.contains(nameobj)) {
1342 return nullptr;
1343 }
1344 return cache[nameobj].ptr();
1345 }
1346
1347
1348
1349
1350
1351
1352 inline void cache_completed_module(pybind11::object const &mod) {
1353 dict state = detail::get_python_state_dict();
1354 if (!state.contains("__pybind11_module_cache")) {
1355 state["__pybind11_module_cache"] = dict();
1356 }
1357 state["__pybind11_module_cache"][mod.attr("__spec__").attr("name")] = mod;
1358 }
1359
1360
1361
1362
1363
1364 inline PyObject *cached_create_module(PyObject *spec, PyModuleDef *) {
1365 (void) &cache_completed_module;
1366
1367 auto nameobj = getattr(reinterpret_borrow<object>(spec), "name", none());
1368 if (nameobj.is_none()) {
1369 set_error(PyExc_ImportError, "module spec is missing a name");
1370 return nullptr;
1371 }
1372
1373 auto *mod = get_cached_module(nameobj);
1374 if (mod) {
1375 Py_INCREF(mod);
1376 } else {
1377 mod = PyModule_NewObject(nameobj.ptr());
1378 }
1379 return mod;
1380 }
1381
1382
1383
1384 using slots_array = std::array<PyModuleDef_Slot, 5>;
1385
1386
1387 template <typename... Options>
1388 inline slots_array init_slots(int (*exec_fn)(PyObject *), Options &&...options) noexcept {
1389
1390
1391 slots_array mod_def_slots;
1392 size_t next_slot = 0;
1393
1394 mod_def_slots[next_slot++] = {Py_mod_create, reinterpret_cast<void *>(&cached_create_module)};
1395
1396 if (exec_fn != nullptr) {
1397 mod_def_slots[next_slot++] = {Py_mod_exec, reinterpret_cast<void *>(exec_fn)};
1398 }
1399
1400 #ifdef Py_mod_multiple_interpreters
1401 mod_def_slots[next_slot++] = {Py_mod_multiple_interpreters, multi_interp_slot(options...)};
1402 #endif
1403
1404 if (gil_not_used_option(options...)) {
1405 #if defined(Py_mod_gil) && defined(Py_GIL_DISABLED)
1406 mod_def_slots[next_slot++] = {Py_mod_gil, Py_MOD_GIL_NOT_USED};
1407 #endif
1408 }
1409
1410
1411 mod_def_slots[next_slot++] = {0, nullptr};
1412
1413 return mod_def_slots;
1414 }
1415
1416 PYBIND11_NAMESPACE_END(detail)
1417
1418
1419 class module_ : public object {
1420 public:
1421 PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)
1422
1423
1424 PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead")
1425 explicit module_(const char *name, const char *doc = nullptr) {
1426 *this = create_extension_module(name, doc, new PyModuleDef());
1427 }
1428
1429
1430
1431
1432
1433
1434 template <typename Func, typename... Extra>
1435 module_ &def(const char *name_, Func &&f, const Extra &...extra) {
1436 cpp_function func(std::forward<Func>(f),
1437 name(name_),
1438 scope(*this),
1439 sibling(getattr(*this, name_, none())),
1440 extra...);
1441
1442
1443
1444 add_object(name_, func, true );
1445 return *this;
1446 }
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458 module_ def_submodule(const char *name, const char *doc = nullptr) {
1459 const char *this_name = PyModule_GetName(m_ptr);
1460 if (this_name == nullptr) {
1461 throw error_already_set();
1462 }
1463 std::string full_name = std::string(this_name) + '.' + name;
1464 handle submodule = PyImport_AddModule(full_name.c_str());
1465 if (!submodule) {
1466 throw error_already_set();
1467 }
1468 auto result = reinterpret_borrow<module_>(submodule);
1469 if (doc && options::show_user_defined_docstrings()) {
1470 result.attr("__doc__") = pybind11::str(doc);
1471 }
1472
1473 #if defined(GRAALVM_PYTHON) && (!defined(GRAALPY_VERSION_NUM) || GRAALPY_VERSION_NUM < 0x190000)
1474
1475
1476 handle this_module = m_ptr;
1477 if (object this_file = getattr(this_module, "__file__", none())) {
1478 result.attr("__file__") = this_file;
1479 }
1480 #else
1481 handle this_file = PyModule_GetFilenameObject(m_ptr);
1482 if (this_file) {
1483 result.attr("__file__") = this_file;
1484 } else if (PyErr_ExceptionMatches(PyExc_SystemError) != 0) {
1485 PyErr_Clear();
1486 } else {
1487 throw error_already_set();
1488 }
1489 #endif
1490 attr(name) = result;
1491 return result;
1492 }
1493
1494
1495 static module_ import(const char *name) {
1496 PyObject *obj = PyImport_ImportModule(name);
1497 if (!obj) {
1498 throw error_already_set();
1499 }
1500 return reinterpret_steal<module_>(obj);
1501 }
1502
1503
1504 void reload() {
1505 PyObject *obj = PyImport_ReloadModule(ptr());
1506 if (!obj) {
1507 throw error_already_set();
1508 }
1509 *this = reinterpret_steal<module_>(obj);
1510 }
1511
1512
1513
1514
1515
1516
1517
1518
1519 PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
1520 if (!overwrite && hasattr(*this, name)) {
1521 pybind11_fail(
1522 "Error during initialization: multiple incompatible definitions with name \""
1523 + std::string(name) + "\"");
1524 }
1525
1526 PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() );
1527 }
1528
1529
1530 using module_def = PyModuleDef;
1531
1532
1533
1534
1535
1536
1537 static module_ create_extension_module(const char *name,
1538 const char *doc,
1539 PyModuleDef *def,
1540 mod_gil_not_used gil_not_used
1541 = mod_gil_not_used(false)) {
1542
1543 new (def) PyModuleDef{ PyModuleDef_HEAD_INIT,
1544 name,
1545 options::show_user_defined_docstrings() ? doc : nullptr,
1546 -1,
1547 nullptr,
1548 nullptr,
1549 nullptr,
1550 nullptr,
1551 nullptr};
1552 auto *m = PyModule_Create(def);
1553 if (m == nullptr) {
1554 if (PyErr_Occurred()) {
1555 throw error_already_set();
1556 }
1557 pybind11_fail("Internal error in module_::create_extension_module()");
1558 }
1559 if (gil_not_used.flag()) {
1560 #ifdef Py_GIL_DISABLED
1561 PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
1562 #endif
1563 }
1564
1565
1566
1567 return reinterpret_borrow<module_>(m);
1568 }
1569 };
1570
1571 PYBIND11_NAMESPACE_BEGIN(detail)
1572
1573 template <>
1574 struct handle_type_name<module_> {
1575 static constexpr auto name = const_name("types.ModuleType");
1576 };
1577
1578 PYBIND11_NAMESPACE_END(detail)
1579
1580
1581
1582
1583 using module = module_;
1584
1585
1586
1587
1588 inline dict globals() {
1589 #if PY_VERSION_HEX >= 0x030d0000
1590 PyObject *p = PyEval_GetFrameGlobals();
1591 return p ? reinterpret_steal<dict>(p)
1592 : reinterpret_borrow<dict>(module_::import("__main__").attr("__dict__").ptr());
1593 #else
1594 PyObject *p = PyEval_GetGlobals();
1595 return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
1596 #endif
1597 }
1598
1599 PYBIND11_NAMESPACE_BEGIN(detail)
1600
1601 class generic_type : public object {
1602 public:
1603 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
1604 protected:
1605 void initialize(const type_record &rec) {
1606 if (rec.scope && hasattr(rec.scope, "__dict__")
1607 && rec.scope.attr("__dict__").contains(rec.name)) {
1608 pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name)
1609 + "\": an object with that name is already defined");
1610 }
1611
1612 if ((rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
1613 != nullptr) {
1614 pybind11_fail("generic_type: type \"" + std::string(rec.name)
1615 + "\" is already registered!");
1616 }
1617
1618 m_ptr = make_new_python_type(rec);
1619
1620
1621 auto *tinfo = new detail::type_info();
1622 tinfo->type = (PyTypeObject *) m_ptr;
1623 tinfo->cpptype = rec.type;
1624 tinfo->type_size = rec.type_size;
1625 tinfo->type_align = rec.type_align;
1626 tinfo->operator_new = rec.operator_new;
1627 tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
1628 tinfo->init_instance = rec.init_instance;
1629 tinfo->dealloc = rec.dealloc;
1630 tinfo->get_trampoline_self_life_support = rec.get_trampoline_self_life_support;
1631 tinfo->simple_type = true;
1632 tinfo->simple_ancestors = true;
1633 tinfo->module_local = rec.module_local;
1634 tinfo->holder_enum_v = rec.holder_enum_v;
1635
1636 with_internals([&](internals &internals) {
1637 auto tindex = std::type_index(*rec.type);
1638 tinfo->direct_conversions = &internals.direct_conversions[tindex];
1639 if (rec.module_local) {
1640 get_local_internals().registered_types_cpp[tindex] = tinfo;
1641 } else {
1642 internals.registered_types_cpp[tindex] = tinfo;
1643 }
1644
1645 PYBIND11_WARNING_PUSH
1646 #if defined(__GNUC__) && __GNUC__ == 12
1647
1648
1649
1650 PYBIND11_WARNING_DISABLE_GCC("-Warray-bounds")
1651 PYBIND11_WARNING_DISABLE_GCC("-Wstringop-overread")
1652 #endif
1653 internals.registered_types_py[(PyTypeObject *) m_ptr] = {tinfo};
1654 PYBIND11_WARNING_POP
1655 });
1656
1657 if (rec.bases.size() > 1 || rec.multiple_inheritance) {
1658 mark_parents_nonsimple(tinfo->type);
1659 tinfo->simple_ancestors = false;
1660 } else if (rec.bases.size() == 1) {
1661 auto *parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
1662 assert(parent_tinfo != nullptr);
1663 bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1664 tinfo->simple_ancestors = parent_simple_ancestors;
1665
1666 parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1667 }
1668
1669 if (rec.module_local) {
1670
1671 tinfo->module_local_load = &type_caster_generic::local_load;
1672 setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
1673 }
1674 }
1675
1676
1677 void mark_parents_nonsimple(PyTypeObject *value) {
1678 auto t = reinterpret_borrow<tuple>(value->tp_bases);
1679 for (handle h : t) {
1680 auto *tinfo2 = get_type_info((PyTypeObject *) h.ptr());
1681 if (tinfo2) {
1682 tinfo2->simple_type = false;
1683 }
1684 mark_parents_nonsimple((PyTypeObject *) h.ptr());
1685 }
1686 }
1687
1688 void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *),
1689 void *get_buffer_data) {
1690 auto *type = (PyHeapTypeObject *) m_ptr;
1691 auto *tinfo = detail::get_type_info(&type->ht_type);
1692
1693 if (!type->ht_type.tp_as_buffer) {
1694 pybind11_fail("To be able to register buffer protocol support for the type '"
1695 + get_fully_qualified_tp_name(tinfo->type)
1696 + "' the associated class<>(..) invocation must "
1697 "include the pybind11::buffer_protocol() annotation!");
1698 }
1699
1700 tinfo->get_buffer = get_buffer;
1701 tinfo->get_buffer_data = get_buffer_data;
1702 }
1703
1704
1705 void def_property_static_impl(const char *name,
1706 handle fget,
1707 handle fset,
1708 detail::function_record *rec_func) {
1709 const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);
1710 const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)
1711 && pybind11::options::show_user_defined_docstrings();
1712 auto property = handle(
1713 (PyObject *) (is_static ? get_internals().static_property_type : &PyProperty_Type));
1714 attr(name) = property(fget.ptr() ? fget : none(),
1715 fset.ptr() ? fset : none(),
1716 none(),
1717 pybind11::str(has_doc ? rec_func->doc : ""));
1718 }
1719 };
1720
1721
1722 template <typename T,
1723 typename = void_t<decltype(static_cast<void *(*) (size_t)>(T::operator new))>>
1724 void set_operator_new(type_record *r) {
1725 r->operator_new = &T::operator new;
1726 }
1727
1728 template <typename>
1729 void set_operator_new(...) {}
1730
1731 template <typename T, typename SFINAE = void>
1732 struct has_operator_delete : std::false_type {};
1733 template <typename T>
1734 struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
1735 : std::true_type {};
1736 template <typename T, typename SFINAE = void>
1737 struct has_operator_delete_size : std::false_type {};
1738 template <typename T>
1739 struct has_operator_delete_size<
1740 T,
1741 void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type {
1742 };
1743
1744 template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
1745 void call_operator_delete(T *p, size_t, size_t) {
1746 T::operator delete(p);
1747 }
1748 template <typename T,
1749 enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int>
1750 = 0>
1751 void call_operator_delete(T *p, size_t s, size_t) {
1752 T::operator delete(p, s);
1753 }
1754
1755 inline void call_operator_delete(void *p, size_t s, size_t a) {
1756 (void) s;
1757 (void) a;
1758 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1759 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1760 # ifdef __cpp_sized_deallocation
1761 ::operator delete(p, s, std::align_val_t(a));
1762 # else
1763 ::operator delete(p, std::align_val_t(a));
1764 # endif
1765 return;
1766 }
1767 #endif
1768 #ifdef __cpp_sized_deallocation
1769 ::operator delete(p, s);
1770 #else
1771 ::operator delete(p);
1772 #endif
1773 }
1774
1775 inline void add_class_method(object &cls, const char *name_, const cpp_function &cf) {
1776 cls.attr(cf.name()) = cf;
1777 if (std::strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) {
1778 cls.attr("__hash__") = none();
1779 }
1780 }
1781
1782 PYBIND11_NAMESPACE_END(detail)
1783
1784
1785
1786 template <typename , typename F>
1787 auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
1788 return std::forward<F>(f);
1789 }
1790
1791 template <typename Derived, typename Return, typename Class, typename... Args>
1792 auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
1793 static_assert(
1794 detail::is_accessible_base_of<Class, Derived>::value,
1795 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1796 return pmf;
1797 }
1798
1799 template <typename Derived, typename Return, typename Class, typename... Args>
1800 auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
1801 static_assert(
1802 detail::is_accessible_base_of<Class, Derived>::value,
1803 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1804 return pmf;
1805 }
1806
1807 PYBIND11_NAMESPACE_BEGIN(detail)
1808
1809
1810
1811
1812
1813
1814
1815 template <typename PM>
1816 using must_be_member_function_pointer = enable_if_t<std::is_member_pointer<PM>::value, int>;
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826 template <typename T, typename D>
1827 struct property_cpp_function_classic {
1828 template <typename PM, must_be_member_function_pointer<PM> = 0>
1829 static cpp_function readonly(PM pm, const handle &hdl) {
1830 return cpp_function([pm](const T &c) -> const D & { return c.*pm; }, is_method(hdl));
1831 }
1832
1833 template <typename PM, must_be_member_function_pointer<PM> = 0>
1834 static cpp_function read(PM pm, const handle &hdl) {
1835 return readonly(pm, hdl);
1836 }
1837
1838 template <typename PM, must_be_member_function_pointer<PM> = 0>
1839 static cpp_function write(PM pm, const handle &hdl) {
1840 return cpp_function([pm](T &c, const D &value) { c.*pm = value; }, is_method(hdl));
1841 }
1842 };
1843
1844 PYBIND11_NAMESPACE_END(detail)
1845
1846 template <typename T, typename D, typename SFINAE = void>
1847 struct property_cpp_function : detail::property_cpp_function_classic<T, D> {};
1848
1849 PYBIND11_NAMESPACE_BEGIN(detail)
1850
1851 template <typename T, typename D, typename SFINAE = void>
1852 struct both_t_and_d_use_type_caster_base : std::false_type {};
1853
1854
1855
1856 template <typename T, typename D>
1857 struct both_t_and_d_use_type_caster_base<
1858 T,
1859 D,
1860 enable_if_t<all_of<std::is_base_of<type_caster_base<T>, type_caster<T>>,
1861 std::is_base_of<type_caster_base<intrinsic_t<D>>, make_caster<D>>>::value>>
1862 : std::true_type {};
1863
1864
1865
1866
1867
1868
1869
1870
1871 template <typename T, typename D>
1872 struct property_cpp_function_sh_raw_ptr_member {
1873 using drp = typename std::remove_pointer<D>::type;
1874
1875 template <typename PM, must_be_member_function_pointer<PM> = 0>
1876 static cpp_function readonly(PM pm, const handle &hdl) {
1877 type_info *tinfo = get_type_info(typeid(T), true);
1878 if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
1879 return cpp_function(
1880 [pm](handle c_hdl) -> std::shared_ptr<drp> {
1881 std::shared_ptr<T> c_sp
1882 = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(
1883 c_hdl);
1884 D ptr = (*c_sp).*pm;
1885 return std::shared_ptr<drp>(c_sp, ptr);
1886 },
1887 is_method(hdl));
1888 }
1889 return property_cpp_function_classic<T, D>::readonly(pm, hdl);
1890 }
1891
1892 template <typename PM, must_be_member_function_pointer<PM> = 0>
1893 static cpp_function read(PM pm, const handle &hdl) {
1894 return readonly(pm, hdl);
1895 }
1896
1897 template <typename PM, must_be_member_function_pointer<PM> = 0>
1898 static cpp_function write(PM pm, const handle &hdl) {
1899 type_info *tinfo = get_type_info(typeid(T), true);
1900 if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
1901 return cpp_function([pm](T &c, D value) { c.*pm = std::forward<D>(std::move(value)); },
1902 is_method(hdl));
1903 }
1904 return property_cpp_function_classic<T, D>::write(pm, hdl);
1905 }
1906 };
1907
1908
1909
1910
1911
1912
1913 template <typename T, typename D>
1914 struct property_cpp_function_sh_member_held_by_value {
1915 template <typename PM, must_be_member_function_pointer<PM> = 0>
1916 static cpp_function readonly(PM pm, const handle &hdl) {
1917 type_info *tinfo = get_type_info(typeid(T), true);
1918 if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
1919 return cpp_function(
1920 [pm](handle c_hdl) -> std::shared_ptr<typename std::add_const<D>::type> {
1921 std::shared_ptr<T> c_sp
1922 = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(
1923 c_hdl);
1924 return std::shared_ptr<typename std::add_const<D>::type>(c_sp,
1925 &(c_sp.get()->*pm));
1926 },
1927 is_method(hdl));
1928 }
1929 return property_cpp_function_classic<T, D>::readonly(pm, hdl);
1930 }
1931
1932 template <typename PM, must_be_member_function_pointer<PM> = 0>
1933 static cpp_function read(PM pm, const handle &hdl) {
1934 type_info *tinfo = get_type_info(typeid(T), true);
1935 if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
1936 return cpp_function(
1937 [pm](handle c_hdl) -> std::shared_ptr<D> {
1938 std::shared_ptr<T> c_sp
1939 = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(
1940 c_hdl);
1941 return std::shared_ptr<D>(c_sp, &(c_sp.get()->*pm));
1942 },
1943 is_method(hdl));
1944 }
1945 return property_cpp_function_classic<T, D>::read(pm, hdl);
1946 }
1947
1948 template <typename PM, must_be_member_function_pointer<PM> = 0>
1949 static cpp_function write(PM pm, const handle &hdl) {
1950 type_info *tinfo = get_type_info(typeid(T), true);
1951 if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
1952 return cpp_function([pm](T &c, const D &value) { c.*pm = value; }, is_method(hdl));
1953 }
1954 return property_cpp_function_classic<T, D>::write(pm, hdl);
1955 }
1956 };
1957
1958
1959
1960
1961
1962
1963
1964
1965 template <typename T, typename D>
1966 struct property_cpp_function_sh_unique_ptr_member {
1967 template <typename PM, must_be_member_function_pointer<PM> = 0>
1968 static cpp_function readonly(PM, const handle &) {
1969 static_assert(!is_instantiation<std::unique_ptr, D>::value,
1970 "def_readonly cannot be used for std::unique_ptr members.");
1971 return cpp_function{};
1972 }
1973
1974 template <typename PM, must_be_member_function_pointer<PM> = 0>
1975 static cpp_function read(PM pm, const handle &hdl) {
1976 type_info *tinfo = get_type_info(typeid(T), true);
1977 if (tinfo->holder_enum_v == holder_enum_t::smart_holder) {
1978 return cpp_function(
1979 [pm](handle c_hdl) -> D {
1980 std::shared_ptr<T> c_sp
1981 = type_caster<std::shared_ptr<T>>::shared_ptr_with_responsible_parent(
1982 c_hdl);
1983 return D{std::move(c_sp.get()->*pm)};
1984 },
1985 is_method(hdl));
1986 }
1987 return property_cpp_function_classic<T, D>::read(pm, hdl);
1988 }
1989
1990 template <typename PM, must_be_member_function_pointer<PM> = 0>
1991 static cpp_function write(PM pm, const handle &hdl) {
1992 return cpp_function([pm](T &c, D &&value) { c.*pm = std::move(value); }, is_method(hdl));
1993 }
1994 };
1995
1996 PYBIND11_NAMESPACE_END(detail)
1997
1998 template <typename T, typename D>
1999 struct property_cpp_function<
2000 T,
2001 D,
2002 detail::enable_if_t<detail::all_of<std::is_pointer<D>,
2003 detail::both_t_and_d_use_type_caster_base<T, D>>::value>>
2004 : detail::property_cpp_function_sh_raw_ptr_member<T, D> {};
2005
2006 template <typename T, typename D>
2007 struct property_cpp_function<T,
2008 D,
2009 detail::enable_if_t<detail::all_of<
2010 detail::none_of<std::is_pointer<D>,
2011 std::is_array<D>,
2012 detail::is_instantiation<std::unique_ptr, D>,
2013 detail::is_instantiation<std::shared_ptr, D>>,
2014 detail::both_t_and_d_use_type_caster_base<T, D>>::value>>
2015 : detail::property_cpp_function_sh_member_held_by_value<T, D> {};
2016
2017 template <typename T, typename D>
2018 struct property_cpp_function<
2019 T,
2020 D,
2021 detail::enable_if_t<detail::all_of<
2022 detail::is_instantiation<std::unique_ptr, D>,
2023 detail::both_t_and_d_use_type_caster_base<T, typename D::element_type>>::value>>
2024 : detail::property_cpp_function_sh_unique_ptr_member<T, D> {};
2025
2026 #ifdef PYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE
2027
2028
2029
2030
2031
2032
2033 template <typename>
2034 using default_holder_type = smart_holder;
2035 #else
2036 template <typename T>
2037 using default_holder_type = std::unique_ptr<T>;
2038 #endif
2039
2040 template <typename type_, typename... options>
2041 class class_ : public detail::generic_type {
2042 template <typename T>
2043 using is_holder = detail::is_holder_type<type_, T>;
2044 template <typename T>
2045 using is_subtype = detail::is_strict_base_of<type_, T>;
2046 template <typename T>
2047 using is_base = detail::is_strict_base_of<T, type_>;
2048
2049 template <typename T>
2050 struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
2051
2052 public:
2053 using type = type_;
2054 using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
2055 constexpr static bool has_alias = !std::is_void<type_alias>::value;
2056 using holder_type = detail::exactly_one_t<is_holder, default_holder_type<type>, options...>;
2057
2058 static_assert(detail::all_of<is_valid_class_option<options>...>::value,
2059 "Unknown/invalid class_ template parameters provided");
2060
2061 static_assert(!has_alias || std::is_polymorphic<type>::value,
2062 "Cannot use an alias class (aka trampoline) with a non-polymorphic type");
2063
2064 #ifndef PYBIND11_RUN_TESTING_WITH_SMART_HOLDER_AS_DEFAULT_BUT_NEVER_USE_IN_PRODUCTION_PLEASE
2065 static_assert(!has_alias || !detail::is_smart_holder<holder_type>::value
2066 || std::is_base_of<trampoline_self_life_support, type_alias>::value,
2067 "Alias class (aka trampoline) must inherit from"
2068 " pybind11::trampoline_self_life_support if used in combination with"
2069 " pybind11::smart_holder");
2070 #endif
2071 static_assert(!has_alias || detail::is_smart_holder<holder_type>::value
2072 || !std::is_base_of<trampoline_self_life_support, type_alias>::value,
2073 "pybind11::trampoline_self_life_support is a smart_holder feature, therefore"
2074 " an alias class (aka trampoline) should inherit from"
2075 " pybind11::trampoline_self_life_support only if used in combination with"
2076 " pybind11::smart_holder");
2077
2078 PYBIND11_OBJECT(class_, generic_type, PyType_Check)
2079
2080 template <typename... Extra>
2081 class_(handle scope, const char *name, const Extra &...extra) {
2082 using namespace detail;
2083
2084
2085 static_assert(
2086 none_of<is_pyobject<Extra>...>::value ||
2087 (constexpr_sum(is_pyobject<Extra>::value...) == 1 &&
2088 constexpr_sum(is_base<options>::value...) == 0 &&
2089
2090 none_of<std::is_same<multiple_inheritance, Extra>...>::value),
2091 "Error: multiple inheritance bases must be specified via class_ template options");
2092
2093 type_record record;
2094 record.scope = scope;
2095 record.name = name;
2096 record.type = &typeid(type);
2097 record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
2098 record.type_align = alignof(conditional_t<has_alias, type_alias, type> &);
2099 record.holder_size = sizeof(holder_type);
2100 record.init_instance = init_instance;
2101
2102 if (detail::is_instantiation<std::unique_ptr, holder_type>::value) {
2103 record.holder_enum_v = detail::holder_enum_t::std_unique_ptr;
2104 } else if (detail::is_instantiation<std::shared_ptr, holder_type>::value) {
2105 record.holder_enum_v = detail::holder_enum_t::std_shared_ptr;
2106 } else if (std::is_same<holder_type, smart_holder>::value) {
2107 record.holder_enum_v = detail::holder_enum_t::smart_holder;
2108 } else {
2109 record.holder_enum_v = detail::holder_enum_t::custom_holder;
2110 }
2111
2112 set_operator_new<type>(&record);
2113
2114
2115 PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
2116
2117
2118 process_attributes<Extra...>::init(extra..., &record);
2119
2120 if (record.release_gil_before_calling_cpp_dtor) {
2121 record.dealloc = dealloc_release_gil_before_calling_cpp_dtor;
2122 } else {
2123 record.dealloc = dealloc_without_manipulating_gil;
2124 }
2125
2126 if (std::is_base_of<trampoline_self_life_support, type_alias>::value) {
2127
2128
2129
2130 record.get_trampoline_self_life_support = [](void *type_ptr) {
2131 return dynamic_raw_ptr_cast_if_possible<trampoline_self_life_support>(
2132 static_cast<type *>(type_ptr));
2133 };
2134 }
2135
2136 generic_type::initialize(record);
2137
2138 if (has_alias) {
2139 with_internals([&](internals &internals) {
2140 auto &instances = record.module_local ? get_local_internals().registered_types_cpp
2141 : internals.registered_types_cpp;
2142 instances[std::type_index(typeid(type_alias))]
2143 = instances[std::type_index(typeid(type))];
2144 });
2145 }
2146 def("_pybind11_conduit_v1_", cpp_conduit_method);
2147 }
2148
2149 template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
2150 static void add_base(detail::type_record &rec) {
2151 rec.add_base(typeid(Base), [](void *src) -> void * {
2152 return static_cast<Base *>(reinterpret_cast<type *>(src));
2153 });
2154 }
2155
2156 template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
2157 static void add_base(detail::type_record &) {}
2158
2159 template <typename Func, typename... Extra>
2160 class_ &def(const char *name_, Func &&f, const Extra &...extra) {
2161 cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
2162 name(name_),
2163 is_method(*this),
2164 sibling(getattr(*this, name_, none())),
2165 extra...);
2166 add_class_method(*this, name_, cf);
2167 return *this;
2168 }
2169
2170 template <typename Func, typename... Extra>
2171 class_ &def_static(const char *name_, Func &&f, const Extra &...extra) {
2172 static_assert(!std::is_member_function_pointer<Func>::value,
2173 "def_static(...) called with a non-static member function pointer");
2174 cpp_function cf(std::forward<Func>(f),
2175 name(name_),
2176 scope(*this),
2177 sibling(getattr(*this, name_, none())),
2178 extra...);
2179 auto cf_name = cf.name();
2180 attr(std::move(cf_name)) = staticmethod(std::move(cf));
2181 return *this;
2182 }
2183
2184 template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
2185 class_ &def(const T &op, const Extra &...extra) {
2186 op.execute(*this, extra...);
2187 return *this;
2188 }
2189
2190 template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
2191 class_ &def_cast(const T &op, const Extra &...extra) {
2192 op.execute_cast(*this, extra...);
2193 return *this;
2194 }
2195
2196 template <typename... Args, typename... Extra>
2197 class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra &...extra) {
2198 PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
2199 init.execute(*this, extra...);
2200 return *this;
2201 }
2202
2203 template <typename... Args, typename... Extra>
2204 class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra &...extra) {
2205 PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
2206 init.execute(*this, extra...);
2207 return *this;
2208 }
2209
2210 template <typename... Args, typename... Extra>
2211 class_ &def(detail::initimpl::factory<Args...> &&init, const Extra &...extra) {
2212 std::move(init).execute(*this, extra...);
2213 return *this;
2214 }
2215
2216 template <typename... Args, typename... Extra>
2217 class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
2218 std::move(pf).execute(*this, extra...);
2219 return *this;
2220 }
2221
2222 template <typename Func>
2223 class_ &def_buffer(Func &&func) {
2224 struct capture {
2225 Func func;
2226 };
2227 auto *ptr = new capture{std::forward<Func>(func)};
2228 install_buffer_funcs(
2229 [](PyObject *obj, void *ptr) -> buffer_info * {
2230 detail::make_caster<type> caster;
2231 if (!caster.load(obj, false)) {
2232 return nullptr;
2233 }
2234 return new buffer_info(((capture *) ptr)->func(std::move(caster)));
2235 },
2236 ptr);
2237 weakref(m_ptr, cpp_function([ptr](handle wr) {
2238 delete ptr;
2239 wr.dec_ref();
2240 }))
2241 .release();
2242 return *this;
2243 }
2244
2245 template <typename Return, typename Class, typename... Args>
2246 class_ &def_buffer(Return (Class::*func)(Args...)) {
2247 return def_buffer([func](type &obj) { return (obj.*func)(); });
2248 }
2249
2250 template <typename Return, typename Class, typename... Args>
2251 class_ &def_buffer(Return (Class::*func)(Args...) const) {
2252 return def_buffer([func](const type &obj) { return (obj.*func)(); });
2253 }
2254
2255 template <typename C, typename D, typename... Extra>
2256 class_ &def_readwrite(const char *name, D C::*pm, const Extra &...extra) {
2257 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
2258 "def_readwrite() requires a class member (or base class member)");
2259 def_property(name,
2260 property_cpp_function<type, D>::read(pm, *this),
2261 property_cpp_function<type, D>::write(pm, *this),
2262 return_value_policy::reference_internal,
2263 extra...);
2264 return *this;
2265 }
2266
2267 template <typename C, typename D, typename... Extra>
2268 class_ &def_readonly(const char *name, const D C::*pm, const Extra &...extra) {
2269 static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
2270 "def_readonly() requires a class member (or base class member)");
2271 def_property_readonly(name,
2272 property_cpp_function<type, D>::readonly(pm, *this),
2273 return_value_policy::reference_internal,
2274 extra...);
2275 return *this;
2276 }
2277
2278 template <typename D, typename... Extra>
2279 class_ &def_readwrite_static(const char *name, D *pm, const Extra &...extra) {
2280 cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)),
2281 fset([pm](const object &, const D &value) { *pm = value; }, scope(*this));
2282 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
2283 return *this;
2284 }
2285
2286 template <typename D, typename... Extra>
2287 class_ &def_readonly_static(const char *name, const D *pm, const Extra &...extra) {
2288 cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this));
2289 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
2290 return *this;
2291 }
2292
2293
2294 template <typename Getter, typename... Extra>
2295 class_ &def_property_readonly(const char *name, const Getter &fget, const Extra &...extra) {
2296 return def_property_readonly(name,
2297 cpp_function(method_adaptor<type>(fget)),
2298 return_value_policy::reference_internal,
2299 extra...);
2300 }
2301
2302
2303 template <typename... Extra>
2304 class_ &
2305 def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra) {
2306 return def_property(name, fget, nullptr, extra...);
2307 }
2308
2309
2310 template <typename Getter, typename... Extra>
2311 class_ &
2312 def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra) {
2313 return def_property_readonly_static(
2314 name, cpp_function(fget), return_value_policy::reference, extra...);
2315 }
2316
2317
2318 template <typename... Extra>
2319 class_ &def_property_readonly_static(const char *name,
2320 const cpp_function &fget,
2321 const Extra &...extra) {
2322 return def_property_static(name, fget, nullptr, extra...);
2323 }
2324
2325
2326 template <typename Getter, typename Setter, typename... Extra>
2327 class_ &
2328 def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) {
2329 return def_property(
2330 name, fget, cpp_function(method_adaptor<type>(fset), is_setter()), extra...);
2331 }
2332 template <typename Getter, typename... Extra>
2333 class_ &def_property(const char *name,
2334 const Getter &fget,
2335 const cpp_function &fset,
2336 const Extra &...extra) {
2337 return def_property(name,
2338 cpp_function(method_adaptor<type>(fget)),
2339 fset,
2340 return_value_policy::reference_internal,
2341 extra...);
2342 }
2343
2344
2345 template <typename... Extra>
2346 class_ &def_property(const char *name,
2347 const cpp_function &fget,
2348 const cpp_function &fset,
2349 const Extra &...extra) {
2350 return def_property_static(name, fget, fset, is_method(*this), extra...);
2351 }
2352
2353
2354 template <typename Getter, typename... Extra>
2355 class_ &def_property_static(const char *name,
2356 const Getter &fget,
2357 const cpp_function &fset,
2358 const Extra &...extra) {
2359 return def_property_static(
2360 name, cpp_function(fget), fset, return_value_policy::reference, extra...);
2361 }
2362
2363
2364 template <typename... Extra>
2365 class_ &def_property_static(const char *name,
2366 const cpp_function &fget,
2367 const cpp_function &fset,
2368 const Extra &...extra) {
2369 static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
2370 "Argument annotations are not allowed for properties");
2371 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
2372 auto *rec_active = rec_fget;
2373 if (rec_fget) {
2374 char *doc_prev = rec_fget->doc;
2375
2376 detail::process_attributes<Extra...>::init(extra..., rec_fget);
2377 if (rec_fget->doc && rec_fget->doc != doc_prev) {
2378 std::free(doc_prev);
2379 rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc);
2380 }
2381 }
2382 if (rec_fset) {
2383 char *doc_prev = rec_fset->doc;
2384 detail::process_attributes<Extra...>::init(extra..., rec_fset);
2385 if (rec_fset->doc && rec_fset->doc != doc_prev) {
2386 std::free(doc_prev);
2387 rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc);
2388 }
2389 if (!rec_active) {
2390 rec_active = rec_fset;
2391 }
2392 }
2393 def_property_static_impl(name, fget, fset, rec_active);
2394 return *this;
2395 }
2396
2397 private:
2398
2399 template <typename T>
2400 static void init_holder(detail::instance *inst,
2401 detail::value_and_holder &v_h,
2402 const holder_type * ,
2403 const std::enable_shared_from_this<T> * ) {
2404
2405 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
2406 detail::try_get_shared_from_this(v_h.value_ptr<type>()));
2407 if (sh) {
2408 new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
2409 v_h.set_holder_constructed();
2410 }
2411
2412 if (!v_h.holder_constructed() && inst->owned) {
2413 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
2414 v_h.set_holder_constructed();
2415 }
2416 }
2417
2418 static void init_holder_from_existing(const detail::value_and_holder &v_h,
2419 const holder_type *holder_ptr,
2420 std::true_type ) {
2421 new (std::addressof(v_h.holder<holder_type>()))
2422 holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
2423 }
2424
2425 static void init_holder_from_existing(const detail::value_and_holder &v_h,
2426 const holder_type *holder_ptr,
2427 std::false_type ) {
2428 new (std::addressof(v_h.holder<holder_type>()))
2429 holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
2430 }
2431
2432
2433
2434 static void init_holder(detail::instance *inst,
2435 detail::value_and_holder &v_h,
2436 const holder_type *holder_ptr,
2437 const void * ) {
2438 if (holder_ptr) {
2439 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
2440 v_h.set_holder_constructed();
2441 } else if (detail::always_construct_holder<holder_type>::value || inst->owned) {
2442 new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
2443 v_h.set_holder_constructed();
2444 }
2445 }
2446
2447
2448
2449
2450
2451 template <typename H = holder_type,
2452 detail::enable_if_t<!detail::is_smart_holder<H>::value, int> = 0>
2453 static void init_instance(detail::instance *inst, const void *holder_ptr) {
2454 auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
2455 if (!v_h.instance_registered()) {
2456 register_instance(inst, v_h.value_ptr(), v_h.type);
2457 v_h.set_instance_registered();
2458 }
2459 init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
2460 }
2461
2462 template <typename WrappedType>
2463 static bool try_initialization_using_shared_from_this(holder_type *, WrappedType *, ...) {
2464 return false;
2465 }
2466
2467
2468
2469
2470
2471
2472 template <typename WrappedType, typename SomeBaseOfWrappedType>
2473 static bool try_initialization_using_shared_from_this(
2474 holder_type *uninitialized_location,
2475 WrappedType *value_ptr_w_t,
2476 const std::enable_shared_from_this<SomeBaseOfWrappedType> *) {
2477 auto shd_ptr = std::dynamic_pointer_cast<WrappedType>(
2478 detail::try_get_shared_from_this(value_ptr_w_t));
2479 if (!shd_ptr) {
2480 return false;
2481 }
2482
2483 new (uninitialized_location) holder_type(holder_type::from_shared_ptr(shd_ptr));
2484 return true;
2485 }
2486
2487 template <typename H = holder_type,
2488 detail::enable_if_t<detail::is_smart_holder<H>::value, int> = 0>
2489 static void init_instance(detail::instance *inst, const void *holder_const_void_ptr) {
2490
2491
2492 auto *holder_void_ptr = const_cast<void *>(holder_const_void_ptr);
2493
2494 auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
2495 if (!v_h.instance_registered()) {
2496 register_instance(inst, v_h.value_ptr(), v_h.type);
2497 v_h.set_instance_registered();
2498 }
2499 auto *uninitialized_location = std::addressof(v_h.holder<holder_type>());
2500 auto *value_ptr_w_t = v_h.value_ptr<type>();
2501
2502 inst->is_alias
2503 = detail::dynamic_raw_ptr_cast_if_possible<type_alias>(value_ptr_w_t) != nullptr;
2504 if (holder_void_ptr) {
2505
2506 auto *holder_ptr = static_cast<holder_type *>(holder_void_ptr);
2507 new (uninitialized_location) holder_type(std::move(*holder_ptr));
2508 } else if (!try_initialization_using_shared_from_this(
2509 uninitialized_location, value_ptr_w_t, value_ptr_w_t)) {
2510 if (inst->owned) {
2511 new (uninitialized_location) holder_type(holder_type::from_raw_ptr_take_ownership(
2512 value_ptr_w_t, inst->is_alias));
2513 } else {
2514 new (uninitialized_location)
2515 holder_type(holder_type::from_raw_ptr_unowned(value_ptr_w_t));
2516 }
2517 }
2518 v_h.set_holder_constructed();
2519 }
2520
2521
2522
2523
2524
2525
2526
2527
2528 static void dealloc_impl(detail::value_and_holder &v_h) {
2529 if (v_h.holder_constructed()) {
2530 v_h.holder<holder_type>().~holder_type();
2531 v_h.set_holder_constructed(false);
2532 } else {
2533 detail::call_operator_delete(
2534 v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align);
2535 }
2536 v_h.value_ptr() = nullptr;
2537 }
2538
2539 static void dealloc_without_manipulating_gil(detail::value_and_holder &v_h) {
2540 error_scope scope;
2541 dealloc_impl(v_h);
2542 }
2543
2544 static void dealloc_release_gil_before_calling_cpp_dtor(detail::value_and_holder &v_h) {
2545 error_scope scope;
2546
2547
2548
2549
2550 PyThreadState *py_ts = PyEval_SaveThread();
2551 try {
2552 dealloc_impl(v_h);
2553 } catch (...) {
2554
2555
2556
2557
2558
2559 PyEval_RestoreThread(py_ts);
2560 throw;
2561 }
2562 PyEval_RestoreThread(py_ts);
2563 }
2564
2565 static detail::function_record *get_function_record(handle h) {
2566 h = detail::get_function(h);
2567 if (!h) {
2568 return nullptr;
2569 }
2570
2571 handle func_self = PyCFunction_GET_SELF(h.ptr());
2572 if (!func_self) {
2573 throw error_already_set();
2574 }
2575 return detail::function_record_ptr_from_PyObject(func_self.ptr());
2576 }
2577 };
2578
2579
2580
2581 template <typename type_, typename... options>
2582 using classh = class_<type_, smart_holder, options...>;
2583
2584
2585 template <typename... Args>
2586 detail::initimpl::constructor<Args...> init() {
2587 return {};
2588 }
2589
2590
2591 template <typename... Args>
2592 detail::initimpl::alias_constructor<Args...> init_alias() {
2593 return {};
2594 }
2595
2596
2597 template <typename Func, typename Ret = detail::initimpl::factory<Func>>
2598 Ret init(Func &&f) {
2599 return {std::forward<Func>(f)};
2600 }
2601
2602
2603
2604
2605 template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
2606 Ret init(CFunc &&c, AFunc &&a) {
2607 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
2608 }
2609
2610
2611
2612 template <typename GetState, typename SetState>
2613 detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
2614 return {std::forward<GetState>(g), std::forward<SetState>(s)};
2615 }
2616
2617 PYBIND11_NAMESPACE_BEGIN(detail)
2618
2619 inline str enum_name(handle arg) {
2620 dict entries = type::handle_of(arg).attr("__entries");
2621 for (auto kv : entries) {
2622 if (handle(kv.second[int_(0)]).equal(arg)) {
2623 return pybind11::str(kv.first);
2624 }
2625 }
2626 return "???";
2627 }
2628
2629 struct enum_base {
2630 enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) {}
2631
2632 PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
2633 m_base.attr("__entries") = dict();
2634 auto property = handle((PyObject *) &PyProperty_Type);
2635 auto static_property = handle((PyObject *) get_internals().static_property_type);
2636
2637 m_base.attr("__repr__") = cpp_function(
2638 [](const object &arg) -> str {
2639 handle type = type::handle_of(arg);
2640 object type_name = type.attr("__name__");
2641 return pybind11::str("<{}.{}: {}>")
2642 .format(std::move(type_name), enum_name(arg), int_(arg));
2643 },
2644 name("__repr__"),
2645 is_method(m_base),
2646 pos_only());
2647
2648 m_base.attr("name")
2649 = property(cpp_function(&enum_name, name("name"), is_method(m_base), pos_only()));
2650
2651 m_base.attr("__str__") = cpp_function(
2652 [](handle arg) -> str {
2653 object type_name = type::handle_of(arg).attr("__name__");
2654 return pybind11::str("{}.{}").format(std::move(type_name), enum_name(arg));
2655 },
2656 name("__str__"),
2657 is_method(m_base),
2658 pos_only());
2659
2660 if (options::show_enum_members_docstring()) {
2661 m_base.attr("__doc__") = static_property(
2662 cpp_function(
2663 [](handle arg) -> std::string {
2664 std::string docstring;
2665 dict entries = arg.attr("__entries");
2666 if (((PyTypeObject *) arg.ptr())->tp_doc) {
2667 docstring += std::string(
2668 reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);
2669 docstring += "\n\n";
2670 }
2671 docstring += "Members:";
2672 for (auto kv : entries) {
2673 auto key = std::string(pybind11::str(kv.first));
2674 auto comment = kv.second[int_(1)];
2675 docstring += "\n\n ";
2676 docstring += key;
2677 if (!comment.is_none()) {
2678 docstring += " : ";
2679 docstring += pybind11::str(comment).cast<std::string>();
2680 }
2681 }
2682 return docstring;
2683 },
2684 name("__doc__")),
2685 none(),
2686 none(),
2687 "");
2688 }
2689
2690 m_base.attr("__members__") = static_property(cpp_function(
2691 [](handle arg) -> dict {
2692 dict entries = arg.attr("__entries"),
2693 m;
2694 for (auto kv : entries) {
2695 m[kv.first] = kv.second[int_(0)];
2696 }
2697 return m;
2698 },
2699 name("__members__")),
2700 none(),
2701 none(),
2702 "");
2703
2704 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
2705 m_base.attr(op) = cpp_function( \
2706 [](const object &a, const object &b) { \
2707 if (!type::handle_of(a).is(type::handle_of(b))) \
2708 strict_behavior; \
2709 return expr; \
2710 }, \
2711 name(op), \
2712 is_method(m_base), \
2713 arg("other"), \
2714 pos_only())
2715
2716 #define PYBIND11_ENUM_OP_CONV(op, expr) \
2717 m_base.attr(op) = cpp_function( \
2718 [](const object &a_, const object &b_) { \
2719 int_ a(a_), b(b_); \
2720 return expr; \
2721 }, \
2722 name(op), \
2723 is_method(m_base), \
2724 arg("other"), \
2725 pos_only())
2726
2727 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
2728 m_base.attr(op) = cpp_function( \
2729 [](const object &a_, const object &b) { \
2730 int_ a(a_); \
2731 return expr; \
2732 }, \
2733 name(op), \
2734 is_method(m_base), \
2735 arg("other"), \
2736 pos_only())
2737
2738 if (is_convertible) {
2739 PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
2740 PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
2741
2742 if (is_arithmetic) {
2743 PYBIND11_ENUM_OP_CONV("__lt__", a < b);
2744 PYBIND11_ENUM_OP_CONV("__gt__", a > b);
2745 PYBIND11_ENUM_OP_CONV("__le__", a <= b);
2746 PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
2747 PYBIND11_ENUM_OP_CONV("__and__", a & b);
2748 PYBIND11_ENUM_OP_CONV("__rand__", a & b);
2749 PYBIND11_ENUM_OP_CONV("__or__", a | b);
2750 PYBIND11_ENUM_OP_CONV("__ror__", a | b);
2751 PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
2752 PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
2753 m_base.attr("__invert__")
2754 = cpp_function([](const object &arg) { return ~(int_(arg)); },
2755 name("__invert__"),
2756 is_method(m_base),
2757 pos_only());
2758 }
2759 } else {
2760 PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
2761 PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
2762
2763 if (is_arithmetic) {
2764 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
2765 PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
2766 PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
2767 PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
2768 PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
2769 #undef PYBIND11_THROW
2770 }
2771 }
2772
2773 #undef PYBIND11_ENUM_OP_CONV_LHS
2774 #undef PYBIND11_ENUM_OP_CONV
2775 #undef PYBIND11_ENUM_OP_STRICT
2776
2777 m_base.attr("__getstate__") = cpp_function([](const object &arg) { return int_(arg); },
2778 name("__getstate__"),
2779 is_method(m_base),
2780 pos_only());
2781
2782 m_base.attr("__hash__") = cpp_function([](const object &arg) { return int_(arg); },
2783 name("__hash__"),
2784 is_method(m_base),
2785 pos_only());
2786 }
2787
2788 PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc = nullptr) {
2789 dict entries = m_base.attr("__entries");
2790 str name(name_);
2791 if (entries.contains(name)) {
2792 std::string type_name = (std::string) str(m_base.attr("__name__"));
2793 throw value_error(std::move(type_name) + ": element \"" + std::string(name_)
2794 + "\" already exists!");
2795 }
2796
2797 entries[name] = pybind11::make_tuple(value, doc);
2798 m_base.attr(std::move(name)) = std::move(value);
2799 }
2800
2801 PYBIND11_NOINLINE void export_values() {
2802 dict entries = m_base.attr("__entries");
2803 for (auto kv : entries) {
2804 m_parent.attr(kv.first) = kv.second[int_(0)];
2805 }
2806 }
2807
2808 handle m_base;
2809 handle m_parent;
2810 };
2811
2812 template <bool is_signed, size_t length>
2813 struct equivalent_integer {};
2814 template <>
2815 struct equivalent_integer<true, 1> {
2816 using type = int8_t;
2817 };
2818 template <>
2819 struct equivalent_integer<false, 1> {
2820 using type = uint8_t;
2821 };
2822 template <>
2823 struct equivalent_integer<true, 2> {
2824 using type = int16_t;
2825 };
2826 template <>
2827 struct equivalent_integer<false, 2> {
2828 using type = uint16_t;
2829 };
2830 template <>
2831 struct equivalent_integer<true, 4> {
2832 using type = int32_t;
2833 };
2834 template <>
2835 struct equivalent_integer<false, 4> {
2836 using type = uint32_t;
2837 };
2838 template <>
2839 struct equivalent_integer<true, 8> {
2840 using type = int64_t;
2841 };
2842 template <>
2843 struct equivalent_integer<false, 8> {
2844 using type = uint64_t;
2845 };
2846
2847 template <typename IntLike>
2848 using equivalent_integer_t =
2849 typename equivalent_integer<std::is_signed<IntLike>::value, sizeof(IntLike)>::type;
2850
2851 PYBIND11_NAMESPACE_END(detail)
2852
2853
2854 template <typename Type>
2855 class enum_ : public class_<Type> {
2856 public:
2857 using Base = class_<Type>;
2858 using Base::attr;
2859 using Base::def;
2860 using Base::def_property_readonly;
2861 using Base::def_property_readonly_static;
2862 using Underlying = typename std::underlying_type<Type>::type;
2863
2864 using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2865 std::is_same<Underlying, bool>>::value,
2866 detail::equivalent_integer_t<Underlying>,
2867 Underlying>;
2868
2869 template <typename... Extra>
2870 enum_(const handle &scope, const char *name, const Extra &...extra)
2871 : class_<Type>(scope, name, extra...), m_base(*this, scope) {
2872 {
2873 if (detail::global_internals_native_enum_type_map_contains(
2874 std::type_index(typeid(Type)))) {
2875 pybind11_fail("pybind11::enum_ \"" + std::string(name)
2876 + "\" is already registered as a pybind11::native_enum!");
2877 }
2878 }
2879
2880 constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
2881 constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
2882 m_base.init(is_arithmetic, is_convertible);
2883
2884 def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
2885 def_property_readonly("value", [](Type value) { return (Scalar) value; }, pos_only());
2886 def("__int__", [](Type value) { return (Scalar) value; }, pos_only());
2887 def("__index__", [](Type value) { return (Scalar) value; }, pos_only());
2888 attr("__setstate__") = cpp_function(
2889 [](detail::value_and_holder &v_h, Scalar arg) {
2890 detail::initimpl::setstate<Base>(
2891 v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type);
2892 },
2893 detail::is_new_style_constructor(),
2894 pybind11::name("__setstate__"),
2895 is_method(*this),
2896 arg("state"),
2897 pos_only());
2898 }
2899
2900
2901 enum_ &export_values() {
2902 m_base.export_values();
2903 return *this;
2904 }
2905
2906
2907 enum_ &value(char const *name, Type value, const char *doc = nullptr) {
2908 m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
2909 return *this;
2910 }
2911
2912 private:
2913 detail::enum_base m_base;
2914 };
2915
2916 PYBIND11_NAMESPACE_BEGIN(detail)
2917
2918 PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient) {
2919 if (!nurse || !patient) {
2920 pybind11_fail("Could not activate keep_alive!");
2921 }
2922
2923 if (patient.is_none() || nurse.is_none()) {
2924 return;
2925 }
2926
2927 auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
2928 if (!tinfo.empty()) {
2929
2930
2931 add_patient(nurse.ptr(), patient.ptr());
2932 } else {
2933
2934
2935
2936 cpp_function disable_lifesupport([patient](handle weakref) {
2937 patient.dec_ref();
2938 weakref.dec_ref();
2939 });
2940
2941 weakref wr(nurse, disable_lifesupport);
2942
2943 patient.inc_ref();
2944 (void) wr.release();
2945 }
2946 }
2947
2948 PYBIND11_NOINLINE void
2949 keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
2950 auto get_arg = [&](size_t n) {
2951 if (n == 0) {
2952 return ret;
2953 }
2954 if (n == 1 && call.init_self) {
2955 return call.init_self;
2956 }
2957 if (n <= call.args.size()) {
2958 return call.args[n - 1];
2959 }
2960 return handle();
2961 };
2962
2963 keep_alive_impl(get_arg(Nurse), get_arg(Patient));
2964 }
2965
2966 inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
2967 all_type_info_get_cache(PyTypeObject *type) {
2968 auto res = with_internals([type](internals &internals) {
2969 auto ins = internals
2970 .registered_types_py
2971 #ifdef __cpp_lib_unordered_map_try_emplace
2972 .try_emplace(type);
2973 #else
2974 .emplace(type, std::vector<detail::type_info *>());
2975 #endif
2976 if (ins.second) {
2977
2978
2979
2980 all_type_info_populate(type, ins.first->second);
2981 }
2982 return ins;
2983 });
2984 if (res.second) {
2985
2986
2987 weakref((PyObject *) type, cpp_function([type](handle wr) {
2988 with_internals([type](internals &internals) {
2989 internals.registered_types_py.erase(type);
2990
2991
2992 auto &cache = internals.inactive_override_cache;
2993 for (auto it = cache.begin(), last = cache.end(); it != last;) {
2994 if (it->first == reinterpret_cast<PyObject *>(type)) {
2995 it = cache.erase(it);
2996 } else {
2997 ++it;
2998 }
2999 }
3000 });
3001
3002 wr.dec_ref();
3003 }))
3004 .release();
3005 }
3006
3007 return res;
3008 }
3009
3010
3011
3012
3013 template <typename Access,
3014 return_value_policy Policy,
3015 typename Iterator,
3016 typename Sentinel,
3017 typename ValueType,
3018 typename... Extra>
3019 struct iterator_state {
3020 Iterator it;
3021 Sentinel end;
3022 bool first_or_done;
3023 };
3024
3025
3026
3027
3028
3029 template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
3030 struct iterator_access {
3031 using result_type = decltype(*std::declval<Iterator &>());
3032
3033 result_type operator()(Iterator &it) const { return *it; }
3034 };
3035
3036 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).first)>
3037 class iterator_key_access {
3038 private:
3039 using pair_type = decltype(*std::declval<Iterator &>());
3040
3041 public:
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051 using result_type
3052 = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
3053 decltype(((*std::declval<Iterator &>()).first)),
3054 decltype(std::declval<pair_type>().first)>;
3055 result_type operator()(Iterator &it) const { return (*it).first; }
3056 };
3057
3058 template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
3059 class iterator_value_access {
3060 private:
3061 using pair_type = decltype(*std::declval<Iterator &>());
3062
3063 public:
3064 using result_type
3065 = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
3066 decltype(((*std::declval<Iterator &>()).second)),
3067 decltype(std::declval<pair_type>().second)>;
3068 result_type operator()(Iterator &it) const { return (*it).second; }
3069 };
3070
3071 template <typename Access,
3072 return_value_policy Policy,
3073 typename Iterator,
3074 typename Sentinel,
3075 typename ValueType,
3076 typename... Extra>
3077
3078 iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra) {
3079 using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
3080
3081
3082 if (!detail::get_type_info(typeid(state), false)) {
3083 class_<state>(handle(), "iterator", pybind11::module_local())
3084 .def(
3085 "__iter__", [](state &s) -> state & { return s; }, pos_only())
3086 .def(
3087 "__next__",
3088 [](state &s) -> ValueType {
3089 if (!s.first_or_done) {
3090 ++s.it;
3091 } else {
3092 s.first_or_done = false;
3093 }
3094 if (s.it == s.end) {
3095 s.first_or_done = true;
3096 throw stop_iteration();
3097 }
3098 return Access()(s.it);
3099
3100 },
3101 std::forward<Extra>(extra)...,
3102 pos_only(),
3103 Policy);
3104 }
3105
3106 return cast(state{std::forward<Iterator>(first), std::forward<Sentinel>(last), true});
3107 }
3108
3109 PYBIND11_NAMESPACE_END(detail)
3110
3111
3112 template <return_value_policy Policy = return_value_policy::reference_internal,
3113 typename Iterator,
3114 typename Sentinel,
3115 typename ValueType = typename detail::iterator_access<Iterator>::result_type,
3116 typename... Extra>
3117
3118 typing::Iterator<ValueType> make_iterator(Iterator first, Sentinel last, Extra &&...extra) {
3119 return detail::make_iterator_impl<detail::iterator_access<Iterator>,
3120 Policy,
3121 Iterator,
3122 Sentinel,
3123 ValueType,
3124 Extra...>(std::forward<Iterator>(first),
3125 std::forward<Sentinel>(last),
3126 std::forward<Extra>(extra)...);
3127 }
3128
3129
3130
3131 template <return_value_policy Policy = return_value_policy::reference_internal,
3132 typename Iterator,
3133 typename Sentinel,
3134 typename KeyType = typename detail::iterator_key_access<Iterator>::result_type,
3135 typename... Extra>
3136 typing::Iterator<KeyType> make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) {
3137 return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
3138 Policy,
3139 Iterator,
3140 Sentinel,
3141 KeyType,
3142 Extra...>(std::forward<Iterator>(first),
3143 std::forward<Sentinel>(last),
3144 std::forward<Extra>(extra)...);
3145 }
3146
3147
3148
3149 template <return_value_policy Policy = return_value_policy::reference_internal,
3150 typename Iterator,
3151 typename Sentinel,
3152 typename ValueType = typename detail::iterator_value_access<Iterator>::result_type,
3153 typename... Extra>
3154 typing::Iterator<ValueType> make_value_iterator(Iterator first, Sentinel last, Extra &&...extra) {
3155 return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
3156 Policy,
3157 Iterator,
3158 Sentinel,
3159 ValueType,
3160 Extra...>(std::forward<Iterator>(first),
3161 std::forward<Sentinel>(last),
3162 std::forward<Extra>(extra)...);
3163 }
3164
3165
3166
3167 template <return_value_policy Policy = return_value_policy::reference_internal,
3168 typename Type,
3169 typename ValueType = typename detail::iterator_access<
3170 decltype(std::begin(std::declval<Type &>()))>::result_type,
3171 typename... Extra>
3172 typing::Iterator<ValueType> make_iterator(Type &value, Extra &&...extra) {
3173 return make_iterator<Policy>(
3174 std::begin(value), std::end(value), std::forward<Extra>(extra)...);
3175 }
3176
3177
3178
3179 template <return_value_policy Policy = return_value_policy::reference_internal,
3180 typename Type,
3181 typename KeyType = typename detail::iterator_key_access<
3182 decltype(std::begin(std::declval<Type &>()))>::result_type,
3183 typename... Extra>
3184 typing::Iterator<KeyType> make_key_iterator(Type &value, Extra &&...extra) {
3185 return make_key_iterator<Policy>(
3186 std::begin(value), std::end(value), std::forward<Extra>(extra)...);
3187 }
3188
3189
3190
3191 template <return_value_policy Policy = return_value_policy::reference_internal,
3192 typename Type,
3193 typename ValueType = typename detail::iterator_value_access<
3194 decltype(std::begin(std::declval<Type &>()))>::result_type,
3195 typename... Extra>
3196 typing::Iterator<ValueType> make_value_iterator(Type &value, Extra &&...extra) {
3197 return make_value_iterator<Policy>(
3198 std::begin(value), std::end(value), std::forward<Extra>(extra)...);
3199 }
3200
3201 template <typename InputType, typename OutputType>
3202 void implicitly_convertible() {
3203 static int tss_sentinel_pointee = 1;
3204 struct set_flag {
3205 thread_specific_storage<int> &flag;
3206 explicit set_flag(thread_specific_storage<int> &flag_) : flag(flag_) {
3207 flag = &tss_sentinel_pointee;
3208 }
3209 ~set_flag() { flag.reset(nullptr); }
3210
3211
3212 set_flag(const set_flag &) = delete;
3213 set_flag(set_flag &&) = delete;
3214 set_flag &operator=(const set_flag &) = delete;
3215 set_flag &operator=(set_flag &&) = delete;
3216 };
3217 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
3218 static thread_specific_storage<int> currently_used;
3219 if (currently_used) {
3220 return nullptr;
3221 }
3222 set_flag flag_helper(currently_used);
3223 if (!detail::make_caster<InputType>().load(obj, false)) {
3224 return nullptr;
3225 }
3226 tuple args(1);
3227 args[0] = obj;
3228 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
3229 if (result == nullptr) {
3230 PyErr_Clear();
3231 }
3232 return result;
3233 };
3234
3235 if (auto *tinfo = detail::get_type_info(typeid(OutputType))) {
3236 tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
3237 } else {
3238 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
3239 }
3240 }
3241
3242 inline void register_exception_translator(ExceptionTranslator &&translator) {
3243 detail::with_exception_translators(
3244 [&](std::forward_list<ExceptionTranslator> &exception_translators,
3245 std::forward_list<ExceptionTranslator> &local_exception_translators) {
3246 (void) local_exception_translators;
3247 exception_translators.push_front(std::forward<ExceptionTranslator>(translator));
3248 });
3249 }
3250
3251
3252
3253
3254
3255
3256
3257 inline void register_local_exception_translator(ExceptionTranslator &&translator) {
3258 detail::with_exception_translators(
3259 [&](std::forward_list<ExceptionTranslator> &exception_translators,
3260 std::forward_list<ExceptionTranslator> &local_exception_translators) {
3261 (void) exception_translators;
3262 local_exception_translators.push_front(std::forward<ExceptionTranslator>(translator));
3263 });
3264 }
3265
3266
3267
3268
3269
3270
3271
3272
3273 template <typename type>
3274 class exception : public object {
3275 public:
3276 exception() = default;
3277 exception(handle scope, const char *name, handle base = PyExc_Exception) {
3278 std::string full_name
3279 = scope.attr("__name__").cast<std::string>() + std::string(".") + name;
3280 m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), nullptr);
3281 if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name)) {
3282 pybind11_fail("Error during initialization: multiple incompatible "
3283 "definitions with name \""
3284 + std::string(name) + "\"");
3285 }
3286 scope.attr(name) = *this;
3287 }
3288
3289
3290 PYBIND11_DEPRECATED("Please use py::set_error() instead "
3291 "(https://github.com/pybind/pybind11/pull/4772)")
3292 void operator()(const char *message) const { set_error(*this, message); }
3293 };
3294
3295 PYBIND11_NAMESPACE_BEGIN(detail)
3296
3297 template <>
3298 struct handle_type_name<exception<void>> {
3299 static constexpr auto name = const_name("Exception");
3300 };
3301
3302
3303 template <typename CppException>
3304 exception<CppException> &
3305 register_exception_impl(handle scope, const char *name, handle base, bool isLocal) {
3306 PYBIND11_CONSTINIT static gil_safe_call_once_and_store<exception<CppException>> exc_storage;
3307 exc_storage.call_once_and_store_result(
3308 [&]() { return exception<CppException>(scope, name, base); });
3309
3310 auto register_func
3311 = isLocal ? ®ister_local_exception_translator : ®ister_exception_translator;
3312
3313 register_func([](std::exception_ptr p) {
3314 if (!p) {
3315 return;
3316 }
3317 try {
3318 std::rethrow_exception(p);
3319 } catch (const CppException &e) {
3320 set_error(exc_storage.get_stored(), e.what());
3321 }
3322 });
3323 return exc_storage.get_stored();
3324 }
3325
3326 PYBIND11_NAMESPACE_END(detail)
3327
3328
3329
3330
3331
3332
3333
3334 template <typename CppException>
3335 exception<CppException> &
3336 register_exception(handle scope, const char *name, handle base = PyExc_Exception) {
3337 return detail::register_exception_impl<CppException>(scope, name, base, false );
3338 }
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348 template <typename CppException>
3349 exception<CppException> &
3350 register_local_exception(handle scope, const char *name, handle base = PyExc_Exception) {
3351 return detail::register_exception_impl<CppException>(scope, name, base, true );
3352 }
3353
3354 PYBIND11_NAMESPACE_BEGIN(detail)
3355 PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) {
3356 auto strings = tuple(args.size());
3357 for (size_t i = 0; i < args.size(); ++i) {
3358 strings[i] = str(args[i]);
3359 }
3360 auto sep = kwargs.contains("sep") ? kwargs["sep"] : str(" ");
3361 auto line = sep.attr("join")(std::move(strings));
3362
3363 object file;
3364 if (kwargs.contains("file")) {
3365 file = kwargs["file"].cast<object>();
3366 } else {
3367 try {
3368 file = module_::import("sys").attr("stdout");
3369 } catch (const error_already_set &) {
3370
3371
3372
3373
3374 return;
3375 }
3376 }
3377
3378 auto write = file.attr("write");
3379 write(std::move(line));
3380 write(kwargs.contains("end") ? kwargs["end"] : str("\n"));
3381
3382 if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) {
3383 file.attr("flush")();
3384 }
3385 }
3386 PYBIND11_NAMESPACE_END(detail)
3387
3388 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
3389 void print(Args &&...args) {
3390 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
3391 detail::print(c.args(), c.kwargs());
3392 }
3393
3394 inline void
3395 error_already_set::m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr) {
3396 gil_scoped_acquire gil;
3397 error_scope scope;
3398 delete raw_ptr;
3399 }
3400
3401 inline const char *error_already_set::what() const noexcept {
3402 gil_scoped_acquire gil;
3403 error_scope scope;
3404 return m_fetched_error->error_string().c_str();
3405 }
3406
3407 PYBIND11_NAMESPACE_BEGIN(detail)
3408
3409 inline function
3410 get_type_override(const void *this_ptr, const type_info *this_type, const char *name) {
3411 handle self = get_object_handle(this_ptr, this_type);
3412 if (!self) {
3413 return function();
3414 }
3415 handle type = type::handle_of(self);
3416 auto key = std::make_pair(type.ptr(), name);
3417
3418
3419
3420 bool not_overridden = with_internals([&key](internals &internals) {
3421 auto &cache = internals.inactive_override_cache;
3422 return cache.find(key) != cache.end();
3423 });
3424 if (not_overridden) {
3425 return function();
3426 }
3427
3428 function override = getattr(self, name, function());
3429 if (override.is_cpp_function()) {
3430 with_internals([&](internals &internals) {
3431 internals.inactive_override_cache.insert(std::move(key));
3432 });
3433 return function();
3434 }
3435
3436
3437
3438 #if !defined(PYPY_VERSION) && !defined(GRAALVM_PYTHON)
3439 # if PY_VERSION_HEX >= 0x03090000
3440 PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
3441 if (frame != nullptr) {
3442 PyCodeObject *f_code = PyFrame_GetCode(frame);
3443
3444 if ((std::string) str(f_code->co_name) == name && f_code->co_argcount > 0) {
3445 # if PY_VERSION_HEX >= 0x030d0000
3446 PyObject *locals = PyEval_GetFrameLocals();
3447 # else
3448 PyObject *locals = PyEval_GetLocals();
3449 Py_XINCREF(locals);
3450 # endif
3451 if (locals != nullptr) {
3452 # if PY_VERSION_HEX >= 0x030b0000
3453 PyObject *co_varnames = PyCode_GetVarnames(f_code);
3454 # else
3455 PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code, "co_varnames");
3456 # endif
3457 PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
3458 Py_DECREF(co_varnames);
3459 PyObject *self_caller = dict_getitem(locals, self_arg);
3460 Py_DECREF(locals);
3461 if (self_caller == self.ptr()) {
3462 Py_DECREF(f_code);
3463 Py_DECREF(frame);
3464 return function();
3465 }
3466 }
3467 }
3468 Py_DECREF(f_code);
3469 Py_DECREF(frame);
3470 }
3471 # else
3472 PyFrameObject *frame = PyThreadState_Get()->frame;
3473 if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name
3474 && frame->f_code->co_argcount > 0) {
3475 PyFrame_FastToLocals(frame);
3476 PyObject *self_caller
3477 = dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
3478 if (self_caller == self.ptr()) {
3479 return function();
3480 }
3481 }
3482 # endif
3483
3484 #else
3485
3486
3487
3488 dict d;
3489 d["self"] = self;
3490 d["name"] = pybind11::str(name);
3491 PyObject *result
3492 = PyRun_String("import inspect\n"
3493 "frame = inspect.currentframe()\n"
3494 "if frame is not None:\n"
3495 " frame = frame.f_back\n"
3496 " if frame is not None and str(frame.f_code.co_name) == name and "
3497 "frame.f_code.co_argcount > 0:\n"
3498 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
3499 " if self_caller == self:\n"
3500 " self = None\n",
3501 Py_file_input,
3502 d.ptr(),
3503 d.ptr());
3504 if (result == nullptr)
3505 throw error_already_set();
3506 Py_DECREF(result);
3507 if (d["self"].is_none())
3508 return function();
3509 #endif
3510
3511 return override;
3512 }
3513 PYBIND11_NAMESPACE_END(detail)
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524 template <class T>
3525 function get_override(const T *this_ptr, const char *name) {
3526 auto *tinfo = detail::get_type_info(typeid(T));
3527 return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
3528 }
3529
3530 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
3531 do { \
3532 pybind11::gil_scoped_acquire gil; \
3533 pybind11::function override \
3534 = pybind11::get_override(static_cast<const cname *>(this), name); \
3535 if (override) { \
3536 auto o = override(__VA_ARGS__); \
3537 PYBIND11_WARNING_PUSH \
3538 PYBIND11_WARNING_DISABLE_MSVC(4127) \
3539 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value \
3540 && !pybind11::detail::is_same_ignoring_cvref<ret_type, PyObject *>::value) { \
3541 static pybind11::detail::override_caster_t<ret_type> caster; \
3542 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
3543 } \
3544 PYBIND11_WARNING_POP \
3545 return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
3546 } \
3547 } while (false)
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
3568 do { \
3569 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
3570 return cname::fn(__VA_ARGS__); \
3571 } while (false)
3572
3573
3574
3575
3576
3577 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
3578 do { \
3579 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
3580 pybind11::pybind11_fail( \
3581 "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
3582 } while (false)
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
3610 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
3611
3612
3613
3614
3615
3616 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
3617 PYBIND11_OVERRIDE_PURE_NAME( \
3618 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
3619
3620
3621
3622 PYBIND11_DEPRECATED("get_type_overload has been deprecated")
3623 inline function
3624 get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
3625 return detail::get_type_override(this_ptr, this_type, name);
3626 }
3627
3628 template <class T>
3629 inline function get_overload(const T *this_ptr, const char *name) {
3630 return get_override(this_ptr, name);
3631 }
3632
3633 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
3634 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
3635 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
3636 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
3637 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
3638 PYBIND11_OVERRIDE_PURE_NAME( \
3639 PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
3640 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
3641 PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
3642 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
3643 PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
3644
3645 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)