blob: 49b877db0f30a961d5cab16dd29f2fcc2404aa95 [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"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +000024 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +000025
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Georg Brandlc255c7b2006-02-20 22:27:28 +000029 Py_INCREF(et->ht_name);
30 return et->ht_name;
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000031 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
Martin v. Löwis68192102007-07-21 06:55:02 +000060 type->tp_name, Py_Type(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +000061 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
Georg Brandlc255c7b2006-02-20 22:27:28 +000074 Py_DECREF(et->ht_name);
75 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000076
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +000090 if (!mod) {
91 PyErr_Format(PyExc_AttributeError, "__module__");
92 return 0;
93 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000094 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000095 return mod;
96 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000097 else {
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(
Armin Rigo7ccbca92006-10-04 12:17:45 +0000101 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000102 return PyString_FromString("__builtin__");
103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104}
105
Guido van Rossum3926a632001-09-25 16:25:58 +0000106static int
107type_set_module(PyTypeObject *type, PyObject *value, void *context)
108{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000109 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000110 PyErr_Format(PyExc_TypeError,
111 "can't set %s.__module__", type->tp_name);
112 return -1;
113 }
114 if (!value) {
115 PyErr_Format(PyExc_TypeError,
116 "can't delete %s.__module__", type->tp_name);
117 return -1;
118 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000119
Guido van Rossum3926a632001-09-25 16:25:58 +0000120 return PyDict_SetItemString(type->tp_dict, "__module__", value);
121}
122
Tim Peters6d6c1a32001-08-02 04:15:00 +0000123static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000124type_get_bases(PyTypeObject *type, void *context)
125{
126 Py_INCREF(type->tp_bases);
127 return type->tp_bases;
128}
129
130static PyTypeObject *best_base(PyObject *);
131static int mro_internal(PyTypeObject *);
132static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
133static int add_subclass(PyTypeObject*, PyTypeObject*);
134static void remove_subclass(PyTypeObject *, PyTypeObject *);
135static void update_all_slots(PyTypeObject *);
136
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000137typedef int (*update_callback)(PyTypeObject *, void *);
138static int update_subclasses(PyTypeObject *type, PyObject *name,
139 update_callback callback, void *data);
140static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
141 update_callback callback, void *data);
142
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000143static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145{
146 PyTypeObject *subclass;
147 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000148 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000149
150 subclasses = type->tp_subclasses;
151 if (subclasses == NULL)
152 return 0;
153 assert(PyList_Check(subclasses));
154 n = PyList_GET_SIZE(subclasses);
155 for (i = 0; i < n; i++) {
156 ref = PyList_GET_ITEM(subclasses, i);
157 assert(PyWeakref_CheckRef(ref));
158 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
159 assert(subclass != NULL);
160 if ((PyObject *)subclass == Py_None)
161 continue;
162 assert(PyType_Check(subclass));
163 old_mro = subclass->tp_mro;
164 if (mro_internal(subclass) < 0) {
165 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000166 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000167 }
168 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000169 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000170 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000171 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000172 if (!tuple)
173 return -1;
174 if (PyList_Append(temp, tuple) < 0)
175 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000176 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000177 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000178 if (mro_subclasses(subclass, temp) < 0)
179 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000180 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000181 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000182}
183
184static int
185type_set_bases(PyTypeObject *type, PyObject *value, void *context)
186{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000187 Py_ssize_t i;
188 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000189 PyObject *ob, *temp;
Armin Rigoc0ba52d2007-04-19 14:44:48 +0000190 PyTypeObject *new_base, *old_base;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000191 PyObject *old_bases, *old_mro;
192
193 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
194 PyErr_Format(PyExc_TypeError,
195 "can't set %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!value) {
199 PyErr_Format(PyExc_TypeError,
200 "can't delete %s.__bases__", type->tp_name);
201 return -1;
202 }
203 if (!PyTuple_Check(value)) {
204 PyErr_Format(PyExc_TypeError,
205 "can only assign tuple to %s.__bases__, not %s",
Martin v. Löwis68192102007-07-21 06:55:02 +0000206 type->tp_name, Py_Type(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000207 return -1;
208 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000209 if (PyTuple_GET_SIZE(value) == 0) {
210 PyErr_Format(PyExc_TypeError,
211 "can only assign non-empty tuple to %s.__bases__, not ()",
212 type->tp_name);
213 return -1;
214 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000215 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
216 ob = PyTuple_GET_ITEM(value, i);
217 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
218 PyErr_Format(
219 PyExc_TypeError,
220 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Martin v. Löwis68192102007-07-21 06:55:02 +0000221 type->tp_name, Py_Type(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000222 return -1;
223 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000224 if (PyType_Check(ob)) {
225 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
226 PyErr_SetString(PyExc_TypeError,
227 "a __bases__ item causes an inheritance cycle");
228 return -1;
229 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000230 }
231 }
232
233 new_base = best_base(value);
234
235 if (!new_base) {
236 return -1;
237 }
238
239 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
240 return -1;
241
242 Py_INCREF(new_base);
243 Py_INCREF(value);
244
245 old_bases = type->tp_bases;
246 old_base = type->tp_base;
247 old_mro = type->tp_mro;
248
249 type->tp_bases = value;
250 type->tp_base = new_base;
251
252 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000253 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000254 }
255
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000256 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000257 if (!temp)
258 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000259
260 r = mro_subclasses(type, temp);
261
262 if (r < 0) {
263 for (i = 0; i < PyList_Size(temp); i++) {
264 PyTypeObject* cls;
265 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000266 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
267 "", 2, 2, &cls, &mro);
Armin Rigo796fc992007-04-19 14:56:48 +0000268 Py_INCREF(mro);
269 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000270 cls->tp_mro = mro;
Armin Rigo796fc992007-04-19 14:56:48 +0000271 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000272 }
273 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000274 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000275 }
276
277 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000278
279 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000280 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000281 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000282 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000283
284 /* for now, sod that: just remove from all old_bases,
285 add to all new_bases */
286
287 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
288 ob = PyTuple_GET_ITEM(old_bases, i);
289 if (PyType_Check(ob)) {
290 remove_subclass(
291 (PyTypeObject*)ob, type);
292 }
293 }
294
295 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
296 ob = PyTuple_GET_ITEM(value, i);
297 if (PyType_Check(ob)) {
298 if (add_subclass((PyTypeObject*)ob, type) < 0)
299 r = -1;
300 }
301 }
302
303 update_all_slots(type);
304
305 Py_DECREF(old_bases);
306 Py_DECREF(old_base);
307 Py_DECREF(old_mro);
308
309 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000310
311 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000312 Py_DECREF(type->tp_bases);
313 Py_DECREF(type->tp_base);
314 if (type->tp_mro != old_mro) {
315 Py_DECREF(type->tp_mro);
316 }
317
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000318 type->tp_bases = old_bases;
319 type->tp_base = old_base;
320 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000321
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000322 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000323}
324
325static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000326type_dict(PyTypeObject *type, void *context)
327{
328 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329 Py_INCREF(Py_None);
330 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000331 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000332 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000333}
334
Tim Peters24008312002-03-17 18:56:20 +0000335static PyObject *
336type_get_doc(PyTypeObject *type, void *context)
337{
338 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000339 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000340 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000341 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000342 if (result == NULL) {
343 result = Py_None;
344 Py_INCREF(result);
345 }
Martin v. Löwis68192102007-07-21 06:55:02 +0000346 else if (Py_Type(result)->tp_descr_get) {
347 result = Py_Type(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000348 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000349 }
350 else {
351 Py_INCREF(result);
352 }
Tim Peters24008312002-03-17 18:56:20 +0000353 return result;
354}
355
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000356static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000357 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
358 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000359 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000360 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000361 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000362 {0}
363};
364
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000365static int
366type_compare(PyObject *v, PyObject *w)
367{
368 /* This is called with type objects only. So we
369 can just compare the addresses. */
370 Py_uintptr_t vv = (Py_uintptr_t)v;
371 Py_uintptr_t ww = (Py_uintptr_t)w;
372 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
373}
374
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000375static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000376type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000377{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000378 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000379 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000380
381 mod = type_module(type, NULL);
382 if (mod == NULL)
383 PyErr_Clear();
384 else if (!PyString_Check(mod)) {
385 Py_DECREF(mod);
386 mod = NULL;
387 }
388 name = type_name(type, NULL);
389 if (name == NULL)
390 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000391
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000392 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
393 kind = "class";
394 else
395 kind = "type";
396
Barry Warsaw7ce36942001-08-24 18:34:26 +0000397 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000398 rtn = PyString_FromFormat("<%s '%s.%s'>",
399 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000400 PyString_AS_STRING(mod),
401 PyString_AS_STRING(name));
402 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000403 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000404 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000405
Guido van Rossumc3542212001-08-16 09:18:56 +0000406 Py_XDECREF(mod);
407 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000408 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409}
410
Tim Peters6d6c1a32001-08-02 04:15:00 +0000411static PyObject *
412type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
413{
414 PyObject *obj;
415
416 if (type->tp_new == NULL) {
417 PyErr_Format(PyExc_TypeError,
418 "cannot create '%.100s' instances",
419 type->tp_name);
420 return NULL;
421 }
422
Tim Peters3f996e72001-09-13 19:18:27 +0000423 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000424 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000425 /* Ugly exception: when the call was type(something),
426 don't call tp_init on the result. */
427 if (type == &PyType_Type &&
428 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
429 (kwds == NULL ||
430 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
431 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000432 /* If the returned object is not an instance of type,
433 it won't be initialized. */
434 if (!PyType_IsSubtype(obj->ob_type, type))
435 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000436 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000437 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
438 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000439 type->tp_init(obj, args, kwds) < 0) {
440 Py_DECREF(obj);
441 obj = NULL;
442 }
443 }
444 return obj;
445}
446
447PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000448PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000449{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000450 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000451 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
452 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000453
454 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000455 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000456 else
Anthony Baxtera6286212006-04-11 07:42:36 +0000457 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000458
Neil Schemenauerc806c882001-08-29 23:54:54 +0000459 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000461
Neil Schemenauerc806c882001-08-29 23:54:54 +0000462 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000463
Tim Peters6d6c1a32001-08-02 04:15:00 +0000464 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
465 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000466
Tim Peters6d6c1a32001-08-02 04:15:00 +0000467 if (type->tp_itemsize == 0)
468 PyObject_INIT(obj, type);
469 else
470 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000471
Tim Peters6d6c1a32001-08-02 04:15:00 +0000472 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000473 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000474 return obj;
475}
476
477PyObject *
478PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
479{
480 return type->tp_alloc(type, 0);
481}
482
Guido van Rossum9475a232001-10-05 20:51:39 +0000483/* Helpers for subtyping */
484
485static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000486traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
487{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000488 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000489 PyMemberDef *mp;
490
Martin v. Löwis68192102007-07-21 06:55:02 +0000491 n = Py_Size(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000492 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000493 for (i = 0; i < n; i++, mp++) {
494 if (mp->type == T_OBJECT_EX) {
495 char *addr = (char *)self + mp->offset;
496 PyObject *obj = *(PyObject **)addr;
497 if (obj != NULL) {
498 int err = visit(obj, arg);
499 if (err)
500 return err;
501 }
502 }
503 }
504 return 0;
505}
506
507static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000508subtype_traverse(PyObject *self, visitproc visit, void *arg)
509{
510 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000511 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000512
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000513 /* Find the nearest base with a different tp_traverse,
514 and traverse slots while we're at it */
Martin v. Löwis68192102007-07-21 06:55:02 +0000515 type = Py_Type(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000516 base = type;
517 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Martin v. Löwis68192102007-07-21 06:55:02 +0000518 if (Py_Size(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000519 int err = traverse_slots(base, self, visit, arg);
520 if (err)
521 return err;
522 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000523 base = base->tp_base;
524 assert(base);
525 }
526
527 if (type->tp_dictoffset != base->tp_dictoffset) {
528 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Woutersc6e55062006-04-15 21:47:09 +0000529 if (dictptr && *dictptr)
530 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000531 }
532
Thomas Woutersc6e55062006-04-15 21:47:09 +0000533 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000534 /* For a heaptype, the instances count as references
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000535 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000536 can find cycles involving this link. */
Thomas Woutersc6e55062006-04-15 21:47:09 +0000537 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000538
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000539 if (basetraverse)
540 return basetraverse(self, visit, arg);
541 return 0;
542}
543
544static void
545clear_slots(PyTypeObject *type, PyObject *self)
546{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000547 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000548 PyMemberDef *mp;
549
Martin v. Löwis68192102007-07-21 06:55:02 +0000550 n = Py_Size(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000551 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000552 for (i = 0; i < n; i++, mp++) {
553 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
554 char *addr = (char *)self + mp->offset;
555 PyObject *obj = *(PyObject **)addr;
556 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000557 *(PyObject **)addr = NULL;
Thomas Woutersedf17d82006-04-15 17:28:34 +0000558 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000559 }
560 }
561 }
562}
563
564static int
565subtype_clear(PyObject *self)
566{
567 PyTypeObject *type, *base;
568 inquiry baseclear;
569
570 /* Find the nearest base with a different tp_clear
571 and clear slots while we're at it */
Martin v. Löwis68192102007-07-21 06:55:02 +0000572 type = Py_Type(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000573 base = type;
574 while ((baseclear = base->tp_clear) == subtype_clear) {
Martin v. Löwis68192102007-07-21 06:55:02 +0000575 if (Py_Size(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000576 clear_slots(base, self);
577 base = base->tp_base;
578 assert(base);
579 }
580
Guido van Rossuma3862092002-06-10 15:24:42 +0000581 /* There's no need to clear the instance dict (if any);
582 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000583
584 if (baseclear)
585 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000586 return 0;
587}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000588
589static void
590subtype_dealloc(PyObject *self)
591{
Guido van Rossum14227b42001-12-06 02:35:58 +0000592 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000593 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594
Guido van Rossum22b13872002-08-06 21:41:44 +0000595 /* Extract the type; we expect it to be a heap type */
Martin v. Löwis68192102007-07-21 06:55:02 +0000596 type = Py_Type(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000597 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000598
Guido van Rossum22b13872002-08-06 21:41:44 +0000599 /* Test whether the type has GC exactly once */
600
601 if (!PyType_IS_GC(type)) {
602 /* It's really rare to find a dynamic type that doesn't have
603 GC; it can only happen when deriving from 'object' and not
604 adding any slots or instance variables. This allows
605 certain simplifications: there's no need to call
606 clear_slots(), or DECREF the dict, or clear weakrefs. */
607
608 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000609 if (type->tp_del) {
610 type->tp_del(self);
611 if (self->ob_refcnt > 0)
612 return;
613 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000614
615 /* Find the nearest base with a different tp_dealloc */
616 base = type;
617 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Martin v. Löwis68192102007-07-21 06:55:02 +0000618 assert(Py_Size(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000619 base = base->tp_base;
620 assert(base);
621 }
622
623 /* Call the base tp_dealloc() */
624 assert(basedealloc);
625 basedealloc(self);
626
627 /* Can't reference self beyond this point */
628 Py_DECREF(type);
629
630 /* Done */
631 return;
632 }
633
634 /* We get here only if the type has GC */
635
636 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000637 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000638 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000639 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000640 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000641 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000642 /* DO NOT restore GC tracking at this point. weakref callbacks
643 * (if any, and whether directly here or indirectly in something we
644 * call) may trigger GC, and if self is tracked at that point, it
645 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000646 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000647
Guido van Rossum59195fd2003-06-13 20:54:40 +0000648 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000649 base = type;
650 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000651 base = base->tp_base;
652 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000653 }
654
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000655 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000656 the finalizer (__del__), clearing slots, or clearing the instance
657 dict. */
658
Guido van Rossum1987c662003-05-29 14:29:23 +0000659 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
660 PyObject_ClearWeakRefs(self);
661
662 /* Maybe call finalizer; exit early if resurrected */
663 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000664 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000665 type->tp_del(self);
666 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000667 goto endlabel; /* resurrected */
668 else
669 _PyObject_GC_UNTRACK(self);
Brett Cannonf5bee302007-01-23 23:21:22 +0000670 /* New weakrefs could be created during the finalizer call.
671 If this occurs, clear them out without calling their
672 finalizers since they might rely on part of the object
673 being finalized that has already been destroyed. */
674 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
675 /* Modeled after GET_WEAKREFS_LISTPTR() */
676 PyWeakReference **list = (PyWeakReference **) \
677 PyObject_GET_WEAKREFS_LISTPTR(self);
678 while (*list)
679 _PyWeakref_ClearRef(*list);
680 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000681 }
682
Guido van Rossum59195fd2003-06-13 20:54:40 +0000683 /* Clear slots up to the nearest base with a different tp_dealloc */
684 base = type;
685 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Martin v. Löwis68192102007-07-21 06:55:02 +0000686 if (Py_Size(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000687 clear_slots(base, self);
688 base = base->tp_base;
689 assert(base);
690 }
691
Tim Peters6d6c1a32001-08-02 04:15:00 +0000692 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000693 if (type->tp_dictoffset && !base->tp_dictoffset) {
694 PyObject **dictptr = _PyObject_GetDictPtr(self);
695 if (dictptr != NULL) {
696 PyObject *dict = *dictptr;
697 if (dict != NULL) {
698 Py_DECREF(dict);
699 *dictptr = NULL;
700 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000701 }
702 }
703
Tim Peters0bd743c2003-11-13 22:50:00 +0000704 /* Call the base tp_dealloc(); first retrack self if
705 * basedealloc knows about gc.
706 */
707 if (PyType_IS_GC(base))
708 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000709 assert(basedealloc);
710 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000711
712 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000713 Py_DECREF(type);
714
Guido van Rossum0906e072002-08-07 20:42:09 +0000715 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000716 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000717 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000718 --_PyTrash_delete_nesting;
719
720 /* Explanation of the weirdness around the trashcan macros:
721
722 Q. What do the trashcan macros do?
723
724 A. Read the comment titled "Trashcan mechanism" in object.h.
725 For one, this explains why there must be a call to GC-untrack
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000726 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000727 trashcan code, the answers to the following questions don't make
728 sense.
729
730 Q. Why do we GC-untrack before the trashcan and then immediately
731 GC-track again afterward?
732
733 A. In the case that the base class is GC-aware, the base class
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000734 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000735 UNTRACK macro, this will crash when the object is already
736 untracked. Because we don't know what the base class does, the
737 only safe thing is to make sure the object is tracked when we
738 call the base class dealloc. But... The trashcan begin macro
739 requires that the object is *untracked* before it is called. So
740 the dance becomes:
741
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000742 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000743 trashcan begin
744 GC track
745
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000746 Q. Why did the last question say "immediately GC-track again"?
747 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000748
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000749 A. Because the code *used* to re-track immediately. Bad Idea.
750 self has a refcount of 0, and if gc ever gets its hands on it
751 (which can happen if any weakref callback gets invoked), it
752 looks like trash to gc too, and gc also tries to delete self
753 then. But we're already deleting self. Double dealloction is
754 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000755
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000756 Q. Why the bizarre (net-zero) manipulation of
757 _PyTrash_delete_nesting around the trashcan macros?
758
759 A. Some base classes (e.g. list) also use the trashcan mechanism.
760 The following scenario used to be possible:
761
762 - suppose the trashcan level is one below the trashcan limit
763
764 - subtype_dealloc() is called
765
766 - the trashcan limit is not yet reached, so the trashcan level
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000767 is incremented and the code between trashcan begin and end is
768 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000769
770 - this destroys much of the object's contents, including its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000771 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000772
773 - basedealloc() is called; this is really list_dealloc(), or
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000774 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000775
776 - the trashcan limit is now reached, so the object is put on the
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000777 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000778
779 - basedealloc() returns
780
781 - subtype_dealloc() decrefs the object's type
782
783 - subtype_dealloc() returns
784
785 - later, the trashcan code starts deleting the objects from its
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000786 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000787
788 - subtype_dealloc() is called *AGAIN* for the same object
789
790 - at the very least (if the destroyed slots and __dict__ don't
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000791 cause problems) the object's type gets decref'ed a second
792 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000793
794 The remedy is to make sure that if the code between trashcan
795 begin and end in subtype_dealloc() is called, the code between
796 trashcan begin and end in basedealloc() will also be called.
797 This is done by decrementing the level after passing into the
798 trashcan block, and incrementing it just before leaving the
799 block.
800
801 But now it's possible that a chain of objects consisting solely
802 of objects whose deallocator is subtype_dealloc() will defeat
803 the trashcan mechanism completely: the decremented level means
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000804 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000805 *increment* the level *before* entering the trashcan block, and
806 matchingly decrement it after leaving. This means the trashcan
807 code will trigger a little early, but that's no big deal.
808
809 Q. Are there any live examples of code in need of all this
810 complexity?
811
812 A. Yes. See SF bug 668433 for code that crashed (when Python was
813 compiled in debug mode) before the trashcan level manipulations
814 were added. For more discussion, see SF patches 581742, 575073
815 and bug 574207.
816 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000817}
818
Jeremy Hylton938ace62002-07-17 16:30:39 +0000819static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000820
Tim Peters6d6c1a32001-08-02 04:15:00 +0000821/* type test with subclassing support */
822
823int
824PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
825{
826 PyObject *mro;
827
Guido van Rossum9478d072001-09-07 18:52:13 +0000828 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
829 return b == a || b == &PyBaseObject_Type;
830
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831 mro = a->tp_mro;
832 if (mro != NULL) {
833 /* Deal with multiple inheritance without recursion
834 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000835 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000836 assert(PyTuple_Check(mro));
837 n = PyTuple_GET_SIZE(mro);
838 for (i = 0; i < n; i++) {
839 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
840 return 1;
841 }
842 return 0;
843 }
844 else {
845 /* a is not completely initilized yet; follow tp_base */
846 do {
847 if (a == b)
848 return 1;
849 a = a->tp_base;
850 } while (a != NULL);
851 return b == &PyBaseObject_Type;
852 }
853}
854
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000855/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000856 without looking in the instance dictionary
857 (so we can't use PyObject_GetAttr) but still binding
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000858 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +0000859 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000860 static variable used to cache the interned Python string.
861
862 Two variants:
863
864 - lookup_maybe() returns NULL without raising an exception
865 when the _PyType_Lookup() call fails;
866
867 - lookup_method() always raises an exception upon errors.
868*/
Guido van Rossum60718732001-08-28 17:47:51 +0000869
870static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000871lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000872{
873 PyObject *res;
874
875 if (*attrobj == NULL) {
876 *attrobj = PyString_InternFromString(attrstr);
877 if (*attrobj == NULL)
878 return NULL;
879 }
Martin v. Löwis68192102007-07-21 06:55:02 +0000880 res = _PyType_Lookup(Py_Type(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000881 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000882 descrgetfunc f;
Martin v. Löwis68192102007-07-21 06:55:02 +0000883 if ((f = Py_Type(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +0000884 Py_INCREF(res);
885 else
Martin v. Löwis68192102007-07-21 06:55:02 +0000886 res = f(res, self, (PyObject *)(Py_Type(self)));
Guido van Rossum60718732001-08-28 17:47:51 +0000887 }
888 return res;
889}
890
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000891static PyObject *
892lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
893{
894 PyObject *res = lookup_maybe(self, attrstr, attrobj);
895 if (res == NULL && !PyErr_Occurred())
896 PyErr_SetObject(PyExc_AttributeError, *attrobj);
897 return res;
898}
899
Guido van Rossum2730b132001-08-28 18:22:14 +0000900/* A variation of PyObject_CallMethod that uses lookup_method()
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +0000901 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +0000902 as lookup_method to cache the interned name string object. */
903
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000904static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000905call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
906{
907 va_list va;
908 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000909 va_start(va, format);
910
Guido van Rossumda21c012001-10-03 00:50:18 +0000911 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000912 if (func == NULL) {
913 va_end(va);
914 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000915 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000916 return NULL;
917 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000918
919 if (format && *format)
920 args = Py_VaBuildValue(format, va);
921 else
922 args = PyTuple_New(0);
923
924 va_end(va);
925
926 if (args == NULL)
927 return NULL;
928
929 assert(PyTuple_Check(args));
930 retval = PyObject_Call(func, args, NULL);
931
932 Py_DECREF(args);
933 Py_DECREF(func);
934
935 return retval;
936}
937
938/* Clone of call_method() that returns NotImplemented when the lookup fails. */
939
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000940static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000941call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
942{
943 va_list va;
944 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000945 va_start(va, format);
946
Guido van Rossumda21c012001-10-03 00:50:18 +0000947 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000948 if (func == NULL) {
949 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000950 if (!PyErr_Occurred()) {
951 Py_INCREF(Py_NotImplemented);
952 return Py_NotImplemented;
953 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000954 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000955 }
956
957 if (format && *format)
958 args = Py_VaBuildValue(format, va);
959 else
960 args = PyTuple_New(0);
961
962 va_end(va);
963
Guido van Rossum717ce002001-09-14 16:58:08 +0000964 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000965 return NULL;
966
Guido van Rossum717ce002001-09-14 16:58:08 +0000967 assert(PyTuple_Check(args));
968 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000969
970 Py_DECREF(args);
971 Py_DECREF(func);
972
973 return retval;
974}
975
Tim Petersa91e9642001-11-14 23:32:33 +0000976static int
977fill_classic_mro(PyObject *mro, PyObject *cls)
978{
979 PyObject *bases, *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000980 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +0000981
982 assert(PyList_Check(mro));
983 assert(PyClass_Check(cls));
984 i = PySequence_Contains(mro, cls);
985 if (i < 0)
986 return -1;
987 if (!i) {
988 if (PyList_Append(mro, cls) < 0)
989 return -1;
990 }
991 bases = ((PyClassObject *)cls)->cl_bases;
992 assert(bases && PyTuple_Check(bases));
993 n = PyTuple_GET_SIZE(bases);
994 for (i = 0; i < n; i++) {
995 base = PyTuple_GET_ITEM(bases, i);
996 if (fill_classic_mro(mro, base) < 0)
997 return -1;
998 }
999 return 0;
1000}
1001
1002static PyObject *
1003classic_mro(PyObject *cls)
1004{
1005 PyObject *mro;
1006
1007 assert(PyClass_Check(cls));
1008 mro = PyList_New(0);
1009 if (mro != NULL) {
1010 if (fill_classic_mro(mro, cls) == 0)
1011 return mro;
1012 Py_DECREF(mro);
1013 }
1014 return NULL;
1015}
1016
Tim Petersea7f75d2002-12-07 21:39:16 +00001017/*
Guido van Rossum1f121312002-11-14 19:49:16 +00001018 Method resolution order algorithm C3 described in
1019 "A Monotonic Superclass Linearization for Dylan",
1020 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +00001021 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +00001022 (OOPSLA 1996)
1023
Guido van Rossum98f33732002-11-25 21:36:54 +00001024 Some notes about the rules implied by C3:
1025
Tim Petersea7f75d2002-12-07 21:39:16 +00001026 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001027 It isn't legal to repeat a class in a list of base classes.
1028
1029 The next three properties are the 3 constraints in "C3".
1030
Tim Petersea7f75d2002-12-07 21:39:16 +00001031 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001032 If A precedes B in C's MRO, then A will precede B in the MRO of all
1033 subclasses of C.
1034
1035 Monotonicity.
1036 The MRO of a class must be an extension without reordering of the
1037 MRO of each of its superclasses.
1038
1039 Extended Precedence Graph (EPG).
1040 Linearization is consistent if there is a path in the EPG from
1041 each class to all its successors in the linearization. See
1042 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001043 */
1044
Tim Petersea7f75d2002-12-07 21:39:16 +00001045static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001046tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001047 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +00001048 size = PyList_GET_SIZE(list);
1049
1050 for (j = whence+1; j < size; j++) {
1051 if (PyList_GET_ITEM(list, j) == o)
1052 return 1;
1053 }
1054 return 0;
1055}
1056
Guido van Rossum98f33732002-11-25 21:36:54 +00001057static PyObject *
1058class_name(PyObject *cls)
1059{
1060 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1061 if (name == NULL) {
1062 PyErr_Clear();
1063 Py_XDECREF(name);
1064 name = PyObject_Repr(cls);
1065 }
1066 if (name == NULL)
1067 return NULL;
1068 if (!PyString_Check(name)) {
1069 Py_DECREF(name);
1070 return NULL;
1071 }
1072 return name;
1073}
1074
1075static int
1076check_duplicates(PyObject *list)
1077{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001078 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001079 /* Let's use a quadratic time algorithm,
1080 assuming that the bases lists is short.
1081 */
1082 n = PyList_GET_SIZE(list);
1083 for (i = 0; i < n; i++) {
1084 PyObject *o = PyList_GET_ITEM(list, i);
1085 for (j = i + 1; j < n; j++) {
1086 if (PyList_GET_ITEM(list, j) == o) {
1087 o = class_name(o);
1088 PyErr_Format(PyExc_TypeError,
1089 "duplicate base class %s",
1090 o ? PyString_AS_STRING(o) : "?");
1091 Py_XDECREF(o);
1092 return -1;
1093 }
1094 }
1095 }
1096 return 0;
1097}
1098
1099/* Raise a TypeError for an MRO order disagreement.
1100
1101 It's hard to produce a good error message. In the absence of better
1102 insight into error reporting, report the classes that were candidates
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001103 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001104 order in which they should be put in the MRO, but it's hard to
1105 diagnose what constraint can't be satisfied.
1106*/
1107
1108static void
1109set_mro_error(PyObject *to_merge, int *remain)
1110{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001111 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001112 char buf[1000];
1113 PyObject *k, *v;
1114 PyObject *set = PyDict_New();
Georg Brandl5c170fd2006-03-17 19:03:25 +00001115 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001116
1117 to_merge_size = PyList_GET_SIZE(to_merge);
1118 for (i = 0; i < to_merge_size; i++) {
1119 PyObject *L = PyList_GET_ITEM(to_merge, i);
1120 if (remain[i] < PyList_GET_SIZE(L)) {
1121 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Georg Brandl5c170fd2006-03-17 19:03:25 +00001122 if (PyDict_SetItem(set, c, Py_None) < 0) {
1123 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001124 return;
Georg Brandl5c170fd2006-03-17 19:03:25 +00001125 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001126 }
1127 }
1128 n = PyDict_Size(set);
1129
Raymond Hettingerf394df42003-04-06 19:13:41 +00001130 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1131consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001132 i = 0;
Skip Montanaro429433b2006-04-18 00:35:43 +00001133 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001134 PyObject *name = class_name(k);
1135 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1136 name ? PyString_AS_STRING(name) : "?");
1137 Py_XDECREF(name);
Skip Montanaro429433b2006-04-18 00:35:43 +00001138 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001139 buf[off++] = ',';
1140 buf[off] = '\0';
1141 }
1142 }
1143 PyErr_SetString(PyExc_TypeError, buf);
1144 Py_DECREF(set);
1145}
1146
Tim Petersea7f75d2002-12-07 21:39:16 +00001147static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001148pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001149 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001150 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001151 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001152
Guido van Rossum1f121312002-11-14 19:49:16 +00001153 to_merge_size = PyList_GET_SIZE(to_merge);
1154
Guido van Rossum98f33732002-11-25 21:36:54 +00001155 /* remain stores an index into each sublist of to_merge.
1156 remain[i] is the index of the next base in to_merge[i]
1157 that is not included in acc.
1158 */
Anthony Baxtera6286212006-04-11 07:42:36 +00001159 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001160 if (remain == NULL)
1161 return -1;
1162 for (i = 0; i < to_merge_size; i++)
1163 remain[i] = 0;
1164
1165 again:
1166 empty_cnt = 0;
1167 for (i = 0; i < to_merge_size; i++) {
1168 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001169
Guido van Rossum1f121312002-11-14 19:49:16 +00001170 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1171
1172 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1173 empty_cnt++;
1174 continue;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001175 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001176
Guido van Rossum98f33732002-11-25 21:36:54 +00001177 /* Choose next candidate for MRO.
1178
1179 The input sequences alone can determine the choice.
1180 If not, choose the class which appears in the MRO
1181 of the earliest direct superclass of the new class.
1182 */
1183
Guido van Rossum1f121312002-11-14 19:49:16 +00001184 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1185 for (j = 0; j < to_merge_size; j++) {
1186 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001187 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001188 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001189 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001190 }
1191 ok = PyList_Append(acc, candidate);
1192 if (ok < 0) {
1193 PyMem_Free(remain);
1194 return -1;
1195 }
1196 for (j = 0; j < to_merge_size; j++) {
1197 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001198 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1199 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001200 remain[j]++;
1201 }
1202 }
1203 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001204 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001205 }
1206
Guido van Rossum98f33732002-11-25 21:36:54 +00001207 if (empty_cnt == to_merge_size) {
1208 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001209 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001210 }
1211 set_mro_error(to_merge, remain);
1212 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001213 return -1;
1214}
1215
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216static PyObject *
1217mro_implementation(PyTypeObject *type)
1218{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001219 Py_ssize_t i, n;
1220 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001222 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001223
Guido van Rossum63517572002-06-18 16:44:57 +00001224 if(type->tp_dict == NULL) {
1225 if(PyType_Ready(type) < 0)
1226 return NULL;
1227 }
1228
Guido van Rossum98f33732002-11-25 21:36:54 +00001229 /* Find a superclass linearization that honors the constraints
1230 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001231 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001232
1233 to_merge is a list of lists, where each list is a superclass
1234 linearization implied by a base class. The last element of
1235 to_merge is the declared list of bases.
1236 */
1237
Tim Peters6d6c1a32001-08-02 04:15:00 +00001238 bases = type->tp_bases;
1239 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001240
1241 to_merge = PyList_New(n+1);
1242 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001243 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001244
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001246 PyObject *base = PyTuple_GET_ITEM(bases, i);
1247 PyObject *parentMRO;
1248 if (PyType_Check(base))
1249 parentMRO = PySequence_List(
1250 ((PyTypeObject*)base)->tp_mro);
1251 else
1252 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001253 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001254 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255 return NULL;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001256 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001257
1258 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001259 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001260
1261 bases_aslist = PySequence_List(bases);
1262 if (bases_aslist == NULL) {
1263 Py_DECREF(to_merge);
1264 return NULL;
1265 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001266 /* This is just a basic sanity check. */
1267 if (check_duplicates(bases_aslist) < 0) {
1268 Py_DECREF(to_merge);
1269 Py_DECREF(bases_aslist);
1270 return NULL;
1271 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001272 PyList_SET_ITEM(to_merge, n, bases_aslist);
1273
1274 result = Py_BuildValue("[O]", (PyObject *)type);
1275 if (result == NULL) {
1276 Py_DECREF(to_merge);
1277 return NULL;
1278 }
1279
1280 ok = pmerge(result, to_merge);
1281 Py_DECREF(to_merge);
1282 if (ok < 0) {
1283 Py_DECREF(result);
1284 return NULL;
1285 }
1286
Tim Peters6d6c1a32001-08-02 04:15:00 +00001287 return result;
1288}
1289
1290static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001291mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292{
1293 PyTypeObject *type = (PyTypeObject *)self;
1294
Tim Peters6d6c1a32001-08-02 04:15:00 +00001295 return mro_implementation(type);
1296}
1297
1298static int
1299mro_internal(PyTypeObject *type)
1300{
1301 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001302 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303
Martin v. Löwis68192102007-07-21 06:55:02 +00001304 if (Py_Type(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305 result = mro_implementation(type);
1306 }
1307 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001308 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001309 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001310 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311 if (mro == NULL)
1312 return -1;
1313 result = PyObject_CallObject(mro, NULL);
1314 Py_DECREF(mro);
1315 }
1316 if (result == NULL)
1317 return -1;
1318 tuple = PySequence_Tuple(result);
1319 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001320 if (tuple == NULL)
1321 return -1;
1322 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001323 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001324 PyObject *cls;
1325 PyTypeObject *solid;
1326
1327 solid = solid_base(type);
1328
1329 len = PyTuple_GET_SIZE(tuple);
1330
1331 for (i = 0; i < len; i++) {
1332 PyTypeObject *t;
1333 cls = PyTuple_GET_ITEM(tuple, i);
1334 if (PyClass_Check(cls))
1335 continue;
1336 else if (!PyType_Check(cls)) {
1337 PyErr_Format(PyExc_TypeError,
1338 "mro() returned a non-class ('%.500s')",
Martin v. Löwis68192102007-07-21 06:55:02 +00001339 Py_Type(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001340 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001341 return -1;
1342 }
1343 t = (PyTypeObject*)cls;
1344 if (!PyType_IsSubtype(solid, solid_base(t))) {
1345 PyErr_Format(PyExc_TypeError,
1346 "mro() returned base with unsuitable layout ('%.500s')",
1347 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001348 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001349 return -1;
1350 }
1351 }
1352 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001353 type->tp_mro = tuple;
1354 return 0;
1355}
1356
1357
1358/* Calculate the best base amongst multiple base classes.
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001359 This is the first one that's on the path to the "solid base". */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001360
1361static PyTypeObject *
1362best_base(PyObject *bases)
1363{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001364 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001365 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001366 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367
1368 assert(PyTuple_Check(bases));
1369 n = PyTuple_GET_SIZE(bases);
1370 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001371 base = NULL;
1372 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001374 base_proto = PyTuple_GET_ITEM(bases, i);
1375 if (PyClass_Check(base_proto))
1376 continue;
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001377 if (!PyType_Check(base_proto)) {
1378 PyErr_SetString(
1379 PyExc_TypeError,
1380 "bases must be types");
1381 return NULL;
1382 }
Tim Petersa91e9642001-11-14 23:32:33 +00001383 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001384 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001385 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001386 return NULL;
1387 }
1388 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001389 if (winner == NULL) {
1390 winner = candidate;
1391 base = base_i;
1392 }
1393 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001394 ;
1395 else if (PyType_IsSubtype(candidate, winner)) {
1396 winner = candidate;
1397 base = base_i;
1398 }
1399 else {
1400 PyErr_SetString(
1401 PyExc_TypeError,
1402 "multiple bases have "
1403 "instance lay-out conflict");
1404 return NULL;
1405 }
1406 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001407 if (base == NULL)
1408 PyErr_SetString(PyExc_TypeError,
1409 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001410 return base;
1411}
1412
1413static int
1414extra_ivars(PyTypeObject *type, PyTypeObject *base)
1415{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001416 size_t t_size = type->tp_basicsize;
1417 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418
Guido van Rossum9676b222001-08-17 20:32:36 +00001419 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001420 if (type->tp_itemsize || base->tp_itemsize) {
1421 /* If itemsize is involved, stricter rules */
1422 return t_size != b_size ||
1423 type->tp_itemsize != base->tp_itemsize;
1424 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001425 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001426 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1427 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001428 t_size -= sizeof(PyObject *);
1429 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Armin Rigo9790a272007-05-02 19:23:31 +00001430 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1431 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001432 t_size -= sizeof(PyObject *);
1433
1434 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001435}
1436
1437static PyTypeObject *
1438solid_base(PyTypeObject *type)
1439{
1440 PyTypeObject *base;
1441
1442 if (type->tp_base)
1443 base = solid_base(type->tp_base);
1444 else
1445 base = &PyBaseObject_Type;
1446 if (extra_ivars(type, base))
1447 return type;
1448 else
1449 return base;
1450}
1451
Jeremy Hylton938ace62002-07-17 16:30:39 +00001452static void object_dealloc(PyObject *);
1453static int object_init(PyObject *, PyObject *, PyObject *);
1454static int update_slot(PyTypeObject *, PyObject *);
1455static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001456
Armin Rigo9790a272007-05-02 19:23:31 +00001457/*
1458 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1459 * inherited from various builtin types. The builtin base usually provides
1460 * its own __dict__ descriptor, so we use that when we can.
1461 */
1462static PyTypeObject *
1463get_builtin_base_with_dict(PyTypeObject *type)
1464{
1465 while (type->tp_base != NULL) {
1466 if (type->tp_dictoffset != 0 &&
1467 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1468 return type;
1469 type = type->tp_base;
1470 }
1471 return NULL;
1472}
1473
1474static PyObject *
1475get_dict_descriptor(PyTypeObject *type)
1476{
1477 static PyObject *dict_str;
1478 PyObject *descr;
1479
1480 if (dict_str == NULL) {
1481 dict_str = PyString_InternFromString("__dict__");
1482 if (dict_str == NULL)
1483 return NULL;
1484 }
1485 descr = _PyType_Lookup(type, dict_str);
1486 if (descr == NULL || !PyDescr_IsData(descr))
1487 return NULL;
1488
1489 return descr;
1490}
1491
1492static void
1493raise_dict_descr_error(PyObject *obj)
1494{
1495 PyErr_Format(PyExc_TypeError,
1496 "this __dict__ descriptor does not support "
1497 "'%.200s' objects", obj->ob_type->tp_name);
1498}
1499
Tim Peters6d6c1a32001-08-02 04:15:00 +00001500static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001501subtype_dict(PyObject *obj, void *context)
1502{
Armin Rigo9790a272007-05-02 19:23:31 +00001503 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001504 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001505 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001506
Armin Rigo9790a272007-05-02 19:23:31 +00001507 base = get_builtin_base_with_dict(obj->ob_type);
1508 if (base != NULL) {
1509 descrgetfunc func;
1510 PyObject *descr = get_dict_descriptor(base);
1511 if (descr == NULL) {
1512 raise_dict_descr_error(obj);
1513 return NULL;
1514 }
1515 func = descr->ob_type->tp_descr_get;
1516 if (func == NULL) {
1517 raise_dict_descr_error(obj);
1518 return NULL;
1519 }
1520 return func(descr, obj, (PyObject *)(obj->ob_type));
1521 }
1522
1523 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001524 if (dictptr == NULL) {
1525 PyErr_SetString(PyExc_AttributeError,
1526 "This object has no __dict__");
1527 return NULL;
1528 }
1529 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001530 if (dict == NULL)
1531 *dictptr = dict = PyDict_New();
1532 Py_XINCREF(dict);
1533 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001534}
1535
Guido van Rossum6661be32001-10-26 04:26:12 +00001536static int
1537subtype_setdict(PyObject *obj, PyObject *value, void *context)
1538{
Armin Rigo9790a272007-05-02 19:23:31 +00001539 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001540 PyObject *dict;
Armin Rigo9790a272007-05-02 19:23:31 +00001541 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001542
Armin Rigo9790a272007-05-02 19:23:31 +00001543 base = get_builtin_base_with_dict(obj->ob_type);
1544 if (base != NULL) {
1545 descrsetfunc func;
1546 PyObject *descr = get_dict_descriptor(base);
1547 if (descr == NULL) {
1548 raise_dict_descr_error(obj);
1549 return -1;
1550 }
1551 func = descr->ob_type->tp_descr_set;
1552 if (func == NULL) {
1553 raise_dict_descr_error(obj);
1554 return -1;
1555 }
1556 return func(descr, obj, value);
1557 }
1558
1559 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001560 if (dictptr == NULL) {
1561 PyErr_SetString(PyExc_AttributeError,
1562 "This object has no __dict__");
1563 return -1;
1564 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001565 if (value != NULL && !PyDict_Check(value)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001566 PyErr_Format(PyExc_TypeError,
1567 "__dict__ must be set to a dictionary, "
Martin v. Löwis68192102007-07-21 06:55:02 +00001568 "not a '%.200s'", Py_Type(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001569 return -1;
1570 }
1571 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001572 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001573 *dictptr = value;
1574 Py_XDECREF(dict);
1575 return 0;
1576}
1577
Guido van Rossumad47da02002-08-12 19:05:44 +00001578static PyObject *
1579subtype_getweakref(PyObject *obj, void *context)
1580{
1581 PyObject **weaklistptr;
1582 PyObject *result;
1583
Martin v. Löwis68192102007-07-21 06:55:02 +00001584 if (Py_Type(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001585 PyErr_SetString(PyExc_AttributeError,
Fred Drake7a36f5f2006-08-04 05:17:21 +00001586 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001587 return NULL;
1588 }
Martin v. Löwis68192102007-07-21 06:55:02 +00001589 assert(Py_Type(obj)->tp_weaklistoffset > 0);
1590 assert(Py_Type(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1591 (size_t)(Py_Type(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001592 weaklistptr = (PyObject **)
Martin v. Löwis68192102007-07-21 06:55:02 +00001593 ((char *)obj + Py_Type(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001594 if (*weaklistptr == NULL)
1595 result = Py_None;
1596 else
1597 result = *weaklistptr;
1598 Py_INCREF(result);
1599 return result;
1600}
1601
Guido van Rossum373c7412003-01-07 13:41:37 +00001602/* Three variants on the subtype_getsets list. */
1603
1604static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001605 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001606 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001607 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001608 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001609 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001610};
1611
Guido van Rossum373c7412003-01-07 13:41:37 +00001612static PyGetSetDef subtype_getsets_dict_only[] = {
1613 {"__dict__", subtype_dict, subtype_setdict,
1614 PyDoc_STR("dictionary for instance variables (if defined)")},
1615 {0}
1616};
1617
1618static PyGetSetDef subtype_getsets_weakref_only[] = {
1619 {"__weakref__", subtype_getweakref, NULL,
1620 PyDoc_STR("list of weak references to the object (if defined)")},
1621 {0}
1622};
1623
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001624static int
1625valid_identifier(PyObject *s)
1626{
Guido van Rossum03013a02002-07-16 14:30:28 +00001627 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001628 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001629
1630 if (!PyString_Check(s)) {
Georg Brandlccff7852006-06-18 22:17:29 +00001631 PyErr_Format(PyExc_TypeError,
1632 "__slots__ items must be strings, not '%.200s'",
Martin v. Löwis68192102007-07-21 06:55:02 +00001633 Py_Type(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001634 return 0;
1635 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001636 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001637 n = PyString_GET_SIZE(s);
1638 /* We must reject an empty name. As a hack, we bump the
1639 length to 1 so that the loop will balk on the trailing \0. */
1640 if (n == 0)
1641 n = 1;
1642 for (i = 0; i < n; i++, p++) {
1643 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1644 PyErr_SetString(PyExc_TypeError,
1645 "__slots__ must be identifiers");
1646 return 0;
1647 }
1648 }
1649 return 1;
1650}
1651
Martin v. Löwisd919a592002-10-14 21:07:28 +00001652#ifdef Py_USING_UNICODE
1653/* Replace Unicode objects in slots. */
1654
1655static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001656_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001657{
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001658 PyObject *tmp = NULL;
1659 PyObject *slot_name, *new_name;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001660 Py_ssize_t i;
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001661
Martin v. Löwisd919a592002-10-14 21:07:28 +00001662 for (i = 0; i < nslots; i++) {
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001663 if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
1664 if (tmp == NULL) {
1665 tmp = PySequence_List(slots);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001666 if (tmp == NULL)
1667 return NULL;
1668 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001669 new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
1670 NULL);
1671 if (new_name == NULL) {
Martin v. Löwisd919a592002-10-14 21:07:28 +00001672 Py_DECREF(tmp);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001673 return NULL;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001674 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001675 Py_INCREF(new_name);
1676 PyList_SET_ITEM(tmp, i, new_name);
1677 Py_DECREF(slot_name);
Martin v. Löwisd919a592002-10-14 21:07:28 +00001678 }
1679 }
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001680 if (tmp != NULL) {
1681 slots = PyList_AsTuple(tmp);
1682 Py_DECREF(tmp);
1683 }
1684 return slots;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001685}
1686#endif
1687
Guido van Rossumf102e242007-03-23 18:53:03 +00001688/* Forward */
1689static int
1690object_init(PyObject *self, PyObject *args, PyObject *kwds);
1691
1692static int
1693type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1694{
1695 int res;
1696
1697 assert(args != NULL && PyTuple_Check(args));
1698 assert(kwds == NULL || PyDict_Check(kwds));
1699
1700 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1701 PyErr_SetString(PyExc_TypeError,
1702 "type.__init__() takes no keyword arguments");
1703 return -1;
1704 }
1705
1706 if (args != NULL && PyTuple_Check(args) &&
1707 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1708 PyErr_SetString(PyExc_TypeError,
1709 "type.__init__() takes 1 or 3 arguments");
1710 return -1;
1711 }
1712
1713 /* Call object.__init__(self) now. */
1714 /* XXX Could call super(type, cls).__init__() but what's the point? */
1715 args = PyTuple_GetSlice(args, 0, 0);
1716 res = object_init(cls, args, NULL);
1717 Py_DECREF(args);
1718 return res;
1719}
1720
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001721static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001722type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1723{
1724 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001725 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001726 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001727 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001728 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001729 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001730 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001731 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001732
Tim Peters3abca122001-10-27 19:37:48 +00001733 assert(args != NULL && PyTuple_Check(args));
1734 assert(kwds == NULL || PyDict_Check(kwds));
1735
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001736 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001737 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001738 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1739 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001740
1741 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1742 PyObject *x = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis68192102007-07-21 06:55:02 +00001743 Py_INCREF(Py_Type(x));
1744 return (PyObject *) Py_Type(x);
Tim Peters3abca122001-10-27 19:37:48 +00001745 }
1746
1747 /* SF bug 475327 -- if that didn't trigger, we need 3
1748 arguments. but PyArg_ParseTupleAndKeywords below may give
1749 a msg saying type() needs exactly 3. */
1750 if (nargs + nkwds != 3) {
1751 PyErr_SetString(PyExc_TypeError,
1752 "type() takes 1 or 3 arguments");
1753 return NULL;
1754 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001755 }
1756
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001757 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001758 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1759 &name,
1760 &PyTuple_Type, &bases,
1761 &PyDict_Type, &dict))
1762 return NULL;
1763
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001764 /* Determine the proper metatype to deal with this,
1765 and check for metatype conflicts while we're at it.
1766 Note that if some other metatype wins to contract,
1767 it's possible that its instances are not types. */
1768 nbases = PyTuple_GET_SIZE(bases);
1769 winner = metatype;
1770 for (i = 0; i < nbases; i++) {
1771 tmp = PyTuple_GET_ITEM(bases, i);
1772 tmptype = tmp->ob_type;
1773 if (tmptype == &PyClass_Type)
1774 continue; /* Special case classic classes */
1775 if (PyType_IsSubtype(winner, tmptype))
1776 continue;
1777 if (PyType_IsSubtype(tmptype, winner)) {
1778 winner = tmptype;
1779 continue;
Jeremy Hyltonfa955692007-02-27 18:29:45 +00001780 }
Armin Rigoc0ba52d2007-04-19 14:44:48 +00001781 PyErr_SetString(PyExc_TypeError,
1782 "metaclass conflict: "
1783 "the metaclass of a derived class "
1784 "must be a (non-strict) subclass "
1785 "of the metaclasses of all its bases");
1786 return NULL;
1787 }
1788 if (winner != metatype) {
1789 if (winner->tp_new != type_new) /* Pass it to the winner */
1790 return winner->tp_new(winner, args, kwds);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001791 metatype = winner;
1792 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001793
1794 /* Adjust for empty tuple bases */
1795 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001796 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001797 if (bases == NULL)
1798 return NULL;
1799 nbases = 1;
1800 }
1801 else
1802 Py_INCREF(bases);
1803
1804 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1805
1806 /* Calculate best base, and check that all bases are type objects */
1807 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001808 if (base == NULL) {
1809 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001811 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001812 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1813 PyErr_Format(PyExc_TypeError,
1814 "type '%.100s' is not an acceptable base type",
1815 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001816 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001817 return NULL;
1818 }
1819
Tim Peters6d6c1a32001-08-02 04:15:00 +00001820 /* Check for a __slots__ sequence variable in dict, and count it */
1821 slots = PyDict_GetItemString(dict, "__slots__");
1822 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001823 add_dict = 0;
1824 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001825 may_add_dict = base->tp_dictoffset == 0;
1826 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1827 if (slots == NULL) {
1828 if (may_add_dict) {
1829 add_dict++;
1830 }
1831 if (may_add_weak) {
1832 add_weak++;
1833 }
1834 }
1835 else {
1836 /* Have slots */
1837
Tim Peters6d6c1a32001-08-02 04:15:00 +00001838 /* Make it into a tuple */
Neal Norwitzcbd9ee62007-04-14 05:25:50 +00001839 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001840 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001841 else
1842 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001843 if (slots == NULL) {
1844 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001846 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001847 assert(PyTuple_Check(slots));
1848
1849 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001850 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001851 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001852 PyErr_Format(PyExc_TypeError,
1853 "nonempty __slots__ "
1854 "not supported for subtype of '%s'",
1855 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001856 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001857 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001858 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001859 return NULL;
1860 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001861
Martin v. Löwisd919a592002-10-14 21:07:28 +00001862#ifdef Py_USING_UNICODE
1863 tmp = _unicode_to_string(slots, nslots);
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001864 if (tmp == NULL)
1865 goto bad_slots;
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001866 if (tmp != slots) {
1867 Py_DECREF(slots);
1868 slots = tmp;
1869 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001870#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001871 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001872 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001873 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1874 char *s;
1875 if (!valid_identifier(tmp))
1876 goto bad_slots;
1877 assert(PyString_Check(tmp));
1878 s = PyString_AS_STRING(tmp);
1879 if (strcmp(s, "__dict__") == 0) {
1880 if (!may_add_dict || add_dict) {
1881 PyErr_SetString(PyExc_TypeError,
1882 "__dict__ slot disallowed: "
1883 "we already got one");
1884 goto bad_slots;
1885 }
1886 add_dict++;
1887 }
1888 if (strcmp(s, "__weakref__") == 0) {
1889 if (!may_add_weak || add_weak) {
1890 PyErr_SetString(PyExc_TypeError,
1891 "__weakref__ slot disallowed: "
1892 "either we already got one, "
1893 "or __itemsize__ != 0");
1894 goto bad_slots;
1895 }
1896 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001897 }
1898 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001899
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00001900 /* Copy slots into a list, mangle names and sort them.
1901 Sorted names are needed for __class__ assignment.
1902 Convert them back to tuple at the end.
1903 */
1904 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001905 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001906 goto bad_slots;
1907 for (i = j = 0; i < nslots; i++) {
1908 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001909 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001910 s = PyString_AS_STRING(tmp);
1911 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1912 (add_weak && strcmp(s, "__weakref__") == 0))
1913 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914 tmp =_Py_Mangle(name, tmp);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00001915 if (!tmp)
1916 goto bad_slots;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00001917 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00001918 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001919 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001920 assert(j == nslots - add_dict - add_weak);
1921 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001922 Py_DECREF(slots);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00001923 if (PyList_Sort(newslots) == -1) {
1924 Py_DECREF(bases);
1925 Py_DECREF(newslots);
1926 return NULL;
1927 }
1928 slots = PyList_AsTuple(newslots);
1929 Py_DECREF(newslots);
1930 if (slots == NULL) {
1931 Py_DECREF(bases);
1932 return NULL;
1933 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001934
Guido van Rossumad47da02002-08-12 19:05:44 +00001935 /* Secondary bases may provide weakrefs or dict */
1936 if (nbases > 1 &&
1937 ((may_add_dict && !add_dict) ||
1938 (may_add_weak && !add_weak))) {
1939 for (i = 0; i < nbases; i++) {
1940 tmp = PyTuple_GET_ITEM(bases, i);
1941 if (tmp == (PyObject *)base)
1942 continue; /* Skip primary base */
1943 if (PyClass_Check(tmp)) {
1944 /* Classic base class provides both */
1945 if (may_add_dict && !add_dict)
1946 add_dict++;
1947 if (may_add_weak && !add_weak)
1948 add_weak++;
1949 break;
1950 }
1951 assert(PyType_Check(tmp));
1952 tmptype = (PyTypeObject *)tmp;
1953 if (may_add_dict && !add_dict &&
1954 tmptype->tp_dictoffset != 0)
1955 add_dict++;
1956 if (may_add_weak && !add_weak &&
1957 tmptype->tp_weaklistoffset != 0)
1958 add_weak++;
1959 if (may_add_dict && !add_dict)
1960 continue;
1961 if (may_add_weak && !add_weak)
1962 continue;
1963 /* Nothing more to check */
1964 break;
1965 }
1966 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001967 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001968
1969 /* XXX From here until type is safely allocated,
1970 "return NULL" may leak slots! */
1971
1972 /* Allocate the type object */
1973 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001974 if (type == NULL) {
1975 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001976 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001977 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001978 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001979
1980 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001981 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001982 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001983 et->ht_name = name;
1984 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001985
Guido van Rossumdc91b992001-08-08 22:26:22 +00001986 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1988 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001989 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1990 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001991
1992 /* It's a new-style number unless it specifically inherits any
1993 old-style numeric behavior */
1994 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1995 (base->tp_as_number == NULL))
1996 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1997
1998 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001999 type->tp_as_number = &et->as_number;
2000 type->tp_as_sequence = &et->as_sequence;
2001 type->tp_as_mapping = &et->as_mapping;
2002 type->tp_as_buffer = &et->as_buffer;
2003 type->tp_name = PyString_AS_STRING(name);
2004
2005 /* Set tp_base and tp_bases */
2006 type->tp_bases = bases;
2007 Py_INCREF(base);
2008 type->tp_base = base;
2009
Guido van Rossum687ae002001-10-15 22:03:32 +00002010 /* Initialize tp_dict from passed-in dict */
2011 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012 if (dict == NULL) {
2013 Py_DECREF(type);
2014 return NULL;
2015 }
2016
Guido van Rossumc3542212001-08-16 09:18:56 +00002017 /* Set __module__ in the dict */
2018 if (PyDict_GetItemString(dict, "__module__") == NULL) {
2019 tmp = PyEval_GetGlobals();
2020 if (tmp != NULL) {
2021 tmp = PyDict_GetItemString(tmp, "__name__");
2022 if (tmp != NULL) {
2023 if (PyDict_SetItemString(dict, "__module__",
2024 tmp) < 0)
2025 return NULL;
2026 }
2027 }
2028 }
2029
Tim Peters2f93e282001-10-04 05:27:00 +00002030 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00002031 and is a string. The __doc__ accessor will first look for tp_doc;
2032 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00002033 */
2034 {
2035 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
2036 if (doc != NULL && PyString_Check(doc)) {
2037 const size_t n = (size_t)PyString_GET_SIZE(doc);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002038 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002039 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00002040 Py_DECREF(type);
2041 return NULL;
2042 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002043 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002044 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00002045 }
2046 }
2047
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048 /* Special-case __new__: if it's a plain function,
2049 make it a static function */
2050 tmp = PyDict_GetItemString(dict, "__new__");
2051 if (tmp != NULL && PyFunction_Check(tmp)) {
2052 tmp = PyStaticMethod_New(tmp);
2053 if (tmp == NULL) {
2054 Py_DECREF(type);
2055 return NULL;
2056 }
2057 PyDict_SetItemString(dict, "__new__", tmp);
2058 Py_DECREF(tmp);
2059 }
2060
2061 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002062 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00002063 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002064 if (slots != NULL) {
2065 for (i = 0; i < nslots; i++, mp++) {
2066 mp->name = PyString_AS_STRING(
2067 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00002068 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002069 mp->offset = slotoffset;
Žiga Seilnacht89032082007-03-11 15:54:54 +00002070
2071 /* __dict__ and __weakref__ are already filtered out */
2072 assert(strcmp(mp->name, "__dict__") != 0);
2073 assert(strcmp(mp->name, "__weakref__") != 0);
2074
Tim Peters6d6c1a32001-08-02 04:15:00 +00002075 slotoffset += sizeof(PyObject *);
2076 }
2077 }
Guido van Rossumad47da02002-08-12 19:05:44 +00002078 if (add_dict) {
2079 if (base->tp_itemsize)
2080 type->tp_dictoffset = -(long)sizeof(PyObject *);
2081 else
2082 type->tp_dictoffset = slotoffset;
2083 slotoffset += sizeof(PyObject *);
2084 }
2085 if (add_weak) {
2086 assert(!base->tp_itemsize);
2087 type->tp_weaklistoffset = slotoffset;
2088 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089 }
2090 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00002091 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00002092 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00002093
2094 if (type->tp_weaklistoffset && type->tp_dictoffset)
2095 type->tp_getset = subtype_getsets_full;
2096 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
2097 type->tp_getset = subtype_getsets_weakref_only;
2098 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
2099 type->tp_getset = subtype_getsets_dict_only;
2100 else
2101 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102
2103 /* Special case some slots */
2104 if (type->tp_dictoffset != 0 || nslots > 0) {
2105 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
2106 type->tp_getattro = PyObject_GenericGetAttr;
2107 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
2108 type->tp_setattro = PyObject_GenericSetAttr;
2109 }
2110 type->tp_dealloc = subtype_dealloc;
2111
Guido van Rossum9475a232001-10-05 20:51:39 +00002112 /* Enable GC unless there are really no instance variables possible */
2113 if (!(type->tp_basicsize == sizeof(PyObject) &&
2114 type->tp_itemsize == 0))
2115 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2116
Tim Peters6d6c1a32001-08-02 04:15:00 +00002117 /* Always override allocation strategy to use regular heap */
2118 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002119 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002120 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002121 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002122 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002123 }
2124 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002125 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126
2127 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002128 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002129 Py_DECREF(type);
2130 return NULL;
2131 }
2132
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002133 /* Put the proper slots in place */
2134 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002135
Tim Peters6d6c1a32001-08-02 04:15:00 +00002136 return (PyObject *)type;
2137}
2138
2139/* Internal API to look for a name through the MRO.
2140 This returns a borrowed reference, and doesn't set an exception! */
2141PyObject *
2142_PyType_Lookup(PyTypeObject *type, PyObject *name)
2143{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002144 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002145 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002146
Guido van Rossum687ae002001-10-15 22:03:32 +00002147 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002148 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002149
2150 /* If mro is NULL, the type is either not yet initialized
2151 by PyType_Ready(), or already cleared by type_clear().
2152 Either way the safest thing to do is to return NULL. */
2153 if (mro == NULL)
2154 return NULL;
2155
Tim Peters6d6c1a32001-08-02 04:15:00 +00002156 assert(PyTuple_Check(mro));
2157 n = PyTuple_GET_SIZE(mro);
2158 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002159 base = PyTuple_GET_ITEM(mro, i);
2160 if (PyClass_Check(base))
2161 dict = ((PyClassObject *)base)->cl_dict;
2162 else {
2163 assert(PyType_Check(base));
2164 dict = ((PyTypeObject *)base)->tp_dict;
2165 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166 assert(dict && PyDict_Check(dict));
2167 res = PyDict_GetItem(dict, name);
2168 if (res != NULL)
2169 return res;
2170 }
2171 return NULL;
2172}
2173
2174/* This is similar to PyObject_GenericGetAttr(),
2175 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2176static PyObject *
2177type_getattro(PyTypeObject *type, PyObject *name)
2178{
Martin v. Löwis68192102007-07-21 06:55:02 +00002179 PyTypeObject *metatype = Py_Type(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002180 PyObject *meta_attribute, *attribute;
2181 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002182
2183 /* Initialize this type (we'll assume the metatype is initialized) */
2184 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002185 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002186 return NULL;
2187 }
2188
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002189 /* No readable descriptor found yet */
2190 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002191
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002192 /* Look for the attribute in the metatype */
2193 meta_attribute = _PyType_Lookup(metatype, name);
2194
2195 if (meta_attribute != NULL) {
Martin v. Löwis68192102007-07-21 06:55:02 +00002196 meta_get = Py_Type(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002197
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002198 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2199 /* Data descriptors implement tp_descr_set to intercept
2200 * writes. Assume the attribute is not overridden in
2201 * type's tp_dict (and bases): call the descriptor now.
2202 */
2203 return meta_get(meta_attribute, (PyObject *)type,
2204 (PyObject *)metatype);
2205 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002206 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002207 }
2208
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002209 /* No data descriptor found on metatype. Look in tp_dict of this
2210 * type and its bases */
2211 attribute = _PyType_Lookup(type, name);
2212 if (attribute != NULL) {
2213 /* Implement descriptor functionality, if any */
Martin v. Löwis68192102007-07-21 06:55:02 +00002214 descrgetfunc local_get = Py_Type(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002215
2216 Py_XDECREF(meta_attribute);
2217
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002218 if (local_get != NULL) {
2219 /* NULL 2nd argument indicates the descriptor was
2220 * found on the target object itself (or a base) */
2221 return local_get(attribute, (PyObject *)NULL,
2222 (PyObject *)type);
2223 }
Tim Peters34592512002-07-11 06:23:50 +00002224
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002225 Py_INCREF(attribute);
2226 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227 }
2228
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002229 /* No attribute found in local __dict__ (or bases): use the
2230 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002231 if (meta_get != NULL) {
2232 PyObject *res;
2233 res = meta_get(meta_attribute, (PyObject *)type,
2234 (PyObject *)metatype);
2235 Py_DECREF(meta_attribute);
2236 return res;
2237 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002238
2239 /* If an ordinary attribute was found on the metatype, return it now */
2240 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002241 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002242 }
2243
2244 /* Give up */
2245 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002246 "type object '%.50s' has no attribute '%.400s'",
2247 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002248 return NULL;
2249}
2250
2251static int
2252type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2253{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002254 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2255 PyErr_Format(
2256 PyExc_TypeError,
2257 "can't set attributes of built-in/extension type '%s'",
2258 type->tp_name);
2259 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002260 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002261 /* XXX Example of how I expect this to be used...
2262 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2263 return -1;
2264 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002265 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2266 return -1;
2267 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002268}
2269
2270static void
2271type_dealloc(PyTypeObject *type)
2272{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002273 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002274
2275 /* Assert this is a heap-allocated type object */
2276 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002277 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002278 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002279 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002280 Py_XDECREF(type->tp_base);
2281 Py_XDECREF(type->tp_dict);
2282 Py_XDECREF(type->tp_bases);
2283 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002284 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002285 Py_XDECREF(type->tp_subclasses);
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002286 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2287 * of most other objects. It's okay to cast it to char *.
2288 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002289 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002290 Py_XDECREF(et->ht_name);
2291 Py_XDECREF(et->ht_slots);
Martin v. Löwis68192102007-07-21 06:55:02 +00002292 Py_Type(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002293}
2294
Guido van Rossum1c450732001-10-08 15:18:27 +00002295static PyObject *
2296type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2297{
2298 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002299 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002300
2301 list = PyList_New(0);
2302 if (list == NULL)
2303 return NULL;
2304 raw = type->tp_subclasses;
2305 if (raw == NULL)
2306 return list;
2307 assert(PyList_Check(raw));
2308 n = PyList_GET_SIZE(raw);
2309 for (i = 0; i < n; i++) {
2310 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002311 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002312 ref = PyWeakref_GET_OBJECT(ref);
2313 if (ref != Py_None) {
2314 if (PyList_Append(list, ref) < 0) {
2315 Py_DECREF(list);
2316 return NULL;
2317 }
2318 }
2319 }
2320 return list;
2321}
2322
Tim Peters6d6c1a32001-08-02 04:15:00 +00002323static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002324 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002325 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002326 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002327 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002328 {0}
2329};
2330
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002331PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002332"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002333"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002334
Guido van Rossum048eb752001-10-02 21:24:57 +00002335static int
2336type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2337{
Guido van Rossuma3862092002-06-10 15:24:42 +00002338 /* Because of type_is_gc(), the collector only calls this
2339 for heaptypes. */
2340 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002341
Thomas Woutersc6e55062006-04-15 21:47:09 +00002342 Py_VISIT(type->tp_dict);
2343 Py_VISIT(type->tp_cache);
2344 Py_VISIT(type->tp_mro);
2345 Py_VISIT(type->tp_bases);
2346 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002347
2348 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002349 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002350 in cycles; tp_subclasses is a list of weak references,
2351 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002352
Guido van Rossum048eb752001-10-02 21:24:57 +00002353 return 0;
2354}
2355
2356static int
2357type_clear(PyTypeObject *type)
2358{
Guido van Rossuma3862092002-06-10 15:24:42 +00002359 /* Because of type_is_gc(), the collector only calls this
2360 for heaptypes. */
2361 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002362
Guido van Rossuma3862092002-06-10 15:24:42 +00002363 /* The only field we need to clear is tp_mro, which is part of a
2364 hard cycle (its first element is the class itself) that won't
2365 be broken otherwise (it's a tuple and tuples don't have a
2366 tp_clear handler). None of the other fields need to be
2367 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002368
Guido van Rossuma3862092002-06-10 15:24:42 +00002369 tp_dict:
2370 It is a dict, so the collector will call its tp_clear.
2371
2372 tp_cache:
2373 Not used; if it were, it would be a dict.
2374
2375 tp_bases, tp_base:
2376 If these are involved in a cycle, there must be at least
2377 one other, mutable object in the cycle, e.g. a base
2378 class's dict; the cycle will be broken that way.
2379
2380 tp_subclasses:
2381 A list of weak references can't be part of a cycle; and
2382 lists have their own tp_clear.
2383
Guido van Rossume5c691a2003-03-07 15:13:17 +00002384 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002385 A tuple of strings can't be part of a cycle.
2386 */
2387
Thomas Woutersedf17d82006-04-15 17:28:34 +00002388 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002389
2390 return 0;
2391}
2392
2393static int
2394type_is_gc(PyTypeObject *type)
2395{
2396 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2397}
2398
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002399PyTypeObject PyType_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002400 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002401 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002402 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002403 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002404 (destructor)type_dealloc, /* tp_dealloc */
2405 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002406 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002407 0, /* tp_setattr */
2408 type_compare, /* tp_compare */
2409 (reprfunc)type_repr, /* tp_repr */
2410 0, /* tp_as_number */
2411 0, /* tp_as_sequence */
2412 0, /* tp_as_mapping */
2413 (hashfunc)_Py_HashPointer, /* tp_hash */
2414 (ternaryfunc)type_call, /* tp_call */
2415 0, /* tp_str */
2416 (getattrofunc)type_getattro, /* tp_getattro */
2417 (setattrofunc)type_setattro, /* tp_setattro */
2418 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002419 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002420 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002421 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002422 (traverseproc)type_traverse, /* tp_traverse */
2423 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002424 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002425 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002426 0, /* tp_iter */
2427 0, /* tp_iternext */
2428 type_methods, /* tp_methods */
2429 type_members, /* tp_members */
2430 type_getsets, /* tp_getset */
2431 0, /* tp_base */
2432 0, /* tp_dict */
2433 0, /* tp_descr_get */
2434 0, /* tp_descr_set */
2435 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumf102e242007-03-23 18:53:03 +00002436 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002437 0, /* tp_alloc */
2438 type_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00002439 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002440 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002441};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002442
2443
2444/* The base type of all types (eventually)... except itself. */
2445
Guido van Rossum143b5642007-03-23 04:58:42 +00002446/* You may wonder why object.__new__() only complains about arguments
2447 when object.__init__() is not overridden, and vice versa.
2448
2449 Consider the use cases:
2450
2451 1. When neither is overridden, we want to hear complaints about
2452 excess (i.e., any) arguments, since their presence could
2453 indicate there's a bug.
2454
2455 2. When defining an Immutable type, we are likely to override only
2456 __new__(), since __init__() is called too late to initialize an
2457 Immutable object. Since __new__() defines the signature for the
2458 type, it would be a pain to have to override __init__() just to
2459 stop it from complaining about excess arguments.
2460
2461 3. When defining a Mutable type, we are likely to override only
2462 __init__(). So here the converse reasoning applies: we don't
2463 want to have to override __new__() just to stop it from
2464 complaining.
2465
2466 4. When __init__() is overridden, and the subclass __init__() calls
2467 object.__init__(), the latter should complain about excess
2468 arguments; ditto for __new__().
2469
2470 Use cases 2 and 3 make it unattractive to unconditionally check for
2471 excess arguments. The best solution that addresses all four use
2472 cases is as follows: __init__() complains about excess arguments
2473 unless __new__() is overridden and __init__() is not overridden
2474 (IOW, if __init__() is overridden or __new__() is not overridden);
2475 symmetrically, __new__() complains about excess arguments unless
2476 __init__() is overridden and __new__() is not overridden
2477 (IOW, if __new__() is overridden or __init__() is not overridden).
2478
2479 However, for backwards compatibility, this breaks too much code.
2480 Therefore, in 2.6, we'll *warn* about excess arguments when both
2481 methods are overridden; for all other cases we'll use the above
2482 rules.
2483
2484*/
2485
2486/* Forward */
2487static PyObject *
2488object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2489
2490static int
2491excess_args(PyObject *args, PyObject *kwds)
2492{
2493 return PyTuple_GET_SIZE(args) ||
2494 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2495}
2496
Tim Peters6d6c1a32001-08-02 04:15:00 +00002497static int
2498object_init(PyObject *self, PyObject *args, PyObject *kwds)
2499{
Guido van Rossum143b5642007-03-23 04:58:42 +00002500 int err = 0;
2501 if (excess_args(args, kwds)) {
Martin v. Löwis68192102007-07-21 06:55:02 +00002502 PyTypeObject *type = Py_Type(self);
Guido van Rossum143b5642007-03-23 04:58:42 +00002503 if (type->tp_init != object_init &&
2504 type->tp_new != object_new)
2505 {
2506 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2507 "object.__init__() takes no parameters",
2508 1);
2509 }
2510 else if (type->tp_init != object_init ||
2511 type->tp_new == object_new)
2512 {
2513 PyErr_SetString(PyExc_TypeError,
2514 "object.__init__() takes no parameters");
2515 err = -1;
2516 }
2517 }
2518 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002519}
2520
Guido van Rossum298e4212003-02-13 16:30:16 +00002521static PyObject *
2522object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2523{
Guido van Rossum143b5642007-03-23 04:58:42 +00002524 int err = 0;
2525 if (excess_args(args, kwds)) {
2526 if (type->tp_new != object_new &&
2527 type->tp_init != object_init)
2528 {
2529 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2530 "object.__new__() takes no parameters",
2531 1);
2532 }
2533 else if (type->tp_new != object_new ||
2534 type->tp_init == object_init)
2535 {
2536 PyErr_SetString(PyExc_TypeError,
2537 "object.__new__() takes no parameters");
2538 err = -1;
2539 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002540 }
Guido van Rossum143b5642007-03-23 04:58:42 +00002541 if (err < 0)
2542 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002543 return type->tp_alloc(type, 0);
2544}
2545
Tim Peters6d6c1a32001-08-02 04:15:00 +00002546static void
2547object_dealloc(PyObject *self)
2548{
Martin v. Löwis68192102007-07-21 06:55:02 +00002549 Py_Type(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002550}
2551
Guido van Rossum8e248182001-08-12 05:17:56 +00002552static PyObject *
2553object_repr(PyObject *self)
2554{
Guido van Rossum76e69632001-08-16 18:52:43 +00002555 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002556 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002557
Martin v. Löwis68192102007-07-21 06:55:02 +00002558 type = Py_Type(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002559 mod = type_module(type, NULL);
2560 if (mod == NULL)
2561 PyErr_Clear();
2562 else if (!PyString_Check(mod)) {
2563 Py_DECREF(mod);
2564 mod = NULL;
2565 }
2566 name = type_name(type, NULL);
2567 if (name == NULL)
2568 return NULL;
2569 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002570 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002571 PyString_AS_STRING(mod),
2572 PyString_AS_STRING(name),
2573 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002574 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002575 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002576 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002577 Py_XDECREF(mod);
2578 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002579 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002580}
2581
Guido van Rossumb8f63662001-08-15 23:57:02 +00002582static PyObject *
2583object_str(PyObject *self)
2584{
2585 unaryfunc f;
2586
Martin v. Löwis68192102007-07-21 06:55:02 +00002587 f = Py_Type(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002588 if (f == NULL)
2589 f = object_repr;
2590 return f(self);
2591}
2592
Guido van Rossum8e248182001-08-12 05:17:56 +00002593static long
2594object_hash(PyObject *self)
2595{
2596 return _Py_HashPointer(self);
2597}
Guido van Rossum8e248182001-08-12 05:17:56 +00002598
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002599static PyObject *
2600object_get_class(PyObject *self, void *closure)
2601{
Martin v. Löwis68192102007-07-21 06:55:02 +00002602 Py_INCREF(Py_Type(self));
2603 return (PyObject *)(Py_Type(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002604}
2605
2606static int
2607equiv_structs(PyTypeObject *a, PyTypeObject *b)
2608{
2609 return a == b ||
2610 (a != NULL &&
2611 b != NULL &&
2612 a->tp_basicsize == b->tp_basicsize &&
2613 a->tp_itemsize == b->tp_itemsize &&
2614 a->tp_dictoffset == b->tp_dictoffset &&
2615 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2616 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2617 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2618}
2619
2620static int
2621same_slots_added(PyTypeObject *a, PyTypeObject *b)
2622{
2623 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002624 Py_ssize_t size;
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002625 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002626
2627 if (base != b->tp_base)
2628 return 0;
2629 if (equiv_structs(a, base) && equiv_structs(b, base))
2630 return 1;
2631 size = base->tp_basicsize;
2632 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2633 size += sizeof(PyObject *);
2634 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2635 size += sizeof(PyObject *);
Žiga Seilnacht6f2d09c2007-03-16 11:59:38 +00002636
2637 /* Check slots compliance */
2638 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2639 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2640 if (slots_a && slots_b) {
2641 if (PyObject_Compare(slots_a, slots_b) != 0)
2642 return 0;
2643 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2644 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002645 return size == a->tp_basicsize && size == b->tp_basicsize;
2646}
2647
2648static int
Anthony Baxtera6286212006-04-11 07:42:36 +00002649compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002650{
2651 PyTypeObject *newbase, *oldbase;
2652
Anthony Baxtera6286212006-04-11 07:42:36 +00002653 if (newto->tp_dealloc != oldto->tp_dealloc ||
2654 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002655 {
2656 PyErr_Format(PyExc_TypeError,
2657 "%s assignment: "
2658 "'%s' deallocator differs from '%s'",
2659 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002660 newto->tp_name,
2661 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002662 return 0;
2663 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002664 newbase = newto;
2665 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002666 while (equiv_structs(newbase, newbase->tp_base))
2667 newbase = newbase->tp_base;
2668 while (equiv_structs(oldbase, oldbase->tp_base))
2669 oldbase = oldbase->tp_base;
2670 if (newbase != oldbase &&
2671 (newbase->tp_base != oldbase->tp_base ||
2672 !same_slots_added(newbase, oldbase))) {
2673 PyErr_Format(PyExc_TypeError,
2674 "%s assignment: "
2675 "'%s' object layout differs from '%s'",
2676 attr,
Anthony Baxtera6286212006-04-11 07:42:36 +00002677 newto->tp_name,
2678 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002679 return 0;
2680 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002681
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002682 return 1;
2683}
2684
2685static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002686object_set_class(PyObject *self, PyObject *value, void *closure)
2687{
Martin v. Löwis68192102007-07-21 06:55:02 +00002688 PyTypeObject *oldto = Py_Type(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002689 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002690
Guido van Rossumb6b89422002-04-15 01:03:30 +00002691 if (value == NULL) {
2692 PyErr_SetString(PyExc_TypeError,
2693 "can't delete __class__ attribute");
2694 return -1;
2695 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002696 if (!PyType_Check(value)) {
2697 PyErr_Format(PyExc_TypeError,
2698 "__class__ must be set to new-style class, not '%s' object",
Martin v. Löwis68192102007-07-21 06:55:02 +00002699 Py_Type(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002700 return -1;
2701 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002702 newto = (PyTypeObject *)value;
2703 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2704 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002705 {
2706 PyErr_Format(PyExc_TypeError,
2707 "__class__ assignment: only for heap types");
2708 return -1;
2709 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002710 if (compatible_for_assignment(newto, oldto, "__class__")) {
2711 Py_INCREF(newto);
Martin v. Löwis68192102007-07-21 06:55:02 +00002712 Py_Type(self) = newto;
Anthony Baxtera6286212006-04-11 07:42:36 +00002713 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002714 return 0;
2715 }
2716 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002717 return -1;
2718 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002719}
2720
2721static PyGetSetDef object_getsets[] = {
2722 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002723 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002724 {0}
2725};
2726
Guido van Rossumc53f0092003-02-18 22:05:12 +00002727
Guido van Rossum036f9992003-02-21 22:02:54 +00002728/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2729 We fall back to helpers in copy_reg for:
2730 - pickle protocols < 2
2731 - calculating the list of slot names (done only once per class)
2732 - the __newobj__ function (which is used as a token but never called)
2733*/
2734
2735static PyObject *
2736import_copy_reg(void)
2737{
2738 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002739
2740 if (!copy_reg_str) {
2741 copy_reg_str = PyString_InternFromString("copy_reg");
2742 if (copy_reg_str == NULL)
2743 return NULL;
2744 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002745
2746 return PyImport_Import(copy_reg_str);
2747}
2748
2749static PyObject *
2750slotnames(PyObject *cls)
2751{
2752 PyObject *clsdict;
2753 PyObject *copy_reg;
2754 PyObject *slotnames;
2755
2756 if (!PyType_Check(cls)) {
2757 Py_INCREF(Py_None);
2758 return Py_None;
2759 }
2760
2761 clsdict = ((PyTypeObject *)cls)->tp_dict;
2762 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002763 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002764 Py_INCREF(slotnames);
2765 return slotnames;
2766 }
2767
2768 copy_reg = import_copy_reg();
2769 if (copy_reg == NULL)
2770 return NULL;
2771
2772 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2773 Py_DECREF(copy_reg);
2774 if (slotnames != NULL &&
2775 slotnames != Py_None &&
2776 !PyList_Check(slotnames))
2777 {
2778 PyErr_SetString(PyExc_TypeError,
2779 "copy_reg._slotnames didn't return a list or None");
2780 Py_DECREF(slotnames);
2781 slotnames = NULL;
2782 }
2783
2784 return slotnames;
2785}
2786
2787static PyObject *
2788reduce_2(PyObject *obj)
2789{
2790 PyObject *cls, *getnewargs;
2791 PyObject *args = NULL, *args2 = NULL;
2792 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2793 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2794 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002795 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002796
2797 cls = PyObject_GetAttrString(obj, "__class__");
2798 if (cls == NULL)
2799 return NULL;
2800
2801 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2802 if (getnewargs != NULL) {
2803 args = PyObject_CallObject(getnewargs, NULL);
2804 Py_DECREF(getnewargs);
2805 if (args != NULL && !PyTuple_Check(args)) {
Georg Brandlccff7852006-06-18 22:17:29 +00002806 PyErr_Format(PyExc_TypeError,
2807 "__getnewargs__ should return a tuple, "
Martin v. Löwis68192102007-07-21 06:55:02 +00002808 "not '%.200s'", Py_Type(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002809 goto end;
2810 }
2811 }
2812 else {
2813 PyErr_Clear();
2814 args = PyTuple_New(0);
2815 }
2816 if (args == NULL)
2817 goto end;
2818
2819 getstate = PyObject_GetAttrString(obj, "__getstate__");
2820 if (getstate != NULL) {
2821 state = PyObject_CallObject(getstate, NULL);
2822 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002823 if (state == NULL)
2824 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002825 }
2826 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002827 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002828 state = PyObject_GetAttrString(obj, "__dict__");
2829 if (state == NULL) {
2830 PyErr_Clear();
2831 state = Py_None;
2832 Py_INCREF(state);
2833 }
2834 names = slotnames(cls);
2835 if (names == NULL)
2836 goto end;
2837 if (names != Py_None) {
2838 assert(PyList_Check(names));
2839 slots = PyDict_New();
2840 if (slots == NULL)
2841 goto end;
2842 n = 0;
2843 /* Can't pre-compute the list size; the list
2844 is stored on the class so accessible to other
2845 threads, which may be run by DECREF */
2846 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2847 PyObject *name, *value;
2848 name = PyList_GET_ITEM(names, i);
2849 value = PyObject_GetAttr(obj, name);
2850 if (value == NULL)
2851 PyErr_Clear();
2852 else {
2853 int err = PyDict_SetItem(slots, name,
2854 value);
2855 Py_DECREF(value);
2856 if (err)
2857 goto end;
2858 n++;
2859 }
2860 }
2861 if (n) {
2862 state = Py_BuildValue("(NO)", state, slots);
2863 if (state == NULL)
2864 goto end;
2865 }
2866 }
2867 }
2868
2869 if (!PyList_Check(obj)) {
2870 listitems = Py_None;
2871 Py_INCREF(listitems);
2872 }
2873 else {
2874 listitems = PyObject_GetIter(obj);
2875 if (listitems == NULL)
2876 goto end;
2877 }
2878
2879 if (!PyDict_Check(obj)) {
2880 dictitems = Py_None;
2881 Py_INCREF(dictitems);
2882 }
2883 else {
2884 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2885 if (dictitems == NULL)
2886 goto end;
2887 }
2888
2889 copy_reg = import_copy_reg();
2890 if (copy_reg == NULL)
2891 goto end;
2892 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2893 if (newobj == NULL)
2894 goto end;
2895
2896 n = PyTuple_GET_SIZE(args);
2897 args2 = PyTuple_New(n+1);
2898 if (args2 == NULL)
2899 goto end;
2900 PyTuple_SET_ITEM(args2, 0, cls);
2901 cls = NULL;
2902 for (i = 0; i < n; i++) {
2903 PyObject *v = PyTuple_GET_ITEM(args, i);
2904 Py_INCREF(v);
2905 PyTuple_SET_ITEM(args2, i+1, v);
2906 }
2907
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002908 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002909
2910 end:
2911 Py_XDECREF(cls);
2912 Py_XDECREF(args);
2913 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002914 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002915 Py_XDECREF(state);
2916 Py_XDECREF(names);
2917 Py_XDECREF(listitems);
2918 Py_XDECREF(dictitems);
2919 Py_XDECREF(copy_reg);
2920 Py_XDECREF(newobj);
2921 return res;
2922}
2923
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002924/*
2925 * There were two problems when object.__reduce__ and object.__reduce_ex__
2926 * were implemented in the same function:
2927 * - trying to pickle an object with a custom __reduce__ method that
2928 * fell back to object.__reduce__ in certain circumstances led to
2929 * infinite recursion at Python level and eventual RuntimeError.
2930 * - Pickling objects that lied about their type by overwriting the
2931 * __class__ descriptor could lead to infinite recursion at C level
2932 * and eventual segfault.
2933 *
2934 * Because of backwards compatibility, the two methods still have to
2935 * behave in the same way, even if this is not required by the pickle
2936 * protocol. This common functionality was moved to the _common_reduce
2937 * function.
2938 */
2939static PyObject *
2940_common_reduce(PyObject *self, int proto)
2941{
2942 PyObject *copy_reg, *res;
2943
2944 if (proto >= 2)
2945 return reduce_2(self);
2946
2947 copy_reg = import_copy_reg();
2948 if (!copy_reg)
2949 return NULL;
2950
2951 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2952 Py_DECREF(copy_reg);
2953
2954 return res;
2955}
2956
2957static PyObject *
2958object_reduce(PyObject *self, PyObject *args)
2959{
2960 int proto = 0;
2961
2962 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
2963 return NULL;
2964
2965 return _common_reduce(self, proto);
2966}
2967
Guido van Rossum036f9992003-02-21 22:02:54 +00002968static PyObject *
2969object_reduce_ex(PyObject *self, PyObject *args)
2970{
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00002971 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00002972 int proto = 0;
2973
2974 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2975 return NULL;
2976
2977 reduce = PyObject_GetAttrString(self, "__reduce__");
2978 if (reduce == NULL)
2979 PyErr_Clear();
2980 else {
2981 PyObject *cls, *clsreduce, *objreduce;
2982 int override;
2983 cls = PyObject_GetAttrString(self, "__class__");
2984 if (cls == NULL) {
2985 Py_DECREF(reduce);
2986 return NULL;
2987 }
2988 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2989 Py_DECREF(cls);
2990 if (clsreduce == NULL) {
2991 Py_DECREF(reduce);
2992 return NULL;
2993 }
2994 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2995 "__reduce__");
2996 override = (clsreduce != objreduce);
2997 Py_DECREF(clsreduce);
2998 if (override) {
2999 res = PyObject_CallObject(reduce, NULL);
3000 Py_DECREF(reduce);
3001 return res;
3002 }
3003 else
3004 Py_DECREF(reduce);
3005 }
3006
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003007 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00003008}
3009
3010static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00003011 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
3012 PyDoc_STR("helper for pickle")},
Žiga Seilnacht20f43d32007-03-15 11:44:55 +00003013 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003014 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00003015 {0}
3016};
3017
Guido van Rossum036f9992003-02-21 22:02:54 +00003018
Tim Peters6d6c1a32001-08-02 04:15:00 +00003019PyTypeObject PyBaseObject_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003020 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003021 "object", /* tp_name */
3022 sizeof(PyObject), /* tp_basicsize */
3023 0, /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003024 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003025 0, /* tp_print */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003026 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003027 0, /* tp_setattr */
3028 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003029 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030 0, /* tp_as_number */
3031 0, /* tp_as_sequence */
3032 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003033 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003034 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003035 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003036 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003037 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003038 0, /* tp_as_buffer */
3039 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003040 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003041 0, /* tp_traverse */
3042 0, /* tp_clear */
3043 0, /* tp_richcompare */
3044 0, /* tp_weaklistoffset */
3045 0, /* tp_iter */
3046 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003047 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003048 0, /* tp_members */
3049 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003050 0, /* tp_base */
3051 0, /* tp_dict */
3052 0, /* tp_descr_get */
3053 0, /* tp_descr_set */
3054 0, /* tp_dictoffset */
3055 object_init, /* tp_init */
3056 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003057 object_new, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003058 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003059};
3060
3061
3062/* Initialize the __dict__ in a type object */
3063
3064static int
3065add_methods(PyTypeObject *type, PyMethodDef *meth)
3066{
Guido van Rossum687ae002001-10-15 22:03:32 +00003067 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003068
3069 for (; meth->ml_name != NULL; meth++) {
3070 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003071 if (PyDict_GetItemString(dict, meth->ml_name) &&
3072 !(meth->ml_flags & METH_COEXIST))
3073 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003074 if (meth->ml_flags & METH_CLASS) {
3075 if (meth->ml_flags & METH_STATIC) {
3076 PyErr_SetString(PyExc_ValueError,
3077 "method cannot be both class and static");
3078 return -1;
3079 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003080 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003081 }
3082 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003083 PyObject *cfunc = PyCFunction_New(meth, NULL);
3084 if (cfunc == NULL)
3085 return -1;
3086 descr = PyStaticMethod_New(cfunc);
3087 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003088 }
3089 else {
3090 descr = PyDescr_NewMethod(type, meth);
3091 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003092 if (descr == NULL)
3093 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003094 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003095 return -1;
3096 Py_DECREF(descr);
3097 }
3098 return 0;
3099}
3100
3101static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003102add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103{
Guido van Rossum687ae002001-10-15 22:03:32 +00003104 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105
3106 for (; memb->name != NULL; memb++) {
3107 PyObject *descr;
3108 if (PyDict_GetItemString(dict, memb->name))
3109 continue;
3110 descr = PyDescr_NewMember(type, memb);
3111 if (descr == NULL)
3112 return -1;
3113 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3114 return -1;
3115 Py_DECREF(descr);
3116 }
3117 return 0;
3118}
3119
3120static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003121add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003122{
Guido van Rossum687ae002001-10-15 22:03:32 +00003123 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003124
3125 for (; gsp->name != NULL; gsp++) {
3126 PyObject *descr;
3127 if (PyDict_GetItemString(dict, gsp->name))
3128 continue;
3129 descr = PyDescr_NewGetSet(type, gsp);
3130
3131 if (descr == NULL)
3132 return -1;
3133 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3134 return -1;
3135 Py_DECREF(descr);
3136 }
3137 return 0;
3138}
3139
Guido van Rossum13d52f02001-08-10 21:24:08 +00003140static void
3141inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003142{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003143 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003144
Guido van Rossum13d52f02001-08-10 21:24:08 +00003145 /* Special flag magic */
3146 if (!type->tp_as_buffer && base->tp_as_buffer) {
3147 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
3148 type->tp_flags |=
3149 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
3150 }
3151 if (!type->tp_as_sequence && base->tp_as_sequence) {
3152 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
3153 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
3154 }
3155 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
3156 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
3157 if ((!type->tp_as_number && base->tp_as_number) ||
3158 (!type->tp_as_sequence && base->tp_as_sequence)) {
3159 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
3160 if (!type->tp_as_number && !type->tp_as_sequence) {
3161 type->tp_flags |= base->tp_flags &
3162 Py_TPFLAGS_HAVE_INPLACEOPS;
3163 }
3164 }
3165 /* Wow */
3166 }
3167 if (!type->tp_as_number && base->tp_as_number) {
3168 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
3169 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
3170 }
3171
3172 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003173 oldsize = base->tp_basicsize;
3174 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3175 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3176 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003177 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
3178 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003179 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003180 if (type->tp_traverse == NULL)
3181 type->tp_traverse = base->tp_traverse;
3182 if (type->tp_clear == NULL)
3183 type->tp_clear = base->tp_clear;
3184 }
3185 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00003186 /* The condition below could use some explanation.
3187 It appears that tp_new is not inherited for static types
3188 whose base class is 'object'; this seems to be a precaution
3189 so that old extension types don't suddenly become
3190 callable (object.__new__ wouldn't insure the invariants
3191 that the extension type's own factory function ensures).
3192 Heap types, of course, are under our control, so they do
3193 inherit tp_new; static extension types that specify some
3194 other built-in type as the default are considered
3195 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003196 if (base != &PyBaseObject_Type ||
3197 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3198 if (type->tp_new == NULL)
3199 type->tp_new = base->tp_new;
3200 }
3201 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003202 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003203
3204 /* Copy other non-function slots */
3205
3206#undef COPYVAL
3207#define COPYVAL(SLOT) \
3208 if (type->SLOT == 0) type->SLOT = base->SLOT
3209
3210 COPYVAL(tp_itemsize);
3211 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
3212 COPYVAL(tp_weaklistoffset);
3213 }
3214 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3215 COPYVAL(tp_dictoffset);
3216 }
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003217
3218 /* Setup fast subclass flags */
3219 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3220 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3221 else if (PyType_IsSubtype(base, &PyType_Type))
3222 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3223 else if (PyType_IsSubtype(base, &PyInt_Type))
3224 type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
3225 else if (PyType_IsSubtype(base, &PyLong_Type))
3226 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3227 else if (PyType_IsSubtype(base, &PyString_Type))
3228 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3229 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3230 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3231 else if (PyType_IsSubtype(base, &PyTuple_Type))
3232 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3233 else if (PyType_IsSubtype(base, &PyList_Type))
3234 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3235 else if (PyType_IsSubtype(base, &PyDict_Type))
3236 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003237}
3238
3239static void
3240inherit_slots(PyTypeObject *type, PyTypeObject *base)
3241{
3242 PyTypeObject *basebase;
3243
3244#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003245#undef COPYSLOT
3246#undef COPYNUM
3247#undef COPYSEQ
3248#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003249#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003250
3251#define SLOTDEFINED(SLOT) \
3252 (base->SLOT != 0 && \
3253 (basebase == NULL || base->SLOT != basebase->SLOT))
3254
Tim Peters6d6c1a32001-08-02 04:15:00 +00003255#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003256 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003257
3258#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3259#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3260#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003261#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003262
Guido van Rossum13d52f02001-08-10 21:24:08 +00003263 /* This won't inherit indirect slots (from tp_as_number etc.)
3264 if type doesn't provide the space. */
3265
3266 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3267 basebase = base->tp_base;
3268 if (basebase->tp_as_number == NULL)
3269 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003270 COPYNUM(nb_add);
3271 COPYNUM(nb_subtract);
3272 COPYNUM(nb_multiply);
3273 COPYNUM(nb_divide);
3274 COPYNUM(nb_remainder);
3275 COPYNUM(nb_divmod);
3276 COPYNUM(nb_power);
3277 COPYNUM(nb_negative);
3278 COPYNUM(nb_positive);
3279 COPYNUM(nb_absolute);
3280 COPYNUM(nb_nonzero);
3281 COPYNUM(nb_invert);
3282 COPYNUM(nb_lshift);
3283 COPYNUM(nb_rshift);
3284 COPYNUM(nb_and);
3285 COPYNUM(nb_xor);
3286 COPYNUM(nb_or);
3287 COPYNUM(nb_coerce);
3288 COPYNUM(nb_int);
3289 COPYNUM(nb_long);
3290 COPYNUM(nb_float);
3291 COPYNUM(nb_oct);
3292 COPYNUM(nb_hex);
3293 COPYNUM(nb_inplace_add);
3294 COPYNUM(nb_inplace_subtract);
3295 COPYNUM(nb_inplace_multiply);
3296 COPYNUM(nb_inplace_divide);
3297 COPYNUM(nb_inplace_remainder);
3298 COPYNUM(nb_inplace_power);
3299 COPYNUM(nb_inplace_lshift);
3300 COPYNUM(nb_inplace_rshift);
3301 COPYNUM(nb_inplace_and);
3302 COPYNUM(nb_inplace_xor);
3303 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003304 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
3305 COPYNUM(nb_true_divide);
3306 COPYNUM(nb_floor_divide);
3307 COPYNUM(nb_inplace_true_divide);
3308 COPYNUM(nb_inplace_floor_divide);
3309 }
Guido van Rossum38fff8c2006-03-07 18:50:55 +00003310 if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
3311 COPYNUM(nb_index);
3312 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003313 }
3314
Guido van Rossum13d52f02001-08-10 21:24:08 +00003315 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3316 basebase = base->tp_base;
3317 if (basebase->tp_as_sequence == NULL)
3318 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003319 COPYSEQ(sq_length);
3320 COPYSEQ(sq_concat);
3321 COPYSEQ(sq_repeat);
3322 COPYSEQ(sq_item);
3323 COPYSEQ(sq_slice);
3324 COPYSEQ(sq_ass_item);
3325 COPYSEQ(sq_ass_slice);
3326 COPYSEQ(sq_contains);
3327 COPYSEQ(sq_inplace_concat);
3328 COPYSEQ(sq_inplace_repeat);
3329 }
3330
Guido van Rossum13d52f02001-08-10 21:24:08 +00003331 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3332 basebase = base->tp_base;
3333 if (basebase->tp_as_mapping == NULL)
3334 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003335 COPYMAP(mp_length);
3336 COPYMAP(mp_subscript);
3337 COPYMAP(mp_ass_subscript);
3338 }
3339
Tim Petersfc57ccb2001-10-12 02:38:24 +00003340 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3341 basebase = base->tp_base;
3342 if (basebase->tp_as_buffer == NULL)
3343 basebase = NULL;
3344 COPYBUF(bf_getreadbuffer);
3345 COPYBUF(bf_getwritebuffer);
3346 COPYBUF(bf_getsegcount);
3347 COPYBUF(bf_getcharbuffer);
3348 }
3349
Guido van Rossum13d52f02001-08-10 21:24:08 +00003350 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003351
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352 COPYSLOT(tp_dealloc);
3353 COPYSLOT(tp_print);
3354 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3355 type->tp_getattr = base->tp_getattr;
3356 type->tp_getattro = base->tp_getattro;
3357 }
3358 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3359 type->tp_setattr = base->tp_setattr;
3360 type->tp_setattro = base->tp_setattro;
3361 }
3362 /* tp_compare see tp_richcompare */
3363 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003364 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365 COPYSLOT(tp_call);
3366 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003368 if (type->tp_compare == NULL &&
3369 type->tp_richcompare == NULL &&
3370 type->tp_hash == NULL)
3371 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003372 type->tp_compare = base->tp_compare;
3373 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003374 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003375 }
3376 }
3377 else {
3378 COPYSLOT(tp_compare);
3379 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003380 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3381 COPYSLOT(tp_iter);
3382 COPYSLOT(tp_iternext);
3383 }
3384 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3385 COPYSLOT(tp_descr_get);
3386 COPYSLOT(tp_descr_set);
3387 COPYSLOT(tp_dictoffset);
3388 COPYSLOT(tp_init);
3389 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003390 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003391 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3392 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3393 /* They agree about gc. */
3394 COPYSLOT(tp_free);
3395 }
3396 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3397 type->tp_free == NULL &&
3398 base->tp_free == _PyObject_Del) {
3399 /* A bit of magic to plug in the correct default
3400 * tp_free function when a derived class adds gc,
3401 * didn't define tp_free, and the base uses the
3402 * default non-gc tp_free.
3403 */
3404 type->tp_free = PyObject_GC_Del;
3405 }
3406 /* else they didn't agree about gc, and there isn't something
3407 * obvious to be done -- the type is on its own.
3408 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003409 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003410}
3411
Jeremy Hylton938ace62002-07-17 16:30:39 +00003412static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003413
Tim Peters6d6c1a32001-08-02 04:15:00 +00003414int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003415PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003417 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003418 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003419 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003420
Guido van Rossumcab05802002-06-10 15:29:03 +00003421 if (type->tp_flags & Py_TPFLAGS_READY) {
3422 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003423 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003424 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003425 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003426
3427 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003428
Tim Peters36eb4df2003-03-23 03:33:13 +00003429#ifdef Py_TRACE_REFS
3430 /* PyType_Ready is the closest thing we have to a choke point
3431 * for type objects, so is the best place I can think of to try
3432 * to get type objects into the doubly-linked list of all objects.
3433 * Still, not all type objects go thru PyType_Ready.
3434 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003435 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003436#endif
3437
Tim Peters6d6c1a32001-08-02 04:15:00 +00003438 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3439 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003440 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003442 Py_INCREF(base);
3443 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003444
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003445 /* Now the only way base can still be NULL is if type is
3446 * &PyBaseObject_Type.
3447 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003448
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003449 /* Initialize the base class */
3450 if (base && base->tp_dict == NULL) {
3451 if (PyType_Ready(base) < 0)
3452 goto error;
3453 }
3454
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003455 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003456 compilable separately on Windows can call PyType_Ready() instead of
3457 initializing the ob_type field of their type objects. */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003458 /* The test for base != NULL is really unnecessary, since base is only
3459 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3460 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3461 know that. */
Martin v. Löwis68192102007-07-21 06:55:02 +00003462 if (Py_Type(type) == NULL && base != NULL)
3463 Py_Type(type) = Py_Type(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003464
Tim Peters6d6c1a32001-08-02 04:15:00 +00003465 /* Initialize tp_bases */
3466 bases = type->tp_bases;
3467 if (bases == NULL) {
3468 if (base == NULL)
3469 bases = PyTuple_New(0);
3470 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003471 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003472 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003473 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003474 type->tp_bases = bases;
3475 }
3476
Guido van Rossum687ae002001-10-15 22:03:32 +00003477 /* Initialize tp_dict */
3478 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003479 if (dict == NULL) {
3480 dict = PyDict_New();
3481 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003482 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003483 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003484 }
3485
Guido van Rossum687ae002001-10-15 22:03:32 +00003486 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003487 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003488 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003489 if (type->tp_methods != NULL) {
3490 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003491 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003492 }
3493 if (type->tp_members != NULL) {
3494 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003495 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003496 }
3497 if (type->tp_getset != NULL) {
3498 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003499 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003500 }
3501
Tim Peters6d6c1a32001-08-02 04:15:00 +00003502 /* Calculate method resolution order */
3503 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003504 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003505 }
3506
Guido van Rossum13d52f02001-08-10 21:24:08 +00003507 /* Inherit special flags from dominant base */
3508 if (type->tp_base != NULL)
3509 inherit_special(type, type->tp_base);
3510
Tim Peters6d6c1a32001-08-02 04:15:00 +00003511 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003512 bases = type->tp_mro;
3513 assert(bases != NULL);
3514 assert(PyTuple_Check(bases));
3515 n = PyTuple_GET_SIZE(bases);
3516 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003517 PyObject *b = PyTuple_GET_ITEM(bases, i);
3518 if (PyType_Check(b))
3519 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003520 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003521
Tim Peters3cfe7542003-05-21 21:29:48 +00003522 /* Sanity check for tp_free. */
3523 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3524 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003525 /* This base class needs to call tp_free, but doesn't have
3526 * one, or its tp_free is for non-gc'ed objects.
3527 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003528 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3529 "gc and is a base type but has inappropriate "
3530 "tp_free slot",
3531 type->tp_name);
3532 goto error;
3533 }
3534
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003535 /* if the type dictionary doesn't contain a __doc__, set it from
3536 the tp_doc slot.
3537 */
3538 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3539 if (type->tp_doc != NULL) {
3540 PyObject *doc = PyString_FromString(type->tp_doc);
Neal Norwitze1fdb322006-07-21 05:32:28 +00003541 if (doc == NULL)
3542 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003543 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3544 Py_DECREF(doc);
3545 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003546 PyDict_SetItemString(type->tp_dict,
3547 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003548 }
3549 }
3550
Guido van Rossum13d52f02001-08-10 21:24:08 +00003551 /* Some more special stuff */
3552 base = type->tp_base;
3553 if (base != NULL) {
3554 if (type->tp_as_number == NULL)
3555 type->tp_as_number = base->tp_as_number;
3556 if (type->tp_as_sequence == NULL)
3557 type->tp_as_sequence = base->tp_as_sequence;
3558 if (type->tp_as_mapping == NULL)
3559 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003560 if (type->tp_as_buffer == NULL)
3561 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003562 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003563
Guido van Rossum1c450732001-10-08 15:18:27 +00003564 /* Link into each base class's list of subclasses */
3565 bases = type->tp_bases;
3566 n = PyTuple_GET_SIZE(bases);
3567 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003568 PyObject *b = PyTuple_GET_ITEM(bases, i);
3569 if (PyType_Check(b) &&
3570 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003571 goto error;
3572 }
3573
Guido van Rossum13d52f02001-08-10 21:24:08 +00003574 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003575 assert(type->tp_dict != NULL);
3576 type->tp_flags =
3577 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003578 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003579
3580 error:
3581 type->tp_flags &= ~Py_TPFLAGS_READYING;
3582 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003583}
3584
Guido van Rossum1c450732001-10-08 15:18:27 +00003585static int
3586add_subclass(PyTypeObject *base, PyTypeObject *type)
3587{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003588 Py_ssize_t i;
3589 int result;
Anthony Baxtera6286212006-04-11 07:42:36 +00003590 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003591
3592 list = base->tp_subclasses;
3593 if (list == NULL) {
3594 base->tp_subclasses = list = PyList_New(0);
3595 if (list == NULL)
3596 return -1;
3597 }
3598 assert(PyList_Check(list));
Anthony Baxtera6286212006-04-11 07:42:36 +00003599 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003600 i = PyList_GET_SIZE(list);
3601 while (--i >= 0) {
3602 ref = PyList_GET_ITEM(list, i);
3603 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003604 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Anthony Baxtera6286212006-04-11 07:42:36 +00003605 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003606 }
Anthony Baxtera6286212006-04-11 07:42:36 +00003607 result = PyList_Append(list, newobj);
3608 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003609 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003610}
3611
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003612static void
3613remove_subclass(PyTypeObject *base, PyTypeObject *type)
3614{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003615 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003616 PyObject *list, *ref;
3617
3618 list = base->tp_subclasses;
3619 if (list == NULL) {
3620 return;
3621 }
3622 assert(PyList_Check(list));
3623 i = PyList_GET_SIZE(list);
3624 while (--i >= 0) {
3625 ref = PyList_GET_ITEM(list, i);
3626 assert(PyWeakref_CheckRef(ref));
3627 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3628 /* this can't fail, right? */
3629 PySequence_DelItem(list, i);
3630 return;
3631 }
3632 }
3633}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003634
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003635static int
3636check_num_args(PyObject *ob, int n)
3637{
3638 if (!PyTuple_CheckExact(ob)) {
3639 PyErr_SetString(PyExc_SystemError,
3640 "PyArg_UnpackTuple() argument list is not a tuple");
3641 return 0;
3642 }
3643 if (n == PyTuple_GET_SIZE(ob))
3644 return 1;
3645 PyErr_Format(
3646 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003647 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003648 return 0;
3649}
3650
Tim Peters6d6c1a32001-08-02 04:15:00 +00003651/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3652
3653/* There's a wrapper *function* for each distinct function typedef used
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00003654 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003655 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3656 Most tables have only one entry; the tables for binary operators have two
3657 entries, one regular and one with reversed arguments. */
3658
3659static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003660wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003661{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003662 lenfunc func = (lenfunc)wrapped;
3663 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003664
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003665 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003666 return NULL;
3667 res = (*func)(self);
3668 if (res == -1 && PyErr_Occurred())
3669 return NULL;
3670 return PyInt_FromLong((long)res);
3671}
3672
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003674wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3675{
3676 inquiry func = (inquiry)wrapped;
3677 int res;
3678
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003679 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003680 return NULL;
3681 res = (*func)(self);
3682 if (res == -1 && PyErr_Occurred())
3683 return NULL;
3684 return PyBool_FromLong((long)res);
3685}
3686
3687static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3689{
3690 binaryfunc func = (binaryfunc)wrapped;
3691 PyObject *other;
3692
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003693 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003694 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003695 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003696 return (*func)(self, other);
3697}
3698
3699static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003700wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3701{
3702 binaryfunc func = (binaryfunc)wrapped;
3703 PyObject *other;
3704
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003705 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003706 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003707 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003708 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003709 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003710 Py_INCREF(Py_NotImplemented);
3711 return Py_NotImplemented;
3712 }
3713 return (*func)(self, other);
3714}
3715
3716static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3718{
3719 binaryfunc func = (binaryfunc)wrapped;
3720 PyObject *other;
3721
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003722 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003723 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003724 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003725 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003726 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003727 Py_INCREF(Py_NotImplemented);
3728 return Py_NotImplemented;
3729 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003730 return (*func)(other, self);
3731}
3732
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003733static PyObject *
3734wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3735{
3736 coercion func = (coercion)wrapped;
3737 PyObject *other, *res;
3738 int ok;
3739
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003740 if (!check_num_args(args, 1))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003741 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003742 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003743 ok = func(&self, &other);
3744 if (ok < 0)
3745 return NULL;
3746 if (ok > 0) {
3747 Py_INCREF(Py_NotImplemented);
3748 return Py_NotImplemented;
3749 }
3750 res = PyTuple_New(2);
3751 if (res == NULL) {
3752 Py_DECREF(self);
3753 Py_DECREF(other);
3754 return NULL;
3755 }
3756 PyTuple_SET_ITEM(res, 0, self);
3757 PyTuple_SET_ITEM(res, 1, other);
3758 return res;
3759}
3760
Tim Peters6d6c1a32001-08-02 04:15:00 +00003761static PyObject *
3762wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3763{
3764 ternaryfunc func = (ternaryfunc)wrapped;
3765 PyObject *other;
3766 PyObject *third = Py_None;
3767
3768 /* Note: This wrapper only works for __pow__() */
3769
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003770 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003771 return NULL;
3772 return (*func)(self, other, third);
3773}
3774
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003775static PyObject *
3776wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3777{
3778 ternaryfunc func = (ternaryfunc)wrapped;
3779 PyObject *other;
3780 PyObject *third = Py_None;
3781
3782 /* Note: This wrapper only works for __pow__() */
3783
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003784 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003785 return NULL;
3786 return (*func)(other, self, third);
3787}
3788
Tim Peters6d6c1a32001-08-02 04:15:00 +00003789static PyObject *
3790wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3791{
3792 unaryfunc func = (unaryfunc)wrapped;
3793
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003794 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003795 return NULL;
3796 return (*func)(self);
3797}
3798
Tim Peters6d6c1a32001-08-02 04:15:00 +00003799static PyObject *
Armin Rigo314861c2006-03-30 14:04:02 +00003800wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003801{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003802 ssizeargfunc func = (ssizeargfunc)wrapped;
Armin Rigo314861c2006-03-30 14:04:02 +00003803 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003804 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003805
Armin Rigo314861c2006-03-30 14:04:02 +00003806 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3807 return NULL;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003808 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Armin Rigo314861c2006-03-30 14:04:02 +00003809 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003810 return NULL;
3811 return (*func)(self, i);
3812}
3813
Martin v. Löwis18e16552006-02-15 17:27:45 +00003814static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003815getindex(PyObject *self, PyObject *arg)
3816{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003817 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003818
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003819 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003820 if (i == -1 && PyErr_Occurred())
3821 return -1;
3822 if (i < 0) {
Martin v. Löwis68192102007-07-21 06:55:02 +00003823 PySequenceMethods *sq = Py_Type(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003824 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003825 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003826 if (n < 0)
3827 return -1;
3828 i += n;
3829 }
3830 }
3831 return i;
3832}
3833
3834static PyObject *
3835wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3836{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003837 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003838 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003839 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003840
Guido van Rossumf4593e02001-10-03 12:09:30 +00003841 if (PyTuple_GET_SIZE(args) == 1) {
3842 arg = PyTuple_GET_ITEM(args, 0);
3843 i = getindex(self, arg);
3844 if (i == -1 && PyErr_Occurred())
3845 return NULL;
3846 return (*func)(self, i);
3847 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003848 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003849 assert(PyErr_Occurred());
3850 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003851}
3852
Tim Peters6d6c1a32001-08-02 04:15:00 +00003853static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003854wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003855{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003856 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3857 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003858
Martin v. Löwis18e16552006-02-15 17:27:45 +00003859 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003860 return NULL;
3861 return (*func)(self, i, j);
3862}
3863
Tim Peters6d6c1a32001-08-02 04:15:00 +00003864static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003865wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003866{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003867 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3868 Py_ssize_t i;
3869 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003870 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003871
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003872 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003873 return NULL;
3874 i = getindex(self, arg);
3875 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876 return NULL;
3877 res = (*func)(self, i, value);
3878 if (res == -1 && PyErr_Occurred())
3879 return NULL;
3880 Py_INCREF(Py_None);
3881 return Py_None;
3882}
3883
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003884static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003885wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003886{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003887 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3888 Py_ssize_t i;
3889 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003890 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003891
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003892 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003893 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003894 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003895 i = getindex(self, arg);
3896 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003897 return NULL;
3898 res = (*func)(self, i, NULL);
3899 if (res == -1 && PyErr_Occurred())
3900 return NULL;
3901 Py_INCREF(Py_None);
3902 return Py_None;
3903}
3904
Tim Peters6d6c1a32001-08-02 04:15:00 +00003905static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003906wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003907{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003908 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3909 Py_ssize_t i, j;
3910 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003911 PyObject *value;
3912
Martin v. Löwis18e16552006-02-15 17:27:45 +00003913 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003914 return NULL;
3915 res = (*func)(self, i, j, value);
3916 if (res == -1 && PyErr_Occurred())
3917 return NULL;
3918 Py_INCREF(Py_None);
3919 return Py_None;
3920}
3921
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003922static PyObject *
3923wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3924{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003925 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3926 Py_ssize_t i, j;
3927 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003928
Martin v. Löwis18e16552006-02-15 17:27:45 +00003929 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003930 return NULL;
3931 res = (*func)(self, i, j, NULL);
3932 if (res == -1 && PyErr_Occurred())
3933 return NULL;
3934 Py_INCREF(Py_None);
3935 return Py_None;
3936}
3937
Tim Peters6d6c1a32001-08-02 04:15:00 +00003938/* XXX objobjproc is a misnomer; should be objargpred */
3939static PyObject *
3940wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3941{
3942 objobjproc func = (objobjproc)wrapped;
3943 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003944 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003945
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003946 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003947 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003948 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003949 res = (*func)(self, value);
3950 if (res == -1 && PyErr_Occurred())
3951 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003952 else
3953 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003954}
3955
Tim Peters6d6c1a32001-08-02 04:15:00 +00003956static PyObject *
3957wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3958{
3959 objobjargproc func = (objobjargproc)wrapped;
3960 int res;
3961 PyObject *key, *value;
3962
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003963 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003964 return NULL;
3965 res = (*func)(self, key, value);
3966 if (res == -1 && PyErr_Occurred())
3967 return NULL;
3968 Py_INCREF(Py_None);
3969 return Py_None;
3970}
3971
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003972static PyObject *
3973wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3974{
3975 objobjargproc func = (objobjargproc)wrapped;
3976 int res;
3977 PyObject *key;
3978
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003979 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003980 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003981 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003982 res = (*func)(self, key, NULL);
3983 if (res == -1 && PyErr_Occurred())
3984 return NULL;
3985 Py_INCREF(Py_None);
3986 return Py_None;
3987}
3988
Tim Peters6d6c1a32001-08-02 04:15:00 +00003989static PyObject *
3990wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3991{
3992 cmpfunc func = (cmpfunc)wrapped;
3993 int res;
3994 PyObject *other;
3995
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003996 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003997 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003998 other = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis68192102007-07-21 06:55:02 +00003999 if (Py_Type(other)->tp_compare != func &&
4000 !PyType_IsSubtype(Py_Type(other), Py_Type(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00004001 PyErr_Format(
4002 PyExc_TypeError,
4003 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Martin v. Löwis68192102007-07-21 06:55:02 +00004004 Py_Type(self)->tp_name,
4005 Py_Type(self)->tp_name,
4006 Py_Type(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00004007 return NULL;
4008 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004009 res = (*func)(self, other);
4010 if (PyErr_Occurred())
4011 return NULL;
4012 return PyInt_FromLong((long)res);
4013}
4014
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004015/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00004016 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004017static int
4018hackcheck(PyObject *self, setattrofunc func, char *what)
4019{
Martin v. Löwis68192102007-07-21 06:55:02 +00004020 PyTypeObject *type = Py_Type(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004021 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
4022 type = type->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004023 /* If type is NULL now, this is a really weird type.
4024 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004025 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004026 PyErr_Format(PyExc_TypeError,
4027 "can't apply this %s to %s object",
4028 what,
4029 type->tp_name);
4030 return 0;
4031 }
4032 return 1;
4033}
4034
Tim Peters6d6c1a32001-08-02 04:15:00 +00004035static PyObject *
4036wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
4037{
4038 setattrofunc func = (setattrofunc)wrapped;
4039 int res;
4040 PyObject *name, *value;
4041
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004042 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004043 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004044 if (!hackcheck(self, func, "__setattr__"))
4045 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004046 res = (*func)(self, name, value);
4047 if (res < 0)
4048 return NULL;
4049 Py_INCREF(Py_None);
4050 return Py_None;
4051}
4052
4053static PyObject *
4054wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
4055{
4056 setattrofunc func = (setattrofunc)wrapped;
4057 int res;
4058 PyObject *name;
4059
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004060 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004061 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004062 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00004063 if (!hackcheck(self, func, "__delattr__"))
4064 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004065 res = (*func)(self, name, NULL);
4066 if (res < 0)
4067 return NULL;
4068 Py_INCREF(Py_None);
4069 return Py_None;
4070}
4071
Tim Peters6d6c1a32001-08-02 04:15:00 +00004072static PyObject *
4073wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
4074{
4075 hashfunc func = (hashfunc)wrapped;
4076 long res;
4077
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004078 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004079 return NULL;
4080 res = (*func)(self);
4081 if (res == -1 && PyErr_Occurred())
4082 return NULL;
4083 return PyInt_FromLong(res);
4084}
4085
Tim Peters6d6c1a32001-08-02 04:15:00 +00004086static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004087wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004088{
4089 ternaryfunc func = (ternaryfunc)wrapped;
4090
Guido van Rossumc8e56452001-10-22 00:43:43 +00004091 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004092}
4093
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094static PyObject *
4095wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4096{
4097 richcmpfunc func = (richcmpfunc)wrapped;
4098 PyObject *other;
4099
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004100 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004101 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004102 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004103 return (*func)(self, other, op);
4104}
4105
4106#undef RICHCMP_WRAPPER
4107#define RICHCMP_WRAPPER(NAME, OP) \
4108static PyObject * \
4109richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4110{ \
4111 return wrap_richcmpfunc(self, args, wrapped, OP); \
4112}
4113
Jack Jansen8e938b42001-08-08 15:29:49 +00004114RICHCMP_WRAPPER(lt, Py_LT)
4115RICHCMP_WRAPPER(le, Py_LE)
4116RICHCMP_WRAPPER(eq, Py_EQ)
4117RICHCMP_WRAPPER(ne, Py_NE)
4118RICHCMP_WRAPPER(gt, Py_GT)
4119RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004120
Tim Peters6d6c1a32001-08-02 04:15:00 +00004121static PyObject *
4122wrap_next(PyObject *self, PyObject *args, void *wrapped)
4123{
4124 unaryfunc func = (unaryfunc)wrapped;
4125 PyObject *res;
4126
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004127 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004128 return NULL;
4129 res = (*func)(self);
4130 if (res == NULL && !PyErr_Occurred())
4131 PyErr_SetNone(PyExc_StopIteration);
4132 return res;
4133}
4134
Tim Peters6d6c1a32001-08-02 04:15:00 +00004135static PyObject *
4136wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4137{
4138 descrgetfunc func = (descrgetfunc)wrapped;
4139 PyObject *obj;
4140 PyObject *type = NULL;
4141
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004142 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004143 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004144 if (obj == Py_None)
4145 obj = NULL;
4146 if (type == Py_None)
4147 type = NULL;
4148 if (type == NULL &&obj == NULL) {
4149 PyErr_SetString(PyExc_TypeError,
4150 "__get__(None, None) is invalid");
4151 return NULL;
4152 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004153 return (*func)(self, obj, type);
4154}
4155
Tim Peters6d6c1a32001-08-02 04:15:00 +00004156static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004157wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004158{
4159 descrsetfunc func = (descrsetfunc)wrapped;
4160 PyObject *obj, *value;
4161 int ret;
4162
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004163 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004164 return NULL;
4165 ret = (*func)(self, obj, value);
4166 if (ret < 0)
4167 return NULL;
4168 Py_INCREF(Py_None);
4169 return Py_None;
4170}
Guido van Rossum22b13872002-08-06 21:41:44 +00004171
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004172static PyObject *
4173wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4174{
4175 descrsetfunc func = (descrsetfunc)wrapped;
4176 PyObject *obj;
4177 int ret;
4178
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004179 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004180 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004181 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004182 ret = (*func)(self, obj, NULL);
4183 if (ret < 0)
4184 return NULL;
4185 Py_INCREF(Py_None);
4186 return Py_None;
4187}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004188
Tim Peters6d6c1a32001-08-02 04:15:00 +00004189static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004190wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004191{
4192 initproc func = (initproc)wrapped;
4193
Guido van Rossumc8e56452001-10-22 00:43:43 +00004194 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004195 return NULL;
4196 Py_INCREF(Py_None);
4197 return Py_None;
4198}
4199
Tim Peters6d6c1a32001-08-02 04:15:00 +00004200static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004201tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004202{
Barry Warsaw60f01882001-08-22 19:24:42 +00004203 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004204 PyObject *arg0, *res;
4205
4206 if (self == NULL || !PyType_Check(self))
4207 Py_FatalError("__new__() called with non-type 'self'");
4208 type = (PyTypeObject *)self;
4209 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004210 PyErr_Format(PyExc_TypeError,
4211 "%s.__new__(): not enough arguments",
4212 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004213 return NULL;
4214 }
4215 arg0 = PyTuple_GET_ITEM(args, 0);
4216 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004217 PyErr_Format(PyExc_TypeError,
4218 "%s.__new__(X): X is not a type object (%s)",
4219 type->tp_name,
Martin v. Löwis68192102007-07-21 06:55:02 +00004220 Py_Type(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004221 return NULL;
4222 }
4223 subtype = (PyTypeObject *)arg0;
4224 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004225 PyErr_Format(PyExc_TypeError,
4226 "%s.__new__(%s): %s is not a subtype of %s",
4227 type->tp_name,
4228 subtype->tp_name,
4229 subtype->tp_name,
4230 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004231 return NULL;
4232 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004233
4234 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004235 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004236 most derived base that's not a heap type is this type. */
4237 staticbase = subtype;
4238 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4239 staticbase = staticbase->tp_base;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004240 /* If staticbase is NULL now, it is a really weird type.
4241 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004242 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004243 PyErr_Format(PyExc_TypeError,
4244 "%s.__new__(%s) is not safe, use %s.__new__()",
4245 type->tp_name,
4246 subtype->tp_name,
4247 staticbase == NULL ? "?" : staticbase->tp_name);
4248 return NULL;
4249 }
4250
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004251 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4252 if (args == NULL)
4253 return NULL;
4254 res = type->tp_new(subtype, args, kwds);
4255 Py_DECREF(args);
4256 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257}
4258
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004259static struct PyMethodDef tp_new_methoddef[] = {
Neal Norwitza84dcd72007-05-22 07:16:44 +00004260 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004261 PyDoc_STR("T.__new__(S, ...) -> "
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004262 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004263 {0}
4264};
4265
4266static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004267add_tp_new_wrapper(PyTypeObject *type)
4268{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004269 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004270
Guido van Rossum687ae002001-10-15 22:03:32 +00004271 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004272 return 0;
4273 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004274 if (func == NULL)
4275 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004276 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004277 Py_DECREF(func);
4278 return -1;
4279 }
4280 Py_DECREF(func);
4281 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004282}
4283
Guido van Rossumf040ede2001-08-07 16:40:56 +00004284/* Slot wrappers that call the corresponding __foo__ slot. See comments
4285 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286
Guido van Rossumdc91b992001-08-08 22:26:22 +00004287#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004288static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004289FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004290{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004291 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004292 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004293}
4294
Guido van Rossumdc91b992001-08-08 22:26:22 +00004295#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004296static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004297FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004298{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004299 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004300 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004301}
4302
Guido van Rossumcd118802003-01-06 22:57:47 +00004303/* Boolean helper for SLOT1BINFULL().
4304 right.__class__ is a nontrivial subclass of left.__class__. */
4305static int
4306method_is_overloaded(PyObject *left, PyObject *right, char *name)
4307{
4308 PyObject *a, *b;
4309 int ok;
4310
Martin v. Löwis68192102007-07-21 06:55:02 +00004311 b = PyObject_GetAttrString((PyObject *)(Py_Type(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004312 if (b == NULL) {
4313 PyErr_Clear();
4314 /* If right doesn't have it, it's not overloaded */
4315 return 0;
4316 }
4317
Martin v. Löwis68192102007-07-21 06:55:02 +00004318 a = PyObject_GetAttrString((PyObject *)(Py_Type(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004319 if (a == NULL) {
4320 PyErr_Clear();
4321 Py_DECREF(b);
4322 /* If right has it but left doesn't, it's overloaded */
4323 return 1;
4324 }
4325
4326 ok = PyObject_RichCompareBool(a, b, Py_NE);
4327 Py_DECREF(a);
4328 Py_DECREF(b);
4329 if (ok < 0) {
4330 PyErr_Clear();
4331 return 0;
4332 }
4333
4334 return ok;
4335}
4336
Guido van Rossumdc91b992001-08-08 22:26:22 +00004337
4338#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004339static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004340FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004341{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004342 static PyObject *cache_str, *rcache_str; \
Martin v. Löwis68192102007-07-21 06:55:02 +00004343 int do_other = Py_Type(self) != Py_Type(other) && \
4344 Py_Type(other)->tp_as_number != NULL && \
4345 Py_Type(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4346 if (Py_Type(self)->tp_as_number != NULL && \
4347 Py_Type(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004348 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004349 if (do_other && \
Martin v. Löwis68192102007-07-21 06:55:02 +00004350 PyType_IsSubtype(Py_Type(other), Py_Type(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004351 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004352 r = call_maybe( \
4353 other, ROPSTR, &rcache_str, "(O)", self); \
4354 if (r != Py_NotImplemented) \
4355 return r; \
4356 Py_DECREF(r); \
4357 do_other = 0; \
4358 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004359 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004360 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004361 if (r != Py_NotImplemented || \
Martin v. Löwis68192102007-07-21 06:55:02 +00004362 Py_Type(other) == Py_Type(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004363 return r; \
4364 Py_DECREF(r); \
4365 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004366 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004367 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004368 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004369 } \
4370 Py_INCREF(Py_NotImplemented); \
4371 return Py_NotImplemented; \
4372}
4373
4374#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4375 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4376
4377#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4378static PyObject * \
4379FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4380{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004381 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004382 return call_method(self, OPSTR, &cache_str, \
4383 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004384}
4385
Martin v. Löwis18e16552006-02-15 17:27:45 +00004386static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004387slot_sq_length(PyObject *self)
4388{
Guido van Rossum2730b132001-08-28 18:22:14 +00004389 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004390 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004391 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004392
4393 if (res == NULL)
4394 return -1;
Neal Norwitz1872b1c2006-08-12 18:44:06 +00004395 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004396 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004397 if (len < 0) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00004398 if (!PyErr_Occurred())
4399 PyErr_SetString(PyExc_ValueError,
4400 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004401 return -1;
4402 }
Guido van Rossum26111622001-10-01 16:42:49 +00004403 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004404}
4405
Guido van Rossumf4593e02001-10-03 12:09:30 +00004406/* Super-optimized version of slot_sq_item.
4407 Other slots could do the same... */
4408static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004409slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004410{
4411 static PyObject *getitem_str;
4412 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4413 descrgetfunc f;
4414
4415 if (getitem_str == NULL) {
4416 getitem_str = PyString_InternFromString("__getitem__");
4417 if (getitem_str == NULL)
4418 return NULL;
4419 }
Martin v. Löwis68192102007-07-21 06:55:02 +00004420 func = _PyType_Lookup(Py_Type(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004421 if (func != NULL) {
Martin v. Löwis68192102007-07-21 06:55:02 +00004422 if ((f = Py_Type(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004423 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004424 else {
Martin v. Löwis68192102007-07-21 06:55:02 +00004425 func = f(func, self, (PyObject *)(Py_Type(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004426 if (func == NULL) {
4427 return NULL;
4428 }
4429 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004430 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004431 if (ival != NULL) {
4432 args = PyTuple_New(1);
4433 if (args != NULL) {
4434 PyTuple_SET_ITEM(args, 0, ival);
4435 retval = PyObject_Call(func, args, NULL);
4436 Py_XDECREF(args);
4437 Py_XDECREF(func);
4438 return retval;
4439 }
4440 }
4441 }
4442 else {
4443 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4444 }
4445 Py_XDECREF(args);
4446 Py_XDECREF(ival);
4447 Py_XDECREF(func);
4448 return NULL;
4449}
4450
Martin v. Löwis18e16552006-02-15 17:27:45 +00004451SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004452
4453static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004454slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004455{
4456 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004457 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004458
4459 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004460 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004461 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004462 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004463 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004464 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004465 if (res == NULL)
4466 return -1;
4467 Py_DECREF(res);
4468 return 0;
4469}
4470
4471static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004472slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004473{
4474 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004475 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004476
4477 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004478 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004479 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004480 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004481 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters4e908102006-04-21 11:26:56 +00004482 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004483 if (res == NULL)
4484 return -1;
4485 Py_DECREF(res);
4486 return 0;
4487}
4488
4489static int
4490slot_sq_contains(PyObject *self, PyObject *value)
4491{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004492 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004493 int result = -1;
4494
Guido van Rossum60718732001-08-28 17:47:51 +00004495 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004496
Guido van Rossum55f20992001-10-01 17:18:22 +00004497 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004498 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004499 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004500 if (args == NULL)
4501 res = NULL;
4502 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004503 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004504 Py_DECREF(args);
4505 }
4506 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004507 if (res != NULL) {
4508 result = PyObject_IsTrue(res);
4509 Py_DECREF(res);
4510 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004511 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004512 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004513 /* Possible results: -1 and 1 */
4514 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004515 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004516 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004517 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004518}
4519
Tim Peters6d6c1a32001-08-02 04:15:00 +00004520#define slot_mp_length slot_sq_length
4521
Guido van Rossumdc91b992001-08-08 22:26:22 +00004522SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004523
4524static int
4525slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4526{
4527 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004528 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004529
4530 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004531 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004532 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004533 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004534 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004535 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004536 if (res == NULL)
4537 return -1;
4538 Py_DECREF(res);
4539 return 0;
4540}
4541
Guido van Rossumdc91b992001-08-08 22:26:22 +00004542SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4543SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4544SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4545SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4546SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4547SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4548
Jeremy Hylton938ace62002-07-17 16:30:39 +00004549static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004550
4551SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4552 nb_power, "__pow__", "__rpow__")
4553
4554static PyObject *
4555slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4556{
Guido van Rossum2730b132001-08-28 18:22:14 +00004557 static PyObject *pow_str;
4558
Guido van Rossumdc91b992001-08-08 22:26:22 +00004559 if (modulus == Py_None)
4560 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004561 /* Three-arg power doesn't use __rpow__. But ternary_op
4562 can call this when the second argument's type uses
4563 slot_nb_power, so check before calling self.__pow__. */
Martin v. Löwis68192102007-07-21 06:55:02 +00004564 if (Py_Type(self)->tp_as_number != NULL &&
4565 Py_Type(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004566 return call_method(self, "__pow__", &pow_str,
4567 "(OO)", other, modulus);
4568 }
4569 Py_INCREF(Py_NotImplemented);
4570 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004571}
4572
4573SLOT0(slot_nb_negative, "__neg__")
4574SLOT0(slot_nb_positive, "__pos__")
4575SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004576
4577static int
4578slot_nb_nonzero(PyObject *self)
4579{
Tim Petersea7f75d2002-12-07 21:39:16 +00004580 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004581 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004582 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004583
Guido van Rossum55f20992001-10-01 17:18:22 +00004584 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004585 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004586 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004587 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004588 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004589 if (func == NULL)
4590 return PyErr_Occurred() ? -1 : 1;
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00004591 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004592 args = PyTuple_New(0);
4593 if (args != NULL) {
4594 PyObject *temp = PyObject_Call(func, args, NULL);
4595 Py_DECREF(args);
4596 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004597 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004598 result = PyObject_IsTrue(temp);
4599 else {
4600 PyErr_Format(PyExc_TypeError,
4601 "__nonzero__ should return "
4602 "bool or int, returned %s",
4603 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004604 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004605 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004606 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004607 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004608 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004609 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004610 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004611}
4612
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004613
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004614static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004615slot_nb_index(PyObject *self)
4616{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004617 static PyObject *index_str;
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00004618 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004619}
4620
4621
Guido van Rossumdc91b992001-08-08 22:26:22 +00004622SLOT0(slot_nb_invert, "__invert__")
4623SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4624SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4625SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4626SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4627SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004628
4629static int
4630slot_nb_coerce(PyObject **a, PyObject **b)
4631{
4632 static PyObject *coerce_str;
4633 PyObject *self = *a, *other = *b;
4634
4635 if (self->ob_type->tp_as_number != NULL &&
4636 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4637 PyObject *r;
4638 r = call_maybe(
4639 self, "__coerce__", &coerce_str, "(O)", other);
4640 if (r == NULL)
4641 return -1;
4642 if (r == Py_NotImplemented) {
4643 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004644 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004645 else {
4646 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4647 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004648 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004649 Py_DECREF(r);
4650 return -1;
4651 }
4652 *a = PyTuple_GET_ITEM(r, 0);
4653 Py_INCREF(*a);
4654 *b = PyTuple_GET_ITEM(r, 1);
4655 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004656 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004657 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004658 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004659 }
4660 if (other->ob_type->tp_as_number != NULL &&
4661 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4662 PyObject *r;
4663 r = call_maybe(
4664 other, "__coerce__", &coerce_str, "(O)", self);
4665 if (r == NULL)
4666 return -1;
4667 if (r == Py_NotImplemented) {
4668 Py_DECREF(r);
4669 return 1;
4670 }
4671 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4672 PyErr_SetString(PyExc_TypeError,
4673 "__coerce__ didn't return a 2-tuple");
4674 Py_DECREF(r);
4675 return -1;
4676 }
4677 *a = PyTuple_GET_ITEM(r, 1);
4678 Py_INCREF(*a);
4679 *b = PyTuple_GET_ITEM(r, 0);
4680 Py_INCREF(*b);
4681 Py_DECREF(r);
4682 return 0;
4683 }
4684 return 1;
4685}
4686
Guido van Rossumdc91b992001-08-08 22:26:22 +00004687SLOT0(slot_nb_int, "__int__")
4688SLOT0(slot_nb_long, "__long__")
4689SLOT0(slot_nb_float, "__float__")
4690SLOT0(slot_nb_oct, "__oct__")
4691SLOT0(slot_nb_hex, "__hex__")
4692SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4693SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4694SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4695SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4696SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Martin v. Löwisfd963262007-02-09 12:19:32 +00004697/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4698static PyObject *
4699slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4700{
4701 static PyObject *cache_str;
4702 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4703}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004704SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4705SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4706SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4707SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4708SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4709SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4710 "__floordiv__", "__rfloordiv__")
4711SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4712SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4713SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004714
4715static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004716half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004717{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004718 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004719 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004720 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004721
Guido van Rossum60718732001-08-28 17:47:51 +00004722 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004723 if (func == NULL) {
4724 PyErr_Clear();
4725 }
4726 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004727 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004728 if (args == NULL)
4729 res = NULL;
4730 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004731 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004732 Py_DECREF(args);
4733 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004734 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004735 if (res != Py_NotImplemented) {
4736 if (res == NULL)
4737 return -2;
4738 c = PyInt_AsLong(res);
4739 Py_DECREF(res);
4740 if (c == -1 && PyErr_Occurred())
4741 return -2;
4742 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4743 }
4744 Py_DECREF(res);
4745 }
4746 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004747}
4748
Guido van Rossumab3b0342001-09-18 20:38:53 +00004749/* This slot is published for the benefit of try_3way_compare in object.c */
4750int
4751_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004752{
4753 int c;
4754
Martin v. Löwis68192102007-07-21 06:55:02 +00004755 if (Py_Type(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004756 c = half_compare(self, other);
4757 if (c <= 1)
4758 return c;
4759 }
Martin v. Löwis68192102007-07-21 06:55:02 +00004760 if (Py_Type(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004761 c = half_compare(other, self);
4762 if (c < -1)
4763 return -2;
4764 if (c <= 1)
4765 return -c;
4766 }
4767 return (void *)self < (void *)other ? -1 :
4768 (void *)self > (void *)other ? 1 : 0;
4769}
4770
4771static PyObject *
4772slot_tp_repr(PyObject *self)
4773{
4774 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004775 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004776
Guido van Rossum60718732001-08-28 17:47:51 +00004777 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004778 if (func != NULL) {
4779 res = PyEval_CallObject(func, NULL);
4780 Py_DECREF(func);
4781 return res;
4782 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004783 PyErr_Clear();
4784 return PyString_FromFormat("<%s object at %p>",
Martin v. Löwis68192102007-07-21 06:55:02 +00004785 Py_Type(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004786}
4787
4788static PyObject *
4789slot_tp_str(PyObject *self)
4790{
4791 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004792 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004793
Guido van Rossum60718732001-08-28 17:47:51 +00004794 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004795 if (func != NULL) {
4796 res = PyEval_CallObject(func, NULL);
4797 Py_DECREF(func);
4798 return res;
4799 }
4800 else {
4801 PyErr_Clear();
4802 return slot_tp_repr(self);
4803 }
4804}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004805
4806static long
4807slot_tp_hash(PyObject *self)
4808{
Tim Peters61ce0a92002-12-06 23:38:02 +00004809 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004810 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004811 long h;
4812
Guido van Rossum60718732001-08-28 17:47:51 +00004813 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004814
4815 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004816 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004817 Py_DECREF(func);
4818 if (res == NULL)
4819 return -1;
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004820 if (PyLong_Check(res))
Armin Rigo51fc8c42006-08-09 14:55:26 +00004821 h = PyLong_Type.tp_hash(res);
Martin v. Löwisab2f8f72006-08-09 07:57:39 +00004822 else
4823 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004824 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004825 }
4826 else {
4827 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004828 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004829 if (func == NULL) {
4830 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004831 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004832 }
4833 if (func != NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00004834 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
4835 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004836 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004837 return -1;
4838 }
4839 PyErr_Clear();
4840 h = _Py_HashPointer((void *)self);
4841 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004842 if (h == -1 && !PyErr_Occurred())
4843 h = -2;
4844 return h;
4845}
4846
4847static PyObject *
4848slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4849{
Guido van Rossum60718732001-08-28 17:47:51 +00004850 static PyObject *call_str;
4851 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004852 PyObject *res;
4853
4854 if (meth == NULL)
4855 return NULL;
Armin Rigo53c1692f2006-06-21 21:58:50 +00004856
4857 /* PyObject_Call() will end up calling slot_tp_call() again if
4858 the object returned for __call__ has __call__ itself defined
4859 upon it. This can be an infinite recursion if you set
4860 __call__ in a class to an instance of it. */
Neal Norwitzb1149842006-06-23 03:32:44 +00004861 if (Py_EnterRecursiveCall(" in __call__")) {
4862 Py_DECREF(meth);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004863 return NULL;
Neal Norwitzb1149842006-06-23 03:32:44 +00004864 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004865 res = PyObject_Call(meth, args, kwds);
Armin Rigo53c1692f2006-06-21 21:58:50 +00004866 Py_LeaveRecursiveCall();
4867
Tim Peters6d6c1a32001-08-02 04:15:00 +00004868 Py_DECREF(meth);
4869 return res;
4870}
4871
Guido van Rossum14a6f832001-10-17 13:59:09 +00004872/* There are two slot dispatch functions for tp_getattro.
4873
4874 - slot_tp_getattro() is used when __getattribute__ is overridden
4875 but no __getattr__ hook is present;
4876
4877 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4878
Guido van Rossumc334df52002-04-04 23:44:47 +00004879 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4880 detects the absence of __getattr__ and then installs the simpler slot if
4881 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004882
Tim Peters6d6c1a32001-08-02 04:15:00 +00004883static PyObject *
4884slot_tp_getattro(PyObject *self, PyObject *name)
4885{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004886 static PyObject *getattribute_str = NULL;
4887 return call_method(self, "__getattribute__", &getattribute_str,
4888 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004889}
4890
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004891static PyObject *
4892slot_tp_getattr_hook(PyObject *self, PyObject *name)
4893{
Martin v. Löwis68192102007-07-21 06:55:02 +00004894 PyTypeObject *tp = Py_Type(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004895 PyObject *getattr, *getattribute, *res;
4896 static PyObject *getattribute_str = NULL;
4897 static PyObject *getattr_str = NULL;
4898
4899 if (getattr_str == NULL) {
4900 getattr_str = PyString_InternFromString("__getattr__");
4901 if (getattr_str == NULL)
4902 return NULL;
4903 }
4904 if (getattribute_str == NULL) {
4905 getattribute_str =
4906 PyString_InternFromString("__getattribute__");
4907 if (getattribute_str == NULL)
4908 return NULL;
4909 }
4910 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004911 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004912 /* No __getattr__ hook: use a simpler dispatcher */
4913 tp->tp_getattro = slot_tp_getattro;
4914 return slot_tp_getattro(self, name);
4915 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004916 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004917 if (getattribute == NULL ||
Martin v. Löwis68192102007-07-21 06:55:02 +00004918 (Py_Type(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00004919 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4920 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004921 res = PyObject_GenericGetAttr(self, name);
4922 else
Georg Brandl684fd0c2006-05-25 19:15:31 +00004923 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004924 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004925 PyErr_Clear();
Georg Brandl684fd0c2006-05-25 19:15:31 +00004926 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004927 }
4928 return res;
4929}
4930
Tim Peters6d6c1a32001-08-02 04:15:00 +00004931static int
4932slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4933{
4934 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004935 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004936
4937 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004938 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004939 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004940 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004941 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004942 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004943 if (res == NULL)
4944 return -1;
4945 Py_DECREF(res);
4946 return 0;
4947}
4948
4949/* Map rich comparison operators to their __xx__ namesakes */
4950static char *name_op[] = {
4951 "__lt__",
4952 "__le__",
4953 "__eq__",
4954 "__ne__",
4955 "__gt__",
4956 "__ge__",
4957};
4958
4959static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004960half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004961{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004962 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004963 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004964
Guido van Rossum60718732001-08-28 17:47:51 +00004965 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004966 if (func == NULL) {
4967 PyErr_Clear();
4968 Py_INCREF(Py_NotImplemented);
4969 return Py_NotImplemented;
4970 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004971 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004972 if (args == NULL)
4973 res = NULL;
4974 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004975 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004976 Py_DECREF(args);
4977 }
4978 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004979 return res;
4980}
4981
Guido van Rossumb8f63662001-08-15 23:57:02 +00004982static PyObject *
4983slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4984{
4985 PyObject *res;
4986
Martin v. Löwis68192102007-07-21 06:55:02 +00004987 if (Py_Type(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004988 res = half_richcompare(self, other, op);
4989 if (res != Py_NotImplemented)
4990 return res;
4991 Py_DECREF(res);
4992 }
Martin v. Löwis68192102007-07-21 06:55:02 +00004993 if (Py_Type(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004994 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004995 if (res != Py_NotImplemented) {
4996 return res;
4997 }
4998 Py_DECREF(res);
4999 }
5000 Py_INCREF(Py_NotImplemented);
5001 return Py_NotImplemented;
5002}
5003
5004static PyObject *
5005slot_tp_iter(PyObject *self)
5006{
5007 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00005008 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005009
Guido van Rossum60718732001-08-28 17:47:51 +00005010 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005011 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00005012 PyObject *args;
5013 args = res = PyTuple_New(0);
5014 if (args != NULL) {
5015 res = PyObject_Call(func, args, NULL);
5016 Py_DECREF(args);
5017 }
5018 Py_DECREF(func);
5019 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00005020 }
5021 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00005022 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005023 if (func == NULL) {
Georg Brandlccff7852006-06-18 22:17:29 +00005024 PyErr_Format(PyExc_TypeError,
5025 "'%.200s' object is not iterable",
Martin v. Löwis68192102007-07-21 06:55:02 +00005026 Py_Type(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00005027 return NULL;
5028 }
5029 Py_DECREF(func);
5030 return PySeqIter_New(self);
5031}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005032
5033static PyObject *
5034slot_tp_iternext(PyObject *self)
5035{
Guido van Rossum2730b132001-08-28 18:22:14 +00005036 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00005037 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005038}
5039
Guido van Rossum1a493502001-08-17 16:47:50 +00005040static PyObject *
5041slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5042{
Martin v. Löwis68192102007-07-21 06:55:02 +00005043 PyTypeObject *tp = Py_Type(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00005044 PyObject *get;
5045 static PyObject *get_str = NULL;
5046
5047 if (get_str == NULL) {
5048 get_str = PyString_InternFromString("__get__");
5049 if (get_str == NULL)
5050 return NULL;
5051 }
5052 get = _PyType_Lookup(tp, get_str);
5053 if (get == NULL) {
5054 /* Avoid further slowdowns */
5055 if (tp->tp_descr_get == slot_tp_descr_get)
5056 tp->tp_descr_get = NULL;
5057 Py_INCREF(self);
5058 return self;
5059 }
Guido van Rossum2c252392001-08-24 10:13:31 +00005060 if (obj == NULL)
5061 obj = Py_None;
5062 if (type == NULL)
5063 type = Py_None;
Georg Brandl684fd0c2006-05-25 19:15:31 +00005064 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00005065}
Tim Peters6d6c1a32001-08-02 04:15:00 +00005066
5067static int
5068slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
5069{
Guido van Rossum2c252392001-08-24 10:13:31 +00005070 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00005071 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00005072
5073 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00005074 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005075 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00005076 else
Guido van Rossum2730b132001-08-28 18:22:14 +00005077 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00005078 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005079 if (res == NULL)
5080 return -1;
5081 Py_DECREF(res);
5082 return 0;
5083}
5084
5085static int
5086slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
5087{
Guido van Rossum60718732001-08-28 17:47:51 +00005088 static PyObject *init_str;
5089 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005090 PyObject *res;
5091
5092 if (meth == NULL)
5093 return -1;
5094 res = PyObject_Call(meth, args, kwds);
5095 Py_DECREF(meth);
5096 if (res == NULL)
5097 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005098 if (res != Py_None) {
Georg Brandlccff7852006-06-18 22:17:29 +00005099 PyErr_Format(PyExc_TypeError,
5100 "__init__() should return None, not '%.200s'",
Martin v. Löwis68192102007-07-21 06:55:02 +00005101 Py_Type(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00005102 Py_DECREF(res);
5103 return -1;
5104 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00005105 Py_DECREF(res);
5106 return 0;
5107}
5108
5109static PyObject *
5110slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5111{
Guido van Rossum7bed2132002-08-08 21:57:53 +00005112 static PyObject *new_str;
5113 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005114 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005115 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005116
Guido van Rossum7bed2132002-08-08 21:57:53 +00005117 if (new_str == NULL) {
5118 new_str = PyString_InternFromString("__new__");
5119 if (new_str == NULL)
5120 return NULL;
5121 }
5122 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005123 if (func == NULL)
5124 return NULL;
5125 assert(PyTuple_Check(args));
5126 n = PyTuple_GET_SIZE(args);
5127 newargs = PyTuple_New(n+1);
5128 if (newargs == NULL)
5129 return NULL;
5130 Py_INCREF(type);
5131 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
5132 for (i = 0; i < n; i++) {
5133 x = PyTuple_GET_ITEM(args, i);
5134 Py_INCREF(x);
5135 PyTuple_SET_ITEM(newargs, i+1, x);
5136 }
5137 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00005138 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005139 Py_DECREF(func);
5140 return x;
5141}
5142
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005143static void
5144slot_tp_del(PyObject *self)
5145{
5146 static PyObject *del_str = NULL;
5147 PyObject *del, *res;
5148 PyObject *error_type, *error_value, *error_traceback;
5149
5150 /* Temporarily resurrect the object. */
5151 assert(self->ob_refcnt == 0);
5152 self->ob_refcnt = 1;
5153
5154 /* Save the current exception, if any. */
5155 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5156
5157 /* Execute __del__ method, if any. */
5158 del = lookup_maybe(self, "__del__", &del_str);
5159 if (del != NULL) {
5160 res = PyEval_CallObject(del, NULL);
5161 if (res == NULL)
5162 PyErr_WriteUnraisable(del);
5163 else
5164 Py_DECREF(res);
5165 Py_DECREF(del);
5166 }
5167
5168 /* Restore the saved exception. */
5169 PyErr_Restore(error_type, error_value, error_traceback);
5170
5171 /* Undo the temporary resurrection; can't use DECREF here, it would
5172 * cause a recursive call.
5173 */
5174 assert(self->ob_refcnt > 0);
5175 if (--self->ob_refcnt == 0)
5176 return; /* this is the normal path out */
5177
5178 /* __del__ resurrected it! Make it look like the original Py_DECREF
5179 * never happened.
5180 */
5181 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005182 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005183 _Py_NewReference(self);
5184 self->ob_refcnt = refcnt;
5185 }
Martin v. Löwis68192102007-07-21 06:55:02 +00005186 assert(!PyType_IS_GC(Py_Type(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005187 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005188 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5189 * we need to undo that. */
5190 _Py_DEC_REFTOTAL;
5191 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5192 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005193 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5194 * _Py_NewReference bumped tp_allocs: both of those need to be
5195 * undone.
5196 */
5197#ifdef COUNT_ALLOCS
Martin v. Löwis68192102007-07-21 06:55:02 +00005198 --Py_Type(self)->tp_frees;
5199 --Py_Type(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005200#endif
5201}
5202
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005203
5204/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005205 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005206 structure, which incorporates the additional structures used for numbers,
5207 sequences and mappings.
5208 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005209 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005210 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5211 terminated with an all-zero entry. (This table is further initialized and
5212 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005213
Guido van Rossum6d204072001-10-21 00:44:31 +00005214typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005215
5216#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005217#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005218#undef ETSLOT
5219#undef SQSLOT
5220#undef MPSLOT
5221#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005222#undef UNSLOT
5223#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005224#undef BINSLOT
5225#undef RBINSLOT
5226
Guido van Rossum6d204072001-10-21 00:44:31 +00005227#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005228 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5229 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005230#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5231 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005232 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005233#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005234 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005235 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005236#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5237 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5238#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5239 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5240#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5241 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5242#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5243 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5244 "x." NAME "() <==> " DOC)
5245#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5246 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5247 "x." NAME "(y) <==> x" DOC "y")
5248#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5249 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5250 "x." NAME "(y) <==> x" DOC "y")
5251#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5252 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5253 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005254#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5255 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5256 "x." NAME "(y) <==> " DOC)
5257#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5258 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5259 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005260
5261static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005262 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005263 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005264 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5265 The logic in abstract.c always falls back to nb_add/nb_multiply in
5266 this case. Defining both the nb_* and the sq_* slots to call the
5267 user-defined methods has unexpected side-effects, as shown by
5268 test_descr.notimplemented() */
5269 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005270 "x.__add__(y) <==> x+y"),
Armin Rigo314861c2006-03-30 14:04:02 +00005271 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005272 "x.__mul__(n) <==> x*n"),
Armin Rigo314861c2006-03-30 14:04:02 +00005273 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005274 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005275 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5276 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005277 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005278 "x.__getslice__(i, j) <==> x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005279 \n\
5280 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005281 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005282 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005283 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005284 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005285 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005286 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005287 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005288 \n\
5289 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005290 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005291 "x.__delslice__(i, j) <==> del x[i:j]\n\
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005292 \n\
5293 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005294 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5295 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005296 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005297 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005298 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005299 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005300
Martin v. Löwis18e16552006-02-15 17:27:45 +00005301 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005302 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005303 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005304 wrap_binaryfunc,
5305 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005306 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005307 wrap_objobjargproc,
5308 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005309 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005310 wrap_delitem,
5311 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005312
Guido van Rossum6d204072001-10-21 00:44:31 +00005313 BINSLOT("__add__", nb_add, slot_nb_add,
5314 "+"),
5315 RBINSLOT("__radd__", nb_add, slot_nb_add,
5316 "+"),
5317 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5318 "-"),
5319 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5320 "-"),
5321 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5322 "*"),
5323 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5324 "*"),
5325 BINSLOT("__div__", nb_divide, slot_nb_divide,
5326 "/"),
5327 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
5328 "/"),
5329 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5330 "%"),
5331 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5332 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005333 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005334 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005335 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005336 "divmod(y, x)"),
5337 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5338 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5339 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5340 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5341 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5342 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5343 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5344 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00005345 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005346 "x != 0"),
5347 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5348 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5349 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5350 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5351 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5352 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5353 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5354 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5355 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5356 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5357 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
5358 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
5359 "x.__coerce__(y) <==> coerce(x, y)"),
5360 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5361 "int(x)"),
5362 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5363 "long(x)"),
5364 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5365 "float(x)"),
5366 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
5367 "oct(x)"),
5368 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
5369 "hex(x)"),
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00005370 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005371 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005372 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5373 wrap_binaryfunc, "+"),
5374 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5375 wrap_binaryfunc, "-"),
5376 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5377 wrap_binaryfunc, "*"),
5378 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
5379 wrap_binaryfunc, "/"),
5380 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5381 wrap_binaryfunc, "%"),
5382 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005383 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005384 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5385 wrap_binaryfunc, "<<"),
5386 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5387 wrap_binaryfunc, ">>"),
5388 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5389 wrap_binaryfunc, "&"),
5390 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5391 wrap_binaryfunc, "^"),
5392 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5393 wrap_binaryfunc, "|"),
5394 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5395 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5396 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5397 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5398 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5399 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5400 IBSLOT("__itruediv__", nb_inplace_true_divide,
5401 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005402
Guido van Rossum6d204072001-10-21 00:44:31 +00005403 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5404 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005405 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005406 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5407 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005408 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005409 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5410 "x.__cmp__(y) <==> cmp(x,y)"),
5411 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5412 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005413 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5414 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005415 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005416 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5417 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5418 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5419 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5420 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5421 "x.__setattr__('name', value) <==> x.name = value"),
5422 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5423 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5424 "x.__delattr__('name') <==> del x.name"),
5425 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5426 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5427 "x.__lt__(y) <==> x<y"),
5428 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5429 "x.__le__(y) <==> x<=y"),
5430 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5431 "x.__eq__(y) <==> x==y"),
5432 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5433 "x.__ne__(y) <==> x!=y"),
5434 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5435 "x.__gt__(y) <==> x>y"),
5436 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5437 "x.__ge__(y) <==> x>=y"),
5438 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5439 "x.__iter__() <==> iter(x)"),
5440 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5441 "x.next() -> the next value, or raise StopIteration"),
5442 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5443 "descr.__get__(obj[, type]) -> value"),
5444 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5445 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005446 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5447 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005448 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005449 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005450 "see x.__class__.__doc__ for signature",
5451 PyWrapperFlag_KEYWORDS),
5452 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005453 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005454 {NULL}
5455};
5456
Guido van Rossumc334df52002-04-04 23:44:47 +00005457/* Given a type pointer and an offset gotten from a slotdef entry, return a
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005458 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005459 the offset to the type pointer, since it takes care to indirect through the
5460 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5461 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005462static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005463slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005464{
5465 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005466 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005467
Guido van Rossume5c691a2003-03-07 15:13:17 +00005468 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005469 assert(offset >= 0);
Skip Montanaro429433b2006-04-18 00:35:43 +00005470 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5471 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005472 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005473 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005474 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005475 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005476 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005477 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005478 }
Skip Montanaro429433b2006-04-18 00:35:43 +00005479 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005480 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005481 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005482 }
5483 else {
Martin v. Löwisee36d652006-04-11 09:08:02 +00005484 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005485 }
5486 if (ptr != NULL)
5487 ptr += offset;
5488 return (void **)ptr;
5489}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005490
Guido van Rossumc334df52002-04-04 23:44:47 +00005491/* Length of array of slotdef pointers used to store slots with the
5492 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5493 the same __name__, for any __name__. Since that's a static property, it is
5494 appropriate to declare fixed-size arrays for this. */
5495#define MAX_EQUIV 10
5496
5497/* Return a slot pointer for a given name, but ONLY if the attribute has
5498 exactly one slot function. The name must be an interned string. */
5499static void **
5500resolve_slotdups(PyTypeObject *type, PyObject *name)
5501{
5502 /* XXX Maybe this could be optimized more -- but is it worth it? */
5503
5504 /* pname and ptrs act as a little cache */
5505 static PyObject *pname;
5506 static slotdef *ptrs[MAX_EQUIV];
5507 slotdef *p, **pp;
5508 void **res, **ptr;
5509
5510 if (pname != name) {
5511 /* Collect all slotdefs that match name into ptrs. */
5512 pname = name;
5513 pp = ptrs;
5514 for (p = slotdefs; p->name_strobj; p++) {
5515 if (p->name_strobj == name)
5516 *pp++ = p;
5517 }
5518 *pp = NULL;
5519 }
5520
5521 /* Look in all matching slots of the type; if exactly one of these has
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005522 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005523 res = NULL;
5524 for (pp = ptrs; *pp; pp++) {
5525 ptr = slotptr(type, (*pp)->offset);
5526 if (ptr == NULL || *ptr == NULL)
5527 continue;
5528 if (res != NULL)
5529 return NULL;
5530 res = ptr;
5531 }
5532 return res;
5533}
5534
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005535/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005536 does some incredibly complex thinking and then sticks something into the
5537 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5538 interests, and then stores a generic wrapper or a specific function into
5539 the slot.) Return a pointer to the next slotdef with a different offset,
5540 because that's convenient for fixup_slot_dispatchers(). */
5541static slotdef *
5542update_one_slot(PyTypeObject *type, slotdef *p)
5543{
5544 PyObject *descr;
5545 PyWrapperDescrObject *d;
5546 void *generic = NULL, *specific = NULL;
5547 int use_generic = 0;
5548 int offset = p->offset;
5549 void **ptr = slotptr(type, offset);
5550
5551 if (ptr == NULL) {
5552 do {
5553 ++p;
5554 } while (p->offset == offset);
5555 return p;
5556 }
5557 do {
5558 descr = _PyType_Lookup(type, p->name_strobj);
5559 if (descr == NULL)
5560 continue;
Martin v. Löwis68192102007-07-21 06:55:02 +00005561 if (Py_Type(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005562 void **tptr = resolve_slotdups(type, p->name_strobj);
5563 if (tptr == NULL || tptr == ptr)
5564 generic = p->function;
5565 d = (PyWrapperDescrObject *)descr;
5566 if (d->d_base->wrapper == p->wrapper &&
5567 PyType_IsSubtype(type, d->d_type))
5568 {
5569 if (specific == NULL ||
5570 specific == d->d_wrapped)
5571 specific = d->d_wrapped;
5572 else
5573 use_generic = 1;
5574 }
5575 }
Martin v. Löwis68192102007-07-21 06:55:02 +00005576 else if (Py_Type(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005577 PyCFunction_GET_FUNCTION(descr) ==
5578 (PyCFunction)tp_new_wrapper &&
5579 strcmp(p->name, "__new__") == 0)
5580 {
5581 /* The __new__ wrapper is not a wrapper descriptor,
5582 so must be special-cased differently.
5583 If we don't do this, creating an instance will
5584 always use slot_tp_new which will look up
5585 __new__ in the MRO which will call tp_new_wrapper
5586 which will look through the base classes looking
5587 for a static base and call its tp_new (usually
5588 PyType_GenericNew), after performing various
5589 sanity checks and constructing a new argument
5590 list. Cut all that nonsense short -- this speeds
5591 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005592 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005593 /* XXX I'm not 100% sure that there isn't a hole
5594 in this reasoning that requires additional
5595 sanity checks. I'll buy the first person to
5596 point out a bug in this reasoning a beer. */
5597 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005598 else {
5599 use_generic = 1;
5600 generic = p->function;
5601 }
5602 } while ((++p)->offset == offset);
5603 if (specific && !use_generic)
5604 *ptr = specific;
5605 else
5606 *ptr = generic;
5607 return p;
5608}
5609
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005610/* In the type, update the slots whose slotdefs are gathered in the pp array.
5611 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005612static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005613update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005614{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005615 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005616
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005617 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005618 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005619 return 0;
5620}
5621
Guido van Rossumc334df52002-04-04 23:44:47 +00005622/* Comparison function for qsort() to compare slotdefs by their offset, and
5623 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005624static int
5625slotdef_cmp(const void *aa, const void *bb)
5626{
5627 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5628 int c = a->offset - b->offset;
5629 if (c != 0)
5630 return c;
5631 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005632 /* Cannot use a-b, as this gives off_t,
5633 which may lose precision when converted to int. */
5634 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005635}
5636
Guido van Rossumc334df52002-04-04 23:44:47 +00005637/* Initialize the slotdefs table by adding interned string objects for the
5638 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005639static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005640init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005641{
5642 slotdef *p;
5643 static int initialized = 0;
5644
5645 if (initialized)
5646 return;
5647 for (p = slotdefs; p->name; p++) {
5648 p->name_strobj = PyString_InternFromString(p->name);
5649 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005650 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005651 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005652 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5653 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005654 initialized = 1;
5655}
5656
Guido van Rossumc334df52002-04-04 23:44:47 +00005657/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005658static int
5659update_slot(PyTypeObject *type, PyObject *name)
5660{
Guido van Rossumc334df52002-04-04 23:44:47 +00005661 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005662 slotdef *p;
5663 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005664 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005665
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005666 init_slotdefs();
5667 pp = ptrs;
5668 for (p = slotdefs; p->name; p++) {
5669 /* XXX assume name is interned! */
5670 if (p->name_strobj == name)
5671 *pp++ = p;
5672 }
5673 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005674 for (pp = ptrs; *pp; pp++) {
5675 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005676 offset = p->offset;
5677 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005678 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005679 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005680 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005681 if (ptrs[0] == NULL)
5682 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005683 return update_subclasses(type, name,
5684 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005685}
5686
Guido van Rossumc334df52002-04-04 23:44:47 +00005687/* Store the proper functions in the slot dispatches at class (type)
5688 definition time, based upon which operations the class overrides in its
5689 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005690static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005691fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005692{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005693 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005694
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005695 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005696 for (p = slotdefs; p->name; )
5697 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005698}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005699
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005700static void
5701update_all_slots(PyTypeObject* type)
5702{
5703 slotdef *p;
5704
5705 init_slotdefs();
5706 for (p = slotdefs; p->name; p++) {
5707 /* update_slot returns int but can't actually fail */
5708 update_slot(type, p->name_strobj);
5709 }
5710}
5711
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005712/* recurse_down_subclasses() and update_subclasses() are mutually
5713 recursive functions to call a callback for all subclasses,
5714 but refraining from recursing into subclasses that define 'name'. */
5715
5716static int
5717update_subclasses(PyTypeObject *type, PyObject *name,
5718 update_callback callback, void *data)
5719{
5720 if (callback(type, data) < 0)
5721 return -1;
5722 return recurse_down_subclasses(type, name, callback, data);
5723}
5724
5725static int
5726recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5727 update_callback callback, void *data)
5728{
5729 PyTypeObject *subclass;
5730 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005731 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005732
5733 subclasses = type->tp_subclasses;
5734 if (subclasses == NULL)
5735 return 0;
5736 assert(PyList_Check(subclasses));
5737 n = PyList_GET_SIZE(subclasses);
5738 for (i = 0; i < n; i++) {
5739 ref = PyList_GET_ITEM(subclasses, i);
5740 assert(PyWeakref_CheckRef(ref));
5741 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5742 assert(subclass != NULL);
5743 if ((PyObject *)subclass == Py_None)
5744 continue;
5745 assert(PyType_Check(subclass));
5746 /* Avoid recursing down into unaffected classes */
5747 dict = subclass->tp_dict;
5748 if (dict != NULL && PyDict_Check(dict) &&
5749 PyDict_GetItem(dict, name) != NULL)
5750 continue;
5751 if (update_subclasses(subclass, name, callback, data) < 0)
5752 return -1;
5753 }
5754 return 0;
5755}
5756
Guido van Rossum6d204072001-10-21 00:44:31 +00005757/* This function is called by PyType_Ready() to populate the type's
5758 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005759 function slot (like tp_repr) that's defined in the type, one or more
5760 corresponding descriptors are added in the type's tp_dict dictionary
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005761 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005762 cause more than one descriptor to be added (for example, the nb_add
5763 slot adds both __add__ and __radd__ descriptors) and some function
5764 slots compete for the same descriptor (for example both sq_item and
5765 mp_subscript generate a __getitem__ descriptor).
5766
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005767 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005768 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005769 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005770 between competing slots: the members of PyHeapTypeObject are listed
5771 from most general to least general, so the most general slot is
5772 preferred. In particular, because as_mapping comes before as_sequence,
5773 for a type that defines both mp_subscript and sq_item, mp_subscript
5774 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005775
5776 This only adds new descriptors and doesn't overwrite entries in
5777 tp_dict that were previously defined. The descriptors contain a
5778 reference to the C function they must call, so that it's safe if they
5779 are copied into a subtype's __dict__ and the subtype has a different
5780 C function in its slot -- calling the method defined by the
5781 descriptor will call the C function that was used to create it,
5782 rather than the C function present in the slot when it is called.
5783 (This is important because a subtype may have a C function in the
5784 slot that calls the method from the dictionary, and we want to avoid
5785 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005786
5787static int
5788add_operators(PyTypeObject *type)
5789{
5790 PyObject *dict = type->tp_dict;
5791 slotdef *p;
5792 PyObject *descr;
5793 void **ptr;
5794
5795 init_slotdefs();
5796 for (p = slotdefs; p->name; p++) {
5797 if (p->wrapper == NULL)
5798 continue;
5799 ptr = slotptr(type, p->offset);
5800 if (!ptr || !*ptr)
5801 continue;
5802 if (PyDict_GetItem(dict, p->name_strobj))
5803 continue;
5804 descr = PyDescr_NewWrapper(type, p, *ptr);
5805 if (descr == NULL)
5806 return -1;
5807 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5808 return -1;
5809 Py_DECREF(descr);
5810 }
5811 if (type->tp_new != NULL) {
5812 if (add_tp_new_wrapper(type) < 0)
5813 return -1;
5814 }
5815 return 0;
5816}
5817
Guido van Rossum705f0f52001-08-24 16:47:00 +00005818
5819/* Cooperative 'super' */
5820
5821typedef struct {
5822 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005823 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005824 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005825 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005826} superobject;
5827
Guido van Rossum6f799372001-09-20 20:46:19 +00005828static PyMemberDef super_members[] = {
5829 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5830 "the class invoking super()"},
5831 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5832 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005833 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005834 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005835 {0}
5836};
5837
Guido van Rossum705f0f52001-08-24 16:47:00 +00005838static void
5839super_dealloc(PyObject *self)
5840{
5841 superobject *su = (superobject *)self;
5842
Guido van Rossum048eb752001-10-02 21:24:57 +00005843 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005844 Py_XDECREF(su->obj);
5845 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005846 Py_XDECREF(su->obj_type);
Martin v. Löwis68192102007-07-21 06:55:02 +00005847 Py_Type(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005848}
5849
5850static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005851super_repr(PyObject *self)
5852{
5853 superobject *su = (superobject *)self;
5854
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005855 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005856 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005857 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005858 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005859 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005860 else
5861 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005862 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005863 su->type ? su->type->tp_name : "NULL");
5864}
5865
5866static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005867super_getattro(PyObject *self, PyObject *name)
5868{
5869 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005870 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005871
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005872 if (!skip) {
5873 /* We want __class__ to return the class of the super object
5874 (i.e. super, or a subclass), not the class of su->obj. */
5875 skip = (PyString_Check(name) &&
5876 PyString_GET_SIZE(name) == 9 &&
5877 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5878 }
5879
5880 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005881 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005882 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005883 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005884 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005885
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005886 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005887 mro = starttype->tp_mro;
5888
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005889 if (mro == NULL)
5890 n = 0;
5891 else {
5892 assert(PyTuple_Check(mro));
5893 n = PyTuple_GET_SIZE(mro);
5894 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005895 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005896 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005897 break;
5898 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005899 i++;
5900 res = NULL;
5901 for (; i < n; i++) {
5902 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005903 if (PyType_Check(tmp))
5904 dict = ((PyTypeObject *)tmp)->tp_dict;
5905 else if (PyClass_Check(tmp))
5906 dict = ((PyClassObject *)tmp)->cl_dict;
5907 else
5908 continue;
5909 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005910 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005911 Py_INCREF(res);
Martin v. Löwis68192102007-07-21 06:55:02 +00005912 f = Py_Type(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005913 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005914 tmp = f(res,
5915 /* Only pass 'obj' param if
5916 this is instance-mode super
5917 (See SF ID #743627)
5918 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005919 (su->obj == (PyObject *)
5920 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005921 ? (PyObject *)NULL
5922 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005923 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005924 Py_DECREF(res);
5925 res = tmp;
5926 }
5927 return res;
5928 }
5929 }
5930 }
5931 return PyObject_GenericGetAttr(self, name);
5932}
5933
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005934static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005935supercheck(PyTypeObject *type, PyObject *obj)
5936{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005937 /* Check that a super() call makes sense. Return a type object.
5938
5939 obj can be a new-style class, or an instance of one:
5940
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005941 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005942 used for class methods; the return value is obj.
5943
5944 - If it is an instance, it must be an instance of 'type'. This is
5945 the normal case; the return value is obj.__class__.
5946
5947 But... when obj is an instance, we want to allow for the case where
Martin v. Löwis68192102007-07-21 06:55:02 +00005948 Py_Type(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005949 This will allow using super() with a proxy for obj.
5950 */
5951
Guido van Rossum8e80a722003-02-18 19:22:22 +00005952 /* Check for first bullet above (special case) */
5953 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5954 Py_INCREF(obj);
5955 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005956 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005957
5958 /* Normal case */
Martin v. Löwis68192102007-07-21 06:55:02 +00005959 if (PyType_IsSubtype(Py_Type(obj), type)) {
5960 Py_INCREF(Py_Type(obj));
5961 return Py_Type(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005962 }
5963 else {
5964 /* Try the slow way */
5965 static PyObject *class_str = NULL;
5966 PyObject *class_attr;
5967
5968 if (class_str == NULL) {
5969 class_str = PyString_FromString("__class__");
5970 if (class_str == NULL)
5971 return NULL;
5972 }
5973
5974 class_attr = PyObject_GetAttr(obj, class_str);
5975
5976 if (class_attr != NULL &&
5977 PyType_Check(class_attr) &&
Martin v. Löwis68192102007-07-21 06:55:02 +00005978 (PyTypeObject *)class_attr != Py_Type(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005979 {
5980 int ok = PyType_IsSubtype(
5981 (PyTypeObject *)class_attr, type);
5982 if (ok)
5983 return (PyTypeObject *)class_attr;
5984 }
5985
5986 if (class_attr == NULL)
5987 PyErr_Clear();
5988 else
5989 Py_DECREF(class_attr);
5990 }
5991
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00005992 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005993 "super(type, obj): "
5994 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005995 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005996}
5997
Guido van Rossum705f0f52001-08-24 16:47:00 +00005998static PyObject *
5999super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
6000{
6001 superobject *su = (superobject *)self;
Anthony Baxtera6286212006-04-11 07:42:36 +00006002 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006003
6004 if (obj == NULL || obj == Py_None || su->obj != NULL) {
6005 /* Not binding to an object, or already bound */
6006 Py_INCREF(self);
6007 return self;
6008 }
Martin v. Löwis68192102007-07-21 06:55:02 +00006009 if (Py_Type(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00006010 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006011 call its type */
Martin v. Löwis68192102007-07-21 06:55:02 +00006012 return PyObject_CallFunctionObjArgs((PyObject *)Py_Type(su),
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006013 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00006014 else {
6015 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006016 PyTypeObject *obj_type = supercheck(su->type, obj);
6017 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006018 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00006019 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00006020 NULL, NULL);
Anthony Baxtera6286212006-04-11 07:42:36 +00006021 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00006022 return NULL;
6023 Py_INCREF(su->type);
6024 Py_INCREF(obj);
Anthony Baxtera6286212006-04-11 07:42:36 +00006025 newobj->type = su->type;
6026 newobj->obj = obj;
6027 newobj->obj_type = obj_type;
6028 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00006029 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006030}
6031
6032static int
6033super_init(PyObject *self, PyObject *args, PyObject *kwds)
6034{
6035 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00006036 PyTypeObject *type;
6037 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006038 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006039
Georg Brandl5d59c092006-09-30 08:43:30 +00006040 if (!_PyArg_NoKeywords("super", kwds))
6041 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006042 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
6043 return -1;
6044 if (obj == Py_None)
6045 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006046 if (obj != NULL) {
6047 obj_type = supercheck(type, obj);
6048 if (obj_type == NULL)
6049 return -1;
6050 Py_INCREF(obj);
6051 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00006052 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00006053 su->type = type;
6054 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00006055 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00006056 return 0;
6057}
6058
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006059PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00006060"super(type) -> unbound super object\n"
6061"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00006062"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00006063"Typical use to call a cooperative superclass method:\n"
6064"class C(B):\n"
6065" def meth(self, arg):\n"
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006066" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00006067
Guido van Rossum048eb752001-10-02 21:24:57 +00006068static int
6069super_traverse(PyObject *self, visitproc visit, void *arg)
6070{
6071 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00006072
Thomas Woutersc6e55062006-04-15 21:47:09 +00006073 Py_VISIT(su->obj);
6074 Py_VISIT(su->type);
6075 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00006076
6077 return 0;
6078}
6079
Guido van Rossum705f0f52001-08-24 16:47:00 +00006080PyTypeObject PySuper_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00006081 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00006082 "super", /* tp_name */
6083 sizeof(superobject), /* tp_basicsize */
6084 0, /* tp_itemsize */
6085 /* methods */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006086 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006087 0, /* tp_print */
6088 0, /* tp_getattr */
6089 0, /* tp_setattr */
6090 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006091 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006092 0, /* tp_as_number */
6093 0, /* tp_as_sequence */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006094 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006095 0, /* tp_hash */
6096 0, /* tp_call */
6097 0, /* tp_str */
6098 super_getattro, /* tp_getattro */
6099 0, /* tp_setattro */
6100 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006101 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6102 Py_TPFLAGS_BASETYPE, /* tp_flags */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006103 super_doc, /* tp_doc */
6104 super_traverse, /* tp_traverse */
6105 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006106 0, /* tp_richcompare */
6107 0, /* tp_weaklistoffset */
6108 0, /* tp_iter */
6109 0, /* tp_iternext */
6110 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006111 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006112 0, /* tp_getset */
6113 0, /* tp_base */
6114 0, /* tp_dict */
6115 super_descr_get, /* tp_descr_get */
6116 0, /* tp_descr_set */
6117 0, /* tp_dictoffset */
6118 super_init, /* tp_init */
6119 PyType_GenericAlloc, /* tp_alloc */
6120 PyType_GenericNew, /* tp_new */
Jeremy Hylton2d1f5c92007-02-27 17:24:48 +00006121 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006122};