blob: a681d337c54ed82fdad1064f2a5f67c4fdf3d3c1 [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
2116 if (!PyArg_ParseTuple(args, "O", &arg))
2117 return NULL;
2118 i = getindex(self, arg);
2119 if (i == -1 && PyErr_Occurred())
2120 return NULL;
2121 return (*func)(self, i);
2122}
2123
Tim Peters6d6c1a32001-08-02 04:15:00 +00002124static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002125 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126 "x.__getitem__(i) <==> x[i]"},
2127 {0}
2128};
2129
2130static PyObject *
2131wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2132{
2133 intintargfunc func = (intintargfunc)wrapped;
2134 int i, j;
2135
2136 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2137 return NULL;
2138 return (*func)(self, i, j);
2139}
2140
2141static struct wrapperbase tab_getslice[] = {
2142 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2143 "x.__getslice__(i, j) <==> x[i:j]"},
2144 {0}
2145};
2146
2147static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002148wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002149{
2150 intobjargproc func = (intobjargproc)wrapped;
2151 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002152 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002153
Guido van Rossum5d815f32001-08-17 21:57:47 +00002154 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2155 return NULL;
2156 i = getindex(self, arg);
2157 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002158 return NULL;
2159 res = (*func)(self, i, value);
2160 if (res == -1 && PyErr_Occurred())
2161 return NULL;
2162 Py_INCREF(Py_None);
2163 return Py_None;
2164}
2165
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002166static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002167wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002168{
2169 intobjargproc func = (intobjargproc)wrapped;
2170 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002171 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002172
Guido van Rossum5d815f32001-08-17 21:57:47 +00002173 if (!PyArg_ParseTuple(args, "O", &arg))
2174 return NULL;
2175 i = getindex(self, arg);
2176 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002177 return NULL;
2178 res = (*func)(self, i, NULL);
2179 if (res == -1 && PyErr_Occurred())
2180 return NULL;
2181 Py_INCREF(Py_None);
2182 return Py_None;
2183}
2184
Tim Peters6d6c1a32001-08-02 04:15:00 +00002185static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002186 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002187 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002188 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002189 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190 {0}
2191};
2192
2193static PyObject *
2194wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2195{
2196 intintobjargproc func = (intintobjargproc)wrapped;
2197 int i, j, res;
2198 PyObject *value;
2199
2200 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2201 return NULL;
2202 res = (*func)(self, i, j, value);
2203 if (res == -1 && PyErr_Occurred())
2204 return NULL;
2205 Py_INCREF(Py_None);
2206 return Py_None;
2207}
2208
2209static struct wrapperbase tab_setslice[] = {
2210 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2211 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
2212 {0}
2213};
2214
2215/* XXX objobjproc is a misnomer; should be objargpred */
2216static PyObject *
2217wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2218{
2219 objobjproc func = (objobjproc)wrapped;
2220 int res;
2221 PyObject *value;
2222
2223 if (!PyArg_ParseTuple(args, "O", &value))
2224 return NULL;
2225 res = (*func)(self, value);
2226 if (res == -1 && PyErr_Occurred())
2227 return NULL;
2228 return PyInt_FromLong((long)res);
2229}
2230
2231static struct wrapperbase tab_contains[] = {
2232 {"__contains__", (wrapperfunc)wrap_objobjproc,
2233 "x.__contains__(y) <==> y in x"},
2234 {0}
2235};
2236
2237static PyObject *
2238wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2239{
2240 objobjargproc func = (objobjargproc)wrapped;
2241 int res;
2242 PyObject *key, *value;
2243
2244 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2245 return NULL;
2246 res = (*func)(self, key, value);
2247 if (res == -1 && PyErr_Occurred())
2248 return NULL;
2249 Py_INCREF(Py_None);
2250 return Py_None;
2251}
2252
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002253static PyObject *
2254wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2255{
2256 objobjargproc func = (objobjargproc)wrapped;
2257 int res;
2258 PyObject *key;
2259
2260 if (!PyArg_ParseTuple(args, "O", &key))
2261 return NULL;
2262 res = (*func)(self, key, NULL);
2263 if (res == -1 && PyErr_Occurred())
2264 return NULL;
2265 Py_INCREF(Py_None);
2266 return Py_None;
2267}
2268
Tim Peters6d6c1a32001-08-02 04:15:00 +00002269static struct wrapperbase tab_setitem[] = {
2270 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2271 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002272 {"__delitem__", (wrapperfunc)wrap_delitem,
2273 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002274 {0}
2275};
2276
2277static PyObject *
2278wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2279{
2280 cmpfunc func = (cmpfunc)wrapped;
2281 int res;
2282 PyObject *other;
2283
2284 if (!PyArg_ParseTuple(args, "O", &other))
2285 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002286 if (other->ob_type->tp_compare != func &&
2287 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002288 PyErr_Format(
2289 PyExc_TypeError,
2290 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2291 self->ob_type->tp_name,
2292 self->ob_type->tp_name,
2293 other->ob_type->tp_name);
2294 return NULL;
2295 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002296 res = (*func)(self, other);
2297 if (PyErr_Occurred())
2298 return NULL;
2299 return PyInt_FromLong((long)res);
2300}
2301
2302static struct wrapperbase tab_cmp[] = {
2303 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2304 "x.__cmp__(y) <==> cmp(x,y)"},
2305 {0}
2306};
2307
2308static struct wrapperbase tab_repr[] = {
2309 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2310 "x.__repr__() <==> repr(x)"},
2311 {0}
2312};
2313
2314static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002315 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2316 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002317 {0}
2318};
2319
2320static PyObject *
2321wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2322{
2323 setattrofunc func = (setattrofunc)wrapped;
2324 int res;
2325 PyObject *name, *value;
2326
2327 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2328 return NULL;
2329 res = (*func)(self, name, value);
2330 if (res < 0)
2331 return NULL;
2332 Py_INCREF(Py_None);
2333 return Py_None;
2334}
2335
2336static PyObject *
2337wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2338{
2339 setattrofunc func = (setattrofunc)wrapped;
2340 int res;
2341 PyObject *name;
2342
2343 if (!PyArg_ParseTuple(args, "O", &name))
2344 return NULL;
2345 res = (*func)(self, name, NULL);
2346 if (res < 0)
2347 return NULL;
2348 Py_INCREF(Py_None);
2349 return Py_None;
2350}
2351
2352static struct wrapperbase tab_setattr[] = {
2353 {"__setattr__", (wrapperfunc)wrap_setattr,
2354 "x.__setattr__('name', value) <==> x.name = value"},
2355 {"__delattr__", (wrapperfunc)wrap_delattr,
2356 "x.__delattr__('name') <==> del x.name"},
2357 {0}
2358};
2359
2360static PyObject *
2361wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2362{
2363 hashfunc func = (hashfunc)wrapped;
2364 long res;
2365
2366 if (!PyArg_ParseTuple(args, ""))
2367 return NULL;
2368 res = (*func)(self);
2369 if (res == -1 && PyErr_Occurred())
2370 return NULL;
2371 return PyInt_FromLong(res);
2372}
2373
2374static struct wrapperbase tab_hash[] = {
2375 {"__hash__", (wrapperfunc)wrap_hashfunc,
2376 "x.__hash__() <==> hash(x)"},
2377 {0}
2378};
2379
2380static PyObject *
2381wrap_call(PyObject *self, PyObject *args, void *wrapped)
2382{
2383 ternaryfunc func = (ternaryfunc)wrapped;
2384
2385 /* XXX What about keyword arguments? */
2386 return (*func)(self, args, NULL);
2387}
2388
2389static struct wrapperbase tab_call[] = {
2390 {"__call__", (wrapperfunc)wrap_call,
2391 "x.__call__(...) <==> x(...)"},
2392 {0}
2393};
2394
2395static struct wrapperbase tab_str[] = {
2396 {"__str__", (wrapperfunc)wrap_unaryfunc,
2397 "x.__str__() <==> str(x)"},
2398 {0}
2399};
2400
2401static PyObject *
2402wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2403{
2404 richcmpfunc func = (richcmpfunc)wrapped;
2405 PyObject *other;
2406
2407 if (!PyArg_ParseTuple(args, "O", &other))
2408 return NULL;
2409 return (*func)(self, other, op);
2410}
2411
2412#undef RICHCMP_WRAPPER
2413#define RICHCMP_WRAPPER(NAME, OP) \
2414static PyObject * \
2415richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2416{ \
2417 return wrap_richcmpfunc(self, args, wrapped, OP); \
2418}
2419
Jack Jansen8e938b42001-08-08 15:29:49 +00002420RICHCMP_WRAPPER(lt, Py_LT)
2421RICHCMP_WRAPPER(le, Py_LE)
2422RICHCMP_WRAPPER(eq, Py_EQ)
2423RICHCMP_WRAPPER(ne, Py_NE)
2424RICHCMP_WRAPPER(gt, Py_GT)
2425RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002426
2427#undef RICHCMP_ENTRY
2428#define RICHCMP_ENTRY(NAME, EXPR) \
2429 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2430 "x.__" #NAME "__(y) <==> " EXPR}
2431
2432static struct wrapperbase tab_richcmp[] = {
2433 RICHCMP_ENTRY(lt, "x<y"),
2434 RICHCMP_ENTRY(le, "x<=y"),
2435 RICHCMP_ENTRY(eq, "x==y"),
2436 RICHCMP_ENTRY(ne, "x!=y"),
2437 RICHCMP_ENTRY(gt, "x>y"),
2438 RICHCMP_ENTRY(ge, "x>=y"),
2439 {0}
2440};
2441
2442static struct wrapperbase tab_iter[] = {
2443 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2444 {0}
2445};
2446
2447static PyObject *
2448wrap_next(PyObject *self, PyObject *args, void *wrapped)
2449{
2450 unaryfunc func = (unaryfunc)wrapped;
2451 PyObject *res;
2452
2453 if (!PyArg_ParseTuple(args, ""))
2454 return NULL;
2455 res = (*func)(self);
2456 if (res == NULL && !PyErr_Occurred())
2457 PyErr_SetNone(PyExc_StopIteration);
2458 return res;
2459}
2460
2461static struct wrapperbase tab_next[] = {
2462 {"next", (wrapperfunc)wrap_next,
2463 "x.next() -> the next value, or raise StopIteration"},
2464 {0}
2465};
2466
2467static PyObject *
2468wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2469{
2470 descrgetfunc func = (descrgetfunc)wrapped;
2471 PyObject *obj;
2472 PyObject *type = NULL;
2473
2474 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2475 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002476 return (*func)(self, obj, type);
2477}
2478
2479static struct wrapperbase tab_descr_get[] = {
2480 {"__get__", (wrapperfunc)wrap_descr_get,
2481 "descr.__get__(obj, type) -> value"},
2482 {0}
2483};
2484
2485static PyObject *
2486wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2487{
2488 descrsetfunc func = (descrsetfunc)wrapped;
2489 PyObject *obj, *value;
2490 int ret;
2491
2492 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2493 return NULL;
2494 ret = (*func)(self, obj, value);
2495 if (ret < 0)
2496 return NULL;
2497 Py_INCREF(Py_None);
2498 return Py_None;
2499}
2500
2501static struct wrapperbase tab_descr_set[] = {
2502 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2503 "descr.__set__(obj, value)"},
2504 {0}
2505};
2506
2507static PyObject *
2508wrap_init(PyObject *self, PyObject *args, void *wrapped)
2509{
2510 initproc func = (initproc)wrapped;
2511
2512 /* XXX What about keyword arguments? */
2513 if (func(self, args, NULL) < 0)
2514 return NULL;
2515 Py_INCREF(Py_None);
2516 return Py_None;
2517}
2518
2519static struct wrapperbase tab_init[] = {
2520 {"__init__", (wrapperfunc)wrap_init,
2521 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002522 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002523 {0}
2524};
2525
2526static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002527tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002528{
Barry Warsaw60f01882001-08-22 19:24:42 +00002529 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002530 PyObject *arg0, *res;
2531
2532 if (self == NULL || !PyType_Check(self))
2533 Py_FatalError("__new__() called with non-type 'self'");
2534 type = (PyTypeObject *)self;
2535 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002536 PyErr_Format(PyExc_TypeError,
2537 "%s.__new__(): not enough arguments",
2538 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002539 return NULL;
2540 }
2541 arg0 = PyTuple_GET_ITEM(args, 0);
2542 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002543 PyErr_Format(PyExc_TypeError,
2544 "%s.__new__(X): X is not a type object (%s)",
2545 type->tp_name,
2546 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002547 return NULL;
2548 }
2549 subtype = (PyTypeObject *)arg0;
2550 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002551 PyErr_Format(PyExc_TypeError,
2552 "%s.__new__(%s): %s is not a subtype of %s",
2553 type->tp_name,
2554 subtype->tp_name,
2555 subtype->tp_name,
2556 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002557 return NULL;
2558 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002559
2560 /* Check that the use doesn't do something silly and unsafe like
2561 object.__new__(dictionary). To do this, we check that the
2562 most derived base that's not a heap type is this type. */
2563 staticbase = subtype;
2564 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2565 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002566 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002567 PyErr_Format(PyExc_TypeError,
2568 "%s.__new__(%s) is not safe, use %s.__new__()",
2569 type->tp_name,
2570 subtype->tp_name,
2571 staticbase == NULL ? "?" : staticbase->tp_name);
2572 return NULL;
2573 }
2574
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002575 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2576 if (args == NULL)
2577 return NULL;
2578 res = type->tp_new(subtype, args, kwds);
2579 Py_DECREF(args);
2580 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002581}
2582
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002583static struct PyMethodDef tp_new_methoddef[] = {
2584 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2585 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002586 {0}
2587};
2588
2589static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002590add_tp_new_wrapper(PyTypeObject *type)
2591{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002592 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002593
Guido van Rossumf040ede2001-08-07 16:40:56 +00002594 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2595 return 0;
2596 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002597 if (func == NULL)
2598 return -1;
2599 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2600}
2601
Guido van Rossum13d52f02001-08-10 21:24:08 +00002602static int
2603add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2604{
2605 PyObject *dict = type->tp_defined;
2606
2607 for (; wraps->name != NULL; wraps++) {
2608 PyObject *descr;
2609 if (PyDict_GetItemString(dict, wraps->name))
2610 continue;
2611 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2612 if (descr == NULL)
2613 return -1;
2614 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2615 return -1;
2616 Py_DECREF(descr);
2617 }
2618 return 0;
2619}
2620
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002621/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002622 dictionary with method descriptors for function slots. For each
2623 function slot (like tp_repr) that's defined in the type, one or
2624 more corresponding descriptors are added in the type's tp_defined
2625 dictionary under the appropriate name (like __repr__). Some
2626 function slots cause more than one descriptor to be added (for
2627 example, the nb_add slot adds both __add__ and __radd__
2628 descriptors) and some function slots compete for the same
2629 descriptor (for example both sq_item and mp_subscript generate a
2630 __getitem__ descriptor). This only adds new descriptors and
2631 doesn't overwrite entries in tp_defined that were previously
2632 defined. The descriptors contain a reference to the C function
2633 they must call, so that it's safe if they are copied into a
2634 subtype's __dict__ and the subtype has a different C function in
2635 its slot -- calling the method defined by the descriptor will call
2636 the C function that was used to create it, rather than the C
2637 function present in the slot when it is called. (This is important
2638 because a subtype may have a C function in the slot that calls the
2639 method from the dictionary, and we want to avoid infinite recursion
2640 here.) */
2641
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002642static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002643add_operators(PyTypeObject *type)
2644{
2645 PySequenceMethods *sq;
2646 PyMappingMethods *mp;
2647 PyNumberMethods *nb;
2648
2649#undef ADD
2650#define ADD(SLOT, TABLE) \
2651 if (SLOT) { \
2652 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2653 return -1; \
2654 }
2655
2656 if ((sq = type->tp_as_sequence) != NULL) {
2657 ADD(sq->sq_length, tab_len);
2658 ADD(sq->sq_concat, tab_concat);
2659 ADD(sq->sq_repeat, tab_mul_int);
2660 ADD(sq->sq_item, tab_getitem_int);
2661 ADD(sq->sq_slice, tab_getslice);
2662 ADD(sq->sq_ass_item, tab_setitem_int);
2663 ADD(sq->sq_ass_slice, tab_setslice);
2664 ADD(sq->sq_contains, tab_contains);
2665 ADD(sq->sq_inplace_concat, tab_iadd);
2666 ADD(sq->sq_inplace_repeat, tab_imul_int);
2667 }
2668
2669 if ((mp = type->tp_as_mapping) != NULL) {
2670 if (sq->sq_length == NULL)
2671 ADD(mp->mp_length, tab_len);
2672 ADD(mp->mp_subscript, tab_getitem);
2673 ADD(mp->mp_ass_subscript, tab_setitem);
2674 }
2675
2676 /* We don't support "old-style numbers" because their binary
2677 operators require that both arguments have the same type;
2678 the wrappers here only work for new-style numbers. */
2679 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2680 (nb = type->tp_as_number) != NULL) {
2681 ADD(nb->nb_add, tab_add);
2682 ADD(nb->nb_subtract, tab_sub);
2683 ADD(nb->nb_multiply, tab_mul);
2684 ADD(nb->nb_divide, tab_div);
2685 ADD(nb->nb_remainder, tab_mod);
2686 ADD(nb->nb_divmod, tab_divmod);
2687 ADD(nb->nb_power, tab_pow);
2688 ADD(nb->nb_negative, tab_neg);
2689 ADD(nb->nb_positive, tab_pos);
2690 ADD(nb->nb_absolute, tab_abs);
2691 ADD(nb->nb_nonzero, tab_nonzero);
2692 ADD(nb->nb_invert, tab_invert);
2693 ADD(nb->nb_lshift, tab_lshift);
2694 ADD(nb->nb_rshift, tab_rshift);
2695 ADD(nb->nb_and, tab_and);
2696 ADD(nb->nb_xor, tab_xor);
2697 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002698 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002699 ADD(nb->nb_int, tab_int);
2700 ADD(nb->nb_long, tab_long);
2701 ADD(nb->nb_float, tab_float);
2702 ADD(nb->nb_oct, tab_oct);
2703 ADD(nb->nb_hex, tab_hex);
2704 ADD(nb->nb_inplace_add, tab_iadd);
2705 ADD(nb->nb_inplace_subtract, tab_isub);
2706 ADD(nb->nb_inplace_multiply, tab_imul);
2707 ADD(nb->nb_inplace_divide, tab_idiv);
2708 ADD(nb->nb_inplace_remainder, tab_imod);
2709 ADD(nb->nb_inplace_power, tab_ipow);
2710 ADD(nb->nb_inplace_lshift, tab_ilshift);
2711 ADD(nb->nb_inplace_rshift, tab_irshift);
2712 ADD(nb->nb_inplace_and, tab_iand);
2713 ADD(nb->nb_inplace_xor, tab_ixor);
2714 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum874f15a2001-09-25 21:16:33 +00002715 if (type->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2716 ADD(nb->nb_floor_divide, tab_floordiv);
2717 ADD(nb->nb_true_divide, tab_truediv);
2718 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2719 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2720 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002721 }
2722
2723 ADD(type->tp_getattro, tab_getattr);
2724 ADD(type->tp_setattro, tab_setattr);
2725 ADD(type->tp_compare, tab_cmp);
2726 ADD(type->tp_repr, tab_repr);
2727 ADD(type->tp_hash, tab_hash);
2728 ADD(type->tp_call, tab_call);
2729 ADD(type->tp_str, tab_str);
2730 ADD(type->tp_richcompare, tab_richcmp);
2731 ADD(type->tp_iter, tab_iter);
2732 ADD(type->tp_iternext, tab_next);
2733 ADD(type->tp_descr_get, tab_descr_get);
2734 ADD(type->tp_descr_set, tab_descr_set);
2735 ADD(type->tp_init, tab_init);
2736
Guido van Rossumf040ede2001-08-07 16:40:56 +00002737 if (type->tp_new != NULL) {
2738 if (add_tp_new_wrapper(type) < 0)
2739 return -1;
2740 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002741
2742 return 0;
2743}
2744
Guido van Rossumf040ede2001-08-07 16:40:56 +00002745/* Slot wrappers that call the corresponding __foo__ slot. See comments
2746 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002747
Guido van Rossumdc91b992001-08-08 22:26:22 +00002748#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002749static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002750FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002752 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002753 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002754}
2755
Guido van Rossumdc91b992001-08-08 22:26:22 +00002756#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002758FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002760 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002761 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002762}
2763
Guido van Rossumdc91b992001-08-08 22:26:22 +00002764
2765#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002767FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002768{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002769 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002770 int do_other = self->ob_type != other->ob_type && \
2771 other->ob_type->tp_as_number != NULL && \
2772 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002773 if (self->ob_type->tp_as_number != NULL && \
2774 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2775 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002776 if (do_other && \
2777 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2778 r = call_maybe( \
2779 other, ROPSTR, &rcache_str, "(O)", self); \
2780 if (r != Py_NotImplemented) \
2781 return r; \
2782 Py_DECREF(r); \
2783 do_other = 0; \
2784 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002785 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002786 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002787 if (r != Py_NotImplemented || \
2788 other->ob_type == self->ob_type) \
2789 return r; \
2790 Py_DECREF(r); \
2791 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002792 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002793 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002794 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002795 } \
2796 Py_INCREF(Py_NotImplemented); \
2797 return Py_NotImplemented; \
2798}
2799
2800#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2801 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2802
2803#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2804static PyObject * \
2805FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2806{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002807 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002808 return call_method(self, OPSTR, &cache_str, \
2809 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810}
2811
2812static int
2813slot_sq_length(PyObject *self)
2814{
Guido van Rossum2730b132001-08-28 18:22:14 +00002815 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002816 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002817 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002818
2819 if (res == NULL)
2820 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002821 len = (int)PyInt_AsLong(res);
2822 Py_DECREF(res);
2823 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002824}
2825
Guido van Rossumdc91b992001-08-08 22:26:22 +00002826SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2827SLOT1(slot_sq_repeat, "__mul__", int, "i")
2828SLOT1(slot_sq_item, "__getitem__", int, "i")
2829SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002830
2831static int
2832slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2833{
2834 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002835 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002836
2837 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002838 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002839 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002840 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002841 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002842 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002843 if (res == NULL)
2844 return -1;
2845 Py_DECREF(res);
2846 return 0;
2847}
2848
2849static int
2850slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2851{
2852 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002853 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002854
2855 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002856 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002857 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002858 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002859 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002860 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002861 if (res == NULL)
2862 return -1;
2863 Py_DECREF(res);
2864 return 0;
2865}
2866
2867static int
2868slot_sq_contains(PyObject *self, PyObject *value)
2869{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002870 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002871 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002872
Guido van Rossum55f20992001-10-01 17:18:22 +00002873 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002874
2875 if (func != NULL) {
2876 args = Py_BuildValue("(O)", value);
2877 if (args == NULL)
2878 res = NULL;
2879 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002880 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002881 Py_DECREF(args);
2882 }
2883 Py_DECREF(func);
2884 if (res == NULL)
2885 return -1;
2886 return PyObject_IsTrue(res);
2887 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002888 else if (PyErr_Occurred())
2889 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002890 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002891 return _PySequence_IterSearch(self, value,
2892 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002893 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002894}
2895
Guido van Rossumdc91b992001-08-08 22:26:22 +00002896SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2897SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002898
2899#define slot_mp_length slot_sq_length
2900
Guido van Rossumdc91b992001-08-08 22:26:22 +00002901SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002902
2903static int
2904slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2905{
2906 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002907 static PyObject *delitem_str, *setitem_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, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002911 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002912 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002913 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002914 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002915 if (res == NULL)
2916 return -1;
2917 Py_DECREF(res);
2918 return 0;
2919}
2920
Guido van Rossumdc91b992001-08-08 22:26:22 +00002921SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2922SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2923SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2924SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2925SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2926SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2927
2928staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2929
2930SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2931 nb_power, "__pow__", "__rpow__")
2932
2933static PyObject *
2934slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2935{
Guido van Rossum2730b132001-08-28 18:22:14 +00002936 static PyObject *pow_str;
2937
Guido van Rossumdc91b992001-08-08 22:26:22 +00002938 if (modulus == Py_None)
2939 return slot_nb_power_binary(self, other);
2940 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002941 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002942 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002943}
2944
2945SLOT0(slot_nb_negative, "__neg__")
2946SLOT0(slot_nb_positive, "__pos__")
2947SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002948
2949static int
2950slot_nb_nonzero(PyObject *self)
2951{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002952 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002953 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002954
Guido van Rossum55f20992001-10-01 17:18:22 +00002955 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002956 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00002957 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00002958 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00002959 func = lookup_maybe(self, "__len__", &len_str);
2960 if (func == NULL) {
2961 if (PyErr_Occurred())
2962 return -1;
2963 else
2964 return 1;
2965 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00002966 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002967 res = PyObject_CallObject(func, NULL);
2968 Py_DECREF(func);
2969 if (res == NULL)
2970 return -1;
2971 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002972}
2973
Guido van Rossumdc91b992001-08-08 22:26:22 +00002974SLOT0(slot_nb_invert, "__invert__")
2975SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2976SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2977SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2978SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2979SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002980
2981static int
2982slot_nb_coerce(PyObject **a, PyObject **b)
2983{
2984 static PyObject *coerce_str;
2985 PyObject *self = *a, *other = *b;
2986
2987 if (self->ob_type->tp_as_number != NULL &&
2988 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
2989 PyObject *r;
2990 r = call_maybe(
2991 self, "__coerce__", &coerce_str, "(O)", other);
2992 if (r == NULL)
2993 return -1;
2994 if (r == Py_NotImplemented) {
2995 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002996 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002997 else {
2998 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
2999 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003000 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003001 Py_DECREF(r);
3002 return -1;
3003 }
3004 *a = PyTuple_GET_ITEM(r, 0);
3005 Py_INCREF(*a);
3006 *b = PyTuple_GET_ITEM(r, 1);
3007 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003008 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003009 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003010 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003011 }
3012 if (other->ob_type->tp_as_number != NULL &&
3013 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3014 PyObject *r;
3015 r = call_maybe(
3016 other, "__coerce__", &coerce_str, "(O)", self);
3017 if (r == NULL)
3018 return -1;
3019 if (r == Py_NotImplemented) {
3020 Py_DECREF(r);
3021 return 1;
3022 }
3023 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3024 PyErr_SetString(PyExc_TypeError,
3025 "__coerce__ didn't return a 2-tuple");
3026 Py_DECREF(r);
3027 return -1;
3028 }
3029 *a = PyTuple_GET_ITEM(r, 1);
3030 Py_INCREF(*a);
3031 *b = PyTuple_GET_ITEM(r, 0);
3032 Py_INCREF(*b);
3033 Py_DECREF(r);
3034 return 0;
3035 }
3036 return 1;
3037}
3038
Guido van Rossumdc91b992001-08-08 22:26:22 +00003039SLOT0(slot_nb_int, "__int__")
3040SLOT0(slot_nb_long, "__long__")
3041SLOT0(slot_nb_float, "__float__")
3042SLOT0(slot_nb_oct, "__oct__")
3043SLOT0(slot_nb_hex, "__hex__")
3044SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3045SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3046SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3047SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3048SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3049SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3050SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3051SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3052SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3053SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3054SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3055SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3056 "__floordiv__", "__rfloordiv__")
3057SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3058SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3059SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003060
3061static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003062half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003063{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003064 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003065 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003066 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067
Guido van Rossum60718732001-08-28 17:47:51 +00003068 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003069 if (func == NULL) {
3070 PyErr_Clear();
3071 }
3072 else {
3073 args = Py_BuildValue("(O)", other);
3074 if (args == NULL)
3075 res = NULL;
3076 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003077 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003078 Py_DECREF(args);
3079 }
3080 if (res != Py_NotImplemented) {
3081 if (res == NULL)
3082 return -2;
3083 c = PyInt_AsLong(res);
3084 Py_DECREF(res);
3085 if (c == -1 && PyErr_Occurred())
3086 return -2;
3087 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3088 }
3089 Py_DECREF(res);
3090 }
3091 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003092}
3093
Guido van Rossumab3b0342001-09-18 20:38:53 +00003094/* This slot is published for the benefit of try_3way_compare in object.c */
3095int
3096_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003097{
3098 int c;
3099
Guido van Rossumab3b0342001-09-18 20:38:53 +00003100 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003101 c = half_compare(self, other);
3102 if (c <= 1)
3103 return c;
3104 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003105 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003106 c = half_compare(other, self);
3107 if (c < -1)
3108 return -2;
3109 if (c <= 1)
3110 return -c;
3111 }
3112 return (void *)self < (void *)other ? -1 :
3113 (void *)self > (void *)other ? 1 : 0;
3114}
3115
3116static PyObject *
3117slot_tp_repr(PyObject *self)
3118{
3119 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003120 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003121
Guido van Rossum60718732001-08-28 17:47:51 +00003122 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003123 if (func != NULL) {
3124 res = PyEval_CallObject(func, NULL);
3125 Py_DECREF(func);
3126 return res;
3127 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003128 PyErr_Clear();
3129 return PyString_FromFormat("<%s object at %p>",
3130 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003131}
3132
3133static PyObject *
3134slot_tp_str(PyObject *self)
3135{
3136 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003137 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003138
Guido van Rossum60718732001-08-28 17:47:51 +00003139 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003140 if (func != NULL) {
3141 res = PyEval_CallObject(func, NULL);
3142 Py_DECREF(func);
3143 return res;
3144 }
3145 else {
3146 PyErr_Clear();
3147 return slot_tp_repr(self);
3148 }
3149}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003150
3151static long
3152slot_tp_hash(PyObject *self)
3153{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003154 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003155 static PyObject *hash_str, *eq_str, *cmp_str;
3156
Tim Peters6d6c1a32001-08-02 04:15:00 +00003157 long h;
3158
Guido van Rossum60718732001-08-28 17:47:51 +00003159 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003160
3161 if (func != NULL) {
3162 res = PyEval_CallObject(func, NULL);
3163 Py_DECREF(func);
3164 if (res == NULL)
3165 return -1;
3166 h = PyInt_AsLong(res);
3167 }
3168 else {
3169 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003170 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003171 if (func == NULL) {
3172 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003173 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003174 }
3175 if (func != NULL) {
3176 Py_DECREF(func);
3177 PyErr_SetString(PyExc_TypeError, "unhashable type");
3178 return -1;
3179 }
3180 PyErr_Clear();
3181 h = _Py_HashPointer((void *)self);
3182 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003183 if (h == -1 && !PyErr_Occurred())
3184 h = -2;
3185 return h;
3186}
3187
3188static PyObject *
3189slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3190{
Guido van Rossum60718732001-08-28 17:47:51 +00003191 static PyObject *call_str;
3192 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003193 PyObject *res;
3194
3195 if (meth == NULL)
3196 return NULL;
3197 res = PyObject_Call(meth, args, kwds);
3198 Py_DECREF(meth);
3199 return res;
3200}
3201
Tim Peters6d6c1a32001-08-02 04:15:00 +00003202static PyObject *
3203slot_tp_getattro(PyObject *self, PyObject *name)
3204{
3205 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003206 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003207 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003208
Guido van Rossum8e248182001-08-12 05:17:56 +00003209 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003210 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003211 if (getattr_str == NULL)
3212 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003213 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003214 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003215 if (getattr == NULL) {
3216 /* Avoid further slowdowns */
3217 if (tp->tp_getattro == slot_tp_getattro)
3218 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003219 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003220 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003221 return PyObject_CallFunction(getattr, "OO", self, name);
3222}
3223
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003224static PyObject *
3225slot_tp_getattr_hook(PyObject *self, PyObject *name)
3226{
3227 PyTypeObject *tp = self->ob_type;
3228 PyObject *getattr, *getattribute, *res;
3229 static PyObject *getattribute_str = NULL;
3230 static PyObject *getattr_str = NULL;
3231
3232 if (getattr_str == NULL) {
3233 getattr_str = PyString_InternFromString("__getattr__");
3234 if (getattr_str == NULL)
3235 return NULL;
3236 }
3237 if (getattribute_str == NULL) {
3238 getattribute_str =
3239 PyString_InternFromString("__getattribute__");
3240 if (getattribute_str == NULL)
3241 return NULL;
3242 }
3243 getattr = _PyType_Lookup(tp, getattr_str);
3244 getattribute = _PyType_Lookup(tp, getattribute_str);
3245 if (getattr == NULL && getattribute == NULL) {
3246 /* Avoid further slowdowns */
3247 if (tp->tp_getattro == slot_tp_getattr_hook)
3248 tp->tp_getattro = PyObject_GenericGetAttr;
3249 return PyObject_GenericGetAttr(self, name);
3250 }
3251 if (getattribute == NULL)
3252 res = PyObject_GenericGetAttr(self, name);
3253 else
3254 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003255 if (getattr != NULL &&
3256 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003257 PyErr_Clear();
3258 res = PyObject_CallFunction(getattr, "OO", self, name);
3259 }
3260 return res;
3261}
3262
Tim Peters6d6c1a32001-08-02 04:15:00 +00003263static int
3264slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3265{
3266 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003267 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003268
3269 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003270 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003271 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003272 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003273 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003274 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003275 if (res == NULL)
3276 return -1;
3277 Py_DECREF(res);
3278 return 0;
3279}
3280
3281/* Map rich comparison operators to their __xx__ namesakes */
3282static char *name_op[] = {
3283 "__lt__",
3284 "__le__",
3285 "__eq__",
3286 "__ne__",
3287 "__gt__",
3288 "__ge__",
3289};
3290
3291static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003292half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003293{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003294 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003295 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003296
Guido van Rossum60718732001-08-28 17:47:51 +00003297 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003298 if (func == NULL) {
3299 PyErr_Clear();
3300 Py_INCREF(Py_NotImplemented);
3301 return Py_NotImplemented;
3302 }
3303 args = Py_BuildValue("(O)", other);
3304 if (args == NULL)
3305 res = NULL;
3306 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003307 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003308 Py_DECREF(args);
3309 }
3310 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003311 return res;
3312}
3313
Guido van Rossumb8f63662001-08-15 23:57:02 +00003314/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3315static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3316
3317static PyObject *
3318slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3319{
3320 PyObject *res;
3321
3322 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3323 res = half_richcompare(self, other, op);
3324 if (res != Py_NotImplemented)
3325 return res;
3326 Py_DECREF(res);
3327 }
3328 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3329 res = half_richcompare(other, self, swapped_op[op]);
3330 if (res != Py_NotImplemented) {
3331 return res;
3332 }
3333 Py_DECREF(res);
3334 }
3335 Py_INCREF(Py_NotImplemented);
3336 return Py_NotImplemented;
3337}
3338
3339static PyObject *
3340slot_tp_iter(PyObject *self)
3341{
3342 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003343 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003344
Guido van Rossum60718732001-08-28 17:47:51 +00003345 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003346 if (func != NULL) {
3347 res = PyObject_CallObject(func, NULL);
3348 Py_DECREF(func);
3349 return res;
3350 }
3351 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003352 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003353 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003354 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003355 return NULL;
3356 }
3357 Py_DECREF(func);
3358 return PySeqIter_New(self);
3359}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003360
3361static PyObject *
3362slot_tp_iternext(PyObject *self)
3363{
Guido van Rossum2730b132001-08-28 18:22:14 +00003364 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003365 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003366}
3367
Guido van Rossum1a493502001-08-17 16:47:50 +00003368static PyObject *
3369slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3370{
3371 PyTypeObject *tp = self->ob_type;
3372 PyObject *get;
3373 static PyObject *get_str = NULL;
3374
3375 if (get_str == NULL) {
3376 get_str = PyString_InternFromString("__get__");
3377 if (get_str == NULL)
3378 return NULL;
3379 }
3380 get = _PyType_Lookup(tp, get_str);
3381 if (get == NULL) {
3382 /* Avoid further slowdowns */
3383 if (tp->tp_descr_get == slot_tp_descr_get)
3384 tp->tp_descr_get = NULL;
3385 Py_INCREF(self);
3386 return self;
3387 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003388 if (obj == NULL)
3389 obj = Py_None;
3390 if (type == NULL)
3391 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003392 return PyObject_CallFunction(get, "OOO", self, obj, type);
3393}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003394
3395static int
3396slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3397{
Guido van Rossum2c252392001-08-24 10:13:31 +00003398 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003399 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003400
3401 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003402 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003403 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003404 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003405 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003406 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003407 if (res == NULL)
3408 return -1;
3409 Py_DECREF(res);
3410 return 0;
3411}
3412
3413static int
3414slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3415{
Guido van Rossum60718732001-08-28 17:47:51 +00003416 static PyObject *init_str;
3417 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003418 PyObject *res;
3419
3420 if (meth == NULL)
3421 return -1;
3422 res = PyObject_Call(meth, args, kwds);
3423 Py_DECREF(meth);
3424 if (res == NULL)
3425 return -1;
3426 Py_DECREF(res);
3427 return 0;
3428}
3429
3430static PyObject *
3431slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3432{
3433 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3434 PyObject *newargs, *x;
3435 int i, n;
3436
3437 if (func == NULL)
3438 return NULL;
3439 assert(PyTuple_Check(args));
3440 n = PyTuple_GET_SIZE(args);
3441 newargs = PyTuple_New(n+1);
3442 if (newargs == NULL)
3443 return NULL;
3444 Py_INCREF(type);
3445 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3446 for (i = 0; i < n; i++) {
3447 x = PyTuple_GET_ITEM(args, i);
3448 Py_INCREF(x);
3449 PyTuple_SET_ITEM(newargs, i+1, x);
3450 }
3451 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003452 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003453 Py_DECREF(func);
3454 return x;
3455}
3456
Guido van Rossumf040ede2001-08-07 16:40:56 +00003457/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003458 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003459 The dict argument is the dictionary argument passed to type_new(),
3460 which is the local namespace of the class statement, in other
3461 words, it contains the methods. For each special method (like
3462 __repr__) defined in the dictionary, the corresponding function
3463 slot in the type object (like tp_repr) is set to a special function
3464 whose name is 'slot_' followed by the slot name and whose signature
3465 is whatever is required for that slot. These slot functions look
3466 up the corresponding method in the type's dictionary and call it.
3467 The slot functions have to take care of the various peculiarities
3468 of the mapping between slots and special methods, such as mapping
3469 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3470 etc.) or mapping multiple slots to a single method (sq_item,
3471 mp_subscript <--> __getitem__). */
3472
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473static void
3474override_slots(PyTypeObject *type, PyObject *dict)
3475{
3476 PySequenceMethods *sq = type->tp_as_sequence;
3477 PyMappingMethods *mp = type->tp_as_mapping;
3478 PyNumberMethods *nb = type->tp_as_number;
3479
Guido van Rossumdc91b992001-08-08 22:26:22 +00003480#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003481 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003482 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483 }
3484
Guido van Rossumdc91b992001-08-08 22:26:22 +00003485#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003486 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003487 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003488 }
3489
Guido van Rossumdc91b992001-08-08 22:26:22 +00003490#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003491 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003492 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003493 }
3494
Guido van Rossumdc91b992001-08-08 22:26:22 +00003495#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003496 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003497 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003498 }
3499
Guido van Rossumdc91b992001-08-08 22:26:22 +00003500 SQSLOT("__len__", sq_length, slot_sq_length);
3501 SQSLOT("__add__", sq_concat, slot_sq_concat);
3502 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3503 SQSLOT("__getitem__", sq_item, slot_sq_item);
3504 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3505 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3506 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3507 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3508 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3509 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3510 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3511 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003512
Guido van Rossumdc91b992001-08-08 22:26:22 +00003513 MPSLOT("__len__", mp_length, slot_mp_length);
3514 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3515 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3516 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003517
Guido van Rossumdc91b992001-08-08 22:26:22 +00003518 NBSLOT("__add__", nb_add, slot_nb_add);
3519 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3520 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3521 NBSLOT("__div__", nb_divide, slot_nb_divide);
3522 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3523 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3524 NBSLOT("__pow__", nb_power, slot_nb_power);
3525 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3526 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3527 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3528 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3529 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3530 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3531 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3532 NBSLOT("__and__", nb_and, slot_nb_and);
3533 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3534 NBSLOT("__or__", nb_or, slot_nb_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003535 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003536 NBSLOT("__int__", nb_int, slot_nb_int);
3537 NBSLOT("__long__", nb_long, slot_nb_long);
3538 NBSLOT("__float__", nb_float, slot_nb_float);
3539 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3540 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3541 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3542 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3543 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3544 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3545 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3546 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3547 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3548 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3549 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3550 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3551 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3552 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3553 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3554 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3555 slot_nb_inplace_floor_divide);
3556 NBSLOT("__itruediv__", nb_inplace_true_divide,
3557 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003558
Guido van Rossum8e248182001-08-12 05:17:56 +00003559 if (dict == NULL ||
3560 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003561 PyDict_GetItemString(dict, "__repr__"))
3562 type->tp_print = NULL;
3563
Guido van Rossumab3b0342001-09-18 20:38:53 +00003564 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003565 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3566 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3567 TPSLOT("__call__", tp_call, slot_tp_call);
3568 TPSLOT("__str__", tp_str, slot_tp_str);
Guido van Rossum867a8d22001-09-21 19:29:08 +00003569 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003570 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003571 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3572 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3573 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3574 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3575 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3576 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3577 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3578 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3579 TPSLOT("next", tp_iternext, slot_tp_iternext);
3580 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3581 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3582 TPSLOT("__init__", tp_init, slot_tp_init);
3583 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003584}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003585
3586
3587/* Cooperative 'super' */
3588
3589typedef struct {
3590 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003591 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003592 PyObject *obj;
3593} superobject;
3594
Guido van Rossum6f799372001-09-20 20:46:19 +00003595static PyMemberDef super_members[] = {
3596 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3597 "the class invoking super()"},
3598 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3599 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003600 {0}
3601};
3602
Guido van Rossum705f0f52001-08-24 16:47:00 +00003603static void
3604super_dealloc(PyObject *self)
3605{
3606 superobject *su = (superobject *)self;
3607
Guido van Rossum048eb752001-10-02 21:24:57 +00003608 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003609 Py_XDECREF(su->obj);
3610 Py_XDECREF(su->type);
3611 self->ob_type->tp_free(self);
3612}
3613
3614static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003615super_repr(PyObject *self)
3616{
3617 superobject *su = (superobject *)self;
3618
3619 if (su->obj)
3620 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003621 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003622 su->type ? su->type->tp_name : "NULL",
3623 su->obj->ob_type->tp_name);
3624 else
3625 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003626 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003627 su->type ? su->type->tp_name : "NULL");
3628}
3629
3630static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003631super_getattro(PyObject *self, PyObject *name)
3632{
3633 superobject *su = (superobject *)self;
3634
3635 if (su->obj != NULL) {
3636 PyObject *mro, *res, *tmp;
3637 descrgetfunc f;
3638 int i, n;
3639
Guido van Rossume705ef12001-08-29 15:47:06 +00003640 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003641 if (mro == NULL)
3642 n = 0;
3643 else {
3644 assert(PyTuple_Check(mro));
3645 n = PyTuple_GET_SIZE(mro);
3646 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003647 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003648 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003649 break;
3650 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003651 if (i >= n && PyType_Check(su->obj)) {
3652 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003653 if (mro == NULL)
3654 n = 0;
3655 else {
3656 assert(PyTuple_Check(mro));
3657 n = PyTuple_GET_SIZE(mro);
3658 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003659 for (i = 0; i < n; i++) {
3660 if ((PyObject *)(su->type) ==
3661 PyTuple_GET_ITEM(mro, i))
3662 break;
3663 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003664 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003665 i++;
3666 res = NULL;
3667 for (; i < n; i++) {
3668 tmp = PyTuple_GET_ITEM(mro, i);
3669 assert(PyType_Check(tmp));
3670 res = PyDict_GetItem(
3671 ((PyTypeObject *)tmp)->tp_defined, name);
3672 if (res != NULL) {
3673 Py_INCREF(res);
3674 f = res->ob_type->tp_descr_get;
3675 if (f != NULL) {
3676 tmp = f(res, su->obj, res);
3677 Py_DECREF(res);
3678 res = tmp;
3679 }
3680 return res;
3681 }
3682 }
3683 }
3684 return PyObject_GenericGetAttr(self, name);
3685}
3686
3687static PyObject *
3688super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3689{
3690 superobject *su = (superobject *)self;
3691 superobject *new;
3692
3693 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3694 /* Not binding to an object, or already bound */
3695 Py_INCREF(self);
3696 return self;
3697 }
3698 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3699 if (new == NULL)
3700 return NULL;
3701 Py_INCREF(su->type);
3702 Py_INCREF(obj);
3703 new->type = su->type;
3704 new->obj = obj;
3705 return (PyObject *)new;
3706}
3707
3708static int
3709super_init(PyObject *self, PyObject *args, PyObject *kwds)
3710{
3711 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003712 PyTypeObject *type;
3713 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003714
3715 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3716 return -1;
3717 if (obj == Py_None)
3718 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003719 if (obj != NULL &&
3720 !PyType_IsSubtype(obj->ob_type, type) &&
3721 !(PyType_Check(obj) &&
3722 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003723 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003724 "super(type, obj): "
3725 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003726 return -1;
3727 }
3728 Py_INCREF(type);
3729 Py_XINCREF(obj);
3730 su->type = type;
3731 su->obj = obj;
3732 return 0;
3733}
3734
3735static char super_doc[] =
3736"super(type) -> unbound super object\n"
3737"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003738"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003739"Typical use to call a cooperative superclass method:\n"
3740"class C(B):\n"
3741" def meth(self, arg):\n"
3742" super(C, self).meth(arg)";
3743
Guido van Rossum048eb752001-10-02 21:24:57 +00003744static int
3745super_traverse(PyObject *self, visitproc visit, void *arg)
3746{
3747 superobject *su = (superobject *)self;
3748 int err;
3749
3750#define VISIT(SLOT) \
3751 if (SLOT) { \
3752 err = visit((PyObject *)(SLOT), arg); \
3753 if (err) \
3754 return err; \
3755 }
3756
3757 VISIT(su->obj);
3758 VISIT(su->type);
3759
3760#undef VISIT
3761
3762 return 0;
3763}
3764
Guido van Rossum705f0f52001-08-24 16:47:00 +00003765PyTypeObject PySuper_Type = {
3766 PyObject_HEAD_INIT(&PyType_Type)
3767 0, /* ob_size */
3768 "super", /* tp_name */
3769 sizeof(superobject), /* tp_basicsize */
3770 0, /* tp_itemsize */
3771 /* methods */
3772 super_dealloc, /* tp_dealloc */
3773 0, /* tp_print */
3774 0, /* tp_getattr */
3775 0, /* tp_setattr */
3776 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003777 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003778 0, /* tp_as_number */
3779 0, /* tp_as_sequence */
3780 0, /* tp_as_mapping */
3781 0, /* tp_hash */
3782 0, /* tp_call */
3783 0, /* tp_str */
3784 super_getattro, /* tp_getattro */
3785 0, /* tp_setattro */
3786 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00003787 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3788 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003789 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00003790 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003791 0, /* tp_clear */
3792 0, /* tp_richcompare */
3793 0, /* tp_weaklistoffset */
3794 0, /* tp_iter */
3795 0, /* tp_iternext */
3796 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003797 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003798 0, /* tp_getset */
3799 0, /* tp_base */
3800 0, /* tp_dict */
3801 super_descr_get, /* tp_descr_get */
3802 0, /* tp_descr_set */
3803 0, /* tp_dictoffset */
3804 super_init, /* tp_init */
3805 PyType_GenericAlloc, /* tp_alloc */
3806 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00003807 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003808};