blob: 964164fd271f847adccd92528dbe62aa75cf0ee8 [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
56static PyObject *
57type_dict(PyTypeObject *type, void *context)
58{
59 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000060 Py_INCREF(Py_None);
61 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000062 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000063 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
64 Py_INCREF(type->tp_dict);
65 return type->tp_dict;
66 }
67 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000068}
69
Tim Peters6d6c1a32001-08-02 04:15:00 +000070static PyObject *
71type_defined(PyTypeObject *type, void *context)
72{
73 if (type->tp_defined == NULL) {
74 Py_INCREF(Py_None);
75 return Py_None;
76 }
77 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
78 Py_INCREF(type->tp_defined);
79 return type->tp_defined;
80 }
81 return PyDictProxy_New(type->tp_defined);
82}
83
84static PyObject *
85type_dynamic(PyTypeObject *type, void *context)
86{
87 PyObject *res;
88
89 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
90 Py_INCREF(res);
91 return res;
92}
93
Guido van Rossum32d34c82001-09-20 21:45:26 +000094PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000095 {"__name__", (getter)type_name, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000096 {"__module__", (getter)type_module, NULL, NULL},
97 {"__dict__", (getter)type_dict, NULL, NULL},
98 {"__defined__", (getter)type_defined, NULL, NULL},
99 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
100 {0}
101};
102
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000103static int
104type_compare(PyObject *v, PyObject *w)
105{
106 /* This is called with type objects only. So we
107 can just compare the addresses. */
108 Py_uintptr_t vv = (Py_uintptr_t)v;
109 Py_uintptr_t ww = (Py_uintptr_t)w;
110 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
111}
112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000114type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000115{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000116 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000117 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000118
119 mod = type_module(type, NULL);
120 if (mod == NULL)
121 PyErr_Clear();
122 else if (!PyString_Check(mod)) {
123 Py_DECREF(mod);
124 mod = NULL;
125 }
126 name = type_name(type, NULL);
127 if (name == NULL)
128 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000129
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000130 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
131 kind = "class";
132 else
133 kind = "type";
134
Barry Warsaw7ce36942001-08-24 18:34:26 +0000135 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000136 rtn = PyString_FromFormat("<%s '%s.%s'>",
137 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000138 PyString_AS_STRING(mod),
139 PyString_AS_STRING(name));
140 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000141 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000142 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000143
Guido van Rossumc3542212001-08-16 09:18:56 +0000144 Py_XDECREF(mod);
145 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000146 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147}
148
Tim Peters6d6c1a32001-08-02 04:15:00 +0000149static PyObject *
150type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
151{
152 PyObject *obj;
153
154 if (type->tp_new == NULL) {
155 PyErr_Format(PyExc_TypeError,
156 "cannot create '%.100s' instances",
157 type->tp_name);
158 return NULL;
159 }
160
Tim Peters3f996e72001-09-13 19:18:27 +0000161 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000162 if (obj != NULL) {
163 type = obj->ob_type;
164 if (type->tp_init != NULL &&
165 type->tp_init(obj, args, kwds) < 0) {
166 Py_DECREF(obj);
167 obj = NULL;
168 }
169 }
170 return obj;
171}
172
173PyObject *
174PyType_GenericAlloc(PyTypeObject *type, int nitems)
175{
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000176#define PTRSIZE (sizeof(PyObject *))
177
Tim Peters6d6c1a32001-08-02 04:15:00 +0000178 int size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 PyObject *obj;
180
181 /* Inline PyObject_New() so we can zero the memory */
182 size = _PyObject_VAR_SIZE(type, nitems);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000183 /* Round up size, if necessary, so we fully zero out __dict__ */
184 if (type->tp_itemsize % PTRSIZE != 0) {
185 size += PTRSIZE - 1;
186 size /= PTRSIZE;
187 size *= PTRSIZE;
188 }
Neil Schemenauerc806c882001-08-29 23:54:54 +0000189 if (PyType_IS_GC(type)) {
190 obj = _PyObject_GC_Malloc(type, nitems);
191 }
192 else {
193 obj = PyObject_MALLOC(size);
194 }
195 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000196 return PyErr_NoMemory();
Neil Schemenauerc806c882001-08-29 23:54:54 +0000197 memset(obj, '\0', size);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000198 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
199 Py_INCREF(type);
200 if (type->tp_itemsize == 0)
201 PyObject_INIT(obj, type);
202 else
203 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
204 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000205 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000206 return obj;
207}
208
209PyObject *
210PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
211{
212 return type->tp_alloc(type, 0);
213}
214
215/* Helper for subtyping */
216
217static void
218subtype_dealloc(PyObject *self)
219{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000220 PyTypeObject *type, *base;
221 destructor f;
222
223 /* This exists so we can DECREF self->ob_type */
224
225 /* Find the nearest base with a different tp_dealloc */
226 type = self->ob_type;
227 base = type->tp_base;
228 while ((f = base->tp_dealloc) == subtype_dealloc) {
229 base = base->tp_base;
230 assert(base);
231 }
232
233 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000234 if (type->tp_dictoffset && !base->tp_dictoffset) {
235 PyObject **dictptr = _PyObject_GetDictPtr(self);
236 if (dictptr != NULL) {
237 PyObject *dict = *dictptr;
238 if (dict != NULL) {
239 Py_DECREF(dict);
240 *dictptr = NULL;
241 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000242 }
243 }
244
Guido van Rossum9676b222001-08-17 20:32:36 +0000245 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000246 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000247 PyObject_ClearWeakRefs(self);
248
Tim Peters6d6c1a32001-08-02 04:15:00 +0000249 /* Finalize GC if the base doesn't do GC and we do */
250 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
251 PyObject_GC_Fini(self);
252
253 /* Call the base tp_dealloc() */
254 assert(f);
255 f(self);
256
257 /* Can't reference self beyond this point */
258 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
259 Py_DECREF(type);
260 }
261}
262
263staticforward void override_slots(PyTypeObject *type, PyObject *dict);
264staticforward PyTypeObject *solid_base(PyTypeObject *type);
265
266typedef struct {
267 PyTypeObject type;
268 PyNumberMethods as_number;
269 PySequenceMethods as_sequence;
270 PyMappingMethods as_mapping;
271 PyBufferProcs as_buffer;
272 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000273 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000274} etype;
275
276/* type test with subclassing support */
277
278int
279PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
280{
281 PyObject *mro;
282
Guido van Rossum9478d072001-09-07 18:52:13 +0000283 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
284 return b == a || b == &PyBaseObject_Type;
285
Tim Peters6d6c1a32001-08-02 04:15:00 +0000286 mro = a->tp_mro;
287 if (mro != NULL) {
288 /* Deal with multiple inheritance without recursion
289 by walking the MRO tuple */
290 int i, n;
291 assert(PyTuple_Check(mro));
292 n = PyTuple_GET_SIZE(mro);
293 for (i = 0; i < n; i++) {
294 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
295 return 1;
296 }
297 return 0;
298 }
299 else {
300 /* a is not completely initilized yet; follow tp_base */
301 do {
302 if (a == b)
303 return 1;
304 a = a->tp_base;
305 } while (a != NULL);
306 return b == &PyBaseObject_Type;
307 }
308}
309
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000310/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000311 without looking in the instance dictionary
312 (so we can't use PyObject_GetAttr) but still binding
313 it to the instance. The arguments are the object,
314 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000315 static variable used to cache the interned Python string.
316
317 Two variants:
318
319 - lookup_maybe() returns NULL without raising an exception
320 when the _PyType_Lookup() call fails;
321
322 - lookup_method() always raises an exception upon errors.
323*/
Guido van Rossum60718732001-08-28 17:47:51 +0000324
325static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000326lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000327{
328 PyObject *res;
329
330 if (*attrobj == NULL) {
331 *attrobj = PyString_InternFromString(attrstr);
332 if (*attrobj == NULL)
333 return NULL;
334 }
335 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000336 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000337 descrgetfunc f;
338 if ((f = res->ob_type->tp_descr_get) == NULL)
339 Py_INCREF(res);
340 else
341 res = f(res, self, (PyObject *)(self->ob_type));
342 }
343 return res;
344}
345
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000346static PyObject *
347lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
348{
349 PyObject *res = lookup_maybe(self, attrstr, attrobj);
350 if (res == NULL && !PyErr_Occurred())
351 PyErr_SetObject(PyExc_AttributeError, *attrobj);
352 return res;
353}
354
Guido van Rossum2730b132001-08-28 18:22:14 +0000355/* A variation of PyObject_CallMethod that uses lookup_method()
356 instead of PyObject_GetAttrString(). This uses the same convention
357 as lookup_method to cache the interned name string object. */
358
359PyObject *
360call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
361{
362 va_list va;
363 PyObject *args, *func = 0, *retval;
364 PyObject *dummy_str = NULL;
365 va_start(va, format);
366
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000367 func = lookup_maybe(o, name, &dummy_str);
368 if (func == NULL) {
369 va_end(va);
370 if (!PyErr_Occurred())
371 PyErr_SetObject(PyExc_AttributeError, dummy_str);
372 Py_XDECREF(dummy_str);
373 return NULL;
374 }
375 Py_DECREF(dummy_str);
376
377 if (format && *format)
378 args = Py_VaBuildValue(format, va);
379 else
380 args = PyTuple_New(0);
381
382 va_end(va);
383
384 if (args == NULL)
385 return NULL;
386
387 assert(PyTuple_Check(args));
388 retval = PyObject_Call(func, args, NULL);
389
390 Py_DECREF(args);
391 Py_DECREF(func);
392
393 return retval;
394}
395
396/* Clone of call_method() that returns NotImplemented when the lookup fails. */
397
398PyObject *
399call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
400{
401 va_list va;
402 PyObject *args, *func = 0, *retval;
403 PyObject *dummy_str = NULL;
404 va_start(va, format);
405
406 func = lookup_maybe(o, name, &dummy_str);
Guido van Rossum2730b132001-08-28 18:22:14 +0000407 Py_XDECREF(dummy_str);
408 if (func == NULL) {
409 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000410 if (!PyErr_Occurred()) {
411 Py_INCREF(Py_NotImplemented);
412 return Py_NotImplemented;
413 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000414 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000415 }
416
417 if (format && *format)
418 args = Py_VaBuildValue(format, va);
419 else
420 args = PyTuple_New(0);
421
422 va_end(va);
423
Guido van Rossum717ce002001-09-14 16:58:08 +0000424 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000425 return NULL;
426
Guido van Rossum717ce002001-09-14 16:58:08 +0000427 assert(PyTuple_Check(args));
428 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000429
430 Py_DECREF(args);
431 Py_DECREF(func);
432
433 return retval;
434}
435
Tim Peters6d6c1a32001-08-02 04:15:00 +0000436/* Method resolution order algorithm from "Putting Metaclasses to Work"
437 by Forman and Danforth (Addison-Wesley 1999). */
438
439static int
440conservative_merge(PyObject *left, PyObject *right)
441{
442 int left_size;
443 int right_size;
444 int i, j, r, ok;
445 PyObject *temp, *rr;
446
447 assert(PyList_Check(left));
448 assert(PyList_Check(right));
449
450 again:
451 left_size = PyList_GET_SIZE(left);
452 right_size = PyList_GET_SIZE(right);
453 for (i = 0; i < left_size; i++) {
454 for (j = 0; j < right_size; j++) {
455 if (PyList_GET_ITEM(left, i) ==
456 PyList_GET_ITEM(right, j)) {
457 /* found a merge point */
458 temp = PyList_New(0);
459 if (temp == NULL)
460 return -1;
461 for (r = 0; r < j; r++) {
462 rr = PyList_GET_ITEM(right, r);
463 ok = PySequence_Contains(left, rr);
464 if (ok < 0) {
465 Py_DECREF(temp);
466 return -1;
467 }
468 if (!ok) {
469 ok = PyList_Append(temp, rr);
470 if (ok < 0) {
471 Py_DECREF(temp);
472 return -1;
473 }
474 }
475 }
476 ok = PyList_SetSlice(left, i, i, temp);
477 Py_DECREF(temp);
478 if (ok < 0)
479 return -1;
480 ok = PyList_SetSlice(right, 0, j+1, NULL);
481 if (ok < 0)
482 return -1;
483 goto again;
484 }
485 }
486 }
487 return PyList_SetSlice(left, left_size, left_size, right);
488}
489
490static int
491serious_order_disagreements(PyObject *left, PyObject *right)
492{
493 return 0; /* XXX later -- for now, we cheat: "don't do that" */
494}
495
496static PyObject *
497mro_implementation(PyTypeObject *type)
498{
499 int i, n, ok;
500 PyObject *bases, *result;
501
502 bases = type->tp_bases;
503 n = PyTuple_GET_SIZE(bases);
504 result = Py_BuildValue("[O]", (PyObject *)type);
505 if (result == NULL)
506 return NULL;
507 for (i = 0; i < n; i++) {
508 PyTypeObject *base =
509 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
510 PyObject *parentMRO = PySequence_List(base->tp_mro);
511 if (parentMRO == NULL) {
512 Py_DECREF(result);
513 return NULL;
514 }
515 if (serious_order_disagreements(result, parentMRO)) {
516 Py_DECREF(result);
517 return NULL;
518 }
519 ok = conservative_merge(result, parentMRO);
520 Py_DECREF(parentMRO);
521 if (ok < 0) {
522 Py_DECREF(result);
523 return NULL;
524 }
525 }
526 return result;
527}
528
529static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000530mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000531{
532 PyTypeObject *type = (PyTypeObject *)self;
533
Tim Peters6d6c1a32001-08-02 04:15:00 +0000534 return mro_implementation(type);
535}
536
537static int
538mro_internal(PyTypeObject *type)
539{
540 PyObject *mro, *result, *tuple;
541
542 if (type->ob_type == &PyType_Type) {
543 result = mro_implementation(type);
544 }
545 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000546 static PyObject *mro_str;
547 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000548 if (mro == NULL)
549 return -1;
550 result = PyObject_CallObject(mro, NULL);
551 Py_DECREF(mro);
552 }
553 if (result == NULL)
554 return -1;
555 tuple = PySequence_Tuple(result);
556 Py_DECREF(result);
557 type->tp_mro = tuple;
558 return 0;
559}
560
561
562/* Calculate the best base amongst multiple base classes.
563 This is the first one that's on the path to the "solid base". */
564
565static PyTypeObject *
566best_base(PyObject *bases)
567{
568 int i, n;
569 PyTypeObject *base, *winner, *candidate, *base_i;
570
571 assert(PyTuple_Check(bases));
572 n = PyTuple_GET_SIZE(bases);
573 assert(n > 0);
574 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
575 winner = &PyBaseObject_Type;
576 for (i = 0; i < n; i++) {
577 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
578 if (!PyType_Check((PyObject *)base_i)) {
579 PyErr_SetString(
580 PyExc_TypeError,
581 "bases must be types");
582 return NULL;
583 }
584 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000585 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000586 return NULL;
587 }
588 candidate = solid_base(base_i);
589 if (PyType_IsSubtype(winner, candidate))
590 ;
591 else if (PyType_IsSubtype(candidate, winner)) {
592 winner = candidate;
593 base = base_i;
594 }
595 else {
596 PyErr_SetString(
597 PyExc_TypeError,
598 "multiple bases have "
599 "instance lay-out conflict");
600 return NULL;
601 }
602 }
603 assert(base != NULL);
604 return base;
605}
606
607static int
608extra_ivars(PyTypeObject *type, PyTypeObject *base)
609{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000610 size_t t_size = type->tp_basicsize;
611 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000612
Guido van Rossum9676b222001-08-17 20:32:36 +0000613 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000614 if (type->tp_itemsize || base->tp_itemsize) {
615 /* If itemsize is involved, stricter rules */
616 return t_size != b_size ||
617 type->tp_itemsize != base->tp_itemsize;
618 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000619 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
620 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
621 t_size -= sizeof(PyObject *);
622 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
623 type->tp_dictoffset + sizeof(PyObject *) == t_size)
624 t_size -= sizeof(PyObject *);
625
626 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000627}
628
629static PyTypeObject *
630solid_base(PyTypeObject *type)
631{
632 PyTypeObject *base;
633
634 if (type->tp_base)
635 base = solid_base(type->tp_base);
636 else
637 base = &PyBaseObject_Type;
638 if (extra_ivars(type, base))
639 return type;
640 else
641 return base;
642}
643
644staticforward void object_dealloc(PyObject *);
645staticforward int object_init(PyObject *, PyObject *, PyObject *);
646
647static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000648subtype_dict(PyObject *obj, void *context)
649{
650 PyObject **dictptr = _PyObject_GetDictPtr(obj);
651 PyObject *dict;
652
653 if (dictptr == NULL) {
654 PyErr_SetString(PyExc_AttributeError,
655 "This object has no __dict__");
656 return NULL;
657 }
658 dict = *dictptr;
659 if (dict == NULL) {
660 Py_INCREF(Py_None);
661 return Py_None;
662 }
663 else {
664 Py_INCREF(dict);
665 return dict;
666 }
667}
668
Guido van Rossum32d34c82001-09-20 21:45:26 +0000669PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000670 {"__dict__", subtype_dict, NULL, NULL},
671 {0},
672};
673
674static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
676{
677 PyObject *name, *bases, *dict;
678 static char *kwlist[] = {"name", "bases", "dict", 0};
679 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000680 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000681 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000682 PyMemberDef *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000683 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000684
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000685 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000686 if (metatype == &PyType_Type &&
687 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
688 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000689 PyObject *x = PyTuple_GET_ITEM(args, 0);
690 Py_INCREF(x->ob_type);
691 return (PyObject *) x->ob_type;
692 }
693
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000694 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000695 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
696 &name,
697 &PyTuple_Type, &bases,
698 &PyDict_Type, &dict))
699 return NULL;
700
701 /* Determine the proper metatype to deal with this,
702 and check for metatype conflicts while we're at it.
703 Note that if some other metatype wins to contract,
704 it's possible that its instances are not types. */
705 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000706 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000707 for (i = 0; i < nbases; i++) {
708 tmp = PyTuple_GET_ITEM(bases, i);
709 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000710 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000711 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000712 if (PyType_IsSubtype(tmptype, winner)) {
713 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000714 continue;
715 }
716 PyErr_SetString(PyExc_TypeError,
717 "metatype conflict among bases");
718 return NULL;
719 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000720 if (winner != metatype) {
721 if (winner->tp_new != type_new) /* Pass it to the winner */
722 return winner->tp_new(winner, args, kwds);
723 metatype = winner;
724 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000725
726 /* Adjust for empty tuple bases */
727 if (nbases == 0) {
728 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
729 if (bases == NULL)
730 return NULL;
731 nbases = 1;
732 }
733 else
734 Py_INCREF(bases);
735
736 /* XXX From here until type is allocated, "return NULL" leaks bases! */
737
738 /* Calculate best base, and check that all bases are type objects */
739 base = best_base(bases);
740 if (base == NULL)
741 return NULL;
742 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
743 PyErr_Format(PyExc_TypeError,
744 "type '%.100s' is not an acceptable base type",
745 base->tp_name);
746 return NULL;
747 }
748
Guido van Rossum1a493502001-08-17 16:47:50 +0000749 /* Should this be a dynamic class (i.e. modifiable __dict__)?
750 Look in two places for a variable named __dynamic__:
751 1) in the class dict
752 2) in the module dict (globals)
753 The first variable that is an int >= 0 is used.
754 Otherwise, a default is calculated from the base classes:
755 if any base class is dynamic, this class is dynamic; otherwise
756 it is static. */
757 dynamic = -1; /* Not yet determined */
758 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000759 tmp = PyDict_GetItemString(dict, "__dynamic__");
760 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000761 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000762 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000763 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000764 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000765 if (dynamic < 0) {
766 /* Look in the module globals */
767 tmp = PyEval_GetGlobals();
768 if (tmp != NULL) {
769 tmp = PyDict_GetItemString(tmp, "__dynamic__");
770 if (tmp != NULL) {
771 dynamic = PyInt_AsLong(tmp);
772 if (dynamic < 0)
773 PyErr_Clear();
774 }
775 }
776 }
777 if (dynamic < 0) {
778 /* Make a new class dynamic if any of its bases is
779 dynamic. This is not always the same as inheriting
780 the __dynamic__ class attribute! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000781 dynamic = 0;
782 for (i = 0; i < nbases; i++) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000783 tmptype = (PyTypeObject *)
784 PyTuple_GET_ITEM(bases, i);
785 if (tmptype->tp_flags &
786 Py_TPFLAGS_DYNAMICTYPE) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000787 dynamic = 1;
788 break;
789 }
790 }
791 }
792
793 /* Check for a __slots__ sequence variable in dict, and count it */
794 slots = PyDict_GetItemString(dict, "__slots__");
795 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000796 add_dict = 0;
797 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000798 if (slots != NULL) {
799 /* Make it into a tuple */
800 if (PyString_Check(slots))
801 slots = Py_BuildValue("(O)", slots);
802 else
803 slots = PySequence_Tuple(slots);
804 if (slots == NULL)
805 return NULL;
806 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000807 if (nslots > 0 && base->tp_itemsize != 0) {
808 PyErr_Format(PyExc_TypeError,
809 "nonempty __slots__ "
810 "not supported for subtype of '%s'",
811 base->tp_name);
812 return NULL;
813 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000814 for (i = 0; i < nslots; i++) {
815 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
816 PyErr_SetString(PyExc_TypeError,
817 "__slots__ must be a sequence of strings");
818 Py_DECREF(slots);
819 return NULL;
820 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000821 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000822 }
823 }
824 if (slots == NULL && base->tp_dictoffset == 0 &&
825 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000826 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000827 add_dict++;
828 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000829 if (slots == NULL && base->tp_weaklistoffset == 0 &&
830 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000831 nslots++;
832 add_weak++;
833 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834
835 /* XXX From here until type is safely allocated,
836 "return NULL" may leak slots! */
837
838 /* Allocate the type object */
839 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
840 if (type == NULL)
841 return NULL;
842
843 /* Keep name and slots alive in the extended type object */
844 et = (etype *)type;
845 Py_INCREF(name);
846 et->name = name;
847 et->slots = slots;
848
Guido van Rossumdc91b992001-08-08 22:26:22 +0000849 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
851 Py_TPFLAGS_BASETYPE;
852 if (dynamic)
853 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000854
855 /* It's a new-style number unless it specifically inherits any
856 old-style numeric behavior */
857 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
858 (base->tp_as_number == NULL))
859 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
860
861 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000862 type->tp_as_number = &et->as_number;
863 type->tp_as_sequence = &et->as_sequence;
864 type->tp_as_mapping = &et->as_mapping;
865 type->tp_as_buffer = &et->as_buffer;
866 type->tp_name = PyString_AS_STRING(name);
867
868 /* Set tp_base and tp_bases */
869 type->tp_bases = bases;
870 Py_INCREF(base);
871 type->tp_base = base;
872
873 /* Initialize tp_defined from passed-in dict */
874 type->tp_defined = dict = PyDict_Copy(dict);
875 if (dict == NULL) {
876 Py_DECREF(type);
877 return NULL;
878 }
879
Guido van Rossumc3542212001-08-16 09:18:56 +0000880 /* Set __module__ in the dict */
881 if (PyDict_GetItemString(dict, "__module__") == NULL) {
882 tmp = PyEval_GetGlobals();
883 if (tmp != NULL) {
884 tmp = PyDict_GetItemString(tmp, "__name__");
885 if (tmp != NULL) {
886 if (PyDict_SetItemString(dict, "__module__",
887 tmp) < 0)
888 return NULL;
889 }
890 }
891 }
892
Tim Peters6d6c1a32001-08-02 04:15:00 +0000893 /* Special-case __new__: if it's a plain function,
894 make it a static function */
895 tmp = PyDict_GetItemString(dict, "__new__");
896 if (tmp != NULL && PyFunction_Check(tmp)) {
897 tmp = PyStaticMethod_New(tmp);
898 if (tmp == NULL) {
899 Py_DECREF(type);
900 return NULL;
901 }
902 PyDict_SetItemString(dict, "__new__", tmp);
903 Py_DECREF(tmp);
904 }
905
906 /* Add descriptors for custom slots from __slots__, or for __dict__ */
907 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000908 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000909 if (slots != NULL) {
910 for (i = 0; i < nslots; i++, mp++) {
911 mp->name = PyString_AS_STRING(
912 PyTuple_GET_ITEM(slots, i));
913 mp->type = T_OBJECT;
914 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000915 if (base->tp_weaklistoffset == 0 &&
916 strcmp(mp->name, "__weakref__") == 0)
917 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000918 slotoffset += sizeof(PyObject *);
919 }
920 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000921 else {
922 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000923 if (base->tp_itemsize)
Tim Peters017cb2c2001-08-30 20:07:55 +0000924 type->tp_dictoffset = -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000925 else
926 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000927 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000928 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000929 }
930 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000931 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000932 type->tp_weaklistoffset = slotoffset;
933 mp->name = "__weakref__";
934 mp->type = T_OBJECT;
935 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000936 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000937 mp++;
938 slotoffset += sizeof(PyObject *);
939 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000940 }
941 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000942 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000943 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000944
945 /* Special case some slots */
946 if (type->tp_dictoffset != 0 || nslots > 0) {
947 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
948 type->tp_getattro = PyObject_GenericGetAttr;
949 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
950 type->tp_setattro = PyObject_GenericSetAttr;
951 }
952 type->tp_dealloc = subtype_dealloc;
953
954 /* Always override allocation strategy to use regular heap */
955 type->tp_alloc = PyType_GenericAlloc;
956 type->tp_free = _PyObject_Del;
957
958 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000959 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000960 Py_DECREF(type);
961 return NULL;
962 }
963
964 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +0000965 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
966 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000967
Tim Peters6d6c1a32001-08-02 04:15:00 +0000968 return (PyObject *)type;
969}
970
971/* Internal API to look for a name through the MRO.
972 This returns a borrowed reference, and doesn't set an exception! */
973PyObject *
974_PyType_Lookup(PyTypeObject *type, PyObject *name)
975{
976 int i, n;
977 PyObject *mro, *res, *dict;
978
979 /* For static types, look in tp_dict */
980 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
981 dict = type->tp_dict;
982 assert(dict && PyDict_Check(dict));
983 return PyDict_GetItem(dict, name);
984 }
985
986 /* For dynamic types, look in tp_defined of types in MRO */
987 mro = type->tp_mro;
988 assert(PyTuple_Check(mro));
989 n = PyTuple_GET_SIZE(mro);
990 for (i = 0; i < n; i++) {
991 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
992 assert(PyType_Check(type));
993 dict = type->tp_defined;
994 assert(dict && PyDict_Check(dict));
995 res = PyDict_GetItem(dict, name);
996 if (res != NULL)
997 return res;
998 }
999 return NULL;
1000}
1001
1002/* This is similar to PyObject_GenericGetAttr(),
1003 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1004static PyObject *
1005type_getattro(PyTypeObject *type, PyObject *name)
1006{
1007 PyTypeObject *metatype = type->ob_type;
1008 PyObject *descr, *res;
1009 descrgetfunc f;
1010
1011 /* Initialize this type (we'll assume the metatype is initialized) */
1012 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001013 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014 return NULL;
1015 }
1016
1017 /* Get a descriptor from the metatype */
1018 descr = _PyType_Lookup(metatype, name);
1019 f = NULL;
1020 if (descr != NULL) {
1021 f = descr->ob_type->tp_descr_get;
1022 if (f != NULL && PyDescr_IsData(descr))
1023 return f(descr,
1024 (PyObject *)type, (PyObject *)metatype);
1025 }
1026
1027 /* Look in tp_defined of this type and its bases */
1028 res = _PyType_Lookup(type, name);
1029 if (res != NULL) {
1030 f = res->ob_type->tp_descr_get;
1031 if (f != NULL)
1032 return f(res, (PyObject *)NULL, (PyObject *)type);
1033 Py_INCREF(res);
1034 return res;
1035 }
1036
1037 /* Use the descriptor from the metatype */
1038 if (f != NULL) {
1039 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1040 return res;
1041 }
1042 if (descr != NULL) {
1043 Py_INCREF(descr);
1044 return descr;
1045 }
1046
1047 /* Give up */
1048 PyErr_Format(PyExc_AttributeError,
1049 "type object '%.50s' has no attribute '%.400s'",
1050 type->tp_name, PyString_AS_STRING(name));
1051 return NULL;
1052}
1053
1054static int
1055type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1056{
1057 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
1058 return PyObject_GenericSetAttr((PyObject *)type, name, value);
1059 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
1060 return -1;
1061}
1062
1063static void
1064type_dealloc(PyTypeObject *type)
1065{
1066 etype *et;
1067
1068 /* Assert this is a heap-allocated type object */
1069 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
1070 et = (etype *)type;
1071 Py_XDECREF(type->tp_base);
1072 Py_XDECREF(type->tp_dict);
1073 Py_XDECREF(type->tp_bases);
1074 Py_XDECREF(type->tp_mro);
1075 Py_XDECREF(type->tp_defined);
1076 /* XXX more? */
1077 Py_XDECREF(et->name);
1078 Py_XDECREF(et->slots);
1079 type->ob_type->tp_free((PyObject *)type);
1080}
1081
1082static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001083 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001084 "mro() -> list\nreturn a type's method resolution order"},
1085 {0}
1086};
1087
1088static char type_doc[] =
1089"type(object) -> the object's type\n"
1090"type(name, bases, dict) -> a new type";
1091
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001092PyTypeObject PyType_Type = {
1093 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094 0, /* ob_size */
1095 "type", /* tp_name */
1096 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001097 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001098 (destructor)type_dealloc, /* tp_dealloc */
1099 0, /* tp_print */
1100 0, /* tp_getattr */
1101 0, /* tp_setattr */
1102 type_compare, /* tp_compare */
1103 (reprfunc)type_repr, /* tp_repr */
1104 0, /* tp_as_number */
1105 0, /* tp_as_sequence */
1106 0, /* tp_as_mapping */
1107 (hashfunc)_Py_HashPointer, /* tp_hash */
1108 (ternaryfunc)type_call, /* tp_call */
1109 0, /* tp_str */
1110 (getattrofunc)type_getattro, /* tp_getattro */
1111 (setattrofunc)type_setattro, /* tp_setattro */
1112 0, /* tp_as_buffer */
1113 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1114 type_doc, /* tp_doc */
1115 0, /* tp_traverse */
1116 0, /* tp_clear */
1117 0, /* tp_richcompare */
1118 0, /* tp_weaklistoffset */
1119 0, /* tp_iter */
1120 0, /* tp_iternext */
1121 type_methods, /* tp_methods */
1122 type_members, /* tp_members */
1123 type_getsets, /* tp_getset */
1124 0, /* tp_base */
1125 0, /* tp_dict */
1126 0, /* tp_descr_get */
1127 0, /* tp_descr_set */
1128 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1129 0, /* tp_init */
1130 0, /* tp_alloc */
1131 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001132};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001133
1134
1135/* The base type of all types (eventually)... except itself. */
1136
1137static int
1138object_init(PyObject *self, PyObject *args, PyObject *kwds)
1139{
1140 return 0;
1141}
1142
1143static void
1144object_dealloc(PyObject *self)
1145{
1146 self->ob_type->tp_free(self);
1147}
1148
Guido van Rossum8e248182001-08-12 05:17:56 +00001149static PyObject *
1150object_repr(PyObject *self)
1151{
Guido van Rossum76e69632001-08-16 18:52:43 +00001152 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001153 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001154
Guido van Rossum76e69632001-08-16 18:52:43 +00001155 type = self->ob_type;
1156 mod = type_module(type, NULL);
1157 if (mod == NULL)
1158 PyErr_Clear();
1159 else if (!PyString_Check(mod)) {
1160 Py_DECREF(mod);
1161 mod = NULL;
1162 }
1163 name = type_name(type, NULL);
1164 if (name == NULL)
1165 return NULL;
1166 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001167 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001168 PyString_AS_STRING(mod),
1169 PyString_AS_STRING(name),
1170 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001171 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001172 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001173 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001174 Py_XDECREF(mod);
1175 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001176 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001177}
1178
Guido van Rossumb8f63662001-08-15 23:57:02 +00001179static PyObject *
1180object_str(PyObject *self)
1181{
1182 unaryfunc f;
1183
1184 f = self->ob_type->tp_repr;
1185 if (f == NULL)
1186 f = object_repr;
1187 return f(self);
1188}
1189
Guido van Rossum8e248182001-08-12 05:17:56 +00001190static long
1191object_hash(PyObject *self)
1192{
1193 return _Py_HashPointer(self);
1194}
Guido van Rossum8e248182001-08-12 05:17:56 +00001195
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196static void
1197object_free(PyObject *self)
1198{
1199 PyObject_Del(self);
1200}
1201
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001202static PyObject *
1203object_get_class(PyObject *self, void *closure)
1204{
1205 Py_INCREF(self->ob_type);
1206 return (PyObject *)(self->ob_type);
1207}
1208
1209static int
1210equiv_structs(PyTypeObject *a, PyTypeObject *b)
1211{
1212 return a == b ||
1213 (a != NULL &&
1214 b != NULL &&
1215 a->tp_basicsize == b->tp_basicsize &&
1216 a->tp_itemsize == b->tp_itemsize &&
1217 a->tp_dictoffset == b->tp_dictoffset &&
1218 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1219 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1220 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1221}
1222
1223static int
1224same_slots_added(PyTypeObject *a, PyTypeObject *b)
1225{
1226 PyTypeObject *base = a->tp_base;
1227 int size;
1228
1229 if (base != b->tp_base)
1230 return 0;
1231 if (equiv_structs(a, base) && equiv_structs(b, base))
1232 return 1;
1233 size = base->tp_basicsize;
1234 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1235 size += sizeof(PyObject *);
1236 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1237 size += sizeof(PyObject *);
1238 return size == a->tp_basicsize && size == b->tp_basicsize;
1239}
1240
1241static int
1242object_set_class(PyObject *self, PyObject *value, void *closure)
1243{
1244 PyTypeObject *old = self->ob_type;
1245 PyTypeObject *new, *newbase, *oldbase;
1246
1247 if (!PyType_Check(value)) {
1248 PyErr_Format(PyExc_TypeError,
1249 "__class__ must be set to new-style class, not '%s' object",
1250 value->ob_type->tp_name);
1251 return -1;
1252 }
1253 new = (PyTypeObject *)value;
1254 newbase = new;
1255 oldbase = old;
1256 while (equiv_structs(newbase, newbase->tp_base))
1257 newbase = newbase->tp_base;
1258 while (equiv_structs(oldbase, oldbase->tp_base))
1259 oldbase = oldbase->tp_base;
1260 if (newbase != oldbase &&
1261 (newbase->tp_base != oldbase->tp_base ||
1262 !same_slots_added(newbase, oldbase))) {
1263 PyErr_Format(PyExc_TypeError,
1264 "__class__ assignment: "
1265 "'%s' object layout differs from '%s'",
1266 new->tp_name,
1267 old->tp_name);
1268 return -1;
1269 }
1270 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1271 Py_INCREF(new);
1272 }
1273 self->ob_type = new;
1274 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1275 Py_DECREF(old);
1276 }
1277 return 0;
1278}
1279
1280static PyGetSetDef object_getsets[] = {
1281 {"__class__", object_get_class, object_set_class,
1282 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001283 {0}
1284};
1285
1286PyTypeObject PyBaseObject_Type = {
1287 PyObject_HEAD_INIT(&PyType_Type)
1288 0, /* ob_size */
1289 "object", /* tp_name */
1290 sizeof(PyObject), /* tp_basicsize */
1291 0, /* tp_itemsize */
1292 (destructor)object_dealloc, /* tp_dealloc */
1293 0, /* tp_print */
1294 0, /* tp_getattr */
1295 0, /* tp_setattr */
1296 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001297 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001298 0, /* tp_as_number */
1299 0, /* tp_as_sequence */
1300 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001301 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001302 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001303 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001304 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001305 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 0, /* tp_as_buffer */
1307 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1308 "The most base type", /* tp_doc */
1309 0, /* tp_traverse */
1310 0, /* tp_clear */
1311 0, /* tp_richcompare */
1312 0, /* tp_weaklistoffset */
1313 0, /* tp_iter */
1314 0, /* tp_iternext */
1315 0, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001316 0, /* tp_members */
1317 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001318 0, /* tp_base */
1319 0, /* tp_dict */
1320 0, /* tp_descr_get */
1321 0, /* tp_descr_set */
1322 0, /* tp_dictoffset */
1323 object_init, /* tp_init */
1324 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001325 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001326 object_free, /* tp_free */
1327};
1328
1329
1330/* Initialize the __dict__ in a type object */
1331
1332static int
1333add_methods(PyTypeObject *type, PyMethodDef *meth)
1334{
1335 PyObject *dict = type->tp_defined;
1336
1337 for (; meth->ml_name != NULL; meth++) {
1338 PyObject *descr;
1339 if (PyDict_GetItemString(dict, meth->ml_name))
1340 continue;
1341 descr = PyDescr_NewMethod(type, meth);
1342 if (descr == NULL)
1343 return -1;
1344 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1345 return -1;
1346 Py_DECREF(descr);
1347 }
1348 return 0;
1349}
1350
1351static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001352add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001353{
1354 PyObject *dict = type->tp_defined;
1355
1356 for (; memb->name != NULL; memb++) {
1357 PyObject *descr;
1358 if (PyDict_GetItemString(dict, memb->name))
1359 continue;
1360 descr = PyDescr_NewMember(type, memb);
1361 if (descr == NULL)
1362 return -1;
1363 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1364 return -1;
1365 Py_DECREF(descr);
1366 }
1367 return 0;
1368}
1369
1370static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001371add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372{
1373 PyObject *dict = type->tp_defined;
1374
1375 for (; gsp->name != NULL; gsp++) {
1376 PyObject *descr;
1377 if (PyDict_GetItemString(dict, gsp->name))
1378 continue;
1379 descr = PyDescr_NewGetSet(type, gsp);
1380
1381 if (descr == NULL)
1382 return -1;
1383 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1384 return -1;
1385 Py_DECREF(descr);
1386 }
1387 return 0;
1388}
1389
Guido van Rossum13d52f02001-08-10 21:24:08 +00001390static void
1391inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001392{
1393 int oldsize, newsize;
1394
Guido van Rossum13d52f02001-08-10 21:24:08 +00001395 /* Special flag magic */
1396 if (!type->tp_as_buffer && base->tp_as_buffer) {
1397 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1398 type->tp_flags |=
1399 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1400 }
1401 if (!type->tp_as_sequence && base->tp_as_sequence) {
1402 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1403 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1404 }
1405 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1406 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1407 if ((!type->tp_as_number && base->tp_as_number) ||
1408 (!type->tp_as_sequence && base->tp_as_sequence)) {
1409 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1410 if (!type->tp_as_number && !type->tp_as_sequence) {
1411 type->tp_flags |= base->tp_flags &
1412 Py_TPFLAGS_HAVE_INPLACEOPS;
1413 }
1414 }
1415 /* Wow */
1416 }
1417 if (!type->tp_as_number && base->tp_as_number) {
1418 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1419 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1420 }
1421
1422 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001423 oldsize = base->tp_basicsize;
1424 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1425 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1426 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001427 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1428 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001429 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001430 if (type->tp_traverse == NULL)
1431 type->tp_traverse = base->tp_traverse;
1432 if (type->tp_clear == NULL)
1433 type->tp_clear = base->tp_clear;
1434 }
1435 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1436 if (base != &PyBaseObject_Type ||
1437 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1438 if (type->tp_new == NULL)
1439 type->tp_new = base->tp_new;
1440 }
1441 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001442 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001443
1444 /* Copy other non-function slots */
1445
1446#undef COPYVAL
1447#define COPYVAL(SLOT) \
1448 if (type->SLOT == 0) type->SLOT = base->SLOT
1449
1450 COPYVAL(tp_itemsize);
1451 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1452 COPYVAL(tp_weaklistoffset);
1453 }
1454 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1455 COPYVAL(tp_dictoffset);
1456 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001457}
1458
1459static void
1460inherit_slots(PyTypeObject *type, PyTypeObject *base)
1461{
1462 PyTypeObject *basebase;
1463
1464#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001465#undef COPYSLOT
1466#undef COPYNUM
1467#undef COPYSEQ
1468#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001469
1470#define SLOTDEFINED(SLOT) \
1471 (base->SLOT != 0 && \
1472 (basebase == NULL || base->SLOT != basebase->SLOT))
1473
Tim Peters6d6c1a32001-08-02 04:15:00 +00001474#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001475 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476
1477#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1478#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1479#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1480
Guido van Rossum13d52f02001-08-10 21:24:08 +00001481 /* This won't inherit indirect slots (from tp_as_number etc.)
1482 if type doesn't provide the space. */
1483
1484 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1485 basebase = base->tp_base;
1486 if (basebase->tp_as_number == NULL)
1487 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488 COPYNUM(nb_add);
1489 COPYNUM(nb_subtract);
1490 COPYNUM(nb_multiply);
1491 COPYNUM(nb_divide);
1492 COPYNUM(nb_remainder);
1493 COPYNUM(nb_divmod);
1494 COPYNUM(nb_power);
1495 COPYNUM(nb_negative);
1496 COPYNUM(nb_positive);
1497 COPYNUM(nb_absolute);
1498 COPYNUM(nb_nonzero);
1499 COPYNUM(nb_invert);
1500 COPYNUM(nb_lshift);
1501 COPYNUM(nb_rshift);
1502 COPYNUM(nb_and);
1503 COPYNUM(nb_xor);
1504 COPYNUM(nb_or);
1505 COPYNUM(nb_coerce);
1506 COPYNUM(nb_int);
1507 COPYNUM(nb_long);
1508 COPYNUM(nb_float);
1509 COPYNUM(nb_oct);
1510 COPYNUM(nb_hex);
1511 COPYNUM(nb_inplace_add);
1512 COPYNUM(nb_inplace_subtract);
1513 COPYNUM(nb_inplace_multiply);
1514 COPYNUM(nb_inplace_divide);
1515 COPYNUM(nb_inplace_remainder);
1516 COPYNUM(nb_inplace_power);
1517 COPYNUM(nb_inplace_lshift);
1518 COPYNUM(nb_inplace_rshift);
1519 COPYNUM(nb_inplace_and);
1520 COPYNUM(nb_inplace_xor);
1521 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001522 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1523 COPYNUM(nb_true_divide);
1524 COPYNUM(nb_floor_divide);
1525 COPYNUM(nb_inplace_true_divide);
1526 COPYNUM(nb_inplace_floor_divide);
1527 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001528 }
1529
Guido van Rossum13d52f02001-08-10 21:24:08 +00001530 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1531 basebase = base->tp_base;
1532 if (basebase->tp_as_sequence == NULL)
1533 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001534 COPYSEQ(sq_length);
1535 COPYSEQ(sq_concat);
1536 COPYSEQ(sq_repeat);
1537 COPYSEQ(sq_item);
1538 COPYSEQ(sq_slice);
1539 COPYSEQ(sq_ass_item);
1540 COPYSEQ(sq_ass_slice);
1541 COPYSEQ(sq_contains);
1542 COPYSEQ(sq_inplace_concat);
1543 COPYSEQ(sq_inplace_repeat);
1544 }
1545
Guido van Rossum13d52f02001-08-10 21:24:08 +00001546 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1547 basebase = base->tp_base;
1548 if (basebase->tp_as_mapping == NULL)
1549 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550 COPYMAP(mp_length);
1551 COPYMAP(mp_subscript);
1552 COPYMAP(mp_ass_subscript);
1553 }
1554
Guido van Rossum13d52f02001-08-10 21:24:08 +00001555 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556
Tim Peters6d6c1a32001-08-02 04:15:00 +00001557 COPYSLOT(tp_dealloc);
1558 COPYSLOT(tp_print);
1559 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1560 type->tp_getattr = base->tp_getattr;
1561 type->tp_getattro = base->tp_getattro;
1562 }
1563 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1564 type->tp_setattr = base->tp_setattr;
1565 type->tp_setattro = base->tp_setattro;
1566 }
1567 /* tp_compare see tp_richcompare */
1568 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001569 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001570 COPYSLOT(tp_call);
1571 COPYSLOT(tp_str);
1572 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001573 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001574 if (type->tp_compare == NULL &&
1575 type->tp_richcompare == NULL &&
1576 type->tp_hash == NULL)
1577 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001578 type->tp_compare = base->tp_compare;
1579 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001580 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001581 }
1582 }
1583 else {
1584 COPYSLOT(tp_compare);
1585 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1587 COPYSLOT(tp_iter);
1588 COPYSLOT(tp_iternext);
1589 }
1590 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1591 COPYSLOT(tp_descr_get);
1592 COPYSLOT(tp_descr_set);
1593 COPYSLOT(tp_dictoffset);
1594 COPYSLOT(tp_init);
1595 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001596 COPYSLOT(tp_free);
1597 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001598}
1599
Guido van Rossum13d52f02001-08-10 21:24:08 +00001600staticforward int add_operators(PyTypeObject *);
1601
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001603PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001604{
1605 PyObject *dict, *bases, *x;
1606 PyTypeObject *base;
1607 int i, n;
1608
Guido van Rossumd614f972001-08-10 17:39:49 +00001609 if (type->tp_flags & Py_TPFLAGS_READY) {
1610 assert(type->tp_dict != NULL);
1611 return 0;
1612 }
1613 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1614 assert(type->tp_dict == NULL);
1615
1616 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001617
1618 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1619 base = type->tp_base;
1620 if (base == NULL && type != &PyBaseObject_Type)
1621 base = type->tp_base = &PyBaseObject_Type;
1622
1623 /* Initialize tp_bases */
1624 bases = type->tp_bases;
1625 if (bases == NULL) {
1626 if (base == NULL)
1627 bases = PyTuple_New(0);
1628 else
1629 bases = Py_BuildValue("(O)", base);
1630 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001631 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001632 type->tp_bases = bases;
1633 }
1634
1635 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001636 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001637 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001638 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001639 }
1640
1641 /* Initialize tp_defined */
1642 dict = type->tp_defined;
1643 if (dict == NULL) {
1644 dict = PyDict_New();
1645 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001646 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001647 type->tp_defined = dict;
1648 }
1649
1650 /* Add type-specific descriptors to tp_defined */
1651 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001652 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653 if (type->tp_methods != NULL) {
1654 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001655 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001656 }
1657 if (type->tp_members != NULL) {
1658 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001659 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001660 }
1661 if (type->tp_getset != NULL) {
1662 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001663 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001664 }
1665
1666 /* Temporarily make tp_dict the same object as tp_defined.
1667 (This is needed to call mro(), and can stay this way for
1668 dynamic types). */
1669 Py_INCREF(type->tp_defined);
1670 type->tp_dict = type->tp_defined;
1671
1672 /* Calculate method resolution order */
1673 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001674 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001675 }
1676
Guido van Rossum13d52f02001-08-10 21:24:08 +00001677 /* Inherit special flags from dominant base */
1678 if (type->tp_base != NULL)
1679 inherit_special(type, type->tp_base);
1680
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001682 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001683 /* For a dynamic type, all slots are overridden */
1684 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001685 }
1686 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001687 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001688 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001689 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001690 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001692 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693 bases = type->tp_mro;
1694 assert(bases != NULL);
1695 assert(PyTuple_Check(bases));
1696 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001697 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1699 assert(PyType_Check(base));
1700 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001701 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001702 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001703 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001704 }
1705 }
1706
Guido van Rossum13d52f02001-08-10 21:24:08 +00001707 /* Some more special stuff */
1708 base = type->tp_base;
1709 if (base != NULL) {
1710 if (type->tp_as_number == NULL)
1711 type->tp_as_number = base->tp_as_number;
1712 if (type->tp_as_sequence == NULL)
1713 type->tp_as_sequence = base->tp_as_sequence;
1714 if (type->tp_as_mapping == NULL)
1715 type->tp_as_mapping = base->tp_as_mapping;
1716 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717
Guido van Rossum13d52f02001-08-10 21:24:08 +00001718 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001719 assert(type->tp_dict != NULL);
1720 type->tp_flags =
1721 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001722 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001723
1724 error:
1725 type->tp_flags &= ~Py_TPFLAGS_READYING;
1726 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001727}
1728
1729
1730/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1731
1732/* There's a wrapper *function* for each distinct function typedef used
1733 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1734 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1735 Most tables have only one entry; the tables for binary operators have two
1736 entries, one regular and one with reversed arguments. */
1737
1738static PyObject *
1739wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1740{
1741 inquiry func = (inquiry)wrapped;
1742 int res;
1743
1744 if (!PyArg_ParseTuple(args, ""))
1745 return NULL;
1746 res = (*func)(self);
1747 if (res == -1 && PyErr_Occurred())
1748 return NULL;
1749 return PyInt_FromLong((long)res);
1750}
1751
1752static struct wrapperbase tab_len[] = {
1753 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1754 {0}
1755};
1756
1757static PyObject *
1758wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1759{
1760 binaryfunc func = (binaryfunc)wrapped;
1761 PyObject *other;
1762
1763 if (!PyArg_ParseTuple(args, "O", &other))
1764 return NULL;
1765 return (*func)(self, other);
1766}
1767
1768static PyObject *
1769wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1770{
1771 binaryfunc func = (binaryfunc)wrapped;
1772 PyObject *other;
1773
1774 if (!PyArg_ParseTuple(args, "O", &other))
1775 return NULL;
1776 return (*func)(other, self);
1777}
1778
1779#undef BINARY
1780#define BINARY(NAME, OP) \
1781static struct wrapperbase tab_##NAME[] = { \
1782 {"__" #NAME "__", \
1783 (wrapperfunc)wrap_binaryfunc, \
1784 "x.__" #NAME "__(y) <==> " #OP}, \
1785 {"__r" #NAME "__", \
1786 (wrapperfunc)wrap_binaryfunc_r, \
1787 "y.__r" #NAME "__(x) <==> " #OP}, \
1788 {0} \
1789}
1790
1791BINARY(add, "x+y");
1792BINARY(sub, "x-y");
1793BINARY(mul, "x*y");
1794BINARY(div, "x/y");
1795BINARY(mod, "x%y");
1796BINARY(divmod, "divmod(x,y)");
1797BINARY(lshift, "x<<y");
1798BINARY(rshift, "x>>y");
1799BINARY(and, "x&y");
1800BINARY(xor, "x^y");
1801BINARY(or, "x|y");
1802
1803static PyObject *
1804wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1805{
1806 ternaryfunc func = (ternaryfunc)wrapped;
1807 PyObject *other;
1808 PyObject *third = Py_None;
1809
1810 /* Note: This wrapper only works for __pow__() */
1811
1812 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1813 return NULL;
1814 return (*func)(self, other, third);
1815}
1816
1817#undef TERNARY
1818#define TERNARY(NAME, OP) \
1819static struct wrapperbase tab_##NAME[] = { \
1820 {"__" #NAME "__", \
1821 (wrapperfunc)wrap_ternaryfunc, \
1822 "x.__" #NAME "__(y, z) <==> " #OP}, \
1823 {"__r" #NAME "__", \
1824 (wrapperfunc)wrap_ternaryfunc, \
1825 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1826 {0} \
1827}
1828
1829TERNARY(pow, "(x**y) % z");
1830
1831#undef UNARY
1832#define UNARY(NAME, OP) \
1833static struct wrapperbase tab_##NAME[] = { \
1834 {"__" #NAME "__", \
1835 (wrapperfunc)wrap_unaryfunc, \
1836 "x.__" #NAME "__() <==> " #OP}, \
1837 {0} \
1838}
1839
1840static PyObject *
1841wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1842{
1843 unaryfunc func = (unaryfunc)wrapped;
1844
1845 if (!PyArg_ParseTuple(args, ""))
1846 return NULL;
1847 return (*func)(self);
1848}
1849
1850UNARY(neg, "-x");
1851UNARY(pos, "+x");
1852UNARY(abs, "abs(x)");
1853UNARY(nonzero, "x != 0");
1854UNARY(invert, "~x");
1855UNARY(int, "int(x)");
1856UNARY(long, "long(x)");
1857UNARY(float, "float(x)");
1858UNARY(oct, "oct(x)");
1859UNARY(hex, "hex(x)");
1860
1861#undef IBINARY
1862#define IBINARY(NAME, OP) \
1863static struct wrapperbase tab_##NAME[] = { \
1864 {"__" #NAME "__", \
1865 (wrapperfunc)wrap_binaryfunc, \
1866 "x.__" #NAME "__(y) <==> " #OP}, \
1867 {0} \
1868}
1869
1870IBINARY(iadd, "x+=y");
1871IBINARY(isub, "x-=y");
1872IBINARY(imul, "x*=y");
1873IBINARY(idiv, "x/=y");
1874IBINARY(imod, "x%=y");
1875IBINARY(ilshift, "x<<=y");
1876IBINARY(irshift, "x>>=y");
1877IBINARY(iand, "x&=y");
1878IBINARY(ixor, "x^=y");
1879IBINARY(ior, "x|=y");
1880
1881#undef ITERNARY
1882#define ITERNARY(NAME, OP) \
1883static struct wrapperbase tab_##NAME[] = { \
1884 {"__" #NAME "__", \
1885 (wrapperfunc)wrap_ternaryfunc, \
1886 "x.__" #NAME "__(y) <==> " #OP}, \
1887 {0} \
1888}
1889
1890ITERNARY(ipow, "x = (x**y) % z");
1891
1892static struct wrapperbase tab_getitem[] = {
1893 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1894 "x.__getitem__(y) <==> x[y]"},
1895 {0}
1896};
1897
1898static PyObject *
1899wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1900{
1901 intargfunc func = (intargfunc)wrapped;
1902 int i;
1903
1904 if (!PyArg_ParseTuple(args, "i", &i))
1905 return NULL;
1906 return (*func)(self, i);
1907}
1908
1909static struct wrapperbase tab_mul_int[] = {
1910 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1911 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1912 {0}
1913};
1914
1915static struct wrapperbase tab_concat[] = {
1916 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1917 {0}
1918};
1919
1920static struct wrapperbase tab_imul_int[] = {
1921 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1922 {0}
1923};
1924
Guido van Rossum5d815f32001-08-17 21:57:47 +00001925static int
1926getindex(PyObject *self, PyObject *arg)
1927{
1928 int i;
1929
1930 i = PyInt_AsLong(arg);
1931 if (i == -1 && PyErr_Occurred())
1932 return -1;
1933 if (i < 0) {
1934 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
1935 if (sq && sq->sq_length) {
1936 int n = (*sq->sq_length)(self);
1937 if (n < 0)
1938 return -1;
1939 i += n;
1940 }
1941 }
1942 return i;
1943}
1944
1945static PyObject *
1946wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
1947{
1948 intargfunc func = (intargfunc)wrapped;
1949 PyObject *arg;
1950 int i;
1951
1952 if (!PyArg_ParseTuple(args, "O", &arg))
1953 return NULL;
1954 i = getindex(self, arg);
1955 if (i == -1 && PyErr_Occurred())
1956 return NULL;
1957 return (*func)(self, i);
1958}
1959
Tim Peters6d6c1a32001-08-02 04:15:00 +00001960static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001961 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001962 "x.__getitem__(i) <==> x[i]"},
1963 {0}
1964};
1965
1966static PyObject *
1967wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1968{
1969 intintargfunc func = (intintargfunc)wrapped;
1970 int i, j;
1971
1972 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1973 return NULL;
1974 return (*func)(self, i, j);
1975}
1976
1977static struct wrapperbase tab_getslice[] = {
1978 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1979 "x.__getslice__(i, j) <==> x[i:j]"},
1980 {0}
1981};
1982
1983static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001984wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001985{
1986 intobjargproc func = (intobjargproc)wrapped;
1987 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001988 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001989
Guido van Rossum5d815f32001-08-17 21:57:47 +00001990 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
1991 return NULL;
1992 i = getindex(self, arg);
1993 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994 return NULL;
1995 res = (*func)(self, i, value);
1996 if (res == -1 && PyErr_Occurred())
1997 return NULL;
1998 Py_INCREF(Py_None);
1999 return Py_None;
2000}
2001
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002002static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002003wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002004{
2005 intobjargproc func = (intobjargproc)wrapped;
2006 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002007 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002008
Guido van Rossum5d815f32001-08-17 21:57:47 +00002009 if (!PyArg_ParseTuple(args, "O", &arg))
2010 return NULL;
2011 i = getindex(self, arg);
2012 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002013 return NULL;
2014 res = (*func)(self, i, NULL);
2015 if (res == -1 && PyErr_Occurred())
2016 return NULL;
2017 Py_INCREF(Py_None);
2018 return Py_None;
2019}
2020
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002022 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002023 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002024 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002025 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026 {0}
2027};
2028
2029static PyObject *
2030wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2031{
2032 intintobjargproc func = (intintobjargproc)wrapped;
2033 int i, j, res;
2034 PyObject *value;
2035
2036 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2037 return NULL;
2038 res = (*func)(self, i, j, value);
2039 if (res == -1 && PyErr_Occurred())
2040 return NULL;
2041 Py_INCREF(Py_None);
2042 return Py_None;
2043}
2044
2045static struct wrapperbase tab_setslice[] = {
2046 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2047 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
2048 {0}
2049};
2050
2051/* XXX objobjproc is a misnomer; should be objargpred */
2052static PyObject *
2053wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2054{
2055 objobjproc func = (objobjproc)wrapped;
2056 int res;
2057 PyObject *value;
2058
2059 if (!PyArg_ParseTuple(args, "O", &value))
2060 return NULL;
2061 res = (*func)(self, value);
2062 if (res == -1 && PyErr_Occurred())
2063 return NULL;
2064 return PyInt_FromLong((long)res);
2065}
2066
2067static struct wrapperbase tab_contains[] = {
2068 {"__contains__", (wrapperfunc)wrap_objobjproc,
2069 "x.__contains__(y) <==> y in x"},
2070 {0}
2071};
2072
2073static PyObject *
2074wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2075{
2076 objobjargproc func = (objobjargproc)wrapped;
2077 int res;
2078 PyObject *key, *value;
2079
2080 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2081 return NULL;
2082 res = (*func)(self, key, value);
2083 if (res == -1 && PyErr_Occurred())
2084 return NULL;
2085 Py_INCREF(Py_None);
2086 return Py_None;
2087}
2088
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002089static PyObject *
2090wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2091{
2092 objobjargproc func = (objobjargproc)wrapped;
2093 int res;
2094 PyObject *key;
2095
2096 if (!PyArg_ParseTuple(args, "O", &key))
2097 return NULL;
2098 res = (*func)(self, key, NULL);
2099 if (res == -1 && PyErr_Occurred())
2100 return NULL;
2101 Py_INCREF(Py_None);
2102 return Py_None;
2103}
2104
Tim Peters6d6c1a32001-08-02 04:15:00 +00002105static struct wrapperbase tab_setitem[] = {
2106 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2107 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002108 {"__delitem__", (wrapperfunc)wrap_delitem,
2109 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110 {0}
2111};
2112
2113static PyObject *
2114wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2115{
2116 cmpfunc func = (cmpfunc)wrapped;
2117 int res;
2118 PyObject *other;
2119
2120 if (!PyArg_ParseTuple(args, "O", &other))
2121 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002122 if (other->ob_type->tp_compare != func &&
2123 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002124 PyErr_Format(
2125 PyExc_TypeError,
2126 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2127 self->ob_type->tp_name,
2128 self->ob_type->tp_name,
2129 other->ob_type->tp_name);
2130 return NULL;
2131 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002132 res = (*func)(self, other);
2133 if (PyErr_Occurred())
2134 return NULL;
2135 return PyInt_FromLong((long)res);
2136}
2137
2138static struct wrapperbase tab_cmp[] = {
2139 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2140 "x.__cmp__(y) <==> cmp(x,y)"},
2141 {0}
2142};
2143
2144static struct wrapperbase tab_repr[] = {
2145 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2146 "x.__repr__() <==> repr(x)"},
2147 {0}
2148};
2149
2150static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002151 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2152 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002153 {0}
2154};
2155
2156static PyObject *
2157wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2158{
2159 setattrofunc func = (setattrofunc)wrapped;
2160 int res;
2161 PyObject *name, *value;
2162
2163 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2164 return NULL;
2165 res = (*func)(self, name, value);
2166 if (res < 0)
2167 return NULL;
2168 Py_INCREF(Py_None);
2169 return Py_None;
2170}
2171
2172static PyObject *
2173wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2174{
2175 setattrofunc func = (setattrofunc)wrapped;
2176 int res;
2177 PyObject *name;
2178
2179 if (!PyArg_ParseTuple(args, "O", &name))
2180 return NULL;
2181 res = (*func)(self, name, NULL);
2182 if (res < 0)
2183 return NULL;
2184 Py_INCREF(Py_None);
2185 return Py_None;
2186}
2187
2188static struct wrapperbase tab_setattr[] = {
2189 {"__setattr__", (wrapperfunc)wrap_setattr,
2190 "x.__setattr__('name', value) <==> x.name = value"},
2191 {"__delattr__", (wrapperfunc)wrap_delattr,
2192 "x.__delattr__('name') <==> del x.name"},
2193 {0}
2194};
2195
2196static PyObject *
2197wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2198{
2199 hashfunc func = (hashfunc)wrapped;
2200 long res;
2201
2202 if (!PyArg_ParseTuple(args, ""))
2203 return NULL;
2204 res = (*func)(self);
2205 if (res == -1 && PyErr_Occurred())
2206 return NULL;
2207 return PyInt_FromLong(res);
2208}
2209
2210static struct wrapperbase tab_hash[] = {
2211 {"__hash__", (wrapperfunc)wrap_hashfunc,
2212 "x.__hash__() <==> hash(x)"},
2213 {0}
2214};
2215
2216static PyObject *
2217wrap_call(PyObject *self, PyObject *args, void *wrapped)
2218{
2219 ternaryfunc func = (ternaryfunc)wrapped;
2220
2221 /* XXX What about keyword arguments? */
2222 return (*func)(self, args, NULL);
2223}
2224
2225static struct wrapperbase tab_call[] = {
2226 {"__call__", (wrapperfunc)wrap_call,
2227 "x.__call__(...) <==> x(...)"},
2228 {0}
2229};
2230
2231static struct wrapperbase tab_str[] = {
2232 {"__str__", (wrapperfunc)wrap_unaryfunc,
2233 "x.__str__() <==> str(x)"},
2234 {0}
2235};
2236
2237static PyObject *
2238wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2239{
2240 richcmpfunc func = (richcmpfunc)wrapped;
2241 PyObject *other;
2242
2243 if (!PyArg_ParseTuple(args, "O", &other))
2244 return NULL;
2245 return (*func)(self, other, op);
2246}
2247
2248#undef RICHCMP_WRAPPER
2249#define RICHCMP_WRAPPER(NAME, OP) \
2250static PyObject * \
2251richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2252{ \
2253 return wrap_richcmpfunc(self, args, wrapped, OP); \
2254}
2255
Jack Jansen8e938b42001-08-08 15:29:49 +00002256RICHCMP_WRAPPER(lt, Py_LT)
2257RICHCMP_WRAPPER(le, Py_LE)
2258RICHCMP_WRAPPER(eq, Py_EQ)
2259RICHCMP_WRAPPER(ne, Py_NE)
2260RICHCMP_WRAPPER(gt, Py_GT)
2261RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002262
2263#undef RICHCMP_ENTRY
2264#define RICHCMP_ENTRY(NAME, EXPR) \
2265 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2266 "x.__" #NAME "__(y) <==> " EXPR}
2267
2268static struct wrapperbase tab_richcmp[] = {
2269 RICHCMP_ENTRY(lt, "x<y"),
2270 RICHCMP_ENTRY(le, "x<=y"),
2271 RICHCMP_ENTRY(eq, "x==y"),
2272 RICHCMP_ENTRY(ne, "x!=y"),
2273 RICHCMP_ENTRY(gt, "x>y"),
2274 RICHCMP_ENTRY(ge, "x>=y"),
2275 {0}
2276};
2277
2278static struct wrapperbase tab_iter[] = {
2279 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2280 {0}
2281};
2282
2283static PyObject *
2284wrap_next(PyObject *self, PyObject *args, void *wrapped)
2285{
2286 unaryfunc func = (unaryfunc)wrapped;
2287 PyObject *res;
2288
2289 if (!PyArg_ParseTuple(args, ""))
2290 return NULL;
2291 res = (*func)(self);
2292 if (res == NULL && !PyErr_Occurred())
2293 PyErr_SetNone(PyExc_StopIteration);
2294 return res;
2295}
2296
2297static struct wrapperbase tab_next[] = {
2298 {"next", (wrapperfunc)wrap_next,
2299 "x.next() -> the next value, or raise StopIteration"},
2300 {0}
2301};
2302
2303static PyObject *
2304wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2305{
2306 descrgetfunc func = (descrgetfunc)wrapped;
2307 PyObject *obj;
2308 PyObject *type = NULL;
2309
2310 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2311 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002312 return (*func)(self, obj, type);
2313}
2314
2315static struct wrapperbase tab_descr_get[] = {
2316 {"__get__", (wrapperfunc)wrap_descr_get,
2317 "descr.__get__(obj, type) -> value"},
2318 {0}
2319};
2320
2321static PyObject *
2322wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2323{
2324 descrsetfunc func = (descrsetfunc)wrapped;
2325 PyObject *obj, *value;
2326 int ret;
2327
2328 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2329 return NULL;
2330 ret = (*func)(self, obj, value);
2331 if (ret < 0)
2332 return NULL;
2333 Py_INCREF(Py_None);
2334 return Py_None;
2335}
2336
2337static struct wrapperbase tab_descr_set[] = {
2338 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2339 "descr.__set__(obj, value)"},
2340 {0}
2341};
2342
2343static PyObject *
2344wrap_init(PyObject *self, PyObject *args, void *wrapped)
2345{
2346 initproc func = (initproc)wrapped;
2347
2348 /* XXX What about keyword arguments? */
2349 if (func(self, args, NULL) < 0)
2350 return NULL;
2351 Py_INCREF(Py_None);
2352 return Py_None;
2353}
2354
2355static struct wrapperbase tab_init[] = {
2356 {"__init__", (wrapperfunc)wrap_init,
2357 "x.__init__(...) initializes x; "
2358 "see x.__type__.__doc__ for signature"},
2359 {0}
2360};
2361
2362static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002363tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002364{
Barry Warsaw60f01882001-08-22 19:24:42 +00002365 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002366 PyObject *arg0, *res;
2367
2368 if (self == NULL || !PyType_Check(self))
2369 Py_FatalError("__new__() called with non-type 'self'");
2370 type = (PyTypeObject *)self;
2371 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002372 PyErr_Format(PyExc_TypeError,
2373 "%s.__new__(): not enough arguments",
2374 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002375 return NULL;
2376 }
2377 arg0 = PyTuple_GET_ITEM(args, 0);
2378 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002379 PyErr_Format(PyExc_TypeError,
2380 "%s.__new__(X): X is not a type object (%s)",
2381 type->tp_name,
2382 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002383 return NULL;
2384 }
2385 subtype = (PyTypeObject *)arg0;
2386 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002387 PyErr_Format(PyExc_TypeError,
2388 "%s.__new__(%s): %s is not a subtype of %s",
2389 type->tp_name,
2390 subtype->tp_name,
2391 subtype->tp_name,
2392 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002393 return NULL;
2394 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002395
2396 /* Check that the use doesn't do something silly and unsafe like
2397 object.__new__(dictionary). To do this, we check that the
2398 most derived base that's not a heap type is this type. */
2399 staticbase = subtype;
2400 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2401 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002402 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002403 PyErr_Format(PyExc_TypeError,
2404 "%s.__new__(%s) is not safe, use %s.__new__()",
2405 type->tp_name,
2406 subtype->tp_name,
2407 staticbase == NULL ? "?" : staticbase->tp_name);
2408 return NULL;
2409 }
2410
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002411 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2412 if (args == NULL)
2413 return NULL;
2414 res = type->tp_new(subtype, args, kwds);
2415 Py_DECREF(args);
2416 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002417}
2418
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002419static struct PyMethodDef tp_new_methoddef[] = {
2420 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2421 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002422 {0}
2423};
2424
2425static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002426add_tp_new_wrapper(PyTypeObject *type)
2427{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002428 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002429
Guido van Rossumf040ede2001-08-07 16:40:56 +00002430 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2431 return 0;
2432 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002433 if (func == NULL)
2434 return -1;
2435 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2436}
2437
Guido van Rossum13d52f02001-08-10 21:24:08 +00002438static int
2439add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2440{
2441 PyObject *dict = type->tp_defined;
2442
2443 for (; wraps->name != NULL; wraps++) {
2444 PyObject *descr;
2445 if (PyDict_GetItemString(dict, wraps->name))
2446 continue;
2447 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2448 if (descr == NULL)
2449 return -1;
2450 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2451 return -1;
2452 Py_DECREF(descr);
2453 }
2454 return 0;
2455}
2456
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002457/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002458 dictionary with method descriptors for function slots. For each
2459 function slot (like tp_repr) that's defined in the type, one or
2460 more corresponding descriptors are added in the type's tp_defined
2461 dictionary under the appropriate name (like __repr__). Some
2462 function slots cause more than one descriptor to be added (for
2463 example, the nb_add slot adds both __add__ and __radd__
2464 descriptors) and some function slots compete for the same
2465 descriptor (for example both sq_item and mp_subscript generate a
2466 __getitem__ descriptor). This only adds new descriptors and
2467 doesn't overwrite entries in tp_defined that were previously
2468 defined. The descriptors contain a reference to the C function
2469 they must call, so that it's safe if they are copied into a
2470 subtype's __dict__ and the subtype has a different C function in
2471 its slot -- calling the method defined by the descriptor will call
2472 the C function that was used to create it, rather than the C
2473 function present in the slot when it is called. (This is important
2474 because a subtype may have a C function in the slot that calls the
2475 method from the dictionary, and we want to avoid infinite recursion
2476 here.) */
2477
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002478static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002479add_operators(PyTypeObject *type)
2480{
2481 PySequenceMethods *sq;
2482 PyMappingMethods *mp;
2483 PyNumberMethods *nb;
2484
2485#undef ADD
2486#define ADD(SLOT, TABLE) \
2487 if (SLOT) { \
2488 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2489 return -1; \
2490 }
2491
2492 if ((sq = type->tp_as_sequence) != NULL) {
2493 ADD(sq->sq_length, tab_len);
2494 ADD(sq->sq_concat, tab_concat);
2495 ADD(sq->sq_repeat, tab_mul_int);
2496 ADD(sq->sq_item, tab_getitem_int);
2497 ADD(sq->sq_slice, tab_getslice);
2498 ADD(sq->sq_ass_item, tab_setitem_int);
2499 ADD(sq->sq_ass_slice, tab_setslice);
2500 ADD(sq->sq_contains, tab_contains);
2501 ADD(sq->sq_inplace_concat, tab_iadd);
2502 ADD(sq->sq_inplace_repeat, tab_imul_int);
2503 }
2504
2505 if ((mp = type->tp_as_mapping) != NULL) {
2506 if (sq->sq_length == NULL)
2507 ADD(mp->mp_length, tab_len);
2508 ADD(mp->mp_subscript, tab_getitem);
2509 ADD(mp->mp_ass_subscript, tab_setitem);
2510 }
2511
2512 /* We don't support "old-style numbers" because their binary
2513 operators require that both arguments have the same type;
2514 the wrappers here only work for new-style numbers. */
2515 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2516 (nb = type->tp_as_number) != NULL) {
2517 ADD(nb->nb_add, tab_add);
2518 ADD(nb->nb_subtract, tab_sub);
2519 ADD(nb->nb_multiply, tab_mul);
2520 ADD(nb->nb_divide, tab_div);
2521 ADD(nb->nb_remainder, tab_mod);
2522 ADD(nb->nb_divmod, tab_divmod);
2523 ADD(nb->nb_power, tab_pow);
2524 ADD(nb->nb_negative, tab_neg);
2525 ADD(nb->nb_positive, tab_pos);
2526 ADD(nb->nb_absolute, tab_abs);
2527 ADD(nb->nb_nonzero, tab_nonzero);
2528 ADD(nb->nb_invert, tab_invert);
2529 ADD(nb->nb_lshift, tab_lshift);
2530 ADD(nb->nb_rshift, tab_rshift);
2531 ADD(nb->nb_and, tab_and);
2532 ADD(nb->nb_xor, tab_xor);
2533 ADD(nb->nb_or, tab_or);
2534 /* We don't support coerce() -- see above comment */
2535 ADD(nb->nb_int, tab_int);
2536 ADD(nb->nb_long, tab_long);
2537 ADD(nb->nb_float, tab_float);
2538 ADD(nb->nb_oct, tab_oct);
2539 ADD(nb->nb_hex, tab_hex);
2540 ADD(nb->nb_inplace_add, tab_iadd);
2541 ADD(nb->nb_inplace_subtract, tab_isub);
2542 ADD(nb->nb_inplace_multiply, tab_imul);
2543 ADD(nb->nb_inplace_divide, tab_idiv);
2544 ADD(nb->nb_inplace_remainder, tab_imod);
2545 ADD(nb->nb_inplace_power, tab_ipow);
2546 ADD(nb->nb_inplace_lshift, tab_ilshift);
2547 ADD(nb->nb_inplace_rshift, tab_irshift);
2548 ADD(nb->nb_inplace_and, tab_iand);
2549 ADD(nb->nb_inplace_xor, tab_ixor);
2550 ADD(nb->nb_inplace_or, tab_ior);
2551 }
2552
2553 ADD(type->tp_getattro, tab_getattr);
2554 ADD(type->tp_setattro, tab_setattr);
2555 ADD(type->tp_compare, tab_cmp);
2556 ADD(type->tp_repr, tab_repr);
2557 ADD(type->tp_hash, tab_hash);
2558 ADD(type->tp_call, tab_call);
2559 ADD(type->tp_str, tab_str);
2560 ADD(type->tp_richcompare, tab_richcmp);
2561 ADD(type->tp_iter, tab_iter);
2562 ADD(type->tp_iternext, tab_next);
2563 ADD(type->tp_descr_get, tab_descr_get);
2564 ADD(type->tp_descr_set, tab_descr_set);
2565 ADD(type->tp_init, tab_init);
2566
Guido van Rossumf040ede2001-08-07 16:40:56 +00002567 if (type->tp_new != NULL) {
2568 if (add_tp_new_wrapper(type) < 0)
2569 return -1;
2570 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002571
2572 return 0;
2573}
2574
Guido van Rossumf040ede2001-08-07 16:40:56 +00002575/* Slot wrappers that call the corresponding __foo__ slot. See comments
2576 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002577
Guido van Rossumdc91b992001-08-08 22:26:22 +00002578#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002579static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002580FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002581{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002582 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002583 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002584}
2585
Guido van Rossumdc91b992001-08-08 22:26:22 +00002586#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002587static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002588FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002590 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002591 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002592}
2593
Guido van Rossumdc91b992001-08-08 22:26:22 +00002594
2595#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002596static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002597FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002598{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002599 static PyObject *cache_str, *rcache_str; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002600 if (self->ob_type->tp_as_number != NULL && \
2601 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2602 PyObject *r; \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002603 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002604 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002605 if (r != Py_NotImplemented || \
2606 other->ob_type == self->ob_type) \
2607 return r; \
2608 Py_DECREF(r); \
2609 } \
2610 if (other->ob_type->tp_as_number != NULL && \
2611 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002612 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002613 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002614 } \
2615 Py_INCREF(Py_NotImplemented); \
2616 return Py_NotImplemented; \
2617}
2618
2619#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2620 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2621
2622#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2623static PyObject * \
2624FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2625{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002626 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002627 return call_method(self, OPSTR, &cache_str, \
2628 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002629}
2630
2631static int
2632slot_sq_length(PyObject *self)
2633{
Guido van Rossum2730b132001-08-28 18:22:14 +00002634 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002635 PyObject *res = call_method(self, "__len__", &len_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002636
2637 if (res == NULL)
2638 return -1;
2639 return (int)PyInt_AsLong(res);
2640}
2641
Guido van Rossumdc91b992001-08-08 22:26:22 +00002642SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2643SLOT1(slot_sq_repeat, "__mul__", int, "i")
2644SLOT1(slot_sq_item, "__getitem__", int, "i")
2645SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002646
2647static int
2648slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2649{
2650 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002651 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002652
2653 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002654 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002655 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002656 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002657 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002658 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002659 if (res == NULL)
2660 return -1;
2661 Py_DECREF(res);
2662 return 0;
2663}
2664
2665static int
2666slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2667{
2668 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002669 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002670
2671 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002672 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002673 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002674 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002675 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002676 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002677 if (res == NULL)
2678 return -1;
2679 Py_DECREF(res);
2680 return 0;
2681}
2682
2683static int
2684slot_sq_contains(PyObject *self, PyObject *value)
2685{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002686 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002687 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002688
Guido van Rossum60718732001-08-28 17:47:51 +00002689 func = lookup_method(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002690
2691 if (func != NULL) {
2692 args = Py_BuildValue("(O)", value);
2693 if (args == NULL)
2694 res = NULL;
2695 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002696 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002697 Py_DECREF(args);
2698 }
2699 Py_DECREF(func);
2700 if (res == NULL)
2701 return -1;
2702 return PyObject_IsTrue(res);
2703 }
2704 else {
2705 PyErr_Clear();
Tim Peters16a77ad2001-09-08 04:00:12 +00002706 return _PySequence_IterSearch(self, value,
2707 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002708 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002709}
2710
Guido van Rossumdc91b992001-08-08 22:26:22 +00002711SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2712SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002713
2714#define slot_mp_length slot_sq_length
2715
Guido van Rossumdc91b992001-08-08 22:26:22 +00002716SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717
2718static int
2719slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2720{
2721 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002722 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723
2724 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002725 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002726 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002727 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002728 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002729 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730 if (res == NULL)
2731 return -1;
2732 Py_DECREF(res);
2733 return 0;
2734}
2735
Guido van Rossumdc91b992001-08-08 22:26:22 +00002736SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2737SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2738SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2739SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2740SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2741SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2742
2743staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2744
2745SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2746 nb_power, "__pow__", "__rpow__")
2747
2748static PyObject *
2749slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2750{
Guido van Rossum2730b132001-08-28 18:22:14 +00002751 static PyObject *pow_str;
2752
Guido van Rossumdc91b992001-08-08 22:26:22 +00002753 if (modulus == Py_None)
2754 return slot_nb_power_binary(self, other);
2755 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002756 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002757 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002758}
2759
2760SLOT0(slot_nb_negative, "__neg__")
2761SLOT0(slot_nb_positive, "__pos__")
2762SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002763
2764static int
2765slot_nb_nonzero(PyObject *self)
2766{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002767 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002768 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769
Guido van Rossum60718732001-08-28 17:47:51 +00002770 func = lookup_method(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002771 if (func == NULL) {
2772 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002773 func = lookup_method(self, "__len__", &len_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002774 }
2775
2776 if (func != NULL) {
Guido van Rossum717ce002001-09-14 16:58:08 +00002777 res = PyObject_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002778 Py_DECREF(func);
2779 if (res == NULL)
2780 return -1;
2781 return PyObject_IsTrue(res);
2782 }
2783 else {
2784 PyErr_Clear();
2785 return 1;
2786 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002787}
2788
Guido van Rossumdc91b992001-08-08 22:26:22 +00002789SLOT0(slot_nb_invert, "__invert__")
2790SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2791SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2792SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2793SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2794SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002795/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002796SLOT0(slot_nb_int, "__int__")
2797SLOT0(slot_nb_long, "__long__")
2798SLOT0(slot_nb_float, "__float__")
2799SLOT0(slot_nb_oct, "__oct__")
2800SLOT0(slot_nb_hex, "__hex__")
2801SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2802SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2803SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2804SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2805SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2806SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2807SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2808SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2809SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2810SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2811SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2812SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2813 "__floordiv__", "__rfloordiv__")
2814SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2815SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2816SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817
2818static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002819half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002820{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002821 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002822 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002823 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002824
Guido van Rossum60718732001-08-28 17:47:51 +00002825 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002826 if (func == NULL) {
2827 PyErr_Clear();
2828 }
2829 else {
2830 args = Py_BuildValue("(O)", other);
2831 if (args == NULL)
2832 res = NULL;
2833 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002834 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002835 Py_DECREF(args);
2836 }
2837 if (res != Py_NotImplemented) {
2838 if (res == NULL)
2839 return -2;
2840 c = PyInt_AsLong(res);
2841 Py_DECREF(res);
2842 if (c == -1 && PyErr_Occurred())
2843 return -2;
2844 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2845 }
2846 Py_DECREF(res);
2847 }
2848 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002849}
2850
Guido van Rossumab3b0342001-09-18 20:38:53 +00002851/* This slot is published for the benefit of try_3way_compare in object.c */
2852int
2853_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00002854{
2855 int c;
2856
Guido van Rossumab3b0342001-09-18 20:38:53 +00002857 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002858 c = half_compare(self, other);
2859 if (c <= 1)
2860 return c;
2861 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00002862 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002863 c = half_compare(other, self);
2864 if (c < -1)
2865 return -2;
2866 if (c <= 1)
2867 return -c;
2868 }
2869 return (void *)self < (void *)other ? -1 :
2870 (void *)self > (void *)other ? 1 : 0;
2871}
2872
2873static PyObject *
2874slot_tp_repr(PyObject *self)
2875{
2876 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002877 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002878
Guido van Rossum60718732001-08-28 17:47:51 +00002879 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002880 if (func != NULL) {
2881 res = PyEval_CallObject(func, NULL);
2882 Py_DECREF(func);
2883 return res;
2884 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00002885 PyErr_Clear();
2886 return PyString_FromFormat("<%s object at %p>",
2887 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002888}
2889
2890static PyObject *
2891slot_tp_str(PyObject *self)
2892{
2893 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002894 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002895
Guido van Rossum60718732001-08-28 17:47:51 +00002896 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002897 if (func != NULL) {
2898 res = PyEval_CallObject(func, NULL);
2899 Py_DECREF(func);
2900 return res;
2901 }
2902 else {
2903 PyErr_Clear();
2904 return slot_tp_repr(self);
2905 }
2906}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002907
2908static long
2909slot_tp_hash(PyObject *self)
2910{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002911 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002912 static PyObject *hash_str, *eq_str, *cmp_str;
2913
Tim Peters6d6c1a32001-08-02 04:15:00 +00002914 long h;
2915
Guido van Rossum60718732001-08-28 17:47:51 +00002916 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002917
2918 if (func != NULL) {
2919 res = PyEval_CallObject(func, NULL);
2920 Py_DECREF(func);
2921 if (res == NULL)
2922 return -1;
2923 h = PyInt_AsLong(res);
2924 }
2925 else {
2926 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002927 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002928 if (func == NULL) {
2929 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002930 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002931 }
2932 if (func != NULL) {
2933 Py_DECREF(func);
2934 PyErr_SetString(PyExc_TypeError, "unhashable type");
2935 return -1;
2936 }
2937 PyErr_Clear();
2938 h = _Py_HashPointer((void *)self);
2939 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002940 if (h == -1 && !PyErr_Occurred())
2941 h = -2;
2942 return h;
2943}
2944
2945static PyObject *
2946slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2947{
Guido van Rossum60718732001-08-28 17:47:51 +00002948 static PyObject *call_str;
2949 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002950 PyObject *res;
2951
2952 if (meth == NULL)
2953 return NULL;
2954 res = PyObject_Call(meth, args, kwds);
2955 Py_DECREF(meth);
2956 return res;
2957}
2958
Tim Peters6d6c1a32001-08-02 04:15:00 +00002959static PyObject *
2960slot_tp_getattro(PyObject *self, PyObject *name)
2961{
2962 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002963 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002964 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002965
Guido van Rossum8e248182001-08-12 05:17:56 +00002966 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002967 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00002968 if (getattr_str == NULL)
2969 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970 }
Guido van Rossum8e248182001-08-12 05:17:56 +00002971 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00002972 if (getattr == NULL) {
2973 /* Avoid further slowdowns */
2974 if (tp->tp_getattro == slot_tp_getattro)
2975 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002976 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00002977 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002978 return PyObject_CallFunction(getattr, "OO", self, name);
2979}
2980
Guido van Rossum19c1cd52001-09-21 21:24:49 +00002981static PyObject *
2982slot_tp_getattr_hook(PyObject *self, PyObject *name)
2983{
2984 PyTypeObject *tp = self->ob_type;
2985 PyObject *getattr, *getattribute, *res;
2986 static PyObject *getattribute_str = NULL;
2987 static PyObject *getattr_str = NULL;
2988
2989 if (getattr_str == NULL) {
2990 getattr_str = PyString_InternFromString("__getattr__");
2991 if (getattr_str == NULL)
2992 return NULL;
2993 }
2994 if (getattribute_str == NULL) {
2995 getattribute_str =
2996 PyString_InternFromString("__getattribute__");
2997 if (getattribute_str == NULL)
2998 return NULL;
2999 }
3000 getattr = _PyType_Lookup(tp, getattr_str);
3001 getattribute = _PyType_Lookup(tp, getattribute_str);
3002 if (getattr == NULL && getattribute == NULL) {
3003 /* Avoid further slowdowns */
3004 if (tp->tp_getattro == slot_tp_getattr_hook)
3005 tp->tp_getattro = PyObject_GenericGetAttr;
3006 return PyObject_GenericGetAttr(self, name);
3007 }
3008 if (getattribute == NULL)
3009 res = PyObject_GenericGetAttr(self, name);
3010 else
3011 res = PyObject_CallFunction(getattribute, "OO", self, name);
3012 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
3013 PyErr_Clear();
3014 res = PyObject_CallFunction(getattr, "OO", self, name);
3015 }
3016 return res;
3017}
3018
Tim Peters6d6c1a32001-08-02 04:15:00 +00003019static int
3020slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3021{
3022 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003023 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003024
3025 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003026 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003027 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003028 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003029 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003030 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003031 if (res == NULL)
3032 return -1;
3033 Py_DECREF(res);
3034 return 0;
3035}
3036
3037/* Map rich comparison operators to their __xx__ namesakes */
3038static char *name_op[] = {
3039 "__lt__",
3040 "__le__",
3041 "__eq__",
3042 "__ne__",
3043 "__gt__",
3044 "__ge__",
3045};
3046
3047static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003048half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003049{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003050 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003051 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003052
Guido van Rossum60718732001-08-28 17:47:51 +00003053 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003054 if (func == NULL) {
3055 PyErr_Clear();
3056 Py_INCREF(Py_NotImplemented);
3057 return Py_NotImplemented;
3058 }
3059 args = Py_BuildValue("(O)", other);
3060 if (args == NULL)
3061 res = NULL;
3062 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003063 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003064 Py_DECREF(args);
3065 }
3066 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067 return res;
3068}
3069
Guido van Rossumb8f63662001-08-15 23:57:02 +00003070/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3071static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3072
3073static PyObject *
3074slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3075{
3076 PyObject *res;
3077
3078 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3079 res = half_richcompare(self, other, op);
3080 if (res != Py_NotImplemented)
3081 return res;
3082 Py_DECREF(res);
3083 }
3084 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3085 res = half_richcompare(other, self, swapped_op[op]);
3086 if (res != Py_NotImplemented) {
3087 return res;
3088 }
3089 Py_DECREF(res);
3090 }
3091 Py_INCREF(Py_NotImplemented);
3092 return Py_NotImplemented;
3093}
3094
3095static PyObject *
3096slot_tp_iter(PyObject *self)
3097{
3098 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003099 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003100
Guido van Rossum60718732001-08-28 17:47:51 +00003101 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003102 if (func != NULL) {
3103 res = PyObject_CallObject(func, NULL);
3104 Py_DECREF(func);
3105 return res;
3106 }
3107 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003108 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003109 if (func == NULL) {
3110 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
3111 return NULL;
3112 }
3113 Py_DECREF(func);
3114 return PySeqIter_New(self);
3115}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116
3117static PyObject *
3118slot_tp_iternext(PyObject *self)
3119{
Guido van Rossum2730b132001-08-28 18:22:14 +00003120 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003121 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003122}
3123
Guido van Rossum1a493502001-08-17 16:47:50 +00003124static PyObject *
3125slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3126{
3127 PyTypeObject *tp = self->ob_type;
3128 PyObject *get;
3129 static PyObject *get_str = NULL;
3130
3131 if (get_str == NULL) {
3132 get_str = PyString_InternFromString("__get__");
3133 if (get_str == NULL)
3134 return NULL;
3135 }
3136 get = _PyType_Lookup(tp, get_str);
3137 if (get == NULL) {
3138 /* Avoid further slowdowns */
3139 if (tp->tp_descr_get == slot_tp_descr_get)
3140 tp->tp_descr_get = NULL;
3141 Py_INCREF(self);
3142 return self;
3143 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003144 if (obj == NULL)
3145 obj = Py_None;
3146 if (type == NULL)
3147 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003148 return PyObject_CallFunction(get, "OOO", self, obj, type);
3149}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003150
3151static int
3152slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3153{
Guido van Rossum2c252392001-08-24 10:13:31 +00003154 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003155 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003156
3157 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003158 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003159 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003160 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003161 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003162 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003163 if (res == NULL)
3164 return -1;
3165 Py_DECREF(res);
3166 return 0;
3167}
3168
3169static int
3170slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3171{
Guido van Rossum60718732001-08-28 17:47:51 +00003172 static PyObject *init_str;
3173 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003174 PyObject *res;
3175
3176 if (meth == NULL)
3177 return -1;
3178 res = PyObject_Call(meth, args, kwds);
3179 Py_DECREF(meth);
3180 if (res == NULL)
3181 return -1;
3182 Py_DECREF(res);
3183 return 0;
3184}
3185
3186static PyObject *
3187slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3188{
3189 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3190 PyObject *newargs, *x;
3191 int i, n;
3192
3193 if (func == NULL)
3194 return NULL;
3195 assert(PyTuple_Check(args));
3196 n = PyTuple_GET_SIZE(args);
3197 newargs = PyTuple_New(n+1);
3198 if (newargs == NULL)
3199 return NULL;
3200 Py_INCREF(type);
3201 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3202 for (i = 0; i < n; i++) {
3203 x = PyTuple_GET_ITEM(args, i);
3204 Py_INCREF(x);
3205 PyTuple_SET_ITEM(newargs, i+1, x);
3206 }
3207 x = PyObject_Call(func, newargs, kwds);
3208 Py_DECREF(func);
3209 return x;
3210}
3211
Guido van Rossumf040ede2001-08-07 16:40:56 +00003212/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003213 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003214 The dict argument is the dictionary argument passed to type_new(),
3215 which is the local namespace of the class statement, in other
3216 words, it contains the methods. For each special method (like
3217 __repr__) defined in the dictionary, the corresponding function
3218 slot in the type object (like tp_repr) is set to a special function
3219 whose name is 'slot_' followed by the slot name and whose signature
3220 is whatever is required for that slot. These slot functions look
3221 up the corresponding method in the type's dictionary and call it.
3222 The slot functions have to take care of the various peculiarities
3223 of the mapping between slots and special methods, such as mapping
3224 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3225 etc.) or mapping multiple slots to a single method (sq_item,
3226 mp_subscript <--> __getitem__). */
3227
Tim Peters6d6c1a32001-08-02 04:15:00 +00003228static void
3229override_slots(PyTypeObject *type, PyObject *dict)
3230{
3231 PySequenceMethods *sq = type->tp_as_sequence;
3232 PyMappingMethods *mp = type->tp_as_mapping;
3233 PyNumberMethods *nb = type->tp_as_number;
3234
Guido van Rossumdc91b992001-08-08 22:26:22 +00003235#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003236 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003237 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003238 }
3239
Guido van Rossumdc91b992001-08-08 22:26:22 +00003240#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003241 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003242 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003243 }
3244
Guido van Rossumdc91b992001-08-08 22:26:22 +00003245#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003246 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003247 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003248 }
3249
Guido van Rossumdc91b992001-08-08 22:26:22 +00003250#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003251 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003252 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003253 }
3254
Guido van Rossumdc91b992001-08-08 22:26:22 +00003255 SQSLOT("__len__", sq_length, slot_sq_length);
3256 SQSLOT("__add__", sq_concat, slot_sq_concat);
3257 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3258 SQSLOT("__getitem__", sq_item, slot_sq_item);
3259 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3260 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3261 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3262 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3263 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3264 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3265 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3266 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003267
Guido van Rossumdc91b992001-08-08 22:26:22 +00003268 MPSLOT("__len__", mp_length, slot_mp_length);
3269 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3270 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3271 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003272
Guido van Rossumdc91b992001-08-08 22:26:22 +00003273 NBSLOT("__add__", nb_add, slot_nb_add);
3274 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3275 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3276 NBSLOT("__div__", nb_divide, slot_nb_divide);
3277 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3278 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3279 NBSLOT("__pow__", nb_power, slot_nb_power);
3280 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3281 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3282 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3283 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3284 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3285 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3286 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3287 NBSLOT("__and__", nb_and, slot_nb_and);
3288 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3289 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003290 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00003291 NBSLOT("__int__", nb_int, slot_nb_int);
3292 NBSLOT("__long__", nb_long, slot_nb_long);
3293 NBSLOT("__float__", nb_float, slot_nb_float);
3294 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3295 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3296 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3297 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3298 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3299 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3300 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3301 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3302 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3303 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3304 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3305 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3306 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3307 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3308 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3309 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3310 slot_nb_inplace_floor_divide);
3311 NBSLOT("__itruediv__", nb_inplace_true_divide,
3312 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003313
Guido van Rossum8e248182001-08-12 05:17:56 +00003314 if (dict == NULL ||
3315 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003316 PyDict_GetItemString(dict, "__repr__"))
3317 type->tp_print = NULL;
3318
Guido van Rossumab3b0342001-09-18 20:38:53 +00003319 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003320 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3321 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3322 TPSLOT("__call__", tp_call, slot_tp_call);
3323 TPSLOT("__str__", tp_str, slot_tp_str);
Guido van Rossum867a8d22001-09-21 19:29:08 +00003324 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003325 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003326 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3327 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3328 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3329 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3330 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3331 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3332 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3333 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3334 TPSLOT("next", tp_iternext, slot_tp_iternext);
3335 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3336 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3337 TPSLOT("__init__", tp_init, slot_tp_init);
3338 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003339}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003340
3341
3342/* Cooperative 'super' */
3343
3344typedef struct {
3345 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003346 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003347 PyObject *obj;
3348} superobject;
3349
Guido van Rossum6f799372001-09-20 20:46:19 +00003350static PyMemberDef super_members[] = {
3351 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3352 "the class invoking super()"},
3353 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3354 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003355 {0}
3356};
3357
Guido van Rossum705f0f52001-08-24 16:47:00 +00003358static void
3359super_dealloc(PyObject *self)
3360{
3361 superobject *su = (superobject *)self;
3362
3363 Py_XDECREF(su->obj);
3364 Py_XDECREF(su->type);
3365 self->ob_type->tp_free(self);
3366}
3367
3368static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003369super_repr(PyObject *self)
3370{
3371 superobject *su = (superobject *)self;
3372
3373 if (su->obj)
3374 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003375 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003376 su->type ? su->type->tp_name : "NULL",
3377 su->obj->ob_type->tp_name);
3378 else
3379 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003380 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003381 su->type ? su->type->tp_name : "NULL");
3382}
3383
3384static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003385super_getattro(PyObject *self, PyObject *name)
3386{
3387 superobject *su = (superobject *)self;
3388
3389 if (su->obj != NULL) {
3390 PyObject *mro, *res, *tmp;
3391 descrgetfunc f;
3392 int i, n;
3393
Guido van Rossume705ef12001-08-29 15:47:06 +00003394 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003395 if (mro == NULL)
3396 n = 0;
3397 else {
3398 assert(PyTuple_Check(mro));
3399 n = PyTuple_GET_SIZE(mro);
3400 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003401 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003402 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003403 break;
3404 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003405 if (i >= n && PyType_Check(su->obj)) {
3406 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003407 if (mro == NULL)
3408 n = 0;
3409 else {
3410 assert(PyTuple_Check(mro));
3411 n = PyTuple_GET_SIZE(mro);
3412 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003413 for (i = 0; i < n; i++) {
3414 if ((PyObject *)(su->type) ==
3415 PyTuple_GET_ITEM(mro, i))
3416 break;
3417 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003418 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003419 i++;
3420 res = NULL;
3421 for (; i < n; i++) {
3422 tmp = PyTuple_GET_ITEM(mro, i);
3423 assert(PyType_Check(tmp));
3424 res = PyDict_GetItem(
3425 ((PyTypeObject *)tmp)->tp_defined, name);
3426 if (res != NULL) {
3427 Py_INCREF(res);
3428 f = res->ob_type->tp_descr_get;
3429 if (f != NULL) {
3430 tmp = f(res, su->obj, res);
3431 Py_DECREF(res);
3432 res = tmp;
3433 }
3434 return res;
3435 }
3436 }
3437 }
3438 return PyObject_GenericGetAttr(self, name);
3439}
3440
3441static PyObject *
3442super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3443{
3444 superobject *su = (superobject *)self;
3445 superobject *new;
3446
3447 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3448 /* Not binding to an object, or already bound */
3449 Py_INCREF(self);
3450 return self;
3451 }
3452 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3453 if (new == NULL)
3454 return NULL;
3455 Py_INCREF(su->type);
3456 Py_INCREF(obj);
3457 new->type = su->type;
3458 new->obj = obj;
3459 return (PyObject *)new;
3460}
3461
3462static int
3463super_init(PyObject *self, PyObject *args, PyObject *kwds)
3464{
3465 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003466 PyTypeObject *type;
3467 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003468
3469 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3470 return -1;
3471 if (obj == Py_None)
3472 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003473 if (obj != NULL &&
3474 !PyType_IsSubtype(obj->ob_type, type) &&
3475 !(PyType_Check(obj) &&
3476 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003477 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003478 "super(type, obj): "
3479 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003480 return -1;
3481 }
3482 Py_INCREF(type);
3483 Py_XINCREF(obj);
3484 su->type = type;
3485 su->obj = obj;
3486 return 0;
3487}
3488
3489static char super_doc[] =
3490"super(type) -> unbound super object\n"
3491"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003492"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003493"Typical use to call a cooperative superclass method:\n"
3494"class C(B):\n"
3495" def meth(self, arg):\n"
3496" super(C, self).meth(arg)";
3497
3498PyTypeObject PySuper_Type = {
3499 PyObject_HEAD_INIT(&PyType_Type)
3500 0, /* ob_size */
3501 "super", /* tp_name */
3502 sizeof(superobject), /* tp_basicsize */
3503 0, /* tp_itemsize */
3504 /* methods */
3505 super_dealloc, /* tp_dealloc */
3506 0, /* tp_print */
3507 0, /* tp_getattr */
3508 0, /* tp_setattr */
3509 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003510 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003511 0, /* tp_as_number */
3512 0, /* tp_as_sequence */
3513 0, /* tp_as_mapping */
3514 0, /* tp_hash */
3515 0, /* tp_call */
3516 0, /* tp_str */
3517 super_getattro, /* tp_getattro */
3518 0, /* tp_setattro */
3519 0, /* tp_as_buffer */
Guido van Rossum31bcff82001-08-30 04:37:15 +00003520 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003521 super_doc, /* tp_doc */
3522 0, /* tp_traverse */
3523 0, /* tp_clear */
3524 0, /* tp_richcompare */
3525 0, /* tp_weaklistoffset */
3526 0, /* tp_iter */
3527 0, /* tp_iternext */
3528 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003529 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003530 0, /* tp_getset */
3531 0, /* tp_base */
3532 0, /* tp_dict */
3533 super_descr_get, /* tp_descr_get */
3534 0, /* tp_descr_set */
3535 0, /* tp_dictoffset */
3536 super_init, /* tp_init */
3537 PyType_GenericAlloc, /* tp_alloc */
3538 PyType_GenericNew, /* tp_new */
3539 _PyObject_Del, /* tp_free */
3540};