Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-10-03 09:19:30

0001 /*
0002     pybind11/detail/class.h: Python C API implementation details for py::class_
0003 
0004     Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
0005 
0006     All rights reserved. Use of this source code is governed by a
0007     BSD-style license that can be found in the LICENSE file.
0008 */
0009 
0010 #pragma once
0011 
0012 #include <pybind11/attr.h>
0013 #include <pybind11/options.h>
0014 
0015 #include "exception_translation.h"
0016 
0017 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0018 PYBIND11_NAMESPACE_BEGIN(detail)
0019 
0020 #if !defined(PYPY_VERSION)
0021 #    define PYBIND11_BUILTIN_QUALNAME
0022 #    define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
0023 #else
0024 // In PyPy, we still set __qualname__ so that we can produce reliable function type
0025 // signatures; in CPython this macro expands to nothing:
0026 #    define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)                                             \
0027         setattr((PyObject *) obj, "__qualname__", nameobj)
0028 #endif
0029 
0030 inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
0031 #if !defined(PYPY_VERSION)
0032     return type->tp_name;
0033 #else
0034     auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
0035     if (module_name == PYBIND11_BUILTINS_MODULE)
0036         return type->tp_name;
0037     else
0038         return std::move(module_name) + "." + type->tp_name;
0039 #endif
0040 }
0041 
0042 inline PyTypeObject *type_incref(PyTypeObject *type) {
0043     Py_INCREF(type);
0044     return type;
0045 }
0046 
0047 #if !defined(PYPY_VERSION)
0048 
0049 /// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.
0050 extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
0051     return PyProperty_Type.tp_descr_get(self, cls, cls);
0052 }
0053 
0054 /// `pybind11_static_property.__set__()`: Just like the above `__get__()`.
0055 extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
0056     PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
0057     return PyProperty_Type.tp_descr_set(self, cls, value);
0058 }
0059 
0060 // Forward declaration to use in `make_static_property_type()`
0061 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type);
0062 
0063 /** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`
0064     methods are modified to always use the object type instead of a concrete instance.
0065     Return value: New reference. */
0066 inline PyTypeObject *make_static_property_type() {
0067     constexpr auto *name = "pybind11_static_property";
0068     auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
0069 
0070     /* Danger zone: from now (and until PyType_Ready), make sure to
0071        issue no Python C API calls which could potentially invoke the
0072        garbage collector (the GC will call type_traverse(), which will in
0073        turn find the newly constructed type in an invalid state) */
0074     auto *heap_type = reinterpret_cast<PyHeapTypeObject *>(PyType_Type.tp_alloc(&PyType_Type, 0));
0075     if (!heap_type) {
0076         pybind11_fail("make_static_property_type(): error allocating type!");
0077     }
0078 
0079     heap_type->ht_name = name_obj.inc_ref().ptr();
0080 #    ifdef PYBIND11_BUILTIN_QUALNAME
0081     heap_type->ht_qualname = name_obj.inc_ref().ptr();
0082 #    endif
0083 
0084     auto *type = &heap_type->ht_type;
0085     type->tp_name = name;
0086     type->tp_base = type_incref(&PyProperty_Type);
0087     type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
0088     type->tp_descr_get = pybind11_static_get;
0089     type->tp_descr_set = pybind11_static_set;
0090 
0091 #    if PY_VERSION_HEX >= 0x030C0000
0092     // Since Python-3.12 property-derived types are required to
0093     // have dynamic attributes (to set `__doc__`)
0094     enable_dynamic_attributes(heap_type);
0095 #    endif
0096 
0097     if (PyType_Ready(type) < 0) {
0098         pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
0099     }
0100 
0101     setattr(reinterpret_cast<PyObject *>(type), "__module__", str(PYBIND11_DUMMY_MODULE_NAME));
0102     PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
0103 
0104     return type;
0105 }
0106 
0107 #else // PYPY
0108 
0109 /** PyPy has some issues with the above C API, so we evaluate Python code instead.
0110     This function will only be called once so performance isn't really a concern.
0111     Return value: New reference. */
0112 inline PyTypeObject *make_static_property_type() {
0113     auto d = dict();
0114     PyObject *result = PyRun_String(R"(\
0115 class pybind11_static_property(property):
0116     def __get__(self, obj, cls):
0117         return property.__get__(self, cls, cls)
0118 
0119     def __set__(self, obj, value):
0120         cls = obj if isinstance(obj, type) else type(obj)
0121         property.__set__(self, cls, value)
0122 )",
0123                                     Py_file_input,
0124                                     d.ptr(),
0125                                     d.ptr());
0126     if (result == nullptr)
0127         throw error_already_set();
0128     Py_DECREF(result);
0129     return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
0130 }
0131 
0132 #endif // PYPY
0133 
0134 /** Types with static properties need to handle `Type.static_prop = x` in a specific way.
0135     By default, Python replaces the `static_property` itself, but for wrapped C++ types
0136     we need to call `static_property.__set__()` in order to propagate the new value to
0137     the underlying C++ data structure. */
0138 extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
0139     // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
0140     // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
0141     PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
0142 
0143     // The following assignment combinations are possible:
0144     //   1. `Type.static_prop = value`             --> descr_set: `Type.static_prop.__set__(value)`
0145     //   2. `Type.static_prop = other_static_prop` --> setattro:  replace existing `static_prop`
0146     //   3. `Type.regular_attribute = value`       --> setattro:  regular attribute assignment
0147     auto *const static_prop = (PyObject *) get_internals().static_property_type;
0148     const auto call_descr_set = (descr != nullptr) && (value != nullptr)
0149                                 && (PyObject_IsInstance(descr, static_prop) != 0)
0150                                 && (PyObject_IsInstance(value, static_prop) == 0);
0151     if (call_descr_set) {
0152         // Call `static_property.__set__()` instead of replacing the `static_property`.
0153 #if !defined(PYPY_VERSION)
0154         return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
0155 #else
0156         if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
0157             Py_DECREF(result);
0158             return 0;
0159         } else {
0160             return -1;
0161         }
0162 #endif
0163     } else {
0164         // Replace existing attribute.
0165         return PyType_Type.tp_setattro(obj, name, value);
0166     }
0167 }
0168 
0169 /**
0170  * Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
0171  * methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
0172  * when called on a class, or a PyMethod, when called on an instance.  Override that behaviour here
0173  * to do a special case bypass for PyInstanceMethod_Types.
0174  */
0175 extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
0176     PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
0177     if (descr && PyInstanceMethod_Check(descr)) {
0178         Py_INCREF(descr);
0179         return descr;
0180     }
0181     return PyType_Type.tp_getattro(obj, name);
0182 }
0183 
0184 /// metaclass `__call__` function that is used to create all pybind11 objects.
0185 extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
0186 
0187     // use the default metaclass call to create/initialize the object
0188     PyObject *self = PyType_Type.tp_call(type, args, kwargs);
0189     if (self == nullptr) {
0190         return nullptr;
0191     }
0192 
0193     // Ensure that the base __init__ function(s) were called
0194     values_and_holders vhs(self);
0195     for (const auto &vh : vhs) {
0196         if (!vh.holder_constructed() && !vhs.is_redundant_value_and_holder(vh)) {
0197             PyErr_Format(PyExc_TypeError,
0198                          "%.200s.__init__() must be called when overriding __init__",
0199                          get_fully_qualified_tp_name(vh.type->type).c_str());
0200             Py_DECREF(self);
0201             return nullptr;
0202         }
0203     }
0204 
0205     return self;
0206 }
0207 
0208 /// Cleanup the type-info for a pybind11-registered type.
0209 extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
0210     with_internals_if_internals([obj](internals &internals) {
0211         auto *type = (PyTypeObject *) obj;
0212 
0213         // A pybind11-registered type will:
0214         // 1) be found in internals.registered_types_py
0215         // 2) have exactly one associated `detail::type_info`
0216         auto found_type = internals.registered_types_py.find(type);
0217         if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
0218             && found_type->second[0]->type == type) {
0219 
0220             auto *tinfo = found_type->second[0];
0221             auto tindex = std::type_index(*tinfo->cpptype);
0222             internals.direct_conversions.erase(tindex);
0223 
0224             auto &local_internals = get_local_internals();
0225             if (tinfo->module_local) {
0226                 local_internals.registered_types_cpp.erase(tinfo->cpptype);
0227             } else {
0228                 internals.registered_types_cpp.erase(tindex);
0229 #if PYBIND11_INTERNALS_VERSION >= 12
0230                 internals.registered_types_cpp_fast.erase(tinfo->cpptype);
0231                 for (const std::type_info *alias : tinfo->alias_chain) {
0232                     auto num_erased = internals.registered_types_cpp_fast.erase(alias);
0233                     (void) num_erased;
0234                     assert(num_erased > 0);
0235                 }
0236 #endif
0237             }
0238             internals.registered_types_py.erase(tinfo->type);
0239 
0240             // Actually just `std::erase_if`, but that's only available in C++20
0241             auto &cache = internals.inactive_override_cache;
0242             for (auto it = cache.begin(), last = cache.end(); it != last;) {
0243                 if (it->first == (PyObject *) tinfo->type) {
0244                     it = cache.erase(it);
0245                 } else {
0246                     ++it;
0247                 }
0248             }
0249 
0250             delete tinfo;
0251         }
0252     });
0253 
0254     PyType_Type.tp_dealloc(obj);
0255 }
0256 
0257 /** This metaclass is assigned by default to all pybind11 types and is required in order
0258     for static properties to function correctly. Users may override this using `py::metaclass`.
0259     Return value: New reference. */
0260 inline PyTypeObject *make_default_metaclass() {
0261     constexpr auto *name = "pybind11_type";
0262     auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
0263 
0264     /* Danger zone: from now (and until PyType_Ready), make sure to
0265        issue no Python C API calls which could potentially invoke the
0266        garbage collector (the GC will call type_traverse(), which will in
0267        turn find the newly constructed type in an invalid state) */
0268     auto *heap_type = reinterpret_cast<PyHeapTypeObject *>(PyType_Type.tp_alloc(&PyType_Type, 0));
0269     if (!heap_type) {
0270         pybind11_fail("make_default_metaclass(): error allocating metaclass!");
0271     }
0272 
0273     heap_type->ht_name = name_obj.inc_ref().ptr();
0274 #ifdef PYBIND11_BUILTIN_QUALNAME
0275     heap_type->ht_qualname = name_obj.inc_ref().ptr();
0276 #endif
0277 
0278     auto *type = &heap_type->ht_type;
0279     type->tp_name = name;
0280     type->tp_base = type_incref(&PyType_Type);
0281     type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
0282 
0283     type->tp_call = pybind11_meta_call;
0284 
0285     type->tp_setattro = pybind11_meta_setattro;
0286     type->tp_getattro = pybind11_meta_getattro;
0287 
0288     type->tp_dealloc = pybind11_meta_dealloc;
0289 
0290     if (PyType_Ready(type) < 0) {
0291         pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
0292     }
0293 
0294     setattr(reinterpret_cast<PyObject *>(type), "__module__", str(PYBIND11_DUMMY_MODULE_NAME));
0295     PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
0296 
0297     return type;
0298 }
0299 
0300 /// For multiple inheritance types we need to recursively register/deregister base pointers for any
0301 /// base classes with pointers that are difference from the instance value pointer so that we can
0302 /// correctly recognize an offset base class pointer. This calls a function with any offset base
0303 /// ptrs.
0304 inline void traverse_offset_bases(void *valueptr,
0305                                   const detail::type_info *tinfo,
0306                                   instance *self,
0307                                   bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
0308     for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
0309         if (auto *parent_tinfo = get_type_info(reinterpret_cast<PyTypeObject *>(h.ptr()))) {
0310             for (auto &c : parent_tinfo->implicit_casts) {
0311                 if (c.first == tinfo->cpptype) {
0312                     auto *parentptr = c.second(valueptr);
0313                     if (parentptr != valueptr) {
0314                         f(parentptr, self);
0315                     }
0316                     traverse_offset_bases(parentptr, parent_tinfo, self, f);
0317                     break;
0318                 }
0319             }
0320         }
0321     }
0322 }
0323 
0324 #ifdef Py_GIL_DISABLED
0325 inline void enable_try_inc_ref(PyObject *obj) {
0326 #    if PY_VERSION_HEX >= 0x030E00A4
0327     PyUnstable_EnableTryIncRef(obj);
0328 #    else
0329     if (_Py_IsImmortal(obj)) {
0330         return;
0331     }
0332     for (;;) {
0333         Py_ssize_t shared = _Py_atomic_load_ssize_relaxed(&obj->ob_ref_shared);
0334         if ((shared & _Py_REF_SHARED_FLAG_MASK) != 0) {
0335             // Nothing to do if it's in WEAKREFS, QUEUED, or MERGED states.
0336             return;
0337         }
0338         if (_Py_atomic_compare_exchange_ssize(
0339                 &obj->ob_ref_shared, &shared, shared | _Py_REF_MAYBE_WEAKREF)) {
0340             return;
0341         }
0342     }
0343 #    endif
0344 }
0345 #endif
0346 
0347 inline bool register_instance_impl(void *ptr, instance *self) {
0348     assert(ptr);
0349 #ifdef Py_GIL_DISABLED
0350     enable_try_inc_ref(reinterpret_cast<PyObject *>(self));
0351 #endif
0352     with_instance_map(ptr, [&](instance_map &instances) { instances.emplace(ptr, self); });
0353     return true; // unused, but gives the same signature as the deregister func
0354 }
0355 inline bool deregister_instance_impl(void *ptr, instance *self) {
0356     assert(ptr);
0357     return with_instance_map(ptr, [&](instance_map &instances) {
0358         auto range = instances.equal_range(ptr);
0359         for (auto it = range.first; it != range.second; ++it) {
0360             if (self == it->second) {
0361                 instances.erase(it);
0362                 return true;
0363             }
0364         }
0365         return false;
0366     });
0367 }
0368 
0369 inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
0370     register_instance_impl(valptr, self);
0371     if (!tinfo->simple_ancestors) {
0372         traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
0373     }
0374 }
0375 
0376 inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
0377     bool ret = deregister_instance_impl(valptr, self);
0378     if (!tinfo->simple_ancestors) {
0379         traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
0380     }
0381     return ret;
0382 }
0383 
0384 /// Instance creation function for all pybind11 types. It allocates the internal instance layout
0385 /// for holding C++ objects and holders.  Allocation is done lazily (the first time the instance is
0386 /// cast to a reference or pointer), and initialization is done by an `__init__` function.
0387 inline PyObject *make_new_instance(PyTypeObject *type) {
0388 #if defined(PYPY_VERSION)
0389     // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
0390     // inherited object is a plain Python type (i.e. not derived from an extension type).  Fix it.
0391     ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
0392     if (type->tp_basicsize < instance_size) {
0393         type->tp_basicsize = instance_size;
0394     }
0395 #endif
0396     PyObject *self = type->tp_alloc(type, 0);
0397     auto *inst = reinterpret_cast<instance *>(self);
0398     // Allocate the value/holder internals:
0399     inst->allocate_layout();
0400 
0401     return self;
0402 }
0403 
0404 /// Instance creation function for all pybind11 types. It only allocates space for the
0405 /// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
0406 extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
0407     return make_new_instance(type);
0408 }
0409 
0410 /// An `__init__` function constructs the C++ object. Users should provide at least one
0411 /// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
0412 /// following default function will be used which simply throws an exception.
0413 extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
0414     PyTypeObject *type = Py_TYPE(self);
0415     std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
0416     set_error(PyExc_TypeError, msg.c_str());
0417     return -1;
0418 }
0419 
0420 inline void add_patient(PyObject *nurse, PyObject *patient) {
0421     auto *instance = reinterpret_cast<detail::instance *>(nurse);
0422     instance->has_patients = true;
0423     Py_INCREF(patient);
0424 
0425     with_internals([&](internals &internals) { internals.patients[nurse].push_back(patient); });
0426 }
0427 
0428 inline void clear_patients(PyObject *self) {
0429     auto *instance = reinterpret_cast<detail::instance *>(self);
0430     std::vector<PyObject *> patients;
0431 
0432     with_internals([&](internals &internals) {
0433         auto pos = internals.patients.find(self);
0434 
0435         if (pos == internals.patients.end()) {
0436             pybind11_fail(
0437                 "FATAL: Internal consistency check failed: Invalid clear_patients() call.");
0438         }
0439 
0440         // Clearing the patients can cause more Python code to run, which
0441         // can invalidate the iterator. Extract the vector of patients
0442         // from the unordered_map first.
0443         patients = std::move(pos->second);
0444         internals.patients.erase(pos);
0445     });
0446 
0447     instance->has_patients = false;
0448     for (PyObject *&patient : patients) {
0449         Py_CLEAR(patient);
0450     }
0451 }
0452 
0453 /// Clears all internal data from the instance and removes it from registered instances in
0454 /// preparation for deallocation.
0455 inline void clear_instance(PyObject *self) {
0456     auto *instance = reinterpret_cast<detail::instance *>(self);
0457 
0458     // Deallocate any values/holders, if present:
0459     for (auto &v_h : values_and_holders(instance)) {
0460         if (v_h) {
0461 
0462             // We have to deregister before we call dealloc because, for virtual MI types, we still
0463             // need to be able to get the parent pointers.
0464             if (v_h.instance_registered()
0465                 && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
0466                 pybind11_fail(
0467                     "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
0468             }
0469 
0470             if (instance->owned || v_h.holder_constructed()) {
0471                 v_h.type->dealloc(v_h);
0472             }
0473         } else if (v_h.holder_constructed()) {
0474             v_h.type->dealloc(v_h); // Disowned instance.
0475         }
0476     }
0477     // Deallocate the value/holder layout internals:
0478     instance->deallocate_layout();
0479 
0480     if (instance->weakrefs) {
0481         PyObject_ClearWeakRefs(self);
0482     }
0483 
0484     PyObject **dict_ptr = _PyObject_GetDictPtr(self);
0485     if (dict_ptr) {
0486         Py_CLEAR(*dict_ptr);
0487     }
0488 
0489     if (instance->has_patients) {
0490         clear_patients(self);
0491     }
0492 }
0493 
0494 /// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
0495 /// to destroy the C++ object itself, while the rest is Python bookkeeping.
0496 extern "C" inline void pybind11_object_dealloc(PyObject *self) {
0497     auto *type = Py_TYPE(self);
0498 
0499     // If this is a GC tracked object, untrack it first
0500     // Note that the track call is implicitly done by the
0501     // default tp_alloc, which we never override.
0502     if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) {
0503         PyObject_GC_UnTrack(self);
0504     }
0505 
0506     clear_instance(self);
0507 
0508     type->tp_free(self);
0509 
0510     // This was not needed before Python 3.8 (Python issue 35810)
0511     // https://github.com/pybind/pybind11/issues/1946
0512     Py_DECREF(type);
0513 }
0514 
0515 PYBIND11_WARNING_PUSH
0516 PYBIND11_WARNING_DISABLE_GCC("-Wredundant-decls")
0517 
0518 std::string error_string();
0519 
0520 PYBIND11_WARNING_POP
0521 
0522 /** Create the type which can be used as a common base for all classes.  This is
0523     needed in order to satisfy Python's requirements for multiple inheritance.
0524     Return value: New reference. */
0525 inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
0526     constexpr auto *name = "pybind11_object";
0527     auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
0528 
0529     /* Danger zone: from now (and until PyType_Ready), make sure to
0530        issue no Python C API calls which could potentially invoke the
0531        garbage collector (the GC will call type_traverse(), which will in
0532        turn find the newly constructed type in an invalid state) */
0533     auto *heap_type = reinterpret_cast<PyHeapTypeObject *>(metaclass->tp_alloc(metaclass, 0));
0534     if (!heap_type) {
0535         pybind11_fail("make_object_base_type(): error allocating type!");
0536     }
0537 
0538     heap_type->ht_name = name_obj.inc_ref().ptr();
0539 #ifdef PYBIND11_BUILTIN_QUALNAME
0540     heap_type->ht_qualname = name_obj.inc_ref().ptr();
0541 #endif
0542 
0543     auto *type = &heap_type->ht_type;
0544     type->tp_name = name;
0545     type->tp_base = type_incref(&PyBaseObject_Type);
0546     type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
0547     type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
0548 
0549     type->tp_new = pybind11_object_new;
0550     type->tp_init = pybind11_object_init;
0551     type->tp_dealloc = pybind11_object_dealloc;
0552 
0553     /* Support weak references (needed for the keep_alive feature) */
0554     type->tp_weaklistoffset = offsetof(instance, weakrefs);
0555 
0556     if (PyType_Ready(type) < 0) {
0557         pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
0558     }
0559 
0560     setattr(reinterpret_cast<PyObject *>(type), "__module__", str(PYBIND11_DUMMY_MODULE_NAME));
0561     PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
0562 
0563     assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
0564     return reinterpret_cast<PyObject *>(heap_type);
0565 }
0566 
0567 /// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
0568 extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
0569 #if PY_VERSION_HEX >= 0x030D0000
0570     PyObject_VisitManagedDict(self, visit, arg);
0571 #else
0572     PyObject *&dict = *_PyObject_GetDictPtr(self);
0573     Py_VISIT(dict);
0574 #endif
0575 // https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
0576 #if PY_VERSION_HEX >= 0x03090000
0577     Py_VISIT(Py_TYPE(self));
0578 #endif
0579     return 0;
0580 }
0581 
0582 /// dynamic_attr: Allow the GC to clear the dictionary.
0583 extern "C" inline int pybind11_clear(PyObject *self) {
0584 #if PY_VERSION_HEX >= 0x030D0000
0585     PyObject_ClearManagedDict(self);
0586 #else
0587     PyObject *&dict = *_PyObject_GetDictPtr(self);
0588     Py_CLEAR(dict);
0589 #endif
0590     return 0;
0591 }
0592 
0593 /// Give instances of this type a `__dict__` and opt into garbage collection.
0594 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
0595     auto *type = &heap_type->ht_type;
0596     type->tp_flags |= Py_TPFLAGS_HAVE_GC;
0597 #ifdef PYBIND11_BACKWARD_COMPATIBILITY_TP_DICTOFFSET
0598     type->tp_dictoffset = type->tp_basicsize;           // place dict at the end
0599     type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
0600 #else
0601     type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
0602 #endif
0603     type->tp_traverse = pybind11_traverse;
0604     type->tp_clear = pybind11_clear;
0605 
0606     static PyGetSetDef getset[]
0607         = {{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, nullptr, nullptr},
0608            {nullptr, nullptr, nullptr, nullptr, nullptr}};
0609     type->tp_getset = getset;
0610 }
0611 
0612 /// buffer_protocol: Fill in the view as specified by flags.
0613 extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
0614     // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
0615     type_info *tinfo = nullptr;
0616     for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
0617         tinfo = get_type_info((PyTypeObject *) type.ptr());
0618         if (tinfo && tinfo->get_buffer) {
0619             break;
0620         }
0621     }
0622     if (view == nullptr || !tinfo || !tinfo->get_buffer) {
0623         if (view) {
0624             view->obj = nullptr;
0625         }
0626         set_error(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
0627         return -1;
0628     }
0629     std::memset(view, 0, sizeof(Py_buffer));
0630     std::unique_ptr<buffer_info> info = nullptr;
0631     try {
0632         info.reset(tinfo->get_buffer(obj, tinfo->get_buffer_data));
0633     } catch (...) {
0634         try_translate_exceptions();
0635         raise_from(PyExc_BufferError, "Error getting buffer");
0636         return -1;
0637     }
0638     if (info == nullptr) {
0639         pybind11_fail("FATAL UNEXPECTED SITUATION: tinfo->get_buffer() returned nullptr.");
0640     }
0641 
0642     if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
0643         // view->obj = nullptr;  // Was just memset to 0, so not necessary
0644         set_error(PyExc_BufferError, "Writable buffer requested for readonly storage");
0645         return -1;
0646     }
0647 
0648     // Fill in all the information, and then downgrade as requested by the caller, or raise an
0649     // error if that's not possible.
0650     view->itemsize = info->itemsize;
0651     view->len = view->itemsize;
0652     for (auto s : info->shape) {
0653         view->len *= s;
0654     }
0655     view->ndim = static_cast<int>(info->ndim);
0656     view->shape = info->shape.data();
0657     view->strides = info->strides.data();
0658     view->readonly = static_cast<int>(info->readonly);
0659     if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
0660         view->format = const_cast<char *>(info->format.c_str());
0661     }
0662 
0663     // Note, all contiguity flags imply PyBUF_STRIDES and lower.
0664     if ((flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) {
0665         if (PyBuffer_IsContiguous(view, 'C') == 0) {
0666             std::memset(view, 0, sizeof(Py_buffer));
0667             set_error(PyExc_BufferError,
0668                       "C-contiguous buffer requested for discontiguous storage");
0669             return -1;
0670         }
0671     } else if ((flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) {
0672         if (PyBuffer_IsContiguous(view, 'F') == 0) {
0673             std::memset(view, 0, sizeof(Py_buffer));
0674             set_error(PyExc_BufferError,
0675                       "Fortran-contiguous buffer requested for discontiguous storage");
0676             return -1;
0677         }
0678     } else if ((flags & PyBUF_ANY_CONTIGUOUS) == PyBUF_ANY_CONTIGUOUS) {
0679         if (PyBuffer_IsContiguous(view, 'A') == 0) {
0680             std::memset(view, 0, sizeof(Py_buffer));
0681             set_error(PyExc_BufferError, "Contiguous buffer requested for discontiguous storage");
0682             return -1;
0683         }
0684 
0685     } else if ((flags & PyBUF_STRIDES) != PyBUF_STRIDES) {
0686         // If no strides are requested, the buffer must be C-contiguous.
0687         // https://docs.python.org/3/c-api/buffer.html#contiguity-requests
0688         if (PyBuffer_IsContiguous(view, 'C') == 0) {
0689             std::memset(view, 0, sizeof(Py_buffer));
0690             set_error(PyExc_BufferError,
0691                       "C-contiguous buffer requested for discontiguous storage");
0692             return -1;
0693         }
0694 
0695         view->strides = nullptr;
0696 
0697         // Since this is a contiguous buffer, it can also pretend to be 1D.
0698         if ((flags & PyBUF_ND) != PyBUF_ND) {
0699             view->shape = nullptr;
0700             view->ndim = 0;
0701         }
0702     }
0703 
0704     // Set these after all checks so they don't leak out into the caller, and can be automatically
0705     // cleaned up on error.
0706     view->buf = info->ptr;
0707     view->internal = info.release();
0708     view->obj = obj;
0709     Py_INCREF(view->obj);
0710     return 0;
0711 }
0712 
0713 /// buffer_protocol: Release the resources of the buffer.
0714 extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
0715     delete (buffer_info *) view->internal;
0716 }
0717 
0718 /// Give this type a buffer interface.
0719 inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
0720     heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
0721 
0722     heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
0723     heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
0724 }
0725 
0726 /** Create a brand new Python type according to the `type_record` specification.
0727     Return value: New reference. */
0728 inline PyObject *make_new_python_type(const type_record &rec) {
0729     auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
0730 
0731     auto qualname = name;
0732     if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
0733         qualname = reinterpret_steal<object>(
0734             PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
0735     }
0736 
0737     object module_ = get_module_name_if_available(rec.scope);
0738     const auto *full_name = c_str(
0739 #if !defined(PYPY_VERSION)
0740         module_ ? str(module_).cast<std::string>() + "." + rec.name :
0741 #endif
0742                 rec.name);
0743 
0744     char *tp_doc = nullptr;
0745     if (rec.doc && options::show_user_defined_docstrings()) {
0746         /* Allocate memory for docstring (Python will free this later on) */
0747         size_t size = std::strlen(rec.doc) + 1;
0748 #if PY_VERSION_HEX >= 0x030D0000
0749         tp_doc = static_cast<char *>(PyMem_MALLOC(size));
0750 #else
0751         tp_doc = (char *) PyObject_MALLOC(size);
0752 #endif
0753         std::memcpy((void *) tp_doc, rec.doc, size);
0754     }
0755 
0756     auto &internals = get_internals();
0757     auto bases = tuple(rec.bases);
0758     auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
0759 
0760     /* Danger zone: from now (and until PyType_Ready), make sure to
0761        issue no Python C API calls which could potentially invoke the
0762        garbage collector (the GC will call type_traverse(), which will in
0763        turn find the newly constructed type in an invalid state) */
0764     auto *metaclass = rec.metaclass.ptr() ? reinterpret_cast<PyTypeObject *>(rec.metaclass.ptr())
0765                                           : internals.default_metaclass;
0766 
0767     auto *heap_type = reinterpret_cast<PyHeapTypeObject *>(metaclass->tp_alloc(metaclass, 0));
0768     if (!heap_type) {
0769         pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
0770     }
0771 
0772     heap_type->ht_name = name.release().ptr();
0773 #ifdef PYBIND11_BUILTIN_QUALNAME
0774     heap_type->ht_qualname = qualname.inc_ref().ptr();
0775 #endif
0776 
0777     auto *type = &heap_type->ht_type;
0778     type->tp_name = full_name;
0779     type->tp_doc = tp_doc;
0780     type->tp_base = type_incref(reinterpret_cast<PyTypeObject *>(base));
0781     type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
0782     if (!bases.empty()) {
0783         type->tp_bases = bases.release().ptr();
0784     }
0785 
0786     /* Don't inherit base __init__ */
0787     type->tp_init = pybind11_object_init;
0788 
0789     /* Supported protocols */
0790     type->tp_as_number = &heap_type->as_number;
0791     type->tp_as_sequence = &heap_type->as_sequence;
0792     type->tp_as_mapping = &heap_type->as_mapping;
0793     type->tp_as_async = &heap_type->as_async;
0794 
0795     /* Flags */
0796     type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
0797     if (!rec.is_final) {
0798         type->tp_flags |= Py_TPFLAGS_BASETYPE;
0799     }
0800 
0801     if (rec.dynamic_attr) {
0802         enable_dynamic_attributes(heap_type);
0803     }
0804 
0805     if (rec.buffer_protocol) {
0806         enable_buffer_protocol(heap_type);
0807     }
0808 
0809     if (rec.custom_type_setup_callback) {
0810         rec.custom_type_setup_callback(heap_type);
0811     }
0812 
0813     if (PyType_Ready(type) < 0) {
0814         pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
0815     }
0816 
0817     assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
0818 
0819     /* Register type with the parent scope */
0820     if (rec.scope) {
0821         setattr(rec.scope, rec.name, reinterpret_cast<PyObject *>(type));
0822     } else {
0823         Py_INCREF(type); // Keep it alive forever (reference leak)
0824     }
0825 
0826     if (module_) { // Needed by pydoc
0827         setattr(reinterpret_cast<PyObject *>(type), "__module__", module_);
0828     }
0829 
0830     PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
0831 
0832     return reinterpret_cast<PyObject *>(type);
0833 }
0834 
0835 PYBIND11_NAMESPACE_END(detail)
0836 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)