blob: 4cfbd49fc4d07b7dc9911d6de9718350c4e3af16 [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
8/* The *real* layout of a type object when allocated on the heap */
9/* XXX Should we publish this in a header file? */
10typedef struct {
Guido van Rossum09638c12002-06-13 19:17:46 +000011 /* Note: there's a dependency on the order of these members
12 in slotptr() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000013 PyTypeObject type;
14 PyNumberMethods as_number;
Guido van Rossum9923ffe2002-06-04 19:52:53 +000015 PyMappingMethods as_mapping;
Guido van Rossum09638c12002-06-13 19:17:46 +000016 PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
17 so that the mapping wins when both
18 the mapping and the sequence define
19 a given operator (e.g. __getitem__).
20 see add_operators() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000021 PyBufferProcs as_buffer;
22 PyObject *name, *slots;
23 PyMemberDef members[1];
24} etype;
25
Guido van Rossum6f799372001-09-20 20:46:19 +000026static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000027 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
28 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
29 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000030 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000031 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
32 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
33 {"__dictoffset__", T_LONG,
34 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000035 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
36 {0}
37};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000038
Guido van Rossumc0b618a1997-05-02 03:12:38 +000039static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000040type_name(PyTypeObject *type, void *context)
41{
42 char *s;
43
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000044 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
45 etype* et = (etype*)type;
46
47 Py_INCREF(et->name);
48 return et->name;
49 }
50 else {
51 s = strrchr(type->tp_name, '.');
52 if (s == NULL)
53 s = type->tp_name;
54 else
55 s++;
56 return PyString_FromString(s);
57 }
Guido van Rossumc3542212001-08-16 09:18:56 +000058}
59
Michael W. Hudson98bbc492002-11-26 14:47:27 +000060static int
61type_set_name(PyTypeObject *type, PyObject *value, void *context)
62{
63 etype* et;
64
65 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
66 PyErr_Format(PyExc_TypeError,
67 "can't set %s.__name__", type->tp_name);
68 return -1;
69 }
70 if (!value) {
71 PyErr_Format(PyExc_TypeError,
72 "can't delete %s.__name__", type->tp_name);
73 return -1;
74 }
75 if (!PyString_Check(value)) {
76 PyErr_Format(PyExc_TypeError,
77 "can only assign string to %s.__name__, not '%s'",
78 type->tp_name, value->ob_type->tp_name);
79 return -1;
80 }
81 if (strlen(PyString_AS_STRING(value))
82 != (size_t)PyString_GET_SIZE(value)) {
83 PyErr_Format(PyExc_ValueError,
84 "__name__ must not contain null bytes");
85 return -1;
86 }
87
88 et = (etype*)type;
89
90 Py_INCREF(value);
91
92 Py_DECREF(et->name);
93 et->name = value;
94
95 type->tp_name = PyString_AS_STRING(value);
96
97 return 0;
98}
99
Guido van Rossumc3542212001-08-16 09:18:56 +0000100static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000101type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000102{
Guido van Rossumc3542212001-08-16 09:18:56 +0000103 PyObject *mod;
104 char *s;
105
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000106 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
107 mod = PyDict_GetItemString(type->tp_dict, "__module__");
108 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000109 return mod;
110 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000111 else {
112 s = strrchr(type->tp_name, '.');
113 if (s != NULL)
114 return PyString_FromStringAndSize(
115 type->tp_name, (int)(s - type->tp_name));
116 return PyString_FromString("__builtin__");
117 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000118}
119
Guido van Rossum3926a632001-09-25 16:25:58 +0000120static int
121type_set_module(PyTypeObject *type, PyObject *value, void *context)
122{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000123 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000124 PyErr_Format(PyExc_TypeError,
125 "can't set %s.__module__", type->tp_name);
126 return -1;
127 }
128 if (!value) {
129 PyErr_Format(PyExc_TypeError,
130 "can't delete %s.__module__", type->tp_name);
131 return -1;
132 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000133
Guido van Rossum3926a632001-09-25 16:25:58 +0000134 return PyDict_SetItemString(type->tp_dict, "__module__", value);
135}
136
Tim Peters6d6c1a32001-08-02 04:15:00 +0000137static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000138type_get_bases(PyTypeObject *type, void *context)
139{
140 Py_INCREF(type->tp_bases);
141 return type->tp_bases;
142}
143
144static PyTypeObject *best_base(PyObject *);
145static int mro_internal(PyTypeObject *);
146static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
147static int add_subclass(PyTypeObject*, PyTypeObject*);
148static void remove_subclass(PyTypeObject *, PyTypeObject *);
149static void update_all_slots(PyTypeObject *);
150
151static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000152mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000153{
154 PyTypeObject *subclass;
155 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000156 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000157
158 subclasses = type->tp_subclasses;
159 if (subclasses == NULL)
160 return 0;
161 assert(PyList_Check(subclasses));
162 n = PyList_GET_SIZE(subclasses);
163 for (i = 0; i < n; i++) {
164 ref = PyList_GET_ITEM(subclasses, i);
165 assert(PyWeakref_CheckRef(ref));
166 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
167 assert(subclass != NULL);
168 if ((PyObject *)subclass == Py_None)
169 continue;
170 assert(PyType_Check(subclass));
171 old_mro = subclass->tp_mro;
172 if (mro_internal(subclass) < 0) {
173 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000174 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000175 }
176 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000177 PyObject* tuple;
178 tuple = Py_BuildValue("OO", subclass, old_mro);
179 if (!tuple)
180 return -1;
181 if (PyList_Append(temp, tuple) < 0)
182 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000183 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000184 if (mro_subclasses(subclass, temp) < 0)
185 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000186 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000187 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000188}
189
190static int
191type_set_bases(PyTypeObject *type, PyObject *value, void *context)
192{
193 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000194 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000195 PyTypeObject *new_base, *old_base;
196 PyObject *old_bases, *old_mro;
197
198 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
199 PyErr_Format(PyExc_TypeError,
200 "can't set %s.__bases__", type->tp_name);
201 return -1;
202 }
203 if (!value) {
204 PyErr_Format(PyExc_TypeError,
205 "can't delete %s.__bases__", type->tp_name);
206 return -1;
207 }
208 if (!PyTuple_Check(value)) {
209 PyErr_Format(PyExc_TypeError,
210 "can only assign tuple to %s.__bases__, not %s",
211 type->tp_name, value->ob_type->tp_name);
212 return -1;
213 }
214 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
215 ob = PyTuple_GET_ITEM(value, i);
216 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
217 PyErr_Format(
218 PyExc_TypeError,
219 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
220 type->tp_name, ob->ob_type->tp_name);
221 return -1;
222 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000223 if (PyType_Check(ob)) {
224 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
225 PyErr_SetString(PyExc_TypeError,
226 "a __bases__ item causes an inheritance cycle");
227 return -1;
228 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000229 }
230 }
231
232 new_base = best_base(value);
233
234 if (!new_base) {
235 return -1;
236 }
237
238 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
239 return -1;
240
241 Py_INCREF(new_base);
242 Py_INCREF(value);
243
244 old_bases = type->tp_bases;
245 old_base = type->tp_base;
246 old_mro = type->tp_mro;
247
248 type->tp_bases = value;
249 type->tp_base = new_base;
250
251 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000252 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000253 }
254
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000255 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000256 if (!temp)
257 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000258
259 r = mro_subclasses(type, temp);
260
261 if (r < 0) {
262 for (i = 0; i < PyList_Size(temp); i++) {
263 PyTypeObject* cls;
264 PyObject* mro;
265 PyArg_ParseTuple(PyList_GetItem(temp, i),
266 "OO", &cls, &mro);
267 Py_DECREF(cls->tp_mro);
268 cls->tp_mro = mro;
269 Py_INCREF(cls->tp_mro);
270 }
271 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000272 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000273 }
274
275 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000276
277 /* any base that was in __bases__ but now isn't, we
278 need to remove |type| from it's tp_subclasses.
279 conversely, any class now in __bases__ that wasn't
280 needs to have |type| added to it's subclasses. */
281
282 /* for now, sod that: just remove from all old_bases,
283 add to all new_bases */
284
285 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
286 ob = PyTuple_GET_ITEM(old_bases, i);
287 if (PyType_Check(ob)) {
288 remove_subclass(
289 (PyTypeObject*)ob, type);
290 }
291 }
292
293 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
294 ob = PyTuple_GET_ITEM(value, i);
295 if (PyType_Check(ob)) {
296 if (add_subclass((PyTypeObject*)ob, type) < 0)
297 r = -1;
298 }
299 }
300
301 update_all_slots(type);
302
303 Py_DECREF(old_bases);
304 Py_DECREF(old_base);
305 Py_DECREF(old_mro);
306
307 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000308
309 bail:
310 type->tp_bases = old_bases;
311 type->tp_base = old_base;
312 type->tp_mro = old_mro;
313
314 Py_DECREF(value);
315 Py_DECREF(new_base);
316
317 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000318}
319
320static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000321type_dict(PyTypeObject *type, void *context)
322{
323 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000324 Py_INCREF(Py_None);
325 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000326 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000327 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000328}
329
Tim Peters24008312002-03-17 18:56:20 +0000330static PyObject *
331type_get_doc(PyTypeObject *type, void *context)
332{
333 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000334 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000335 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000336 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000337 if (result == NULL) {
338 result = Py_None;
339 Py_INCREF(result);
340 }
341 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000342 result = result->ob_type->tp_descr_get(result, NULL,
343 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000344 }
345 else {
346 Py_INCREF(result);
347 }
Tim Peters24008312002-03-17 18:56:20 +0000348 return result;
349}
350
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000351static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000352 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
353 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000354 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000355 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000356 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000357 {0}
358};
359
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000360static int
361type_compare(PyObject *v, PyObject *w)
362{
363 /* This is called with type objects only. So we
364 can just compare the addresses. */
365 Py_uintptr_t vv = (Py_uintptr_t)v;
366 Py_uintptr_t ww = (Py_uintptr_t)w;
367 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
368}
369
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000371type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000372{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000373 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000374 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000375
376 mod = type_module(type, NULL);
377 if (mod == NULL)
378 PyErr_Clear();
379 else if (!PyString_Check(mod)) {
380 Py_DECREF(mod);
381 mod = NULL;
382 }
383 name = type_name(type, NULL);
384 if (name == NULL)
385 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000386
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000387 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
388 kind = "class";
389 else
390 kind = "type";
391
Barry Warsaw7ce36942001-08-24 18:34:26 +0000392 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000393 rtn = PyString_FromFormat("<%s '%s.%s'>",
394 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000395 PyString_AS_STRING(mod),
396 PyString_AS_STRING(name));
397 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000398 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000399 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000400
Guido van Rossumc3542212001-08-16 09:18:56 +0000401 Py_XDECREF(mod);
402 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000403 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404}
405
Tim Peters6d6c1a32001-08-02 04:15:00 +0000406static PyObject *
407type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
408{
409 PyObject *obj;
410
411 if (type->tp_new == NULL) {
412 PyErr_Format(PyExc_TypeError,
413 "cannot create '%.100s' instances",
414 type->tp_name);
415 return NULL;
416 }
417
Tim Peters3f996e72001-09-13 19:18:27 +0000418 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000419 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000420 /* Ugly exception: when the call was type(something),
421 don't call tp_init on the result. */
422 if (type == &PyType_Type &&
423 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
424 (kwds == NULL ||
425 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
426 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000427 /* If the returned object is not an instance of type,
428 it won't be initialized. */
429 if (!PyType_IsSubtype(obj->ob_type, type))
430 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000431 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000432 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
433 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000434 type->tp_init(obj, args, kwds) < 0) {
435 Py_DECREF(obj);
436 obj = NULL;
437 }
438 }
439 return obj;
440}
441
442PyObject *
443PyType_GenericAlloc(PyTypeObject *type, int nitems)
444{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000445 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000446 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447
448 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000449 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000450 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000451 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Neil Schemenauerc806c882001-08-29 23:54:54 +0000453 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000454 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000455
Neil Schemenauerc806c882001-08-29 23:54:54 +0000456 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
459 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 if (type->tp_itemsize == 0)
462 PyObject_INIT(obj, type);
463 else
464 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000465
Tim Peters6d6c1a32001-08-02 04:15:00 +0000466 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000467 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000468 return obj;
469}
470
471PyObject *
472PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
473{
474 return type->tp_alloc(type, 0);
475}
476
Guido van Rossum9475a232001-10-05 20:51:39 +0000477/* Helpers for subtyping */
478
479static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000480traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
481{
482 int i, n;
483 PyMemberDef *mp;
484
485 n = type->ob_size;
486 mp = ((etype *)type)->members;
487 for (i = 0; i < n; i++, mp++) {
488 if (mp->type == T_OBJECT_EX) {
489 char *addr = (char *)self + mp->offset;
490 PyObject *obj = *(PyObject **)addr;
491 if (obj != NULL) {
492 int err = visit(obj, arg);
493 if (err)
494 return err;
495 }
496 }
497 }
498 return 0;
499}
500
501static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000502subtype_traverse(PyObject *self, visitproc visit, void *arg)
503{
504 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000505 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000506
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000507 /* Find the nearest base with a different tp_traverse,
508 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000509 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000510 base = type;
511 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
512 if (base->ob_size) {
513 int err = traverse_slots(base, self, visit, arg);
514 if (err)
515 return err;
516 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000517 base = base->tp_base;
518 assert(base);
519 }
520
521 if (type->tp_dictoffset != base->tp_dictoffset) {
522 PyObject **dictptr = _PyObject_GetDictPtr(self);
523 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000524 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000525 if (err)
526 return err;
527 }
528 }
529
Guido van Rossuma3862092002-06-10 15:24:42 +0000530 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
531 /* For a heaptype, the instances count as references
532 to the type. Traverse the type so the collector
533 can find cycles involving this link. */
534 int err = visit((PyObject *)type, arg);
535 if (err)
536 return err;
537 }
538
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{
547 int i, n;
548 PyMemberDef *mp;
549
550 n = type->ob_size;
551 mp = ((etype *)type)->members;
552 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) {
557 Py_DECREF(obj);
558 *(PyObject **)addr = NULL;
559 }
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 */
572 type = self->ob_type;
573 base = type;
574 while ((baseclear = base->tp_clear) == subtype_clear) {
575 if (base->ob_size)
576 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 */
596 type = self->ob_type;
597 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) {
618 assert(base->ob_size == 0);
619 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 */
Guido van Rossum0906e072002-08-07 20:42:09 +0000637 PyObject_GC_UnTrack(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000638 Py_TRASHCAN_SAFE_BEGIN(self);
639 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
640
641 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000642 if (type->tp_del) {
643 type->tp_del(self);
644 if (self->ob_refcnt > 0)
645 goto endlabel;
646 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000647
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000648 /* Find the nearest base with a different tp_dealloc
649 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000650 base = type;
651 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
652 if (base->ob_size)
653 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000654 base = base->tp_base;
655 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000656 }
657
Tim Peters6d6c1a32001-08-02 04:15:00 +0000658 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000659 if (type->tp_dictoffset && !base->tp_dictoffset) {
660 PyObject **dictptr = _PyObject_GetDictPtr(self);
661 if (dictptr != NULL) {
662 PyObject *dict = *dictptr;
663 if (dict != NULL) {
664 Py_DECREF(dict);
665 *dictptr = NULL;
666 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000667 }
668 }
669
Guido van Rossum9676b222001-08-17 20:32:36 +0000670 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000671 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000672 PyObject_ClearWeakRefs(self);
673
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000675 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000676 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677
678 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000679 assert(basedealloc);
680 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000681
682 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000683 Py_DECREF(type);
684
Guido van Rossum0906e072002-08-07 20:42:09 +0000685 endlabel:
Guido van Rossum22b13872002-08-06 21:41:44 +0000686 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000687}
688
Jeremy Hylton938ace62002-07-17 16:30:39 +0000689static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000690
Tim Peters6d6c1a32001-08-02 04:15:00 +0000691/* type test with subclassing support */
692
693int
694PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
695{
696 PyObject *mro;
697
Guido van Rossum9478d072001-09-07 18:52:13 +0000698 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
699 return b == a || b == &PyBaseObject_Type;
700
Tim Peters6d6c1a32001-08-02 04:15:00 +0000701 mro = a->tp_mro;
702 if (mro != NULL) {
703 /* Deal with multiple inheritance without recursion
704 by walking the MRO tuple */
705 int i, n;
706 assert(PyTuple_Check(mro));
707 n = PyTuple_GET_SIZE(mro);
708 for (i = 0; i < n; i++) {
709 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
710 return 1;
711 }
712 return 0;
713 }
714 else {
715 /* a is not completely initilized yet; follow tp_base */
716 do {
717 if (a == b)
718 return 1;
719 a = a->tp_base;
720 } while (a != NULL);
721 return b == &PyBaseObject_Type;
722 }
723}
724
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000725/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000726 without looking in the instance dictionary
727 (so we can't use PyObject_GetAttr) but still binding
728 it to the instance. The arguments are the object,
729 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000730 static variable used to cache the interned Python string.
731
732 Two variants:
733
734 - lookup_maybe() returns NULL without raising an exception
735 when the _PyType_Lookup() call fails;
736
737 - lookup_method() always raises an exception upon errors.
738*/
Guido van Rossum60718732001-08-28 17:47:51 +0000739
740static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000741lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000742{
743 PyObject *res;
744
745 if (*attrobj == NULL) {
746 *attrobj = PyString_InternFromString(attrstr);
747 if (*attrobj == NULL)
748 return NULL;
749 }
750 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000751 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000752 descrgetfunc f;
753 if ((f = res->ob_type->tp_descr_get) == NULL)
754 Py_INCREF(res);
755 else
756 res = f(res, self, (PyObject *)(self->ob_type));
757 }
758 return res;
759}
760
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000761static PyObject *
762lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
763{
764 PyObject *res = lookup_maybe(self, attrstr, attrobj);
765 if (res == NULL && !PyErr_Occurred())
766 PyErr_SetObject(PyExc_AttributeError, *attrobj);
767 return res;
768}
769
Guido van Rossum2730b132001-08-28 18:22:14 +0000770/* A variation of PyObject_CallMethod that uses lookup_method()
771 instead of PyObject_GetAttrString(). This uses the same convention
772 as lookup_method to cache the interned name string object. */
773
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000774static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000775call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
776{
777 va_list va;
778 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000779 va_start(va, format);
780
Guido van Rossumda21c012001-10-03 00:50:18 +0000781 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000782 if (func == NULL) {
783 va_end(va);
784 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000785 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000786 return NULL;
787 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000788
789 if (format && *format)
790 args = Py_VaBuildValue(format, va);
791 else
792 args = PyTuple_New(0);
793
794 va_end(va);
795
796 if (args == NULL)
797 return NULL;
798
799 assert(PyTuple_Check(args));
800 retval = PyObject_Call(func, args, NULL);
801
802 Py_DECREF(args);
803 Py_DECREF(func);
804
805 return retval;
806}
807
808/* Clone of call_method() that returns NotImplemented when the lookup fails. */
809
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000810static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000811call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
812{
813 va_list va;
814 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000815 va_start(va, format);
816
Guido van Rossumda21c012001-10-03 00:50:18 +0000817 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000818 if (func == NULL) {
819 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000820 if (!PyErr_Occurred()) {
821 Py_INCREF(Py_NotImplemented);
822 return Py_NotImplemented;
823 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000824 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000825 }
826
827 if (format && *format)
828 args = Py_VaBuildValue(format, va);
829 else
830 args = PyTuple_New(0);
831
832 va_end(va);
833
Guido van Rossum717ce002001-09-14 16:58:08 +0000834 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000835 return NULL;
836
Guido van Rossum717ce002001-09-14 16:58:08 +0000837 assert(PyTuple_Check(args));
838 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000839
840 Py_DECREF(args);
841 Py_DECREF(func);
842
843 return retval;
844}
845
Tim Petersa91e9642001-11-14 23:32:33 +0000846static int
847fill_classic_mro(PyObject *mro, PyObject *cls)
848{
849 PyObject *bases, *base;
850 int i, n;
851
852 assert(PyList_Check(mro));
853 assert(PyClass_Check(cls));
854 i = PySequence_Contains(mro, cls);
855 if (i < 0)
856 return -1;
857 if (!i) {
858 if (PyList_Append(mro, cls) < 0)
859 return -1;
860 }
861 bases = ((PyClassObject *)cls)->cl_bases;
862 assert(bases && PyTuple_Check(bases));
863 n = PyTuple_GET_SIZE(bases);
864 for (i = 0; i < n; i++) {
865 base = PyTuple_GET_ITEM(bases, i);
866 if (fill_classic_mro(mro, base) < 0)
867 return -1;
868 }
869 return 0;
870}
871
872static PyObject *
873classic_mro(PyObject *cls)
874{
875 PyObject *mro;
876
877 assert(PyClass_Check(cls));
878 mro = PyList_New(0);
879 if (mro != NULL) {
880 if (fill_classic_mro(mro, cls) == 0)
881 return mro;
882 Py_DECREF(mro);
883 }
884 return NULL;
885}
886
Guido van Rossum1f121312002-11-14 19:49:16 +0000887/*
888 Method resolution order algorithm C3 described in
889 "A Monotonic Superclass Linearization for Dylan",
890 by Kim Barrett, Bob Cassel, Paul Haahr,
891 David A. Moon, Keith Playford, and P. Tucker Withington.
892 (OOPSLA 1996)
893
Guido van Rossum98f33732002-11-25 21:36:54 +0000894 Some notes about the rules implied by C3:
895
896 No duplicate bases.
897 It isn't legal to repeat a class in a list of base classes.
898
899 The next three properties are the 3 constraints in "C3".
900
901 Local precendece order.
902 If A precedes B in C's MRO, then A will precede B in the MRO of all
903 subclasses of C.
904
905 Monotonicity.
906 The MRO of a class must be an extension without reordering of the
907 MRO of each of its superclasses.
908
909 Extended Precedence Graph (EPG).
910 Linearization is consistent if there is a path in the EPG from
911 each class to all its successors in the linearization. See
912 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000913 */
914
915static int
916tail_contains(PyObject *list, int whence, PyObject *o) {
917 int j, size;
918 size = PyList_GET_SIZE(list);
919
920 for (j = whence+1; j < size; j++) {
921 if (PyList_GET_ITEM(list, j) == o)
922 return 1;
923 }
924 return 0;
925}
926
Guido van Rossum98f33732002-11-25 21:36:54 +0000927static PyObject *
928class_name(PyObject *cls)
929{
930 PyObject *name = PyObject_GetAttrString(cls, "__name__");
931 if (name == NULL) {
932 PyErr_Clear();
933 Py_XDECREF(name);
934 name = PyObject_Repr(cls);
935 }
936 if (name == NULL)
937 return NULL;
938 if (!PyString_Check(name)) {
939 Py_DECREF(name);
940 return NULL;
941 }
942 return name;
943}
944
945static int
946check_duplicates(PyObject *list)
947{
948 int i, j, n;
949 /* Let's use a quadratic time algorithm,
950 assuming that the bases lists is short.
951 */
952 n = PyList_GET_SIZE(list);
953 for (i = 0; i < n; i++) {
954 PyObject *o = PyList_GET_ITEM(list, i);
955 for (j = i + 1; j < n; j++) {
956 if (PyList_GET_ITEM(list, j) == o) {
957 o = class_name(o);
958 PyErr_Format(PyExc_TypeError,
959 "duplicate base class %s",
960 o ? PyString_AS_STRING(o) : "?");
961 Py_XDECREF(o);
962 return -1;
963 }
964 }
965 }
966 return 0;
967}
968
969/* Raise a TypeError for an MRO order disagreement.
970
971 It's hard to produce a good error message. In the absence of better
972 insight into error reporting, report the classes that were candidates
973 to be put next into the MRO. There is some conflict between the
974 order in which they should be put in the MRO, but it's hard to
975 diagnose what constraint can't be satisfied.
976*/
977
978static void
979set_mro_error(PyObject *to_merge, int *remain)
980{
981 int i, n, off, to_merge_size;
982 char buf[1000];
983 PyObject *k, *v;
984 PyObject *set = PyDict_New();
985
986 to_merge_size = PyList_GET_SIZE(to_merge);
987 for (i = 0; i < to_merge_size; i++) {
988 PyObject *L = PyList_GET_ITEM(to_merge, i);
989 if (remain[i] < PyList_GET_SIZE(L)) {
990 PyObject *c = PyList_GET_ITEM(L, remain[i]);
991 if (PyDict_SetItem(set, c, Py_None) < 0)
992 return;
993 }
994 }
995 n = PyDict_Size(set);
996
997 off = PyOS_snprintf(buf, sizeof(buf), "MRO conflict among bases");
998 i = 0;
999 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1000 PyObject *name = class_name(k);
1001 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1002 name ? PyString_AS_STRING(name) : "?");
1003 Py_XDECREF(name);
1004 if (--n && off+1 < sizeof(buf)) {
1005 buf[off++] = ',';
1006 buf[off] = '\0';
1007 }
1008 }
1009 PyErr_SetString(PyExc_TypeError, buf);
1010 Py_DECREF(set);
1011}
1012
Guido van Rossum1f121312002-11-14 19:49:16 +00001013static int
1014pmerge(PyObject *acc, PyObject* to_merge) {
1015 int i, j, to_merge_size;
1016 int *remain;
1017 int ok, empty_cnt;
1018
1019 to_merge_size = PyList_GET_SIZE(to_merge);
1020
Guido van Rossum98f33732002-11-25 21:36:54 +00001021 /* remain stores an index into each sublist of to_merge.
1022 remain[i] is the index of the next base in to_merge[i]
1023 that is not included in acc.
1024 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001025 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1026 if (remain == NULL)
1027 return -1;
1028 for (i = 0; i < to_merge_size; i++)
1029 remain[i] = 0;
1030
1031 again:
1032 empty_cnt = 0;
1033 for (i = 0; i < to_merge_size; i++) {
1034 PyObject *candidate;
1035
1036 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1037
1038 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1039 empty_cnt++;
1040 continue;
1041 }
1042
Guido van Rossum98f33732002-11-25 21:36:54 +00001043 /* Choose next candidate for MRO.
1044
1045 The input sequences alone can determine the choice.
1046 If not, choose the class which appears in the MRO
1047 of the earliest direct superclass of the new class.
1048 */
1049
Guido van Rossum1f121312002-11-14 19:49:16 +00001050 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1051 for (j = 0; j < to_merge_size; j++) {
1052 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001053 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001054 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001055 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001056 }
1057 ok = PyList_Append(acc, candidate);
1058 if (ok < 0) {
1059 PyMem_Free(remain);
1060 return -1;
1061 }
1062 for (j = 0; j < to_merge_size; j++) {
1063 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1064 if (PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1065 remain[j]++;
1066 }
1067 }
1068 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001069 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001070 }
1071
Guido van Rossum98f33732002-11-25 21:36:54 +00001072 if (empty_cnt == to_merge_size) {
1073 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001074 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001075 }
1076 set_mro_error(to_merge, remain);
1077 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001078 return -1;
1079}
1080
Tim Peters6d6c1a32001-08-02 04:15:00 +00001081static PyObject *
1082mro_implementation(PyTypeObject *type)
1083{
1084 int i, n, ok;
1085 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001086 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087
Guido van Rossum63517572002-06-18 16:44:57 +00001088 if(type->tp_dict == NULL) {
1089 if(PyType_Ready(type) < 0)
1090 return NULL;
1091 }
1092
Guido van Rossum98f33732002-11-25 21:36:54 +00001093 /* Find a superclass linearization that honors the constraints
1094 of the explicit lists of bases and the constraints implied by
1095 each base class.
1096
1097 to_merge is a list of lists, where each list is a superclass
1098 linearization implied by a base class. The last element of
1099 to_merge is the declared list of bases.
1100 */
1101
Tim Peters6d6c1a32001-08-02 04:15:00 +00001102 bases = type->tp_bases;
1103 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001104
1105 to_merge = PyList_New(n+1);
1106 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001107 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001108
Tim Peters6d6c1a32001-08-02 04:15:00 +00001109 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001110 PyObject *base = PyTuple_GET_ITEM(bases, i);
1111 PyObject *parentMRO;
1112 if (PyType_Check(base))
1113 parentMRO = PySequence_List(
1114 ((PyTypeObject*)base)->tp_mro);
1115 else
1116 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001117 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001118 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001120 }
1121
1122 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001124
1125 bases_aslist = PySequence_List(bases);
1126 if (bases_aslist == NULL) {
1127 Py_DECREF(to_merge);
1128 return NULL;
1129 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001130 /* This is just a basic sanity check. */
1131 if (check_duplicates(bases_aslist) < 0) {
1132 Py_DECREF(to_merge);
1133 Py_DECREF(bases_aslist);
1134 return NULL;
1135 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001136 PyList_SET_ITEM(to_merge, n, bases_aslist);
1137
1138 result = Py_BuildValue("[O]", (PyObject *)type);
1139 if (result == NULL) {
1140 Py_DECREF(to_merge);
1141 return NULL;
1142 }
1143
1144 ok = pmerge(result, to_merge);
1145 Py_DECREF(to_merge);
1146 if (ok < 0) {
1147 Py_DECREF(result);
1148 return NULL;
1149 }
1150
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151 return result;
1152}
1153
1154static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001155mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001156{
1157 PyTypeObject *type = (PyTypeObject *)self;
1158
Tim Peters6d6c1a32001-08-02 04:15:00 +00001159 return mro_implementation(type);
1160}
1161
1162static int
1163mro_internal(PyTypeObject *type)
1164{
1165 PyObject *mro, *result, *tuple;
1166
1167 if (type->ob_type == &PyType_Type) {
1168 result = mro_implementation(type);
1169 }
1170 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001171 static PyObject *mro_str;
1172 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173 if (mro == NULL)
1174 return -1;
1175 result = PyObject_CallObject(mro, NULL);
1176 Py_DECREF(mro);
1177 }
1178 if (result == NULL)
1179 return -1;
1180 tuple = PySequence_Tuple(result);
1181 Py_DECREF(result);
1182 type->tp_mro = tuple;
1183 return 0;
1184}
1185
1186
1187/* Calculate the best base amongst multiple base classes.
1188 This is the first one that's on the path to the "solid base". */
1189
1190static PyTypeObject *
1191best_base(PyObject *bases)
1192{
1193 int i, n;
1194 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001195 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196
1197 assert(PyTuple_Check(bases));
1198 n = PyTuple_GET_SIZE(bases);
1199 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001200 base = NULL;
1201 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001203 base_proto = PyTuple_GET_ITEM(bases, i);
1204 if (PyClass_Check(base_proto))
1205 continue;
1206 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001207 PyErr_SetString(
1208 PyExc_TypeError,
1209 "bases must be types");
1210 return NULL;
1211 }
Tim Petersa91e9642001-11-14 23:32:33 +00001212 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001214 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215 return NULL;
1216 }
1217 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001218 if (winner == NULL) {
1219 winner = candidate;
1220 base = base_i;
1221 }
1222 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001223 ;
1224 else if (PyType_IsSubtype(candidate, winner)) {
1225 winner = candidate;
1226 base = base_i;
1227 }
1228 else {
1229 PyErr_SetString(
1230 PyExc_TypeError,
1231 "multiple bases have "
1232 "instance lay-out conflict");
1233 return NULL;
1234 }
1235 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001236 if (base == NULL)
1237 PyErr_SetString(PyExc_TypeError,
1238 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001239 return base;
1240}
1241
1242static int
1243extra_ivars(PyTypeObject *type, PyTypeObject *base)
1244{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001245 size_t t_size = type->tp_basicsize;
1246 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001247
Guido van Rossum9676b222001-08-17 20:32:36 +00001248 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249 if (type->tp_itemsize || base->tp_itemsize) {
1250 /* If itemsize is involved, stricter rules */
1251 return t_size != b_size ||
1252 type->tp_itemsize != base->tp_itemsize;
1253 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001254 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1255 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1256 t_size -= sizeof(PyObject *);
1257 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1258 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1259 t_size -= sizeof(PyObject *);
1260
1261 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001262}
1263
1264static PyTypeObject *
1265solid_base(PyTypeObject *type)
1266{
1267 PyTypeObject *base;
1268
1269 if (type->tp_base)
1270 base = solid_base(type->tp_base);
1271 else
1272 base = &PyBaseObject_Type;
1273 if (extra_ivars(type, base))
1274 return type;
1275 else
1276 return base;
1277}
1278
Jeremy Hylton938ace62002-07-17 16:30:39 +00001279static void object_dealloc(PyObject *);
1280static int object_init(PyObject *, PyObject *, PyObject *);
1281static int update_slot(PyTypeObject *, PyObject *);
1282static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001283
1284static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001285subtype_dict(PyObject *obj, void *context)
1286{
1287 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1288 PyObject *dict;
1289
1290 if (dictptr == NULL) {
1291 PyErr_SetString(PyExc_AttributeError,
1292 "This object has no __dict__");
1293 return NULL;
1294 }
1295 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001296 if (dict == NULL)
1297 *dictptr = dict = PyDict_New();
1298 Py_XINCREF(dict);
1299 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001300}
1301
Guido van Rossum6661be32001-10-26 04:26:12 +00001302static int
1303subtype_setdict(PyObject *obj, PyObject *value, void *context)
1304{
1305 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1306 PyObject *dict;
1307
1308 if (dictptr == NULL) {
1309 PyErr_SetString(PyExc_AttributeError,
1310 "This object has no __dict__");
1311 return -1;
1312 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001313 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001314 PyErr_SetString(PyExc_TypeError,
1315 "__dict__ must be set to a dictionary");
1316 return -1;
1317 }
1318 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001319 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001320 *dictptr = value;
1321 Py_XDECREF(dict);
1322 return 0;
1323}
1324
Guido van Rossumad47da02002-08-12 19:05:44 +00001325static PyObject *
1326subtype_getweakref(PyObject *obj, void *context)
1327{
1328 PyObject **weaklistptr;
1329 PyObject *result;
1330
1331 if (obj->ob_type->tp_weaklistoffset == 0) {
1332 PyErr_SetString(PyExc_AttributeError,
1333 "This object has no __weaklist__");
1334 return NULL;
1335 }
1336 assert(obj->ob_type->tp_weaklistoffset > 0);
1337 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001338 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001339 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001340 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001341 if (*weaklistptr == NULL)
1342 result = Py_None;
1343 else
1344 result = *weaklistptr;
1345 Py_INCREF(result);
1346 return result;
1347}
1348
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001349static PyGetSetDef subtype_getsets[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001350 /* Not all objects have these attributes!
1351 The descriptor's __get__ method may raise AttributeError. */
1352 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001353 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001354 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001355 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001356 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001357};
1358
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001359/* bozo: __getstate__ that raises TypeError */
1360
1361static PyObject *
1362bozo_func(PyObject *self, PyObject *args)
1363{
1364 PyErr_SetString(PyExc_TypeError,
1365 "a class that defines __slots__ without "
1366 "defining __getstate__ cannot be pickled");
1367 return NULL;
1368}
1369
Neal Norwitz93c1e232002-03-31 16:06:11 +00001370static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001371
1372static PyObject *bozo_obj = NULL;
1373
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001374static int
1375valid_identifier(PyObject *s)
1376{
Guido van Rossum03013a02002-07-16 14:30:28 +00001377 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001378 int i, n;
1379
1380 if (!PyString_Check(s)) {
1381 PyErr_SetString(PyExc_TypeError,
1382 "__slots__ must be strings");
1383 return 0;
1384 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001385 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001386 n = PyString_GET_SIZE(s);
1387 /* We must reject an empty name. As a hack, we bump the
1388 length to 1 so that the loop will balk on the trailing \0. */
1389 if (n == 0)
1390 n = 1;
1391 for (i = 0; i < n; i++, p++) {
1392 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1393 PyErr_SetString(PyExc_TypeError,
1394 "__slots__ must be identifiers");
1395 return 0;
1396 }
1397 }
1398 return 1;
1399}
1400
Martin v. Löwisd919a592002-10-14 21:07:28 +00001401#ifdef Py_USING_UNICODE
1402/* Replace Unicode objects in slots. */
1403
1404static PyObject *
1405_unicode_to_string(PyObject *slots, int nslots)
1406{
1407 PyObject *tmp = slots;
1408 PyObject *o, *o1;
1409 int i;
1410 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1411 for (i = 0; i < nslots; i++) {
1412 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1413 if (tmp == slots) {
1414 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1415 if (tmp == NULL)
1416 return NULL;
1417 }
1418 o1 = _PyUnicode_AsDefaultEncodedString
1419 (o, NULL);
1420 if (o1 == NULL) {
1421 Py_DECREF(tmp);
1422 return 0;
1423 }
1424 Py_INCREF(o1);
1425 Py_DECREF(o);
1426 PyTuple_SET_ITEM(tmp, i, o1);
1427 }
1428 }
1429 return tmp;
1430}
1431#endif
1432
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001433static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001434type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1435{
1436 PyObject *name, *bases, *dict;
1437 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001438 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001439 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001441 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001442 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001443 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001444
Tim Peters3abca122001-10-27 19:37:48 +00001445 assert(args != NULL && PyTuple_Check(args));
1446 assert(kwds == NULL || PyDict_Check(kwds));
1447
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001448 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001449 {
1450 const int nargs = PyTuple_GET_SIZE(args);
1451 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1452
1453 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1454 PyObject *x = PyTuple_GET_ITEM(args, 0);
1455 Py_INCREF(x->ob_type);
1456 return (PyObject *) x->ob_type;
1457 }
1458
1459 /* SF bug 475327 -- if that didn't trigger, we need 3
1460 arguments. but PyArg_ParseTupleAndKeywords below may give
1461 a msg saying type() needs exactly 3. */
1462 if (nargs + nkwds != 3) {
1463 PyErr_SetString(PyExc_TypeError,
1464 "type() takes 1 or 3 arguments");
1465 return NULL;
1466 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001467 }
1468
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001469 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1471 &name,
1472 &PyTuple_Type, &bases,
1473 &PyDict_Type, &dict))
1474 return NULL;
1475
1476 /* Determine the proper metatype to deal with this,
1477 and check for metatype conflicts while we're at it.
1478 Note that if some other metatype wins to contract,
1479 it's possible that its instances are not types. */
1480 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001481 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001482 for (i = 0; i < nbases; i++) {
1483 tmp = PyTuple_GET_ITEM(bases, i);
1484 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001485 if (tmptype == &PyClass_Type)
1486 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001487 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001489 if (PyType_IsSubtype(tmptype, winner)) {
1490 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001491 continue;
1492 }
1493 PyErr_SetString(PyExc_TypeError,
1494 "metatype conflict among bases");
1495 return NULL;
1496 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001497 if (winner != metatype) {
1498 if (winner->tp_new != type_new) /* Pass it to the winner */
1499 return winner->tp_new(winner, args, kwds);
1500 metatype = winner;
1501 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001502
1503 /* Adjust for empty tuple bases */
1504 if (nbases == 0) {
1505 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1506 if (bases == NULL)
1507 return NULL;
1508 nbases = 1;
1509 }
1510 else
1511 Py_INCREF(bases);
1512
1513 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1514
1515 /* Calculate best base, and check that all bases are type objects */
1516 base = best_base(bases);
1517 if (base == NULL)
1518 return NULL;
1519 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1520 PyErr_Format(PyExc_TypeError,
1521 "type '%.100s' is not an acceptable base type",
1522 base->tp_name);
1523 return NULL;
1524 }
1525
Tim Peters6d6c1a32001-08-02 04:15:00 +00001526 /* Check for a __slots__ sequence variable in dict, and count it */
1527 slots = PyDict_GetItemString(dict, "__slots__");
1528 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001529 add_dict = 0;
1530 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001531 may_add_dict = base->tp_dictoffset == 0;
1532 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1533 if (slots == NULL) {
1534 if (may_add_dict) {
1535 add_dict++;
1536 }
1537 if (may_add_weak) {
1538 add_weak++;
1539 }
1540 }
1541 else {
1542 /* Have slots */
1543
Tim Peters6d6c1a32001-08-02 04:15:00 +00001544 /* Make it into a tuple */
1545 if (PyString_Check(slots))
1546 slots = Py_BuildValue("(O)", slots);
1547 else
1548 slots = PySequence_Tuple(slots);
1549 if (slots == NULL)
1550 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001551 assert(PyTuple_Check(slots));
1552
1553 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001555 if (nslots > 0 && base->tp_itemsize != 0) {
1556 PyErr_Format(PyExc_TypeError,
1557 "nonempty __slots__ "
1558 "not supported for subtype of '%s'",
1559 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001560 bad_slots:
1561 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001562 return NULL;
1563 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001564
Martin v. Löwisd919a592002-10-14 21:07:28 +00001565#ifdef Py_USING_UNICODE
1566 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001567 if (tmp != slots) {
1568 Py_DECREF(slots);
1569 slots = tmp;
1570 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001571 if (!tmp)
1572 return NULL;
1573#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001574 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001575 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001576 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1577 char *s;
1578 if (!valid_identifier(tmp))
1579 goto bad_slots;
1580 assert(PyString_Check(tmp));
1581 s = PyString_AS_STRING(tmp);
1582 if (strcmp(s, "__dict__") == 0) {
1583 if (!may_add_dict || add_dict) {
1584 PyErr_SetString(PyExc_TypeError,
1585 "__dict__ slot disallowed: "
1586 "we already got one");
1587 goto bad_slots;
1588 }
1589 add_dict++;
1590 }
1591 if (strcmp(s, "__weakref__") == 0) {
1592 if (!may_add_weak || add_weak) {
1593 PyErr_SetString(PyExc_TypeError,
1594 "__weakref__ slot disallowed: "
1595 "either we already got one, "
1596 "or __itemsize__ != 0");
1597 goto bad_slots;
1598 }
1599 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600 }
1601 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001602
Guido van Rossumad47da02002-08-12 19:05:44 +00001603 /* Copy slots into yet another tuple, demangling names */
1604 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001605 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001606 goto bad_slots;
1607 for (i = j = 0; i < nslots; i++) {
1608 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001609 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001610 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001611 s = PyString_AS_STRING(tmp);
1612 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1613 (add_weak && strcmp(s, "__weakref__") == 0))
1614 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001615 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001616 PyString_AS_STRING(tmp),
1617 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001618 {
1619 tmp = PyString_FromString(buffer);
1620 } else {
1621 Py_INCREF(tmp);
1622 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001623 PyTuple_SET_ITEM(newslots, j, tmp);
1624 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001625 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001626 assert(j == nslots - add_dict - add_weak);
1627 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001628 Py_DECREF(slots);
1629 slots = newslots;
1630
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001631 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001632 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001633 /* If not, provide a bozo that raises TypeError */
1634 if (bozo_obj == NULL) {
1635 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001636 if (bozo_obj == NULL)
1637 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001638 }
1639 if (PyDict_SetItemString(dict,
1640 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001641 bozo_obj) < 0)
1642 {
1643 Py_DECREF(bozo_obj);
1644 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001645 }
1646 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001647
1648 /* Secondary bases may provide weakrefs or dict */
1649 if (nbases > 1 &&
1650 ((may_add_dict && !add_dict) ||
1651 (may_add_weak && !add_weak))) {
1652 for (i = 0; i < nbases; i++) {
1653 tmp = PyTuple_GET_ITEM(bases, i);
1654 if (tmp == (PyObject *)base)
1655 continue; /* Skip primary base */
1656 if (PyClass_Check(tmp)) {
1657 /* Classic base class provides both */
1658 if (may_add_dict && !add_dict)
1659 add_dict++;
1660 if (may_add_weak && !add_weak)
1661 add_weak++;
1662 break;
1663 }
1664 assert(PyType_Check(tmp));
1665 tmptype = (PyTypeObject *)tmp;
1666 if (may_add_dict && !add_dict &&
1667 tmptype->tp_dictoffset != 0)
1668 add_dict++;
1669 if (may_add_weak && !add_weak &&
1670 tmptype->tp_weaklistoffset != 0)
1671 add_weak++;
1672 if (may_add_dict && !add_dict)
1673 continue;
1674 if (may_add_weak && !add_weak)
1675 continue;
1676 /* Nothing more to check */
1677 break;
1678 }
1679 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001680 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681
1682 /* XXX From here until type is safely allocated,
1683 "return NULL" may leak slots! */
1684
1685 /* Allocate the type object */
1686 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001687 if (type == NULL) {
1688 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001689 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001690 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691
1692 /* Keep name and slots alive in the extended type object */
1693 et = (etype *)type;
1694 Py_INCREF(name);
1695 et->name = name;
1696 et->slots = slots;
1697
Guido van Rossumdc91b992001-08-08 22:26:22 +00001698 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001699 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1700 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001701 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1702 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001703
1704 /* It's a new-style number unless it specifically inherits any
1705 old-style numeric behavior */
1706 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1707 (base->tp_as_number == NULL))
1708 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1709
1710 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001711 type->tp_as_number = &et->as_number;
1712 type->tp_as_sequence = &et->as_sequence;
1713 type->tp_as_mapping = &et->as_mapping;
1714 type->tp_as_buffer = &et->as_buffer;
1715 type->tp_name = PyString_AS_STRING(name);
1716
1717 /* Set tp_base and tp_bases */
1718 type->tp_bases = bases;
1719 Py_INCREF(base);
1720 type->tp_base = base;
1721
Guido van Rossum687ae002001-10-15 22:03:32 +00001722 /* Initialize tp_dict from passed-in dict */
1723 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001724 if (dict == NULL) {
1725 Py_DECREF(type);
1726 return NULL;
1727 }
1728
Guido van Rossumc3542212001-08-16 09:18:56 +00001729 /* Set __module__ in the dict */
1730 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1731 tmp = PyEval_GetGlobals();
1732 if (tmp != NULL) {
1733 tmp = PyDict_GetItemString(tmp, "__name__");
1734 if (tmp != NULL) {
1735 if (PyDict_SetItemString(dict, "__module__",
1736 tmp) < 0)
1737 return NULL;
1738 }
1739 }
1740 }
1741
Tim Peters2f93e282001-10-04 05:27:00 +00001742 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001743 and is a string. The __doc__ accessor will first look for tp_doc;
1744 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001745 */
1746 {
1747 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1748 if (doc != NULL && PyString_Check(doc)) {
1749 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001750 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001751 if (type->tp_doc == NULL) {
1752 Py_DECREF(type);
1753 return NULL;
1754 }
1755 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1756 }
1757 }
1758
Tim Peters6d6c1a32001-08-02 04:15:00 +00001759 /* Special-case __new__: if it's a plain function,
1760 make it a static function */
1761 tmp = PyDict_GetItemString(dict, "__new__");
1762 if (tmp != NULL && PyFunction_Check(tmp)) {
1763 tmp = PyStaticMethod_New(tmp);
1764 if (tmp == NULL) {
1765 Py_DECREF(type);
1766 return NULL;
1767 }
1768 PyDict_SetItemString(dict, "__new__", tmp);
1769 Py_DECREF(tmp);
1770 }
1771
1772 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1773 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001774 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775 if (slots != NULL) {
1776 for (i = 0; i < nslots; i++, mp++) {
1777 mp->name = PyString_AS_STRING(
1778 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001779 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001780 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001781 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001782 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001783 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001784 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001785 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001786 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001787 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 slotoffset += sizeof(PyObject *);
1789 }
1790 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001791 if (add_dict) {
1792 if (base->tp_itemsize)
1793 type->tp_dictoffset = -(long)sizeof(PyObject *);
1794 else
1795 type->tp_dictoffset = slotoffset;
1796 slotoffset += sizeof(PyObject *);
1797 }
1798 if (add_weak) {
1799 assert(!base->tp_itemsize);
1800 type->tp_weaklistoffset = slotoffset;
1801 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001802 }
1803 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001804 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001805 type->tp_members = et->members;
Guido van Rossumad47da02002-08-12 19:05:44 +00001806 type->tp_getset = subtype_getsets;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807
1808 /* Special case some slots */
1809 if (type->tp_dictoffset != 0 || nslots > 0) {
1810 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1811 type->tp_getattro = PyObject_GenericGetAttr;
1812 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1813 type->tp_setattro = PyObject_GenericSetAttr;
1814 }
1815 type->tp_dealloc = subtype_dealloc;
1816
Guido van Rossum9475a232001-10-05 20:51:39 +00001817 /* Enable GC unless there are really no instance variables possible */
1818 if (!(type->tp_basicsize == sizeof(PyObject) &&
1819 type->tp_itemsize == 0))
1820 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1821
Tim Peters6d6c1a32001-08-02 04:15:00 +00001822 /* Always override allocation strategy to use regular heap */
1823 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001824 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001825 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001826 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001827 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001828 }
1829 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001830 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001831
1832 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001833 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834 Py_DECREF(type);
1835 return NULL;
1836 }
1837
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001838 /* Put the proper slots in place */
1839 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001840
Tim Peters6d6c1a32001-08-02 04:15:00 +00001841 return (PyObject *)type;
1842}
1843
1844/* Internal API to look for a name through the MRO.
1845 This returns a borrowed reference, and doesn't set an exception! */
1846PyObject *
1847_PyType_Lookup(PyTypeObject *type, PyObject *name)
1848{
1849 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001850 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851
Guido van Rossum687ae002001-10-15 22:03:32 +00001852 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001854
1855 /* If mro is NULL, the type is either not yet initialized
1856 by PyType_Ready(), or already cleared by type_clear().
1857 Either way the safest thing to do is to return NULL. */
1858 if (mro == NULL)
1859 return NULL;
1860
Tim Peters6d6c1a32001-08-02 04:15:00 +00001861 assert(PyTuple_Check(mro));
1862 n = PyTuple_GET_SIZE(mro);
1863 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001864 base = PyTuple_GET_ITEM(mro, i);
1865 if (PyClass_Check(base))
1866 dict = ((PyClassObject *)base)->cl_dict;
1867 else {
1868 assert(PyType_Check(base));
1869 dict = ((PyTypeObject *)base)->tp_dict;
1870 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001871 assert(dict && PyDict_Check(dict));
1872 res = PyDict_GetItem(dict, name);
1873 if (res != NULL)
1874 return res;
1875 }
1876 return NULL;
1877}
1878
1879/* This is similar to PyObject_GenericGetAttr(),
1880 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1881static PyObject *
1882type_getattro(PyTypeObject *type, PyObject *name)
1883{
1884 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001885 PyObject *meta_attribute, *attribute;
1886 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887
1888 /* Initialize this type (we'll assume the metatype is initialized) */
1889 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001890 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001891 return NULL;
1892 }
1893
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001894 /* No readable descriptor found yet */
1895 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001896
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001897 /* Look for the attribute in the metatype */
1898 meta_attribute = _PyType_Lookup(metatype, name);
1899
1900 if (meta_attribute != NULL) {
1901 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001902
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001903 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1904 /* Data descriptors implement tp_descr_set to intercept
1905 * writes. Assume the attribute is not overridden in
1906 * type's tp_dict (and bases): call the descriptor now.
1907 */
1908 return meta_get(meta_attribute, (PyObject *)type,
1909 (PyObject *)metatype);
1910 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001911 }
1912
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001913 /* No data descriptor found on metatype. Look in tp_dict of this
1914 * type and its bases */
1915 attribute = _PyType_Lookup(type, name);
1916 if (attribute != NULL) {
1917 /* Implement descriptor functionality, if any */
1918 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1919 if (local_get != NULL) {
1920 /* NULL 2nd argument indicates the descriptor was
1921 * found on the target object itself (or a base) */
1922 return local_get(attribute, (PyObject *)NULL,
1923 (PyObject *)type);
1924 }
Tim Peters34592512002-07-11 06:23:50 +00001925
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001926 Py_INCREF(attribute);
1927 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001928 }
1929
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001930 /* No attribute found in local __dict__ (or bases): use the
1931 * descriptor from the metatype, if any */
1932 if (meta_get != NULL)
1933 return meta_get(meta_attribute, (PyObject *)type,
1934 (PyObject *)metatype);
1935
1936 /* If an ordinary attribute was found on the metatype, return it now */
1937 if (meta_attribute != NULL) {
1938 Py_INCREF(meta_attribute);
1939 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940 }
1941
1942 /* Give up */
1943 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001944 "type object '%.50s' has no attribute '%.400s'",
1945 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001946 return NULL;
1947}
1948
1949static int
1950type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1951{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001952 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1953 PyErr_Format(
1954 PyExc_TypeError,
1955 "can't set attributes of built-in/extension type '%s'",
1956 type->tp_name);
1957 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001958 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001959 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1960 return -1;
1961 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001962}
1963
1964static void
1965type_dealloc(PyTypeObject *type)
1966{
1967 etype *et;
1968
1969 /* Assert this is a heap-allocated type object */
1970 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001971 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001972 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001973 et = (etype *)type;
1974 Py_XDECREF(type->tp_base);
1975 Py_XDECREF(type->tp_dict);
1976 Py_XDECREF(type->tp_bases);
1977 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001978 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001979 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001980 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001981 Py_XDECREF(et->name);
1982 Py_XDECREF(et->slots);
1983 type->ob_type->tp_free((PyObject *)type);
1984}
1985
Guido van Rossum1c450732001-10-08 15:18:27 +00001986static PyObject *
1987type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1988{
1989 PyObject *list, *raw, *ref;
1990 int i, n;
1991
1992 list = PyList_New(0);
1993 if (list == NULL)
1994 return NULL;
1995 raw = type->tp_subclasses;
1996 if (raw == NULL)
1997 return list;
1998 assert(PyList_Check(raw));
1999 n = PyList_GET_SIZE(raw);
2000 for (i = 0; i < n; i++) {
2001 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002002 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002003 ref = PyWeakref_GET_OBJECT(ref);
2004 if (ref != Py_None) {
2005 if (PyList_Append(list, ref) < 0) {
2006 Py_DECREF(list);
2007 return NULL;
2008 }
2009 }
2010 }
2011 return list;
2012}
2013
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002015 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002016 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002017 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002018 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019 {0}
2020};
2021
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002022PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002023"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002024"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025
Guido van Rossum048eb752001-10-02 21:24:57 +00002026static int
2027type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2028{
Guido van Rossum048eb752001-10-02 21:24:57 +00002029 int err;
2030
Guido van Rossuma3862092002-06-10 15:24:42 +00002031 /* Because of type_is_gc(), the collector only calls this
2032 for heaptypes. */
2033 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002034
2035#define VISIT(SLOT) \
2036 if (SLOT) { \
2037 err = visit((PyObject *)(SLOT), arg); \
2038 if (err) \
2039 return err; \
2040 }
2041
2042 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002043 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002044 VISIT(type->tp_mro);
2045 VISIT(type->tp_bases);
2046 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002047
2048 /* There's no need to visit type->tp_subclasses or
2049 ((etype *)type)->slots, because they can't be involved
2050 in cycles; tp_subclasses is a list of weak references,
2051 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002052
2053#undef VISIT
2054
2055 return 0;
2056}
2057
2058static int
2059type_clear(PyTypeObject *type)
2060{
Guido van Rossum048eb752001-10-02 21:24:57 +00002061 PyObject *tmp;
2062
Guido van Rossuma3862092002-06-10 15:24:42 +00002063 /* Because of type_is_gc(), the collector only calls this
2064 for heaptypes. */
2065 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002066
2067#define CLEAR(SLOT) \
2068 if (SLOT) { \
2069 tmp = (PyObject *)(SLOT); \
2070 SLOT = NULL; \
2071 Py_DECREF(tmp); \
2072 }
2073
Guido van Rossuma3862092002-06-10 15:24:42 +00002074 /* The only field we need to clear is tp_mro, which is part of a
2075 hard cycle (its first element is the class itself) that won't
2076 be broken otherwise (it's a tuple and tuples don't have a
2077 tp_clear handler). None of the other fields need to be
2078 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002079
Guido van Rossuma3862092002-06-10 15:24:42 +00002080 tp_dict:
2081 It is a dict, so the collector will call its tp_clear.
2082
2083 tp_cache:
2084 Not used; if it were, it would be a dict.
2085
2086 tp_bases, tp_base:
2087 If these are involved in a cycle, there must be at least
2088 one other, mutable object in the cycle, e.g. a base
2089 class's dict; the cycle will be broken that way.
2090
2091 tp_subclasses:
2092 A list of weak references can't be part of a cycle; and
2093 lists have their own tp_clear.
2094
2095 slots (in etype):
2096 A tuple of strings can't be part of a cycle.
2097 */
2098
2099 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002100
Guido van Rossum048eb752001-10-02 21:24:57 +00002101#undef CLEAR
2102
2103 return 0;
2104}
2105
2106static int
2107type_is_gc(PyTypeObject *type)
2108{
2109 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2110}
2111
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002112PyTypeObject PyType_Type = {
2113 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002114 0, /* ob_size */
2115 "type", /* tp_name */
2116 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002117 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002118 (destructor)type_dealloc, /* tp_dealloc */
2119 0, /* tp_print */
2120 0, /* tp_getattr */
2121 0, /* tp_setattr */
2122 type_compare, /* tp_compare */
2123 (reprfunc)type_repr, /* tp_repr */
2124 0, /* tp_as_number */
2125 0, /* tp_as_sequence */
2126 0, /* tp_as_mapping */
2127 (hashfunc)_Py_HashPointer, /* tp_hash */
2128 (ternaryfunc)type_call, /* tp_call */
2129 0, /* tp_str */
2130 (getattrofunc)type_getattro, /* tp_getattro */
2131 (setattrofunc)type_setattro, /* tp_setattro */
2132 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002133 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2134 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002135 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002136 (traverseproc)type_traverse, /* tp_traverse */
2137 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002139 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002140 0, /* tp_iter */
2141 0, /* tp_iternext */
2142 type_methods, /* tp_methods */
2143 type_members, /* tp_members */
2144 type_getsets, /* tp_getset */
2145 0, /* tp_base */
2146 0, /* tp_dict */
2147 0, /* tp_descr_get */
2148 0, /* tp_descr_set */
2149 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2150 0, /* tp_init */
2151 0, /* tp_alloc */
2152 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002153 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002154 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002155};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002156
2157
2158/* The base type of all types (eventually)... except itself. */
2159
2160static int
2161object_init(PyObject *self, PyObject *args, PyObject *kwds)
2162{
2163 return 0;
2164}
2165
2166static void
2167object_dealloc(PyObject *self)
2168{
2169 self->ob_type->tp_free(self);
2170}
2171
Guido van Rossum8e248182001-08-12 05:17:56 +00002172static PyObject *
2173object_repr(PyObject *self)
2174{
Guido van Rossum76e69632001-08-16 18:52:43 +00002175 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002176 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002177
Guido van Rossum76e69632001-08-16 18:52:43 +00002178 type = self->ob_type;
2179 mod = type_module(type, NULL);
2180 if (mod == NULL)
2181 PyErr_Clear();
2182 else if (!PyString_Check(mod)) {
2183 Py_DECREF(mod);
2184 mod = NULL;
2185 }
2186 name = type_name(type, NULL);
2187 if (name == NULL)
2188 return NULL;
2189 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002190 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002191 PyString_AS_STRING(mod),
2192 PyString_AS_STRING(name),
2193 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002194 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002195 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002196 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002197 Py_XDECREF(mod);
2198 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002199 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002200}
2201
Guido van Rossumb8f63662001-08-15 23:57:02 +00002202static PyObject *
2203object_str(PyObject *self)
2204{
2205 unaryfunc f;
2206
2207 f = self->ob_type->tp_repr;
2208 if (f == NULL)
2209 f = object_repr;
2210 return f(self);
2211}
2212
Guido van Rossum8e248182001-08-12 05:17:56 +00002213static long
2214object_hash(PyObject *self)
2215{
2216 return _Py_HashPointer(self);
2217}
Guido van Rossum8e248182001-08-12 05:17:56 +00002218
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002219static PyObject *
2220object_get_class(PyObject *self, void *closure)
2221{
2222 Py_INCREF(self->ob_type);
2223 return (PyObject *)(self->ob_type);
2224}
2225
2226static int
2227equiv_structs(PyTypeObject *a, PyTypeObject *b)
2228{
2229 return a == b ||
2230 (a != NULL &&
2231 b != NULL &&
2232 a->tp_basicsize == b->tp_basicsize &&
2233 a->tp_itemsize == b->tp_itemsize &&
2234 a->tp_dictoffset == b->tp_dictoffset &&
2235 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2236 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2237 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2238}
2239
2240static int
2241same_slots_added(PyTypeObject *a, PyTypeObject *b)
2242{
2243 PyTypeObject *base = a->tp_base;
2244 int size;
2245
2246 if (base != b->tp_base)
2247 return 0;
2248 if (equiv_structs(a, base) && equiv_structs(b, base))
2249 return 1;
2250 size = base->tp_basicsize;
2251 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2252 size += sizeof(PyObject *);
2253 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2254 size += sizeof(PyObject *);
2255 return size == a->tp_basicsize && size == b->tp_basicsize;
2256}
2257
2258static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002259compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2260{
2261 PyTypeObject *newbase, *oldbase;
2262
2263 if (new->tp_dealloc != old->tp_dealloc ||
2264 new->tp_free != old->tp_free)
2265 {
2266 PyErr_Format(PyExc_TypeError,
2267 "%s assignment: "
2268 "'%s' deallocator differs from '%s'",
2269 attr,
2270 new->tp_name,
2271 old->tp_name);
2272 return 0;
2273 }
2274 newbase = new;
2275 oldbase = old;
2276 while (equiv_structs(newbase, newbase->tp_base))
2277 newbase = newbase->tp_base;
2278 while (equiv_structs(oldbase, oldbase->tp_base))
2279 oldbase = oldbase->tp_base;
2280 if (newbase != oldbase &&
2281 (newbase->tp_base != oldbase->tp_base ||
2282 !same_slots_added(newbase, oldbase))) {
2283 PyErr_Format(PyExc_TypeError,
2284 "%s assignment: "
2285 "'%s' object layout differs from '%s'",
2286 attr,
2287 new->tp_name,
2288 old->tp_name);
2289 return 0;
2290 }
2291
2292 return 1;
2293}
2294
2295static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002296object_set_class(PyObject *self, PyObject *value, void *closure)
2297{
2298 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002299 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002300
Guido van Rossumb6b89422002-04-15 01:03:30 +00002301 if (value == NULL) {
2302 PyErr_SetString(PyExc_TypeError,
2303 "can't delete __class__ attribute");
2304 return -1;
2305 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002306 if (!PyType_Check(value)) {
2307 PyErr_Format(PyExc_TypeError,
2308 "__class__ must be set to new-style class, not '%s' object",
2309 value->ob_type->tp_name);
2310 return -1;
2311 }
2312 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002313 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2314 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2315 {
2316 PyErr_Format(PyExc_TypeError,
2317 "__class__ assignment: only for heap types");
2318 return -1;
2319 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002320 if (compatible_for_assignment(new, old, "__class__")) {
2321 Py_INCREF(new);
2322 self->ob_type = new;
2323 Py_DECREF(old);
2324 return 0;
2325 }
2326 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002327 return -1;
2328 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002329}
2330
2331static PyGetSetDef object_getsets[] = {
2332 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002333 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002334 {0}
2335};
2336
Guido van Rossum3926a632001-09-25 16:25:58 +00002337static PyObject *
2338object_reduce(PyObject *self, PyObject *args)
2339{
2340 /* Call copy_reg._reduce(self) */
2341 static PyObject *copy_reg_str;
2342 PyObject *copy_reg, *res;
2343
2344 if (!copy_reg_str) {
2345 copy_reg_str = PyString_InternFromString("copy_reg");
2346 if (copy_reg_str == NULL)
2347 return NULL;
2348 }
2349 copy_reg = PyImport_Import(copy_reg_str);
2350 if (!copy_reg)
2351 return NULL;
2352 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
2353 Py_DECREF(copy_reg);
2354 return res;
2355}
2356
2357static PyMethodDef object_methods[] = {
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002358 {"__reduce__", object_reduce, METH_NOARGS,
2359 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002360 {0}
2361};
2362
Tim Peters6d6c1a32001-08-02 04:15:00 +00002363PyTypeObject PyBaseObject_Type = {
2364 PyObject_HEAD_INIT(&PyType_Type)
2365 0, /* ob_size */
2366 "object", /* tp_name */
2367 sizeof(PyObject), /* tp_basicsize */
2368 0, /* tp_itemsize */
2369 (destructor)object_dealloc, /* tp_dealloc */
2370 0, /* tp_print */
2371 0, /* tp_getattr */
2372 0, /* tp_setattr */
2373 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002374 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002375 0, /* tp_as_number */
2376 0, /* tp_as_sequence */
2377 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002378 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002379 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002380 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002381 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002382 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002383 0, /* tp_as_buffer */
2384 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002385 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002386 0, /* tp_traverse */
2387 0, /* tp_clear */
2388 0, /* tp_richcompare */
2389 0, /* tp_weaklistoffset */
2390 0, /* tp_iter */
2391 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002392 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002393 0, /* tp_members */
2394 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002395 0, /* tp_base */
2396 0, /* tp_dict */
2397 0, /* tp_descr_get */
2398 0, /* tp_descr_set */
2399 0, /* tp_dictoffset */
2400 object_init, /* tp_init */
2401 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00002402 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002403 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002404};
2405
2406
2407/* Initialize the __dict__ in a type object */
2408
Fred Drake7bf97152002-03-28 05:33:33 +00002409static PyObject *
2410create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
2411{
2412 PyObject *cfunc;
2413 PyObject *result;
2414
2415 cfunc = PyCFunction_New(meth, NULL);
2416 if (cfunc == NULL)
2417 return NULL;
2418 result = func(cfunc);
2419 Py_DECREF(cfunc);
2420 return result;
2421}
2422
Tim Peters6d6c1a32001-08-02 04:15:00 +00002423static int
2424add_methods(PyTypeObject *type, PyMethodDef *meth)
2425{
Guido van Rossum687ae002001-10-15 22:03:32 +00002426 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002427
2428 for (; meth->ml_name != NULL; meth++) {
2429 PyObject *descr;
2430 if (PyDict_GetItemString(dict, meth->ml_name))
2431 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002432 if (meth->ml_flags & METH_CLASS) {
2433 if (meth->ml_flags & METH_STATIC) {
2434 PyErr_SetString(PyExc_ValueError,
2435 "method cannot be both class and static");
2436 return -1;
2437 }
2438 descr = create_specialmethod(meth, PyClassMethod_New);
2439 }
2440 else if (meth->ml_flags & METH_STATIC) {
2441 descr = create_specialmethod(meth, PyStaticMethod_New);
2442 }
2443 else {
2444 descr = PyDescr_NewMethod(type, meth);
2445 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002446 if (descr == NULL)
2447 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002448 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449 return -1;
2450 Py_DECREF(descr);
2451 }
2452 return 0;
2453}
2454
2455static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002456add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002457{
Guido van Rossum687ae002001-10-15 22:03:32 +00002458 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002459
2460 for (; memb->name != NULL; memb++) {
2461 PyObject *descr;
2462 if (PyDict_GetItemString(dict, memb->name))
2463 continue;
2464 descr = PyDescr_NewMember(type, memb);
2465 if (descr == NULL)
2466 return -1;
2467 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2468 return -1;
2469 Py_DECREF(descr);
2470 }
2471 return 0;
2472}
2473
2474static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002475add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002476{
Guido van Rossum687ae002001-10-15 22:03:32 +00002477 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002478
2479 for (; gsp->name != NULL; gsp++) {
2480 PyObject *descr;
2481 if (PyDict_GetItemString(dict, gsp->name))
2482 continue;
2483 descr = PyDescr_NewGetSet(type, gsp);
2484
2485 if (descr == NULL)
2486 return -1;
2487 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2488 return -1;
2489 Py_DECREF(descr);
2490 }
2491 return 0;
2492}
2493
Guido van Rossum13d52f02001-08-10 21:24:08 +00002494static void
2495inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002496{
2497 int oldsize, newsize;
2498
Guido van Rossum13d52f02001-08-10 21:24:08 +00002499 /* Special flag magic */
2500 if (!type->tp_as_buffer && base->tp_as_buffer) {
2501 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2502 type->tp_flags |=
2503 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2504 }
2505 if (!type->tp_as_sequence && base->tp_as_sequence) {
2506 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2507 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2508 }
2509 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2510 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2511 if ((!type->tp_as_number && base->tp_as_number) ||
2512 (!type->tp_as_sequence && base->tp_as_sequence)) {
2513 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2514 if (!type->tp_as_number && !type->tp_as_sequence) {
2515 type->tp_flags |= base->tp_flags &
2516 Py_TPFLAGS_HAVE_INPLACEOPS;
2517 }
2518 }
2519 /* Wow */
2520 }
2521 if (!type->tp_as_number && base->tp_as_number) {
2522 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2523 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2524 }
2525
2526 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002527 oldsize = base->tp_basicsize;
2528 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2529 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2530 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002531 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2532 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002533 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002534 if (type->tp_traverse == NULL)
2535 type->tp_traverse = base->tp_traverse;
2536 if (type->tp_clear == NULL)
2537 type->tp_clear = base->tp_clear;
2538 }
2539 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002540 /* The condition below could use some explanation.
2541 It appears that tp_new is not inherited for static types
2542 whose base class is 'object'; this seems to be a precaution
2543 so that old extension types don't suddenly become
2544 callable (object.__new__ wouldn't insure the invariants
2545 that the extension type's own factory function ensures).
2546 Heap types, of course, are under our control, so they do
2547 inherit tp_new; static extension types that specify some
2548 other built-in type as the default are considered
2549 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002550 if (base != &PyBaseObject_Type ||
2551 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2552 if (type->tp_new == NULL)
2553 type->tp_new = base->tp_new;
2554 }
2555 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002556 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002557
2558 /* Copy other non-function slots */
2559
2560#undef COPYVAL
2561#define COPYVAL(SLOT) \
2562 if (type->SLOT == 0) type->SLOT = base->SLOT
2563
2564 COPYVAL(tp_itemsize);
2565 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2566 COPYVAL(tp_weaklistoffset);
2567 }
2568 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2569 COPYVAL(tp_dictoffset);
2570 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002571}
2572
2573static void
2574inherit_slots(PyTypeObject *type, PyTypeObject *base)
2575{
2576 PyTypeObject *basebase;
2577
2578#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002579#undef COPYSLOT
2580#undef COPYNUM
2581#undef COPYSEQ
2582#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002583#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002584
2585#define SLOTDEFINED(SLOT) \
2586 (base->SLOT != 0 && \
2587 (basebase == NULL || base->SLOT != basebase->SLOT))
2588
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002590 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002591
2592#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2593#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2594#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002595#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002596
Guido van Rossum13d52f02001-08-10 21:24:08 +00002597 /* This won't inherit indirect slots (from tp_as_number etc.)
2598 if type doesn't provide the space. */
2599
2600 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2601 basebase = base->tp_base;
2602 if (basebase->tp_as_number == NULL)
2603 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002604 COPYNUM(nb_add);
2605 COPYNUM(nb_subtract);
2606 COPYNUM(nb_multiply);
2607 COPYNUM(nb_divide);
2608 COPYNUM(nb_remainder);
2609 COPYNUM(nb_divmod);
2610 COPYNUM(nb_power);
2611 COPYNUM(nb_negative);
2612 COPYNUM(nb_positive);
2613 COPYNUM(nb_absolute);
2614 COPYNUM(nb_nonzero);
2615 COPYNUM(nb_invert);
2616 COPYNUM(nb_lshift);
2617 COPYNUM(nb_rshift);
2618 COPYNUM(nb_and);
2619 COPYNUM(nb_xor);
2620 COPYNUM(nb_or);
2621 COPYNUM(nb_coerce);
2622 COPYNUM(nb_int);
2623 COPYNUM(nb_long);
2624 COPYNUM(nb_float);
2625 COPYNUM(nb_oct);
2626 COPYNUM(nb_hex);
2627 COPYNUM(nb_inplace_add);
2628 COPYNUM(nb_inplace_subtract);
2629 COPYNUM(nb_inplace_multiply);
2630 COPYNUM(nb_inplace_divide);
2631 COPYNUM(nb_inplace_remainder);
2632 COPYNUM(nb_inplace_power);
2633 COPYNUM(nb_inplace_lshift);
2634 COPYNUM(nb_inplace_rshift);
2635 COPYNUM(nb_inplace_and);
2636 COPYNUM(nb_inplace_xor);
2637 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002638 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2639 COPYNUM(nb_true_divide);
2640 COPYNUM(nb_floor_divide);
2641 COPYNUM(nb_inplace_true_divide);
2642 COPYNUM(nb_inplace_floor_divide);
2643 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002644 }
2645
Guido van Rossum13d52f02001-08-10 21:24:08 +00002646 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2647 basebase = base->tp_base;
2648 if (basebase->tp_as_sequence == NULL)
2649 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002650 COPYSEQ(sq_length);
2651 COPYSEQ(sq_concat);
2652 COPYSEQ(sq_repeat);
2653 COPYSEQ(sq_item);
2654 COPYSEQ(sq_slice);
2655 COPYSEQ(sq_ass_item);
2656 COPYSEQ(sq_ass_slice);
2657 COPYSEQ(sq_contains);
2658 COPYSEQ(sq_inplace_concat);
2659 COPYSEQ(sq_inplace_repeat);
2660 }
2661
Guido van Rossum13d52f02001-08-10 21:24:08 +00002662 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2663 basebase = base->tp_base;
2664 if (basebase->tp_as_mapping == NULL)
2665 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002666 COPYMAP(mp_length);
2667 COPYMAP(mp_subscript);
2668 COPYMAP(mp_ass_subscript);
2669 }
2670
Tim Petersfc57ccb2001-10-12 02:38:24 +00002671 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2672 basebase = base->tp_base;
2673 if (basebase->tp_as_buffer == NULL)
2674 basebase = NULL;
2675 COPYBUF(bf_getreadbuffer);
2676 COPYBUF(bf_getwritebuffer);
2677 COPYBUF(bf_getsegcount);
2678 COPYBUF(bf_getcharbuffer);
2679 }
2680
Guido van Rossum13d52f02001-08-10 21:24:08 +00002681 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682
Tim Peters6d6c1a32001-08-02 04:15:00 +00002683 COPYSLOT(tp_dealloc);
2684 COPYSLOT(tp_print);
2685 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2686 type->tp_getattr = base->tp_getattr;
2687 type->tp_getattro = base->tp_getattro;
2688 }
2689 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2690 type->tp_setattr = base->tp_setattr;
2691 type->tp_setattro = base->tp_setattro;
2692 }
2693 /* tp_compare see tp_richcompare */
2694 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002695 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696 COPYSLOT(tp_call);
2697 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002699 if (type->tp_compare == NULL &&
2700 type->tp_richcompare == NULL &&
2701 type->tp_hash == NULL)
2702 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002703 type->tp_compare = base->tp_compare;
2704 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002705 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002706 }
2707 }
2708 else {
2709 COPYSLOT(tp_compare);
2710 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002711 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2712 COPYSLOT(tp_iter);
2713 COPYSLOT(tp_iternext);
2714 }
2715 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2716 COPYSLOT(tp_descr_get);
2717 COPYSLOT(tp_descr_set);
2718 COPYSLOT(tp_dictoffset);
2719 COPYSLOT(tp_init);
2720 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002721 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002722 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002724}
2725
Jeremy Hylton938ace62002-07-17 16:30:39 +00002726static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002727
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002729PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002731 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002732 PyTypeObject *base;
2733 int i, n;
2734
Guido van Rossumcab05802002-06-10 15:29:03 +00002735 if (type->tp_flags & Py_TPFLAGS_READY) {
2736 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002737 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002738 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002739 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002740
2741 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002742
2743 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2744 base = type->tp_base;
2745 if (base == NULL && type != &PyBaseObject_Type)
2746 base = type->tp_base = &PyBaseObject_Type;
2747
Guido van Rossum323a9cf2002-08-14 17:26:30 +00002748 /* Initialize the base class */
2749 if (base && base->tp_dict == NULL) {
2750 if (PyType_Ready(base) < 0)
2751 goto error;
2752 }
2753
Guido van Rossum0986d822002-04-08 01:38:42 +00002754 /* Initialize ob_type if NULL. This means extensions that want to be
2755 compilable separately on Windows can call PyType_Ready() instead of
2756 initializing the ob_type field of their type objects. */
2757 if (type->ob_type == NULL)
2758 type->ob_type = base->ob_type;
2759
Tim Peters6d6c1a32001-08-02 04:15:00 +00002760 /* Initialize tp_bases */
2761 bases = type->tp_bases;
2762 if (bases == NULL) {
2763 if (base == NULL)
2764 bases = PyTuple_New(0);
2765 else
2766 bases = Py_BuildValue("(O)", base);
2767 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002768 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769 type->tp_bases = bases;
2770 }
2771
Guido van Rossum687ae002001-10-15 22:03:32 +00002772 /* Initialize tp_dict */
2773 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002774 if (dict == NULL) {
2775 dict = PyDict_New();
2776 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002777 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002778 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002779 }
2780
Guido van Rossum687ae002001-10-15 22:03:32 +00002781 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002783 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784 if (type->tp_methods != NULL) {
2785 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002786 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002787 }
2788 if (type->tp_members != NULL) {
2789 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002790 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791 }
2792 if (type->tp_getset != NULL) {
2793 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002794 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002795 }
2796
Tim Peters6d6c1a32001-08-02 04:15:00 +00002797 /* Calculate method resolution order */
2798 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002799 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002800 }
2801
Guido van Rossum13d52f02001-08-10 21:24:08 +00002802 /* Inherit special flags from dominant base */
2803 if (type->tp_base != NULL)
2804 inherit_special(type, type->tp_base);
2805
Tim Peters6d6c1a32001-08-02 04:15:00 +00002806 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002807 bases = type->tp_mro;
2808 assert(bases != NULL);
2809 assert(PyTuple_Check(bases));
2810 n = PyTuple_GET_SIZE(bases);
2811 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002812 PyObject *b = PyTuple_GET_ITEM(bases, i);
2813 if (PyType_Check(b))
2814 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002815 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002816
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002817 /* if the type dictionary doesn't contain a __doc__, set it from
2818 the tp_doc slot.
2819 */
2820 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2821 if (type->tp_doc != NULL) {
2822 PyObject *doc = PyString_FromString(type->tp_doc);
2823 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2824 Py_DECREF(doc);
2825 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002826 PyDict_SetItemString(type->tp_dict,
2827 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002828 }
2829 }
2830
Guido van Rossum13d52f02001-08-10 21:24:08 +00002831 /* Some more special stuff */
2832 base = type->tp_base;
2833 if (base != NULL) {
2834 if (type->tp_as_number == NULL)
2835 type->tp_as_number = base->tp_as_number;
2836 if (type->tp_as_sequence == NULL)
2837 type->tp_as_sequence = base->tp_as_sequence;
2838 if (type->tp_as_mapping == NULL)
2839 type->tp_as_mapping = base->tp_as_mapping;
2840 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002841
Guido van Rossum1c450732001-10-08 15:18:27 +00002842 /* Link into each base class's list of subclasses */
2843 bases = type->tp_bases;
2844 n = PyTuple_GET_SIZE(bases);
2845 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002846 PyObject *b = PyTuple_GET_ITEM(bases, i);
2847 if (PyType_Check(b) &&
2848 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002849 goto error;
2850 }
2851
Guido van Rossum13d52f02001-08-10 21:24:08 +00002852 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002853 assert(type->tp_dict != NULL);
2854 type->tp_flags =
2855 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002856 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002857
2858 error:
2859 type->tp_flags &= ~Py_TPFLAGS_READYING;
2860 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002861}
2862
Guido van Rossum1c450732001-10-08 15:18:27 +00002863static int
2864add_subclass(PyTypeObject *base, PyTypeObject *type)
2865{
2866 int i;
2867 PyObject *list, *ref, *new;
2868
2869 list = base->tp_subclasses;
2870 if (list == NULL) {
2871 base->tp_subclasses = list = PyList_New(0);
2872 if (list == NULL)
2873 return -1;
2874 }
2875 assert(PyList_Check(list));
2876 new = PyWeakref_NewRef((PyObject *)type, NULL);
2877 i = PyList_GET_SIZE(list);
2878 while (--i >= 0) {
2879 ref = PyList_GET_ITEM(list, i);
2880 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00002881 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2882 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00002883 }
2884 i = PyList_Append(list, new);
2885 Py_DECREF(new);
2886 return i;
2887}
2888
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002889static void
2890remove_subclass(PyTypeObject *base, PyTypeObject *type)
2891{
2892 int i;
2893 PyObject *list, *ref;
2894
2895 list = base->tp_subclasses;
2896 if (list == NULL) {
2897 return;
2898 }
2899 assert(PyList_Check(list));
2900 i = PyList_GET_SIZE(list);
2901 while (--i >= 0) {
2902 ref = PyList_GET_ITEM(list, i);
2903 assert(PyWeakref_CheckRef(ref));
2904 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
2905 /* this can't fail, right? */
2906 PySequence_DelItem(list, i);
2907 return;
2908 }
2909 }
2910}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002911
2912/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2913
2914/* There's a wrapper *function* for each distinct function typedef used
2915 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2916 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2917 Most tables have only one entry; the tables for binary operators have two
2918 entries, one regular and one with reversed arguments. */
2919
2920static PyObject *
2921wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2922{
2923 inquiry func = (inquiry)wrapped;
2924 int res;
2925
2926 if (!PyArg_ParseTuple(args, ""))
2927 return NULL;
2928 res = (*func)(self);
2929 if (res == -1 && PyErr_Occurred())
2930 return NULL;
2931 return PyInt_FromLong((long)res);
2932}
2933
Tim Peters6d6c1a32001-08-02 04:15:00 +00002934static PyObject *
2935wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2936{
2937 binaryfunc func = (binaryfunc)wrapped;
2938 PyObject *other;
2939
2940 if (!PyArg_ParseTuple(args, "O", &other))
2941 return NULL;
2942 return (*func)(self, other);
2943}
2944
2945static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002946wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2947{
2948 binaryfunc func = (binaryfunc)wrapped;
2949 PyObject *other;
2950
2951 if (!PyArg_ParseTuple(args, "O", &other))
2952 return NULL;
2953 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002954 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002955 Py_INCREF(Py_NotImplemented);
2956 return Py_NotImplemented;
2957 }
2958 return (*func)(self, other);
2959}
2960
2961static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2963{
2964 binaryfunc func = (binaryfunc)wrapped;
2965 PyObject *other;
2966
2967 if (!PyArg_ParseTuple(args, "O", &other))
2968 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002969 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002970 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002971 Py_INCREF(Py_NotImplemented);
2972 return Py_NotImplemented;
2973 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974 return (*func)(other, self);
2975}
2976
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002977static PyObject *
2978wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2979{
2980 coercion func = (coercion)wrapped;
2981 PyObject *other, *res;
2982 int ok;
2983
2984 if (!PyArg_ParseTuple(args, "O", &other))
2985 return NULL;
2986 ok = func(&self, &other);
2987 if (ok < 0)
2988 return NULL;
2989 if (ok > 0) {
2990 Py_INCREF(Py_NotImplemented);
2991 return Py_NotImplemented;
2992 }
2993 res = PyTuple_New(2);
2994 if (res == NULL) {
2995 Py_DECREF(self);
2996 Py_DECREF(other);
2997 return NULL;
2998 }
2999 PyTuple_SET_ITEM(res, 0, self);
3000 PyTuple_SET_ITEM(res, 1, other);
3001 return res;
3002}
3003
Tim Peters6d6c1a32001-08-02 04:15:00 +00003004static PyObject *
3005wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3006{
3007 ternaryfunc func = (ternaryfunc)wrapped;
3008 PyObject *other;
3009 PyObject *third = Py_None;
3010
3011 /* Note: This wrapper only works for __pow__() */
3012
3013 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3014 return NULL;
3015 return (*func)(self, other, third);
3016}
3017
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003018static PyObject *
3019wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3020{
3021 ternaryfunc func = (ternaryfunc)wrapped;
3022 PyObject *other;
3023 PyObject *third = Py_None;
3024
3025 /* Note: This wrapper only works for __pow__() */
3026
3027 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3028 return NULL;
3029 return (*func)(other, self, third);
3030}
3031
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032static PyObject *
3033wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3034{
3035 unaryfunc func = (unaryfunc)wrapped;
3036
3037 if (!PyArg_ParseTuple(args, ""))
3038 return NULL;
3039 return (*func)(self);
3040}
3041
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042static PyObject *
3043wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3044{
3045 intargfunc func = (intargfunc)wrapped;
3046 int i;
3047
3048 if (!PyArg_ParseTuple(args, "i", &i))
3049 return NULL;
3050 return (*func)(self, i);
3051}
3052
Guido van Rossum5d815f32001-08-17 21:57:47 +00003053static int
3054getindex(PyObject *self, PyObject *arg)
3055{
3056 int i;
3057
3058 i = PyInt_AsLong(arg);
3059 if (i == -1 && PyErr_Occurred())
3060 return -1;
3061 if (i < 0) {
3062 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3063 if (sq && sq->sq_length) {
3064 int n = (*sq->sq_length)(self);
3065 if (n < 0)
3066 return -1;
3067 i += n;
3068 }
3069 }
3070 return i;
3071}
3072
3073static PyObject *
3074wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3075{
3076 intargfunc func = (intargfunc)wrapped;
3077 PyObject *arg;
3078 int i;
3079
Guido van Rossumf4593e02001-10-03 12:09:30 +00003080 if (PyTuple_GET_SIZE(args) == 1) {
3081 arg = PyTuple_GET_ITEM(args, 0);
3082 i = getindex(self, arg);
3083 if (i == -1 && PyErr_Occurred())
3084 return NULL;
3085 return (*func)(self, i);
3086 }
3087 PyArg_ParseTuple(args, "O", &arg);
3088 assert(PyErr_Occurred());
3089 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003090}
3091
Tim Peters6d6c1a32001-08-02 04:15:00 +00003092static PyObject *
3093wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3094{
3095 intintargfunc func = (intintargfunc)wrapped;
3096 int i, j;
3097
3098 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3099 return NULL;
3100 return (*func)(self, i, j);
3101}
3102
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003104wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105{
3106 intobjargproc func = (intobjargproc)wrapped;
3107 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003108 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109
Guido van Rossum5d815f32001-08-17 21:57:47 +00003110 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3111 return NULL;
3112 i = getindex(self, arg);
3113 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003114 return NULL;
3115 res = (*func)(self, i, value);
3116 if (res == -1 && PyErr_Occurred())
3117 return NULL;
3118 Py_INCREF(Py_None);
3119 return Py_None;
3120}
3121
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003122static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003123wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003124{
3125 intobjargproc func = (intobjargproc)wrapped;
3126 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003127 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003128
Guido van Rossum5d815f32001-08-17 21:57:47 +00003129 if (!PyArg_ParseTuple(args, "O", &arg))
3130 return NULL;
3131 i = getindex(self, arg);
3132 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003133 return NULL;
3134 res = (*func)(self, i, NULL);
3135 if (res == -1 && PyErr_Occurred())
3136 return NULL;
3137 Py_INCREF(Py_None);
3138 return Py_None;
3139}
3140
Tim Peters6d6c1a32001-08-02 04:15:00 +00003141static PyObject *
3142wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3143{
3144 intintobjargproc func = (intintobjargproc)wrapped;
3145 int i, j, res;
3146 PyObject *value;
3147
3148 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3149 return NULL;
3150 res = (*func)(self, i, j, value);
3151 if (res == -1 && PyErr_Occurred())
3152 return NULL;
3153 Py_INCREF(Py_None);
3154 return Py_None;
3155}
3156
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003157static PyObject *
3158wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3159{
3160 intintobjargproc func = (intintobjargproc)wrapped;
3161 int i, j, res;
3162
3163 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3164 return NULL;
3165 res = (*func)(self, i, j, NULL);
3166 if (res == -1 && PyErr_Occurred())
3167 return NULL;
3168 Py_INCREF(Py_None);
3169 return Py_None;
3170}
3171
Tim Peters6d6c1a32001-08-02 04:15:00 +00003172/* XXX objobjproc is a misnomer; should be objargpred */
3173static PyObject *
3174wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3175{
3176 objobjproc func = (objobjproc)wrapped;
3177 int res;
3178 PyObject *value;
3179
3180 if (!PyArg_ParseTuple(args, "O", &value))
3181 return NULL;
3182 res = (*func)(self, value);
3183 if (res == -1 && PyErr_Occurred())
3184 return NULL;
3185 return PyInt_FromLong((long)res);
3186}
3187
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188static PyObject *
3189wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3190{
3191 objobjargproc func = (objobjargproc)wrapped;
3192 int res;
3193 PyObject *key, *value;
3194
3195 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3196 return NULL;
3197 res = (*func)(self, key, value);
3198 if (res == -1 && PyErr_Occurred())
3199 return NULL;
3200 Py_INCREF(Py_None);
3201 return Py_None;
3202}
3203
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003204static PyObject *
3205wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3206{
3207 objobjargproc func = (objobjargproc)wrapped;
3208 int res;
3209 PyObject *key;
3210
3211 if (!PyArg_ParseTuple(args, "O", &key))
3212 return NULL;
3213 res = (*func)(self, key, NULL);
3214 if (res == -1 && PyErr_Occurred())
3215 return NULL;
3216 Py_INCREF(Py_None);
3217 return Py_None;
3218}
3219
Tim Peters6d6c1a32001-08-02 04:15:00 +00003220static PyObject *
3221wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3222{
3223 cmpfunc func = (cmpfunc)wrapped;
3224 int res;
3225 PyObject *other;
3226
3227 if (!PyArg_ParseTuple(args, "O", &other))
3228 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003229 if (other->ob_type->tp_compare != func &&
3230 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003231 PyErr_Format(
3232 PyExc_TypeError,
3233 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3234 self->ob_type->tp_name,
3235 self->ob_type->tp_name,
3236 other->ob_type->tp_name);
3237 return NULL;
3238 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003239 res = (*func)(self, other);
3240 if (PyErr_Occurred())
3241 return NULL;
3242 return PyInt_FromLong((long)res);
3243}
3244
Tim Peters6d6c1a32001-08-02 04:15:00 +00003245static PyObject *
3246wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3247{
3248 setattrofunc func = (setattrofunc)wrapped;
3249 int res;
3250 PyObject *name, *value;
3251
3252 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3253 return NULL;
3254 res = (*func)(self, name, value);
3255 if (res < 0)
3256 return NULL;
3257 Py_INCREF(Py_None);
3258 return Py_None;
3259}
3260
3261static PyObject *
3262wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3263{
3264 setattrofunc func = (setattrofunc)wrapped;
3265 int res;
3266 PyObject *name;
3267
3268 if (!PyArg_ParseTuple(args, "O", &name))
3269 return NULL;
3270 res = (*func)(self, name, NULL);
3271 if (res < 0)
3272 return NULL;
3273 Py_INCREF(Py_None);
3274 return Py_None;
3275}
3276
Tim Peters6d6c1a32001-08-02 04:15:00 +00003277static PyObject *
3278wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3279{
3280 hashfunc func = (hashfunc)wrapped;
3281 long res;
3282
3283 if (!PyArg_ParseTuple(args, ""))
3284 return NULL;
3285 res = (*func)(self);
3286 if (res == -1 && PyErr_Occurred())
3287 return NULL;
3288 return PyInt_FromLong(res);
3289}
3290
Tim Peters6d6c1a32001-08-02 04:15:00 +00003291static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003292wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003293{
3294 ternaryfunc func = (ternaryfunc)wrapped;
3295
Guido van Rossumc8e56452001-10-22 00:43:43 +00003296 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003297}
3298
Tim Peters6d6c1a32001-08-02 04:15:00 +00003299static PyObject *
3300wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3301{
3302 richcmpfunc func = (richcmpfunc)wrapped;
3303 PyObject *other;
3304
3305 if (!PyArg_ParseTuple(args, "O", &other))
3306 return NULL;
3307 return (*func)(self, other, op);
3308}
3309
3310#undef RICHCMP_WRAPPER
3311#define RICHCMP_WRAPPER(NAME, OP) \
3312static PyObject * \
3313richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3314{ \
3315 return wrap_richcmpfunc(self, args, wrapped, OP); \
3316}
3317
Jack Jansen8e938b42001-08-08 15:29:49 +00003318RICHCMP_WRAPPER(lt, Py_LT)
3319RICHCMP_WRAPPER(le, Py_LE)
3320RICHCMP_WRAPPER(eq, Py_EQ)
3321RICHCMP_WRAPPER(ne, Py_NE)
3322RICHCMP_WRAPPER(gt, Py_GT)
3323RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324
Tim Peters6d6c1a32001-08-02 04:15:00 +00003325static PyObject *
3326wrap_next(PyObject *self, PyObject *args, void *wrapped)
3327{
3328 unaryfunc func = (unaryfunc)wrapped;
3329 PyObject *res;
3330
3331 if (!PyArg_ParseTuple(args, ""))
3332 return NULL;
3333 res = (*func)(self);
3334 if (res == NULL && !PyErr_Occurred())
3335 PyErr_SetNone(PyExc_StopIteration);
3336 return res;
3337}
3338
Tim Peters6d6c1a32001-08-02 04:15:00 +00003339static PyObject *
3340wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3341{
3342 descrgetfunc func = (descrgetfunc)wrapped;
3343 PyObject *obj;
3344 PyObject *type = NULL;
3345
3346 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3347 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003348 return (*func)(self, obj, type);
3349}
3350
Tim Peters6d6c1a32001-08-02 04:15:00 +00003351static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003352wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003353{
3354 descrsetfunc func = (descrsetfunc)wrapped;
3355 PyObject *obj, *value;
3356 int ret;
3357
3358 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3359 return NULL;
3360 ret = (*func)(self, obj, value);
3361 if (ret < 0)
3362 return NULL;
3363 Py_INCREF(Py_None);
3364 return Py_None;
3365}
Guido van Rossum22b13872002-08-06 21:41:44 +00003366
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003367static PyObject *
3368wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3369{
3370 descrsetfunc func = (descrsetfunc)wrapped;
3371 PyObject *obj;
3372 int ret;
3373
3374 if (!PyArg_ParseTuple(args, "O", &obj))
3375 return NULL;
3376 ret = (*func)(self, obj, NULL);
3377 if (ret < 0)
3378 return NULL;
3379 Py_INCREF(Py_None);
3380 return Py_None;
3381}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003382
Tim Peters6d6c1a32001-08-02 04:15:00 +00003383static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003384wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003385{
3386 initproc func = (initproc)wrapped;
3387
Guido van Rossumc8e56452001-10-22 00:43:43 +00003388 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003389 return NULL;
3390 Py_INCREF(Py_None);
3391 return Py_None;
3392}
3393
Tim Peters6d6c1a32001-08-02 04:15:00 +00003394static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003395tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003396{
Barry Warsaw60f01882001-08-22 19:24:42 +00003397 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003398 PyObject *arg0, *res;
3399
3400 if (self == NULL || !PyType_Check(self))
3401 Py_FatalError("__new__() called with non-type 'self'");
3402 type = (PyTypeObject *)self;
3403 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003404 PyErr_Format(PyExc_TypeError,
3405 "%s.__new__(): not enough arguments",
3406 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003407 return NULL;
3408 }
3409 arg0 = PyTuple_GET_ITEM(args, 0);
3410 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003411 PyErr_Format(PyExc_TypeError,
3412 "%s.__new__(X): X is not a type object (%s)",
3413 type->tp_name,
3414 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003415 return NULL;
3416 }
3417 subtype = (PyTypeObject *)arg0;
3418 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003419 PyErr_Format(PyExc_TypeError,
3420 "%s.__new__(%s): %s is not a subtype of %s",
3421 type->tp_name,
3422 subtype->tp_name,
3423 subtype->tp_name,
3424 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003425 return NULL;
3426 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003427
3428 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003429 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003430 most derived base that's not a heap type is this type. */
3431 staticbase = subtype;
3432 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3433 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003434 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003435 PyErr_Format(PyExc_TypeError,
3436 "%s.__new__(%s) is not safe, use %s.__new__()",
3437 type->tp_name,
3438 subtype->tp_name,
3439 staticbase == NULL ? "?" : staticbase->tp_name);
3440 return NULL;
3441 }
3442
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003443 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3444 if (args == NULL)
3445 return NULL;
3446 res = type->tp_new(subtype, args, kwds);
3447 Py_DECREF(args);
3448 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003449}
3450
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003451static struct PyMethodDef tp_new_methoddef[] = {
3452 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003453 PyDoc_STR("T.__new__(S, ...) -> "
3454 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003455 {0}
3456};
3457
3458static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003459add_tp_new_wrapper(PyTypeObject *type)
3460{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003461 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003462
Guido van Rossum687ae002001-10-15 22:03:32 +00003463 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003464 return 0;
3465 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003466 if (func == NULL)
3467 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003468 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003469}
3470
Guido van Rossumf040ede2001-08-07 16:40:56 +00003471/* Slot wrappers that call the corresponding __foo__ slot. See comments
3472 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473
Guido van Rossumdc91b992001-08-08 22:26:22 +00003474#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003475static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003476FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003477{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003478 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003479 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480}
3481
Guido van Rossumdc91b992001-08-08 22:26:22 +00003482#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003484FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003485{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003486 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003487 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003488}
3489
Guido van Rossumdc91b992001-08-08 22:26:22 +00003490
3491#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003492static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003493FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003494{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003495 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003496 int do_other = self->ob_type != other->ob_type && \
3497 other->ob_type->tp_as_number != NULL && \
3498 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003499 if (self->ob_type->tp_as_number != NULL && \
3500 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3501 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003502 if (do_other && \
3503 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
3504 r = call_maybe( \
3505 other, ROPSTR, &rcache_str, "(O)", self); \
3506 if (r != Py_NotImplemented) \
3507 return r; \
3508 Py_DECREF(r); \
3509 do_other = 0; \
3510 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003511 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003512 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003513 if (r != Py_NotImplemented || \
3514 other->ob_type == self->ob_type) \
3515 return r; \
3516 Py_DECREF(r); \
3517 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003518 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003519 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003520 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003521 } \
3522 Py_INCREF(Py_NotImplemented); \
3523 return Py_NotImplemented; \
3524}
3525
3526#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3527 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3528
3529#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3530static PyObject * \
3531FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3532{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003533 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003534 return call_method(self, OPSTR, &cache_str, \
3535 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003536}
3537
3538static int
3539slot_sq_length(PyObject *self)
3540{
Guido van Rossum2730b132001-08-28 18:22:14 +00003541 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003542 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003543 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003544
3545 if (res == NULL)
3546 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003547 len = (int)PyInt_AsLong(res);
3548 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003549 if (len == -1 && PyErr_Occurred())
3550 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003551 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003552 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003553 "__len__() should return >= 0");
3554 return -1;
3555 }
Guido van Rossum26111622001-10-01 16:42:49 +00003556 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003557}
3558
Guido van Rossumdc91b992001-08-08 22:26:22 +00003559SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3560SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003561
3562/* Super-optimized version of slot_sq_item.
3563 Other slots could do the same... */
3564static PyObject *
3565slot_sq_item(PyObject *self, int i)
3566{
3567 static PyObject *getitem_str;
3568 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3569 descrgetfunc f;
3570
3571 if (getitem_str == NULL) {
3572 getitem_str = PyString_InternFromString("__getitem__");
3573 if (getitem_str == NULL)
3574 return NULL;
3575 }
3576 func = _PyType_Lookup(self->ob_type, getitem_str);
3577 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003578 if ((f = func->ob_type->tp_descr_get) == NULL)
3579 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003580 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003581 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003582 if (func == NULL) {
3583 return NULL;
3584 }
3585 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003586 ival = PyInt_FromLong(i);
3587 if (ival != NULL) {
3588 args = PyTuple_New(1);
3589 if (args != NULL) {
3590 PyTuple_SET_ITEM(args, 0, ival);
3591 retval = PyObject_Call(func, args, NULL);
3592 Py_XDECREF(args);
3593 Py_XDECREF(func);
3594 return retval;
3595 }
3596 }
3597 }
3598 else {
3599 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3600 }
3601 Py_XDECREF(args);
3602 Py_XDECREF(ival);
3603 Py_XDECREF(func);
3604 return NULL;
3605}
3606
Guido van Rossumdc91b992001-08-08 22:26:22 +00003607SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608
3609static int
3610slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3611{
3612 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003613 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003614
3615 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003616 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003617 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003618 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003619 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003620 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003621 if (res == NULL)
3622 return -1;
3623 Py_DECREF(res);
3624 return 0;
3625}
3626
3627static int
3628slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3629{
3630 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003631 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632
3633 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003634 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003635 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003636 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003637 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003638 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639 if (res == NULL)
3640 return -1;
3641 Py_DECREF(res);
3642 return 0;
3643}
3644
3645static int
3646slot_sq_contains(PyObject *self, PyObject *value)
3647{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003648 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003649 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003650
Guido van Rossum55f20992001-10-01 17:18:22 +00003651 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003652
3653 if (func != NULL) {
3654 args = Py_BuildValue("(O)", value);
3655 if (args == NULL)
3656 res = NULL;
3657 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003658 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003659 Py_DECREF(args);
3660 }
3661 Py_DECREF(func);
3662 if (res == NULL)
3663 return -1;
3664 return PyObject_IsTrue(res);
3665 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003666 else if (PyErr_Occurred())
3667 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003668 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003669 return _PySequence_IterSearch(self, value,
3670 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003671 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003672}
3673
Guido van Rossumdc91b992001-08-08 22:26:22 +00003674SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3675SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676
3677#define slot_mp_length slot_sq_length
3678
Guido van Rossumdc91b992001-08-08 22:26:22 +00003679SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003680
3681static int
3682slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3683{
3684 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003685 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003686
3687 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003688 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003689 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003690 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003691 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003692 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693 if (res == NULL)
3694 return -1;
3695 Py_DECREF(res);
3696 return 0;
3697}
3698
Guido van Rossumdc91b992001-08-08 22:26:22 +00003699SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3700SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3701SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3702SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3703SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3704SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3705
Jeremy Hylton938ace62002-07-17 16:30:39 +00003706static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003707
3708SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3709 nb_power, "__pow__", "__rpow__")
3710
3711static PyObject *
3712slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3713{
Guido van Rossum2730b132001-08-28 18:22:14 +00003714 static PyObject *pow_str;
3715
Guido van Rossumdc91b992001-08-08 22:26:22 +00003716 if (modulus == Py_None)
3717 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003718 /* Three-arg power doesn't use __rpow__. But ternary_op
3719 can call this when the second argument's type uses
3720 slot_nb_power, so check before calling self.__pow__. */
3721 if (self->ob_type->tp_as_number != NULL &&
3722 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3723 return call_method(self, "__pow__", &pow_str,
3724 "(OO)", other, modulus);
3725 }
3726 Py_INCREF(Py_NotImplemented);
3727 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003728}
3729
3730SLOT0(slot_nb_negative, "__neg__")
3731SLOT0(slot_nb_positive, "__pos__")
3732SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003733
3734static int
3735slot_nb_nonzero(PyObject *self)
3736{
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003737 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003738 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003739
Guido van Rossum55f20992001-10-01 17:18:22 +00003740 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003741 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003742 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003743 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003744 func = lookup_maybe(self, "__len__", &len_str);
3745 if (func == NULL) {
3746 if (PyErr_Occurred())
3747 return -1;
3748 else
3749 return 1;
3750 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003751 }
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003752 args = res = PyTuple_New(0);
3753 if (args != NULL) {
3754 res = PyObject_Call(func, args, NULL);
3755 Py_DECREF(args);
3756 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003757 Py_DECREF(func);
3758 if (res == NULL)
3759 return -1;
3760 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003761}
3762
Guido van Rossumdc91b992001-08-08 22:26:22 +00003763SLOT0(slot_nb_invert, "__invert__")
3764SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3765SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3766SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3767SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3768SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003769
3770static int
3771slot_nb_coerce(PyObject **a, PyObject **b)
3772{
3773 static PyObject *coerce_str;
3774 PyObject *self = *a, *other = *b;
3775
3776 if (self->ob_type->tp_as_number != NULL &&
3777 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3778 PyObject *r;
3779 r = call_maybe(
3780 self, "__coerce__", &coerce_str, "(O)", other);
3781 if (r == NULL)
3782 return -1;
3783 if (r == Py_NotImplemented) {
3784 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003785 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003786 else {
3787 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3788 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003789 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003790 Py_DECREF(r);
3791 return -1;
3792 }
3793 *a = PyTuple_GET_ITEM(r, 0);
3794 Py_INCREF(*a);
3795 *b = PyTuple_GET_ITEM(r, 1);
3796 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003797 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003798 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003799 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003800 }
3801 if (other->ob_type->tp_as_number != NULL &&
3802 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3803 PyObject *r;
3804 r = call_maybe(
3805 other, "__coerce__", &coerce_str, "(O)", self);
3806 if (r == NULL)
3807 return -1;
3808 if (r == Py_NotImplemented) {
3809 Py_DECREF(r);
3810 return 1;
3811 }
3812 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3813 PyErr_SetString(PyExc_TypeError,
3814 "__coerce__ didn't return a 2-tuple");
3815 Py_DECREF(r);
3816 return -1;
3817 }
3818 *a = PyTuple_GET_ITEM(r, 1);
3819 Py_INCREF(*a);
3820 *b = PyTuple_GET_ITEM(r, 0);
3821 Py_INCREF(*b);
3822 Py_DECREF(r);
3823 return 0;
3824 }
3825 return 1;
3826}
3827
Guido van Rossumdc91b992001-08-08 22:26:22 +00003828SLOT0(slot_nb_int, "__int__")
3829SLOT0(slot_nb_long, "__long__")
3830SLOT0(slot_nb_float, "__float__")
3831SLOT0(slot_nb_oct, "__oct__")
3832SLOT0(slot_nb_hex, "__hex__")
3833SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3834SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3835SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3836SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3837SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003838SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003839SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3840SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3841SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3842SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3843SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3844SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3845 "__floordiv__", "__rfloordiv__")
3846SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3847SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3848SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003849
3850static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003851half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003852{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003853 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003854 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003855 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003856
Guido van Rossum60718732001-08-28 17:47:51 +00003857 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003858 if (func == NULL) {
3859 PyErr_Clear();
3860 }
3861 else {
3862 args = Py_BuildValue("(O)", other);
3863 if (args == NULL)
3864 res = NULL;
3865 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003866 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003867 Py_DECREF(args);
3868 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003869 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003870 if (res != Py_NotImplemented) {
3871 if (res == NULL)
3872 return -2;
3873 c = PyInt_AsLong(res);
3874 Py_DECREF(res);
3875 if (c == -1 && PyErr_Occurred())
3876 return -2;
3877 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3878 }
3879 Py_DECREF(res);
3880 }
3881 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882}
3883
Guido van Rossumab3b0342001-09-18 20:38:53 +00003884/* This slot is published for the benefit of try_3way_compare in object.c */
3885int
3886_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003887{
3888 int c;
3889
Guido van Rossumab3b0342001-09-18 20:38:53 +00003890 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003891 c = half_compare(self, other);
3892 if (c <= 1)
3893 return c;
3894 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003895 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003896 c = half_compare(other, self);
3897 if (c < -1)
3898 return -2;
3899 if (c <= 1)
3900 return -c;
3901 }
3902 return (void *)self < (void *)other ? -1 :
3903 (void *)self > (void *)other ? 1 : 0;
3904}
3905
3906static PyObject *
3907slot_tp_repr(PyObject *self)
3908{
3909 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003910 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003911
Guido van Rossum60718732001-08-28 17:47:51 +00003912 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003913 if (func != NULL) {
3914 res = PyEval_CallObject(func, NULL);
3915 Py_DECREF(func);
3916 return res;
3917 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003918 PyErr_Clear();
3919 return PyString_FromFormat("<%s object at %p>",
3920 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003921}
3922
3923static PyObject *
3924slot_tp_str(PyObject *self)
3925{
3926 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003927 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003928
Guido van Rossum60718732001-08-28 17:47:51 +00003929 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003930 if (func != NULL) {
3931 res = PyEval_CallObject(func, NULL);
3932 Py_DECREF(func);
3933 return res;
3934 }
3935 else {
3936 PyErr_Clear();
3937 return slot_tp_repr(self);
3938 }
3939}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003940
3941static long
3942slot_tp_hash(PyObject *self)
3943{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003944 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003945 static PyObject *hash_str, *eq_str, *cmp_str;
3946
Tim Peters6d6c1a32001-08-02 04:15:00 +00003947 long h;
3948
Guido van Rossum60718732001-08-28 17:47:51 +00003949 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003950
3951 if (func != NULL) {
3952 res = PyEval_CallObject(func, NULL);
3953 Py_DECREF(func);
3954 if (res == NULL)
3955 return -1;
3956 h = PyInt_AsLong(res);
3957 }
3958 else {
3959 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003960 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003961 if (func == NULL) {
3962 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003963 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003964 }
3965 if (func != NULL) {
3966 Py_DECREF(func);
3967 PyErr_SetString(PyExc_TypeError, "unhashable type");
3968 return -1;
3969 }
3970 PyErr_Clear();
3971 h = _Py_HashPointer((void *)self);
3972 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973 if (h == -1 && !PyErr_Occurred())
3974 h = -2;
3975 return h;
3976}
3977
3978static PyObject *
3979slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3980{
Guido van Rossum60718732001-08-28 17:47:51 +00003981 static PyObject *call_str;
3982 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003983 PyObject *res;
3984
3985 if (meth == NULL)
3986 return NULL;
3987 res = PyObject_Call(meth, args, kwds);
3988 Py_DECREF(meth);
3989 return res;
3990}
3991
Guido van Rossum14a6f832001-10-17 13:59:09 +00003992/* There are two slot dispatch functions for tp_getattro.
3993
3994 - slot_tp_getattro() is used when __getattribute__ is overridden
3995 but no __getattr__ hook is present;
3996
3997 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3998
Guido van Rossumc334df52002-04-04 23:44:47 +00003999 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4000 detects the absence of __getattr__ and then installs the simpler slot if
4001 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004002
Tim Peters6d6c1a32001-08-02 04:15:00 +00004003static PyObject *
4004slot_tp_getattro(PyObject *self, PyObject *name)
4005{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004006 static PyObject *getattribute_str = NULL;
4007 return call_method(self, "__getattribute__", &getattribute_str,
4008 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004009}
4010
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004011static PyObject *
4012slot_tp_getattr_hook(PyObject *self, PyObject *name)
4013{
4014 PyTypeObject *tp = self->ob_type;
4015 PyObject *getattr, *getattribute, *res;
4016 static PyObject *getattribute_str = NULL;
4017 static PyObject *getattr_str = NULL;
4018
4019 if (getattr_str == NULL) {
4020 getattr_str = PyString_InternFromString("__getattr__");
4021 if (getattr_str == NULL)
4022 return NULL;
4023 }
4024 if (getattribute_str == NULL) {
4025 getattribute_str =
4026 PyString_InternFromString("__getattribute__");
4027 if (getattribute_str == NULL)
4028 return NULL;
4029 }
4030 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004031 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004032 /* No __getattr__ hook: use a simpler dispatcher */
4033 tp->tp_getattro = slot_tp_getattro;
4034 return slot_tp_getattro(self, name);
4035 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004036 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004037 if (getattribute == NULL ||
4038 (getattribute->ob_type == &PyWrapperDescr_Type &&
4039 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4040 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004041 res = PyObject_GenericGetAttr(self, name);
4042 else
4043 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004044 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004045 PyErr_Clear();
4046 res = PyObject_CallFunction(getattr, "OO", self, name);
4047 }
4048 return res;
4049}
4050
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051static int
4052slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4053{
4054 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004055 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004056
4057 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004058 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004059 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004060 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004061 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004062 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004063 if (res == NULL)
4064 return -1;
4065 Py_DECREF(res);
4066 return 0;
4067}
4068
4069/* Map rich comparison operators to their __xx__ namesakes */
4070static char *name_op[] = {
4071 "__lt__",
4072 "__le__",
4073 "__eq__",
4074 "__ne__",
4075 "__gt__",
4076 "__ge__",
4077};
4078
4079static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004080half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004081{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004082 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004083 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004084
Guido van Rossum60718732001-08-28 17:47:51 +00004085 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004086 if (func == NULL) {
4087 PyErr_Clear();
4088 Py_INCREF(Py_NotImplemented);
4089 return Py_NotImplemented;
4090 }
4091 args = Py_BuildValue("(O)", other);
4092 if (args == NULL)
4093 res = NULL;
4094 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004095 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004096 Py_DECREF(args);
4097 }
4098 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004099 return res;
4100}
4101
Guido van Rossumb8f63662001-08-15 23:57:02 +00004102/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4103static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4104
4105static PyObject *
4106slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4107{
4108 PyObject *res;
4109
4110 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4111 res = half_richcompare(self, other, op);
4112 if (res != Py_NotImplemented)
4113 return res;
4114 Py_DECREF(res);
4115 }
4116 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4117 res = half_richcompare(other, self, swapped_op[op]);
4118 if (res != Py_NotImplemented) {
4119 return res;
4120 }
4121 Py_DECREF(res);
4122 }
4123 Py_INCREF(Py_NotImplemented);
4124 return Py_NotImplemented;
4125}
4126
4127static PyObject *
4128slot_tp_iter(PyObject *self)
4129{
4130 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004131 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004132
Guido van Rossum60718732001-08-28 17:47:51 +00004133 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004134 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004135 PyObject *args;
4136 args = res = PyTuple_New(0);
4137 if (args != NULL) {
4138 res = PyObject_Call(func, args, NULL);
4139 Py_DECREF(args);
4140 }
4141 Py_DECREF(func);
4142 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004143 }
4144 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004145 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004146 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004147 PyErr_SetString(PyExc_TypeError,
4148 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004149 return NULL;
4150 }
4151 Py_DECREF(func);
4152 return PySeqIter_New(self);
4153}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004154
4155static PyObject *
4156slot_tp_iternext(PyObject *self)
4157{
Guido van Rossum2730b132001-08-28 18:22:14 +00004158 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004159 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004160}
4161
Guido van Rossum1a493502001-08-17 16:47:50 +00004162static PyObject *
4163slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4164{
4165 PyTypeObject *tp = self->ob_type;
4166 PyObject *get;
4167 static PyObject *get_str = NULL;
4168
4169 if (get_str == NULL) {
4170 get_str = PyString_InternFromString("__get__");
4171 if (get_str == NULL)
4172 return NULL;
4173 }
4174 get = _PyType_Lookup(tp, get_str);
4175 if (get == NULL) {
4176 /* Avoid further slowdowns */
4177 if (tp->tp_descr_get == slot_tp_descr_get)
4178 tp->tp_descr_get = NULL;
4179 Py_INCREF(self);
4180 return self;
4181 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004182 if (obj == NULL)
4183 obj = Py_None;
4184 if (type == NULL)
4185 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004186 return PyObject_CallFunction(get, "OOO", self, obj, type);
4187}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004188
4189static int
4190slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4191{
Guido van Rossum2c252392001-08-24 10:13:31 +00004192 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004193 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004194
4195 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004196 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004197 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004198 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004199 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004200 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201 if (res == NULL)
4202 return -1;
4203 Py_DECREF(res);
4204 return 0;
4205}
4206
4207static int
4208slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4209{
Guido van Rossum60718732001-08-28 17:47:51 +00004210 static PyObject *init_str;
4211 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004212 PyObject *res;
4213
4214 if (meth == NULL)
4215 return -1;
4216 res = PyObject_Call(meth, args, kwds);
4217 Py_DECREF(meth);
4218 if (res == NULL)
4219 return -1;
4220 Py_DECREF(res);
4221 return 0;
4222}
4223
4224static PyObject *
4225slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4226{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004227 static PyObject *new_str;
4228 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004229 PyObject *newargs, *x;
4230 int i, n;
4231
Guido van Rossum7bed2132002-08-08 21:57:53 +00004232 if (new_str == NULL) {
4233 new_str = PyString_InternFromString("__new__");
4234 if (new_str == NULL)
4235 return NULL;
4236 }
4237 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004238 if (func == NULL)
4239 return NULL;
4240 assert(PyTuple_Check(args));
4241 n = PyTuple_GET_SIZE(args);
4242 newargs = PyTuple_New(n+1);
4243 if (newargs == NULL)
4244 return NULL;
4245 Py_INCREF(type);
4246 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4247 for (i = 0; i < n; i++) {
4248 x = PyTuple_GET_ITEM(args, i);
4249 Py_INCREF(x);
4250 PyTuple_SET_ITEM(newargs, i+1, x);
4251 }
4252 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004253 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004254 Py_DECREF(func);
4255 return x;
4256}
4257
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004258static void
4259slot_tp_del(PyObject *self)
4260{
4261 static PyObject *del_str = NULL;
4262 PyObject *del, *res;
4263 PyObject *error_type, *error_value, *error_traceback;
4264
4265 /* Temporarily resurrect the object. */
4266 assert(self->ob_refcnt == 0);
4267 self->ob_refcnt = 1;
4268
4269 /* Save the current exception, if any. */
4270 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4271
4272 /* Execute __del__ method, if any. */
4273 del = lookup_maybe(self, "__del__", &del_str);
4274 if (del != NULL) {
4275 res = PyEval_CallObject(del, NULL);
4276 if (res == NULL)
4277 PyErr_WriteUnraisable(del);
4278 else
4279 Py_DECREF(res);
4280 Py_DECREF(del);
4281 }
4282
4283 /* Restore the saved exception. */
4284 PyErr_Restore(error_type, error_value, error_traceback);
4285
4286 /* Undo the temporary resurrection; can't use DECREF here, it would
4287 * cause a recursive call.
4288 */
4289 assert(self->ob_refcnt > 0);
4290 if (--self->ob_refcnt == 0)
4291 return; /* this is the normal path out */
4292
4293 /* __del__ resurrected it! Make it look like the original Py_DECREF
4294 * never happened.
4295 */
4296 {
4297 int refcnt = self->ob_refcnt;
4298 _Py_NewReference(self);
4299 self->ob_refcnt = refcnt;
4300 }
4301 assert(!PyType_IS_GC(self->ob_type) ||
4302 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4303 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4304 * _Py_NewReference bumped it again, so that's a wash.
4305 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4306 * chain, so no more to do there either.
4307 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4308 * _Py_NewReference bumped tp_allocs: both of those need to be
4309 * undone.
4310 */
4311#ifdef COUNT_ALLOCS
4312 --self->ob_type->tp_frees;
4313 --self->ob_type->tp_allocs;
4314#endif
4315}
4316
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004317
4318/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4319 functions. The offsets here are relative to the 'etype' structure, which
4320 incorporates the additional structures used for numbers, sequences and
4321 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4322 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004323 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4324 terminated with an all-zero entry. (This table is further initialized and
4325 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004326
Guido van Rossum6d204072001-10-21 00:44:31 +00004327typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004328
4329#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004330#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004331#undef ETSLOT
4332#undef SQSLOT
4333#undef MPSLOT
4334#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004335#undef UNSLOT
4336#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004337#undef BINSLOT
4338#undef RBINSLOT
4339
Guido van Rossum6d204072001-10-21 00:44:31 +00004340#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004341 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4342 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004343#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4344 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004345 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004346#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004347 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4348 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004349#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4350 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4351#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4352 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4353#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4354 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4355#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4356 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4357 "x." NAME "() <==> " DOC)
4358#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4359 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4360 "x." NAME "(y) <==> x" DOC "y")
4361#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4362 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4363 "x." NAME "(y) <==> x" DOC "y")
4364#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4365 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4366 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004367
4368static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004369 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4370 "x.__len__() <==> len(x)"),
4371 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4372 "x.__add__(y) <==> x+y"),
4373 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4374 "x.__mul__(n) <==> x*n"),
4375 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4376 "x.__rmul__(n) <==> n*x"),
4377 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4378 "x.__getitem__(y) <==> x[y]"),
4379 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4380 "x.__getslice__(i, j) <==> x[i:j]"),
4381 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4382 "x.__setitem__(i, y) <==> x[i]=y"),
4383 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4384 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004385 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004386 wrap_intintobjargproc,
4387 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4388 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4389 "x.__delslice__(i, j) <==> del x[i:j]"),
4390 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4391 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004392 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004393 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004394 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004395 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004396
Guido van Rossum6d204072001-10-21 00:44:31 +00004397 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4398 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004399 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004400 wrap_binaryfunc,
4401 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004402 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004403 wrap_objobjargproc,
4404 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004405 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004406 wrap_delitem,
4407 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004408
Guido van Rossum6d204072001-10-21 00:44:31 +00004409 BINSLOT("__add__", nb_add, slot_nb_add,
4410 "+"),
4411 RBINSLOT("__radd__", nb_add, slot_nb_add,
4412 "+"),
4413 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4414 "-"),
4415 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4416 "-"),
4417 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4418 "*"),
4419 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4420 "*"),
4421 BINSLOT("__div__", nb_divide, slot_nb_divide,
4422 "/"),
4423 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4424 "/"),
4425 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4426 "%"),
4427 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4428 "%"),
4429 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4430 "divmod(x, y)"),
4431 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4432 "divmod(y, x)"),
4433 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4434 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4435 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4436 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4437 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4438 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4439 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4440 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004441 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004442 "x != 0"),
4443 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4444 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4445 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4446 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4447 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4448 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4449 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4450 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4451 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4452 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4453 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4454 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4455 "x.__coerce__(y) <==> coerce(x, y)"),
4456 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4457 "int(x)"),
4458 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4459 "long(x)"),
4460 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4461 "float(x)"),
4462 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4463 "oct(x)"),
4464 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4465 "hex(x)"),
4466 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4467 wrap_binaryfunc, "+"),
4468 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4469 wrap_binaryfunc, "-"),
4470 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4471 wrap_binaryfunc, "*"),
4472 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4473 wrap_binaryfunc, "/"),
4474 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4475 wrap_binaryfunc, "%"),
4476 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004477 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004478 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4479 wrap_binaryfunc, "<<"),
4480 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4481 wrap_binaryfunc, ">>"),
4482 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4483 wrap_binaryfunc, "&"),
4484 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4485 wrap_binaryfunc, "^"),
4486 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4487 wrap_binaryfunc, "|"),
4488 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4489 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4490 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4491 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4492 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4493 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4494 IBSLOT("__itruediv__", nb_inplace_true_divide,
4495 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004496
Guido van Rossum6d204072001-10-21 00:44:31 +00004497 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4498 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004499 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004500 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4501 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004502 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004503 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4504 "x.__cmp__(y) <==> cmp(x,y)"),
4505 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4506 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004507 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4508 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004509 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004510 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4511 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4512 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4513 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4514 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4515 "x.__setattr__('name', value) <==> x.name = value"),
4516 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4517 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4518 "x.__delattr__('name') <==> del x.name"),
4519 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4520 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4521 "x.__lt__(y) <==> x<y"),
4522 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4523 "x.__le__(y) <==> x<=y"),
4524 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4525 "x.__eq__(y) <==> x==y"),
4526 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4527 "x.__ne__(y) <==> x!=y"),
4528 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4529 "x.__gt__(y) <==> x>y"),
4530 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4531 "x.__ge__(y) <==> x>=y"),
4532 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4533 "x.__iter__() <==> iter(x)"),
4534 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4535 "x.next() -> the next value, or raise StopIteration"),
4536 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4537 "descr.__get__(obj[, type]) -> value"),
4538 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4539 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004540 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4541 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004542 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004543 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004544 "see x.__class__.__doc__ for signature",
4545 PyWrapperFlag_KEYWORDS),
4546 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004547 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004548 {NULL}
4549};
4550
Guido van Rossumc334df52002-04-04 23:44:47 +00004551/* Given a type pointer and an offset gotten from a slotdef entry, return a
4552 pointer to the actual slot. This is not quite the same as simply adding
4553 the offset to the type pointer, since it takes care to indirect through the
4554 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4555 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004556static void **
4557slotptr(PyTypeObject *type, int offset)
4558{
4559 char *ptr;
4560
Guido van Rossum09638c12002-06-13 19:17:46 +00004561 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004562 assert(offset >= 0);
4563 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004564 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004565 ptr = (void *)type->tp_as_sequence;
4566 offset -= offsetof(etype, as_sequence);
4567 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004568 else if (offset >= offsetof(etype, as_mapping)) {
4569 ptr = (void *)type->tp_as_mapping;
4570 offset -= offsetof(etype, as_mapping);
4571 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004572 else if (offset >= offsetof(etype, as_number)) {
4573 ptr = (void *)type->tp_as_number;
4574 offset -= offsetof(etype, as_number);
4575 }
4576 else {
4577 ptr = (void *)type;
4578 }
4579 if (ptr != NULL)
4580 ptr += offset;
4581 return (void **)ptr;
4582}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004583
Guido van Rossumc334df52002-04-04 23:44:47 +00004584/* Length of array of slotdef pointers used to store slots with the
4585 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4586 the same __name__, for any __name__. Since that's a static property, it is
4587 appropriate to declare fixed-size arrays for this. */
4588#define MAX_EQUIV 10
4589
4590/* Return a slot pointer for a given name, but ONLY if the attribute has
4591 exactly one slot function. The name must be an interned string. */
4592static void **
4593resolve_slotdups(PyTypeObject *type, PyObject *name)
4594{
4595 /* XXX Maybe this could be optimized more -- but is it worth it? */
4596
4597 /* pname and ptrs act as a little cache */
4598 static PyObject *pname;
4599 static slotdef *ptrs[MAX_EQUIV];
4600 slotdef *p, **pp;
4601 void **res, **ptr;
4602
4603 if (pname != name) {
4604 /* Collect all slotdefs that match name into ptrs. */
4605 pname = name;
4606 pp = ptrs;
4607 for (p = slotdefs; p->name_strobj; p++) {
4608 if (p->name_strobj == name)
4609 *pp++ = p;
4610 }
4611 *pp = NULL;
4612 }
4613
4614 /* Look in all matching slots of the type; if exactly one of these has
4615 a filled-in slot, return its value. Otherwise return NULL. */
4616 res = NULL;
4617 for (pp = ptrs; *pp; pp++) {
4618 ptr = slotptr(type, (*pp)->offset);
4619 if (ptr == NULL || *ptr == NULL)
4620 continue;
4621 if (res != NULL)
4622 return NULL;
4623 res = ptr;
4624 }
4625 return res;
4626}
4627
4628/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4629 does some incredibly complex thinking and then sticks something into the
4630 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4631 interests, and then stores a generic wrapper or a specific function into
4632 the slot.) Return a pointer to the next slotdef with a different offset,
4633 because that's convenient for fixup_slot_dispatchers(). */
4634static slotdef *
4635update_one_slot(PyTypeObject *type, slotdef *p)
4636{
4637 PyObject *descr;
4638 PyWrapperDescrObject *d;
4639 void *generic = NULL, *specific = NULL;
4640 int use_generic = 0;
4641 int offset = p->offset;
4642 void **ptr = slotptr(type, offset);
4643
4644 if (ptr == NULL) {
4645 do {
4646 ++p;
4647 } while (p->offset == offset);
4648 return p;
4649 }
4650 do {
4651 descr = _PyType_Lookup(type, p->name_strobj);
4652 if (descr == NULL)
4653 continue;
4654 if (descr->ob_type == &PyWrapperDescr_Type) {
4655 void **tptr = resolve_slotdups(type, p->name_strobj);
4656 if (tptr == NULL || tptr == ptr)
4657 generic = p->function;
4658 d = (PyWrapperDescrObject *)descr;
4659 if (d->d_base->wrapper == p->wrapper &&
4660 PyType_IsSubtype(type, d->d_type))
4661 {
4662 if (specific == NULL ||
4663 specific == d->d_wrapped)
4664 specific = d->d_wrapped;
4665 else
4666 use_generic = 1;
4667 }
4668 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004669 else if (descr->ob_type == &PyCFunction_Type &&
4670 PyCFunction_GET_FUNCTION(descr) ==
4671 (PyCFunction)tp_new_wrapper &&
4672 strcmp(p->name, "__new__") == 0)
4673 {
4674 /* The __new__ wrapper is not a wrapper descriptor,
4675 so must be special-cased differently.
4676 If we don't do this, creating an instance will
4677 always use slot_tp_new which will look up
4678 __new__ in the MRO which will call tp_new_wrapper
4679 which will look through the base classes looking
4680 for a static base and call its tp_new (usually
4681 PyType_GenericNew), after performing various
4682 sanity checks and constructing a new argument
4683 list. Cut all that nonsense short -- this speeds
4684 up instance creation tremendously. */
4685 specific = type->tp_new;
4686 /* XXX I'm not 100% sure that there isn't a hole
4687 in this reasoning that requires additional
4688 sanity checks. I'll buy the first person to
4689 point out a bug in this reasoning a beer. */
4690 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004691 else {
4692 use_generic = 1;
4693 generic = p->function;
4694 }
4695 } while ((++p)->offset == offset);
4696 if (specific && !use_generic)
4697 *ptr = specific;
4698 else
4699 *ptr = generic;
4700 return p;
4701}
4702
Guido van Rossum22b13872002-08-06 21:41:44 +00004703static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004704 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004705
Guido van Rossumc334df52002-04-04 23:44:47 +00004706/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4707 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004708static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004709update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004710{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004711 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004712
Guido van Rossumc334df52002-04-04 23:44:47 +00004713 for (pp = pp0; *pp; pp++)
4714 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004715 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004716}
4717
Guido van Rossumc334df52002-04-04 23:44:47 +00004718/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4719 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004720static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004721recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004722{
4723 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004724 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004725 int i, n;
4726
4727 subclasses = type->tp_subclasses;
4728 if (subclasses == NULL)
4729 return 0;
4730 assert(PyList_Check(subclasses));
4731 n = PyList_GET_SIZE(subclasses);
4732 for (i = 0; i < n; i++) {
4733 ref = PyList_GET_ITEM(subclasses, i);
4734 assert(PyWeakref_CheckRef(ref));
4735 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004736 assert(subclass != NULL);
4737 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004738 continue;
4739 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004740 /* Avoid recursing down into unaffected classes */
4741 dict = subclass->tp_dict;
4742 if (dict != NULL && PyDict_Check(dict) &&
4743 PyDict_GetItem(dict, name) != NULL)
4744 continue;
4745 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004746 return -1;
4747 }
4748 return 0;
4749}
4750
Guido van Rossumc334df52002-04-04 23:44:47 +00004751/* Comparison function for qsort() to compare slotdefs by their offset, and
4752 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004753static int
4754slotdef_cmp(const void *aa, const void *bb)
4755{
4756 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4757 int c = a->offset - b->offset;
4758 if (c != 0)
4759 return c;
4760 else
4761 return a - b;
4762}
4763
Guido van Rossumc334df52002-04-04 23:44:47 +00004764/* Initialize the slotdefs table by adding interned string objects for the
4765 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004766static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004767init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004768{
4769 slotdef *p;
4770 static int initialized = 0;
4771
4772 if (initialized)
4773 return;
4774 for (p = slotdefs; p->name; p++) {
4775 p->name_strobj = PyString_InternFromString(p->name);
4776 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004777 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004778 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004779 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4780 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004781 initialized = 1;
4782}
4783
Guido van Rossumc334df52002-04-04 23:44:47 +00004784/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004785static int
4786update_slot(PyTypeObject *type, PyObject *name)
4787{
Guido van Rossumc334df52002-04-04 23:44:47 +00004788 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004789 slotdef *p;
4790 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004791 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004792
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004793 init_slotdefs();
4794 pp = ptrs;
4795 for (p = slotdefs; p->name; p++) {
4796 /* XXX assume name is interned! */
4797 if (p->name_strobj == name)
4798 *pp++ = p;
4799 }
4800 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004801 for (pp = ptrs; *pp; pp++) {
4802 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004803 offset = p->offset;
4804 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004805 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004806 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004807 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004808 if (ptrs[0] == NULL)
4809 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004810 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004811}
4812
Guido van Rossumc334df52002-04-04 23:44:47 +00004813/* Store the proper functions in the slot dispatches at class (type)
4814 definition time, based upon which operations the class overrides in its
4815 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004816static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004817fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004818{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004819 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004820
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004821 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004822 for (p = slotdefs; p->name; )
4823 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004824}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004825
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004826static void
4827update_all_slots(PyTypeObject* type)
4828{
4829 slotdef *p;
4830
4831 init_slotdefs();
4832 for (p = slotdefs; p->name; p++) {
4833 /* update_slot returns int but can't actually fail */
4834 update_slot(type, p->name_strobj);
4835 }
4836}
4837
Guido van Rossum6d204072001-10-21 00:44:31 +00004838/* This function is called by PyType_Ready() to populate the type's
4839 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004840 function slot (like tp_repr) that's defined in the type, one or more
4841 corresponding descriptors are added in the type's tp_dict dictionary
4842 under the appropriate name (like __repr__). Some function slots
4843 cause more than one descriptor to be added (for example, the nb_add
4844 slot adds both __add__ and __radd__ descriptors) and some function
4845 slots compete for the same descriptor (for example both sq_item and
4846 mp_subscript generate a __getitem__ descriptor).
4847
4848 In the latter case, the first slotdef entry encoutered wins. Since
4849 slotdef entries are sorted by the offset of the slot in the etype
4850 struct, this gives us some control over disambiguating between
4851 competing slots: the members of struct etype are listed from most
4852 general to least general, so the most general slot is preferred. In
4853 particular, because as_mapping comes before as_sequence, for a type
4854 that defines both mp_subscript and sq_item, mp_subscript wins.
4855
4856 This only adds new descriptors and doesn't overwrite entries in
4857 tp_dict that were previously defined. The descriptors contain a
4858 reference to the C function they must call, so that it's safe if they
4859 are copied into a subtype's __dict__ and the subtype has a different
4860 C function in its slot -- calling the method defined by the
4861 descriptor will call the C function that was used to create it,
4862 rather than the C function present in the slot when it is called.
4863 (This is important because a subtype may have a C function in the
4864 slot that calls the method from the dictionary, and we want to avoid
4865 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004866
4867static int
4868add_operators(PyTypeObject *type)
4869{
4870 PyObject *dict = type->tp_dict;
4871 slotdef *p;
4872 PyObject *descr;
4873 void **ptr;
4874
4875 init_slotdefs();
4876 for (p = slotdefs; p->name; p++) {
4877 if (p->wrapper == NULL)
4878 continue;
4879 ptr = slotptr(type, p->offset);
4880 if (!ptr || !*ptr)
4881 continue;
4882 if (PyDict_GetItem(dict, p->name_strobj))
4883 continue;
4884 descr = PyDescr_NewWrapper(type, p, *ptr);
4885 if (descr == NULL)
4886 return -1;
4887 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4888 return -1;
4889 Py_DECREF(descr);
4890 }
4891 if (type->tp_new != NULL) {
4892 if (add_tp_new_wrapper(type) < 0)
4893 return -1;
4894 }
4895 return 0;
4896}
4897
Guido van Rossum705f0f52001-08-24 16:47:00 +00004898
4899/* Cooperative 'super' */
4900
4901typedef struct {
4902 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004903 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004904 PyObject *obj;
4905} superobject;
4906
Guido van Rossum6f799372001-09-20 20:46:19 +00004907static PyMemberDef super_members[] = {
4908 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4909 "the class invoking super()"},
4910 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4911 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004912 {0}
4913};
4914
Guido van Rossum705f0f52001-08-24 16:47:00 +00004915static void
4916super_dealloc(PyObject *self)
4917{
4918 superobject *su = (superobject *)self;
4919
Guido van Rossum048eb752001-10-02 21:24:57 +00004920 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004921 Py_XDECREF(su->obj);
4922 Py_XDECREF(su->type);
4923 self->ob_type->tp_free(self);
4924}
4925
4926static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004927super_repr(PyObject *self)
4928{
4929 superobject *su = (superobject *)self;
4930
4931 if (su->obj)
4932 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004933 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004934 su->type ? su->type->tp_name : "NULL",
4935 su->obj->ob_type->tp_name);
4936 else
4937 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004938 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004939 su->type ? su->type->tp_name : "NULL");
4940}
4941
4942static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004943super_getattro(PyObject *self, PyObject *name)
4944{
4945 superobject *su = (superobject *)self;
4946
4947 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004948 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004949 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004950 descrgetfunc f;
4951 int i, n;
4952
Guido van Rossum155db9a2002-04-02 17:53:47 +00004953 starttype = su->obj->ob_type;
4954 mro = starttype->tp_mro;
4955
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004956 if (mro == NULL)
4957 n = 0;
4958 else {
4959 assert(PyTuple_Check(mro));
4960 n = PyTuple_GET_SIZE(mro);
4961 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004962 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004963 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004964 break;
4965 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004966 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004967 starttype = (PyTypeObject *)(su->obj);
4968 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004969 if (mro == NULL)
4970 n = 0;
4971 else {
4972 assert(PyTuple_Check(mro));
4973 n = PyTuple_GET_SIZE(mro);
4974 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004975 for (i = 0; i < n; i++) {
4976 if ((PyObject *)(su->type) ==
4977 PyTuple_GET_ITEM(mro, i))
4978 break;
4979 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004980 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004981 i++;
4982 res = NULL;
4983 for (; i < n; i++) {
4984 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004985 if (PyType_Check(tmp))
4986 dict = ((PyTypeObject *)tmp)->tp_dict;
4987 else if (PyClass_Check(tmp))
4988 dict = ((PyClassObject *)tmp)->cl_dict;
4989 else
4990 continue;
4991 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004992 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004993 Py_INCREF(res);
4994 f = res->ob_type->tp_descr_get;
4995 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004996 tmp = f(res, su->obj,
4997 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004998 Py_DECREF(res);
4999 res = tmp;
5000 }
5001 return res;
5002 }
5003 }
5004 }
5005 return PyObject_GenericGetAttr(self, name);
5006}
5007
Guido van Rossum5b443c62001-12-03 15:38:28 +00005008static int
5009supercheck(PyTypeObject *type, PyObject *obj)
5010{
5011 if (!PyType_IsSubtype(obj->ob_type, type) &&
5012 !(PyType_Check(obj) &&
5013 PyType_IsSubtype((PyTypeObject *)obj, type))) {
5014 PyErr_SetString(PyExc_TypeError,
5015 "super(type, obj): "
5016 "obj must be an instance or subtype of type");
5017 return -1;
5018 }
5019 else
5020 return 0;
5021}
5022
Guido van Rossum705f0f52001-08-24 16:47:00 +00005023static PyObject *
5024super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5025{
5026 superobject *su = (superobject *)self;
5027 superobject *new;
5028
5029 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5030 /* Not binding to an object, or already bound */
5031 Py_INCREF(self);
5032 return self;
5033 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005034 if (su->ob_type != &PySuper_Type)
5035 /* If su is an instance of a subclass of super,
5036 call its type */
5037 return PyObject_CallFunction((PyObject *)su->ob_type,
5038 "OO", su->type, obj);
5039 else {
5040 /* Inline the common case */
5041 if (supercheck(su->type, obj) < 0)
5042 return NULL;
5043 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5044 NULL, NULL);
5045 if (new == NULL)
5046 return NULL;
5047 Py_INCREF(su->type);
5048 Py_INCREF(obj);
5049 new->type = su->type;
5050 new->obj = obj;
5051 return (PyObject *)new;
5052 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005053}
5054
5055static int
5056super_init(PyObject *self, PyObject *args, PyObject *kwds)
5057{
5058 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005059 PyTypeObject *type;
5060 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005061
5062 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5063 return -1;
5064 if (obj == Py_None)
5065 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005066 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005067 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005068 Py_INCREF(type);
5069 Py_XINCREF(obj);
5070 su->type = type;
5071 su->obj = obj;
5072 return 0;
5073}
5074
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005075PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005076"super(type) -> unbound super object\n"
5077"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005078"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005079"Typical use to call a cooperative superclass method:\n"
5080"class C(B):\n"
5081" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005082" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005083
Guido van Rossum048eb752001-10-02 21:24:57 +00005084static int
5085super_traverse(PyObject *self, visitproc visit, void *arg)
5086{
5087 superobject *su = (superobject *)self;
5088 int err;
5089
5090#define VISIT(SLOT) \
5091 if (SLOT) { \
5092 err = visit((PyObject *)(SLOT), arg); \
5093 if (err) \
5094 return err; \
5095 }
5096
5097 VISIT(su->obj);
5098 VISIT(su->type);
5099
5100#undef VISIT
5101
5102 return 0;
5103}
5104
Guido van Rossum705f0f52001-08-24 16:47:00 +00005105PyTypeObject PySuper_Type = {
5106 PyObject_HEAD_INIT(&PyType_Type)
5107 0, /* ob_size */
5108 "super", /* tp_name */
5109 sizeof(superobject), /* tp_basicsize */
5110 0, /* tp_itemsize */
5111 /* methods */
5112 super_dealloc, /* tp_dealloc */
5113 0, /* tp_print */
5114 0, /* tp_getattr */
5115 0, /* tp_setattr */
5116 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005117 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005118 0, /* tp_as_number */
5119 0, /* tp_as_sequence */
5120 0, /* tp_as_mapping */
5121 0, /* tp_hash */
5122 0, /* tp_call */
5123 0, /* tp_str */
5124 super_getattro, /* tp_getattro */
5125 0, /* tp_setattro */
5126 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005127 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5128 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005129 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005130 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005131 0, /* tp_clear */
5132 0, /* tp_richcompare */
5133 0, /* tp_weaklistoffset */
5134 0, /* tp_iter */
5135 0, /* tp_iternext */
5136 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005137 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005138 0, /* tp_getset */
5139 0, /* tp_base */
5140 0, /* tp_dict */
5141 super_descr_get, /* tp_descr_get */
5142 0, /* tp_descr_set */
5143 0, /* tp_dictoffset */
5144 super_init, /* tp_init */
5145 PyType_GenericAlloc, /* tp_alloc */
5146 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005147 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005148};