blob: bf07188b4fe6b43ce2152029bb417fb9a69d8dcc [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00004#include "frameobject.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum9923ffe2002-06-04 19:52:53 +00007#include <ctype.h>
8
Guido van Rossum6f799372001-09-20 20:46:19 +00009static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000010 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
11 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
12 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000013 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000014 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
15 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
16 {"__dictoffset__", T_LONG,
17 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000018 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +000025 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +000026
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000027 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000028 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000029
Georg Brandlc255c7b2006-02-20 22:27:28 +000030 Py_INCREF(et->ht_name);
31 return et->ht_name;
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000032 }
33 else {
34 s = strrchr(type->tp_name, '.');
35 if (s == NULL)
36 s = type->tp_name;
37 else
38 s++;
Martin v. Löwis5b222132007-06-10 09:51:05 +000039 return PyUnicode_FromString(s);
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000040 }
Guido van Rossumc3542212001-08-16 09:18:56 +000041}
42
Michael W. Hudson98bbc492002-11-26 14:47:27 +000043static int
44type_set_name(PyTypeObject *type, PyObject *value, void *context)
45{
Guido van Rossume5c691a2003-03-07 15:13:17 +000046 PyHeapTypeObject* et;
Neal Norwitz80e7f272007-08-26 06:45:23 +000047 char *tp_name;
Guido van Rossume845c0f2007-11-02 23:07:07 +000048 PyObject *tmp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000049
50 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
51 PyErr_Format(PyExc_TypeError,
52 "can't set %s.__name__", type->tp_name);
53 return -1;
54 }
55 if (!value) {
56 PyErr_Format(PyExc_TypeError,
57 "can't delete %s.__name__", type->tp_name);
58 return -1;
59 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +000060 if (!PyUnicode_Check(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +000061 PyErr_Format(PyExc_TypeError,
62 "can only assign string to %s.__name__, not '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +000063 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 return -1;
65 }
Guido van Rossume845c0f2007-11-02 23:07:07 +000066
67 /* Check absence of null characters */
68 tmp = PyUnicode_FromStringAndSize("\0", 1);
69 if (tmp == NULL)
Neal Norwitz6ea45d32007-08-26 04:19:43 +000070 return -1;
Guido van Rossume845c0f2007-11-02 23:07:07 +000071 if (PyUnicode_Contains(value, tmp) != 0) {
72 Py_DECREF(tmp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +000073 PyErr_Format(PyExc_ValueError,
74 "__name__ must not contain null bytes");
75 return -1;
76 }
Guido van Rossume845c0f2007-11-02 23:07:07 +000077 Py_DECREF(tmp);
78
79 tp_name = PyUnicode_AsString(value);
80 if (tp_name == NULL)
81 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000082
Guido van Rossume5c691a2003-03-07 15:13:17 +000083 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000084
85 Py_INCREF(value);
86
Georg Brandlc255c7b2006-02-20 22:27:28 +000087 Py_DECREF(et->ht_name);
88 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000089
Neal Norwitz80e7f272007-08-26 06:45:23 +000090 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000091
92 return 0;
93}
94
Guido van Rossumc3542212001-08-16 09:18:56 +000095static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000096type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000097{
Guido van Rossumc3542212001-08-16 09:18:56 +000098 PyObject *mod;
99 char *s;
100
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000101 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
102 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +0000103 if (!mod) {
104 PyErr_Format(PyExc_AttributeError, "__module__");
105 return 0;
106 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000107 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000108 return mod;
109 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000110 else {
111 s = strrchr(type->tp_name, '.');
112 if (s != NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +0000113 return PyUnicode_FromStringAndSize(
Thomas Wouters89f507f2006-12-13 04:49:30 +0000114 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Georg Brandl1a3284e2007-12-02 09:40:06 +0000115 return PyUnicode_FromString("builtins");
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000116 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000117}
118
Guido van Rossum3926a632001-09-25 16:25:58 +0000119static int
120type_set_module(PyTypeObject *type, PyObject *value, void *context)
121{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000122 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000123 PyErr_Format(PyExc_TypeError,
124 "can't set %s.__module__", type->tp_name);
125 return -1;
126 }
127 if (!value) {
128 PyErr_Format(PyExc_TypeError,
129 "can't delete %s.__module__", type->tp_name);
130 return -1;
131 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000132
Guido van Rossum3926a632001-09-25 16:25:58 +0000133 return PyDict_SetItemString(type->tp_dict, "__module__", value);
134}
135
Tim Peters6d6c1a32001-08-02 04:15:00 +0000136static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000137type_get_bases(PyTypeObject *type, void *context)
138{
139 Py_INCREF(type->tp_bases);
140 return type->tp_bases;
141}
142
143static PyTypeObject *best_base(PyObject *);
144static int mro_internal(PyTypeObject *);
145static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
146static int add_subclass(PyTypeObject*, PyTypeObject*);
147static void remove_subclass(PyTypeObject *, PyTypeObject *);
148static void update_all_slots(PyTypeObject *);
149
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000150typedef int (*update_callback)(PyTypeObject *, void *);
151static int update_subclasses(PyTypeObject *type, PyObject *name,
152 update_callback callback, void *data);
153static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
154 update_callback callback, void *data);
155
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000156static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000157mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000158{
159 PyTypeObject *subclass;
160 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000161 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000162
163 subclasses = type->tp_subclasses;
164 if (subclasses == NULL)
165 return 0;
166 assert(PyList_Check(subclasses));
167 n = PyList_GET_SIZE(subclasses);
168 for (i = 0; i < n; i++) {
169 ref = PyList_GET_ITEM(subclasses, i);
170 assert(PyWeakref_CheckRef(ref));
171 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
172 assert(subclass != NULL);
173 if ((PyObject *)subclass == Py_None)
174 continue;
175 assert(PyType_Check(subclass));
176 old_mro = subclass->tp_mro;
177 if (mro_internal(subclass) < 0) {
178 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000179 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000180 }
181 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000182 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000183 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000184 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000185 if (!tuple)
186 return -1;
187 if (PyList_Append(temp, tuple) < 0)
188 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000189 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000190 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000191 if (mro_subclasses(subclass, temp) < 0)
192 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000193 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000194 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000195}
196
197static int
198type_set_bases(PyTypeObject *type, PyObject *value, void *context)
199{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000200 Py_ssize_t i;
201 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000202 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000203 PyTypeObject *new_base, *old_base;
204 PyObject *old_bases, *old_mro;
205
206 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
207 PyErr_Format(PyExc_TypeError,
208 "can't set %s.__bases__", type->tp_name);
209 return -1;
210 }
211 if (!value) {
212 PyErr_Format(PyExc_TypeError,
213 "can't delete %s.__bases__", type->tp_name);
214 return -1;
215 }
216 if (!PyTuple_Check(value)) {
217 PyErr_Format(PyExc_TypeError,
218 "can only assign tuple to %s.__bases__, not %s",
Christian Heimes90aa7642007-12-19 02:45:37 +0000219 type->tp_name, Py_TYPE(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000220 return -1;
221 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000222 if (PyTuple_GET_SIZE(value) == 0) {
223 PyErr_Format(PyExc_TypeError,
224 "can only assign non-empty tuple to %s.__bases__, not ()",
225 type->tp_name);
226 return -1;
227 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000228 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
229 ob = PyTuple_GET_ITEM(value, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000230 if (!PyType_Check(ob)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000231 PyErr_Format(
232 PyExc_TypeError,
233 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +0000234 type->tp_name, Py_TYPE(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000235 return -1;
236 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000237 if (PyType_Check(ob)) {
238 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
239 PyErr_SetString(PyExc_TypeError,
240 "a __bases__ item causes an inheritance cycle");
241 return -1;
242 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000243 }
244 }
245
246 new_base = best_base(value);
247
248 if (!new_base) {
249 return -1;
250 }
251
252 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
253 return -1;
254
255 Py_INCREF(new_base);
256 Py_INCREF(value);
257
258 old_bases = type->tp_bases;
259 old_base = type->tp_base;
260 old_mro = type->tp_mro;
261
262 type->tp_bases = value;
263 type->tp_base = new_base;
264
265 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000266 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000267 }
268
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000269 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000270 if (!temp)
271 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000272
273 r = mro_subclasses(type, temp);
274
275 if (r < 0) {
276 for (i = 0; i < PyList_Size(temp); i++) {
277 PyTypeObject* cls;
278 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000279 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
280 "", 2, 2, &cls, &mro);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000281 Py_INCREF(mro);
282 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000283 cls->tp_mro = mro;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000284 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000285 }
286 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000287 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000288 }
289
290 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000291
292 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000293 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000294 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000295 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000296
297 /* for now, sod that: just remove from all old_bases,
298 add to all new_bases */
299
300 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
301 ob = PyTuple_GET_ITEM(old_bases, i);
302 if (PyType_Check(ob)) {
303 remove_subclass(
304 (PyTypeObject*)ob, type);
305 }
306 }
307
308 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
309 ob = PyTuple_GET_ITEM(value, i);
310 if (PyType_Check(ob)) {
311 if (add_subclass((PyTypeObject*)ob, type) < 0)
312 r = -1;
313 }
314 }
315
316 update_all_slots(type);
317
318 Py_DECREF(old_bases);
319 Py_DECREF(old_base);
320 Py_DECREF(old_mro);
321
322 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000323
324 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000325 Py_DECREF(type->tp_bases);
326 Py_DECREF(type->tp_base);
327 if (type->tp_mro != old_mro) {
328 Py_DECREF(type->tp_mro);
329 }
330
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000331 type->tp_bases = old_bases;
332 type->tp_base = old_base;
333 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000334
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000335 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000336}
337
338static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000339type_dict(PyTypeObject *type, void *context)
340{
341 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000342 Py_INCREF(Py_None);
343 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000344 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000345 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000346}
347
Tim Peters24008312002-03-17 18:56:20 +0000348static PyObject *
349type_get_doc(PyTypeObject *type, void *context)
350{
351 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000352 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Neal Norwitza369c5a2007-08-25 07:41:59 +0000353 return PyUnicode_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000354 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000355 if (result == NULL) {
356 result = Py_None;
357 Py_INCREF(result);
358 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000359 else if (Py_TYPE(result)->tp_descr_get) {
360 result = Py_TYPE(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000361 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000362 }
363 else {
364 Py_INCREF(result);
365 }
Tim Peters24008312002-03-17 18:56:20 +0000366 return result;
367}
368
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000369static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000370 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
371 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000372 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000373 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000374 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000375 {0}
376};
377
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000378static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000379type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000380{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000381 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000382 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000383
384 mod = type_module(type, NULL);
385 if (mod == NULL)
386 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +0000387 else if (!PyUnicode_Check(mod)) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000388 Py_DECREF(mod);
389 mod = NULL;
390 }
391 name = type_name(type, NULL);
392 if (name == NULL)
393 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000394
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000395 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
396 kind = "class";
397 else
398 kind = "type";
399
Georg Brandl1a3284e2007-12-02 09:40:06 +0000400 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
Walter Dörwald75163602007-06-11 15:47:13 +0000401 rtn = PyUnicode_FromFormat("<%s '%U.%U'>", kind, mod, name);
Guido van Rossumc3542212001-08-16 09:18:56 +0000402 else
Walter Dörwald1ab83302007-05-18 17:15:44 +0000403 rtn = PyUnicode_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000404
Guido van Rossumc3542212001-08-16 09:18:56 +0000405 Py_XDECREF(mod);
406 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000407 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000408}
409
Tim Peters6d6c1a32001-08-02 04:15:00 +0000410static PyObject *
411type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
412{
413 PyObject *obj;
414
415 if (type->tp_new == NULL) {
416 PyErr_Format(PyExc_TypeError,
417 "cannot create '%.100s' instances",
418 type->tp_name);
419 return NULL;
420 }
421
Tim Peters3f996e72001-09-13 19:18:27 +0000422 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000423 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000424 /* Ugly exception: when the call was type(something),
425 don't call tp_init on the result. */
426 if (type == &PyType_Type &&
427 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
428 (kwds == NULL ||
429 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
430 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000431 /* If the returned object is not an instance of type,
432 it won't be initialized. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000433 if (!PyType_IsSubtype(Py_TYPE(obj), type))
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000434 return obj;
Christian Heimes90aa7642007-12-19 02:45:37 +0000435 type = Py_TYPE(obj);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000436 if (type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437 type->tp_init(obj, args, kwds) < 0) {
438 Py_DECREF(obj);
439 obj = NULL;
440 }
441 }
442 return obj;
443}
444
445PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000446PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000447{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000448 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000449 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
450 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000451
452 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000453 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000455 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000456
Neil Schemenauerc806c882001-08-29 23:54:54 +0000457 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000459
Neil Schemenauerc806c882001-08-29 23:54:54 +0000460 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000461
Tim Peters6d6c1a32001-08-02 04:15:00 +0000462 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
463 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000464
Tim Peters6d6c1a32001-08-02 04:15:00 +0000465 if (type->tp_itemsize == 0)
466 PyObject_INIT(obj, type);
467 else
468 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000469
Tim Peters6d6c1a32001-08-02 04:15:00 +0000470 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000471 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000472 return obj;
473}
474
475PyObject *
476PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
477{
478 return type->tp_alloc(type, 0);
479}
480
Guido van Rossum9475a232001-10-05 20:51:39 +0000481/* Helpers for subtyping */
482
483static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000484traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
485{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000486 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000487 PyMemberDef *mp;
488
Christian Heimes90aa7642007-12-19 02:45:37 +0000489 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000490 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000491 for (i = 0; i < n; i++, mp++) {
492 if (mp->type == T_OBJECT_EX) {
493 char *addr = (char *)self + mp->offset;
494 PyObject *obj = *(PyObject **)addr;
495 if (obj != NULL) {
496 int err = visit(obj, arg);
497 if (err)
498 return err;
499 }
500 }
501 }
502 return 0;
503}
504
505static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000506subtype_traverse(PyObject *self, visitproc visit, void *arg)
507{
508 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000509 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000510
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000511 /* Find the nearest base with a different tp_traverse,
512 and traverse slots while we're at it */
Christian Heimes90aa7642007-12-19 02:45:37 +0000513 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000514 base = type;
515 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000516 if (Py_SIZE(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000517 int err = traverse_slots(base, self, visit, arg);
518 if (err)
519 return err;
520 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000521 base = base->tp_base;
522 assert(base);
523 }
524
525 if (type->tp_dictoffset != base->tp_dictoffset) {
526 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000527 if (dictptr && *dictptr)
528 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000529 }
530
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000531 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000532 /* For a heaptype, the instances count as references
Guido van Rossumd8faa362007-04-27 19:54:29 +0000533 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000534 can find cycles involving this link. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000535 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000536
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000537 if (basetraverse)
538 return basetraverse(self, visit, arg);
539 return 0;
540}
541
542static void
543clear_slots(PyTypeObject *type, PyObject *self)
544{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000545 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000546 PyMemberDef *mp;
547
Christian Heimes90aa7642007-12-19 02:45:37 +0000548 n = Py_SIZE(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000549 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000550 for (i = 0; i < n; i++, mp++) {
551 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
552 char *addr = (char *)self + mp->offset;
553 PyObject *obj = *(PyObject **)addr;
554 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000555 *(PyObject **)addr = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000556 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000557 }
558 }
559 }
560}
561
562static int
563subtype_clear(PyObject *self)
564{
565 PyTypeObject *type, *base;
566 inquiry baseclear;
567
568 /* Find the nearest base with a different tp_clear
569 and clear slots while we're at it */
Christian Heimes90aa7642007-12-19 02:45:37 +0000570 type = Py_TYPE(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000571 base = type;
572 while ((baseclear = base->tp_clear) == subtype_clear) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000573 if (Py_SIZE(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000574 clear_slots(base, self);
575 base = base->tp_base;
576 assert(base);
577 }
578
Guido van Rossuma3862092002-06-10 15:24:42 +0000579 /* There's no need to clear the instance dict (if any);
580 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000581
582 if (baseclear)
583 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000584 return 0;
585}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000586
587static void
588subtype_dealloc(PyObject *self)
589{
Guido van Rossum14227b42001-12-06 02:35:58 +0000590 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000591 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000592
Guido van Rossum22b13872002-08-06 21:41:44 +0000593 /* Extract the type; we expect it to be a heap type */
Christian Heimes90aa7642007-12-19 02:45:37 +0000594 type = Py_TYPE(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000595 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000596
Guido van Rossum22b13872002-08-06 21:41:44 +0000597 /* Test whether the type has GC exactly once */
598
599 if (!PyType_IS_GC(type)) {
600 /* It's really rare to find a dynamic type that doesn't have
601 GC; it can only happen when deriving from 'object' and not
602 adding any slots or instance variables. This allows
603 certain simplifications: there's no need to call
604 clear_slots(), or DECREF the dict, or clear weakrefs. */
605
606 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000607 if (type->tp_del) {
608 type->tp_del(self);
609 if (self->ob_refcnt > 0)
610 return;
611 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000612
613 /* Find the nearest base with a different tp_dealloc */
614 base = type;
615 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000616 assert(Py_SIZE(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000617 base = base->tp_base;
618 assert(base);
619 }
620
621 /* Call the base tp_dealloc() */
622 assert(basedealloc);
623 basedealloc(self);
624
625 /* Can't reference self beyond this point */
626 Py_DECREF(type);
627
628 /* Done */
629 return;
630 }
631
632 /* We get here only if the type has GC */
633
634 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000635 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000636 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000637 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000638 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000639 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000640 /* DO NOT restore GC tracking at this point. weakref callbacks
641 * (if any, and whether directly here or indirectly in something we
642 * call) may trigger GC, and if self is tracked at that point, it
643 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000644 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000645
Guido van Rossum59195fd2003-06-13 20:54:40 +0000646 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000647 base = type;
648 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000649 base = base->tp_base;
650 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000651 }
652
Guido van Rossumd8faa362007-04-27 19:54:29 +0000653 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000654 the finalizer (__del__), clearing slots, or clearing the instance
655 dict. */
656
Guido van Rossum1987c662003-05-29 14:29:23 +0000657 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
658 PyObject_ClearWeakRefs(self);
659
660 /* Maybe call finalizer; exit early if resurrected */
661 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000662 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000663 type->tp_del(self);
664 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000665 goto endlabel; /* resurrected */
666 else
667 _PyObject_GC_UNTRACK(self);
Thomas Woutersb2137042007-02-01 18:02:27 +0000668 /* New weakrefs could be created during the finalizer call.
669 If this occurs, clear them out without calling their
670 finalizers since they might rely on part of the object
671 being finalized that has already been destroyed. */
672 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
673 /* Modeled after GET_WEAKREFS_LISTPTR() */
674 PyWeakReference **list = (PyWeakReference **) \
675 PyObject_GET_WEAKREFS_LISTPTR(self);
676 while (*list)
677 _PyWeakref_ClearRef(*list);
678 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000679 }
680
Guido van Rossum59195fd2003-06-13 20:54:40 +0000681 /* Clear slots up to the nearest base with a different tp_dealloc */
682 base = type;
683 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000684 if (Py_SIZE(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000685 clear_slots(base, self);
686 base = base->tp_base;
687 assert(base);
688 }
689
Tim Peters6d6c1a32001-08-02 04:15:00 +0000690 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000691 if (type->tp_dictoffset && !base->tp_dictoffset) {
692 PyObject **dictptr = _PyObject_GetDictPtr(self);
693 if (dictptr != NULL) {
694 PyObject *dict = *dictptr;
695 if (dict != NULL) {
696 Py_DECREF(dict);
697 *dictptr = NULL;
698 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000699 }
700 }
701
Tim Peters0bd743c2003-11-13 22:50:00 +0000702 /* Call the base tp_dealloc(); first retrack self if
703 * basedealloc knows about gc.
704 */
705 if (PyType_IS_GC(base))
706 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000707 assert(basedealloc);
708 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000709
710 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000711 Py_DECREF(type);
712
Guido van Rossum0906e072002-08-07 20:42:09 +0000713 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000714 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000715 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000716 --_PyTrash_delete_nesting;
717
718 /* Explanation of the weirdness around the trashcan macros:
719
720 Q. What do the trashcan macros do?
721
722 A. Read the comment titled "Trashcan mechanism" in object.h.
723 For one, this explains why there must be a call to GC-untrack
Guido van Rossumd8faa362007-04-27 19:54:29 +0000724 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000725 trashcan code, the answers to the following questions don't make
726 sense.
727
728 Q. Why do we GC-untrack before the trashcan and then immediately
729 GC-track again afterward?
730
731 A. In the case that the base class is GC-aware, the base class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000732 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000733 UNTRACK macro, this will crash when the object is already
734 untracked. Because we don't know what the base class does, the
735 only safe thing is to make sure the object is tracked when we
736 call the base class dealloc. But... The trashcan begin macro
737 requires that the object is *untracked* before it is called. So
738 the dance becomes:
739
Guido van Rossumd8faa362007-04-27 19:54:29 +0000740 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000741 trashcan begin
742 GC track
743
Guido van Rossumd8faa362007-04-27 19:54:29 +0000744 Q. Why did the last question say "immediately GC-track again"?
745 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000746
Guido van Rossumd8faa362007-04-27 19:54:29 +0000747 A. Because the code *used* to re-track immediately. Bad Idea.
748 self has a refcount of 0, and if gc ever gets its hands on it
749 (which can happen if any weakref callback gets invoked), it
750 looks like trash to gc too, and gc also tries to delete self
751 then. But we're already deleting self. Double dealloction is
752 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000753
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000754 Q. Why the bizarre (net-zero) manipulation of
755 _PyTrash_delete_nesting around the trashcan macros?
756
757 A. Some base classes (e.g. list) also use the trashcan mechanism.
758 The following scenario used to be possible:
759
760 - suppose the trashcan level is one below the trashcan limit
761
762 - subtype_dealloc() is called
763
764 - the trashcan limit is not yet reached, so the trashcan level
Guido van Rossumd8faa362007-04-27 19:54:29 +0000765 is incremented and the code between trashcan begin and end is
766 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000767
768 - this destroys much of the object's contents, including its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000769 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000770
771 - basedealloc() is called; this is really list_dealloc(), or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000772 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000773
774 - the trashcan limit is now reached, so the object is put on the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000775 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000776
777 - basedealloc() returns
778
779 - subtype_dealloc() decrefs the object's type
780
781 - subtype_dealloc() returns
782
783 - later, the trashcan code starts deleting the objects from its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000784 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000785
786 - subtype_dealloc() is called *AGAIN* for the same object
787
788 - at the very least (if the destroyed slots and __dict__ don't
Guido van Rossumd8faa362007-04-27 19:54:29 +0000789 cause problems) the object's type gets decref'ed a second
790 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000791
792 The remedy is to make sure that if the code between trashcan
793 begin and end in subtype_dealloc() is called, the code between
794 trashcan begin and end in basedealloc() will also be called.
795 This is done by decrementing the level after passing into the
796 trashcan block, and incrementing it just before leaving the
797 block.
798
799 But now it's possible that a chain of objects consisting solely
800 of objects whose deallocator is subtype_dealloc() will defeat
801 the trashcan mechanism completely: the decremented level means
Guido van Rossumd8faa362007-04-27 19:54:29 +0000802 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000803 *increment* the level *before* entering the trashcan block, and
804 matchingly decrement it after leaving. This means the trashcan
805 code will trigger a little early, but that's no big deal.
806
807 Q. Are there any live examples of code in need of all this
808 complexity?
809
810 A. Yes. See SF bug 668433 for code that crashed (when Python was
811 compiled in debug mode) before the trashcan level manipulations
812 were added. For more discussion, see SF patches 581742, 575073
813 and bug 574207.
814 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000815}
816
Jeremy Hylton938ace62002-07-17 16:30:39 +0000817static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819/* type test with subclassing support */
820
821int
822PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
823{
824 PyObject *mro;
825
826 mro = a->tp_mro;
827 if (mro != NULL) {
828 /* Deal with multiple inheritance without recursion
829 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000830 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831 assert(PyTuple_Check(mro));
832 n = PyTuple_GET_SIZE(mro);
833 for (i = 0; i < n; i++) {
834 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
835 return 1;
836 }
837 return 0;
838 }
839 else {
840 /* a is not completely initilized yet; follow tp_base */
841 do {
842 if (a == b)
843 return 1;
844 a = a->tp_base;
845 } while (a != NULL);
846 return b == &PyBaseObject_Type;
847 }
848}
849
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000850/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000851 without looking in the instance dictionary
852 (so we can't use PyObject_GetAttr) but still binding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000853 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +0000854 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000855 static variable used to cache the interned Python string.
856
857 Two variants:
858
859 - lookup_maybe() returns NULL without raising an exception
860 when the _PyType_Lookup() call fails;
861
862 - lookup_method() always raises an exception upon errors.
863*/
Guido van Rossum60718732001-08-28 17:47:51 +0000864
865static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000866lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000867{
868 PyObject *res;
869
870 if (*attrobj == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000871 *attrobj = PyUnicode_InternFromString(attrstr);
Guido van Rossum60718732001-08-28 17:47:51 +0000872 if (*attrobj == NULL)
873 return NULL;
874 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000875 res = _PyType_Lookup(Py_TYPE(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000876 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000877 descrgetfunc f;
Christian Heimes90aa7642007-12-19 02:45:37 +0000878 if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +0000879 Py_INCREF(res);
880 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000881 res = f(res, self, (PyObject *)(Py_TYPE(self)));
Guido van Rossum60718732001-08-28 17:47:51 +0000882 }
883 return res;
884}
885
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000886static PyObject *
887lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
888{
889 PyObject *res = lookup_maybe(self, attrstr, attrobj);
890 if (res == NULL && !PyErr_Occurred())
891 PyErr_SetObject(PyExc_AttributeError, *attrobj);
892 return res;
893}
894
Guido van Rossum2730b132001-08-28 18:22:14 +0000895/* A variation of PyObject_CallMethod that uses lookup_method()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000896 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +0000897 as lookup_method to cache the interned name string object. */
898
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000899static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000900call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
901{
902 va_list va;
903 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000904 va_start(va, format);
905
Guido van Rossumda21c012001-10-03 00:50:18 +0000906 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000907 if (func == NULL) {
908 va_end(va);
909 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000910 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000911 return NULL;
912 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000913
914 if (format && *format)
915 args = Py_VaBuildValue(format, va);
916 else
917 args = PyTuple_New(0);
918
919 va_end(va);
920
921 if (args == NULL)
922 return NULL;
923
924 assert(PyTuple_Check(args));
925 retval = PyObject_Call(func, args, NULL);
926
927 Py_DECREF(args);
928 Py_DECREF(func);
929
930 return retval;
931}
932
933/* Clone of call_method() that returns NotImplemented when the lookup fails. */
934
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000935static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000936call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
937{
938 va_list va;
939 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000940 va_start(va, format);
941
Guido van Rossumda21c012001-10-03 00:50:18 +0000942 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000943 if (func == NULL) {
944 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000945 if (!PyErr_Occurred()) {
946 Py_INCREF(Py_NotImplemented);
947 return Py_NotImplemented;
948 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000949 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000950 }
951
952 if (format && *format)
953 args = Py_VaBuildValue(format, va);
954 else
955 args = PyTuple_New(0);
956
957 va_end(va);
958
Guido van Rossum717ce002001-09-14 16:58:08 +0000959 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000960 return NULL;
961
Guido van Rossum717ce002001-09-14 16:58:08 +0000962 assert(PyTuple_Check(args));
963 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000964
965 Py_DECREF(args);
966 Py_DECREF(func);
967
968 return retval;
969}
970
Tim Petersea7f75d2002-12-07 21:39:16 +0000971/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000972 Method resolution order algorithm C3 described in
973 "A Monotonic Superclass Linearization for Dylan",
974 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000975 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000976 (OOPSLA 1996)
977
Guido van Rossum98f33732002-11-25 21:36:54 +0000978 Some notes about the rules implied by C3:
979
Tim Petersea7f75d2002-12-07 21:39:16 +0000980 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000981 It isn't legal to repeat a class in a list of base classes.
982
983 The next three properties are the 3 constraints in "C3".
984
Tim Petersea7f75d2002-12-07 21:39:16 +0000985 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000986 If A precedes B in C's MRO, then A will precede B in the MRO of all
987 subclasses of C.
988
989 Monotonicity.
990 The MRO of a class must be an extension without reordering of the
991 MRO of each of its superclasses.
992
993 Extended Precedence Graph (EPG).
994 Linearization is consistent if there is a path in the EPG from
995 each class to all its successors in the linearization. See
996 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000997 */
998
Tim Petersea7f75d2002-12-07 21:39:16 +0000999static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001000tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001001 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001002 size = PyList_GET_SIZE(list);
1003
1004 for (j = whence+1; j < size; j++) {
1005 if (PyList_GET_ITEM(list, j) == o)
1006 return 1;
1007 }
1008 return 0;
1009}
1010
Guido van Rossum98f33732002-11-25 21:36:54 +00001011static PyObject *
1012class_name(PyObject *cls)
1013{
1014 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1015 if (name == NULL) {
1016 PyErr_Clear();
1017 Py_XDECREF(name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001018 name = PyObject_Repr(cls);
Guido van Rossum98f33732002-11-25 21:36:54 +00001019 }
1020 if (name == NULL)
1021 return NULL;
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001022 if (!PyUnicode_Check(name)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001023 Py_DECREF(name);
1024 return NULL;
1025 }
1026 return name;
1027}
1028
1029static int
1030check_duplicates(PyObject *list)
1031{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001032 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001033 /* Let's use a quadratic time algorithm,
1034 assuming that the bases lists is short.
1035 */
1036 n = PyList_GET_SIZE(list);
1037 for (i = 0; i < n; i++) {
1038 PyObject *o = PyList_GET_ITEM(list, i);
1039 for (j = i + 1; j < n; j++) {
1040 if (PyList_GET_ITEM(list, j) == o) {
1041 o = class_name(o);
1042 PyErr_Format(PyExc_TypeError,
1043 "duplicate base class %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001044 o ? PyUnicode_AsString(o) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001045 Py_XDECREF(o);
1046 return -1;
1047 }
1048 }
1049 }
1050 return 0;
1051}
1052
1053/* Raise a TypeError for an MRO order disagreement.
1054
1055 It's hard to produce a good error message. In the absence of better
1056 insight into error reporting, report the classes that were candidates
Guido van Rossumd8faa362007-04-27 19:54:29 +00001057 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001058 order in which they should be put in the MRO, but it's hard to
1059 diagnose what constraint can't be satisfied.
1060*/
1061
1062static void
1063set_mro_error(PyObject *to_merge, int *remain)
1064{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001065 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001066 char buf[1000];
1067 PyObject *k, *v;
1068 PyObject *set = PyDict_New();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001069 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001070
1071 to_merge_size = PyList_GET_SIZE(to_merge);
1072 for (i = 0; i < to_merge_size; i++) {
1073 PyObject *L = PyList_GET_ITEM(to_merge, i);
1074 if (remain[i] < PyList_GET_SIZE(L)) {
1075 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001076 if (PyDict_SetItem(set, c, Py_None) < 0) {
1077 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001078 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001079 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001080 }
1081 }
1082 n = PyDict_Size(set);
1083
Raymond Hettingerf394df42003-04-06 19:13:41 +00001084 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1085consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001086 i = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001087 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001088 PyObject *name = class_name(k);
1089 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001090 name ? PyUnicode_AsString(name) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001091 Py_XDECREF(name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001092 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001093 buf[off++] = ',';
1094 buf[off] = '\0';
1095 }
1096 }
1097 PyErr_SetString(PyExc_TypeError, buf);
1098 Py_DECREF(set);
1099}
1100
Tim Petersea7f75d2002-12-07 21:39:16 +00001101static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001102pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001103 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001104 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001105 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001106
Guido van Rossum1f121312002-11-14 19:49:16 +00001107 to_merge_size = PyList_GET_SIZE(to_merge);
1108
Guido van Rossum98f33732002-11-25 21:36:54 +00001109 /* remain stores an index into each sublist of to_merge.
1110 remain[i] is the index of the next base in to_merge[i]
1111 that is not included in acc.
1112 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001113 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001114 if (remain == NULL)
1115 return -1;
1116 for (i = 0; i < to_merge_size; i++)
1117 remain[i] = 0;
1118
1119 again:
1120 empty_cnt = 0;
1121 for (i = 0; i < to_merge_size; i++) {
1122 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001123
Guido van Rossum1f121312002-11-14 19:49:16 +00001124 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1125
1126 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1127 empty_cnt++;
1128 continue;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001129 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001130
Guido van Rossum98f33732002-11-25 21:36:54 +00001131 /* Choose next candidate for MRO.
1132
1133 The input sequences alone can determine the choice.
1134 If not, choose the class which appears in the MRO
1135 of the earliest direct superclass of the new class.
1136 */
1137
Guido van Rossum1f121312002-11-14 19:49:16 +00001138 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1139 for (j = 0; j < to_merge_size; j++) {
1140 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001141 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001142 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001143 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001144 }
1145 ok = PyList_Append(acc, candidate);
1146 if (ok < 0) {
1147 PyMem_Free(remain);
1148 return -1;
1149 }
1150 for (j = 0; j < to_merge_size; j++) {
1151 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001152 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1153 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001154 remain[j]++;
1155 }
1156 }
1157 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001158 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001159 }
1160
Guido van Rossum98f33732002-11-25 21:36:54 +00001161 if (empty_cnt == to_merge_size) {
1162 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001163 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001164 }
1165 set_mro_error(to_merge, remain);
1166 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001167 return -1;
1168}
1169
Tim Peters6d6c1a32001-08-02 04:15:00 +00001170static PyObject *
1171mro_implementation(PyTypeObject *type)
1172{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001173 Py_ssize_t i, n;
1174 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001175 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001176 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177
Guido van Rossum63517572002-06-18 16:44:57 +00001178 if(type->tp_dict == NULL) {
1179 if(PyType_Ready(type) < 0)
1180 return NULL;
1181 }
1182
Guido van Rossum98f33732002-11-25 21:36:54 +00001183 /* Find a superclass linearization that honors the constraints
1184 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001185 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001186
1187 to_merge is a list of lists, where each list is a superclass
1188 linearization implied by a base class. The last element of
1189 to_merge is the declared list of bases.
1190 */
1191
Tim Peters6d6c1a32001-08-02 04:15:00 +00001192 bases = type->tp_bases;
1193 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001194
1195 to_merge = PyList_New(n+1);
1196 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001197 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001198
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001200 PyObject *base = PyTuple_GET_ITEM(bases, i);
1201 PyObject *parentMRO;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001202 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001204 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001205 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001206 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001207
1208 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001210
1211 bases_aslist = PySequence_List(bases);
1212 if (bases_aslist == NULL) {
1213 Py_DECREF(to_merge);
1214 return NULL;
1215 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001216 /* This is just a basic sanity check. */
1217 if (check_duplicates(bases_aslist) < 0) {
1218 Py_DECREF(to_merge);
1219 Py_DECREF(bases_aslist);
1220 return NULL;
1221 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001222 PyList_SET_ITEM(to_merge, n, bases_aslist);
1223
1224 result = Py_BuildValue("[O]", (PyObject *)type);
1225 if (result == NULL) {
1226 Py_DECREF(to_merge);
1227 return NULL;
1228 }
1229
1230 ok = pmerge(result, to_merge);
1231 Py_DECREF(to_merge);
1232 if (ok < 0) {
1233 Py_DECREF(result);
1234 return NULL;
1235 }
1236
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 return result;
1238}
1239
1240static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001241mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242{
1243 PyTypeObject *type = (PyTypeObject *)self;
1244
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 return mro_implementation(type);
1246}
1247
1248static int
1249mro_internal(PyTypeObject *type)
1250{
1251 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001252 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001253
Christian Heimes90aa7642007-12-19 02:45:37 +00001254 if (Py_TYPE(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255 result = mro_implementation(type);
1256 }
1257 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001258 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001259 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001260 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001261 if (mro == NULL)
1262 return -1;
1263 result = PyObject_CallObject(mro, NULL);
1264 Py_DECREF(mro);
1265 }
1266 if (result == NULL)
1267 return -1;
1268 tuple = PySequence_Tuple(result);
1269 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001270 if (tuple == NULL)
1271 return -1;
1272 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001273 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001274 PyObject *cls;
1275 PyTypeObject *solid;
1276
1277 solid = solid_base(type);
1278
1279 len = PyTuple_GET_SIZE(tuple);
1280
1281 for (i = 0; i < len; i++) {
1282 PyTypeObject *t;
1283 cls = PyTuple_GET_ITEM(tuple, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001284 if (!PyType_Check(cls)) {
Armin Rigo037d1e02005-12-29 17:07:39 +00001285 PyErr_Format(PyExc_TypeError,
1286 "mro() returned a non-class ('%.500s')",
Christian Heimes90aa7642007-12-19 02:45:37 +00001287 Py_TYPE(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001288 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001289 return -1;
1290 }
1291 t = (PyTypeObject*)cls;
1292 if (!PyType_IsSubtype(solid, solid_base(t))) {
1293 PyErr_Format(PyExc_TypeError,
1294 "mro() returned base with unsuitable layout ('%.500s')",
1295 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001296 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001297 return -1;
1298 }
1299 }
1300 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001301 type->tp_mro = tuple;
1302 return 0;
1303}
1304
1305
1306/* Calculate the best base amongst multiple base classes.
1307 This is the first one that's on the path to the "solid base". */
1308
1309static PyTypeObject *
1310best_base(PyObject *bases)
1311{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001312 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001313 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001314 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315
1316 assert(PyTuple_Check(bases));
1317 n = PyTuple_GET_SIZE(bases);
1318 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001319 base = NULL;
1320 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001321 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001322 base_proto = PyTuple_GET_ITEM(bases, i);
Tim Petersa91e9642001-11-14 23:32:33 +00001323 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001324 PyErr_SetString(
1325 PyExc_TypeError,
1326 "bases must be types");
1327 return NULL;
1328 }
Tim Petersa91e9642001-11-14 23:32:33 +00001329 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001331 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332 return NULL;
1333 }
1334 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001335 if (winner == NULL) {
1336 winner = candidate;
1337 base = base_i;
1338 }
1339 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340 ;
1341 else if (PyType_IsSubtype(candidate, winner)) {
1342 winner = candidate;
1343 base = base_i;
1344 }
1345 else {
1346 PyErr_SetString(
1347 PyExc_TypeError,
1348 "multiple bases have "
1349 "instance lay-out conflict");
1350 return NULL;
1351 }
1352 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001353 if (base == NULL)
1354 PyErr_SetString(PyExc_TypeError,
1355 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356 return base;
1357}
1358
1359static int
1360extra_ivars(PyTypeObject *type, PyTypeObject *base)
1361{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001362 size_t t_size = type->tp_basicsize;
1363 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364
Guido van Rossum9676b222001-08-17 20:32:36 +00001365 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366 if (type->tp_itemsize || base->tp_itemsize) {
1367 /* If itemsize is involved, stricter rules */
1368 return t_size != b_size ||
1369 type->tp_itemsize != base->tp_itemsize;
1370 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001371 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001372 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1373 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001374 t_size -= sizeof(PyObject *);
1375 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001376 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1377 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001378 t_size -= sizeof(PyObject *);
1379
1380 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001381}
1382
1383static PyTypeObject *
1384solid_base(PyTypeObject *type)
1385{
1386 PyTypeObject *base;
1387
1388 if (type->tp_base)
1389 base = solid_base(type->tp_base);
1390 else
1391 base = &PyBaseObject_Type;
1392 if (extra_ivars(type, base))
1393 return type;
1394 else
1395 return base;
1396}
1397
Jeremy Hylton938ace62002-07-17 16:30:39 +00001398static void object_dealloc(PyObject *);
1399static int object_init(PyObject *, PyObject *, PyObject *);
1400static int update_slot(PyTypeObject *, PyObject *);
1401static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402
Guido van Rossum360e4b82007-05-14 22:51:27 +00001403/*
1404 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1405 * inherited from various builtin types. The builtin base usually provides
1406 * its own __dict__ descriptor, so we use that when we can.
1407 */
1408static PyTypeObject *
1409get_builtin_base_with_dict(PyTypeObject *type)
1410{
1411 while (type->tp_base != NULL) {
1412 if (type->tp_dictoffset != 0 &&
1413 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1414 return type;
1415 type = type->tp_base;
1416 }
1417 return NULL;
1418}
1419
1420static PyObject *
1421get_dict_descriptor(PyTypeObject *type)
1422{
1423 static PyObject *dict_str;
1424 PyObject *descr;
1425
1426 if (dict_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001427 dict_str = PyUnicode_InternFromString("__dict__");
Guido van Rossum360e4b82007-05-14 22:51:27 +00001428 if (dict_str == NULL)
1429 return NULL;
1430 }
1431 descr = _PyType_Lookup(type, dict_str);
1432 if (descr == NULL || !PyDescr_IsData(descr))
1433 return NULL;
1434
1435 return descr;
1436}
1437
1438static void
1439raise_dict_descr_error(PyObject *obj)
1440{
1441 PyErr_Format(PyExc_TypeError,
1442 "this __dict__ descriptor does not support "
Christian Heimes90aa7642007-12-19 02:45:37 +00001443 "'%.200s' objects", Py_TYPE(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001444}
1445
Tim Peters6d6c1a32001-08-02 04:15:00 +00001446static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001447subtype_dict(PyObject *obj, void *context)
1448{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001449 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001450 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001451 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001452
Christian Heimes90aa7642007-12-19 02:45:37 +00001453 base = get_builtin_base_with_dict(Py_TYPE(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001454 if (base != NULL) {
1455 descrgetfunc func;
1456 PyObject *descr = get_dict_descriptor(base);
1457 if (descr == NULL) {
1458 raise_dict_descr_error(obj);
1459 return NULL;
1460 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001461 func = Py_TYPE(descr)->tp_descr_get;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001462 if (func == NULL) {
1463 raise_dict_descr_error(obj);
1464 return NULL;
1465 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001466 return func(descr, obj, (PyObject *)(Py_TYPE(obj)));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001467 }
1468
1469 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001470 if (dictptr == NULL) {
1471 PyErr_SetString(PyExc_AttributeError,
1472 "This object has no __dict__");
1473 return NULL;
1474 }
1475 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001476 if (dict == NULL)
1477 *dictptr = dict = PyDict_New();
1478 Py_XINCREF(dict);
1479 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001480}
1481
Guido van Rossum6661be32001-10-26 04:26:12 +00001482static int
1483subtype_setdict(PyObject *obj, PyObject *value, void *context)
1484{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001485 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001486 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001487 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001488
Christian Heimes90aa7642007-12-19 02:45:37 +00001489 base = get_builtin_base_with_dict(Py_TYPE(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001490 if (base != NULL) {
1491 descrsetfunc func;
1492 PyObject *descr = get_dict_descriptor(base);
1493 if (descr == NULL) {
1494 raise_dict_descr_error(obj);
1495 return -1;
1496 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001497 func = Py_TYPE(descr)->tp_descr_set;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001498 if (func == NULL) {
1499 raise_dict_descr_error(obj);
1500 return -1;
1501 }
1502 return func(descr, obj, value);
1503 }
1504
1505 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001506 if (dictptr == NULL) {
1507 PyErr_SetString(PyExc_AttributeError,
1508 "This object has no __dict__");
1509 return -1;
1510 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001511 if (value != NULL && !PyDict_Check(value)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001512 PyErr_Format(PyExc_TypeError,
1513 "__dict__ must be set to a dictionary, "
Christian Heimes90aa7642007-12-19 02:45:37 +00001514 "not a '%.200s'", Py_TYPE(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001515 return -1;
1516 }
1517 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001518 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001519 *dictptr = value;
1520 Py_XDECREF(dict);
1521 return 0;
1522}
1523
Guido van Rossumad47da02002-08-12 19:05:44 +00001524static PyObject *
1525subtype_getweakref(PyObject *obj, void *context)
1526{
1527 PyObject **weaklistptr;
1528 PyObject *result;
1529
Christian Heimes90aa7642007-12-19 02:45:37 +00001530 if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001531 PyErr_SetString(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001532 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001533 return NULL;
1534 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001535 assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
1536 assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1537 (size_t)(Py_TYPE(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001538 weaklistptr = (PyObject **)
Christian Heimes90aa7642007-12-19 02:45:37 +00001539 ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001540 if (*weaklistptr == NULL)
1541 result = Py_None;
1542 else
1543 result = *weaklistptr;
1544 Py_INCREF(result);
1545 return result;
1546}
1547
Guido van Rossum373c7412003-01-07 13:41:37 +00001548/* Three variants on the subtype_getsets list. */
1549
1550static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001551 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001552 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001553 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001554 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001555 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001556};
1557
Guido van Rossum373c7412003-01-07 13:41:37 +00001558static PyGetSetDef subtype_getsets_dict_only[] = {
1559 {"__dict__", subtype_dict, subtype_setdict,
1560 PyDoc_STR("dictionary for instance variables (if defined)")},
1561 {0}
1562};
1563
1564static PyGetSetDef subtype_getsets_weakref_only[] = {
1565 {"__weakref__", subtype_getweakref, NULL,
1566 PyDoc_STR("list of weak references to the object (if defined)")},
1567 {0}
1568};
1569
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001570static int
1571valid_identifier(PyObject *s)
1572{
Martin v. Löwis5b222132007-06-10 09:51:05 +00001573 if (!PyUnicode_Check(s)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001574 PyErr_Format(PyExc_TypeError,
1575 "__slots__ items must be strings, not '%.200s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00001576 Py_TYPE(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001577 return 0;
1578 }
Georg Brandlf4780d02007-08-30 18:29:48 +00001579 if (!PyUnicode_IsIdentifier(s)) {
1580 PyErr_SetString(PyExc_TypeError,
1581 "__slots__ must be identifiers");
1582 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001583 }
1584 return 1;
1585}
1586
Guido van Rossumd8faa362007-04-27 19:54:29 +00001587/* Forward */
1588static int
1589object_init(PyObject *self, PyObject *args, PyObject *kwds);
1590
1591static int
1592type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1593{
1594 int res;
1595
1596 assert(args != NULL && PyTuple_Check(args));
1597 assert(kwds == NULL || PyDict_Check(kwds));
1598
1599 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1600 PyErr_SetString(PyExc_TypeError,
1601 "type.__init__() takes no keyword arguments");
1602 return -1;
1603 }
1604
1605 if (args != NULL && PyTuple_Check(args) &&
1606 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1607 PyErr_SetString(PyExc_TypeError,
1608 "type.__init__() takes 1 or 3 arguments");
1609 return -1;
1610 }
1611
1612 /* Call object.__init__(self) now. */
1613 /* XXX Could call super(type, cls).__init__() but what's the point? */
1614 args = PyTuple_GetSlice(args, 0, 0);
1615 res = object_init(cls, args, NULL);
1616 Py_DECREF(args);
1617 return res;
1618}
1619
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001620static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001621type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1622{
1623 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001624 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001625 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001626 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001627 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001628 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001629 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001630 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631
Tim Peters3abca122001-10-27 19:37:48 +00001632 assert(args != NULL && PyTuple_Check(args));
1633 assert(kwds == NULL || PyDict_Check(kwds));
1634
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001635 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001636 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001637 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1638 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001639
1640 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1641 PyObject *x = PyTuple_GET_ITEM(args, 0);
Christian Heimes90aa7642007-12-19 02:45:37 +00001642 Py_INCREF(Py_TYPE(x));
1643 return (PyObject *) Py_TYPE(x);
Tim Peters3abca122001-10-27 19:37:48 +00001644 }
1645
1646 /* SF bug 475327 -- if that didn't trigger, we need 3
1647 arguments. but PyArg_ParseTupleAndKeywords below may give
1648 a msg saying type() needs exactly 3. */
1649 if (nargs + nkwds != 3) {
1650 PyErr_SetString(PyExc_TypeError,
1651 "type() takes 1 or 3 arguments");
1652 return NULL;
1653 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001654 }
1655
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001656 /* Check arguments: (name, bases, dict) */
Guido van Rossum98297ee2007-11-06 21:34:58 +00001657 if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001658 &name,
1659 &PyTuple_Type, &bases,
1660 &PyDict_Type, &dict))
1661 return NULL;
1662
1663 /* Determine the proper metatype to deal with this,
1664 and check for metatype conflicts while we're at it.
1665 Note that if some other metatype wins to contract,
1666 it's possible that its instances are not types. */
1667 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001668 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001669 for (i = 0; i < nbases; i++) {
1670 tmp = PyTuple_GET_ITEM(bases, i);
Christian Heimes90aa7642007-12-19 02:45:37 +00001671 tmptype = Py_TYPE(tmp);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001672 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001673 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001674 if (PyType_IsSubtype(tmptype, winner)) {
1675 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001676 continue;
1677 }
1678 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001679 "metaclass conflict: "
1680 "the metaclass of a derived class "
1681 "must be a (non-strict) subclass "
1682 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001683 return NULL;
1684 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001685 if (winner != metatype) {
1686 if (winner->tp_new != type_new) /* Pass it to the winner */
1687 return winner->tp_new(winner, args, kwds);
1688 metatype = winner;
1689 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690
1691 /* Adjust for empty tuple bases */
1692 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001693 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001694 if (bases == NULL)
1695 return NULL;
1696 nbases = 1;
1697 }
1698 else
1699 Py_INCREF(bases);
1700
1701 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1702
1703 /* Calculate best base, and check that all bases are type objects */
1704 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001705 if (base == NULL) {
1706 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001707 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001708 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001709 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1710 PyErr_Format(PyExc_TypeError,
1711 "type '%.100s' is not an acceptable base type",
1712 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001713 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001714 return NULL;
1715 }
1716
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717 /* Check for a __slots__ sequence variable in dict, and count it */
1718 slots = PyDict_GetItemString(dict, "__slots__");
1719 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001720 add_dict = 0;
1721 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001722 may_add_dict = base->tp_dictoffset == 0;
1723 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1724 if (slots == NULL) {
1725 if (may_add_dict) {
1726 add_dict++;
1727 }
1728 if (may_add_weak) {
1729 add_weak++;
1730 }
1731 }
1732 else {
1733 /* Have slots */
1734
Tim Peters6d6c1a32001-08-02 04:15:00 +00001735 /* Make it into a tuple */
Neal Norwitz80e7f272007-08-26 06:45:23 +00001736 if (PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001737 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001738 else
1739 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001740 if (slots == NULL) {
1741 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001742 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001743 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001744 assert(PyTuple_Check(slots));
1745
1746 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001747 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001748 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001749 PyErr_Format(PyExc_TypeError,
1750 "nonempty __slots__ "
1751 "not supported for subtype of '%s'",
1752 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001753 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001754 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001755 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001756 return NULL;
1757 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001758
1759 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001760 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001761 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001762 if (!valid_identifier(tmp))
1763 goto bad_slots;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001764 assert(PyUnicode_Check(tmp));
1765 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001766 if (!may_add_dict || add_dict) {
1767 PyErr_SetString(PyExc_TypeError,
1768 "__dict__ slot disallowed: "
1769 "we already got one");
1770 goto bad_slots;
1771 }
1772 add_dict++;
1773 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00001774 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001775 if (!may_add_weak || add_weak) {
1776 PyErr_SetString(PyExc_TypeError,
1777 "__weakref__ slot disallowed: "
1778 "either we already got one, "
1779 "or __itemsize__ != 0");
1780 goto bad_slots;
1781 }
1782 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783 }
1784 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001785
Guido van Rossumd8faa362007-04-27 19:54:29 +00001786 /* Copy slots into a list, mangle names and sort them.
1787 Sorted names are needed for __class__ assignment.
1788 Convert them back to tuple at the end.
1789 */
1790 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001791 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001792 goto bad_slots;
1793 for (i = j = 0; i < nslots; i++) {
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001794 tmp = PyTuple_GET_ITEM(slots, i);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001795 if ((add_dict &&
1796 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
1797 (add_weak &&
1798 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
Guido van Rossumad47da02002-08-12 19:05:44 +00001799 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800 tmp =_Py_Mangle(name, tmp);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001801 if (!tmp)
1802 goto bad_slots;
1803 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00001804 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001805 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001806 assert(j == nslots - add_dict - add_weak);
1807 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001808 Py_DECREF(slots);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001809 if (PyList_Sort(newslots) == -1) {
1810 Py_DECREF(bases);
1811 Py_DECREF(newslots);
1812 return NULL;
1813 }
1814 slots = PyList_AsTuple(newslots);
1815 Py_DECREF(newslots);
1816 if (slots == NULL) {
1817 Py_DECREF(bases);
1818 return NULL;
1819 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001820
Guido van Rossumad47da02002-08-12 19:05:44 +00001821 /* Secondary bases may provide weakrefs or dict */
1822 if (nbases > 1 &&
1823 ((may_add_dict && !add_dict) ||
1824 (may_add_weak && !add_weak))) {
1825 for (i = 0; i < nbases; i++) {
1826 tmp = PyTuple_GET_ITEM(bases, i);
1827 if (tmp == (PyObject *)base)
1828 continue; /* Skip primary base */
Guido van Rossumad47da02002-08-12 19:05:44 +00001829 assert(PyType_Check(tmp));
1830 tmptype = (PyTypeObject *)tmp;
1831 if (may_add_dict && !add_dict &&
1832 tmptype->tp_dictoffset != 0)
1833 add_dict++;
1834 if (may_add_weak && !add_weak &&
1835 tmptype->tp_weaklistoffset != 0)
1836 add_weak++;
1837 if (may_add_dict && !add_dict)
1838 continue;
1839 if (may_add_weak && !add_weak)
1840 continue;
1841 /* Nothing more to check */
1842 break;
1843 }
1844 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001845 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001846
1847 /* XXX From here until type is safely allocated,
1848 "return NULL" may leak slots! */
1849
1850 /* Allocate the type object */
1851 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001852 if (type == NULL) {
1853 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001854 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001856 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001857
1858 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001859 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001860 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001861 et->ht_name = name;
1862 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001863
Guido van Rossumdc91b992001-08-08 22:26:22 +00001864 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1866 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001867 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1868 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001869
Guido van Rossumdc91b992001-08-08 22:26:22 +00001870 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001871 type->tp_as_number = &et->as_number;
1872 type->tp_as_sequence = &et->as_sequence;
1873 type->tp_as_mapping = &et->as_mapping;
1874 type->tp_as_buffer = &et->as_buffer;
Neal Norwitz80e7f272007-08-26 06:45:23 +00001875 type->tp_name = PyUnicode_AsString(name);
1876 if (!type->tp_name) {
1877 Py_DECREF(type);
1878 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001879 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001880
1881 /* Set tp_base and tp_bases */
1882 type->tp_bases = bases;
1883 Py_INCREF(base);
1884 type->tp_base = base;
1885
Guido van Rossum687ae002001-10-15 22:03:32 +00001886 /* Initialize tp_dict from passed-in dict */
1887 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888 if (dict == NULL) {
1889 Py_DECREF(type);
1890 return NULL;
1891 }
1892
Guido van Rossumc3542212001-08-16 09:18:56 +00001893 /* Set __module__ in the dict */
1894 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1895 tmp = PyEval_GetGlobals();
1896 if (tmp != NULL) {
1897 tmp = PyDict_GetItemString(tmp, "__name__");
1898 if (tmp != NULL) {
1899 if (PyDict_SetItemString(dict, "__module__",
1900 tmp) < 0)
1901 return NULL;
1902 }
1903 }
1904 }
1905
Tim Peters2f93e282001-10-04 05:27:00 +00001906 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001907 and is a string. The __doc__ accessor will first look for tp_doc;
1908 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001909 */
1910 {
1911 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001912 if (doc != NULL && PyUnicode_Check(doc)) {
Neal Norwitza369c5a2007-08-25 07:41:59 +00001913 size_t n;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001914 char *tp_doc;
1915 const char *str = PyUnicode_AsString(doc);
1916 if (str == NULL) {
1917 Py_DECREF(type);
1918 return NULL;
Tim Peters2f93e282001-10-04 05:27:00 +00001919 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001920 n = strlen(str);
1921 tp_doc = (char *)PyObject_MALLOC(n+1);
1922 if (tp_doc == NULL) {
1923 Py_DECREF(type);
1924 return NULL;
Neal Norwitza369c5a2007-08-25 07:41:59 +00001925 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001926 memcpy(tp_doc, str, n+1);
1927 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001928 }
1929 }
1930
Tim Peters6d6c1a32001-08-02 04:15:00 +00001931 /* Special-case __new__: if it's a plain function,
1932 make it a static function */
1933 tmp = PyDict_GetItemString(dict, "__new__");
1934 if (tmp != NULL && PyFunction_Check(tmp)) {
1935 tmp = PyStaticMethod_New(tmp);
1936 if (tmp == NULL) {
1937 Py_DECREF(type);
1938 return NULL;
1939 }
1940 PyDict_SetItemString(dict, "__new__", tmp);
1941 Py_DECREF(tmp);
1942 }
1943
1944 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001945 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001946 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001947 if (slots != NULL) {
1948 for (i = 0; i < nslots; i++, mp++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001949 mp->name = PyUnicode_AsString(
Tim Peters6d6c1a32001-08-02 04:15:00 +00001950 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001951 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001953
1954 /* __dict__ and __weakref__ are already filtered out */
1955 assert(strcmp(mp->name, "__dict__") != 0);
1956 assert(strcmp(mp->name, "__weakref__") != 0);
1957
Tim Peters6d6c1a32001-08-02 04:15:00 +00001958 slotoffset += sizeof(PyObject *);
1959 }
1960 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001961 if (add_dict) {
1962 if (base->tp_itemsize)
1963 type->tp_dictoffset = -(long)sizeof(PyObject *);
1964 else
1965 type->tp_dictoffset = slotoffset;
1966 slotoffset += sizeof(PyObject *);
1967 }
1968 if (add_weak) {
1969 assert(!base->tp_itemsize);
1970 type->tp_weaklistoffset = slotoffset;
1971 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972 }
1973 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001974 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001975 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001976
1977 if (type->tp_weaklistoffset && type->tp_dictoffset)
1978 type->tp_getset = subtype_getsets_full;
1979 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1980 type->tp_getset = subtype_getsets_weakref_only;
1981 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1982 type->tp_getset = subtype_getsets_dict_only;
1983 else
1984 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001985
1986 /* Special case some slots */
1987 if (type->tp_dictoffset != 0 || nslots > 0) {
1988 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1989 type->tp_getattro = PyObject_GenericGetAttr;
1990 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1991 type->tp_setattro = PyObject_GenericSetAttr;
1992 }
1993 type->tp_dealloc = subtype_dealloc;
1994
Guido van Rossum9475a232001-10-05 20:51:39 +00001995 /* Enable GC unless there are really no instance variables possible */
1996 if (!(type->tp_basicsize == sizeof(PyObject) &&
1997 type->tp_itemsize == 0))
1998 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1999
Tim Peters6d6c1a32001-08-02 04:15:00 +00002000 /* Always override allocation strategy to use regular heap */
2001 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002002 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002003 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002004 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002005 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002006 }
2007 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002008 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009
2010 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002011 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012 Py_DECREF(type);
2013 return NULL;
2014 }
2015
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002016 /* Put the proper slots in place */
2017 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002018
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019 return (PyObject *)type;
2020}
2021
2022/* Internal API to look for a name through the MRO.
2023 This returns a borrowed reference, and doesn't set an exception! */
2024PyObject *
2025_PyType_Lookup(PyTypeObject *type, PyObject *name)
2026{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002027 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002028 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029
Guido van Rossum687ae002001-10-15 22:03:32 +00002030 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002032
2033 /* If mro is NULL, the type is either not yet initialized
2034 by PyType_Ready(), or already cleared by type_clear().
2035 Either way the safest thing to do is to return NULL. */
2036 if (mro == NULL)
2037 return NULL;
2038
Tim Peters6d6c1a32001-08-02 04:15:00 +00002039 assert(PyTuple_Check(mro));
2040 n = PyTuple_GET_SIZE(mro);
2041 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002042 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002043 assert(PyType_Check(base));
2044 dict = ((PyTypeObject *)base)->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045 assert(dict && PyDict_Check(dict));
2046 res = PyDict_GetItem(dict, name);
2047 if (res != NULL)
2048 return res;
2049 }
2050 return NULL;
2051}
2052
2053/* This is similar to PyObject_GenericGetAttr(),
2054 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2055static PyObject *
2056type_getattro(PyTypeObject *type, PyObject *name)
2057{
Christian Heimes90aa7642007-12-19 02:45:37 +00002058 PyTypeObject *metatype = Py_TYPE(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002059 PyObject *meta_attribute, *attribute;
2060 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002061
2062 /* Initialize this type (we'll assume the metatype is initialized) */
2063 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002064 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065 return NULL;
2066 }
2067
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002068 /* No readable descriptor found yet */
2069 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002070
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002071 /* Look for the attribute in the metatype */
2072 meta_attribute = _PyType_Lookup(metatype, name);
2073
2074 if (meta_attribute != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002075 meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002076
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002077 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2078 /* Data descriptors implement tp_descr_set to intercept
2079 * writes. Assume the attribute is not overridden in
2080 * type's tp_dict (and bases): call the descriptor now.
2081 */
2082 return meta_get(meta_attribute, (PyObject *)type,
2083 (PyObject *)metatype);
2084 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002085 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002086 }
2087
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002088 /* No data descriptor found on metatype. Look in tp_dict of this
2089 * type and its bases */
2090 attribute = _PyType_Lookup(type, name);
2091 if (attribute != NULL) {
2092 /* Implement descriptor functionality, if any */
Christian Heimes90aa7642007-12-19 02:45:37 +00002093 descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002094
2095 Py_XDECREF(meta_attribute);
2096
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002097 if (local_get != NULL) {
2098 /* NULL 2nd argument indicates the descriptor was
2099 * found on the target object itself (or a base) */
2100 return local_get(attribute, (PyObject *)NULL,
2101 (PyObject *)type);
2102 }
Tim Peters34592512002-07-11 06:23:50 +00002103
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002104 Py_INCREF(attribute);
2105 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106 }
2107
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002108 /* No attribute found in local __dict__ (or bases): use the
2109 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002110 if (meta_get != NULL) {
2111 PyObject *res;
2112 res = meta_get(meta_attribute, (PyObject *)type,
2113 (PyObject *)metatype);
2114 Py_DECREF(meta_attribute);
2115 return res;
2116 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002117
2118 /* If an ordinary attribute was found on the metatype, return it now */
2119 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002120 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002121 }
2122
2123 /* Give up */
2124 PyErr_Format(PyExc_AttributeError,
Walter Dörwald75163602007-06-11 15:47:13 +00002125 "type object '%.50s' has no attribute '%U'",
2126 type->tp_name, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002127 return NULL;
2128}
2129
2130static int
2131type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2132{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002133 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2134 PyErr_Format(
2135 PyExc_TypeError,
2136 "can't set attributes of built-in/extension type '%s'",
2137 type->tp_name);
2138 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002139 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002140 /* XXX Example of how I expect this to be used...
2141 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2142 return -1;
2143 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002144 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2145 return -1;
2146 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002147}
2148
2149static void
2150type_dealloc(PyTypeObject *type)
2151{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002152 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002153
2154 /* Assert this is a heap-allocated type object */
2155 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002156 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002157 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002158 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002159 Py_XDECREF(type->tp_base);
2160 Py_XDECREF(type->tp_dict);
2161 Py_XDECREF(type->tp_bases);
2162 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002163 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002164 Py_XDECREF(type->tp_subclasses);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002165 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2166 * of most other objects. It's okay to cast it to char *.
2167 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002168 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002169 Py_XDECREF(et->ht_name);
2170 Py_XDECREF(et->ht_slots);
Christian Heimes90aa7642007-12-19 02:45:37 +00002171 Py_TYPE(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002172}
2173
Guido van Rossum1c450732001-10-08 15:18:27 +00002174static PyObject *
2175type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2176{
2177 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002178 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002179
2180 list = PyList_New(0);
2181 if (list == NULL)
2182 return NULL;
2183 raw = type->tp_subclasses;
2184 if (raw == NULL)
2185 return list;
2186 assert(PyList_Check(raw));
2187 n = PyList_GET_SIZE(raw);
2188 for (i = 0; i < n; i++) {
2189 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002190 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002191 ref = PyWeakref_GET_OBJECT(ref);
2192 if (ref != Py_None) {
2193 if (PyList_Append(list, ref) < 0) {
2194 Py_DECREF(list);
2195 return NULL;
2196 }
2197 }
2198 }
2199 return list;
2200}
2201
Guido van Rossum47374822007-08-02 16:48:17 +00002202static PyObject *
2203type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2204{
2205 return PyDict_New();
2206}
2207
Tim Peters6d6c1a32001-08-02 04:15:00 +00002208static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002209 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002210 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002211 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002212 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Guido van Rossum47374822007-08-02 16:48:17 +00002213 {"__prepare__", (PyCFunction)type_prepare,
2214 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2215 PyDoc_STR("__prepare__() -> dict\n"
2216 "used to create the namespace for the class statement")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002217 {0}
2218};
2219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002220PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002221"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002222"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002223
Guido van Rossum048eb752001-10-02 21:24:57 +00002224static int
2225type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2226{
Guido van Rossuma3862092002-06-10 15:24:42 +00002227 /* Because of type_is_gc(), the collector only calls this
2228 for heaptypes. */
2229 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002230
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002231 Py_VISIT(type->tp_dict);
2232 Py_VISIT(type->tp_cache);
2233 Py_VISIT(type->tp_mro);
2234 Py_VISIT(type->tp_bases);
2235 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002236
2237 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002238 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002239 in cycles; tp_subclasses is a list of weak references,
2240 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002241
Guido van Rossum048eb752001-10-02 21:24:57 +00002242 return 0;
2243}
2244
2245static int
2246type_clear(PyTypeObject *type)
2247{
Guido van Rossuma3862092002-06-10 15:24:42 +00002248 /* Because of type_is_gc(), the collector only calls this
2249 for heaptypes. */
2250 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002251
Guido van Rossuma3862092002-06-10 15:24:42 +00002252 /* The only field we need to clear is tp_mro, which is part of a
2253 hard cycle (its first element is the class itself) that won't
2254 be broken otherwise (it's a tuple and tuples don't have a
2255 tp_clear handler). None of the other fields need to be
2256 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002257
Guido van Rossuma3862092002-06-10 15:24:42 +00002258 tp_dict:
2259 It is a dict, so the collector will call its tp_clear.
2260
2261 tp_cache:
2262 Not used; if it were, it would be a dict.
2263
2264 tp_bases, tp_base:
2265 If these are involved in a cycle, there must be at least
2266 one other, mutable object in the cycle, e.g. a base
2267 class's dict; the cycle will be broken that way.
2268
2269 tp_subclasses:
2270 A list of weak references can't be part of a cycle; and
2271 lists have their own tp_clear.
2272
Guido van Rossume5c691a2003-03-07 15:13:17 +00002273 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002274 A tuple of strings can't be part of a cycle.
2275 */
2276
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002277 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002278
2279 return 0;
2280}
2281
2282static int
2283type_is_gc(PyTypeObject *type)
2284{
2285 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2286}
2287
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002288PyTypeObject PyType_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002289 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002290 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002291 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002292 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002293 (destructor)type_dealloc, /* tp_dealloc */
2294 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002295 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002296 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002297 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002298 (reprfunc)type_repr, /* tp_repr */
2299 0, /* tp_as_number */
2300 0, /* tp_as_sequence */
2301 0, /* tp_as_mapping */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002302 0, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002303 (ternaryfunc)type_call, /* tp_call */
2304 0, /* tp_str */
2305 (getattrofunc)type_getattro, /* tp_getattro */
2306 (setattrofunc)type_setattro, /* tp_setattro */
2307 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002308 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002309 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002310 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002311 (traverseproc)type_traverse, /* tp_traverse */
2312 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002313 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002314 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315 0, /* tp_iter */
2316 0, /* tp_iternext */
2317 type_methods, /* tp_methods */
2318 type_members, /* tp_members */
2319 type_getsets, /* tp_getset */
2320 0, /* tp_base */
2321 0, /* tp_dict */
2322 0, /* tp_descr_get */
2323 0, /* tp_descr_set */
2324 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002325 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002326 0, /* tp_alloc */
2327 type_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002328 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002329 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002330};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002331
2332
2333/* The base type of all types (eventually)... except itself. */
2334
Guido van Rossumd8faa362007-04-27 19:54:29 +00002335/* You may wonder why object.__new__() only complains about arguments
2336 when object.__init__() is not overridden, and vice versa.
2337
2338 Consider the use cases:
2339
2340 1. When neither is overridden, we want to hear complaints about
2341 excess (i.e., any) arguments, since their presence could
2342 indicate there's a bug.
2343
2344 2. When defining an Immutable type, we are likely to override only
2345 __new__(), since __init__() is called too late to initialize an
2346 Immutable object. Since __new__() defines the signature for the
2347 type, it would be a pain to have to override __init__() just to
2348 stop it from complaining about excess arguments.
2349
2350 3. When defining a Mutable type, we are likely to override only
2351 __init__(). So here the converse reasoning applies: we don't
2352 want to have to override __new__() just to stop it from
2353 complaining.
2354
2355 4. When __init__() is overridden, and the subclass __init__() calls
2356 object.__init__(), the latter should complain about excess
2357 arguments; ditto for __new__().
2358
2359 Use cases 2 and 3 make it unattractive to unconditionally check for
2360 excess arguments. The best solution that addresses all four use
2361 cases is as follows: __init__() complains about excess arguments
2362 unless __new__() is overridden and __init__() is not overridden
2363 (IOW, if __init__() is overridden or __new__() is not overridden);
2364 symmetrically, __new__() complains about excess arguments unless
2365 __init__() is overridden and __new__() is not overridden
2366 (IOW, if __new__() is overridden or __init__() is not overridden).
2367
2368 However, for backwards compatibility, this breaks too much code.
2369 Therefore, in 2.6, we'll *warn* about excess arguments when both
2370 methods are overridden; for all other cases we'll use the above
2371 rules.
2372
2373*/
2374
2375/* Forward */
2376static PyObject *
2377object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2378
2379static int
2380excess_args(PyObject *args, PyObject *kwds)
2381{
2382 return PyTuple_GET_SIZE(args) ||
2383 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2384}
2385
Tim Peters6d6c1a32001-08-02 04:15:00 +00002386static int
2387object_init(PyObject *self, PyObject *args, PyObject *kwds)
2388{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002389 int err = 0;
2390 if (excess_args(args, kwds)) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002391 PyTypeObject *type = Py_TYPE(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002392 if (type->tp_init != object_init &&
2393 type->tp_new != object_new)
2394 {
2395 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2396 "object.__init__() takes no parameters",
2397 1);
2398 }
2399 else if (type->tp_init != object_init ||
2400 type->tp_new == object_new)
2401 {
2402 PyErr_SetString(PyExc_TypeError,
2403 "object.__init__() takes no parameters");
2404 err = -1;
2405 }
2406 }
2407 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002408}
2409
Guido van Rossum298e4212003-02-13 16:30:16 +00002410static PyObject *
2411object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2412{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002413 int err = 0;
2414 if (excess_args(args, kwds)) {
2415 if (type->tp_new != object_new &&
2416 type->tp_init != object_init)
2417 {
2418 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2419 "object.__new__() takes no parameters",
2420 1);
2421 }
2422 else if (type->tp_new != object_new ||
2423 type->tp_init == object_init)
2424 {
2425 PyErr_SetString(PyExc_TypeError,
2426 "object.__new__() takes no parameters");
2427 err = -1;
2428 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002429 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002430 if (err < 0)
2431 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002432 return type->tp_alloc(type, 0);
2433}
2434
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435static void
2436object_dealloc(PyObject *self)
2437{
Christian Heimes90aa7642007-12-19 02:45:37 +00002438 Py_TYPE(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002439}
2440
Guido van Rossum8e248182001-08-12 05:17:56 +00002441static PyObject *
2442object_repr(PyObject *self)
2443{
Guido van Rossum76e69632001-08-16 18:52:43 +00002444 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002445 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002446
Christian Heimes90aa7642007-12-19 02:45:37 +00002447 type = Py_TYPE(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002448 mod = type_module(type, NULL);
2449 if (mod == NULL)
2450 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +00002451 else if (!PyUnicode_Check(mod)) {
Guido van Rossum76e69632001-08-16 18:52:43 +00002452 Py_DECREF(mod);
2453 mod = NULL;
2454 }
2455 name = type_name(type, NULL);
2456 if (name == NULL)
2457 return NULL;
Georg Brandl1a3284e2007-12-02 09:40:06 +00002458 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
Walter Dörwald4dbd01b2007-06-11 14:03:45 +00002459 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002460 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00002461 rtn = PyUnicode_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002462 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002463 Py_XDECREF(mod);
2464 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002465 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002466}
2467
Guido van Rossumb8f63662001-08-15 23:57:02 +00002468static PyObject *
2469object_str(PyObject *self)
2470{
2471 unaryfunc f;
2472
Christian Heimes90aa7642007-12-19 02:45:37 +00002473 f = Py_TYPE(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002474 if (f == NULL)
2475 f = object_repr;
2476 return f(self);
2477}
2478
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002479static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002480object_richcompare(PyObject *self, PyObject *other, int op)
2481{
2482 PyObject *res;
2483
2484 switch (op) {
2485
2486 case Py_EQ:
2487 res = (self == other) ? Py_True : Py_False;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002488 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002489 break;
2490
2491 case Py_NE:
Guido van Rossume27dc722007-03-27 22:37:34 +00002492 /* By default, != returns the opposite of ==,
2493 unless the latter returns NotImplemented. */
2494 res = PyObject_RichCompare(self, other, Py_EQ);
2495 if (res != NULL && res != Py_NotImplemented) {
2496 int ok = PyObject_IsTrue(res);
2497 Py_DECREF(res);
2498 if (ok < 0)
2499 res = NULL;
2500 else {
2501 if (ok)
2502 res = Py_False;
2503 else
2504 res = Py_True;
2505 Py_INCREF(res);
2506 }
2507 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002508 break;
2509
2510 default:
2511 res = Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002512 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002513 break;
2514 }
2515
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002516 return res;
2517}
2518
2519static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002520object_get_class(PyObject *self, void *closure)
2521{
Christian Heimes90aa7642007-12-19 02:45:37 +00002522 Py_INCREF(Py_TYPE(self));
2523 return (PyObject *)(Py_TYPE(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002524}
2525
2526static int
2527equiv_structs(PyTypeObject *a, PyTypeObject *b)
2528{
2529 return a == b ||
2530 (a != NULL &&
2531 b != NULL &&
2532 a->tp_basicsize == b->tp_basicsize &&
2533 a->tp_itemsize == b->tp_itemsize &&
2534 a->tp_dictoffset == b->tp_dictoffset &&
2535 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2536 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2537 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2538}
2539
2540static int
2541same_slots_added(PyTypeObject *a, PyTypeObject *b)
2542{
2543 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002544 Py_ssize_t size;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002545 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002546
2547 if (base != b->tp_base)
2548 return 0;
2549 if (equiv_structs(a, base) && equiv_structs(b, base))
2550 return 1;
2551 size = base->tp_basicsize;
2552 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2553 size += sizeof(PyObject *);
2554 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2555 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002556
2557 /* Check slots compliance */
2558 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2559 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2560 if (slots_a && slots_b) {
2561 if (PyObject_Compare(slots_a, slots_b) != 0)
2562 return 0;
2563 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2564 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002565 return size == a->tp_basicsize && size == b->tp_basicsize;
2566}
2567
2568static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002569compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002570{
2571 PyTypeObject *newbase, *oldbase;
2572
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002573 if (newto->tp_dealloc != oldto->tp_dealloc ||
2574 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002575 {
2576 PyErr_Format(PyExc_TypeError,
2577 "%s assignment: "
2578 "'%s' deallocator differs from '%s'",
2579 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002580 newto->tp_name,
2581 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002582 return 0;
2583 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002584 newbase = newto;
2585 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002586 while (equiv_structs(newbase, newbase->tp_base))
2587 newbase = newbase->tp_base;
2588 while (equiv_structs(oldbase, oldbase->tp_base))
2589 oldbase = oldbase->tp_base;
2590 if (newbase != oldbase &&
2591 (newbase->tp_base != oldbase->tp_base ||
2592 !same_slots_added(newbase, oldbase))) {
2593 PyErr_Format(PyExc_TypeError,
2594 "%s assignment: "
2595 "'%s' object layout differs from '%s'",
2596 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002597 newto->tp_name,
2598 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002599 return 0;
2600 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002601
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002602 return 1;
2603}
2604
2605static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002606object_set_class(PyObject *self, PyObject *value, void *closure)
2607{
Christian Heimes90aa7642007-12-19 02:45:37 +00002608 PyTypeObject *oldto = Py_TYPE(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002609 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002610
Guido van Rossumb6b89422002-04-15 01:03:30 +00002611 if (value == NULL) {
2612 PyErr_SetString(PyExc_TypeError,
2613 "can't delete __class__ attribute");
2614 return -1;
2615 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002616 if (!PyType_Check(value)) {
2617 PyErr_Format(PyExc_TypeError,
2618 "__class__ must be set to new-style class, not '%s' object",
Christian Heimes90aa7642007-12-19 02:45:37 +00002619 Py_TYPE(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002620 return -1;
2621 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002622 newto = (PyTypeObject *)value;
2623 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2624 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002625 {
2626 PyErr_Format(PyExc_TypeError,
2627 "__class__ assignment: only for heap types");
2628 return -1;
2629 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002630 if (compatible_for_assignment(newto, oldto, "__class__")) {
2631 Py_INCREF(newto);
Christian Heimes90aa7642007-12-19 02:45:37 +00002632 Py_TYPE(self) = newto;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002633 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002634 return 0;
2635 }
2636 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002637 return -1;
2638 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002639}
2640
2641static PyGetSetDef object_getsets[] = {
2642 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002643 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002644 {0}
2645};
2646
Guido van Rossumc53f0092003-02-18 22:05:12 +00002647
Guido van Rossum036f9992003-02-21 22:02:54 +00002648/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2649 We fall back to helpers in copy_reg for:
2650 - pickle protocols < 2
2651 - calculating the list of slot names (done only once per class)
2652 - the __newobj__ function (which is used as a token but never called)
2653*/
2654
2655static PyObject *
2656import_copy_reg(void)
2657{
2658 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002659
2660 if (!copy_reg_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002661 copy_reg_str = PyUnicode_InternFromString("copy_reg");
Guido van Rossum3926a632001-09-25 16:25:58 +00002662 if (copy_reg_str == NULL)
2663 return NULL;
2664 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002665
2666 return PyImport_Import(copy_reg_str);
2667}
2668
2669static PyObject *
2670slotnames(PyObject *cls)
2671{
2672 PyObject *clsdict;
2673 PyObject *copy_reg;
2674 PyObject *slotnames;
2675
2676 if (!PyType_Check(cls)) {
2677 Py_INCREF(Py_None);
2678 return Py_None;
2679 }
2680
2681 clsdict = ((PyTypeObject *)cls)->tp_dict;
2682 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002683 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002684 Py_INCREF(slotnames);
2685 return slotnames;
2686 }
2687
2688 copy_reg = import_copy_reg();
2689 if (copy_reg == NULL)
2690 return NULL;
2691
2692 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2693 Py_DECREF(copy_reg);
2694 if (slotnames != NULL &&
2695 slotnames != Py_None &&
2696 !PyList_Check(slotnames))
2697 {
2698 PyErr_SetString(PyExc_TypeError,
2699 "copy_reg._slotnames didn't return a list or None");
2700 Py_DECREF(slotnames);
2701 slotnames = NULL;
2702 }
2703
2704 return slotnames;
2705}
2706
2707static PyObject *
2708reduce_2(PyObject *obj)
2709{
2710 PyObject *cls, *getnewargs;
2711 PyObject *args = NULL, *args2 = NULL;
2712 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2713 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2714 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002715 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002716
2717 cls = PyObject_GetAttrString(obj, "__class__");
2718 if (cls == NULL)
2719 return NULL;
2720
2721 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2722 if (getnewargs != NULL) {
2723 args = PyObject_CallObject(getnewargs, NULL);
2724 Py_DECREF(getnewargs);
2725 if (args != NULL && !PyTuple_Check(args)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002726 PyErr_Format(PyExc_TypeError,
2727 "__getnewargs__ should return a tuple, "
Christian Heimes90aa7642007-12-19 02:45:37 +00002728 "not '%.200s'", Py_TYPE(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002729 goto end;
2730 }
2731 }
2732 else {
2733 PyErr_Clear();
2734 args = PyTuple_New(0);
2735 }
2736 if (args == NULL)
2737 goto end;
2738
2739 getstate = PyObject_GetAttrString(obj, "__getstate__");
2740 if (getstate != NULL) {
2741 state = PyObject_CallObject(getstate, NULL);
2742 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002743 if (state == NULL)
2744 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002745 }
2746 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002747 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002748 state = PyObject_GetAttrString(obj, "__dict__");
2749 if (state == NULL) {
2750 PyErr_Clear();
2751 state = Py_None;
2752 Py_INCREF(state);
2753 }
2754 names = slotnames(cls);
2755 if (names == NULL)
2756 goto end;
2757 if (names != Py_None) {
2758 assert(PyList_Check(names));
2759 slots = PyDict_New();
2760 if (slots == NULL)
2761 goto end;
2762 n = 0;
2763 /* Can't pre-compute the list size; the list
2764 is stored on the class so accessible to other
2765 threads, which may be run by DECREF */
2766 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2767 PyObject *name, *value;
2768 name = PyList_GET_ITEM(names, i);
2769 value = PyObject_GetAttr(obj, name);
2770 if (value == NULL)
2771 PyErr_Clear();
2772 else {
2773 int err = PyDict_SetItem(slots, name,
2774 value);
2775 Py_DECREF(value);
2776 if (err)
2777 goto end;
2778 n++;
2779 }
2780 }
2781 if (n) {
2782 state = Py_BuildValue("(NO)", state, slots);
2783 if (state == NULL)
2784 goto end;
2785 }
2786 }
2787 }
2788
2789 if (!PyList_Check(obj)) {
2790 listitems = Py_None;
2791 Py_INCREF(listitems);
2792 }
2793 else {
2794 listitems = PyObject_GetIter(obj);
2795 if (listitems == NULL)
2796 goto end;
2797 }
2798
2799 if (!PyDict_Check(obj)) {
2800 dictitems = Py_None;
2801 Py_INCREF(dictitems);
2802 }
2803 else {
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002804 PyObject *items = PyObject_CallMethod(obj, "items", "");
2805 if (items == NULL)
2806 goto end;
2807 dictitems = PyObject_GetIter(items);
2808 Py_DECREF(items);
Guido van Rossum036f9992003-02-21 22:02:54 +00002809 if (dictitems == NULL)
2810 goto end;
2811 }
2812
2813 copy_reg = import_copy_reg();
2814 if (copy_reg == NULL)
2815 goto end;
2816 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2817 if (newobj == NULL)
2818 goto end;
2819
2820 n = PyTuple_GET_SIZE(args);
2821 args2 = PyTuple_New(n+1);
2822 if (args2 == NULL)
2823 goto end;
2824 PyTuple_SET_ITEM(args2, 0, cls);
2825 cls = NULL;
2826 for (i = 0; i < n; i++) {
2827 PyObject *v = PyTuple_GET_ITEM(args, i);
2828 Py_INCREF(v);
2829 PyTuple_SET_ITEM(args2, i+1, v);
2830 }
2831
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002832 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002833
2834 end:
2835 Py_XDECREF(cls);
2836 Py_XDECREF(args);
2837 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002838 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002839 Py_XDECREF(state);
2840 Py_XDECREF(names);
2841 Py_XDECREF(listitems);
2842 Py_XDECREF(dictitems);
2843 Py_XDECREF(copy_reg);
2844 Py_XDECREF(newobj);
2845 return res;
2846}
2847
Guido van Rossumd8faa362007-04-27 19:54:29 +00002848/*
2849 * There were two problems when object.__reduce__ and object.__reduce_ex__
2850 * were implemented in the same function:
2851 * - trying to pickle an object with a custom __reduce__ method that
2852 * fell back to object.__reduce__ in certain circumstances led to
2853 * infinite recursion at Python level and eventual RuntimeError.
2854 * - Pickling objects that lied about their type by overwriting the
2855 * __class__ descriptor could lead to infinite recursion at C level
2856 * and eventual segfault.
2857 *
2858 * Because of backwards compatibility, the two methods still have to
2859 * behave in the same way, even if this is not required by the pickle
2860 * protocol. This common functionality was moved to the _common_reduce
2861 * function.
2862 */
2863static PyObject *
2864_common_reduce(PyObject *self, int proto)
2865{
2866 PyObject *copy_reg, *res;
2867
2868 if (proto >= 2)
2869 return reduce_2(self);
2870
2871 copy_reg = import_copy_reg();
2872 if (!copy_reg)
2873 return NULL;
2874
2875 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2876 Py_DECREF(copy_reg);
2877
2878 return res;
2879}
2880
2881static PyObject *
2882object_reduce(PyObject *self, PyObject *args)
2883{
2884 int proto = 0;
2885
2886 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
2887 return NULL;
2888
2889 return _common_reduce(self, proto);
2890}
2891
Guido van Rossum036f9992003-02-21 22:02:54 +00002892static PyObject *
2893object_reduce_ex(PyObject *self, PyObject *args)
2894{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002895 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00002896 int proto = 0;
2897
2898 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2899 return NULL;
2900
2901 reduce = PyObject_GetAttrString(self, "__reduce__");
2902 if (reduce == NULL)
2903 PyErr_Clear();
2904 else {
2905 PyObject *cls, *clsreduce, *objreduce;
2906 int override;
2907 cls = PyObject_GetAttrString(self, "__class__");
2908 if (cls == NULL) {
2909 Py_DECREF(reduce);
2910 return NULL;
2911 }
2912 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2913 Py_DECREF(cls);
2914 if (clsreduce == NULL) {
2915 Py_DECREF(reduce);
2916 return NULL;
2917 }
2918 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2919 "__reduce__");
2920 override = (clsreduce != objreduce);
2921 Py_DECREF(clsreduce);
2922 if (override) {
2923 res = PyObject_CallObject(reduce, NULL);
2924 Py_DECREF(reduce);
2925 return res;
2926 }
2927 else
2928 Py_DECREF(reduce);
2929 }
2930
Guido van Rossumd8faa362007-04-27 19:54:29 +00002931 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002932}
2933
Eric Smith8c663262007-08-25 02:26:07 +00002934
2935/*
2936 from PEP 3101, this code implements:
2937
2938 class object:
2939 def __format__(self, format_spec):
2940 return format(str(self), format_spec)
2941*/
2942static PyObject *
2943object_format(PyObject *self, PyObject *args)
2944{
2945 PyObject *format_spec;
2946 PyObject *self_as_str = NULL;
2947 PyObject *result = NULL;
2948 PyObject *format_meth = NULL;
2949
2950 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
2951 return NULL;
2952 if (!PyUnicode_Check(format_spec)) {
2953 PyErr_SetString(PyExc_TypeError, "Unicode object required");
2954 return NULL;
2955 }
2956
Thomas Heller519a0422007-11-15 20:48:54 +00002957 self_as_str = PyObject_Str(self);
Eric Smith8c663262007-08-25 02:26:07 +00002958 if (self_as_str != NULL) {
2959 /* find the format function */
2960 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
2961 if (format_meth != NULL) {
2962 /* and call it */
2963 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
2964 }
2965 }
2966
2967 Py_XDECREF(self_as_str);
2968 Py_XDECREF(format_meth);
2969
2970 return result;
2971}
2972
Guido van Rossum3926a632001-09-25 16:25:58 +00002973static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002974 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2975 PyDoc_STR("helper for pickle")},
Guido van Rossumd8faa362007-04-27 19:54:29 +00002976 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002977 PyDoc_STR("helper for pickle")},
Eric Smith8c663262007-08-25 02:26:07 +00002978 {"__format__", object_format, METH_VARARGS,
2979 PyDoc_STR("default object formatter")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002980 {0}
2981};
2982
Guido van Rossum036f9992003-02-21 22:02:54 +00002983
Tim Peters6d6c1a32001-08-02 04:15:00 +00002984PyTypeObject PyBaseObject_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002985 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002986 "object", /* tp_name */
2987 sizeof(PyObject), /* tp_basicsize */
2988 0, /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002989 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002990 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002991 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002992 0, /* tp_setattr */
2993 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002994 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995 0, /* tp_as_number */
2996 0, /* tp_as_sequence */
2997 0, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002998 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002999 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003000 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003001 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003002 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003003 0, /* tp_as_buffer */
3004 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003005 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003006 0, /* tp_traverse */
3007 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003008 object_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003009 0, /* tp_weaklistoffset */
3010 0, /* tp_iter */
3011 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003012 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003013 0, /* tp_members */
3014 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015 0, /* tp_base */
3016 0, /* tp_dict */
3017 0, /* tp_descr_get */
3018 0, /* tp_descr_set */
3019 0, /* tp_dictoffset */
3020 object_init, /* tp_init */
3021 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003022 object_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003023 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003024};
3025
3026
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003027/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003028
3029static int
3030add_methods(PyTypeObject *type, PyMethodDef *meth)
3031{
Guido van Rossum687ae002001-10-15 22:03:32 +00003032 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003033
3034 for (; meth->ml_name != NULL; meth++) {
3035 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003036 if (PyDict_GetItemString(dict, meth->ml_name) &&
3037 !(meth->ml_flags & METH_COEXIST))
3038 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003039 if (meth->ml_flags & METH_CLASS) {
3040 if (meth->ml_flags & METH_STATIC) {
3041 PyErr_SetString(PyExc_ValueError,
3042 "method cannot be both class and static");
3043 return -1;
3044 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003045 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003046 }
3047 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003048 PyObject *cfunc = PyCFunction_New(meth, NULL);
3049 if (cfunc == NULL)
3050 return -1;
3051 descr = PyStaticMethod_New(cfunc);
3052 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003053 }
3054 else {
3055 descr = PyDescr_NewMethod(type, meth);
3056 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003057 if (descr == NULL)
3058 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003059 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003060 return -1;
3061 Py_DECREF(descr);
3062 }
3063 return 0;
3064}
3065
3066static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003067add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003068{
Guido van Rossum687ae002001-10-15 22:03:32 +00003069 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003070
3071 for (; memb->name != NULL; memb++) {
3072 PyObject *descr;
3073 if (PyDict_GetItemString(dict, memb->name))
3074 continue;
3075 descr = PyDescr_NewMember(type, memb);
3076 if (descr == NULL)
3077 return -1;
3078 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3079 return -1;
3080 Py_DECREF(descr);
3081 }
3082 return 0;
3083}
3084
3085static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003086add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003087{
Guido van Rossum687ae002001-10-15 22:03:32 +00003088 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003089
3090 for (; gsp->name != NULL; gsp++) {
3091 PyObject *descr;
3092 if (PyDict_GetItemString(dict, gsp->name))
3093 continue;
3094 descr = PyDescr_NewGetSet(type, gsp);
3095
3096 if (descr == NULL)
3097 return -1;
3098 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3099 return -1;
3100 Py_DECREF(descr);
3101 }
3102 return 0;
3103}
3104
Guido van Rossum13d52f02001-08-10 21:24:08 +00003105static void
3106inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003107{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003108 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109
Guido van Rossum13d52f02001-08-10 21:24:08 +00003110 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003111 oldsize = base->tp_basicsize;
3112 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3113 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3114 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003115 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003116 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003117 if (type->tp_traverse == NULL)
3118 type->tp_traverse = base->tp_traverse;
3119 if (type->tp_clear == NULL)
3120 type->tp_clear = base->tp_clear;
3121 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003122 {
Guido van Rossumf884b742001-12-17 17:14:22 +00003123 /* The condition below could use some explanation.
3124 It appears that tp_new is not inherited for static types
3125 whose base class is 'object'; this seems to be a precaution
3126 so that old extension types don't suddenly become
3127 callable (object.__new__ wouldn't insure the invariants
3128 that the extension type's own factory function ensures).
3129 Heap types, of course, are under our control, so they do
3130 inherit tp_new; static extension types that specify some
3131 other built-in type as the default are considered
3132 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003133 if (base != &PyBaseObject_Type ||
3134 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3135 if (type->tp_new == NULL)
3136 type->tp_new = base->tp_new;
3137 }
3138 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003139 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003140
3141 /* Copy other non-function slots */
3142
3143#undef COPYVAL
3144#define COPYVAL(SLOT) \
3145 if (type->SLOT == 0) type->SLOT = base->SLOT
3146
3147 COPYVAL(tp_itemsize);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003148 COPYVAL(tp_weaklistoffset);
3149 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003150
3151 /* Setup fast subclass flags */
3152 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3153 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3154 else if (PyType_IsSubtype(base, &PyType_Type))
3155 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3156 else if (PyType_IsSubtype(base, &PyLong_Type))
3157 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3158 else if (PyType_IsSubtype(base, &PyString_Type))
3159 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3160 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3161 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3162 else if (PyType_IsSubtype(base, &PyTuple_Type))
3163 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3164 else if (PyType_IsSubtype(base, &PyList_Type))
3165 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3166 else if (PyType_IsSubtype(base, &PyDict_Type))
3167 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003168}
3169
Guido van Rossum38938152006-08-21 23:36:26 +00003170/* Map rich comparison operators to their __xx__ namesakes */
3171static char *name_op[] = {
3172 "__lt__",
3173 "__le__",
3174 "__eq__",
3175 "__ne__",
3176 "__gt__",
3177 "__ge__",
3178 /* These are only for overrides_cmp_or_hash(): */
3179 "__cmp__",
3180 "__hash__",
3181};
3182
3183static int
3184overrides_cmp_or_hash(PyTypeObject *type)
3185{
3186 int i;
3187 PyObject *dict = type->tp_dict;
3188
3189 assert(dict != NULL);
3190 for (i = 0; i < 8; i++) {
3191 if (PyDict_GetItemString(dict, name_op[i]) != NULL)
3192 return 1;
3193 }
3194 return 0;
3195}
3196
Guido van Rossum13d52f02001-08-10 21:24:08 +00003197static void
3198inherit_slots(PyTypeObject *type, PyTypeObject *base)
3199{
3200 PyTypeObject *basebase;
3201
3202#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003203#undef COPYSLOT
3204#undef COPYNUM
3205#undef COPYSEQ
3206#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003207#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003208
3209#define SLOTDEFINED(SLOT) \
3210 (base->SLOT != 0 && \
3211 (basebase == NULL || base->SLOT != basebase->SLOT))
3212
Tim Peters6d6c1a32001-08-02 04:15:00 +00003213#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003214 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003215
3216#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3217#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3218#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003219#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003220
Guido van Rossum13d52f02001-08-10 21:24:08 +00003221 /* This won't inherit indirect slots (from tp_as_number etc.)
3222 if type doesn't provide the space. */
3223
3224 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3225 basebase = base->tp_base;
3226 if (basebase->tp_as_number == NULL)
3227 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003228 COPYNUM(nb_add);
3229 COPYNUM(nb_subtract);
3230 COPYNUM(nb_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003231 COPYNUM(nb_remainder);
3232 COPYNUM(nb_divmod);
3233 COPYNUM(nb_power);
3234 COPYNUM(nb_negative);
3235 COPYNUM(nb_positive);
3236 COPYNUM(nb_absolute);
Jack Diederich4dafcc42006-11-28 19:15:13 +00003237 COPYNUM(nb_bool);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003238 COPYNUM(nb_invert);
3239 COPYNUM(nb_lshift);
3240 COPYNUM(nb_rshift);
3241 COPYNUM(nb_and);
3242 COPYNUM(nb_xor);
3243 COPYNUM(nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003244 COPYNUM(nb_int);
3245 COPYNUM(nb_long);
3246 COPYNUM(nb_float);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003247 COPYNUM(nb_inplace_add);
3248 COPYNUM(nb_inplace_subtract);
3249 COPYNUM(nb_inplace_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003250 COPYNUM(nb_inplace_remainder);
3251 COPYNUM(nb_inplace_power);
3252 COPYNUM(nb_inplace_lshift);
3253 COPYNUM(nb_inplace_rshift);
3254 COPYNUM(nb_inplace_and);
3255 COPYNUM(nb_inplace_xor);
3256 COPYNUM(nb_inplace_or);
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003257 COPYNUM(nb_true_divide);
3258 COPYNUM(nb_floor_divide);
3259 COPYNUM(nb_inplace_true_divide);
3260 COPYNUM(nb_inplace_floor_divide);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003261 COPYNUM(nb_index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003262 }
3263
Guido van Rossum13d52f02001-08-10 21:24:08 +00003264 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3265 basebase = base->tp_base;
3266 if (basebase->tp_as_sequence == NULL)
3267 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003268 COPYSEQ(sq_length);
3269 COPYSEQ(sq_concat);
3270 COPYSEQ(sq_repeat);
3271 COPYSEQ(sq_item);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003272 COPYSEQ(sq_ass_item);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003273 COPYSEQ(sq_contains);
3274 COPYSEQ(sq_inplace_concat);
3275 COPYSEQ(sq_inplace_repeat);
3276 }
3277
Guido van Rossum13d52f02001-08-10 21:24:08 +00003278 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3279 basebase = base->tp_base;
3280 if (basebase->tp_as_mapping == NULL)
3281 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003282 COPYMAP(mp_length);
3283 COPYMAP(mp_subscript);
3284 COPYMAP(mp_ass_subscript);
3285 }
3286
Tim Petersfc57ccb2001-10-12 02:38:24 +00003287 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3288 basebase = base->tp_base;
3289 if (basebase->tp_as_buffer == NULL)
3290 basebase = NULL;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00003291 COPYBUF(bf_getbuffer);
3292 COPYBUF(bf_releasebuffer);
Tim Petersfc57ccb2001-10-12 02:38:24 +00003293 }
3294
Guido van Rossum13d52f02001-08-10 21:24:08 +00003295 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003296
Tim Peters6d6c1a32001-08-02 04:15:00 +00003297 COPYSLOT(tp_dealloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003298 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3299 type->tp_getattr = base->tp_getattr;
3300 type->tp_getattro = base->tp_getattro;
3301 }
3302 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3303 type->tp_setattr = base->tp_setattr;
3304 type->tp_setattro = base->tp_setattro;
3305 }
3306 /* tp_compare see tp_richcompare */
3307 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003308 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003309 COPYSLOT(tp_call);
3310 COPYSLOT(tp_str);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003311 {
Guido van Rossum38938152006-08-21 23:36:26 +00003312 /* Copy comparison-related slots only when
3313 not overriding them anywhere */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003314 if (type->tp_compare == NULL &&
3315 type->tp_richcompare == NULL &&
Guido van Rossum38938152006-08-21 23:36:26 +00003316 type->tp_hash == NULL &&
3317 !overrides_cmp_or_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003318 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003319 type->tp_compare = base->tp_compare;
3320 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003321 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003322 }
3323 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003324 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003325 COPYSLOT(tp_iter);
3326 COPYSLOT(tp_iternext);
3327 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003328 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003329 COPYSLOT(tp_descr_get);
3330 COPYSLOT(tp_descr_set);
3331 COPYSLOT(tp_dictoffset);
3332 COPYSLOT(tp_init);
3333 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003334 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003335 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3336 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3337 /* They agree about gc. */
3338 COPYSLOT(tp_free);
3339 }
3340 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3341 type->tp_free == NULL &&
Neal Norwitz30d1c512007-08-19 22:48:23 +00003342 base->tp_free == PyObject_Free) {
Tim Peters3cfe7542003-05-21 21:29:48 +00003343 /* A bit of magic to plug in the correct default
3344 * tp_free function when a derived class adds gc,
3345 * didn't define tp_free, and the base uses the
3346 * default non-gc tp_free.
3347 */
3348 type->tp_free = PyObject_GC_Del;
3349 }
3350 /* else they didn't agree about gc, and there isn't something
3351 * obvious to be done -- the type is on its own.
3352 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003353 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003354}
3355
Jeremy Hylton938ace62002-07-17 16:30:39 +00003356static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003357
Tim Peters6d6c1a32001-08-02 04:15:00 +00003358int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003359PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003360{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003361 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003362 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003363 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003364
Guido van Rossumcab05802002-06-10 15:29:03 +00003365 if (type->tp_flags & Py_TPFLAGS_READY) {
3366 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003367 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003368 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003369 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003370
3371 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003372
Tim Peters36eb4df2003-03-23 03:33:13 +00003373#ifdef Py_TRACE_REFS
3374 /* PyType_Ready is the closest thing we have to a choke point
3375 * for type objects, so is the best place I can think of to try
3376 * to get type objects into the doubly-linked list of all objects.
3377 * Still, not all type objects go thru PyType_Ready.
3378 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003379 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003380#endif
3381
Tim Peters6d6c1a32001-08-02 04:15:00 +00003382 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3383 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003384 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003385 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003386 Py_INCREF(base);
3387 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003388
Guido van Rossumd8faa362007-04-27 19:54:29 +00003389 /* Now the only way base can still be NULL is if type is
3390 * &PyBaseObject_Type.
3391 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003392
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003393 /* Initialize the base class */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003394 if (base != NULL && base->tp_dict == NULL) {
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003395 if (PyType_Ready(base) < 0)
3396 goto error;
3397 }
3398
Guido van Rossumd8faa362007-04-27 19:54:29 +00003399 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003400 compilable separately on Windows can call PyType_Ready() instead of
3401 initializing the ob_type field of their type objects. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003402 /* The test for base != NULL is really unnecessary, since base is only
3403 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3404 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3405 know that. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003406 if (Py_TYPE(type) == NULL && base != NULL)
3407 Py_TYPE(type) = Py_TYPE(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003408
Tim Peters6d6c1a32001-08-02 04:15:00 +00003409 /* Initialize tp_bases */
3410 bases = type->tp_bases;
3411 if (bases == NULL) {
3412 if (base == NULL)
3413 bases = PyTuple_New(0);
3414 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003415 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003417 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003418 type->tp_bases = bases;
3419 }
3420
Guido van Rossum687ae002001-10-15 22:03:32 +00003421 /* Initialize tp_dict */
3422 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423 if (dict == NULL) {
3424 dict = PyDict_New();
3425 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003426 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003427 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003428 }
3429
Guido van Rossum687ae002001-10-15 22:03:32 +00003430 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003431 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003432 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003433 if (type->tp_methods != NULL) {
3434 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003435 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003436 }
3437 if (type->tp_members != NULL) {
3438 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003439 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003440 }
3441 if (type->tp_getset != NULL) {
3442 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003443 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003444 }
3445
Tim Peters6d6c1a32001-08-02 04:15:00 +00003446 /* Calculate method resolution order */
3447 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003448 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003449 }
3450
Guido van Rossum13d52f02001-08-10 21:24:08 +00003451 /* Inherit special flags from dominant base */
3452 if (type->tp_base != NULL)
3453 inherit_special(type, type->tp_base);
3454
Tim Peters6d6c1a32001-08-02 04:15:00 +00003455 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003456 bases = type->tp_mro;
3457 assert(bases != NULL);
3458 assert(PyTuple_Check(bases));
3459 n = PyTuple_GET_SIZE(bases);
3460 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003461 PyObject *b = PyTuple_GET_ITEM(bases, i);
3462 if (PyType_Check(b))
3463 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003464 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003465
Tim Peters3cfe7542003-05-21 21:29:48 +00003466 /* Sanity check for tp_free. */
3467 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3468 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003469 /* This base class needs to call tp_free, but doesn't have
3470 * one, or its tp_free is for non-gc'ed objects.
3471 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003472 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3473 "gc and is a base type but has inappropriate "
3474 "tp_free slot",
3475 type->tp_name);
3476 goto error;
3477 }
3478
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003479 /* if the type dictionary doesn't contain a __doc__, set it from
3480 the tp_doc slot.
3481 */
3482 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3483 if (type->tp_doc != NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +00003484 PyObject *doc = PyUnicode_FromString(type->tp_doc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003485 if (doc == NULL)
3486 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003487 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3488 Py_DECREF(doc);
3489 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003490 PyDict_SetItemString(type->tp_dict,
3491 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003492 }
3493 }
3494
Guido van Rossum38938152006-08-21 23:36:26 +00003495 /* Hack for tp_hash and __hash__.
3496 If after all that, tp_hash is still NULL, and __hash__ is not in
3497 tp_dict, set tp_dict['__hash__'] equal to None.
3498 This signals that __hash__ is not inherited.
3499 */
3500 if (type->tp_hash == NULL) {
3501 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3502 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3503 goto error;
3504 }
3505 }
3506
Guido van Rossum13d52f02001-08-10 21:24:08 +00003507 /* Some more special stuff */
3508 base = type->tp_base;
3509 if (base != NULL) {
3510 if (type->tp_as_number == NULL)
3511 type->tp_as_number = base->tp_as_number;
3512 if (type->tp_as_sequence == NULL)
3513 type->tp_as_sequence = base->tp_as_sequence;
3514 if (type->tp_as_mapping == NULL)
3515 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003516 if (type->tp_as_buffer == NULL)
3517 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003518 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003519
Guido van Rossum1c450732001-10-08 15:18:27 +00003520 /* Link into each base class's list of subclasses */
3521 bases = type->tp_bases;
3522 n = PyTuple_GET_SIZE(bases);
3523 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003524 PyObject *b = PyTuple_GET_ITEM(bases, i);
3525 if (PyType_Check(b) &&
3526 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003527 goto error;
3528 }
3529
Guido van Rossum13d52f02001-08-10 21:24:08 +00003530 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003531 assert(type->tp_dict != NULL);
3532 type->tp_flags =
3533 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003534 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003535
3536 error:
3537 type->tp_flags &= ~Py_TPFLAGS_READYING;
3538 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003539}
3540
Guido van Rossum1c450732001-10-08 15:18:27 +00003541static int
3542add_subclass(PyTypeObject *base, PyTypeObject *type)
3543{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003544 Py_ssize_t i;
3545 int result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003546 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003547
3548 list = base->tp_subclasses;
3549 if (list == NULL) {
3550 base->tp_subclasses = list = PyList_New(0);
3551 if (list == NULL)
3552 return -1;
3553 }
3554 assert(PyList_Check(list));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003555 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003556 i = PyList_GET_SIZE(list);
3557 while (--i >= 0) {
3558 ref = PyList_GET_ITEM(list, i);
3559 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003560 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003561 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003562 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003563 result = PyList_Append(list, newobj);
3564 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003565 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003566}
3567
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003568static void
3569remove_subclass(PyTypeObject *base, PyTypeObject *type)
3570{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003571 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003572 PyObject *list, *ref;
3573
3574 list = base->tp_subclasses;
3575 if (list == NULL) {
3576 return;
3577 }
3578 assert(PyList_Check(list));
3579 i = PyList_GET_SIZE(list);
3580 while (--i >= 0) {
3581 ref = PyList_GET_ITEM(list, i);
3582 assert(PyWeakref_CheckRef(ref));
3583 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3584 /* this can't fail, right? */
3585 PySequence_DelItem(list, i);
3586 return;
3587 }
3588 }
3589}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003590
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003591static int
3592check_num_args(PyObject *ob, int n)
3593{
3594 if (!PyTuple_CheckExact(ob)) {
3595 PyErr_SetString(PyExc_SystemError,
3596 "PyArg_UnpackTuple() argument list is not a tuple");
3597 return 0;
3598 }
3599 if (n == PyTuple_GET_SIZE(ob))
3600 return 1;
3601 PyErr_Format(
3602 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003603 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003604 return 0;
3605}
3606
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3608
3609/* There's a wrapper *function* for each distinct function typedef used
Guido van Rossumd8faa362007-04-27 19:54:29 +00003610 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003611 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3612 Most tables have only one entry; the tables for binary operators have two
3613 entries, one regular and one with reversed arguments. */
3614
3615static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003616wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003617{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003618 lenfunc func = (lenfunc)wrapped;
3619 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003620
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003621 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003622 return NULL;
3623 res = (*func)(self);
3624 if (res == -1 && PyErr_Occurred())
3625 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00003626 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627}
3628
Tim Peters6d6c1a32001-08-02 04:15:00 +00003629static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003630wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3631{
3632 inquiry func = (inquiry)wrapped;
3633 int res;
3634
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003635 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003636 return NULL;
3637 res = (*func)(self);
3638 if (res == -1 && PyErr_Occurred())
3639 return NULL;
3640 return PyBool_FromLong((long)res);
3641}
3642
3643static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003644wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3645{
3646 binaryfunc func = (binaryfunc)wrapped;
3647 PyObject *other;
3648
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003649 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003650 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003651 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003652 return (*func)(self, other);
3653}
3654
3655static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003656wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3657{
3658 binaryfunc func = (binaryfunc)wrapped;
3659 PyObject *other;
3660
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003661 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003662 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003663 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003664 return (*func)(self, other);
3665}
3666
3667static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003668wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3669{
3670 binaryfunc func = (binaryfunc)wrapped;
3671 PyObject *other;
3672
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003673 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003675 other = PyTuple_GET_ITEM(args, 0);
Christian Heimes90aa7642007-12-19 02:45:37 +00003676 if (!PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003677 Py_INCREF(Py_NotImplemented);
3678 return Py_NotImplemented;
3679 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003680 return (*func)(other, self);
3681}
3682
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003683static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003684wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3685{
3686 ternaryfunc func = (ternaryfunc)wrapped;
3687 PyObject *other;
3688 PyObject *third = Py_None;
3689
3690 /* Note: This wrapper only works for __pow__() */
3691
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003692 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693 return NULL;
3694 return (*func)(self, other, third);
3695}
3696
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003697static PyObject *
3698wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3699{
3700 ternaryfunc func = (ternaryfunc)wrapped;
3701 PyObject *other;
3702 PyObject *third = Py_None;
3703
3704 /* Note: This wrapper only works for __pow__() */
3705
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003706 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003707 return NULL;
3708 return (*func)(other, self, third);
3709}
3710
Tim Peters6d6c1a32001-08-02 04:15:00 +00003711static PyObject *
3712wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3713{
3714 unaryfunc func = (unaryfunc)wrapped;
3715
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003716 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717 return NULL;
3718 return (*func)(self);
3719}
3720
Tim Peters6d6c1a32001-08-02 04:15:00 +00003721static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003722wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003723{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003724 ssizeargfunc func = (ssizeargfunc)wrapped;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003725 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003726 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003727
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003728 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3729 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003730 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003731 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732 return NULL;
3733 return (*func)(self, i);
3734}
3735
Martin v. Löwis18e16552006-02-15 17:27:45 +00003736static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003737getindex(PyObject *self, PyObject *arg)
3738{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003739 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003740
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003741 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003742 if (i == -1 && PyErr_Occurred())
3743 return -1;
3744 if (i < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00003745 PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003746 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003747 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003748 if (n < 0)
3749 return -1;
3750 i += n;
3751 }
3752 }
3753 return i;
3754}
3755
3756static PyObject *
3757wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3758{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003759 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003760 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003761 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003762
Guido van Rossumf4593e02001-10-03 12:09:30 +00003763 if (PyTuple_GET_SIZE(args) == 1) {
3764 arg = PyTuple_GET_ITEM(args, 0);
3765 i = getindex(self, arg);
3766 if (i == -1 && PyErr_Occurred())
3767 return NULL;
3768 return (*func)(self, i);
3769 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003770 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003771 assert(PyErr_Occurred());
3772 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003773}
3774
Tim Peters6d6c1a32001-08-02 04:15:00 +00003775static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003776wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003777{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003778 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3779 Py_ssize_t i;
3780 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003781 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003782
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003783 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003784 return NULL;
3785 i = getindex(self, arg);
3786 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003787 return NULL;
3788 res = (*func)(self, i, value);
3789 if (res == -1 && PyErr_Occurred())
3790 return NULL;
3791 Py_INCREF(Py_None);
3792 return Py_None;
3793}
3794
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003795static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003796wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003797{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003798 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3799 Py_ssize_t i;
3800 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003801 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003802
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003803 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003804 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003805 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003806 i = getindex(self, arg);
3807 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003808 return NULL;
3809 res = (*func)(self, i, NULL);
3810 if (res == -1 && PyErr_Occurred())
3811 return NULL;
3812 Py_INCREF(Py_None);
3813 return Py_None;
3814}
3815
Tim Peters6d6c1a32001-08-02 04:15:00 +00003816/* XXX objobjproc is a misnomer; should be objargpred */
3817static PyObject *
3818wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3819{
3820 objobjproc func = (objobjproc)wrapped;
3821 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003822 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003823
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003824 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003825 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003826 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003827 res = (*func)(self, value);
3828 if (res == -1 && PyErr_Occurred())
3829 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003830 else
3831 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003832}
3833
Tim Peters6d6c1a32001-08-02 04:15:00 +00003834static PyObject *
3835wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3836{
3837 objobjargproc func = (objobjargproc)wrapped;
3838 int res;
3839 PyObject *key, *value;
3840
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003841 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003842 return NULL;
3843 res = (*func)(self, key, value);
3844 if (res == -1 && PyErr_Occurred())
3845 return NULL;
3846 Py_INCREF(Py_None);
3847 return Py_None;
3848}
3849
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003850static PyObject *
3851wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3852{
3853 objobjargproc func = (objobjargproc)wrapped;
3854 int res;
3855 PyObject *key;
3856
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003857 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003858 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003859 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003860 res = (*func)(self, key, NULL);
3861 if (res == -1 && PyErr_Occurred())
3862 return NULL;
3863 Py_INCREF(Py_None);
3864 return Py_None;
3865}
3866
Tim Peters6d6c1a32001-08-02 04:15:00 +00003867static PyObject *
3868wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3869{
3870 cmpfunc func = (cmpfunc)wrapped;
3871 int res;
3872 PyObject *other;
3873
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003874 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003875 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003876 other = PyTuple_GET_ITEM(args, 0);
Christian Heimes90aa7642007-12-19 02:45:37 +00003877 if (Py_TYPE(other)->tp_compare != func &&
3878 !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003879 PyErr_Format(
3880 PyExc_TypeError,
3881 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00003882 Py_TYPE(self)->tp_name,
3883 Py_TYPE(self)->tp_name,
3884 Py_TYPE(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00003885 return NULL;
3886 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003887 res = (*func)(self, other);
3888 if (PyErr_Occurred())
3889 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00003890 return PyLong_FromLong((long)res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003891}
3892
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003893/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003894 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003895static int
3896hackcheck(PyObject *self, setattrofunc func, char *what)
3897{
Christian Heimes90aa7642007-12-19 02:45:37 +00003898 PyTypeObject *type = Py_TYPE(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003899 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3900 type = type->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003901 /* If type is NULL now, this is a really weird type.
3902 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003903 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003904 PyErr_Format(PyExc_TypeError,
3905 "can't apply this %s to %s object",
3906 what,
3907 type->tp_name);
3908 return 0;
3909 }
3910 return 1;
3911}
3912
Tim Peters6d6c1a32001-08-02 04:15:00 +00003913static PyObject *
3914wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3915{
3916 setattrofunc func = (setattrofunc)wrapped;
3917 int res;
3918 PyObject *name, *value;
3919
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003920 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003921 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003922 if (!hackcheck(self, func, "__setattr__"))
3923 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003924 res = (*func)(self, name, value);
3925 if (res < 0)
3926 return NULL;
3927 Py_INCREF(Py_None);
3928 return Py_None;
3929}
3930
3931static PyObject *
3932wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3933{
3934 setattrofunc func = (setattrofunc)wrapped;
3935 int res;
3936 PyObject *name;
3937
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003938 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003939 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003940 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003941 if (!hackcheck(self, func, "__delattr__"))
3942 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003943 res = (*func)(self, name, NULL);
3944 if (res < 0)
3945 return NULL;
3946 Py_INCREF(Py_None);
3947 return Py_None;
3948}
3949
Tim Peters6d6c1a32001-08-02 04:15:00 +00003950static PyObject *
3951wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3952{
3953 hashfunc func = (hashfunc)wrapped;
3954 long res;
3955
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003956 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003957 return NULL;
3958 res = (*func)(self);
3959 if (res == -1 && PyErr_Occurred())
3960 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00003961 return PyLong_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003962}
3963
Tim Peters6d6c1a32001-08-02 04:15:00 +00003964static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003965wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003966{
3967 ternaryfunc func = (ternaryfunc)wrapped;
3968
Guido van Rossumc8e56452001-10-22 00:43:43 +00003969 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003970}
3971
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972static PyObject *
3973wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3974{
3975 richcmpfunc func = (richcmpfunc)wrapped;
3976 PyObject *other;
3977
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003978 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003979 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003980 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981 return (*func)(self, other, op);
3982}
3983
3984#undef RICHCMP_WRAPPER
3985#define RICHCMP_WRAPPER(NAME, OP) \
3986static PyObject * \
3987richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3988{ \
3989 return wrap_richcmpfunc(self, args, wrapped, OP); \
3990}
3991
Jack Jansen8e938b42001-08-08 15:29:49 +00003992RICHCMP_WRAPPER(lt, Py_LT)
3993RICHCMP_WRAPPER(le, Py_LE)
3994RICHCMP_WRAPPER(eq, Py_EQ)
3995RICHCMP_WRAPPER(ne, Py_NE)
3996RICHCMP_WRAPPER(gt, Py_GT)
3997RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003998
Tim Peters6d6c1a32001-08-02 04:15:00 +00003999static PyObject *
4000wrap_next(PyObject *self, PyObject *args, void *wrapped)
4001{
4002 unaryfunc func = (unaryfunc)wrapped;
4003 PyObject *res;
4004
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004005 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004006 return NULL;
4007 res = (*func)(self);
4008 if (res == NULL && !PyErr_Occurred())
4009 PyErr_SetNone(PyExc_StopIteration);
4010 return res;
4011}
4012
Tim Peters6d6c1a32001-08-02 04:15:00 +00004013static PyObject *
4014wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4015{
4016 descrgetfunc func = (descrgetfunc)wrapped;
4017 PyObject *obj;
4018 PyObject *type = NULL;
4019
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004020 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004021 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004022 if (obj == Py_None)
4023 obj = NULL;
4024 if (type == Py_None)
4025 type = NULL;
4026 if (type == NULL &&obj == NULL) {
4027 PyErr_SetString(PyExc_TypeError,
4028 "__get__(None, None) is invalid");
4029 return NULL;
4030 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004031 return (*func)(self, obj, type);
4032}
4033
Tim Peters6d6c1a32001-08-02 04:15:00 +00004034static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004035wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004036{
4037 descrsetfunc func = (descrsetfunc)wrapped;
4038 PyObject *obj, *value;
4039 int ret;
4040
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004041 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004042 return NULL;
4043 ret = (*func)(self, obj, value);
4044 if (ret < 0)
4045 return NULL;
4046 Py_INCREF(Py_None);
4047 return Py_None;
4048}
Guido van Rossum22b13872002-08-06 21:41:44 +00004049
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004050static PyObject *
4051wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4052{
4053 descrsetfunc func = (descrsetfunc)wrapped;
4054 PyObject *obj;
4055 int ret;
4056
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004057 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004058 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004059 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004060 ret = (*func)(self, obj, NULL);
4061 if (ret < 0)
4062 return NULL;
4063 Py_INCREF(Py_None);
4064 return Py_None;
4065}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004066
Tim Peters6d6c1a32001-08-02 04:15:00 +00004067static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004068wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004069{
4070 initproc func = (initproc)wrapped;
4071
Guido van Rossumc8e56452001-10-22 00:43:43 +00004072 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004073 return NULL;
4074 Py_INCREF(Py_None);
4075 return Py_None;
4076}
4077
Tim Peters6d6c1a32001-08-02 04:15:00 +00004078static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004079tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004080{
Barry Warsaw60f01882001-08-22 19:24:42 +00004081 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004082 PyObject *arg0, *res;
4083
4084 if (self == NULL || !PyType_Check(self))
4085 Py_FatalError("__new__() called with non-type 'self'");
4086 type = (PyTypeObject *)self;
4087 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004088 PyErr_Format(PyExc_TypeError,
4089 "%s.__new__(): not enough arguments",
4090 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004091 return NULL;
4092 }
4093 arg0 = PyTuple_GET_ITEM(args, 0);
4094 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004095 PyErr_Format(PyExc_TypeError,
4096 "%s.__new__(X): X is not a type object (%s)",
4097 type->tp_name,
Christian Heimes90aa7642007-12-19 02:45:37 +00004098 Py_TYPE(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004099 return NULL;
4100 }
4101 subtype = (PyTypeObject *)arg0;
4102 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004103 PyErr_Format(PyExc_TypeError,
4104 "%s.__new__(%s): %s is not a subtype of %s",
4105 type->tp_name,
4106 subtype->tp_name,
4107 subtype->tp_name,
4108 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004109 return NULL;
4110 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004111
4112 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004113 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004114 most derived base that's not a heap type is this type. */
4115 staticbase = subtype;
4116 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4117 staticbase = staticbase->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004118 /* If staticbase is NULL now, it is a really weird type.
4119 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004120 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004121 PyErr_Format(PyExc_TypeError,
4122 "%s.__new__(%s) is not safe, use %s.__new__()",
4123 type->tp_name,
4124 subtype->tp_name,
4125 staticbase == NULL ? "?" : staticbase->tp_name);
4126 return NULL;
4127 }
4128
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004129 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4130 if (args == NULL)
4131 return NULL;
4132 res = type->tp_new(subtype, args, kwds);
4133 Py_DECREF(args);
4134 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004135}
4136
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004137static struct PyMethodDef tp_new_methoddef[] = {
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004138 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004139 PyDoc_STR("T.__new__(S, ...) -> "
Guido van Rossumd8faa362007-04-27 19:54:29 +00004140 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004141 {0}
4142};
4143
4144static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004145add_tp_new_wrapper(PyTypeObject *type)
4146{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004147 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004148
Guido van Rossum687ae002001-10-15 22:03:32 +00004149 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004150 return 0;
4151 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004152 if (func == NULL)
4153 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004154 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004155 Py_DECREF(func);
4156 return -1;
4157 }
4158 Py_DECREF(func);
4159 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004160}
4161
Guido van Rossumf040ede2001-08-07 16:40:56 +00004162/* Slot wrappers that call the corresponding __foo__ slot. See comments
4163 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004164
Guido van Rossumdc91b992001-08-08 22:26:22 +00004165#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004166static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004167FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004168{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004169 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004170 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004171}
4172
Guido van Rossumdc91b992001-08-08 22:26:22 +00004173#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004174static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004175FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004176{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004177 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004178 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004179}
4180
Guido van Rossumcd118802003-01-06 22:57:47 +00004181/* Boolean helper for SLOT1BINFULL().
4182 right.__class__ is a nontrivial subclass of left.__class__. */
4183static int
4184method_is_overloaded(PyObject *left, PyObject *right, char *name)
4185{
4186 PyObject *a, *b;
4187 int ok;
4188
Christian Heimes90aa7642007-12-19 02:45:37 +00004189 b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004190 if (b == NULL) {
4191 PyErr_Clear();
4192 /* If right doesn't have it, it's not overloaded */
4193 return 0;
4194 }
4195
Christian Heimes90aa7642007-12-19 02:45:37 +00004196 a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004197 if (a == NULL) {
4198 PyErr_Clear();
4199 Py_DECREF(b);
4200 /* If right has it but left doesn't, it's overloaded */
4201 return 1;
4202 }
4203
4204 ok = PyObject_RichCompareBool(a, b, Py_NE);
4205 Py_DECREF(a);
4206 Py_DECREF(b);
4207 if (ok < 0) {
4208 PyErr_Clear();
4209 return 0;
4210 }
4211
4212 return ok;
4213}
4214
Guido van Rossumdc91b992001-08-08 22:26:22 +00004215
4216#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004217static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004218FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004219{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004220 static PyObject *cache_str, *rcache_str; \
Christian Heimes90aa7642007-12-19 02:45:37 +00004221 int do_other = Py_TYPE(self) != Py_TYPE(other) && \
4222 Py_TYPE(other)->tp_as_number != NULL && \
4223 Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4224 if (Py_TYPE(self)->tp_as_number != NULL && \
4225 Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004226 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004227 if (do_other && \
Christian Heimes90aa7642007-12-19 02:45:37 +00004228 PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004229 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004230 r = call_maybe( \
4231 other, ROPSTR, &rcache_str, "(O)", self); \
4232 if (r != Py_NotImplemented) \
4233 return r; \
4234 Py_DECREF(r); \
4235 do_other = 0; \
4236 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004237 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004238 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004239 if (r != Py_NotImplemented || \
Christian Heimes90aa7642007-12-19 02:45:37 +00004240 Py_TYPE(other) == Py_TYPE(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004241 return r; \
4242 Py_DECREF(r); \
4243 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004244 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004245 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004246 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004247 } \
4248 Py_INCREF(Py_NotImplemented); \
4249 return Py_NotImplemented; \
4250}
4251
4252#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4253 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4254
4255#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4256static PyObject * \
4257FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4258{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004259 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004260 return call_method(self, OPSTR, &cache_str, \
4261 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004262}
4263
Martin v. Löwis18e16552006-02-15 17:27:45 +00004264static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004265slot_sq_length(PyObject *self)
4266{
Guido van Rossum2730b132001-08-28 18:22:14 +00004267 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004268 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004269 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004270
4271 if (res == NULL)
4272 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00004273 len = PyLong_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004274 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004275 if (len < 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00004276 if (!PyErr_Occurred())
4277 PyErr_SetString(PyExc_ValueError,
4278 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004279 return -1;
4280 }
Guido van Rossum26111622001-10-01 16:42:49 +00004281 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004282}
4283
Guido van Rossumf4593e02001-10-03 12:09:30 +00004284/* Super-optimized version of slot_sq_item.
4285 Other slots could do the same... */
4286static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004287slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004288{
4289 static PyObject *getitem_str;
4290 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4291 descrgetfunc f;
4292
4293 if (getitem_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004294 getitem_str = PyUnicode_InternFromString("__getitem__");
Guido van Rossumf4593e02001-10-03 12:09:30 +00004295 if (getitem_str == NULL)
4296 return NULL;
4297 }
Christian Heimes90aa7642007-12-19 02:45:37 +00004298 func = _PyType_Lookup(Py_TYPE(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004299 if (func != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +00004300 if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004301 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004302 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00004303 func = f(func, self, (PyObject *)(Py_TYPE(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004304 if (func == NULL) {
4305 return NULL;
4306 }
4307 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004308 ival = PyLong_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004309 if (ival != NULL) {
4310 args = PyTuple_New(1);
4311 if (args != NULL) {
4312 PyTuple_SET_ITEM(args, 0, ival);
4313 retval = PyObject_Call(func, args, NULL);
4314 Py_XDECREF(args);
4315 Py_XDECREF(func);
4316 return retval;
4317 }
4318 }
4319 }
4320 else {
4321 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4322 }
4323 Py_XDECREF(args);
4324 Py_XDECREF(ival);
4325 Py_XDECREF(func);
4326 return NULL;
4327}
4328
Tim Peters6d6c1a32001-08-02 04:15:00 +00004329static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004330slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004331{
4332 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004333 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004334
4335 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004336 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004337 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004338 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004339 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004340 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004341 if (res == NULL)
4342 return -1;
4343 Py_DECREF(res);
4344 return 0;
4345}
4346
4347static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00004348slot_sq_contains(PyObject *self, PyObject *value)
4349{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004350 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004351 int result = -1;
4352
Guido van Rossum60718732001-08-28 17:47:51 +00004353 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004354
Guido van Rossum55f20992001-10-01 17:18:22 +00004355 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004356 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004357 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004358 if (args == NULL)
4359 res = NULL;
4360 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004361 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004362 Py_DECREF(args);
4363 }
4364 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004365 if (res != NULL) {
4366 result = PyObject_IsTrue(res);
4367 Py_DECREF(res);
4368 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004369 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004370 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004371 /* Possible results: -1 and 1 */
4372 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004373 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004374 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004375 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004376}
4377
Tim Peters6d6c1a32001-08-02 04:15:00 +00004378#define slot_mp_length slot_sq_length
4379
Guido van Rossumdc91b992001-08-08 22:26:22 +00004380SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004381
4382static int
4383slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4384{
4385 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004386 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004387
4388 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004389 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004390 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004391 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004392 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004393 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004394 if (res == NULL)
4395 return -1;
4396 Py_DECREF(res);
4397 return 0;
4398}
4399
Guido van Rossumdc91b992001-08-08 22:26:22 +00004400SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4401SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4402SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004403SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4404SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4405
Jeremy Hylton938ace62002-07-17 16:30:39 +00004406static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004407
4408SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4409 nb_power, "__pow__", "__rpow__")
4410
4411static PyObject *
4412slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4413{
Guido van Rossum2730b132001-08-28 18:22:14 +00004414 static PyObject *pow_str;
4415
Guido van Rossumdc91b992001-08-08 22:26:22 +00004416 if (modulus == Py_None)
4417 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004418 /* Three-arg power doesn't use __rpow__. But ternary_op
4419 can call this when the second argument's type uses
4420 slot_nb_power, so check before calling self.__pow__. */
Christian Heimes90aa7642007-12-19 02:45:37 +00004421 if (Py_TYPE(self)->tp_as_number != NULL &&
4422 Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004423 return call_method(self, "__pow__", &pow_str,
4424 "(OO)", other, modulus);
4425 }
4426 Py_INCREF(Py_NotImplemented);
4427 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004428}
4429
4430SLOT0(slot_nb_negative, "__neg__")
4431SLOT0(slot_nb_positive, "__pos__")
4432SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004433
4434static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004435slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004436{
Tim Petersea7f75d2002-12-07 21:39:16 +00004437 PyObject *func, *args;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004438 static PyObject *bool_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004439 int result = -1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004440 int from_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004441
Jack Diederich4dafcc42006-11-28 19:15:13 +00004442 func = lookup_maybe(self, "__bool__", &bool_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004443 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004444 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004445 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004446 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004447 if (func == NULL)
4448 return PyErr_Occurred() ? -1 : 1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004449 from_len = 1;
Tim Petersea7f75d2002-12-07 21:39:16 +00004450 }
4451 args = PyTuple_New(0);
4452 if (args != NULL) {
4453 PyObject *temp = PyObject_Call(func, args, NULL);
4454 Py_DECREF(args);
4455 if (temp != NULL) {
Jack Diederich4dafcc42006-11-28 19:15:13 +00004456 if (from_len) {
4457 /* enforced by slot_nb_len */
Jeremy Hylton090a3492003-06-27 16:46:45 +00004458 result = PyObject_IsTrue(temp);
Jack Diederich4dafcc42006-11-28 19:15:13 +00004459 }
4460 else if (PyBool_Check(temp)) {
4461 result = PyObject_IsTrue(temp);
4462 }
Jeremy Hylton090a3492003-06-27 16:46:45 +00004463 else {
4464 PyErr_Format(PyExc_TypeError,
Jack Diederich4dafcc42006-11-28 19:15:13 +00004465 "__bool__ should return "
4466 "bool, returned %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00004467 Py_TYPE(temp)->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004468 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004469 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004470 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004471 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004472 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004473 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004474 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004475}
4476
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004477
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004478static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004479slot_nb_index(PyObject *self)
4480{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004481 static PyObject *index_str;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004482 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004483}
4484
4485
Guido van Rossumdc91b992001-08-08 22:26:22 +00004486SLOT0(slot_nb_invert, "__invert__")
4487SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4488SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4489SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4490SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4491SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004492
Guido van Rossumdc91b992001-08-08 22:26:22 +00004493SLOT0(slot_nb_int, "__int__")
4494SLOT0(slot_nb_long, "__long__")
4495SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004496SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4497SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4498SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004499SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004500/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4501static PyObject *
4502slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4503{
4504 static PyObject *cache_str;
4505 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4506}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004507SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4508SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4509SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4510SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4511SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4512SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4513 "__floordiv__", "__rfloordiv__")
4514SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4515SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4516SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004517
4518static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004519half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004520{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004521 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004522 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004523 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004524
Guido van Rossum60718732001-08-28 17:47:51 +00004525 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004526 if (func == NULL) {
4527 PyErr_Clear();
4528 }
4529 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004530 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004531 if (args == NULL)
4532 res = NULL;
4533 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004534 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004535 Py_DECREF(args);
4536 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004537 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004538 if (res != Py_NotImplemented) {
4539 if (res == NULL)
4540 return -2;
Christian Heimes217cfd12007-12-02 14:31:20 +00004541 c = PyLong_AsLong(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004542 Py_DECREF(res);
4543 if (c == -1 && PyErr_Occurred())
4544 return -2;
4545 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4546 }
4547 Py_DECREF(res);
4548 }
4549 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004550}
4551
Guido van Rossumab3b0342001-09-18 20:38:53 +00004552/* This slot is published for the benefit of try_3way_compare in object.c */
4553int
4554_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004555{
4556 int c;
4557
Christian Heimes90aa7642007-12-19 02:45:37 +00004558 if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004559 c = half_compare(self, other);
4560 if (c <= 1)
4561 return c;
4562 }
Christian Heimes90aa7642007-12-19 02:45:37 +00004563 if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004564 c = half_compare(other, self);
4565 if (c < -1)
4566 return -2;
4567 if (c <= 1)
4568 return -c;
4569 }
4570 return (void *)self < (void *)other ? -1 :
4571 (void *)self > (void *)other ? 1 : 0;
4572}
4573
4574static PyObject *
4575slot_tp_repr(PyObject *self)
4576{
4577 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004578 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004579
Guido van Rossum60718732001-08-28 17:47:51 +00004580 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004581 if (func != NULL) {
4582 res = PyEval_CallObject(func, NULL);
4583 Py_DECREF(func);
4584 return res;
4585 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004586 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004587 return PyUnicode_FromFormat("<%s object at %p>",
Christian Heimes90aa7642007-12-19 02:45:37 +00004588 Py_TYPE(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004589}
4590
4591static PyObject *
4592slot_tp_str(PyObject *self)
4593{
4594 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004595 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004596
Guido van Rossum60718732001-08-28 17:47:51 +00004597 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004598 if (func != NULL) {
4599 res = PyEval_CallObject(func, NULL);
4600 Py_DECREF(func);
4601 return res;
4602 }
4603 else {
Walter Dörwald1ab83302007-05-18 17:15:44 +00004604 PyObject *ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004605 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004606 res = slot_tp_repr(self);
4607 if (!res)
4608 return NULL;
4609 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
4610 Py_DECREF(res);
4611 return ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004612 }
4613}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004614
4615static long
4616slot_tp_hash(PyObject *self)
4617{
Guido van Rossum4011a242006-08-17 23:09:57 +00004618 PyObject *func, *res;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004619 static PyObject *hash_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004620 long h;
4621
Guido van Rossum60718732001-08-28 17:47:51 +00004622 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004623
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004624 if (func == Py_None) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004625 Py_DECREF(func);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004626 func = NULL;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004627 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004628
4629 if (func == NULL) {
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004630 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00004631 Py_TYPE(self)->tp_name);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004632 return -1;
4633 }
4634
Guido van Rossum4011a242006-08-17 23:09:57 +00004635 res = PyEval_CallObject(func, NULL);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004636 Py_DECREF(func);
4637 if (res == NULL)
4638 return -1;
4639 if (PyLong_Check(res))
4640 h = PyLong_Type.tp_hash(res);
4641 else
Christian Heimes217cfd12007-12-02 14:31:20 +00004642 h = PyLong_AsLong(res);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004643 Py_DECREF(res);
4644 if (h == -1 && !PyErr_Occurred())
4645 h = -2;
4646 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004647}
4648
4649static PyObject *
4650slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4651{
Guido van Rossum60718732001-08-28 17:47:51 +00004652 static PyObject *call_str;
4653 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004654 PyObject *res;
4655
4656 if (meth == NULL)
4657 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004658
Tim Peters6d6c1a32001-08-02 04:15:00 +00004659 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004660
Tim Peters6d6c1a32001-08-02 04:15:00 +00004661 Py_DECREF(meth);
4662 return res;
4663}
4664
Guido van Rossum14a6f832001-10-17 13:59:09 +00004665/* There are two slot dispatch functions for tp_getattro.
4666
4667 - slot_tp_getattro() is used when __getattribute__ is overridden
4668 but no __getattr__ hook is present;
4669
4670 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4671
Guido van Rossumc334df52002-04-04 23:44:47 +00004672 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4673 detects the absence of __getattr__ and then installs the simpler slot if
4674 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004675
Tim Peters6d6c1a32001-08-02 04:15:00 +00004676static PyObject *
4677slot_tp_getattro(PyObject *self, PyObject *name)
4678{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004679 static PyObject *getattribute_str = NULL;
4680 return call_method(self, "__getattribute__", &getattribute_str,
4681 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004682}
4683
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004684static PyObject *
4685slot_tp_getattr_hook(PyObject *self, PyObject *name)
4686{
Christian Heimes90aa7642007-12-19 02:45:37 +00004687 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004688 PyObject *getattr, *getattribute, *res;
4689 static PyObject *getattribute_str = NULL;
4690 static PyObject *getattr_str = NULL;
4691
4692 if (getattr_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004693 getattr_str = PyUnicode_InternFromString("__getattr__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004694 if (getattr_str == NULL)
4695 return NULL;
4696 }
4697 if (getattribute_str == NULL) {
4698 getattribute_str =
Martin v. Löwis5b222132007-06-10 09:51:05 +00004699 PyUnicode_InternFromString("__getattribute__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004700 if (getattribute_str == NULL)
4701 return NULL;
4702 }
4703 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004704 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004705 /* No __getattr__ hook: use a simpler dispatcher */
4706 tp->tp_getattro = slot_tp_getattro;
4707 return slot_tp_getattro(self, name);
4708 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004709 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004710 if (getattribute == NULL ||
Christian Heimes90aa7642007-12-19 02:45:37 +00004711 (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00004712 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4713 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004714 res = PyObject_GenericGetAttr(self, name);
4715 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00004716 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004717 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004718 PyErr_Clear();
Thomas Wouters477c8d52006-05-27 19:21:47 +00004719 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004720 }
4721 return res;
4722}
4723
Tim Peters6d6c1a32001-08-02 04:15:00 +00004724static int
4725slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4726{
4727 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004728 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004729
4730 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004731 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004732 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004733 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004734 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004735 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004736 if (res == NULL)
4737 return -1;
4738 Py_DECREF(res);
4739 return 0;
4740}
4741
Tim Peters6d6c1a32001-08-02 04:15:00 +00004742static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004743half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004744{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004745 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004746 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004747
Guido van Rossum60718732001-08-28 17:47:51 +00004748 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004749 if (func == NULL) {
4750 PyErr_Clear();
4751 Py_INCREF(Py_NotImplemented);
4752 return Py_NotImplemented;
4753 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004754 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004755 if (args == NULL)
4756 res = NULL;
4757 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004758 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004759 Py_DECREF(args);
4760 }
4761 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004762 return res;
4763}
4764
Guido van Rossumb8f63662001-08-15 23:57:02 +00004765static PyObject *
4766slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4767{
4768 PyObject *res;
4769
Christian Heimes90aa7642007-12-19 02:45:37 +00004770 if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004771 res = half_richcompare(self, other, op);
4772 if (res != Py_NotImplemented)
4773 return res;
4774 Py_DECREF(res);
4775 }
Christian Heimes90aa7642007-12-19 02:45:37 +00004776 if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004777 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004778 if (res != Py_NotImplemented) {
4779 return res;
4780 }
4781 Py_DECREF(res);
4782 }
4783 Py_INCREF(Py_NotImplemented);
4784 return Py_NotImplemented;
4785}
4786
4787static PyObject *
4788slot_tp_iter(PyObject *self)
4789{
4790 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004791 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004792
Guido van Rossum60718732001-08-28 17:47:51 +00004793 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004794 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004795 PyObject *args;
4796 args = res = PyTuple_New(0);
4797 if (args != NULL) {
4798 res = PyObject_Call(func, args, NULL);
4799 Py_DECREF(args);
4800 }
4801 Py_DECREF(func);
4802 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004803 }
4804 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004805 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004806 if (func == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004807 PyErr_Format(PyExc_TypeError,
4808 "'%.200s' object is not iterable",
Christian Heimes90aa7642007-12-19 02:45:37 +00004809 Py_TYPE(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004810 return NULL;
4811 }
4812 Py_DECREF(func);
4813 return PySeqIter_New(self);
4814}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004815
4816static PyObject *
4817slot_tp_iternext(PyObject *self)
4818{
Guido van Rossum2730b132001-08-28 18:22:14 +00004819 static PyObject *next_str;
Georg Brandla18af4e2007-04-21 15:47:16 +00004820 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004821}
4822
Guido van Rossum1a493502001-08-17 16:47:50 +00004823static PyObject *
4824slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4825{
Christian Heimes90aa7642007-12-19 02:45:37 +00004826 PyTypeObject *tp = Py_TYPE(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00004827 PyObject *get;
4828 static PyObject *get_str = NULL;
4829
4830 if (get_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004831 get_str = PyUnicode_InternFromString("__get__");
Guido van Rossum1a493502001-08-17 16:47:50 +00004832 if (get_str == NULL)
4833 return NULL;
4834 }
4835 get = _PyType_Lookup(tp, get_str);
4836 if (get == NULL) {
4837 /* Avoid further slowdowns */
4838 if (tp->tp_descr_get == slot_tp_descr_get)
4839 tp->tp_descr_get = NULL;
4840 Py_INCREF(self);
4841 return self;
4842 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004843 if (obj == NULL)
4844 obj = Py_None;
4845 if (type == NULL)
4846 type = Py_None;
Thomas Wouters477c8d52006-05-27 19:21:47 +00004847 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004848}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004849
4850static int
4851slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4852{
Guido van Rossum2c252392001-08-24 10:13:31 +00004853 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004854 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004855
4856 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004857 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004858 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004859 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004860 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004861 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004862 if (res == NULL)
4863 return -1;
4864 Py_DECREF(res);
4865 return 0;
4866}
4867
4868static int
4869slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4870{
Guido van Rossum60718732001-08-28 17:47:51 +00004871 static PyObject *init_str;
4872 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004873 PyObject *res;
4874
4875 if (meth == NULL)
4876 return -1;
4877 res = PyObject_Call(meth, args, kwds);
4878 Py_DECREF(meth);
4879 if (res == NULL)
4880 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004881 if (res != Py_None) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004882 PyErr_Format(PyExc_TypeError,
4883 "__init__() should return None, not '%.200s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00004884 Py_TYPE(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004885 Py_DECREF(res);
4886 return -1;
4887 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004888 Py_DECREF(res);
4889 return 0;
4890}
4891
4892static PyObject *
4893slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4894{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004895 static PyObject *new_str;
4896 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004897 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004898 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004899
Guido van Rossum7bed2132002-08-08 21:57:53 +00004900 if (new_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004901 new_str = PyUnicode_InternFromString("__new__");
Guido van Rossum7bed2132002-08-08 21:57:53 +00004902 if (new_str == NULL)
4903 return NULL;
4904 }
4905 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004906 if (func == NULL)
4907 return NULL;
4908 assert(PyTuple_Check(args));
4909 n = PyTuple_GET_SIZE(args);
4910 newargs = PyTuple_New(n+1);
4911 if (newargs == NULL)
4912 return NULL;
4913 Py_INCREF(type);
4914 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4915 for (i = 0; i < n; i++) {
4916 x = PyTuple_GET_ITEM(args, i);
4917 Py_INCREF(x);
4918 PyTuple_SET_ITEM(newargs, i+1, x);
4919 }
4920 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004921 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004922 Py_DECREF(func);
4923 return x;
4924}
4925
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004926static void
4927slot_tp_del(PyObject *self)
4928{
4929 static PyObject *del_str = NULL;
4930 PyObject *del, *res;
4931 PyObject *error_type, *error_value, *error_traceback;
4932
4933 /* Temporarily resurrect the object. */
4934 assert(self->ob_refcnt == 0);
4935 self->ob_refcnt = 1;
4936
4937 /* Save the current exception, if any. */
4938 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4939
4940 /* Execute __del__ method, if any. */
4941 del = lookup_maybe(self, "__del__", &del_str);
4942 if (del != NULL) {
4943 res = PyEval_CallObject(del, NULL);
4944 if (res == NULL)
4945 PyErr_WriteUnraisable(del);
4946 else
4947 Py_DECREF(res);
4948 Py_DECREF(del);
4949 }
4950
4951 /* Restore the saved exception. */
4952 PyErr_Restore(error_type, error_value, error_traceback);
4953
4954 /* Undo the temporary resurrection; can't use DECREF here, it would
4955 * cause a recursive call.
4956 */
4957 assert(self->ob_refcnt > 0);
4958 if (--self->ob_refcnt == 0)
4959 return; /* this is the normal path out */
4960
4961 /* __del__ resurrected it! Make it look like the original Py_DECREF
4962 * never happened.
4963 */
4964 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004965 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004966 _Py_NewReference(self);
4967 self->ob_refcnt = refcnt;
4968 }
Christian Heimes90aa7642007-12-19 02:45:37 +00004969 assert(!PyType_IS_GC(Py_TYPE(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004970 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00004971 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
4972 * we need to undo that. */
4973 _Py_DEC_REFTOTAL;
4974 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4975 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004976 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4977 * _Py_NewReference bumped tp_allocs: both of those need to be
4978 * undone.
4979 */
4980#ifdef COUNT_ALLOCS
Christian Heimes90aa7642007-12-19 02:45:37 +00004981 --Py_TYPE(self)->tp_frees;
4982 --Py_TYPE(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004983#endif
4984}
4985
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004986
4987/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004988 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004989 structure, which incorporates the additional structures used for numbers,
4990 sequences and mappings.
4991 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004992 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004993 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4994 terminated with an all-zero entry. (This table is further initialized and
4995 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004996
Guido van Rossum6d204072001-10-21 00:44:31 +00004997typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004998
4999#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005000#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005001#undef ETSLOT
5002#undef SQSLOT
5003#undef MPSLOT
5004#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005005#undef UNSLOT
5006#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005007#undef BINSLOT
5008#undef RBINSLOT
5009
Guido van Rossum6d204072001-10-21 00:44:31 +00005010#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005011 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5012 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005013#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5014 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005015 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005016#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005017 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005018 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005019#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5020 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5021#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5022 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5023#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5024 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5025#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5026 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5027 "x." NAME "() <==> " DOC)
5028#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5029 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5030 "x." NAME "(y) <==> x" DOC "y")
5031#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5032 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5033 "x." NAME "(y) <==> x" DOC "y")
5034#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5035 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5036 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005037#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5038 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5039 "x." NAME "(y) <==> " DOC)
5040#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5041 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5042 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005043
5044static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005045 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005046 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005047 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5048 The logic in abstract.c always falls back to nb_add/nb_multiply in
5049 this case. Defining both the nb_* and the sq_* slots to call the
5050 user-defined methods has unexpected side-effects, as shown by
5051 test_descr.notimplemented() */
5052 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005053 "x.__add__(y) <==> x+y"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005054 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005055 "x.__mul__(n) <==> x*n"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005056 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005057 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005058 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5059 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005060 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005061 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005062 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005063 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005064 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5065 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005066 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005067 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005068 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005069 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005070
Martin v. Löwis18e16552006-02-15 17:27:45 +00005071 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005072 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005073 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005074 wrap_binaryfunc,
5075 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005076 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005077 wrap_objobjargproc,
5078 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005079 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005080 wrap_delitem,
5081 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005082
Guido van Rossum6d204072001-10-21 00:44:31 +00005083 BINSLOT("__add__", nb_add, slot_nb_add,
5084 "+"),
5085 RBINSLOT("__radd__", nb_add, slot_nb_add,
5086 "+"),
5087 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5088 "-"),
5089 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5090 "-"),
5091 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5092 "*"),
5093 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5094 "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005095 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5096 "%"),
5097 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5098 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005099 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005100 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005101 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005102 "divmod(y, x)"),
5103 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5104 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5105 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5106 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5107 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5108 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5109 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5110 "abs(x)"),
Jack Diederich4dafcc42006-11-28 19:15:13 +00005111 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005112 "x != 0"),
5113 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5114 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5115 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5116 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5117 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5118 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5119 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5120 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5121 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5122 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5123 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005124 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5125 "int(x)"),
5126 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5127 "long(x)"),
5128 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5129 "float(x)"),
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005130 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005131 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005132 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5133 wrap_binaryfunc, "+"),
5134 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5135 wrap_binaryfunc, "-"),
5136 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5137 wrap_binaryfunc, "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005138 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5139 wrap_binaryfunc, "%"),
5140 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005141 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005142 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5143 wrap_binaryfunc, "<<"),
5144 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5145 wrap_binaryfunc, ">>"),
5146 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5147 wrap_binaryfunc, "&"),
5148 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5149 wrap_binaryfunc, "^"),
5150 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5151 wrap_binaryfunc, "|"),
5152 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5153 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5154 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5155 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5156 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5157 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5158 IBSLOT("__itruediv__", nb_inplace_true_divide,
5159 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005160
Guido van Rossum6d204072001-10-21 00:44:31 +00005161 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5162 "x.__str__() <==> str(x)"),
5163 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5164 "x.__repr__() <==> repr(x)"),
5165 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5166 "x.__cmp__(y) <==> cmp(x,y)"),
5167 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5168 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005169 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5170 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005171 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005172 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5173 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5174 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5175 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5176 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5177 "x.__setattr__('name', value) <==> x.name = value"),
5178 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5179 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5180 "x.__delattr__('name') <==> del x.name"),
5181 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5182 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5183 "x.__lt__(y) <==> x<y"),
5184 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5185 "x.__le__(y) <==> x<=y"),
5186 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5187 "x.__eq__(y) <==> x==y"),
5188 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5189 "x.__ne__(y) <==> x!=y"),
5190 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5191 "x.__gt__(y) <==> x>y"),
5192 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5193 "x.__ge__(y) <==> x>=y"),
5194 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5195 "x.__iter__() <==> iter(x)"),
Georg Brandla18af4e2007-04-21 15:47:16 +00005196 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5197 "x.__next__() <==> next(x)"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005198 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5199 "descr.__get__(obj[, type]) -> value"),
5200 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5201 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005202 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5203 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005204 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005205 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005206 "see x.__class__.__doc__ for signature",
5207 PyWrapperFlag_KEYWORDS),
5208 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005209 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005210 {NULL}
5211};
5212
Guido van Rossumc334df52002-04-04 23:44:47 +00005213/* Given a type pointer and an offset gotten from a slotdef entry, return a
Guido van Rossumd8faa362007-04-27 19:54:29 +00005214 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005215 the offset to the type pointer, since it takes care to indirect through the
5216 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5217 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005218static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005219slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005220{
5221 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005222 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005223
Guido van Rossume5c691a2003-03-07 15:13:17 +00005224 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005225 assert(offset >= 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005226 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5227 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5228 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005229 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005230 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005231 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5232 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005233 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005234 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005235 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5236 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005237 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005238 }
5239 else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005240 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005241 }
5242 if (ptr != NULL)
5243 ptr += offset;
5244 return (void **)ptr;
5245}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005246
Guido van Rossumc334df52002-04-04 23:44:47 +00005247/* Length of array of slotdef pointers used to store slots with the
5248 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5249 the same __name__, for any __name__. Since that's a static property, it is
5250 appropriate to declare fixed-size arrays for this. */
5251#define MAX_EQUIV 10
5252
5253/* Return a slot pointer for a given name, but ONLY if the attribute has
5254 exactly one slot function. The name must be an interned string. */
5255static void **
5256resolve_slotdups(PyTypeObject *type, PyObject *name)
5257{
5258 /* XXX Maybe this could be optimized more -- but is it worth it? */
5259
5260 /* pname and ptrs act as a little cache */
5261 static PyObject *pname;
5262 static slotdef *ptrs[MAX_EQUIV];
5263 slotdef *p, **pp;
5264 void **res, **ptr;
5265
5266 if (pname != name) {
5267 /* Collect all slotdefs that match name into ptrs. */
5268 pname = name;
5269 pp = ptrs;
5270 for (p = slotdefs; p->name_strobj; p++) {
5271 if (p->name_strobj == name)
5272 *pp++ = p;
5273 }
5274 *pp = NULL;
5275 }
5276
5277 /* Look in all matching slots of the type; if exactly one of these has
Guido van Rossumd8faa362007-04-27 19:54:29 +00005278 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005279 res = NULL;
5280 for (pp = ptrs; *pp; pp++) {
5281 ptr = slotptr(type, (*pp)->offset);
5282 if (ptr == NULL || *ptr == NULL)
5283 continue;
5284 if (res != NULL)
5285 return NULL;
5286 res = ptr;
5287 }
5288 return res;
5289}
5290
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005291/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005292 does some incredibly complex thinking and then sticks something into the
5293 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5294 interests, and then stores a generic wrapper or a specific function into
5295 the slot.) Return a pointer to the next slotdef with a different offset,
5296 because that's convenient for fixup_slot_dispatchers(). */
5297static slotdef *
5298update_one_slot(PyTypeObject *type, slotdef *p)
5299{
5300 PyObject *descr;
5301 PyWrapperDescrObject *d;
5302 void *generic = NULL, *specific = NULL;
5303 int use_generic = 0;
5304 int offset = p->offset;
5305 void **ptr = slotptr(type, offset);
5306
5307 if (ptr == NULL) {
5308 do {
5309 ++p;
5310 } while (p->offset == offset);
5311 return p;
5312 }
5313 do {
5314 descr = _PyType_Lookup(type, p->name_strobj);
5315 if (descr == NULL)
5316 continue;
Christian Heimes90aa7642007-12-19 02:45:37 +00005317 if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005318 void **tptr = resolve_slotdups(type, p->name_strobj);
5319 if (tptr == NULL || tptr == ptr)
5320 generic = p->function;
5321 d = (PyWrapperDescrObject *)descr;
5322 if (d->d_base->wrapper == p->wrapper &&
5323 PyType_IsSubtype(type, d->d_type))
5324 {
5325 if (specific == NULL ||
5326 specific == d->d_wrapped)
5327 specific = d->d_wrapped;
5328 else
5329 use_generic = 1;
5330 }
5331 }
Christian Heimes90aa7642007-12-19 02:45:37 +00005332 else if (Py_TYPE(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005333 PyCFunction_GET_FUNCTION(descr) ==
5334 (PyCFunction)tp_new_wrapper &&
5335 strcmp(p->name, "__new__") == 0)
5336 {
5337 /* The __new__ wrapper is not a wrapper descriptor,
5338 so must be special-cased differently.
5339 If we don't do this, creating an instance will
5340 always use slot_tp_new which will look up
5341 __new__ in the MRO which will call tp_new_wrapper
5342 which will look through the base classes looking
5343 for a static base and call its tp_new (usually
5344 PyType_GenericNew), after performing various
5345 sanity checks and constructing a new argument
5346 list. Cut all that nonsense short -- this speeds
5347 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005348 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005349 /* XXX I'm not 100% sure that there isn't a hole
5350 in this reasoning that requires additional
5351 sanity checks. I'll buy the first person to
5352 point out a bug in this reasoning a beer. */
5353 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005354 else {
5355 use_generic = 1;
5356 generic = p->function;
5357 }
5358 } while ((++p)->offset == offset);
5359 if (specific && !use_generic)
5360 *ptr = specific;
5361 else
5362 *ptr = generic;
5363 return p;
5364}
5365
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005366/* In the type, update the slots whose slotdefs are gathered in the pp array.
5367 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005368static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005369update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005370{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005371 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005372
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005373 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005374 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005375 return 0;
5376}
5377
Guido van Rossumc334df52002-04-04 23:44:47 +00005378/* Comparison function for qsort() to compare slotdefs by their offset, and
5379 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005380static int
5381slotdef_cmp(const void *aa, const void *bb)
5382{
5383 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5384 int c = a->offset - b->offset;
5385 if (c != 0)
5386 return c;
5387 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005388 /* Cannot use a-b, as this gives off_t,
5389 which may lose precision when converted to int. */
5390 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005391}
5392
Guido van Rossumc334df52002-04-04 23:44:47 +00005393/* Initialize the slotdefs table by adding interned string objects for the
5394 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005395static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005396init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005397{
5398 slotdef *p;
5399 static int initialized = 0;
5400
5401 if (initialized)
5402 return;
5403 for (p = slotdefs; p->name; p++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005404 p->name_strobj = PyUnicode_InternFromString(p->name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005405 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005406 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005407 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005408 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5409 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005410 initialized = 1;
5411}
5412
Guido van Rossumc334df52002-04-04 23:44:47 +00005413/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005414static int
5415update_slot(PyTypeObject *type, PyObject *name)
5416{
Guido van Rossumc334df52002-04-04 23:44:47 +00005417 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005418 slotdef *p;
5419 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005420 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005421
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005422 init_slotdefs();
5423 pp = ptrs;
5424 for (p = slotdefs; p->name; p++) {
5425 /* XXX assume name is interned! */
5426 if (p->name_strobj == name)
5427 *pp++ = p;
5428 }
5429 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005430 for (pp = ptrs; *pp; pp++) {
5431 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005432 offset = p->offset;
5433 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005434 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005435 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005436 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005437 if (ptrs[0] == NULL)
5438 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005439 return update_subclasses(type, name,
5440 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005441}
5442
Guido van Rossumc334df52002-04-04 23:44:47 +00005443/* Store the proper functions in the slot dispatches at class (type)
5444 definition time, based upon which operations the class overrides in its
5445 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005446static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005447fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005448{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005449 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005450
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005451 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005452 for (p = slotdefs; p->name; )
5453 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005454}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005455
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005456static void
5457update_all_slots(PyTypeObject* type)
5458{
5459 slotdef *p;
5460
5461 init_slotdefs();
5462 for (p = slotdefs; p->name; p++) {
5463 /* update_slot returns int but can't actually fail */
5464 update_slot(type, p->name_strobj);
5465 }
5466}
5467
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005468/* recurse_down_subclasses() and update_subclasses() are mutually
5469 recursive functions to call a callback for all subclasses,
5470 but refraining from recursing into subclasses that define 'name'. */
5471
5472static int
5473update_subclasses(PyTypeObject *type, PyObject *name,
5474 update_callback callback, void *data)
5475{
5476 if (callback(type, data) < 0)
5477 return -1;
5478 return recurse_down_subclasses(type, name, callback, data);
5479}
5480
5481static int
5482recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5483 update_callback callback, void *data)
5484{
5485 PyTypeObject *subclass;
5486 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005487 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005488
5489 subclasses = type->tp_subclasses;
5490 if (subclasses == NULL)
5491 return 0;
5492 assert(PyList_Check(subclasses));
5493 n = PyList_GET_SIZE(subclasses);
5494 for (i = 0; i < n; i++) {
5495 ref = PyList_GET_ITEM(subclasses, i);
5496 assert(PyWeakref_CheckRef(ref));
5497 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5498 assert(subclass != NULL);
5499 if ((PyObject *)subclass == Py_None)
5500 continue;
5501 assert(PyType_Check(subclass));
5502 /* Avoid recursing down into unaffected classes */
5503 dict = subclass->tp_dict;
5504 if (dict != NULL && PyDict_Check(dict) &&
5505 PyDict_GetItem(dict, name) != NULL)
5506 continue;
5507 if (update_subclasses(subclass, name, callback, data) < 0)
5508 return -1;
5509 }
5510 return 0;
5511}
5512
Guido van Rossum6d204072001-10-21 00:44:31 +00005513/* This function is called by PyType_Ready() to populate the type's
5514 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005515 function slot (like tp_repr) that's defined in the type, one or more
5516 corresponding descriptors are added in the type's tp_dict dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +00005517 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005518 cause more than one descriptor to be added (for example, the nb_add
5519 slot adds both __add__ and __radd__ descriptors) and some function
5520 slots compete for the same descriptor (for example both sq_item and
5521 mp_subscript generate a __getitem__ descriptor).
5522
Guido van Rossumd8faa362007-04-27 19:54:29 +00005523 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005524 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005525 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005526 between competing slots: the members of PyHeapTypeObject are listed
5527 from most general to least general, so the most general slot is
5528 preferred. In particular, because as_mapping comes before as_sequence,
5529 for a type that defines both mp_subscript and sq_item, mp_subscript
5530 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005531
5532 This only adds new descriptors and doesn't overwrite entries in
5533 tp_dict that were previously defined. The descriptors contain a
5534 reference to the C function they must call, so that it's safe if they
5535 are copied into a subtype's __dict__ and the subtype has a different
5536 C function in its slot -- calling the method defined by the
5537 descriptor will call the C function that was used to create it,
5538 rather than the C function present in the slot when it is called.
5539 (This is important because a subtype may have a C function in the
5540 slot that calls the method from the dictionary, and we want to avoid
5541 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005542
5543static int
5544add_operators(PyTypeObject *type)
5545{
5546 PyObject *dict = type->tp_dict;
5547 slotdef *p;
5548 PyObject *descr;
5549 void **ptr;
5550
5551 init_slotdefs();
5552 for (p = slotdefs; p->name; p++) {
5553 if (p->wrapper == NULL)
5554 continue;
5555 ptr = slotptr(type, p->offset);
5556 if (!ptr || !*ptr)
5557 continue;
5558 if (PyDict_GetItem(dict, p->name_strobj))
5559 continue;
5560 descr = PyDescr_NewWrapper(type, p, *ptr);
5561 if (descr == NULL)
5562 return -1;
5563 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5564 return -1;
5565 Py_DECREF(descr);
5566 }
5567 if (type->tp_new != NULL) {
5568 if (add_tp_new_wrapper(type) < 0)
5569 return -1;
5570 }
5571 return 0;
5572}
5573
Guido van Rossum705f0f52001-08-24 16:47:00 +00005574
5575/* Cooperative 'super' */
5576
5577typedef struct {
5578 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005579 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005580 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005581 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005582} superobject;
5583
Guido van Rossum6f799372001-09-20 20:46:19 +00005584static PyMemberDef super_members[] = {
5585 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5586 "the class invoking super()"},
5587 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5588 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005589 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005590 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005591 {0}
5592};
5593
Guido van Rossum705f0f52001-08-24 16:47:00 +00005594static void
5595super_dealloc(PyObject *self)
5596{
5597 superobject *su = (superobject *)self;
5598
Guido van Rossum048eb752001-10-02 21:24:57 +00005599 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005600 Py_XDECREF(su->obj);
5601 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005602 Py_XDECREF(su->obj_type);
Christian Heimes90aa7642007-12-19 02:45:37 +00005603 Py_TYPE(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005604}
5605
5606static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005607super_repr(PyObject *self)
5608{
5609 superobject *su = (superobject *)self;
5610
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005611 if (su->obj_type)
Walter Dörwald1ab83302007-05-18 17:15:44 +00005612 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005613 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005614 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005615 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005616 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00005617 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005618 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005619 su->type ? su->type->tp_name : "NULL");
5620}
5621
5622static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005623super_getattro(PyObject *self, PyObject *name)
5624{
5625 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005626 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005627
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005628 if (!skip) {
5629 /* We want __class__ to return the class of the super object
5630 (i.e. super, or a subclass), not the class of su->obj. */
Martin v. Löwis5b222132007-06-10 09:51:05 +00005631 skip = (PyUnicode_Check(name) &&
5632 PyUnicode_GET_SIZE(name) == 9 &&
5633 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005634 }
5635
5636 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005637 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005638 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005639 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005640 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005641
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005642 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005643 mro = starttype->tp_mro;
5644
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005645 if (mro == NULL)
5646 n = 0;
5647 else {
5648 assert(PyTuple_Check(mro));
5649 n = PyTuple_GET_SIZE(mro);
5650 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005651 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005652 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005653 break;
5654 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005655 i++;
5656 res = NULL;
5657 for (; i < n; i++) {
5658 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005659 if (PyType_Check(tmp))
5660 dict = ((PyTypeObject *)tmp)->tp_dict;
Tim Petersa91e9642001-11-14 23:32:33 +00005661 else
5662 continue;
5663 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005664 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005665 Py_INCREF(res);
Christian Heimes90aa7642007-12-19 02:45:37 +00005666 f = Py_TYPE(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005667 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005668 tmp = f(res,
5669 /* Only pass 'obj' param if
5670 this is instance-mode super
5671 (See SF ID #743627)
5672 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005673 (su->obj == (PyObject *)
5674 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005675 ? (PyObject *)NULL
5676 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005677 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005678 Py_DECREF(res);
5679 res = tmp;
5680 }
5681 return res;
5682 }
5683 }
5684 }
5685 return PyObject_GenericGetAttr(self, name);
5686}
5687
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005688static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005689supercheck(PyTypeObject *type, PyObject *obj)
5690{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005691 /* Check that a super() call makes sense. Return a type object.
5692
5693 obj can be a new-style class, or an instance of one:
5694
Guido van Rossumd8faa362007-04-27 19:54:29 +00005695 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005696 used for class methods; the return value is obj.
5697
5698 - If it is an instance, it must be an instance of 'type'. This is
5699 the normal case; the return value is obj.__class__.
5700
5701 But... when obj is an instance, we want to allow for the case where
Christian Heimes90aa7642007-12-19 02:45:37 +00005702 Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005703 This will allow using super() with a proxy for obj.
5704 */
5705
Guido van Rossum8e80a722003-02-18 19:22:22 +00005706 /* Check for first bullet above (special case) */
5707 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5708 Py_INCREF(obj);
5709 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005710 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005711
5712 /* Normal case */
Christian Heimes90aa7642007-12-19 02:45:37 +00005713 if (PyType_IsSubtype(Py_TYPE(obj), type)) {
5714 Py_INCREF(Py_TYPE(obj));
5715 return Py_TYPE(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005716 }
5717 else {
5718 /* Try the slow way */
5719 static PyObject *class_str = NULL;
5720 PyObject *class_attr;
5721
5722 if (class_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005723 class_str = PyUnicode_FromString("__class__");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005724 if (class_str == NULL)
5725 return NULL;
5726 }
5727
5728 class_attr = PyObject_GetAttr(obj, class_str);
5729
5730 if (class_attr != NULL &&
5731 PyType_Check(class_attr) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00005732 (PyTypeObject *)class_attr != Py_TYPE(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005733 {
5734 int ok = PyType_IsSubtype(
5735 (PyTypeObject *)class_attr, type);
5736 if (ok)
5737 return (PyTypeObject *)class_attr;
5738 }
5739
5740 if (class_attr == NULL)
5741 PyErr_Clear();
5742 else
5743 Py_DECREF(class_attr);
5744 }
5745
Guido van Rossumd8faa362007-04-27 19:54:29 +00005746 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005747 "super(type, obj): "
5748 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005749 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005750}
5751
Guido van Rossum705f0f52001-08-24 16:47:00 +00005752static PyObject *
5753super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5754{
5755 superobject *su = (superobject *)self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005756 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005757
5758 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5759 /* Not binding to an object, or already bound */
5760 Py_INCREF(self);
5761 return self;
5762 }
Christian Heimes90aa7642007-12-19 02:45:37 +00005763 if (Py_TYPE(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005764 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005765 call its type */
Christian Heimes90aa7642007-12-19 02:45:37 +00005766 return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
Guido van Rossumd8faa362007-04-27 19:54:29 +00005767 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005768 else {
5769 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005770 PyTypeObject *obj_type = supercheck(su->type, obj);
5771 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005772 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005773 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005774 NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005775 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005776 return NULL;
5777 Py_INCREF(su->type);
5778 Py_INCREF(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005779 newobj->type = su->type;
5780 newobj->obj = obj;
5781 newobj->obj_type = obj_type;
5782 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005783 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005784}
5785
5786static int
5787super_init(PyObject *self, PyObject *args, PyObject *kwds)
5788{
5789 superobject *su = (superobject *)self;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005790 PyTypeObject *type = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00005791 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005792 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005793
Thomas Wouters89f507f2006-12-13 04:49:30 +00005794 if (!_PyArg_NoKeywords("super", kwds))
5795 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005796 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005797 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005798
5799 if (type == NULL) {
5800 /* Call super(), without args -- fill in from __class__
5801 and first local variable on the stack. */
5802 PyFrameObject *f = PyThreadState_GET()->frame;
5803 PyCodeObject *co = f->f_code;
5804 int i, n;
5805 if (co == NULL) {
5806 PyErr_SetString(PyExc_SystemError,
5807 "super(): no code object");
5808 return -1;
5809 }
5810 if (co->co_argcount == 0) {
5811 PyErr_SetString(PyExc_SystemError,
5812 "super(): no arguments");
5813 return -1;
5814 }
5815 obj = f->f_localsplus[0];
5816 if (obj == NULL) {
5817 PyErr_SetString(PyExc_SystemError,
5818 "super(): arg[0] deleted");
5819 return -1;
5820 }
5821 if (co->co_freevars == NULL)
5822 n = 0;
5823 else {
5824 assert(PyTuple_Check(co->co_freevars));
5825 n = PyTuple_GET_SIZE(co->co_freevars);
5826 }
5827 for (i = 0; i < n; i++) {
5828 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
5829 assert(PyUnicode_Check(name));
5830 if (!PyUnicode_CompareWithASCIIString(name,
5831 "__class__")) {
5832 PyObject *cell =
5833 f->f_localsplus[co->co_nlocals + i];
5834 if (cell == NULL || !PyCell_Check(cell)) {
5835 PyErr_SetString(PyExc_SystemError,
5836 "super(): bad __class__ cell");
5837 return -1;
5838 }
5839 type = (PyTypeObject *) PyCell_GET(cell);
5840 if (type == NULL) {
5841 PyErr_SetString(PyExc_SystemError,
5842 "super(): empty __class__ cell");
5843 return -1;
5844 }
5845 if (!PyType_Check(type)) {
5846 PyErr_Format(PyExc_SystemError,
5847 "super(): __class__ is not a type (%s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00005848 Py_TYPE(type)->tp_name);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005849 return -1;
5850 }
5851 break;
5852 }
5853 }
5854 if (type == NULL) {
5855 PyErr_SetString(PyExc_SystemError,
5856 "super(): __class__ cell not found");
5857 return -1;
5858 }
5859 }
5860
Guido van Rossum705f0f52001-08-24 16:47:00 +00005861 if (obj == Py_None)
5862 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005863 if (obj != NULL) {
5864 obj_type = supercheck(type, obj);
5865 if (obj_type == NULL)
5866 return -1;
5867 Py_INCREF(obj);
5868 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005869 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005870 su->type = type;
5871 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005872 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005873 return 0;
5874}
5875
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005876PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005877"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005878"super(type) -> unbound super object\n"
5879"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005880"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005881"Typical use to call a cooperative superclass method:\n"
5882"class C(B):\n"
5883" def meth(self, arg):\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005884" super().meth(arg)\n"
5885"This works for class methods too:\n"
5886"class C(B):\n"
5887" @classmethod\n"
5888" def cmeth(cls, arg):\n"
5889" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005890
Guido van Rossum048eb752001-10-02 21:24:57 +00005891static int
5892super_traverse(PyObject *self, visitproc visit, void *arg)
5893{
5894 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005895
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005896 Py_VISIT(su->obj);
5897 Py_VISIT(su->type);
5898 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005899
5900 return 0;
5901}
5902
Guido van Rossum705f0f52001-08-24 16:47:00 +00005903PyTypeObject PySuper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005904 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005905 "super", /* tp_name */
5906 sizeof(superobject), /* tp_basicsize */
5907 0, /* tp_itemsize */
5908 /* methods */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005909 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005910 0, /* tp_print */
5911 0, /* tp_getattr */
5912 0, /* tp_setattr */
5913 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005914 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005915 0, /* tp_as_number */
5916 0, /* tp_as_sequence */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005917 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005918 0, /* tp_hash */
5919 0, /* tp_call */
5920 0, /* tp_str */
5921 super_getattro, /* tp_getattro */
5922 0, /* tp_setattro */
5923 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005924 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5925 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005926 super_doc, /* tp_doc */
5927 super_traverse, /* tp_traverse */
5928 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005929 0, /* tp_richcompare */
5930 0, /* tp_weaklistoffset */
5931 0, /* tp_iter */
5932 0, /* tp_iternext */
5933 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005934 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005935 0, /* tp_getset */
5936 0, /* tp_base */
5937 0, /* tp_dict */
5938 super_descr_get, /* tp_descr_get */
5939 0, /* tp_descr_set */
5940 0, /* tp_dictoffset */
5941 super_init, /* tp_init */
5942 PyType_GenericAlloc, /* tp_alloc */
5943 PyType_GenericNew, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005944 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005945};