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