blob: d9769455d962e07c86b305944ed049c4fb928008 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Type object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum6f799372001-09-20 20:46:19 +00007static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00008 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
9 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
10 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
11 {"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
17 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
18 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
25 char *s;
26
27 s = strrchr(type->tp_name, '.');
28 if (s == NULL)
29 s = type->tp_name;
30 else
31 s++;
32 return PyString_FromString(s);
33}
34
35static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000036type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000037{
Guido van Rossumc3542212001-08-16 09:18:56 +000038 PyObject *mod;
39 char *s;
40
41 s = strrchr(type->tp_name, '.');
42 if (s != NULL)
43 return PyString_FromStringAndSize(type->tp_name,
44 (int)(s - type->tp_name));
45 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
46 return PyString_FromString("__builtin__");
47 mod = PyDict_GetItemString(type->tp_defined, "__module__");
48 if (mod != NULL && PyString_Check(mod)) {
49 Py_INCREF(mod);
50 return mod;
51 }
52 PyErr_SetString(PyExc_AttributeError, "__module__");
53 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000054}
55
Guido van Rossum3926a632001-09-25 16:25:58 +000056static int
57type_set_module(PyTypeObject *type, PyObject *value, void *context)
58{
59 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ||
60 strrchr(type->tp_name, '.')) {
61 PyErr_Format(PyExc_TypeError,
62 "can't set %s.__module__", type->tp_name);
63 return -1;
64 }
65 if (!value) {
66 PyErr_Format(PyExc_TypeError,
67 "can't delete %s.__module__", type->tp_name);
68 return -1;
69 }
70 return PyDict_SetItemString(type->tp_dict, "__module__", value);
71}
72
Tim Peters6d6c1a32001-08-02 04:15:00 +000073static PyObject *
74type_dict(PyTypeObject *type, void *context)
75{
76 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077 Py_INCREF(Py_None);
78 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000079 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000080 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
81 Py_INCREF(type->tp_dict);
82 return type->tp_dict;
83 }
84 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000085}
86
Tim Peters6d6c1a32001-08-02 04:15:00 +000087static PyObject *
88type_defined(PyTypeObject *type, void *context)
89{
90 if (type->tp_defined == NULL) {
91 Py_INCREF(Py_None);
92 return Py_None;
93 }
94 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
95 Py_INCREF(type->tp_defined);
96 return type->tp_defined;
97 }
98 return PyDictProxy_New(type->tp_defined);
99}
100
101static PyObject *
102type_dynamic(PyTypeObject *type, void *context)
103{
104 PyObject *res;
105
106 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
107 Py_INCREF(res);
108 return res;
109}
110
Guido van Rossum32d34c82001-09-20 21:45:26 +0000111PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000112 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000113 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000114 {"__dict__", (getter)type_dict, NULL, NULL},
115 {"__defined__", (getter)type_defined, NULL, NULL},
116 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
117 {0}
118};
119
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000120static int
121type_compare(PyObject *v, PyObject *w)
122{
123 /* This is called with type objects only. So we
124 can just compare the addresses. */
125 Py_uintptr_t vv = (Py_uintptr_t)v;
126 Py_uintptr_t ww = (Py_uintptr_t)w;
127 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
128}
129
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000131type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000133 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000134 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000135
136 mod = type_module(type, NULL);
137 if (mod == NULL)
138 PyErr_Clear();
139 else if (!PyString_Check(mod)) {
140 Py_DECREF(mod);
141 mod = NULL;
142 }
143 name = type_name(type, NULL);
144 if (name == NULL)
145 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000146
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000147 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
148 kind = "class";
149 else
150 kind = "type";
151
Barry Warsaw7ce36942001-08-24 18:34:26 +0000152 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000153 rtn = PyString_FromFormat("<%s '%s.%s'>",
154 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000155 PyString_AS_STRING(mod),
156 PyString_AS_STRING(name));
157 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000158 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000159 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000160
Guido van Rossumc3542212001-08-16 09:18:56 +0000161 Py_XDECREF(mod);
162 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000163 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
Tim Peters6d6c1a32001-08-02 04:15:00 +0000166static PyObject *
167type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
168{
169 PyObject *obj;
170
171 if (type->tp_new == NULL) {
172 PyErr_Format(PyExc_TypeError,
173 "cannot create '%.100s' instances",
174 type->tp_name);
175 return NULL;
176 }
177
Tim Peters3f996e72001-09-13 19:18:27 +0000178 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 if (obj != NULL) {
180 type = obj->ob_type;
181 if (type->tp_init != NULL &&
182 type->tp_init(obj, args, kwds) < 0) {
183 Py_DECREF(obj);
184 obj = NULL;
185 }
186 }
187 return obj;
188}
189
190PyObject *
191PyType_GenericAlloc(PyTypeObject *type, int nitems)
192{
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000193#define PTRSIZE (sizeof(PyObject *))
194
Tim Peters6d6c1a32001-08-02 04:15:00 +0000195 int size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000196 PyObject *obj;
197
198 /* Inline PyObject_New() so we can zero the memory */
199 size = _PyObject_VAR_SIZE(type, nitems);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000200 /* Round up size, if necessary, so we fully zero out __dict__ */
201 if (type->tp_itemsize % PTRSIZE != 0) {
202 size += PTRSIZE - 1;
203 size /= PTRSIZE;
204 size *= PTRSIZE;
205 }
Neil Schemenauerc806c882001-08-29 23:54:54 +0000206 if (PyType_IS_GC(type)) {
207 obj = _PyObject_GC_Malloc(type, nitems);
208 }
209 else {
210 obj = PyObject_MALLOC(size);
211 }
212 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000213 return PyErr_NoMemory();
Neil Schemenauerc806c882001-08-29 23:54:54 +0000214 memset(obj, '\0', size);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000215 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
216 Py_INCREF(type);
217 if (type->tp_itemsize == 0)
218 PyObject_INIT(obj, type);
219 else
220 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
221 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000222 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000223 return obj;
224}
225
226PyObject *
227PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
228{
229 return type->tp_alloc(type, 0);
230}
231
232/* Helper for subtyping */
233
234static void
235subtype_dealloc(PyObject *self)
236{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000237 PyTypeObject *type, *base;
238 destructor f;
239
240 /* This exists so we can DECREF self->ob_type */
241
242 /* Find the nearest base with a different tp_dealloc */
243 type = self->ob_type;
244 base = type->tp_base;
245 while ((f = base->tp_dealloc) == subtype_dealloc) {
246 base = base->tp_base;
247 assert(base);
248 }
249
250 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000251 if (type->tp_dictoffset && !base->tp_dictoffset) {
252 PyObject **dictptr = _PyObject_GetDictPtr(self);
253 if (dictptr != NULL) {
254 PyObject *dict = *dictptr;
255 if (dict != NULL) {
256 Py_DECREF(dict);
257 *dictptr = NULL;
258 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000259 }
260 }
261
Guido van Rossum9676b222001-08-17 20:32:36 +0000262 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000263 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000264 PyObject_ClearWeakRefs(self);
265
Tim Peters6d6c1a32001-08-02 04:15:00 +0000266 /* Finalize GC if the base doesn't do GC and we do */
267 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000268 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000269
270 /* Call the base tp_dealloc() */
271 assert(f);
272 f(self);
273
274 /* Can't reference self beyond this point */
275 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
276 Py_DECREF(type);
277 }
278}
279
280staticforward void override_slots(PyTypeObject *type, PyObject *dict);
281staticforward PyTypeObject *solid_base(PyTypeObject *type);
282
283typedef struct {
284 PyTypeObject type;
285 PyNumberMethods as_number;
286 PySequenceMethods as_sequence;
287 PyMappingMethods as_mapping;
288 PyBufferProcs as_buffer;
289 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000290 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000291} etype;
292
293/* type test with subclassing support */
294
295int
296PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
297{
298 PyObject *mro;
299
Guido van Rossum9478d072001-09-07 18:52:13 +0000300 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
301 return b == a || b == &PyBaseObject_Type;
302
Tim Peters6d6c1a32001-08-02 04:15:00 +0000303 mro = a->tp_mro;
304 if (mro != NULL) {
305 /* Deal with multiple inheritance without recursion
306 by walking the MRO tuple */
307 int i, n;
308 assert(PyTuple_Check(mro));
309 n = PyTuple_GET_SIZE(mro);
310 for (i = 0; i < n; i++) {
311 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
312 return 1;
313 }
314 return 0;
315 }
316 else {
317 /* a is not completely initilized yet; follow tp_base */
318 do {
319 if (a == b)
320 return 1;
321 a = a->tp_base;
322 } while (a != NULL);
323 return b == &PyBaseObject_Type;
324 }
325}
326
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000327/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000328 without looking in the instance dictionary
329 (so we can't use PyObject_GetAttr) but still binding
330 it to the instance. The arguments are the object,
331 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000332 static variable used to cache the interned Python string.
333
334 Two variants:
335
336 - lookup_maybe() returns NULL without raising an exception
337 when the _PyType_Lookup() call fails;
338
339 - lookup_method() always raises an exception upon errors.
340*/
Guido van Rossum60718732001-08-28 17:47:51 +0000341
342static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000343lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000344{
345 PyObject *res;
346
347 if (*attrobj == NULL) {
348 *attrobj = PyString_InternFromString(attrstr);
349 if (*attrobj == NULL)
350 return NULL;
351 }
352 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000353 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000354 descrgetfunc f;
355 if ((f = res->ob_type->tp_descr_get) == NULL)
356 Py_INCREF(res);
357 else
358 res = f(res, self, (PyObject *)(self->ob_type));
359 }
360 return res;
361}
362
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000363static PyObject *
364lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
365{
366 PyObject *res = lookup_maybe(self, attrstr, attrobj);
367 if (res == NULL && !PyErr_Occurred())
368 PyErr_SetObject(PyExc_AttributeError, *attrobj);
369 return res;
370}
371
Guido van Rossum2730b132001-08-28 18:22:14 +0000372/* A variation of PyObject_CallMethod that uses lookup_method()
373 instead of PyObject_GetAttrString(). This uses the same convention
374 as lookup_method to cache the interned name string object. */
375
376PyObject *
377call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
378{
379 va_list va;
380 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000381 va_start(va, format);
382
Guido van Rossumda21c012001-10-03 00:50:18 +0000383 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000384 if (func == NULL) {
385 va_end(va);
386 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000387 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000388 return NULL;
389 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000390
391 if (format && *format)
392 args = Py_VaBuildValue(format, va);
393 else
394 args = PyTuple_New(0);
395
396 va_end(va);
397
398 if (args == NULL)
399 return NULL;
400
401 assert(PyTuple_Check(args));
402 retval = PyObject_Call(func, args, NULL);
403
404 Py_DECREF(args);
405 Py_DECREF(func);
406
407 return retval;
408}
409
410/* Clone of call_method() that returns NotImplemented when the lookup fails. */
411
412PyObject *
413call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
414{
415 va_list va;
416 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000417 va_start(va, format);
418
Guido van Rossumda21c012001-10-03 00:50:18 +0000419 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000420 if (func == NULL) {
421 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000422 if (!PyErr_Occurred()) {
423 Py_INCREF(Py_NotImplemented);
424 return Py_NotImplemented;
425 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000426 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000427 }
428
429 if (format && *format)
430 args = Py_VaBuildValue(format, va);
431 else
432 args = PyTuple_New(0);
433
434 va_end(va);
435
Guido van Rossum717ce002001-09-14 16:58:08 +0000436 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000437 return NULL;
438
Guido van Rossum717ce002001-09-14 16:58:08 +0000439 assert(PyTuple_Check(args));
440 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000441
442 Py_DECREF(args);
443 Py_DECREF(func);
444
445 return retval;
446}
447
Tim Peters6d6c1a32001-08-02 04:15:00 +0000448/* Method resolution order algorithm from "Putting Metaclasses to Work"
449 by Forman and Danforth (Addison-Wesley 1999). */
450
451static int
452conservative_merge(PyObject *left, PyObject *right)
453{
454 int left_size;
455 int right_size;
456 int i, j, r, ok;
457 PyObject *temp, *rr;
458
459 assert(PyList_Check(left));
460 assert(PyList_Check(right));
461
462 again:
463 left_size = PyList_GET_SIZE(left);
464 right_size = PyList_GET_SIZE(right);
465 for (i = 0; i < left_size; i++) {
466 for (j = 0; j < right_size; j++) {
467 if (PyList_GET_ITEM(left, i) ==
468 PyList_GET_ITEM(right, j)) {
469 /* found a merge point */
470 temp = PyList_New(0);
471 if (temp == NULL)
472 return -1;
473 for (r = 0; r < j; r++) {
474 rr = PyList_GET_ITEM(right, r);
475 ok = PySequence_Contains(left, rr);
476 if (ok < 0) {
477 Py_DECREF(temp);
478 return -1;
479 }
480 if (!ok) {
481 ok = PyList_Append(temp, rr);
482 if (ok < 0) {
483 Py_DECREF(temp);
484 return -1;
485 }
486 }
487 }
488 ok = PyList_SetSlice(left, i, i, temp);
489 Py_DECREF(temp);
490 if (ok < 0)
491 return -1;
492 ok = PyList_SetSlice(right, 0, j+1, NULL);
493 if (ok < 0)
494 return -1;
495 goto again;
496 }
497 }
498 }
499 return PyList_SetSlice(left, left_size, left_size, right);
500}
501
502static int
503serious_order_disagreements(PyObject *left, PyObject *right)
504{
505 return 0; /* XXX later -- for now, we cheat: "don't do that" */
506}
507
508static PyObject *
509mro_implementation(PyTypeObject *type)
510{
511 int i, n, ok;
512 PyObject *bases, *result;
513
514 bases = type->tp_bases;
515 n = PyTuple_GET_SIZE(bases);
516 result = Py_BuildValue("[O]", (PyObject *)type);
517 if (result == NULL)
518 return NULL;
519 for (i = 0; i < n; i++) {
520 PyTypeObject *base =
521 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
522 PyObject *parentMRO = PySequence_List(base->tp_mro);
523 if (parentMRO == NULL) {
524 Py_DECREF(result);
525 return NULL;
526 }
527 if (serious_order_disagreements(result, parentMRO)) {
528 Py_DECREF(result);
529 return NULL;
530 }
531 ok = conservative_merge(result, parentMRO);
532 Py_DECREF(parentMRO);
533 if (ok < 0) {
534 Py_DECREF(result);
535 return NULL;
536 }
537 }
538 return result;
539}
540
541static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000542mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000543{
544 PyTypeObject *type = (PyTypeObject *)self;
545
Tim Peters6d6c1a32001-08-02 04:15:00 +0000546 return mro_implementation(type);
547}
548
549static int
550mro_internal(PyTypeObject *type)
551{
552 PyObject *mro, *result, *tuple;
553
554 if (type->ob_type == &PyType_Type) {
555 result = mro_implementation(type);
556 }
557 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000558 static PyObject *mro_str;
559 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000560 if (mro == NULL)
561 return -1;
562 result = PyObject_CallObject(mro, NULL);
563 Py_DECREF(mro);
564 }
565 if (result == NULL)
566 return -1;
567 tuple = PySequence_Tuple(result);
568 Py_DECREF(result);
569 type->tp_mro = tuple;
570 return 0;
571}
572
573
574/* Calculate the best base amongst multiple base classes.
575 This is the first one that's on the path to the "solid base". */
576
577static PyTypeObject *
578best_base(PyObject *bases)
579{
580 int i, n;
581 PyTypeObject *base, *winner, *candidate, *base_i;
582
583 assert(PyTuple_Check(bases));
584 n = PyTuple_GET_SIZE(bases);
585 assert(n > 0);
586 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
587 winner = &PyBaseObject_Type;
588 for (i = 0; i < n; i++) {
589 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
590 if (!PyType_Check((PyObject *)base_i)) {
591 PyErr_SetString(
592 PyExc_TypeError,
593 "bases must be types");
594 return NULL;
595 }
596 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000597 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000598 return NULL;
599 }
600 candidate = solid_base(base_i);
601 if (PyType_IsSubtype(winner, candidate))
602 ;
603 else if (PyType_IsSubtype(candidate, winner)) {
604 winner = candidate;
605 base = base_i;
606 }
607 else {
608 PyErr_SetString(
609 PyExc_TypeError,
610 "multiple bases have "
611 "instance lay-out conflict");
612 return NULL;
613 }
614 }
615 assert(base != NULL);
616 return base;
617}
618
619static int
620extra_ivars(PyTypeObject *type, PyTypeObject *base)
621{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000622 size_t t_size = type->tp_basicsize;
623 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000624
Guido van Rossum9676b222001-08-17 20:32:36 +0000625 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000626 if (type->tp_itemsize || base->tp_itemsize) {
627 /* If itemsize is involved, stricter rules */
628 return t_size != b_size ||
629 type->tp_itemsize != base->tp_itemsize;
630 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000631 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
632 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
633 t_size -= sizeof(PyObject *);
634 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
635 type->tp_dictoffset + sizeof(PyObject *) == t_size)
636 t_size -= sizeof(PyObject *);
637
638 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000639}
640
641static PyTypeObject *
642solid_base(PyTypeObject *type)
643{
644 PyTypeObject *base;
645
646 if (type->tp_base)
647 base = solid_base(type->tp_base);
648 else
649 base = &PyBaseObject_Type;
650 if (extra_ivars(type, base))
651 return type;
652 else
653 return base;
654}
655
656staticforward void object_dealloc(PyObject *);
657staticforward int object_init(PyObject *, PyObject *, PyObject *);
658
659static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000660subtype_dict(PyObject *obj, void *context)
661{
662 PyObject **dictptr = _PyObject_GetDictPtr(obj);
663 PyObject *dict;
664
665 if (dictptr == NULL) {
666 PyErr_SetString(PyExc_AttributeError,
667 "This object has no __dict__");
668 return NULL;
669 }
670 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000671 if (dict == NULL)
672 *dictptr = dict = PyDict_New();
673 Py_XINCREF(dict);
674 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000675}
676
Guido van Rossum32d34c82001-09-20 21:45:26 +0000677PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000678 {"__dict__", subtype_dict, NULL, NULL},
679 {0},
680};
681
682static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000683type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
684{
685 PyObject *name, *bases, *dict;
686 static char *kwlist[] = {"name", "bases", "dict", 0};
687 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000688 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000689 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000690 PyMemberDef *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000691 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000692
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000693 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000694 if (metatype == &PyType_Type &&
695 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
696 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000697 PyObject *x = PyTuple_GET_ITEM(args, 0);
698 Py_INCREF(x->ob_type);
699 return (PyObject *) x->ob_type;
700 }
701
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000702 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000703 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
704 &name,
705 &PyTuple_Type, &bases,
706 &PyDict_Type, &dict))
707 return NULL;
708
709 /* Determine the proper metatype to deal with this,
710 and check for metatype conflicts while we're at it.
711 Note that if some other metatype wins to contract,
712 it's possible that its instances are not types. */
713 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000714 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000715 for (i = 0; i < nbases; i++) {
716 tmp = PyTuple_GET_ITEM(bases, i);
717 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000718 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000719 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000720 if (PyType_IsSubtype(tmptype, winner)) {
721 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000722 continue;
723 }
724 PyErr_SetString(PyExc_TypeError,
725 "metatype conflict among bases");
726 return NULL;
727 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000728 if (winner != metatype) {
729 if (winner->tp_new != type_new) /* Pass it to the winner */
730 return winner->tp_new(winner, args, kwds);
731 metatype = winner;
732 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000733
734 /* Adjust for empty tuple bases */
735 if (nbases == 0) {
736 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
737 if (bases == NULL)
738 return NULL;
739 nbases = 1;
740 }
741 else
742 Py_INCREF(bases);
743
744 /* XXX From here until type is allocated, "return NULL" leaks bases! */
745
746 /* Calculate best base, and check that all bases are type objects */
747 base = best_base(bases);
748 if (base == NULL)
749 return NULL;
750 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
751 PyErr_Format(PyExc_TypeError,
752 "type '%.100s' is not an acceptable base type",
753 base->tp_name);
754 return NULL;
755 }
756
Guido van Rossum1a493502001-08-17 16:47:50 +0000757 /* Should this be a dynamic class (i.e. modifiable __dict__)?
758 Look in two places for a variable named __dynamic__:
759 1) in the class dict
760 2) in the module dict (globals)
761 The first variable that is an int >= 0 is used.
762 Otherwise, a default is calculated from the base classes:
763 if any base class is dynamic, this class is dynamic; otherwise
764 it is static. */
765 dynamic = -1; /* Not yet determined */
766 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000767 tmp = PyDict_GetItemString(dict, "__dynamic__");
768 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000769 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000770 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000771 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000772 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000773 if (dynamic < 0) {
774 /* Look in the module globals */
775 tmp = PyEval_GetGlobals();
776 if (tmp != NULL) {
777 tmp = PyDict_GetItemString(tmp, "__dynamic__");
778 if (tmp != NULL) {
779 dynamic = PyInt_AsLong(tmp);
780 if (dynamic < 0)
781 PyErr_Clear();
782 }
783 }
784 }
785 if (dynamic < 0) {
786 /* Make a new class dynamic if any of its bases is
787 dynamic. This is not always the same as inheriting
788 the __dynamic__ class attribute! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000789 dynamic = 0;
790 for (i = 0; i < nbases; i++) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000791 tmptype = (PyTypeObject *)
792 PyTuple_GET_ITEM(bases, i);
793 if (tmptype->tp_flags &
794 Py_TPFLAGS_DYNAMICTYPE) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000795 dynamic = 1;
796 break;
797 }
798 }
799 }
800
801 /* Check for a __slots__ sequence variable in dict, and count it */
802 slots = PyDict_GetItemString(dict, "__slots__");
803 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000804 add_dict = 0;
805 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000806 if (slots != NULL) {
807 /* Make it into a tuple */
808 if (PyString_Check(slots))
809 slots = Py_BuildValue("(O)", slots);
810 else
811 slots = PySequence_Tuple(slots);
812 if (slots == NULL)
813 return NULL;
814 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000815 if (nslots > 0 && base->tp_itemsize != 0) {
816 PyErr_Format(PyExc_TypeError,
817 "nonempty __slots__ "
818 "not supported for subtype of '%s'",
819 base->tp_name);
820 return NULL;
821 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000822 for (i = 0; i < nslots; i++) {
823 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
824 PyErr_SetString(PyExc_TypeError,
825 "__slots__ must be a sequence of strings");
826 Py_DECREF(slots);
827 return NULL;
828 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000829 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000830 }
831 }
832 if (slots == NULL && base->tp_dictoffset == 0 &&
833 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000834 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000835 add_dict++;
836 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000837 if (slots == NULL && base->tp_weaklistoffset == 0 &&
838 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000839 nslots++;
840 add_weak++;
841 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842
843 /* XXX From here until type is safely allocated,
844 "return NULL" may leak slots! */
845
846 /* Allocate the type object */
847 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
848 if (type == NULL)
849 return NULL;
850
851 /* Keep name and slots alive in the extended type object */
852 et = (etype *)type;
853 Py_INCREF(name);
854 et->name = name;
855 et->slots = slots;
856
Guido van Rossumdc91b992001-08-08 22:26:22 +0000857 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000858 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
859 Py_TPFLAGS_BASETYPE;
860 if (dynamic)
861 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000862 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
863 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000864
865 /* It's a new-style number unless it specifically inherits any
866 old-style numeric behavior */
867 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
868 (base->tp_as_number == NULL))
869 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
870
871 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000872 type->tp_as_number = &et->as_number;
873 type->tp_as_sequence = &et->as_sequence;
874 type->tp_as_mapping = &et->as_mapping;
875 type->tp_as_buffer = &et->as_buffer;
876 type->tp_name = PyString_AS_STRING(name);
877
878 /* Set tp_base and tp_bases */
879 type->tp_bases = bases;
880 Py_INCREF(base);
881 type->tp_base = base;
882
883 /* Initialize tp_defined from passed-in dict */
884 type->tp_defined = dict = PyDict_Copy(dict);
885 if (dict == NULL) {
886 Py_DECREF(type);
887 return NULL;
888 }
889
Guido van Rossumc3542212001-08-16 09:18:56 +0000890 /* Set __module__ in the dict */
891 if (PyDict_GetItemString(dict, "__module__") == NULL) {
892 tmp = PyEval_GetGlobals();
893 if (tmp != NULL) {
894 tmp = PyDict_GetItemString(tmp, "__name__");
895 if (tmp != NULL) {
896 if (PyDict_SetItemString(dict, "__module__",
897 tmp) < 0)
898 return NULL;
899 }
900 }
901 }
902
Tim Peters6d6c1a32001-08-02 04:15:00 +0000903 /* Special-case __new__: if it's a plain function,
904 make it a static function */
905 tmp = PyDict_GetItemString(dict, "__new__");
906 if (tmp != NULL && PyFunction_Check(tmp)) {
907 tmp = PyStaticMethod_New(tmp);
908 if (tmp == NULL) {
909 Py_DECREF(type);
910 return NULL;
911 }
912 PyDict_SetItemString(dict, "__new__", tmp);
913 Py_DECREF(tmp);
914 }
915
916 /* Add descriptors for custom slots from __slots__, or for __dict__ */
917 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000918 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000919 if (slots != NULL) {
920 for (i = 0; i < nslots; i++, mp++) {
921 mp->name = PyString_AS_STRING(
922 PyTuple_GET_ITEM(slots, i));
923 mp->type = T_OBJECT;
924 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000925 if (base->tp_weaklistoffset == 0 &&
926 strcmp(mp->name, "__weakref__") == 0)
927 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000928 slotoffset += sizeof(PyObject *);
929 }
930 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000931 else {
932 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000933 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +0000934 type->tp_dictoffset =
935 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000936 else
937 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000938 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000939 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000940 }
941 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000942 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000943 type->tp_weaklistoffset = slotoffset;
944 mp->name = "__weakref__";
945 mp->type = T_OBJECT;
946 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000947 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000948 mp++;
949 slotoffset += sizeof(PyObject *);
950 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000951 }
952 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000953 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000954 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000955
956 /* Special case some slots */
957 if (type->tp_dictoffset != 0 || nslots > 0) {
958 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
959 type->tp_getattro = PyObject_GenericGetAttr;
960 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
961 type->tp_setattro = PyObject_GenericSetAttr;
962 }
963 type->tp_dealloc = subtype_dealloc;
964
965 /* Always override allocation strategy to use regular heap */
966 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +0000967 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
968 type->tp_free = _PyObject_GC_Del;
969 type->tp_traverse = base->tp_traverse;
970 type->tp_clear = base->tp_clear;
971 }
972 else
973 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000974
975 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000976 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000977 Py_DECREF(type);
978 return NULL;
979 }
980
981 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +0000982 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
983 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000984
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985 return (PyObject *)type;
986}
987
988/* Internal API to look for a name through the MRO.
989 This returns a borrowed reference, and doesn't set an exception! */
990PyObject *
991_PyType_Lookup(PyTypeObject *type, PyObject *name)
992{
993 int i, n;
994 PyObject *mro, *res, *dict;
995
996 /* For static types, look in tp_dict */
997 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
998 dict = type->tp_dict;
999 assert(dict && PyDict_Check(dict));
1000 return PyDict_GetItem(dict, name);
1001 }
1002
1003 /* For dynamic types, look in tp_defined of types in MRO */
1004 mro = type->tp_mro;
1005 assert(PyTuple_Check(mro));
1006 n = PyTuple_GET_SIZE(mro);
1007 for (i = 0; i < n; i++) {
1008 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
1009 assert(PyType_Check(type));
1010 dict = type->tp_defined;
1011 assert(dict && PyDict_Check(dict));
1012 res = PyDict_GetItem(dict, name);
1013 if (res != NULL)
1014 return res;
1015 }
1016 return NULL;
1017}
1018
1019/* This is similar to PyObject_GenericGetAttr(),
1020 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1021static PyObject *
1022type_getattro(PyTypeObject *type, PyObject *name)
1023{
1024 PyTypeObject *metatype = type->ob_type;
1025 PyObject *descr, *res;
1026 descrgetfunc f;
1027
1028 /* Initialize this type (we'll assume the metatype is initialized) */
1029 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001030 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001031 return NULL;
1032 }
1033
1034 /* Get a descriptor from the metatype */
1035 descr = _PyType_Lookup(metatype, name);
1036 f = NULL;
1037 if (descr != NULL) {
1038 f = descr->ob_type->tp_descr_get;
1039 if (f != NULL && PyDescr_IsData(descr))
1040 return f(descr,
1041 (PyObject *)type, (PyObject *)metatype);
1042 }
1043
1044 /* Look in tp_defined of this type and its bases */
1045 res = _PyType_Lookup(type, name);
1046 if (res != NULL) {
1047 f = res->ob_type->tp_descr_get;
1048 if (f != NULL)
1049 return f(res, (PyObject *)NULL, (PyObject *)type);
1050 Py_INCREF(res);
1051 return res;
1052 }
1053
1054 /* Use the descriptor from the metatype */
1055 if (f != NULL) {
1056 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1057 return res;
1058 }
1059 if (descr != NULL) {
1060 Py_INCREF(descr);
1061 return descr;
1062 }
1063
1064 /* Give up */
1065 PyErr_Format(PyExc_AttributeError,
1066 "type object '%.50s' has no attribute '%.400s'",
1067 type->tp_name, PyString_AS_STRING(name));
1068 return NULL;
1069}
1070
1071static int
1072type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1073{
1074 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
1075 return PyObject_GenericSetAttr((PyObject *)type, name, value);
1076 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
1077 return -1;
1078}
1079
1080static void
1081type_dealloc(PyTypeObject *type)
1082{
1083 etype *et;
1084
1085 /* Assert this is a heap-allocated type object */
1086 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001087 _PyObject_GC_UNTRACK(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001088 et = (etype *)type;
1089 Py_XDECREF(type->tp_base);
1090 Py_XDECREF(type->tp_dict);
1091 Py_XDECREF(type->tp_bases);
1092 Py_XDECREF(type->tp_mro);
1093 Py_XDECREF(type->tp_defined);
1094 /* XXX more? */
1095 Py_XDECREF(et->name);
1096 Py_XDECREF(et->slots);
1097 type->ob_type->tp_free((PyObject *)type);
1098}
1099
1100static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001101 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001102 "mro() -> list\nreturn a type's method resolution order"},
1103 {0}
1104};
1105
1106static char type_doc[] =
1107"type(object) -> the object's type\n"
1108"type(name, bases, dict) -> a new type";
1109
Guido van Rossum048eb752001-10-02 21:24:57 +00001110static int
1111type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1112{
1113 etype *et;
1114 int err;
1115
1116 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1117 return 0;
1118
1119 et = (etype *)type;
1120
1121#define VISIT(SLOT) \
1122 if (SLOT) { \
1123 err = visit((PyObject *)(SLOT), arg); \
1124 if (err) \
1125 return err; \
1126 }
1127
1128 VISIT(type->tp_dict);
1129 VISIT(type->tp_defined);
1130 VISIT(type->tp_mro);
1131 VISIT(type->tp_bases);
1132 VISIT(type->tp_base);
1133 VISIT(et->slots);
1134
1135#undef VISIT
1136
1137 return 0;
1138}
1139
1140static int
1141type_clear(PyTypeObject *type)
1142{
1143 etype *et;
1144 PyObject *tmp;
1145
1146 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1147 return 0;
1148
1149 et = (etype *)type;
1150
1151#define CLEAR(SLOT) \
1152 if (SLOT) { \
1153 tmp = (PyObject *)(SLOT); \
1154 SLOT = NULL; \
1155 Py_DECREF(tmp); \
1156 }
1157
1158 CLEAR(type->tp_dict);
1159 CLEAR(type->tp_defined);
1160 CLEAR(type->tp_mro);
1161 CLEAR(type->tp_bases);
1162 CLEAR(type->tp_base);
1163 CLEAR(et->slots);
1164
1165#undef CLEAR
1166
1167 return 0;
1168}
1169
1170static int
1171type_is_gc(PyTypeObject *type)
1172{
1173 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1174}
1175
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001176PyTypeObject PyType_Type = {
1177 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001178 0, /* ob_size */
1179 "type", /* tp_name */
1180 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001181 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182 (destructor)type_dealloc, /* tp_dealloc */
1183 0, /* tp_print */
1184 0, /* tp_getattr */
1185 0, /* tp_setattr */
1186 type_compare, /* tp_compare */
1187 (reprfunc)type_repr, /* tp_repr */
1188 0, /* tp_as_number */
1189 0, /* tp_as_sequence */
1190 0, /* tp_as_mapping */
1191 (hashfunc)_Py_HashPointer, /* tp_hash */
1192 (ternaryfunc)type_call, /* tp_call */
1193 0, /* tp_str */
1194 (getattrofunc)type_getattro, /* tp_getattro */
1195 (setattrofunc)type_setattro, /* tp_setattro */
1196 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001197 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1198 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001200 (traverseproc)type_traverse, /* tp_traverse */
1201 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 0, /* tp_richcompare */
1203 0, /* tp_weaklistoffset */
1204 0, /* tp_iter */
1205 0, /* tp_iternext */
1206 type_methods, /* tp_methods */
1207 type_members, /* tp_members */
1208 type_getsets, /* tp_getset */
1209 0, /* tp_base */
1210 0, /* tp_dict */
1211 0, /* tp_descr_get */
1212 0, /* tp_descr_set */
1213 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1214 0, /* tp_init */
1215 0, /* tp_alloc */
1216 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001217 _PyObject_GC_Del, /* tp_free */
1218 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001219};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001220
1221
1222/* The base type of all types (eventually)... except itself. */
1223
1224static int
1225object_init(PyObject *self, PyObject *args, PyObject *kwds)
1226{
1227 return 0;
1228}
1229
1230static void
1231object_dealloc(PyObject *self)
1232{
1233 self->ob_type->tp_free(self);
1234}
1235
Guido van Rossum8e248182001-08-12 05:17:56 +00001236static PyObject *
1237object_repr(PyObject *self)
1238{
Guido van Rossum76e69632001-08-16 18:52:43 +00001239 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001240 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001241
Guido van Rossum76e69632001-08-16 18:52:43 +00001242 type = self->ob_type;
1243 mod = type_module(type, NULL);
1244 if (mod == NULL)
1245 PyErr_Clear();
1246 else if (!PyString_Check(mod)) {
1247 Py_DECREF(mod);
1248 mod = NULL;
1249 }
1250 name = type_name(type, NULL);
1251 if (name == NULL)
1252 return NULL;
1253 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001254 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001255 PyString_AS_STRING(mod),
1256 PyString_AS_STRING(name),
1257 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001258 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001259 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001260 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001261 Py_XDECREF(mod);
1262 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001263 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001264}
1265
Guido van Rossumb8f63662001-08-15 23:57:02 +00001266static PyObject *
1267object_str(PyObject *self)
1268{
1269 unaryfunc f;
1270
1271 f = self->ob_type->tp_repr;
1272 if (f == NULL)
1273 f = object_repr;
1274 return f(self);
1275}
1276
Guido van Rossum8e248182001-08-12 05:17:56 +00001277static long
1278object_hash(PyObject *self)
1279{
1280 return _Py_HashPointer(self);
1281}
Guido van Rossum8e248182001-08-12 05:17:56 +00001282
Tim Peters6d6c1a32001-08-02 04:15:00 +00001283static void
1284object_free(PyObject *self)
1285{
1286 PyObject_Del(self);
1287}
1288
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001289static PyObject *
1290object_get_class(PyObject *self, void *closure)
1291{
1292 Py_INCREF(self->ob_type);
1293 return (PyObject *)(self->ob_type);
1294}
1295
1296static int
1297equiv_structs(PyTypeObject *a, PyTypeObject *b)
1298{
1299 return a == b ||
1300 (a != NULL &&
1301 b != NULL &&
1302 a->tp_basicsize == b->tp_basicsize &&
1303 a->tp_itemsize == b->tp_itemsize &&
1304 a->tp_dictoffset == b->tp_dictoffset &&
1305 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1306 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1307 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1308}
1309
1310static int
1311same_slots_added(PyTypeObject *a, PyTypeObject *b)
1312{
1313 PyTypeObject *base = a->tp_base;
1314 int size;
1315
1316 if (base != b->tp_base)
1317 return 0;
1318 if (equiv_structs(a, base) && equiv_structs(b, base))
1319 return 1;
1320 size = base->tp_basicsize;
1321 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1322 size += sizeof(PyObject *);
1323 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1324 size += sizeof(PyObject *);
1325 return size == a->tp_basicsize && size == b->tp_basicsize;
1326}
1327
1328static int
1329object_set_class(PyObject *self, PyObject *value, void *closure)
1330{
1331 PyTypeObject *old = self->ob_type;
1332 PyTypeObject *new, *newbase, *oldbase;
1333
1334 if (!PyType_Check(value)) {
1335 PyErr_Format(PyExc_TypeError,
1336 "__class__ must be set to new-style class, not '%s' object",
1337 value->ob_type->tp_name);
1338 return -1;
1339 }
1340 new = (PyTypeObject *)value;
1341 newbase = new;
1342 oldbase = old;
1343 while (equiv_structs(newbase, newbase->tp_base))
1344 newbase = newbase->tp_base;
1345 while (equiv_structs(oldbase, oldbase->tp_base))
1346 oldbase = oldbase->tp_base;
1347 if (newbase != oldbase &&
1348 (newbase->tp_base != oldbase->tp_base ||
1349 !same_slots_added(newbase, oldbase))) {
1350 PyErr_Format(PyExc_TypeError,
1351 "__class__ assignment: "
1352 "'%s' object layout differs from '%s'",
1353 new->tp_name,
1354 old->tp_name);
1355 return -1;
1356 }
1357 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1358 Py_INCREF(new);
1359 }
1360 self->ob_type = new;
1361 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1362 Py_DECREF(old);
1363 }
1364 return 0;
1365}
1366
1367static PyGetSetDef object_getsets[] = {
1368 {"__class__", object_get_class, object_set_class,
1369 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001370 {0}
1371};
1372
Guido van Rossum3926a632001-09-25 16:25:58 +00001373static PyObject *
1374object_reduce(PyObject *self, PyObject *args)
1375{
1376 /* Call copy_reg._reduce(self) */
1377 static PyObject *copy_reg_str;
1378 PyObject *copy_reg, *res;
1379
1380 if (!copy_reg_str) {
1381 copy_reg_str = PyString_InternFromString("copy_reg");
1382 if (copy_reg_str == NULL)
1383 return NULL;
1384 }
1385 copy_reg = PyImport_Import(copy_reg_str);
1386 if (!copy_reg)
1387 return NULL;
1388 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1389 Py_DECREF(copy_reg);
1390 return res;
1391}
1392
1393static PyMethodDef object_methods[] = {
1394 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1395 {0}
1396};
1397
Tim Peters6d6c1a32001-08-02 04:15:00 +00001398PyTypeObject PyBaseObject_Type = {
1399 PyObject_HEAD_INIT(&PyType_Type)
1400 0, /* ob_size */
1401 "object", /* tp_name */
1402 sizeof(PyObject), /* tp_basicsize */
1403 0, /* tp_itemsize */
1404 (destructor)object_dealloc, /* tp_dealloc */
1405 0, /* tp_print */
1406 0, /* tp_getattr */
1407 0, /* tp_setattr */
1408 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001409 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001410 0, /* tp_as_number */
1411 0, /* tp_as_sequence */
1412 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001413 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001414 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001415 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001416 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001417 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418 0, /* tp_as_buffer */
1419 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1420 "The most base type", /* tp_doc */
1421 0, /* tp_traverse */
1422 0, /* tp_clear */
1423 0, /* tp_richcompare */
1424 0, /* tp_weaklistoffset */
1425 0, /* tp_iter */
1426 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001427 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001428 0, /* tp_members */
1429 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001430 0, /* tp_base */
1431 0, /* tp_dict */
1432 0, /* tp_descr_get */
1433 0, /* tp_descr_set */
1434 0, /* tp_dictoffset */
1435 object_init, /* tp_init */
1436 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001437 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001438 object_free, /* tp_free */
1439};
1440
1441
1442/* Initialize the __dict__ in a type object */
1443
1444static int
1445add_methods(PyTypeObject *type, PyMethodDef *meth)
1446{
1447 PyObject *dict = type->tp_defined;
1448
1449 for (; meth->ml_name != NULL; meth++) {
1450 PyObject *descr;
1451 if (PyDict_GetItemString(dict, meth->ml_name))
1452 continue;
1453 descr = PyDescr_NewMethod(type, meth);
1454 if (descr == NULL)
1455 return -1;
1456 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1457 return -1;
1458 Py_DECREF(descr);
1459 }
1460 return 0;
1461}
1462
1463static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001464add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001465{
1466 PyObject *dict = type->tp_defined;
1467
1468 for (; memb->name != NULL; memb++) {
1469 PyObject *descr;
1470 if (PyDict_GetItemString(dict, memb->name))
1471 continue;
1472 descr = PyDescr_NewMember(type, memb);
1473 if (descr == NULL)
1474 return -1;
1475 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1476 return -1;
1477 Py_DECREF(descr);
1478 }
1479 return 0;
1480}
1481
1482static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001483add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484{
1485 PyObject *dict = type->tp_defined;
1486
1487 for (; gsp->name != NULL; gsp++) {
1488 PyObject *descr;
1489 if (PyDict_GetItemString(dict, gsp->name))
1490 continue;
1491 descr = PyDescr_NewGetSet(type, gsp);
1492
1493 if (descr == NULL)
1494 return -1;
1495 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1496 return -1;
1497 Py_DECREF(descr);
1498 }
1499 return 0;
1500}
1501
Guido van Rossum13d52f02001-08-10 21:24:08 +00001502static void
1503inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001504{
1505 int oldsize, newsize;
1506
Guido van Rossum13d52f02001-08-10 21:24:08 +00001507 /* Special flag magic */
1508 if (!type->tp_as_buffer && base->tp_as_buffer) {
1509 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1510 type->tp_flags |=
1511 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1512 }
1513 if (!type->tp_as_sequence && base->tp_as_sequence) {
1514 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1515 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1516 }
1517 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1518 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1519 if ((!type->tp_as_number && base->tp_as_number) ||
1520 (!type->tp_as_sequence && base->tp_as_sequence)) {
1521 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1522 if (!type->tp_as_number && !type->tp_as_sequence) {
1523 type->tp_flags |= base->tp_flags &
1524 Py_TPFLAGS_HAVE_INPLACEOPS;
1525 }
1526 }
1527 /* Wow */
1528 }
1529 if (!type->tp_as_number && base->tp_as_number) {
1530 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1531 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1532 }
1533
1534 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001535 oldsize = base->tp_basicsize;
1536 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1537 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1538 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001539 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1540 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001541 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001542 if (type->tp_traverse == NULL)
1543 type->tp_traverse = base->tp_traverse;
1544 if (type->tp_clear == NULL)
1545 type->tp_clear = base->tp_clear;
1546 }
1547 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1548 if (base != &PyBaseObject_Type ||
1549 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1550 if (type->tp_new == NULL)
1551 type->tp_new = base->tp_new;
1552 }
1553 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001554 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001555
1556 /* Copy other non-function slots */
1557
1558#undef COPYVAL
1559#define COPYVAL(SLOT) \
1560 if (type->SLOT == 0) type->SLOT = base->SLOT
1561
1562 COPYVAL(tp_itemsize);
1563 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1564 COPYVAL(tp_weaklistoffset);
1565 }
1566 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1567 COPYVAL(tp_dictoffset);
1568 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001569}
1570
1571static void
1572inherit_slots(PyTypeObject *type, PyTypeObject *base)
1573{
1574 PyTypeObject *basebase;
1575
1576#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577#undef COPYSLOT
1578#undef COPYNUM
1579#undef COPYSEQ
1580#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001581
1582#define SLOTDEFINED(SLOT) \
1583 (base->SLOT != 0 && \
1584 (basebase == NULL || base->SLOT != basebase->SLOT))
1585
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001587 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588
1589#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1590#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1591#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1592
Guido van Rossum13d52f02001-08-10 21:24:08 +00001593 /* This won't inherit indirect slots (from tp_as_number etc.)
1594 if type doesn't provide the space. */
1595
1596 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1597 basebase = base->tp_base;
1598 if (basebase->tp_as_number == NULL)
1599 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600 COPYNUM(nb_add);
1601 COPYNUM(nb_subtract);
1602 COPYNUM(nb_multiply);
1603 COPYNUM(nb_divide);
1604 COPYNUM(nb_remainder);
1605 COPYNUM(nb_divmod);
1606 COPYNUM(nb_power);
1607 COPYNUM(nb_negative);
1608 COPYNUM(nb_positive);
1609 COPYNUM(nb_absolute);
1610 COPYNUM(nb_nonzero);
1611 COPYNUM(nb_invert);
1612 COPYNUM(nb_lshift);
1613 COPYNUM(nb_rshift);
1614 COPYNUM(nb_and);
1615 COPYNUM(nb_xor);
1616 COPYNUM(nb_or);
1617 COPYNUM(nb_coerce);
1618 COPYNUM(nb_int);
1619 COPYNUM(nb_long);
1620 COPYNUM(nb_float);
1621 COPYNUM(nb_oct);
1622 COPYNUM(nb_hex);
1623 COPYNUM(nb_inplace_add);
1624 COPYNUM(nb_inplace_subtract);
1625 COPYNUM(nb_inplace_multiply);
1626 COPYNUM(nb_inplace_divide);
1627 COPYNUM(nb_inplace_remainder);
1628 COPYNUM(nb_inplace_power);
1629 COPYNUM(nb_inplace_lshift);
1630 COPYNUM(nb_inplace_rshift);
1631 COPYNUM(nb_inplace_and);
1632 COPYNUM(nb_inplace_xor);
1633 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001634 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1635 COPYNUM(nb_true_divide);
1636 COPYNUM(nb_floor_divide);
1637 COPYNUM(nb_inplace_true_divide);
1638 COPYNUM(nb_inplace_floor_divide);
1639 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001640 }
1641
Guido van Rossum13d52f02001-08-10 21:24:08 +00001642 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1643 basebase = base->tp_base;
1644 if (basebase->tp_as_sequence == NULL)
1645 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001646 COPYSEQ(sq_length);
1647 COPYSEQ(sq_concat);
1648 COPYSEQ(sq_repeat);
1649 COPYSEQ(sq_item);
1650 COPYSEQ(sq_slice);
1651 COPYSEQ(sq_ass_item);
1652 COPYSEQ(sq_ass_slice);
1653 COPYSEQ(sq_contains);
1654 COPYSEQ(sq_inplace_concat);
1655 COPYSEQ(sq_inplace_repeat);
1656 }
1657
Guido van Rossum13d52f02001-08-10 21:24:08 +00001658 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1659 basebase = base->tp_base;
1660 if (basebase->tp_as_mapping == NULL)
1661 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001662 COPYMAP(mp_length);
1663 COPYMAP(mp_subscript);
1664 COPYMAP(mp_ass_subscript);
1665 }
1666
Guido van Rossum13d52f02001-08-10 21:24:08 +00001667 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668
Tim Peters6d6c1a32001-08-02 04:15:00 +00001669 COPYSLOT(tp_dealloc);
1670 COPYSLOT(tp_print);
1671 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1672 type->tp_getattr = base->tp_getattr;
1673 type->tp_getattro = base->tp_getattro;
1674 }
1675 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1676 type->tp_setattr = base->tp_setattr;
1677 type->tp_setattro = base->tp_setattro;
1678 }
1679 /* tp_compare see tp_richcompare */
1680 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001681 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001682 COPYSLOT(tp_call);
1683 COPYSLOT(tp_str);
1684 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001685 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001686 if (type->tp_compare == NULL &&
1687 type->tp_richcompare == NULL &&
1688 type->tp_hash == NULL)
1689 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690 type->tp_compare = base->tp_compare;
1691 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001692 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693 }
1694 }
1695 else {
1696 COPYSLOT(tp_compare);
1697 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1699 COPYSLOT(tp_iter);
1700 COPYSLOT(tp_iternext);
1701 }
1702 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1703 COPYSLOT(tp_descr_get);
1704 COPYSLOT(tp_descr_set);
1705 COPYSLOT(tp_dictoffset);
1706 COPYSLOT(tp_init);
1707 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001708 COPYSLOT(tp_free);
1709 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001710}
1711
Guido van Rossum13d52f02001-08-10 21:24:08 +00001712staticforward int add_operators(PyTypeObject *);
1713
Tim Peters6d6c1a32001-08-02 04:15:00 +00001714int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001715PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001716{
1717 PyObject *dict, *bases, *x;
1718 PyTypeObject *base;
1719 int i, n;
1720
Guido van Rossumd614f972001-08-10 17:39:49 +00001721 if (type->tp_flags & Py_TPFLAGS_READY) {
1722 assert(type->tp_dict != NULL);
1723 return 0;
1724 }
1725 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1726 assert(type->tp_dict == NULL);
1727
1728 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001729
1730 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1731 base = type->tp_base;
1732 if (base == NULL && type != &PyBaseObject_Type)
1733 base = type->tp_base = &PyBaseObject_Type;
1734
1735 /* Initialize tp_bases */
1736 bases = type->tp_bases;
1737 if (bases == NULL) {
1738 if (base == NULL)
1739 bases = PyTuple_New(0);
1740 else
1741 bases = Py_BuildValue("(O)", base);
1742 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001743 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001744 type->tp_bases = bases;
1745 }
1746
1747 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001748 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001749 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001750 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001751 }
1752
1753 /* Initialize tp_defined */
1754 dict = type->tp_defined;
1755 if (dict == NULL) {
1756 dict = PyDict_New();
1757 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001758 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001759 type->tp_defined = dict;
1760 }
1761
1762 /* Add type-specific descriptors to tp_defined */
1763 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001764 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001765 if (type->tp_methods != NULL) {
1766 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001767 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768 }
1769 if (type->tp_members != NULL) {
1770 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001771 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001772 }
1773 if (type->tp_getset != NULL) {
1774 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001775 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776 }
1777
1778 /* Temporarily make tp_dict the same object as tp_defined.
1779 (This is needed to call mro(), and can stay this way for
1780 dynamic types). */
1781 Py_INCREF(type->tp_defined);
1782 type->tp_dict = type->tp_defined;
1783
1784 /* Calculate method resolution order */
1785 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001786 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001787 }
1788
Guido van Rossum13d52f02001-08-10 21:24:08 +00001789 /* Inherit special flags from dominant base */
1790 if (type->tp_base != NULL)
1791 inherit_special(type, type->tp_base);
1792
Tim Peters6d6c1a32001-08-02 04:15:00 +00001793 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001794 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001795 /* For a dynamic type, all slots are overridden */
1796 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001797 }
1798 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001800 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001801 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001802 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001803 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001804 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001805 bases = type->tp_mro;
1806 assert(bases != NULL);
1807 assert(PyTuple_Check(bases));
1808 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001809 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1811 assert(PyType_Check(base));
1812 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001813 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001814 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001815 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001816 }
1817 }
1818
Guido van Rossum13d52f02001-08-10 21:24:08 +00001819 /* Some more special stuff */
1820 base = type->tp_base;
1821 if (base != NULL) {
1822 if (type->tp_as_number == NULL)
1823 type->tp_as_number = base->tp_as_number;
1824 if (type->tp_as_sequence == NULL)
1825 type->tp_as_sequence = base->tp_as_sequence;
1826 if (type->tp_as_mapping == NULL)
1827 type->tp_as_mapping = base->tp_as_mapping;
1828 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001829
Guido van Rossum13d52f02001-08-10 21:24:08 +00001830 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001831 assert(type->tp_dict != NULL);
1832 type->tp_flags =
1833 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001835
1836 error:
1837 type->tp_flags &= ~Py_TPFLAGS_READYING;
1838 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001839}
1840
1841
1842/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1843
1844/* There's a wrapper *function* for each distinct function typedef used
1845 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1846 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1847 Most tables have only one entry; the tables for binary operators have two
1848 entries, one regular and one with reversed arguments. */
1849
1850static PyObject *
1851wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1852{
1853 inquiry func = (inquiry)wrapped;
1854 int res;
1855
1856 if (!PyArg_ParseTuple(args, ""))
1857 return NULL;
1858 res = (*func)(self);
1859 if (res == -1 && PyErr_Occurred())
1860 return NULL;
1861 return PyInt_FromLong((long)res);
1862}
1863
1864static struct wrapperbase tab_len[] = {
1865 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1866 {0}
1867};
1868
1869static PyObject *
1870wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1871{
1872 binaryfunc func = (binaryfunc)wrapped;
1873 PyObject *other;
1874
1875 if (!PyArg_ParseTuple(args, "O", &other))
1876 return NULL;
1877 return (*func)(self, other);
1878}
1879
1880static PyObject *
1881wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1882{
1883 binaryfunc func = (binaryfunc)wrapped;
1884 PyObject *other;
1885
1886 if (!PyArg_ParseTuple(args, "O", &other))
1887 return NULL;
1888 return (*func)(other, self);
1889}
1890
1891#undef BINARY
1892#define BINARY(NAME, OP) \
1893static struct wrapperbase tab_##NAME[] = { \
1894 {"__" #NAME "__", \
1895 (wrapperfunc)wrap_binaryfunc, \
1896 "x.__" #NAME "__(y) <==> " #OP}, \
1897 {"__r" #NAME "__", \
1898 (wrapperfunc)wrap_binaryfunc_r, \
1899 "y.__r" #NAME "__(x) <==> " #OP}, \
1900 {0} \
1901}
1902
1903BINARY(add, "x+y");
1904BINARY(sub, "x-y");
1905BINARY(mul, "x*y");
1906BINARY(div, "x/y");
1907BINARY(mod, "x%y");
1908BINARY(divmod, "divmod(x,y)");
1909BINARY(lshift, "x<<y");
1910BINARY(rshift, "x>>y");
1911BINARY(and, "x&y");
1912BINARY(xor, "x^y");
1913BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00001914
1915static PyObject *
1916wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
1917{
1918 coercion func = (coercion)wrapped;
1919 PyObject *other, *res;
1920 int ok;
1921
1922 if (!PyArg_ParseTuple(args, "O", &other))
1923 return NULL;
1924 ok = func(&self, &other);
1925 if (ok < 0)
1926 return NULL;
1927 if (ok > 0) {
1928 Py_INCREF(Py_NotImplemented);
1929 return Py_NotImplemented;
1930 }
1931 res = PyTuple_New(2);
1932 if (res == NULL) {
1933 Py_DECREF(self);
1934 Py_DECREF(other);
1935 return NULL;
1936 }
1937 PyTuple_SET_ITEM(res, 0, self);
1938 PyTuple_SET_ITEM(res, 1, other);
1939 return res;
1940}
1941
1942static struct wrapperbase tab_coerce[] = {
1943 {"__coerce__", (wrapperfunc)wrap_coercefunc,
1944 "x.__coerce__(y) <==> coerce(x, y)"},
1945 {0}
1946};
1947
Guido van Rossum874f15a2001-09-25 21:16:33 +00001948BINARY(floordiv, "x//y");
1949BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001950
1951static PyObject *
1952wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1953{
1954 ternaryfunc func = (ternaryfunc)wrapped;
1955 PyObject *other;
1956 PyObject *third = Py_None;
1957
1958 /* Note: This wrapper only works for __pow__() */
1959
1960 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1961 return NULL;
1962 return (*func)(self, other, third);
1963}
1964
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00001965static PyObject *
1966wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1967{
1968 ternaryfunc func = (ternaryfunc)wrapped;
1969 PyObject *other;
1970 PyObject *third = Py_None;
1971
1972 /* Note: This wrapper only works for __pow__() */
1973
1974 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1975 return NULL;
1976 return (*func)(other, self, third);
1977}
1978
Tim Peters6d6c1a32001-08-02 04:15:00 +00001979#undef TERNARY
1980#define TERNARY(NAME, OP) \
1981static struct wrapperbase tab_##NAME[] = { \
1982 {"__" #NAME "__", \
1983 (wrapperfunc)wrap_ternaryfunc, \
1984 "x.__" #NAME "__(y, z) <==> " #OP}, \
1985 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00001986 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1988 {0} \
1989}
1990
1991TERNARY(pow, "(x**y) % z");
1992
1993#undef UNARY
1994#define UNARY(NAME, OP) \
1995static struct wrapperbase tab_##NAME[] = { \
1996 {"__" #NAME "__", \
1997 (wrapperfunc)wrap_unaryfunc, \
1998 "x.__" #NAME "__() <==> " #OP}, \
1999 {0} \
2000}
2001
2002static PyObject *
2003wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2004{
2005 unaryfunc func = (unaryfunc)wrapped;
2006
2007 if (!PyArg_ParseTuple(args, ""))
2008 return NULL;
2009 return (*func)(self);
2010}
2011
2012UNARY(neg, "-x");
2013UNARY(pos, "+x");
2014UNARY(abs, "abs(x)");
2015UNARY(nonzero, "x != 0");
2016UNARY(invert, "~x");
2017UNARY(int, "int(x)");
2018UNARY(long, "long(x)");
2019UNARY(float, "float(x)");
2020UNARY(oct, "oct(x)");
2021UNARY(hex, "hex(x)");
2022
2023#undef IBINARY
2024#define IBINARY(NAME, OP) \
2025static struct wrapperbase tab_##NAME[] = { \
2026 {"__" #NAME "__", \
2027 (wrapperfunc)wrap_binaryfunc, \
2028 "x.__" #NAME "__(y) <==> " #OP}, \
2029 {0} \
2030}
2031
2032IBINARY(iadd, "x+=y");
2033IBINARY(isub, "x-=y");
2034IBINARY(imul, "x*=y");
2035IBINARY(idiv, "x/=y");
2036IBINARY(imod, "x%=y");
2037IBINARY(ilshift, "x<<=y");
2038IBINARY(irshift, "x>>=y");
2039IBINARY(iand, "x&=y");
2040IBINARY(ixor, "x^=y");
2041IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002042IBINARY(ifloordiv, "x//=y");
2043IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002044
2045#undef ITERNARY
2046#define ITERNARY(NAME, OP) \
2047static struct wrapperbase tab_##NAME[] = { \
2048 {"__" #NAME "__", \
2049 (wrapperfunc)wrap_ternaryfunc, \
2050 "x.__" #NAME "__(y) <==> " #OP}, \
2051 {0} \
2052}
2053
2054ITERNARY(ipow, "x = (x**y) % z");
2055
2056static struct wrapperbase tab_getitem[] = {
2057 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2058 "x.__getitem__(y) <==> x[y]"},
2059 {0}
2060};
2061
2062static PyObject *
2063wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2064{
2065 intargfunc func = (intargfunc)wrapped;
2066 int i;
2067
2068 if (!PyArg_ParseTuple(args, "i", &i))
2069 return NULL;
2070 return (*func)(self, i);
2071}
2072
2073static struct wrapperbase tab_mul_int[] = {
2074 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2075 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2076 {0}
2077};
2078
2079static struct wrapperbase tab_concat[] = {
2080 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2081 {0}
2082};
2083
2084static struct wrapperbase tab_imul_int[] = {
2085 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2086 {0}
2087};
2088
Guido van Rossum5d815f32001-08-17 21:57:47 +00002089static int
2090getindex(PyObject *self, PyObject *arg)
2091{
2092 int i;
2093
2094 i = PyInt_AsLong(arg);
2095 if (i == -1 && PyErr_Occurred())
2096 return -1;
2097 if (i < 0) {
2098 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2099 if (sq && sq->sq_length) {
2100 int n = (*sq->sq_length)(self);
2101 if (n < 0)
2102 return -1;
2103 i += n;
2104 }
2105 }
2106 return i;
2107}
2108
2109static PyObject *
2110wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2111{
2112 intargfunc func = (intargfunc)wrapped;
2113 PyObject *arg;
2114 int i;
2115
Guido van Rossumf4593e02001-10-03 12:09:30 +00002116 if (PyTuple_GET_SIZE(args) == 1) {
2117 arg = PyTuple_GET_ITEM(args, 0);
2118 i = getindex(self, arg);
2119 if (i == -1 && PyErr_Occurred())
2120 return NULL;
2121 return (*func)(self, i);
2122 }
2123 PyArg_ParseTuple(args, "O", &arg);
2124 assert(PyErr_Occurred());
2125 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002126}
2127
Tim Peters6d6c1a32001-08-02 04:15:00 +00002128static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002129 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002130 "x.__getitem__(i) <==> x[i]"},
2131 {0}
2132};
2133
2134static PyObject *
2135wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2136{
2137 intintargfunc func = (intintargfunc)wrapped;
2138 int i, j;
2139
2140 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2141 return NULL;
2142 return (*func)(self, i, j);
2143}
2144
2145static struct wrapperbase tab_getslice[] = {
2146 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2147 "x.__getslice__(i, j) <==> x[i:j]"},
2148 {0}
2149};
2150
2151static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002152wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002153{
2154 intobjargproc func = (intobjargproc)wrapped;
2155 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002156 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002157
Guido van Rossum5d815f32001-08-17 21:57:47 +00002158 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2159 return NULL;
2160 i = getindex(self, arg);
2161 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002162 return NULL;
2163 res = (*func)(self, i, value);
2164 if (res == -1 && PyErr_Occurred())
2165 return NULL;
2166 Py_INCREF(Py_None);
2167 return Py_None;
2168}
2169
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002170static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002171wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002172{
2173 intobjargproc func = (intobjargproc)wrapped;
2174 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002175 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002176
Guido van Rossum5d815f32001-08-17 21:57:47 +00002177 if (!PyArg_ParseTuple(args, "O", &arg))
2178 return NULL;
2179 i = getindex(self, arg);
2180 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002181 return NULL;
2182 res = (*func)(self, i, NULL);
2183 if (res == -1 && PyErr_Occurred())
2184 return NULL;
2185 Py_INCREF(Py_None);
2186 return Py_None;
2187}
2188
Tim Peters6d6c1a32001-08-02 04:15:00 +00002189static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002190 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002191 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002192 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002193 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002194 {0}
2195};
2196
2197static PyObject *
2198wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2199{
2200 intintobjargproc func = (intintobjargproc)wrapped;
2201 int i, j, res;
2202 PyObject *value;
2203
2204 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2205 return NULL;
2206 res = (*func)(self, i, j, value);
2207 if (res == -1 && PyErr_Occurred())
2208 return NULL;
2209 Py_INCREF(Py_None);
2210 return Py_None;
2211}
2212
2213static struct wrapperbase tab_setslice[] = {
2214 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2215 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
2216 {0}
2217};
2218
2219/* XXX objobjproc is a misnomer; should be objargpred */
2220static PyObject *
2221wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2222{
2223 objobjproc func = (objobjproc)wrapped;
2224 int res;
2225 PyObject *value;
2226
2227 if (!PyArg_ParseTuple(args, "O", &value))
2228 return NULL;
2229 res = (*func)(self, value);
2230 if (res == -1 && PyErr_Occurred())
2231 return NULL;
2232 return PyInt_FromLong((long)res);
2233}
2234
2235static struct wrapperbase tab_contains[] = {
2236 {"__contains__", (wrapperfunc)wrap_objobjproc,
2237 "x.__contains__(y) <==> y in x"},
2238 {0}
2239};
2240
2241static PyObject *
2242wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2243{
2244 objobjargproc func = (objobjargproc)wrapped;
2245 int res;
2246 PyObject *key, *value;
2247
2248 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2249 return NULL;
2250 res = (*func)(self, key, value);
2251 if (res == -1 && PyErr_Occurred())
2252 return NULL;
2253 Py_INCREF(Py_None);
2254 return Py_None;
2255}
2256
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002257static PyObject *
2258wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2259{
2260 objobjargproc func = (objobjargproc)wrapped;
2261 int res;
2262 PyObject *key;
2263
2264 if (!PyArg_ParseTuple(args, "O", &key))
2265 return NULL;
2266 res = (*func)(self, key, NULL);
2267 if (res == -1 && PyErr_Occurred())
2268 return NULL;
2269 Py_INCREF(Py_None);
2270 return Py_None;
2271}
2272
Tim Peters6d6c1a32001-08-02 04:15:00 +00002273static struct wrapperbase tab_setitem[] = {
2274 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2275 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002276 {"__delitem__", (wrapperfunc)wrap_delitem,
2277 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002278 {0}
2279};
2280
2281static PyObject *
2282wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2283{
2284 cmpfunc func = (cmpfunc)wrapped;
2285 int res;
2286 PyObject *other;
2287
2288 if (!PyArg_ParseTuple(args, "O", &other))
2289 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002290 if (other->ob_type->tp_compare != func &&
2291 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002292 PyErr_Format(
2293 PyExc_TypeError,
2294 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2295 self->ob_type->tp_name,
2296 self->ob_type->tp_name,
2297 other->ob_type->tp_name);
2298 return NULL;
2299 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002300 res = (*func)(self, other);
2301 if (PyErr_Occurred())
2302 return NULL;
2303 return PyInt_FromLong((long)res);
2304}
2305
2306static struct wrapperbase tab_cmp[] = {
2307 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2308 "x.__cmp__(y) <==> cmp(x,y)"},
2309 {0}
2310};
2311
2312static struct wrapperbase tab_repr[] = {
2313 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2314 "x.__repr__() <==> repr(x)"},
2315 {0}
2316};
2317
2318static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002319 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2320 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002321 {0}
2322};
2323
2324static PyObject *
2325wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2326{
2327 setattrofunc func = (setattrofunc)wrapped;
2328 int res;
2329 PyObject *name, *value;
2330
2331 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2332 return NULL;
2333 res = (*func)(self, name, value);
2334 if (res < 0)
2335 return NULL;
2336 Py_INCREF(Py_None);
2337 return Py_None;
2338}
2339
2340static PyObject *
2341wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2342{
2343 setattrofunc func = (setattrofunc)wrapped;
2344 int res;
2345 PyObject *name;
2346
2347 if (!PyArg_ParseTuple(args, "O", &name))
2348 return NULL;
2349 res = (*func)(self, name, NULL);
2350 if (res < 0)
2351 return NULL;
2352 Py_INCREF(Py_None);
2353 return Py_None;
2354}
2355
2356static struct wrapperbase tab_setattr[] = {
2357 {"__setattr__", (wrapperfunc)wrap_setattr,
2358 "x.__setattr__('name', value) <==> x.name = value"},
2359 {"__delattr__", (wrapperfunc)wrap_delattr,
2360 "x.__delattr__('name') <==> del x.name"},
2361 {0}
2362};
2363
2364static PyObject *
2365wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2366{
2367 hashfunc func = (hashfunc)wrapped;
2368 long res;
2369
2370 if (!PyArg_ParseTuple(args, ""))
2371 return NULL;
2372 res = (*func)(self);
2373 if (res == -1 && PyErr_Occurred())
2374 return NULL;
2375 return PyInt_FromLong(res);
2376}
2377
2378static struct wrapperbase tab_hash[] = {
2379 {"__hash__", (wrapperfunc)wrap_hashfunc,
2380 "x.__hash__() <==> hash(x)"},
2381 {0}
2382};
2383
2384static PyObject *
2385wrap_call(PyObject *self, PyObject *args, void *wrapped)
2386{
2387 ternaryfunc func = (ternaryfunc)wrapped;
2388
2389 /* XXX What about keyword arguments? */
2390 return (*func)(self, args, NULL);
2391}
2392
2393static struct wrapperbase tab_call[] = {
2394 {"__call__", (wrapperfunc)wrap_call,
2395 "x.__call__(...) <==> x(...)"},
2396 {0}
2397};
2398
2399static struct wrapperbase tab_str[] = {
2400 {"__str__", (wrapperfunc)wrap_unaryfunc,
2401 "x.__str__() <==> str(x)"},
2402 {0}
2403};
2404
2405static PyObject *
2406wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2407{
2408 richcmpfunc func = (richcmpfunc)wrapped;
2409 PyObject *other;
2410
2411 if (!PyArg_ParseTuple(args, "O", &other))
2412 return NULL;
2413 return (*func)(self, other, op);
2414}
2415
2416#undef RICHCMP_WRAPPER
2417#define RICHCMP_WRAPPER(NAME, OP) \
2418static PyObject * \
2419richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2420{ \
2421 return wrap_richcmpfunc(self, args, wrapped, OP); \
2422}
2423
Jack Jansen8e938b42001-08-08 15:29:49 +00002424RICHCMP_WRAPPER(lt, Py_LT)
2425RICHCMP_WRAPPER(le, Py_LE)
2426RICHCMP_WRAPPER(eq, Py_EQ)
2427RICHCMP_WRAPPER(ne, Py_NE)
2428RICHCMP_WRAPPER(gt, Py_GT)
2429RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002430
2431#undef RICHCMP_ENTRY
2432#define RICHCMP_ENTRY(NAME, EXPR) \
2433 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2434 "x.__" #NAME "__(y) <==> " EXPR}
2435
2436static struct wrapperbase tab_richcmp[] = {
2437 RICHCMP_ENTRY(lt, "x<y"),
2438 RICHCMP_ENTRY(le, "x<=y"),
2439 RICHCMP_ENTRY(eq, "x==y"),
2440 RICHCMP_ENTRY(ne, "x!=y"),
2441 RICHCMP_ENTRY(gt, "x>y"),
2442 RICHCMP_ENTRY(ge, "x>=y"),
2443 {0}
2444};
2445
2446static struct wrapperbase tab_iter[] = {
2447 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2448 {0}
2449};
2450
2451static PyObject *
2452wrap_next(PyObject *self, PyObject *args, void *wrapped)
2453{
2454 unaryfunc func = (unaryfunc)wrapped;
2455 PyObject *res;
2456
2457 if (!PyArg_ParseTuple(args, ""))
2458 return NULL;
2459 res = (*func)(self);
2460 if (res == NULL && !PyErr_Occurred())
2461 PyErr_SetNone(PyExc_StopIteration);
2462 return res;
2463}
2464
2465static struct wrapperbase tab_next[] = {
2466 {"next", (wrapperfunc)wrap_next,
2467 "x.next() -> the next value, or raise StopIteration"},
2468 {0}
2469};
2470
2471static PyObject *
2472wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2473{
2474 descrgetfunc func = (descrgetfunc)wrapped;
2475 PyObject *obj;
2476 PyObject *type = NULL;
2477
2478 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2479 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002480 return (*func)(self, obj, type);
2481}
2482
2483static struct wrapperbase tab_descr_get[] = {
2484 {"__get__", (wrapperfunc)wrap_descr_get,
2485 "descr.__get__(obj, type) -> value"},
2486 {0}
2487};
2488
2489static PyObject *
2490wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2491{
2492 descrsetfunc func = (descrsetfunc)wrapped;
2493 PyObject *obj, *value;
2494 int ret;
2495
2496 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2497 return NULL;
2498 ret = (*func)(self, obj, value);
2499 if (ret < 0)
2500 return NULL;
2501 Py_INCREF(Py_None);
2502 return Py_None;
2503}
2504
2505static struct wrapperbase tab_descr_set[] = {
2506 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2507 "descr.__set__(obj, value)"},
2508 {0}
2509};
2510
2511static PyObject *
2512wrap_init(PyObject *self, PyObject *args, void *wrapped)
2513{
2514 initproc func = (initproc)wrapped;
2515
2516 /* XXX What about keyword arguments? */
2517 if (func(self, args, NULL) < 0)
2518 return NULL;
2519 Py_INCREF(Py_None);
2520 return Py_None;
2521}
2522
2523static struct wrapperbase tab_init[] = {
2524 {"__init__", (wrapperfunc)wrap_init,
2525 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002526 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002527 {0}
2528};
2529
2530static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002531tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002532{
Barry Warsaw60f01882001-08-22 19:24:42 +00002533 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002534 PyObject *arg0, *res;
2535
2536 if (self == NULL || !PyType_Check(self))
2537 Py_FatalError("__new__() called with non-type 'self'");
2538 type = (PyTypeObject *)self;
2539 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002540 PyErr_Format(PyExc_TypeError,
2541 "%s.__new__(): not enough arguments",
2542 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002543 return NULL;
2544 }
2545 arg0 = PyTuple_GET_ITEM(args, 0);
2546 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002547 PyErr_Format(PyExc_TypeError,
2548 "%s.__new__(X): X is not a type object (%s)",
2549 type->tp_name,
2550 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002551 return NULL;
2552 }
2553 subtype = (PyTypeObject *)arg0;
2554 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002555 PyErr_Format(PyExc_TypeError,
2556 "%s.__new__(%s): %s is not a subtype of %s",
2557 type->tp_name,
2558 subtype->tp_name,
2559 subtype->tp_name,
2560 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002561 return NULL;
2562 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002563
2564 /* Check that the use doesn't do something silly and unsafe like
2565 object.__new__(dictionary). To do this, we check that the
2566 most derived base that's not a heap type is this type. */
2567 staticbase = subtype;
2568 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2569 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002570 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002571 PyErr_Format(PyExc_TypeError,
2572 "%s.__new__(%s) is not safe, use %s.__new__()",
2573 type->tp_name,
2574 subtype->tp_name,
2575 staticbase == NULL ? "?" : staticbase->tp_name);
2576 return NULL;
2577 }
2578
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002579 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2580 if (args == NULL)
2581 return NULL;
2582 res = type->tp_new(subtype, args, kwds);
2583 Py_DECREF(args);
2584 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002585}
2586
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002587static struct PyMethodDef tp_new_methoddef[] = {
2588 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2589 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002590 {0}
2591};
2592
2593static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002594add_tp_new_wrapper(PyTypeObject *type)
2595{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002596 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002597
Guido van Rossumf040ede2001-08-07 16:40:56 +00002598 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2599 return 0;
2600 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002601 if (func == NULL)
2602 return -1;
2603 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2604}
2605
Guido van Rossum13d52f02001-08-10 21:24:08 +00002606static int
2607add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2608{
2609 PyObject *dict = type->tp_defined;
2610
2611 for (; wraps->name != NULL; wraps++) {
2612 PyObject *descr;
2613 if (PyDict_GetItemString(dict, wraps->name))
2614 continue;
2615 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2616 if (descr == NULL)
2617 return -1;
2618 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2619 return -1;
2620 Py_DECREF(descr);
2621 }
2622 return 0;
2623}
2624
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002625/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002626 dictionary with method descriptors for function slots. For each
2627 function slot (like tp_repr) that's defined in the type, one or
2628 more corresponding descriptors are added in the type's tp_defined
2629 dictionary under the appropriate name (like __repr__). Some
2630 function slots cause more than one descriptor to be added (for
2631 example, the nb_add slot adds both __add__ and __radd__
2632 descriptors) and some function slots compete for the same
2633 descriptor (for example both sq_item and mp_subscript generate a
2634 __getitem__ descriptor). This only adds new descriptors and
2635 doesn't overwrite entries in tp_defined that were previously
2636 defined. The descriptors contain a reference to the C function
2637 they must call, so that it's safe if they are copied into a
2638 subtype's __dict__ and the subtype has a different C function in
2639 its slot -- calling the method defined by the descriptor will call
2640 the C function that was used to create it, rather than the C
2641 function present in the slot when it is called. (This is important
2642 because a subtype may have a C function in the slot that calls the
2643 method from the dictionary, and we want to avoid infinite recursion
2644 here.) */
2645
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002646static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002647add_operators(PyTypeObject *type)
2648{
2649 PySequenceMethods *sq;
2650 PyMappingMethods *mp;
2651 PyNumberMethods *nb;
2652
2653#undef ADD
2654#define ADD(SLOT, TABLE) \
2655 if (SLOT) { \
2656 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2657 return -1; \
2658 }
2659
2660 if ((sq = type->tp_as_sequence) != NULL) {
2661 ADD(sq->sq_length, tab_len);
2662 ADD(sq->sq_concat, tab_concat);
2663 ADD(sq->sq_repeat, tab_mul_int);
2664 ADD(sq->sq_item, tab_getitem_int);
2665 ADD(sq->sq_slice, tab_getslice);
2666 ADD(sq->sq_ass_item, tab_setitem_int);
2667 ADD(sq->sq_ass_slice, tab_setslice);
2668 ADD(sq->sq_contains, tab_contains);
2669 ADD(sq->sq_inplace_concat, tab_iadd);
2670 ADD(sq->sq_inplace_repeat, tab_imul_int);
2671 }
2672
2673 if ((mp = type->tp_as_mapping) != NULL) {
2674 if (sq->sq_length == NULL)
2675 ADD(mp->mp_length, tab_len);
2676 ADD(mp->mp_subscript, tab_getitem);
2677 ADD(mp->mp_ass_subscript, tab_setitem);
2678 }
2679
2680 /* We don't support "old-style numbers" because their binary
2681 operators require that both arguments have the same type;
2682 the wrappers here only work for new-style numbers. */
2683 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2684 (nb = type->tp_as_number) != NULL) {
2685 ADD(nb->nb_add, tab_add);
2686 ADD(nb->nb_subtract, tab_sub);
2687 ADD(nb->nb_multiply, tab_mul);
2688 ADD(nb->nb_divide, tab_div);
2689 ADD(nb->nb_remainder, tab_mod);
2690 ADD(nb->nb_divmod, tab_divmod);
2691 ADD(nb->nb_power, tab_pow);
2692 ADD(nb->nb_negative, tab_neg);
2693 ADD(nb->nb_positive, tab_pos);
2694 ADD(nb->nb_absolute, tab_abs);
2695 ADD(nb->nb_nonzero, tab_nonzero);
2696 ADD(nb->nb_invert, tab_invert);
2697 ADD(nb->nb_lshift, tab_lshift);
2698 ADD(nb->nb_rshift, tab_rshift);
2699 ADD(nb->nb_and, tab_and);
2700 ADD(nb->nb_xor, tab_xor);
2701 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002702 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002703 ADD(nb->nb_int, tab_int);
2704 ADD(nb->nb_long, tab_long);
2705 ADD(nb->nb_float, tab_float);
2706 ADD(nb->nb_oct, tab_oct);
2707 ADD(nb->nb_hex, tab_hex);
2708 ADD(nb->nb_inplace_add, tab_iadd);
2709 ADD(nb->nb_inplace_subtract, tab_isub);
2710 ADD(nb->nb_inplace_multiply, tab_imul);
2711 ADD(nb->nb_inplace_divide, tab_idiv);
2712 ADD(nb->nb_inplace_remainder, tab_imod);
2713 ADD(nb->nb_inplace_power, tab_ipow);
2714 ADD(nb->nb_inplace_lshift, tab_ilshift);
2715 ADD(nb->nb_inplace_rshift, tab_irshift);
2716 ADD(nb->nb_inplace_and, tab_iand);
2717 ADD(nb->nb_inplace_xor, tab_ixor);
2718 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum874f15a2001-09-25 21:16:33 +00002719 if (type->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2720 ADD(nb->nb_floor_divide, tab_floordiv);
2721 ADD(nb->nb_true_divide, tab_truediv);
2722 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2723 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2724 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725 }
2726
2727 ADD(type->tp_getattro, tab_getattr);
2728 ADD(type->tp_setattro, tab_setattr);
2729 ADD(type->tp_compare, tab_cmp);
2730 ADD(type->tp_repr, tab_repr);
2731 ADD(type->tp_hash, tab_hash);
2732 ADD(type->tp_call, tab_call);
2733 ADD(type->tp_str, tab_str);
2734 ADD(type->tp_richcompare, tab_richcmp);
2735 ADD(type->tp_iter, tab_iter);
2736 ADD(type->tp_iternext, tab_next);
2737 ADD(type->tp_descr_get, tab_descr_get);
2738 ADD(type->tp_descr_set, tab_descr_set);
2739 ADD(type->tp_init, tab_init);
2740
Guido van Rossumf040ede2001-08-07 16:40:56 +00002741 if (type->tp_new != NULL) {
2742 if (add_tp_new_wrapper(type) < 0)
2743 return -1;
2744 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745
2746 return 0;
2747}
2748
Guido van Rossumf040ede2001-08-07 16:40:56 +00002749/* Slot wrappers that call the corresponding __foo__ slot. See comments
2750 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751
Guido van Rossumdc91b992001-08-08 22:26:22 +00002752#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002753static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002754FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002756 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002757 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758}
2759
Guido van Rossumdc91b992001-08-08 22:26:22 +00002760#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002761static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002762FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002763{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002764 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002765 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766}
2767
Guido van Rossumdc91b992001-08-08 22:26:22 +00002768
2769#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002770static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002771FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002773 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002774 int do_other = self->ob_type != other->ob_type && \
2775 other->ob_type->tp_as_number != NULL && \
2776 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002777 if (self->ob_type->tp_as_number != NULL && \
2778 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2779 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002780 if (do_other && \
2781 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2782 r = call_maybe( \
2783 other, ROPSTR, &rcache_str, "(O)", self); \
2784 if (r != Py_NotImplemented) \
2785 return r; \
2786 Py_DECREF(r); \
2787 do_other = 0; \
2788 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002789 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002790 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002791 if (r != Py_NotImplemented || \
2792 other->ob_type == self->ob_type) \
2793 return r; \
2794 Py_DECREF(r); \
2795 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002796 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002797 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002798 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002799 } \
2800 Py_INCREF(Py_NotImplemented); \
2801 return Py_NotImplemented; \
2802}
2803
2804#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2805 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2806
2807#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2808static PyObject * \
2809FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2810{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002811 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002812 return call_method(self, OPSTR, &cache_str, \
2813 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002814}
2815
2816static int
2817slot_sq_length(PyObject *self)
2818{
Guido van Rossum2730b132001-08-28 18:22:14 +00002819 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002820 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002821 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002822
2823 if (res == NULL)
2824 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002825 len = (int)PyInt_AsLong(res);
2826 Py_DECREF(res);
2827 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002828}
2829
Guido van Rossumdc91b992001-08-08 22:26:22 +00002830SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2831SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002832
2833/* Super-optimized version of slot_sq_item.
2834 Other slots could do the same... */
2835static PyObject *
2836slot_sq_item(PyObject *self, int i)
2837{
2838 static PyObject *getitem_str;
2839 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2840 descrgetfunc f;
2841
2842 if (getitem_str == NULL) {
2843 getitem_str = PyString_InternFromString("__getitem__");
2844 if (getitem_str == NULL)
2845 return NULL;
2846 }
2847 func = _PyType_Lookup(self->ob_type, getitem_str);
2848 if (func != NULL) {
2849 if (func->ob_type == &PyWrapperDescr_Type) {
2850 PyWrapperDescrObject *wrapper =
2851 (PyWrapperDescrObject *)func;
2852 if (wrapper->d_base->wrapper == wrap_sq_item) {
2853 intargfunc f;
2854 f = (intargfunc)(wrapper->d_wrapped);
2855 return f(self, i);
2856 }
2857 }
2858 if ((f = func->ob_type->tp_descr_get) == NULL)
2859 Py_INCREF(func);
2860 else
2861 func = f(func, self, (PyObject *)(self->ob_type));
2862 ival = PyInt_FromLong(i);
2863 if (ival != NULL) {
2864 args = PyTuple_New(1);
2865 if (args != NULL) {
2866 PyTuple_SET_ITEM(args, 0, ival);
2867 retval = PyObject_Call(func, args, NULL);
2868 Py_XDECREF(args);
2869 Py_XDECREF(func);
2870 return retval;
2871 }
2872 }
2873 }
2874 else {
2875 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2876 }
2877 Py_XDECREF(args);
2878 Py_XDECREF(ival);
2879 Py_XDECREF(func);
2880 return NULL;
2881}
2882
Guido van Rossumdc91b992001-08-08 22:26:22 +00002883SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002884
2885static int
2886slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2887{
2888 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002889 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002890
2891 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002892 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002893 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002894 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002895 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002896 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002897 if (res == NULL)
2898 return -1;
2899 Py_DECREF(res);
2900 return 0;
2901}
2902
2903static int
2904slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2905{
2906 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002907 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002908
2909 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002910 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002911 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002912 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002913 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002914 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002915 if (res == NULL)
2916 return -1;
2917 Py_DECREF(res);
2918 return 0;
2919}
2920
2921static int
2922slot_sq_contains(PyObject *self, PyObject *value)
2923{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002924 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002925 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002926
Guido van Rossum55f20992001-10-01 17:18:22 +00002927 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002928
2929 if (func != NULL) {
2930 args = Py_BuildValue("(O)", value);
2931 if (args == NULL)
2932 res = NULL;
2933 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002934 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002935 Py_DECREF(args);
2936 }
2937 Py_DECREF(func);
2938 if (res == NULL)
2939 return -1;
2940 return PyObject_IsTrue(res);
2941 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002942 else if (PyErr_Occurred())
2943 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002944 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002945 return _PySequence_IterSearch(self, value,
2946 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002947 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002948}
2949
Guido van Rossumdc91b992001-08-08 22:26:22 +00002950SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2951SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002952
2953#define slot_mp_length slot_sq_length
2954
Guido van Rossumdc91b992001-08-08 22:26:22 +00002955SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956
2957static int
2958slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2959{
2960 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002961 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962
2963 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002964 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002965 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002966 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002967 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002968 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002969 if (res == NULL)
2970 return -1;
2971 Py_DECREF(res);
2972 return 0;
2973}
2974
Guido van Rossumdc91b992001-08-08 22:26:22 +00002975SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2976SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2977SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2978SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2979SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2980SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2981
2982staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2983
2984SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2985 nb_power, "__pow__", "__rpow__")
2986
2987static PyObject *
2988slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2989{
Guido van Rossum2730b132001-08-28 18:22:14 +00002990 static PyObject *pow_str;
2991
Guido van Rossumdc91b992001-08-08 22:26:22 +00002992 if (modulus == Py_None)
2993 return slot_nb_power_binary(self, other);
2994 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002995 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002996 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002997}
2998
2999SLOT0(slot_nb_negative, "__neg__")
3000SLOT0(slot_nb_positive, "__pos__")
3001SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003002
3003static int
3004slot_nb_nonzero(PyObject *self)
3005{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003006 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003007 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003008
Guido van Rossum55f20992001-10-01 17:18:22 +00003009 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003010 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003011 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003012 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003013 func = lookup_maybe(self, "__len__", &len_str);
3014 if (func == NULL) {
3015 if (PyErr_Occurred())
3016 return -1;
3017 else
3018 return 1;
3019 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003020 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003021 res = PyObject_CallObject(func, NULL);
3022 Py_DECREF(func);
3023 if (res == NULL)
3024 return -1;
3025 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003026}
3027
Guido van Rossumdc91b992001-08-08 22:26:22 +00003028SLOT0(slot_nb_invert, "__invert__")
3029SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3030SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3031SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3032SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3033SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003034
3035static int
3036slot_nb_coerce(PyObject **a, PyObject **b)
3037{
3038 static PyObject *coerce_str;
3039 PyObject *self = *a, *other = *b;
3040
3041 if (self->ob_type->tp_as_number != NULL &&
3042 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3043 PyObject *r;
3044 r = call_maybe(
3045 self, "__coerce__", &coerce_str, "(O)", other);
3046 if (r == NULL)
3047 return -1;
3048 if (r == Py_NotImplemented) {
3049 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003050 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003051 else {
3052 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3053 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003054 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003055 Py_DECREF(r);
3056 return -1;
3057 }
3058 *a = PyTuple_GET_ITEM(r, 0);
3059 Py_INCREF(*a);
3060 *b = PyTuple_GET_ITEM(r, 1);
3061 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003062 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003063 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003064 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003065 }
3066 if (other->ob_type->tp_as_number != NULL &&
3067 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3068 PyObject *r;
3069 r = call_maybe(
3070 other, "__coerce__", &coerce_str, "(O)", self);
3071 if (r == NULL)
3072 return -1;
3073 if (r == Py_NotImplemented) {
3074 Py_DECREF(r);
3075 return 1;
3076 }
3077 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3078 PyErr_SetString(PyExc_TypeError,
3079 "__coerce__ didn't return a 2-tuple");
3080 Py_DECREF(r);
3081 return -1;
3082 }
3083 *a = PyTuple_GET_ITEM(r, 1);
3084 Py_INCREF(*a);
3085 *b = PyTuple_GET_ITEM(r, 0);
3086 Py_INCREF(*b);
3087 Py_DECREF(r);
3088 return 0;
3089 }
3090 return 1;
3091}
3092
Guido van Rossumdc91b992001-08-08 22:26:22 +00003093SLOT0(slot_nb_int, "__int__")
3094SLOT0(slot_nb_long, "__long__")
3095SLOT0(slot_nb_float, "__float__")
3096SLOT0(slot_nb_oct, "__oct__")
3097SLOT0(slot_nb_hex, "__hex__")
3098SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3099SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3100SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3101SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3102SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3103SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3104SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3105SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3106SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3107SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3108SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3109SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3110 "__floordiv__", "__rfloordiv__")
3111SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3112SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3113SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003114
3115static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003116half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003117{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003118 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003119 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003120 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003121
Guido van Rossum60718732001-08-28 17:47:51 +00003122 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003123 if (func == NULL) {
3124 PyErr_Clear();
3125 }
3126 else {
3127 args = Py_BuildValue("(O)", other);
3128 if (args == NULL)
3129 res = NULL;
3130 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003131 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003132 Py_DECREF(args);
3133 }
3134 if (res != Py_NotImplemented) {
3135 if (res == NULL)
3136 return -2;
3137 c = PyInt_AsLong(res);
3138 Py_DECREF(res);
3139 if (c == -1 && PyErr_Occurred())
3140 return -2;
3141 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3142 }
3143 Py_DECREF(res);
3144 }
3145 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003146}
3147
Guido van Rossumab3b0342001-09-18 20:38:53 +00003148/* This slot is published for the benefit of try_3way_compare in object.c */
3149int
3150_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003151{
3152 int c;
3153
Guido van Rossumab3b0342001-09-18 20:38:53 +00003154 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003155 c = half_compare(self, other);
3156 if (c <= 1)
3157 return c;
3158 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003159 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003160 c = half_compare(other, self);
3161 if (c < -1)
3162 return -2;
3163 if (c <= 1)
3164 return -c;
3165 }
3166 return (void *)self < (void *)other ? -1 :
3167 (void *)self > (void *)other ? 1 : 0;
3168}
3169
3170static PyObject *
3171slot_tp_repr(PyObject *self)
3172{
3173 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003174 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003175
Guido van Rossum60718732001-08-28 17:47:51 +00003176 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003177 if (func != NULL) {
3178 res = PyEval_CallObject(func, NULL);
3179 Py_DECREF(func);
3180 return res;
3181 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003182 PyErr_Clear();
3183 return PyString_FromFormat("<%s object at %p>",
3184 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003185}
3186
3187static PyObject *
3188slot_tp_str(PyObject *self)
3189{
3190 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003191 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003192
Guido van Rossum60718732001-08-28 17:47:51 +00003193 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003194 if (func != NULL) {
3195 res = PyEval_CallObject(func, NULL);
3196 Py_DECREF(func);
3197 return res;
3198 }
3199 else {
3200 PyErr_Clear();
3201 return slot_tp_repr(self);
3202 }
3203}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003204
3205static long
3206slot_tp_hash(PyObject *self)
3207{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003208 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003209 static PyObject *hash_str, *eq_str, *cmp_str;
3210
Tim Peters6d6c1a32001-08-02 04:15:00 +00003211 long h;
3212
Guido van Rossum60718732001-08-28 17:47:51 +00003213 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003214
3215 if (func != NULL) {
3216 res = PyEval_CallObject(func, NULL);
3217 Py_DECREF(func);
3218 if (res == NULL)
3219 return -1;
3220 h = PyInt_AsLong(res);
3221 }
3222 else {
3223 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003224 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003225 if (func == NULL) {
3226 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003227 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003228 }
3229 if (func != NULL) {
3230 Py_DECREF(func);
3231 PyErr_SetString(PyExc_TypeError, "unhashable type");
3232 return -1;
3233 }
3234 PyErr_Clear();
3235 h = _Py_HashPointer((void *)self);
3236 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003237 if (h == -1 && !PyErr_Occurred())
3238 h = -2;
3239 return h;
3240}
3241
3242static PyObject *
3243slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3244{
Guido van Rossum60718732001-08-28 17:47:51 +00003245 static PyObject *call_str;
3246 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003247 PyObject *res;
3248
3249 if (meth == NULL)
3250 return NULL;
3251 res = PyObject_Call(meth, args, kwds);
3252 Py_DECREF(meth);
3253 return res;
3254}
3255
Tim Peters6d6c1a32001-08-02 04:15:00 +00003256static PyObject *
3257slot_tp_getattro(PyObject *self, PyObject *name)
3258{
3259 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003260 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003261 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003262
Guido van Rossum8e248182001-08-12 05:17:56 +00003263 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003264 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003265 if (getattr_str == NULL)
3266 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003267 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003268 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003269 if (getattr == NULL) {
3270 /* Avoid further slowdowns */
3271 if (tp->tp_getattro == slot_tp_getattro)
3272 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003273 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003274 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003275 return PyObject_CallFunction(getattr, "OO", self, name);
3276}
3277
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003278static PyObject *
3279slot_tp_getattr_hook(PyObject *self, PyObject *name)
3280{
3281 PyTypeObject *tp = self->ob_type;
3282 PyObject *getattr, *getattribute, *res;
3283 static PyObject *getattribute_str = NULL;
3284 static PyObject *getattr_str = NULL;
3285
3286 if (getattr_str == NULL) {
3287 getattr_str = PyString_InternFromString("__getattr__");
3288 if (getattr_str == NULL)
3289 return NULL;
3290 }
3291 if (getattribute_str == NULL) {
3292 getattribute_str =
3293 PyString_InternFromString("__getattribute__");
3294 if (getattribute_str == NULL)
3295 return NULL;
3296 }
3297 getattr = _PyType_Lookup(tp, getattr_str);
3298 getattribute = _PyType_Lookup(tp, getattribute_str);
3299 if (getattr == NULL && getattribute == NULL) {
3300 /* Avoid further slowdowns */
3301 if (tp->tp_getattro == slot_tp_getattr_hook)
3302 tp->tp_getattro = PyObject_GenericGetAttr;
3303 return PyObject_GenericGetAttr(self, name);
3304 }
3305 if (getattribute == NULL)
3306 res = PyObject_GenericGetAttr(self, name);
3307 else
3308 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003309 if (getattr != NULL &&
3310 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003311 PyErr_Clear();
3312 res = PyObject_CallFunction(getattr, "OO", self, name);
3313 }
3314 return res;
3315}
3316
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317static int
3318slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3319{
3320 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003321 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003322
3323 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003324 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003325 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003326 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003327 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003328 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003329 if (res == NULL)
3330 return -1;
3331 Py_DECREF(res);
3332 return 0;
3333}
3334
3335/* Map rich comparison operators to their __xx__ namesakes */
3336static char *name_op[] = {
3337 "__lt__",
3338 "__le__",
3339 "__eq__",
3340 "__ne__",
3341 "__gt__",
3342 "__ge__",
3343};
3344
3345static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003346half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003347{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003348 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003349 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003350
Guido van Rossum60718732001-08-28 17:47:51 +00003351 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003352 if (func == NULL) {
3353 PyErr_Clear();
3354 Py_INCREF(Py_NotImplemented);
3355 return Py_NotImplemented;
3356 }
3357 args = Py_BuildValue("(O)", other);
3358 if (args == NULL)
3359 res = NULL;
3360 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003361 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003362 Py_DECREF(args);
3363 }
3364 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365 return res;
3366}
3367
Guido van Rossumb8f63662001-08-15 23:57:02 +00003368/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3369static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3370
3371static PyObject *
3372slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3373{
3374 PyObject *res;
3375
3376 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3377 res = half_richcompare(self, other, op);
3378 if (res != Py_NotImplemented)
3379 return res;
3380 Py_DECREF(res);
3381 }
3382 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3383 res = half_richcompare(other, self, swapped_op[op]);
3384 if (res != Py_NotImplemented) {
3385 return res;
3386 }
3387 Py_DECREF(res);
3388 }
3389 Py_INCREF(Py_NotImplemented);
3390 return Py_NotImplemented;
3391}
3392
3393static PyObject *
3394slot_tp_iter(PyObject *self)
3395{
3396 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003397 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003398
Guido van Rossum60718732001-08-28 17:47:51 +00003399 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003400 if (func != NULL) {
3401 res = PyObject_CallObject(func, NULL);
3402 Py_DECREF(func);
3403 return res;
3404 }
3405 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003406 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003407 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003408 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003409 return NULL;
3410 }
3411 Py_DECREF(func);
3412 return PySeqIter_New(self);
3413}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003414
3415static PyObject *
3416slot_tp_iternext(PyObject *self)
3417{
Guido van Rossum2730b132001-08-28 18:22:14 +00003418 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003419 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003420}
3421
Guido van Rossum1a493502001-08-17 16:47:50 +00003422static PyObject *
3423slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3424{
3425 PyTypeObject *tp = self->ob_type;
3426 PyObject *get;
3427 static PyObject *get_str = NULL;
3428
3429 if (get_str == NULL) {
3430 get_str = PyString_InternFromString("__get__");
3431 if (get_str == NULL)
3432 return NULL;
3433 }
3434 get = _PyType_Lookup(tp, get_str);
3435 if (get == NULL) {
3436 /* Avoid further slowdowns */
3437 if (tp->tp_descr_get == slot_tp_descr_get)
3438 tp->tp_descr_get = NULL;
3439 Py_INCREF(self);
3440 return self;
3441 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003442 if (obj == NULL)
3443 obj = Py_None;
3444 if (type == NULL)
3445 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003446 return PyObject_CallFunction(get, "OOO", self, obj, type);
3447}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003448
3449static int
3450slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3451{
Guido van Rossum2c252392001-08-24 10:13:31 +00003452 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003453 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003454
3455 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003456 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003457 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003458 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003459 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003460 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003461 if (res == NULL)
3462 return -1;
3463 Py_DECREF(res);
3464 return 0;
3465}
3466
3467static int
3468slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3469{
Guido van Rossum60718732001-08-28 17:47:51 +00003470 static PyObject *init_str;
3471 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003472 PyObject *res;
3473
3474 if (meth == NULL)
3475 return -1;
3476 res = PyObject_Call(meth, args, kwds);
3477 Py_DECREF(meth);
3478 if (res == NULL)
3479 return -1;
3480 Py_DECREF(res);
3481 return 0;
3482}
3483
3484static PyObject *
3485slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3486{
3487 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3488 PyObject *newargs, *x;
3489 int i, n;
3490
3491 if (func == NULL)
3492 return NULL;
3493 assert(PyTuple_Check(args));
3494 n = PyTuple_GET_SIZE(args);
3495 newargs = PyTuple_New(n+1);
3496 if (newargs == NULL)
3497 return NULL;
3498 Py_INCREF(type);
3499 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3500 for (i = 0; i < n; i++) {
3501 x = PyTuple_GET_ITEM(args, i);
3502 Py_INCREF(x);
3503 PyTuple_SET_ITEM(newargs, i+1, x);
3504 }
3505 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003506 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003507 Py_DECREF(func);
3508 return x;
3509}
3510
Guido van Rossumf040ede2001-08-07 16:40:56 +00003511/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003512 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003513 The dict argument is the dictionary argument passed to type_new(),
3514 which is the local namespace of the class statement, in other
3515 words, it contains the methods. For each special method (like
3516 __repr__) defined in the dictionary, the corresponding function
3517 slot in the type object (like tp_repr) is set to a special function
3518 whose name is 'slot_' followed by the slot name and whose signature
3519 is whatever is required for that slot. These slot functions look
3520 up the corresponding method in the type's dictionary and call it.
3521 The slot functions have to take care of the various peculiarities
3522 of the mapping between slots and special methods, such as mapping
3523 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3524 etc.) or mapping multiple slots to a single method (sq_item,
3525 mp_subscript <--> __getitem__). */
3526
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527static void
3528override_slots(PyTypeObject *type, PyObject *dict)
3529{
3530 PySequenceMethods *sq = type->tp_as_sequence;
3531 PyMappingMethods *mp = type->tp_as_mapping;
3532 PyNumberMethods *nb = type->tp_as_number;
3533
Guido van Rossumdc91b992001-08-08 22:26:22 +00003534#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003535 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003536 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537 }
3538
Guido van Rossumdc91b992001-08-08 22:26:22 +00003539#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003540 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003541 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003542 }
3543
Guido van Rossumdc91b992001-08-08 22:26:22 +00003544#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003545 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003546 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003547 }
3548
Guido van Rossumdc91b992001-08-08 22:26:22 +00003549#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003550 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003551 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003552 }
3553
Guido van Rossumdc91b992001-08-08 22:26:22 +00003554 SQSLOT("__len__", sq_length, slot_sq_length);
3555 SQSLOT("__add__", sq_concat, slot_sq_concat);
3556 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3557 SQSLOT("__getitem__", sq_item, slot_sq_item);
3558 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3559 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3560 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3561 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3562 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3563 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3564 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3565 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003566
Guido van Rossumdc91b992001-08-08 22:26:22 +00003567 MPSLOT("__len__", mp_length, slot_mp_length);
3568 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3569 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3570 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003571
Guido van Rossumdc91b992001-08-08 22:26:22 +00003572 NBSLOT("__add__", nb_add, slot_nb_add);
3573 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3574 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3575 NBSLOT("__div__", nb_divide, slot_nb_divide);
3576 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3577 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3578 NBSLOT("__pow__", nb_power, slot_nb_power);
3579 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3580 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3581 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3582 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3583 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3584 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3585 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3586 NBSLOT("__and__", nb_and, slot_nb_and);
3587 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3588 NBSLOT("__or__", nb_or, slot_nb_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003589 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003590 NBSLOT("__int__", nb_int, slot_nb_int);
3591 NBSLOT("__long__", nb_long, slot_nb_long);
3592 NBSLOT("__float__", nb_float, slot_nb_float);
3593 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3594 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3595 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3596 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3597 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3598 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3599 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3600 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3601 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3602 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3603 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3604 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3605 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3606 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3607 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3608 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3609 slot_nb_inplace_floor_divide);
3610 NBSLOT("__itruediv__", nb_inplace_true_divide,
3611 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003612
Guido van Rossum8e248182001-08-12 05:17:56 +00003613 if (dict == NULL ||
3614 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003615 PyDict_GetItemString(dict, "__repr__"))
3616 type->tp_print = NULL;
3617
Guido van Rossumab3b0342001-09-18 20:38:53 +00003618 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003619 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3620 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3621 TPSLOT("__call__", tp_call, slot_tp_call);
3622 TPSLOT("__str__", tp_str, slot_tp_str);
Guido van Rossum867a8d22001-09-21 19:29:08 +00003623 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003624 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003625 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3626 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3627 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3628 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3629 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3630 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3631 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3632 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3633 TPSLOT("next", tp_iternext, slot_tp_iternext);
3634 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3635 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3636 TPSLOT("__init__", tp_init, slot_tp_init);
3637 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003638}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003639
3640
3641/* Cooperative 'super' */
3642
3643typedef struct {
3644 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003645 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003646 PyObject *obj;
3647} superobject;
3648
Guido van Rossum6f799372001-09-20 20:46:19 +00003649static PyMemberDef super_members[] = {
3650 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3651 "the class invoking super()"},
3652 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3653 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003654 {0}
3655};
3656
Guido van Rossum705f0f52001-08-24 16:47:00 +00003657static void
3658super_dealloc(PyObject *self)
3659{
3660 superobject *su = (superobject *)self;
3661
Guido van Rossum048eb752001-10-02 21:24:57 +00003662 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003663 Py_XDECREF(su->obj);
3664 Py_XDECREF(su->type);
3665 self->ob_type->tp_free(self);
3666}
3667
3668static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003669super_repr(PyObject *self)
3670{
3671 superobject *su = (superobject *)self;
3672
3673 if (su->obj)
3674 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003675 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003676 su->type ? su->type->tp_name : "NULL",
3677 su->obj->ob_type->tp_name);
3678 else
3679 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003680 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003681 su->type ? su->type->tp_name : "NULL");
3682}
3683
3684static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003685super_getattro(PyObject *self, PyObject *name)
3686{
3687 superobject *su = (superobject *)self;
3688
3689 if (su->obj != NULL) {
3690 PyObject *mro, *res, *tmp;
3691 descrgetfunc f;
3692 int i, n;
3693
Guido van Rossume705ef12001-08-29 15:47:06 +00003694 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003695 if (mro == NULL)
3696 n = 0;
3697 else {
3698 assert(PyTuple_Check(mro));
3699 n = PyTuple_GET_SIZE(mro);
3700 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003701 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003702 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003703 break;
3704 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003705 if (i >= n && PyType_Check(su->obj)) {
3706 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003707 if (mro == NULL)
3708 n = 0;
3709 else {
3710 assert(PyTuple_Check(mro));
3711 n = PyTuple_GET_SIZE(mro);
3712 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003713 for (i = 0; i < n; i++) {
3714 if ((PyObject *)(su->type) ==
3715 PyTuple_GET_ITEM(mro, i))
3716 break;
3717 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003718 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003719 i++;
3720 res = NULL;
3721 for (; i < n; i++) {
3722 tmp = PyTuple_GET_ITEM(mro, i);
3723 assert(PyType_Check(tmp));
3724 res = PyDict_GetItem(
3725 ((PyTypeObject *)tmp)->tp_defined, name);
3726 if (res != NULL) {
3727 Py_INCREF(res);
3728 f = res->ob_type->tp_descr_get;
3729 if (f != NULL) {
3730 tmp = f(res, su->obj, res);
3731 Py_DECREF(res);
3732 res = tmp;
3733 }
3734 return res;
3735 }
3736 }
3737 }
3738 return PyObject_GenericGetAttr(self, name);
3739}
3740
3741static PyObject *
3742super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3743{
3744 superobject *su = (superobject *)self;
3745 superobject *new;
3746
3747 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3748 /* Not binding to an object, or already bound */
3749 Py_INCREF(self);
3750 return self;
3751 }
3752 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3753 if (new == NULL)
3754 return NULL;
3755 Py_INCREF(su->type);
3756 Py_INCREF(obj);
3757 new->type = su->type;
3758 new->obj = obj;
3759 return (PyObject *)new;
3760}
3761
3762static int
3763super_init(PyObject *self, PyObject *args, PyObject *kwds)
3764{
3765 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003766 PyTypeObject *type;
3767 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003768
3769 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3770 return -1;
3771 if (obj == Py_None)
3772 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003773 if (obj != NULL &&
3774 !PyType_IsSubtype(obj->ob_type, type) &&
3775 !(PyType_Check(obj) &&
3776 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003777 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003778 "super(type, obj): "
3779 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003780 return -1;
3781 }
3782 Py_INCREF(type);
3783 Py_XINCREF(obj);
3784 su->type = type;
3785 su->obj = obj;
3786 return 0;
3787}
3788
3789static char super_doc[] =
3790"super(type) -> unbound super object\n"
3791"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003792"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003793"Typical use to call a cooperative superclass method:\n"
3794"class C(B):\n"
3795" def meth(self, arg):\n"
3796" super(C, self).meth(arg)";
3797
Guido van Rossum048eb752001-10-02 21:24:57 +00003798static int
3799super_traverse(PyObject *self, visitproc visit, void *arg)
3800{
3801 superobject *su = (superobject *)self;
3802 int err;
3803
3804#define VISIT(SLOT) \
3805 if (SLOT) { \
3806 err = visit((PyObject *)(SLOT), arg); \
3807 if (err) \
3808 return err; \
3809 }
3810
3811 VISIT(su->obj);
3812 VISIT(su->type);
3813
3814#undef VISIT
3815
3816 return 0;
3817}
3818
Guido van Rossum705f0f52001-08-24 16:47:00 +00003819PyTypeObject PySuper_Type = {
3820 PyObject_HEAD_INIT(&PyType_Type)
3821 0, /* ob_size */
3822 "super", /* tp_name */
3823 sizeof(superobject), /* tp_basicsize */
3824 0, /* tp_itemsize */
3825 /* methods */
3826 super_dealloc, /* tp_dealloc */
3827 0, /* tp_print */
3828 0, /* tp_getattr */
3829 0, /* tp_setattr */
3830 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003831 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003832 0, /* tp_as_number */
3833 0, /* tp_as_sequence */
3834 0, /* tp_as_mapping */
3835 0, /* tp_hash */
3836 0, /* tp_call */
3837 0, /* tp_str */
3838 super_getattro, /* tp_getattro */
3839 0, /* tp_setattro */
3840 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00003841 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3842 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003843 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00003844 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003845 0, /* tp_clear */
3846 0, /* tp_richcompare */
3847 0, /* tp_weaklistoffset */
3848 0, /* tp_iter */
3849 0, /* tp_iternext */
3850 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003851 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003852 0, /* tp_getset */
3853 0, /* tp_base */
3854 0, /* tp_dict */
3855 super_descr_get, /* tp_descr_get */
3856 0, /* tp_descr_set */
3857 0, /* tp_dictoffset */
3858 super_init, /* tp_init */
3859 PyType_GenericAlloc, /* tp_alloc */
3860 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00003861 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003862};