1 /*
2     pybind11/detail/class.h: Python C API implementation details for py::class_
3 
4     Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5 
6     All rights reserved. Use of this source code is governed by a
7     BSD-style license that can be found in the LICENSE file.
8 */
9 
10 #pragma once
11 
12 #include "../attr.h"
13 
14 NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
NAMESPACE_BEGIN(detail)15 NAMESPACE_BEGIN(detail)
16 
17 inline PyTypeObject *type_incref(PyTypeObject *type) {
18     Py_INCREF(type);
19     return type;
20 }
21 
22 #if !defined(PYPY_VERSION)
23 
24 /// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.
pybind11_static_get(PyObject * self,PyObject *,PyObject * cls)25 extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
26     return PyProperty_Type.tp_descr_get(self, cls, cls);
27 }
28 
29 /// `pybind11_static_property.__set__()`: Just like the above `__get__()`.
pybind11_static_set(PyObject * self,PyObject * obj,PyObject * value)30 extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
31     PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
32     return PyProperty_Type.tp_descr_set(self, cls, value);
33 }
34 
35 /** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`
36     methods are modified to always use the object type instead of a concrete instance.
37     Return value: New reference. */
make_static_property_type()38 inline PyTypeObject *make_static_property_type() {
39     constexpr auto *name = "pybind11_static_property";
40     auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
41 
42     /* Danger zone: from now (and until PyType_Ready), make sure to
43        issue no Python C API calls which could potentially invoke the
44        garbage collector (the GC will call type_traverse(), which will in
45        turn find the newly constructed type in an invalid state) */
46     auto heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
47     if (!heap_type)
48         pybind11_fail("make_static_property_type(): error allocating type!");
49 
50     heap_type->ht_name = name_obj.inc_ref().ptr();
51 #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
52     heap_type->ht_qualname = name_obj.inc_ref().ptr();
53 #endif
54 
55     auto type = &heap_type->ht_type;
56     type->tp_name = name;
57     type->tp_base = type_incref(&PyProperty_Type);
58     type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
59     type->tp_descr_get = pybind11_static_get;
60     type->tp_descr_set = pybind11_static_set;
61 
62     if (PyType_Ready(type) < 0)
63         pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
64 
65     setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
66 
67     return type;
68 }
69 
70 #else // PYPY
71 
72 /** PyPy has some issues with the above C API, so we evaluate Python code instead.
73     This function will only be called once so performance isn't really a concern.
74     Return value: New reference. */
make_static_property_type()75 inline PyTypeObject *make_static_property_type() {
76     auto d = dict();
77     PyObject *result = PyRun_String(R"(\
78         class pybind11_static_property(property):
79             def __get__(self, obj, cls):
80                 return property.__get__(self, cls, cls)
81 
82             def __set__(self, obj, value):
83                 cls = obj if isinstance(obj, type) else type(obj)
84                 property.__set__(self, cls, value)
85         )", Py_file_input, d.ptr(), d.ptr()
86     );
87     if (result == nullptr)
88         throw error_already_set();
89     Py_DECREF(result);
90     return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
91 }
92 
93 #endif // PYPY
94 
95 /** Types with static properties need to handle `Type.static_prop = x` in a specific way.
96     By default, Python replaces the `static_property` itself, but for wrapped C++ types
97     we need to call `static_property.__set__()` in order to propagate the new value to
98     the underlying C++ data structure. */
pybind11_meta_setattro(PyObject * obj,PyObject * name,PyObject * value)99 extern "C" inline int pybind11_meta_setattro(PyObject* obj, PyObject* name, PyObject* value) {
100     // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
101     // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
102     PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
103 
104     // The following assignment combinations are possible:
105     //   1. `Type.static_prop = value`             --> descr_set: `Type.static_prop.__set__(value)`
106     //   2. `Type.static_prop = other_static_prop` --> setattro:  replace existing `static_prop`
107     //   3. `Type.regular_attribute = value`       --> setattro:  regular attribute assignment
108     const auto static_prop = (PyObject *) get_internals().static_property_type;
109     const auto call_descr_set = descr && PyObject_IsInstance(descr, static_prop)
110                                 && !PyObject_IsInstance(value, static_prop);
111     if (call_descr_set) {
112         // Call `static_property.__set__()` instead of replacing the `static_property`.
113 #if !defined(PYPY_VERSION)
114         return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
115 #else
116         if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
117             Py_DECREF(result);
118             return 0;
119         } else {
120             return -1;
121         }
122 #endif
123     } else {
124         // Replace existing attribute.
125         return PyType_Type.tp_setattro(obj, name, value);
126     }
127 }
128 
129 #if PY_MAJOR_VERSION >= 3
130 /**
131  * Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
132  * methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
133  * when called on a class, or a PyMethod, when called on an instance.  Override that behaviour here
134  * to do a special case bypass for PyInstanceMethod_Types.
135  */
pybind11_meta_getattro(PyObject * obj,PyObject * name)136 extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
137     PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
138     if (descr && PyInstanceMethod_Check(descr)) {
139         Py_INCREF(descr);
140         return descr;
141     }
142     else {
143         return PyType_Type.tp_getattro(obj, name);
144     }
145 }
146 #endif
147 
148 /** This metaclass is assigned by default to all pybind11 types and is required in order
149     for static properties to function correctly. Users may override this using `py::metaclass`.
150     Return value: New reference. */
make_default_metaclass()151 inline PyTypeObject* make_default_metaclass() {
152     constexpr auto *name = "pybind11_type";
153     auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
154 
155     /* Danger zone: from now (and until PyType_Ready), make sure to
156        issue no Python C API calls which could potentially invoke the
157        garbage collector (the GC will call type_traverse(), which will in
158        turn find the newly constructed type in an invalid state) */
159     auto heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
160     if (!heap_type)
161         pybind11_fail("make_default_metaclass(): error allocating metaclass!");
162 
163     heap_type->ht_name = name_obj.inc_ref().ptr();
164 #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
165     heap_type->ht_qualname = name_obj.inc_ref().ptr();
166 #endif
167 
168     auto type = &heap_type->ht_type;
169     type->tp_name = name;
170     type->tp_base = type_incref(&PyType_Type);
171     type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
172 
173     type->tp_setattro = pybind11_meta_setattro;
174 #if PY_MAJOR_VERSION >= 3
175     type->tp_getattro = pybind11_meta_getattro;
176 #endif
177 
178     if (PyType_Ready(type) < 0)
179         pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
180 
181     setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
182 
183     return type;
184 }
185 
186 /// For multiple inheritance types we need to recursively register/deregister base pointers for any
187 /// base classes with pointers that are difference from the instance value pointer so that we can
188 /// correctly recognize an offset base class pointer. This calls a function with any offset base ptrs.
traverse_offset_bases(void * valueptr,const detail::type_info * tinfo,instance * self,bool (* f)(void *,instance *))189 inline void traverse_offset_bases(void *valueptr, const detail::type_info *tinfo, instance *self,
190         bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
191     for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
192         if (auto parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
193             for (auto &c : parent_tinfo->implicit_casts) {
194                 if (c.first == tinfo->cpptype) {
195                     auto *parentptr = c.second(valueptr);
196                     if (parentptr != valueptr)
197                         f(parentptr, self);
198                     traverse_offset_bases(parentptr, parent_tinfo, self, f);
199                     break;
200                 }
201             }
202         }
203     }
204 }
205 
register_instance_impl(void * ptr,instance * self)206 inline bool register_instance_impl(void *ptr, instance *self) {
207     get_internals().registered_instances.emplace(ptr, self);
208     return true; // unused, but gives the same signature as the deregister func
209 }
deregister_instance_impl(void * ptr,instance * self)210 inline bool deregister_instance_impl(void *ptr, instance *self) {
211     auto &registered_instances = get_internals().registered_instances;
212     auto range = registered_instances.equal_range(ptr);
213     for (auto it = range.first; it != range.second; ++it) {
214         if (Py_TYPE(self) == Py_TYPE(it->second)) {
215             registered_instances.erase(it);
216             return true;
217         }
218     }
219     return false;
220 }
221 
register_instance(instance * self,void * valptr,const type_info * tinfo)222 inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
223     register_instance_impl(valptr, self);
224     if (!tinfo->simple_ancestors)
225         traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
226 }
227 
deregister_instance(instance * self,void * valptr,const type_info * tinfo)228 inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
229     bool ret = deregister_instance_impl(valptr, self);
230     if (!tinfo->simple_ancestors)
231         traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
232     return ret;
233 }
234 
235 /// Instance creation function for all pybind11 types. It allocates the internal instance layout for
236 /// holding C++ objects and holders.  Allocation is done lazily (the first time the instance is cast
237 /// to a reference or pointer), and initialization is done by an `__init__` function.
make_new_instance(PyTypeObject * type)238 inline PyObject *make_new_instance(PyTypeObject *type) {
239 #if defined(PYPY_VERSION)
240     // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first inherited
241     // object is a a plain Python type (i.e. not derived from an extension type).  Fix it.
242     ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
243     if (type->tp_basicsize < instance_size) {
244         type->tp_basicsize = instance_size;
245     }
246 #endif
247     PyObject *self = type->tp_alloc(type, 0);
248     auto inst = reinterpret_cast<instance *>(self);
249     // Allocate the value/holder internals:
250     inst->allocate_layout();
251 
252     inst->owned = true;
253 
254     return self;
255 }
256 
257 /// Instance creation function for all pybind11 types. It only allocates space for the
258 /// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
pybind11_object_new(PyTypeObject * type,PyObject *,PyObject *)259 extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
260     return make_new_instance(type);
261 }
262 
263 /// An `__init__` function constructs the C++ object. Users should provide at least one
264 /// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
265 /// following default function will be used which simply throws an exception.
pybind11_object_init(PyObject * self,PyObject *,PyObject *)266 extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
267     PyTypeObject *type = Py_TYPE(self);
268     std::string msg;
269 #if defined(PYPY_VERSION)
270     msg += handle((PyObject *) type).attr("__module__").cast<std::string>() + ".";
271 #endif
272     msg += type->tp_name;
273     msg += ": No constructor defined!";
274     PyErr_SetString(PyExc_TypeError, msg.c_str());
275     return -1;
276 }
277 
add_patient(PyObject * nurse,PyObject * patient)278 inline void add_patient(PyObject *nurse, PyObject *patient) {
279     auto &internals = get_internals();
280     auto instance = reinterpret_cast<detail::instance *>(nurse);
281     instance->has_patients = true;
282     Py_INCREF(patient);
283     internals.patients[nurse].push_back(patient);
284 }
285 
clear_patients(PyObject * self)286 inline void clear_patients(PyObject *self) {
287     auto instance = reinterpret_cast<detail::instance *>(self);
288     auto &internals = get_internals();
289     auto pos = internals.patients.find(self);
290     assert(pos != internals.patients.end());
291     // Clearing the patients can cause more Python code to run, which
292     // can invalidate the iterator. Extract the vector of patients
293     // from the unordered_map first.
294     auto patients = std::move(pos->second);
295     internals.patients.erase(pos);
296     instance->has_patients = false;
297     for (PyObject *&patient : patients)
298         Py_CLEAR(patient);
299 }
300 
301 /// Clears all internal data from the instance and removes it from registered instances in
302 /// preparation for deallocation.
clear_instance(PyObject * self)303 inline void clear_instance(PyObject *self) {
304     auto instance = reinterpret_cast<detail::instance *>(self);
305 
306     // Deallocate any values/holders, if present:
307     for (auto &v_h : values_and_holders(instance)) {
308         if (v_h) {
309 
310             // We have to deregister before we call dealloc because, for virtual MI types, we still
311             // need to be able to get the parent pointers.
312             if (v_h.instance_registered() && !deregister_instance(instance, v_h.value_ptr(), v_h.type))
313                 pybind11_fail("pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
314 
315             if (instance->owned || v_h.holder_constructed())
316                 v_h.type->dealloc(v_h);
317         }
318     }
319     // Deallocate the value/holder layout internals:
320     instance->deallocate_layout();
321 
322     if (instance->weakrefs)
323         PyObject_ClearWeakRefs(self);
324 
325     PyObject **dict_ptr = _PyObject_GetDictPtr(self);
326     if (dict_ptr)
327         Py_CLEAR(*dict_ptr);
328 
329     if (instance->has_patients)
330         clear_patients(self);
331 }
332 
333 /// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
334 /// to destroy the C++ object itself, while the rest is Python bookkeeping.
pybind11_object_dealloc(PyObject * self)335 extern "C" inline void pybind11_object_dealloc(PyObject *self) {
336     clear_instance(self);
337 
338     auto type = Py_TYPE(self);
339     type->tp_free(self);
340 
341     // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
342     // as part of a derived type's dealloc, in which case we're not allowed to decref
343     // the type here. For cross-module compatibility, we shouldn't compare directly
344     // with `pybind11_object_dealloc`, but with the common one stashed in internals.
345     auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
346     if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
347         Py_DECREF(type);
348 }
349 
350 /** Create the type which can be used as a common base for all classes.  This is
351     needed in order to satisfy Python's requirements for multiple inheritance.
352     Return value: New reference. */
make_object_base_type(PyTypeObject * metaclass)353 inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
354     constexpr auto *name = "pybind11_object";
355     auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
356 
357     /* Danger zone: from now (and until PyType_Ready), make sure to
358        issue no Python C API calls which could potentially invoke the
359        garbage collector (the GC will call type_traverse(), which will in
360        turn find the newly constructed type in an invalid state) */
361     auto heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
362     if (!heap_type)
363         pybind11_fail("make_object_base_type(): error allocating type!");
364 
365     heap_type->ht_name = name_obj.inc_ref().ptr();
366 #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
367     heap_type->ht_qualname = name_obj.inc_ref().ptr();
368 #endif
369 
370     auto type = &heap_type->ht_type;
371     type->tp_name = name;
372     type->tp_base = type_incref(&PyBaseObject_Type);
373     type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
374     type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
375 
376     type->tp_new = pybind11_object_new;
377     type->tp_init = pybind11_object_init;
378     type->tp_dealloc = pybind11_object_dealloc;
379 
380     /* Support weak references (needed for the keep_alive feature) */
381     type->tp_weaklistoffset = offsetof(instance, weakrefs);
382 
383     if (PyType_Ready(type) < 0)
384         pybind11_fail("PyType_Ready failed in make_object_base_type():" + error_string());
385 
386     setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
387 
388     assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
389     return (PyObject *) heap_type;
390 }
391 
392 /// dynamic_attr: Support for `d = instance.__dict__`.
pybind11_get_dict(PyObject * self,void *)393 extern "C" inline PyObject *pybind11_get_dict(PyObject *self, void *) {
394     PyObject *&dict = *_PyObject_GetDictPtr(self);
395     if (!dict)
396         dict = PyDict_New();
397     Py_XINCREF(dict);
398     return dict;
399 }
400 
401 /// dynamic_attr: Support for `instance.__dict__ = dict()`.
pybind11_set_dict(PyObject * self,PyObject * new_dict,void *)402 extern "C" inline int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *) {
403     if (!PyDict_Check(new_dict)) {
404         PyErr_Format(PyExc_TypeError, "__dict__ must be set to a dictionary, not a '%.200s'",
405                      Py_TYPE(new_dict)->tp_name);
406         return -1;
407     }
408     PyObject *&dict = *_PyObject_GetDictPtr(self);
409     Py_INCREF(new_dict);
410     Py_CLEAR(dict);
411     dict = new_dict;
412     return 0;
413 }
414 
415 /// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
pybind11_traverse(PyObject * self,visitproc visit,void * arg)416 extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
417     PyObject *&dict = *_PyObject_GetDictPtr(self);
418     Py_VISIT(dict);
419     return 0;
420 }
421 
422 /// dynamic_attr: Allow the GC to clear the dictionary.
pybind11_clear(PyObject * self)423 extern "C" inline int pybind11_clear(PyObject *self) {
424     PyObject *&dict = *_PyObject_GetDictPtr(self);
425     Py_CLEAR(dict);
426     return 0;
427 }
428 
429 /// Give instances of this type a `__dict__` and opt into garbage collection.
enable_dynamic_attributes(PyHeapTypeObject * heap_type)430 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
431     auto type = &heap_type->ht_type;
432 #if defined(PYPY_VERSION)
433     pybind11_fail(std::string(type->tp_name) + ": dynamic attributes are "
434                                                "currently not supported in "
435                                                "conjunction with PyPy!");
436 #endif
437     type->tp_flags |= Py_TPFLAGS_HAVE_GC;
438     type->tp_dictoffset = type->tp_basicsize; // place dict at the end
439     type->tp_basicsize += (ssize_t)sizeof(PyObject *); // and allocate enough space for it
440     type->tp_traverse = pybind11_traverse;
441     type->tp_clear = pybind11_clear;
442 
443     static PyGetSetDef getset[] = {
444         {const_cast<char*>("__dict__"), pybind11_get_dict, pybind11_set_dict, nullptr, nullptr},
445         {nullptr, nullptr, nullptr, nullptr, nullptr}
446     };
447     type->tp_getset = getset;
448 }
449 
450 /// buffer_protocol: Fill in the view as specified by flags.
pybind11_getbuffer(PyObject * obj,Py_buffer * view,int flags)451 extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
452     // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
453     type_info *tinfo = nullptr;
454     for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
455         tinfo = get_type_info((PyTypeObject *) type.ptr());
456         if (tinfo && tinfo->get_buffer)
457             break;
458     }
459     if (view == nullptr || obj == nullptr || !tinfo || !tinfo->get_buffer) {
460         if (view)
461             view->obj = nullptr;
462         PyErr_SetString(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
463         return -1;
464     }
465     std::memset(view, 0, sizeof(Py_buffer));
466     buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
467     view->obj = obj;
468     view->ndim = 1;
469     view->internal = info;
470     view->buf = info->ptr;
471     view->itemsize = info->itemsize;
472     view->len = view->itemsize;
473     for (auto s : info->shape)
474         view->len *= s;
475     if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
476         view->format = const_cast<char *>(info->format.c_str());
477     if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
478         view->ndim = (int) info->ndim;
479         view->strides = &info->strides[0];
480         view->shape = &info->shape[0];
481     }
482     Py_INCREF(view->obj);
483     return 0;
484 }
485 
486 /// buffer_protocol: Release the resources of the buffer.
pybind11_releasebuffer(PyObject *,Py_buffer * view)487 extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
488     delete (buffer_info *) view->internal;
489 }
490 
491 /// Give this type a buffer interface.
enable_buffer_protocol(PyHeapTypeObject * heap_type)492 inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
493     heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
494 #if PY_MAJOR_VERSION < 3
495     heap_type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
496 #endif
497 
498     heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
499     heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
500 }
501 
502 /** Create a brand new Python type according to the `type_record` specification.
503     Return value: New reference. */
make_new_python_type(const type_record & rec)504 inline PyObject* make_new_python_type(const type_record &rec) {
505     auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
506 
507 #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
508     auto ht_qualname = name;
509     if (rec.scope && hasattr(rec.scope, "__qualname__")) {
510         ht_qualname = reinterpret_steal<object>(
511             PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
512     }
513 #endif
514 
515     object module;
516     if (rec.scope) {
517         if (hasattr(rec.scope, "__module__"))
518             module = rec.scope.attr("__module__");
519         else if (hasattr(rec.scope, "__name__"))
520             module = rec.scope.attr("__name__");
521     }
522 
523     auto full_name = c_str(
524 #if !defined(PYPY_VERSION)
525         module ? str(module).cast<std::string>() + "." + rec.name :
526 #endif
527         rec.name);
528 
529     char *tp_doc = nullptr;
530     if (rec.doc && options::show_user_defined_docstrings()) {
531         /* Allocate memory for docstring (using PyObject_MALLOC, since
532            Python will free this later on) */
533         size_t size = strlen(rec.doc) + 1;
534         tp_doc = (char *) PyObject_MALLOC(size);
535         memcpy((void *) tp_doc, rec.doc, size);
536     }
537 
538     auto &internals = get_internals();
539     auto bases = tuple(rec.bases);
540     auto base = (bases.size() == 0) ? internals.instance_base
541                                     : bases[0].ptr();
542 
543     /* Danger zone: from now (and until PyType_Ready), make sure to
544        issue no Python C API calls which could potentially invoke the
545        garbage collector (the GC will call type_traverse(), which will in
546        turn find the newly constructed type in an invalid state) */
547     auto metaclass = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr()
548                                          : internals.default_metaclass;
549 
550     auto heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
551     if (!heap_type)
552         pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
553 
554     heap_type->ht_name = name.release().ptr();
555 #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
556     heap_type->ht_qualname = ht_qualname.release().ptr();
557 #endif
558 
559     auto type = &heap_type->ht_type;
560     type->tp_name = full_name;
561     type->tp_doc = tp_doc;
562     type->tp_base = type_incref((PyTypeObject *)base);
563     type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
564     if (bases.size() > 0)
565         type->tp_bases = bases.release().ptr();
566 
567     /* Don't inherit base __init__ */
568     type->tp_init = pybind11_object_init;
569 
570     /* Supported protocols */
571     type->tp_as_number = &heap_type->as_number;
572     type->tp_as_sequence = &heap_type->as_sequence;
573     type->tp_as_mapping = &heap_type->as_mapping;
574 
575     /* Flags */
576     type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
577 #if PY_MAJOR_VERSION < 3
578     type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
579 #endif
580 
581     if (rec.dynamic_attr)
582         enable_dynamic_attributes(heap_type);
583 
584     if (rec.buffer_protocol)
585         enable_buffer_protocol(heap_type);
586 
587     if (PyType_Ready(type) < 0)
588         pybind11_fail(std::string(rec.name) + ": PyType_Ready failed (" + error_string() + ")!");
589 
590     assert(rec.dynamic_attr ? PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC)
591                             : !PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
592 
593     /* Register type with the parent scope */
594     if (rec.scope)
595         setattr(rec.scope, rec.name, (PyObject *) type);
596     else
597         Py_INCREF(type); // Keep it alive forever (reference leak)
598 
599     if (module) // Needed by pydoc
600         setattr((PyObject *) type, "__module__", module);
601 
602     return (PyObject *) type;
603 }
604 
605 NAMESPACE_END(detail)
606 NAMESPACE_END(PYBIND11_NAMESPACE)
607