blob: 295be89c382aa981239bb19d93c05d735afb7307 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Type object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum6f799372001-09-20 20:46:19 +00007static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00008 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
9 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
10 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
11 {"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
17 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
18 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
25 char *s;
26
27 s = strrchr(type->tp_name, '.');
28 if (s == NULL)
29 s = type->tp_name;
30 else
31 s++;
32 return PyString_FromString(s);
33}
34
35static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000036type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000037{
Guido van Rossumc3542212001-08-16 09:18:56 +000038 PyObject *mod;
39 char *s;
40
41 s = strrchr(type->tp_name, '.');
42 if (s != NULL)
43 return PyString_FromStringAndSize(type->tp_name,
44 (int)(s - type->tp_name));
45 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
46 return PyString_FromString("__builtin__");
47 mod = PyDict_GetItemString(type->tp_defined, "__module__");
48 if (mod != NULL && PyString_Check(mod)) {
49 Py_INCREF(mod);
50 return mod;
51 }
52 PyErr_SetString(PyExc_AttributeError, "__module__");
53 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000054}
55
Guido van Rossum3926a632001-09-25 16:25:58 +000056static int
57type_set_module(PyTypeObject *type, PyObject *value, void *context)
58{
59 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ||
60 strrchr(type->tp_name, '.')) {
61 PyErr_Format(PyExc_TypeError,
62 "can't set %s.__module__", type->tp_name);
63 return -1;
64 }
65 if (!value) {
66 PyErr_Format(PyExc_TypeError,
67 "can't delete %s.__module__", type->tp_name);
68 return -1;
69 }
70 return PyDict_SetItemString(type->tp_dict, "__module__", value);
71}
72
Tim Peters6d6c1a32001-08-02 04:15:00 +000073static PyObject *
74type_dict(PyTypeObject *type, void *context)
75{
76 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077 Py_INCREF(Py_None);
78 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000079 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000080 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
81 Py_INCREF(type->tp_dict);
82 return type->tp_dict;
83 }
84 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000085}
86
Tim Peters6d6c1a32001-08-02 04:15:00 +000087static PyObject *
88type_defined(PyTypeObject *type, void *context)
89{
90 if (type->tp_defined == NULL) {
91 Py_INCREF(Py_None);
92 return Py_None;
93 }
94 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
95 Py_INCREF(type->tp_defined);
96 return type->tp_defined;
97 }
98 return PyDictProxy_New(type->tp_defined);
99}
100
101static PyObject *
102type_dynamic(PyTypeObject *type, void *context)
103{
104 PyObject *res;
105
106 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
107 Py_INCREF(res);
108 return res;
109}
110
Guido van Rossum32d34c82001-09-20 21:45:26 +0000111PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000112 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000113 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000114 {"__dict__", (getter)type_dict, NULL, NULL},
115 {"__defined__", (getter)type_defined, NULL, NULL},
116 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
117 {0}
118};
119
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000120static int
121type_compare(PyObject *v, PyObject *w)
122{
123 /* This is called with type objects only. So we
124 can just compare the addresses. */
125 Py_uintptr_t vv = (Py_uintptr_t)v;
126 Py_uintptr_t ww = (Py_uintptr_t)w;
127 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
128}
129
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000131type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000133 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000134 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000135
136 mod = type_module(type, NULL);
137 if (mod == NULL)
138 PyErr_Clear();
139 else if (!PyString_Check(mod)) {
140 Py_DECREF(mod);
141 mod = NULL;
142 }
143 name = type_name(type, NULL);
144 if (name == NULL)
145 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000146
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000147 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
148 kind = "class";
149 else
150 kind = "type";
151
Barry Warsaw7ce36942001-08-24 18:34:26 +0000152 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000153 rtn = PyString_FromFormat("<%s '%s.%s'>",
154 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000155 PyString_AS_STRING(mod),
156 PyString_AS_STRING(name));
157 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000158 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000159 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000160
Guido van Rossumc3542212001-08-16 09:18:56 +0000161 Py_XDECREF(mod);
162 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000163 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
Tim Peters6d6c1a32001-08-02 04:15:00 +0000166static PyObject *
167type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
168{
169 PyObject *obj;
170
171 if (type->tp_new == NULL) {
172 PyErr_Format(PyExc_TypeError,
173 "cannot create '%.100s' instances",
174 type->tp_name);
175 return NULL;
176 }
177
Tim Peters3f996e72001-09-13 19:18:27 +0000178 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 if (obj != NULL) {
180 type = obj->ob_type;
181 if (type->tp_init != NULL &&
182 type->tp_init(obj, args, kwds) < 0) {
183 Py_DECREF(obj);
184 obj = NULL;
185 }
186 }
187 return obj;
188}
189
190PyObject *
191PyType_GenericAlloc(PyTypeObject *type, int nitems)
192{
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000193#define PTRSIZE (sizeof(PyObject *))
194
Tim Peters6d6c1a32001-08-02 04:15:00 +0000195 int size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000196 PyObject *obj;
197
198 /* Inline PyObject_New() so we can zero the memory */
199 size = _PyObject_VAR_SIZE(type, nitems);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000200 /* Round up size, if necessary, so we fully zero out __dict__ */
201 if (type->tp_itemsize % PTRSIZE != 0) {
202 size += PTRSIZE - 1;
203 size /= PTRSIZE;
204 size *= PTRSIZE;
205 }
Neil Schemenauerc806c882001-08-29 23:54:54 +0000206 if (PyType_IS_GC(type)) {
207 obj = _PyObject_GC_Malloc(type, nitems);
208 }
209 else {
210 obj = PyObject_MALLOC(size);
211 }
212 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000213 return PyErr_NoMemory();
Neil Schemenauerc806c882001-08-29 23:54:54 +0000214 memset(obj, '\0', size);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000215 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
216 Py_INCREF(type);
217 if (type->tp_itemsize == 0)
218 PyObject_INIT(obj, type);
219 else
220 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
221 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000222 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000223 return obj;
224}
225
226PyObject *
227PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
228{
229 return type->tp_alloc(type, 0);
230}
231
232/* Helper for subtyping */
233
234static void
235subtype_dealloc(PyObject *self)
236{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000237 PyTypeObject *type, *base;
238 destructor f;
239
240 /* This exists so we can DECREF self->ob_type */
241
242 /* Find the nearest base with a different tp_dealloc */
243 type = self->ob_type;
244 base = type->tp_base;
245 while ((f = base->tp_dealloc) == subtype_dealloc) {
246 base = base->tp_base;
247 assert(base);
248 }
249
250 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000251 if (type->tp_dictoffset && !base->tp_dictoffset) {
252 PyObject **dictptr = _PyObject_GetDictPtr(self);
253 if (dictptr != NULL) {
254 PyObject *dict = *dictptr;
255 if (dict != NULL) {
256 Py_DECREF(dict);
257 *dictptr = NULL;
258 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000259 }
260 }
261
Guido van Rossum9676b222001-08-17 20:32:36 +0000262 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000263 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000264 PyObject_ClearWeakRefs(self);
265
Tim Peters6d6c1a32001-08-02 04:15:00 +0000266 /* Finalize GC if the base doesn't do GC and we do */
267 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000268 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000269
270 /* Call the base tp_dealloc() */
271 assert(f);
272 f(self);
273
274 /* Can't reference self beyond this point */
275 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
276 Py_DECREF(type);
277 }
278}
279
280staticforward void override_slots(PyTypeObject *type, PyObject *dict);
281staticforward PyTypeObject *solid_base(PyTypeObject *type);
282
283typedef struct {
284 PyTypeObject type;
285 PyNumberMethods as_number;
286 PySequenceMethods as_sequence;
287 PyMappingMethods as_mapping;
288 PyBufferProcs as_buffer;
289 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000290 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000291} etype;
292
293/* type test with subclassing support */
294
295int
296PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
297{
298 PyObject *mro;
299
Guido van Rossum9478d072001-09-07 18:52:13 +0000300 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
301 return b == a || b == &PyBaseObject_Type;
302
Tim Peters6d6c1a32001-08-02 04:15:00 +0000303 mro = a->tp_mro;
304 if (mro != NULL) {
305 /* Deal with multiple inheritance without recursion
306 by walking the MRO tuple */
307 int i, n;
308 assert(PyTuple_Check(mro));
309 n = PyTuple_GET_SIZE(mro);
310 for (i = 0; i < n; i++) {
311 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
312 return 1;
313 }
314 return 0;
315 }
316 else {
317 /* a is not completely initilized yet; follow tp_base */
318 do {
319 if (a == b)
320 return 1;
321 a = a->tp_base;
322 } while (a != NULL);
323 return b == &PyBaseObject_Type;
324 }
325}
326
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000327/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000328 without looking in the instance dictionary
329 (so we can't use PyObject_GetAttr) but still binding
330 it to the instance. The arguments are the object,
331 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000332 static variable used to cache the interned Python string.
333
334 Two variants:
335
336 - lookup_maybe() returns NULL without raising an exception
337 when the _PyType_Lookup() call fails;
338
339 - lookup_method() always raises an exception upon errors.
340*/
Guido van Rossum60718732001-08-28 17:47:51 +0000341
342static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000343lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000344{
345 PyObject *res;
346
347 if (*attrobj == NULL) {
348 *attrobj = PyString_InternFromString(attrstr);
349 if (*attrobj == NULL)
350 return NULL;
351 }
352 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000353 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000354 descrgetfunc f;
355 if ((f = res->ob_type->tp_descr_get) == NULL)
356 Py_INCREF(res);
357 else
358 res = f(res, self, (PyObject *)(self->ob_type));
359 }
360 return res;
361}
362
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000363static PyObject *
364lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
365{
366 PyObject *res = lookup_maybe(self, attrstr, attrobj);
367 if (res == NULL && !PyErr_Occurred())
368 PyErr_SetObject(PyExc_AttributeError, *attrobj);
369 return res;
370}
371
Guido van Rossum2730b132001-08-28 18:22:14 +0000372/* A variation of PyObject_CallMethod that uses lookup_method()
373 instead of PyObject_GetAttrString(). This uses the same convention
374 as lookup_method to cache the interned name string object. */
375
376PyObject *
377call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
378{
379 va_list va;
380 PyObject *args, *func = 0, *retval;
381 PyObject *dummy_str = NULL;
382 va_start(va, format);
383
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000384 func = lookup_maybe(o, name, &dummy_str);
385 if (func == NULL) {
386 va_end(va);
387 if (!PyErr_Occurred())
388 PyErr_SetObject(PyExc_AttributeError, dummy_str);
389 Py_XDECREF(dummy_str);
390 return NULL;
391 }
392 Py_DECREF(dummy_str);
393
394 if (format && *format)
395 args = Py_VaBuildValue(format, va);
396 else
397 args = PyTuple_New(0);
398
399 va_end(va);
400
401 if (args == NULL)
402 return NULL;
403
404 assert(PyTuple_Check(args));
405 retval = PyObject_Call(func, args, NULL);
406
407 Py_DECREF(args);
408 Py_DECREF(func);
409
410 return retval;
411}
412
413/* Clone of call_method() that returns NotImplemented when the lookup fails. */
414
415PyObject *
416call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
417{
418 va_list va;
419 PyObject *args, *func = 0, *retval;
420 PyObject *dummy_str = NULL;
421 va_start(va, format);
422
423 func = lookup_maybe(o, name, &dummy_str);
Guido van Rossum2730b132001-08-28 18:22:14 +0000424 Py_XDECREF(dummy_str);
425 if (func == NULL) {
426 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000427 if (!PyErr_Occurred()) {
428 Py_INCREF(Py_NotImplemented);
429 return Py_NotImplemented;
430 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000431 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000432 }
433
434 if (format && *format)
435 args = Py_VaBuildValue(format, va);
436 else
437 args = PyTuple_New(0);
438
439 va_end(va);
440
Guido van Rossum717ce002001-09-14 16:58:08 +0000441 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000442 return NULL;
443
Guido van Rossum717ce002001-09-14 16:58:08 +0000444 assert(PyTuple_Check(args));
445 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000446
447 Py_DECREF(args);
448 Py_DECREF(func);
449
450 return retval;
451}
452
Tim Peters6d6c1a32001-08-02 04:15:00 +0000453/* Method resolution order algorithm from "Putting Metaclasses to Work"
454 by Forman and Danforth (Addison-Wesley 1999). */
455
456static int
457conservative_merge(PyObject *left, PyObject *right)
458{
459 int left_size;
460 int right_size;
461 int i, j, r, ok;
462 PyObject *temp, *rr;
463
464 assert(PyList_Check(left));
465 assert(PyList_Check(right));
466
467 again:
468 left_size = PyList_GET_SIZE(left);
469 right_size = PyList_GET_SIZE(right);
470 for (i = 0; i < left_size; i++) {
471 for (j = 0; j < right_size; j++) {
472 if (PyList_GET_ITEM(left, i) ==
473 PyList_GET_ITEM(right, j)) {
474 /* found a merge point */
475 temp = PyList_New(0);
476 if (temp == NULL)
477 return -1;
478 for (r = 0; r < j; r++) {
479 rr = PyList_GET_ITEM(right, r);
480 ok = PySequence_Contains(left, rr);
481 if (ok < 0) {
482 Py_DECREF(temp);
483 return -1;
484 }
485 if (!ok) {
486 ok = PyList_Append(temp, rr);
487 if (ok < 0) {
488 Py_DECREF(temp);
489 return -1;
490 }
491 }
492 }
493 ok = PyList_SetSlice(left, i, i, temp);
494 Py_DECREF(temp);
495 if (ok < 0)
496 return -1;
497 ok = PyList_SetSlice(right, 0, j+1, NULL);
498 if (ok < 0)
499 return -1;
500 goto again;
501 }
502 }
503 }
504 return PyList_SetSlice(left, left_size, left_size, right);
505}
506
507static int
508serious_order_disagreements(PyObject *left, PyObject *right)
509{
510 return 0; /* XXX later -- for now, we cheat: "don't do that" */
511}
512
513static PyObject *
514mro_implementation(PyTypeObject *type)
515{
516 int i, n, ok;
517 PyObject *bases, *result;
518
519 bases = type->tp_bases;
520 n = PyTuple_GET_SIZE(bases);
521 result = Py_BuildValue("[O]", (PyObject *)type);
522 if (result == NULL)
523 return NULL;
524 for (i = 0; i < n; i++) {
525 PyTypeObject *base =
526 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
527 PyObject *parentMRO = PySequence_List(base->tp_mro);
528 if (parentMRO == NULL) {
529 Py_DECREF(result);
530 return NULL;
531 }
532 if (serious_order_disagreements(result, parentMRO)) {
533 Py_DECREF(result);
534 return NULL;
535 }
536 ok = conservative_merge(result, parentMRO);
537 Py_DECREF(parentMRO);
538 if (ok < 0) {
539 Py_DECREF(result);
540 return NULL;
541 }
542 }
543 return result;
544}
545
546static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000547mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000548{
549 PyTypeObject *type = (PyTypeObject *)self;
550
Tim Peters6d6c1a32001-08-02 04:15:00 +0000551 return mro_implementation(type);
552}
553
554static int
555mro_internal(PyTypeObject *type)
556{
557 PyObject *mro, *result, *tuple;
558
559 if (type->ob_type == &PyType_Type) {
560 result = mro_implementation(type);
561 }
562 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000563 static PyObject *mro_str;
564 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000565 if (mro == NULL)
566 return -1;
567 result = PyObject_CallObject(mro, NULL);
568 Py_DECREF(mro);
569 }
570 if (result == NULL)
571 return -1;
572 tuple = PySequence_Tuple(result);
573 Py_DECREF(result);
574 type->tp_mro = tuple;
575 return 0;
576}
577
578
579/* Calculate the best base amongst multiple base classes.
580 This is the first one that's on the path to the "solid base". */
581
582static PyTypeObject *
583best_base(PyObject *bases)
584{
585 int i, n;
586 PyTypeObject *base, *winner, *candidate, *base_i;
587
588 assert(PyTuple_Check(bases));
589 n = PyTuple_GET_SIZE(bases);
590 assert(n > 0);
591 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
592 winner = &PyBaseObject_Type;
593 for (i = 0; i < n; i++) {
594 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
595 if (!PyType_Check((PyObject *)base_i)) {
596 PyErr_SetString(
597 PyExc_TypeError,
598 "bases must be types");
599 return NULL;
600 }
601 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000602 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000603 return NULL;
604 }
605 candidate = solid_base(base_i);
606 if (PyType_IsSubtype(winner, candidate))
607 ;
608 else if (PyType_IsSubtype(candidate, winner)) {
609 winner = candidate;
610 base = base_i;
611 }
612 else {
613 PyErr_SetString(
614 PyExc_TypeError,
615 "multiple bases have "
616 "instance lay-out conflict");
617 return NULL;
618 }
619 }
620 assert(base != NULL);
621 return base;
622}
623
624static int
625extra_ivars(PyTypeObject *type, PyTypeObject *base)
626{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000627 size_t t_size = type->tp_basicsize;
628 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000629
Guido van Rossum9676b222001-08-17 20:32:36 +0000630 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000631 if (type->tp_itemsize || base->tp_itemsize) {
632 /* If itemsize is involved, stricter rules */
633 return t_size != b_size ||
634 type->tp_itemsize != base->tp_itemsize;
635 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000636 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
637 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
638 t_size -= sizeof(PyObject *);
639 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
640 type->tp_dictoffset + sizeof(PyObject *) == t_size)
641 t_size -= sizeof(PyObject *);
642
643 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000644}
645
646static PyTypeObject *
647solid_base(PyTypeObject *type)
648{
649 PyTypeObject *base;
650
651 if (type->tp_base)
652 base = solid_base(type->tp_base);
653 else
654 base = &PyBaseObject_Type;
655 if (extra_ivars(type, base))
656 return type;
657 else
658 return base;
659}
660
661staticforward void object_dealloc(PyObject *);
662staticforward int object_init(PyObject *, PyObject *, PyObject *);
663
664static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000665subtype_dict(PyObject *obj, void *context)
666{
667 PyObject **dictptr = _PyObject_GetDictPtr(obj);
668 PyObject *dict;
669
670 if (dictptr == NULL) {
671 PyErr_SetString(PyExc_AttributeError,
672 "This object has no __dict__");
673 return NULL;
674 }
675 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000676 if (dict == NULL)
677 *dictptr = dict = PyDict_New();
678 Py_XINCREF(dict);
679 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000680}
681
Guido van Rossum32d34c82001-09-20 21:45:26 +0000682PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000683 {"__dict__", subtype_dict, NULL, NULL},
684 {0},
685};
686
687static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
689{
690 PyObject *name, *bases, *dict;
691 static char *kwlist[] = {"name", "bases", "dict", 0};
692 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000693 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000694 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000695 PyMemberDef *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000696 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000697
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000698 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000699 if (metatype == &PyType_Type &&
700 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
701 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000702 PyObject *x = PyTuple_GET_ITEM(args, 0);
703 Py_INCREF(x->ob_type);
704 return (PyObject *) x->ob_type;
705 }
706
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000707 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000708 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
709 &name,
710 &PyTuple_Type, &bases,
711 &PyDict_Type, &dict))
712 return NULL;
713
714 /* Determine the proper metatype to deal with this,
715 and check for metatype conflicts while we're at it.
716 Note that if some other metatype wins to contract,
717 it's possible that its instances are not types. */
718 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000719 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000720 for (i = 0; i < nbases; i++) {
721 tmp = PyTuple_GET_ITEM(bases, i);
722 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000723 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000724 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000725 if (PyType_IsSubtype(tmptype, winner)) {
726 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000727 continue;
728 }
729 PyErr_SetString(PyExc_TypeError,
730 "metatype conflict among bases");
731 return NULL;
732 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000733 if (winner != metatype) {
734 if (winner->tp_new != type_new) /* Pass it to the winner */
735 return winner->tp_new(winner, args, kwds);
736 metatype = winner;
737 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000738
739 /* Adjust for empty tuple bases */
740 if (nbases == 0) {
741 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
742 if (bases == NULL)
743 return NULL;
744 nbases = 1;
745 }
746 else
747 Py_INCREF(bases);
748
749 /* XXX From here until type is allocated, "return NULL" leaks bases! */
750
751 /* Calculate best base, and check that all bases are type objects */
752 base = best_base(bases);
753 if (base == NULL)
754 return NULL;
755 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
756 PyErr_Format(PyExc_TypeError,
757 "type '%.100s' is not an acceptable base type",
758 base->tp_name);
759 return NULL;
760 }
761
Guido van Rossum1a493502001-08-17 16:47:50 +0000762 /* Should this be a dynamic class (i.e. modifiable __dict__)?
763 Look in two places for a variable named __dynamic__:
764 1) in the class dict
765 2) in the module dict (globals)
766 The first variable that is an int >= 0 is used.
767 Otherwise, a default is calculated from the base classes:
768 if any base class is dynamic, this class is dynamic; otherwise
769 it is static. */
770 dynamic = -1; /* Not yet determined */
771 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000772 tmp = PyDict_GetItemString(dict, "__dynamic__");
773 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000774 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000775 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000776 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000777 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000778 if (dynamic < 0) {
779 /* Look in the module globals */
780 tmp = PyEval_GetGlobals();
781 if (tmp != NULL) {
782 tmp = PyDict_GetItemString(tmp, "__dynamic__");
783 if (tmp != NULL) {
784 dynamic = PyInt_AsLong(tmp);
785 if (dynamic < 0)
786 PyErr_Clear();
787 }
788 }
789 }
790 if (dynamic < 0) {
791 /* Make a new class dynamic if any of its bases is
792 dynamic. This is not always the same as inheriting
793 the __dynamic__ class attribute! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000794 dynamic = 0;
795 for (i = 0; i < nbases; i++) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000796 tmptype = (PyTypeObject *)
797 PyTuple_GET_ITEM(bases, i);
798 if (tmptype->tp_flags &
799 Py_TPFLAGS_DYNAMICTYPE) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000800 dynamic = 1;
801 break;
802 }
803 }
804 }
805
806 /* Check for a __slots__ sequence variable in dict, and count it */
807 slots = PyDict_GetItemString(dict, "__slots__");
808 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000809 add_dict = 0;
810 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000811 if (slots != NULL) {
812 /* Make it into a tuple */
813 if (PyString_Check(slots))
814 slots = Py_BuildValue("(O)", slots);
815 else
816 slots = PySequence_Tuple(slots);
817 if (slots == NULL)
818 return NULL;
819 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000820 if (nslots > 0 && base->tp_itemsize != 0) {
821 PyErr_Format(PyExc_TypeError,
822 "nonempty __slots__ "
823 "not supported for subtype of '%s'",
824 base->tp_name);
825 return NULL;
826 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000827 for (i = 0; i < nslots; i++) {
828 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
829 PyErr_SetString(PyExc_TypeError,
830 "__slots__ must be a sequence of strings");
831 Py_DECREF(slots);
832 return NULL;
833 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000834 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000835 }
836 }
837 if (slots == NULL && base->tp_dictoffset == 0 &&
838 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000839 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000840 add_dict++;
841 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000842 if (slots == NULL && base->tp_weaklistoffset == 0 &&
843 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000844 nslots++;
845 add_weak++;
846 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000847
848 /* XXX From here until type is safely allocated,
849 "return NULL" may leak slots! */
850
851 /* Allocate the type object */
852 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
853 if (type == NULL)
854 return NULL;
855
856 /* Keep name and slots alive in the extended type object */
857 et = (etype *)type;
858 Py_INCREF(name);
859 et->name = name;
860 et->slots = slots;
861
Guido van Rossumdc91b992001-08-08 22:26:22 +0000862 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000863 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
864 Py_TPFLAGS_BASETYPE;
865 if (dynamic)
866 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000867 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
868 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000869
870 /* It's a new-style number unless it specifically inherits any
871 old-style numeric behavior */
872 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
873 (base->tp_as_number == NULL))
874 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
875
876 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000877 type->tp_as_number = &et->as_number;
878 type->tp_as_sequence = &et->as_sequence;
879 type->tp_as_mapping = &et->as_mapping;
880 type->tp_as_buffer = &et->as_buffer;
881 type->tp_name = PyString_AS_STRING(name);
882
883 /* Set tp_base and tp_bases */
884 type->tp_bases = bases;
885 Py_INCREF(base);
886 type->tp_base = base;
887
888 /* Initialize tp_defined from passed-in dict */
889 type->tp_defined = dict = PyDict_Copy(dict);
890 if (dict == NULL) {
891 Py_DECREF(type);
892 return NULL;
893 }
894
Guido van Rossumc3542212001-08-16 09:18:56 +0000895 /* Set __module__ in the dict */
896 if (PyDict_GetItemString(dict, "__module__") == NULL) {
897 tmp = PyEval_GetGlobals();
898 if (tmp != NULL) {
899 tmp = PyDict_GetItemString(tmp, "__name__");
900 if (tmp != NULL) {
901 if (PyDict_SetItemString(dict, "__module__",
902 tmp) < 0)
903 return NULL;
904 }
905 }
906 }
907
Tim Peters6d6c1a32001-08-02 04:15:00 +0000908 /* Special-case __new__: if it's a plain function,
909 make it a static function */
910 tmp = PyDict_GetItemString(dict, "__new__");
911 if (tmp != NULL && PyFunction_Check(tmp)) {
912 tmp = PyStaticMethod_New(tmp);
913 if (tmp == NULL) {
914 Py_DECREF(type);
915 return NULL;
916 }
917 PyDict_SetItemString(dict, "__new__", tmp);
918 Py_DECREF(tmp);
919 }
920
921 /* Add descriptors for custom slots from __slots__, or for __dict__ */
922 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000923 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000924 if (slots != NULL) {
925 for (i = 0; i < nslots; i++, mp++) {
926 mp->name = PyString_AS_STRING(
927 PyTuple_GET_ITEM(slots, i));
928 mp->type = T_OBJECT;
929 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000930 if (base->tp_weaklistoffset == 0 &&
931 strcmp(mp->name, "__weakref__") == 0)
932 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000933 slotoffset += sizeof(PyObject *);
934 }
935 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000936 else {
937 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000938 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +0000939 type->tp_dictoffset =
940 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000941 else
942 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000943 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000944 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000945 }
946 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000947 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000948 type->tp_weaklistoffset = slotoffset;
949 mp->name = "__weakref__";
950 mp->type = T_OBJECT;
951 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000952 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000953 mp++;
954 slotoffset += sizeof(PyObject *);
955 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000956 }
957 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000958 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000959 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000960
961 /* Special case some slots */
962 if (type->tp_dictoffset != 0 || nslots > 0) {
963 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
964 type->tp_getattro = PyObject_GenericGetAttr;
965 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
966 type->tp_setattro = PyObject_GenericSetAttr;
967 }
968 type->tp_dealloc = subtype_dealloc;
969
970 /* Always override allocation strategy to use regular heap */
971 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +0000972 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
973 type->tp_free = _PyObject_GC_Del;
974 type->tp_traverse = base->tp_traverse;
975 type->tp_clear = base->tp_clear;
976 }
977 else
978 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000979
980 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000981 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000982 Py_DECREF(type);
983 return NULL;
984 }
985
986 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +0000987 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
988 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000989
Tim Peters6d6c1a32001-08-02 04:15:00 +0000990 return (PyObject *)type;
991}
992
993/* Internal API to look for a name through the MRO.
994 This returns a borrowed reference, and doesn't set an exception! */
995PyObject *
996_PyType_Lookup(PyTypeObject *type, PyObject *name)
997{
998 int i, n;
999 PyObject *mro, *res, *dict;
1000
1001 /* For static types, look in tp_dict */
1002 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
1003 dict = type->tp_dict;
1004 assert(dict && PyDict_Check(dict));
1005 return PyDict_GetItem(dict, name);
1006 }
1007
1008 /* For dynamic types, look in tp_defined of types in MRO */
1009 mro = type->tp_mro;
1010 assert(PyTuple_Check(mro));
1011 n = PyTuple_GET_SIZE(mro);
1012 for (i = 0; i < n; i++) {
1013 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
1014 assert(PyType_Check(type));
1015 dict = type->tp_defined;
1016 assert(dict && PyDict_Check(dict));
1017 res = PyDict_GetItem(dict, name);
1018 if (res != NULL)
1019 return res;
1020 }
1021 return NULL;
1022}
1023
1024/* This is similar to PyObject_GenericGetAttr(),
1025 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1026static PyObject *
1027type_getattro(PyTypeObject *type, PyObject *name)
1028{
1029 PyTypeObject *metatype = type->ob_type;
1030 PyObject *descr, *res;
1031 descrgetfunc f;
1032
1033 /* Initialize this type (we'll assume the metatype is initialized) */
1034 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001035 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001036 return NULL;
1037 }
1038
1039 /* Get a descriptor from the metatype */
1040 descr = _PyType_Lookup(metatype, name);
1041 f = NULL;
1042 if (descr != NULL) {
1043 f = descr->ob_type->tp_descr_get;
1044 if (f != NULL && PyDescr_IsData(descr))
1045 return f(descr,
1046 (PyObject *)type, (PyObject *)metatype);
1047 }
1048
1049 /* Look in tp_defined of this type and its bases */
1050 res = _PyType_Lookup(type, name);
1051 if (res != NULL) {
1052 f = res->ob_type->tp_descr_get;
1053 if (f != NULL)
1054 return f(res, (PyObject *)NULL, (PyObject *)type);
1055 Py_INCREF(res);
1056 return res;
1057 }
1058
1059 /* Use the descriptor from the metatype */
1060 if (f != NULL) {
1061 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1062 return res;
1063 }
1064 if (descr != NULL) {
1065 Py_INCREF(descr);
1066 return descr;
1067 }
1068
1069 /* Give up */
1070 PyErr_Format(PyExc_AttributeError,
1071 "type object '%.50s' has no attribute '%.400s'",
1072 type->tp_name, PyString_AS_STRING(name));
1073 return NULL;
1074}
1075
1076static int
1077type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1078{
1079 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
1080 return PyObject_GenericSetAttr((PyObject *)type, name, value);
1081 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
1082 return -1;
1083}
1084
1085static void
1086type_dealloc(PyTypeObject *type)
1087{
1088 etype *et;
1089
1090 /* Assert this is a heap-allocated type object */
1091 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001092 _PyObject_GC_UNTRACK(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093 et = (etype *)type;
1094 Py_XDECREF(type->tp_base);
1095 Py_XDECREF(type->tp_dict);
1096 Py_XDECREF(type->tp_bases);
1097 Py_XDECREF(type->tp_mro);
1098 Py_XDECREF(type->tp_defined);
1099 /* XXX more? */
1100 Py_XDECREF(et->name);
1101 Py_XDECREF(et->slots);
1102 type->ob_type->tp_free((PyObject *)type);
1103}
1104
1105static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001106 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001107 "mro() -> list\nreturn a type's method resolution order"},
1108 {0}
1109};
1110
1111static char type_doc[] =
1112"type(object) -> the object's type\n"
1113"type(name, bases, dict) -> a new type";
1114
Guido van Rossum048eb752001-10-02 21:24:57 +00001115static int
1116type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1117{
1118 etype *et;
1119 int err;
1120
1121 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1122 return 0;
1123
1124 et = (etype *)type;
1125
1126#define VISIT(SLOT) \
1127 if (SLOT) { \
1128 err = visit((PyObject *)(SLOT), arg); \
1129 if (err) \
1130 return err; \
1131 }
1132
1133 VISIT(type->tp_dict);
1134 VISIT(type->tp_defined);
1135 VISIT(type->tp_mro);
1136 VISIT(type->tp_bases);
1137 VISIT(type->tp_base);
1138 VISIT(et->slots);
1139
1140#undef VISIT
1141
1142 return 0;
1143}
1144
1145static int
1146type_clear(PyTypeObject *type)
1147{
1148 etype *et;
1149 PyObject *tmp;
1150
1151 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1152 return 0;
1153
1154 et = (etype *)type;
1155
1156#define CLEAR(SLOT) \
1157 if (SLOT) { \
1158 tmp = (PyObject *)(SLOT); \
1159 SLOT = NULL; \
1160 Py_DECREF(tmp); \
1161 }
1162
1163 CLEAR(type->tp_dict);
1164 CLEAR(type->tp_defined);
1165 CLEAR(type->tp_mro);
1166 CLEAR(type->tp_bases);
1167 CLEAR(type->tp_base);
1168 CLEAR(et->slots);
1169
1170#undef CLEAR
1171
1172 return 0;
1173}
1174
1175static int
1176type_is_gc(PyTypeObject *type)
1177{
1178 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1179}
1180
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001181PyTypeObject PyType_Type = {
1182 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183 0, /* ob_size */
1184 "type", /* tp_name */
1185 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001186 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001187 (destructor)type_dealloc, /* tp_dealloc */
1188 0, /* tp_print */
1189 0, /* tp_getattr */
1190 0, /* tp_setattr */
1191 type_compare, /* tp_compare */
1192 (reprfunc)type_repr, /* tp_repr */
1193 0, /* tp_as_number */
1194 0, /* tp_as_sequence */
1195 0, /* tp_as_mapping */
1196 (hashfunc)_Py_HashPointer, /* tp_hash */
1197 (ternaryfunc)type_call, /* tp_call */
1198 0, /* tp_str */
1199 (getattrofunc)type_getattro, /* tp_getattro */
1200 (setattrofunc)type_setattro, /* tp_setattro */
1201 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001202 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1203 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001204 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001205 (traverseproc)type_traverse, /* tp_traverse */
1206 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001207 0, /* tp_richcompare */
1208 0, /* tp_weaklistoffset */
1209 0, /* tp_iter */
1210 0, /* tp_iternext */
1211 type_methods, /* tp_methods */
1212 type_members, /* tp_members */
1213 type_getsets, /* tp_getset */
1214 0, /* tp_base */
1215 0, /* tp_dict */
1216 0, /* tp_descr_get */
1217 0, /* tp_descr_set */
1218 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1219 0, /* tp_init */
1220 0, /* tp_alloc */
1221 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001222 _PyObject_GC_Del, /* tp_free */
1223 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001224};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001225
1226
1227/* The base type of all types (eventually)... except itself. */
1228
1229static int
1230object_init(PyObject *self, PyObject *args, PyObject *kwds)
1231{
1232 return 0;
1233}
1234
1235static void
1236object_dealloc(PyObject *self)
1237{
1238 self->ob_type->tp_free(self);
1239}
1240
Guido van Rossum8e248182001-08-12 05:17:56 +00001241static PyObject *
1242object_repr(PyObject *self)
1243{
Guido van Rossum76e69632001-08-16 18:52:43 +00001244 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001245 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001246
Guido van Rossum76e69632001-08-16 18:52:43 +00001247 type = self->ob_type;
1248 mod = type_module(type, NULL);
1249 if (mod == NULL)
1250 PyErr_Clear();
1251 else if (!PyString_Check(mod)) {
1252 Py_DECREF(mod);
1253 mod = NULL;
1254 }
1255 name = type_name(type, NULL);
1256 if (name == NULL)
1257 return NULL;
1258 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001259 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001260 PyString_AS_STRING(mod),
1261 PyString_AS_STRING(name),
1262 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001263 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001264 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001265 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001266 Py_XDECREF(mod);
1267 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001268 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001269}
1270
Guido van Rossumb8f63662001-08-15 23:57:02 +00001271static PyObject *
1272object_str(PyObject *self)
1273{
1274 unaryfunc f;
1275
1276 f = self->ob_type->tp_repr;
1277 if (f == NULL)
1278 f = object_repr;
1279 return f(self);
1280}
1281
Guido van Rossum8e248182001-08-12 05:17:56 +00001282static long
1283object_hash(PyObject *self)
1284{
1285 return _Py_HashPointer(self);
1286}
Guido van Rossum8e248182001-08-12 05:17:56 +00001287
Tim Peters6d6c1a32001-08-02 04:15:00 +00001288static void
1289object_free(PyObject *self)
1290{
1291 PyObject_Del(self);
1292}
1293
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001294static PyObject *
1295object_get_class(PyObject *self, void *closure)
1296{
1297 Py_INCREF(self->ob_type);
1298 return (PyObject *)(self->ob_type);
1299}
1300
1301static int
1302equiv_structs(PyTypeObject *a, PyTypeObject *b)
1303{
1304 return a == b ||
1305 (a != NULL &&
1306 b != NULL &&
1307 a->tp_basicsize == b->tp_basicsize &&
1308 a->tp_itemsize == b->tp_itemsize &&
1309 a->tp_dictoffset == b->tp_dictoffset &&
1310 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1311 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1312 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1313}
1314
1315static int
1316same_slots_added(PyTypeObject *a, PyTypeObject *b)
1317{
1318 PyTypeObject *base = a->tp_base;
1319 int size;
1320
1321 if (base != b->tp_base)
1322 return 0;
1323 if (equiv_structs(a, base) && equiv_structs(b, base))
1324 return 1;
1325 size = base->tp_basicsize;
1326 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1327 size += sizeof(PyObject *);
1328 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1329 size += sizeof(PyObject *);
1330 return size == a->tp_basicsize && size == b->tp_basicsize;
1331}
1332
1333static int
1334object_set_class(PyObject *self, PyObject *value, void *closure)
1335{
1336 PyTypeObject *old = self->ob_type;
1337 PyTypeObject *new, *newbase, *oldbase;
1338
1339 if (!PyType_Check(value)) {
1340 PyErr_Format(PyExc_TypeError,
1341 "__class__ must be set to new-style class, not '%s' object",
1342 value->ob_type->tp_name);
1343 return -1;
1344 }
1345 new = (PyTypeObject *)value;
1346 newbase = new;
1347 oldbase = old;
1348 while (equiv_structs(newbase, newbase->tp_base))
1349 newbase = newbase->tp_base;
1350 while (equiv_structs(oldbase, oldbase->tp_base))
1351 oldbase = oldbase->tp_base;
1352 if (newbase != oldbase &&
1353 (newbase->tp_base != oldbase->tp_base ||
1354 !same_slots_added(newbase, oldbase))) {
1355 PyErr_Format(PyExc_TypeError,
1356 "__class__ assignment: "
1357 "'%s' object layout differs from '%s'",
1358 new->tp_name,
1359 old->tp_name);
1360 return -1;
1361 }
1362 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1363 Py_INCREF(new);
1364 }
1365 self->ob_type = new;
1366 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1367 Py_DECREF(old);
1368 }
1369 return 0;
1370}
1371
1372static PyGetSetDef object_getsets[] = {
1373 {"__class__", object_get_class, object_set_class,
1374 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375 {0}
1376};
1377
Guido van Rossum3926a632001-09-25 16:25:58 +00001378static PyObject *
1379object_reduce(PyObject *self, PyObject *args)
1380{
1381 /* Call copy_reg._reduce(self) */
1382 static PyObject *copy_reg_str;
1383 PyObject *copy_reg, *res;
1384
1385 if (!copy_reg_str) {
1386 copy_reg_str = PyString_InternFromString("copy_reg");
1387 if (copy_reg_str == NULL)
1388 return NULL;
1389 }
1390 copy_reg = PyImport_Import(copy_reg_str);
1391 if (!copy_reg)
1392 return NULL;
1393 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1394 Py_DECREF(copy_reg);
1395 return res;
1396}
1397
1398static PyMethodDef object_methods[] = {
1399 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1400 {0}
1401};
1402
Tim Peters6d6c1a32001-08-02 04:15:00 +00001403PyTypeObject PyBaseObject_Type = {
1404 PyObject_HEAD_INIT(&PyType_Type)
1405 0, /* ob_size */
1406 "object", /* tp_name */
1407 sizeof(PyObject), /* tp_basicsize */
1408 0, /* tp_itemsize */
1409 (destructor)object_dealloc, /* tp_dealloc */
1410 0, /* tp_print */
1411 0, /* tp_getattr */
1412 0, /* tp_setattr */
1413 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001414 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001415 0, /* tp_as_number */
1416 0, /* tp_as_sequence */
1417 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001418 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001419 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001420 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001421 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001422 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001423 0, /* tp_as_buffer */
1424 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1425 "The most base type", /* tp_doc */
1426 0, /* tp_traverse */
1427 0, /* tp_clear */
1428 0, /* tp_richcompare */
1429 0, /* tp_weaklistoffset */
1430 0, /* tp_iter */
1431 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001432 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001433 0, /* tp_members */
1434 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001435 0, /* tp_base */
1436 0, /* tp_dict */
1437 0, /* tp_descr_get */
1438 0, /* tp_descr_set */
1439 0, /* tp_dictoffset */
1440 object_init, /* tp_init */
1441 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001442 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001443 object_free, /* tp_free */
1444};
1445
1446
1447/* Initialize the __dict__ in a type object */
1448
1449static int
1450add_methods(PyTypeObject *type, PyMethodDef *meth)
1451{
1452 PyObject *dict = type->tp_defined;
1453
1454 for (; meth->ml_name != NULL; meth++) {
1455 PyObject *descr;
1456 if (PyDict_GetItemString(dict, meth->ml_name))
1457 continue;
1458 descr = PyDescr_NewMethod(type, meth);
1459 if (descr == NULL)
1460 return -1;
1461 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1462 return -1;
1463 Py_DECREF(descr);
1464 }
1465 return 0;
1466}
1467
1468static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001469add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470{
1471 PyObject *dict = type->tp_defined;
1472
1473 for (; memb->name != NULL; memb++) {
1474 PyObject *descr;
1475 if (PyDict_GetItemString(dict, memb->name))
1476 continue;
1477 descr = PyDescr_NewMember(type, memb);
1478 if (descr == NULL)
1479 return -1;
1480 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1481 return -1;
1482 Py_DECREF(descr);
1483 }
1484 return 0;
1485}
1486
1487static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001488add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001489{
1490 PyObject *dict = type->tp_defined;
1491
1492 for (; gsp->name != NULL; gsp++) {
1493 PyObject *descr;
1494 if (PyDict_GetItemString(dict, gsp->name))
1495 continue;
1496 descr = PyDescr_NewGetSet(type, gsp);
1497
1498 if (descr == NULL)
1499 return -1;
1500 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1501 return -1;
1502 Py_DECREF(descr);
1503 }
1504 return 0;
1505}
1506
Guido van Rossum13d52f02001-08-10 21:24:08 +00001507static void
1508inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001509{
1510 int oldsize, newsize;
1511
Guido van Rossum13d52f02001-08-10 21:24:08 +00001512 /* Special flag magic */
1513 if (!type->tp_as_buffer && base->tp_as_buffer) {
1514 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1515 type->tp_flags |=
1516 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1517 }
1518 if (!type->tp_as_sequence && base->tp_as_sequence) {
1519 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1520 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1521 }
1522 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1523 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1524 if ((!type->tp_as_number && base->tp_as_number) ||
1525 (!type->tp_as_sequence && base->tp_as_sequence)) {
1526 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1527 if (!type->tp_as_number && !type->tp_as_sequence) {
1528 type->tp_flags |= base->tp_flags &
1529 Py_TPFLAGS_HAVE_INPLACEOPS;
1530 }
1531 }
1532 /* Wow */
1533 }
1534 if (!type->tp_as_number && base->tp_as_number) {
1535 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1536 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1537 }
1538
1539 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001540 oldsize = base->tp_basicsize;
1541 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1542 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1543 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001544 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1545 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001546 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001547 if (type->tp_traverse == NULL)
1548 type->tp_traverse = base->tp_traverse;
1549 if (type->tp_clear == NULL)
1550 type->tp_clear = base->tp_clear;
1551 }
1552 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1553 if (base != &PyBaseObject_Type ||
1554 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1555 if (type->tp_new == NULL)
1556 type->tp_new = base->tp_new;
1557 }
1558 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001559 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001560
1561 /* Copy other non-function slots */
1562
1563#undef COPYVAL
1564#define COPYVAL(SLOT) \
1565 if (type->SLOT == 0) type->SLOT = base->SLOT
1566
1567 COPYVAL(tp_itemsize);
1568 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1569 COPYVAL(tp_weaklistoffset);
1570 }
1571 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1572 COPYVAL(tp_dictoffset);
1573 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001574}
1575
1576static void
1577inherit_slots(PyTypeObject *type, PyTypeObject *base)
1578{
1579 PyTypeObject *basebase;
1580
1581#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001582#undef COPYSLOT
1583#undef COPYNUM
1584#undef COPYSEQ
1585#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001586
1587#define SLOTDEFINED(SLOT) \
1588 (base->SLOT != 0 && \
1589 (basebase == NULL || base->SLOT != basebase->SLOT))
1590
Tim Peters6d6c1a32001-08-02 04:15:00 +00001591#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001592 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001593
1594#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1595#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1596#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1597
Guido van Rossum13d52f02001-08-10 21:24:08 +00001598 /* This won't inherit indirect slots (from tp_as_number etc.)
1599 if type doesn't provide the space. */
1600
1601 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1602 basebase = base->tp_base;
1603 if (basebase->tp_as_number == NULL)
1604 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001605 COPYNUM(nb_add);
1606 COPYNUM(nb_subtract);
1607 COPYNUM(nb_multiply);
1608 COPYNUM(nb_divide);
1609 COPYNUM(nb_remainder);
1610 COPYNUM(nb_divmod);
1611 COPYNUM(nb_power);
1612 COPYNUM(nb_negative);
1613 COPYNUM(nb_positive);
1614 COPYNUM(nb_absolute);
1615 COPYNUM(nb_nonzero);
1616 COPYNUM(nb_invert);
1617 COPYNUM(nb_lshift);
1618 COPYNUM(nb_rshift);
1619 COPYNUM(nb_and);
1620 COPYNUM(nb_xor);
1621 COPYNUM(nb_or);
1622 COPYNUM(nb_coerce);
1623 COPYNUM(nb_int);
1624 COPYNUM(nb_long);
1625 COPYNUM(nb_float);
1626 COPYNUM(nb_oct);
1627 COPYNUM(nb_hex);
1628 COPYNUM(nb_inplace_add);
1629 COPYNUM(nb_inplace_subtract);
1630 COPYNUM(nb_inplace_multiply);
1631 COPYNUM(nb_inplace_divide);
1632 COPYNUM(nb_inplace_remainder);
1633 COPYNUM(nb_inplace_power);
1634 COPYNUM(nb_inplace_lshift);
1635 COPYNUM(nb_inplace_rshift);
1636 COPYNUM(nb_inplace_and);
1637 COPYNUM(nb_inplace_xor);
1638 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001639 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1640 COPYNUM(nb_true_divide);
1641 COPYNUM(nb_floor_divide);
1642 COPYNUM(nb_inplace_true_divide);
1643 COPYNUM(nb_inplace_floor_divide);
1644 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645 }
1646
Guido van Rossum13d52f02001-08-10 21:24:08 +00001647 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1648 basebase = base->tp_base;
1649 if (basebase->tp_as_sequence == NULL)
1650 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651 COPYSEQ(sq_length);
1652 COPYSEQ(sq_concat);
1653 COPYSEQ(sq_repeat);
1654 COPYSEQ(sq_item);
1655 COPYSEQ(sq_slice);
1656 COPYSEQ(sq_ass_item);
1657 COPYSEQ(sq_ass_slice);
1658 COPYSEQ(sq_contains);
1659 COPYSEQ(sq_inplace_concat);
1660 COPYSEQ(sq_inplace_repeat);
1661 }
1662
Guido van Rossum13d52f02001-08-10 21:24:08 +00001663 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1664 basebase = base->tp_base;
1665 if (basebase->tp_as_mapping == NULL)
1666 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667 COPYMAP(mp_length);
1668 COPYMAP(mp_subscript);
1669 COPYMAP(mp_ass_subscript);
1670 }
1671
Guido van Rossum13d52f02001-08-10 21:24:08 +00001672 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001673
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674 COPYSLOT(tp_dealloc);
1675 COPYSLOT(tp_print);
1676 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1677 type->tp_getattr = base->tp_getattr;
1678 type->tp_getattro = base->tp_getattro;
1679 }
1680 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1681 type->tp_setattr = base->tp_setattr;
1682 type->tp_setattro = base->tp_setattro;
1683 }
1684 /* tp_compare see tp_richcompare */
1685 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001686 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001687 COPYSLOT(tp_call);
1688 COPYSLOT(tp_str);
1689 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001691 if (type->tp_compare == NULL &&
1692 type->tp_richcompare == NULL &&
1693 type->tp_hash == NULL)
1694 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001695 type->tp_compare = base->tp_compare;
1696 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001697 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698 }
1699 }
1700 else {
1701 COPYSLOT(tp_compare);
1702 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001703 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1704 COPYSLOT(tp_iter);
1705 COPYSLOT(tp_iternext);
1706 }
1707 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1708 COPYSLOT(tp_descr_get);
1709 COPYSLOT(tp_descr_set);
1710 COPYSLOT(tp_dictoffset);
1711 COPYSLOT(tp_init);
1712 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713 COPYSLOT(tp_free);
1714 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715}
1716
Guido van Rossum13d52f02001-08-10 21:24:08 +00001717staticforward int add_operators(PyTypeObject *);
1718
Tim Peters6d6c1a32001-08-02 04:15:00 +00001719int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001720PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721{
1722 PyObject *dict, *bases, *x;
1723 PyTypeObject *base;
1724 int i, n;
1725
Guido van Rossumd614f972001-08-10 17:39:49 +00001726 if (type->tp_flags & Py_TPFLAGS_READY) {
1727 assert(type->tp_dict != NULL);
1728 return 0;
1729 }
1730 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1731 assert(type->tp_dict == NULL);
1732
1733 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001734
1735 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1736 base = type->tp_base;
1737 if (base == NULL && type != &PyBaseObject_Type)
1738 base = type->tp_base = &PyBaseObject_Type;
1739
1740 /* Initialize tp_bases */
1741 bases = type->tp_bases;
1742 if (bases == NULL) {
1743 if (base == NULL)
1744 bases = PyTuple_New(0);
1745 else
1746 bases = Py_BuildValue("(O)", base);
1747 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001748 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001749 type->tp_bases = bases;
1750 }
1751
1752 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001753 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001754 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001755 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001756 }
1757
1758 /* Initialize tp_defined */
1759 dict = type->tp_defined;
1760 if (dict == NULL) {
1761 dict = PyDict_New();
1762 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001763 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764 type->tp_defined = dict;
1765 }
1766
1767 /* Add type-specific descriptors to tp_defined */
1768 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001769 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001770 if (type->tp_methods != NULL) {
1771 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001772 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001773 }
1774 if (type->tp_members != NULL) {
1775 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001776 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777 }
1778 if (type->tp_getset != NULL) {
1779 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001780 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001781 }
1782
1783 /* Temporarily make tp_dict the same object as tp_defined.
1784 (This is needed to call mro(), and can stay this way for
1785 dynamic types). */
1786 Py_INCREF(type->tp_defined);
1787 type->tp_dict = type->tp_defined;
1788
1789 /* Calculate method resolution order */
1790 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001791 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001792 }
1793
Guido van Rossum13d52f02001-08-10 21:24:08 +00001794 /* Inherit special flags from dominant base */
1795 if (type->tp_base != NULL)
1796 inherit_special(type, type->tp_base);
1797
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001799 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001800 /* For a dynamic type, all slots are overridden */
1801 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001802 }
1803 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001804 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001805 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001806 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001807 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001808 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001809 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810 bases = type->tp_mro;
1811 assert(bases != NULL);
1812 assert(PyTuple_Check(bases));
1813 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001814 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1816 assert(PyType_Check(base));
1817 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001818 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001819 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001820 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001821 }
1822 }
1823
Guido van Rossum13d52f02001-08-10 21:24:08 +00001824 /* Some more special stuff */
1825 base = type->tp_base;
1826 if (base != NULL) {
1827 if (type->tp_as_number == NULL)
1828 type->tp_as_number = base->tp_as_number;
1829 if (type->tp_as_sequence == NULL)
1830 type->tp_as_sequence = base->tp_as_sequence;
1831 if (type->tp_as_mapping == NULL)
1832 type->tp_as_mapping = base->tp_as_mapping;
1833 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834
Guido van Rossum13d52f02001-08-10 21:24:08 +00001835 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001836 assert(type->tp_dict != NULL);
1837 type->tp_flags =
1838 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001839 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001840
1841 error:
1842 type->tp_flags &= ~Py_TPFLAGS_READYING;
1843 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844}
1845
1846
1847/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1848
1849/* There's a wrapper *function* for each distinct function typedef used
1850 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1851 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1852 Most tables have only one entry; the tables for binary operators have two
1853 entries, one regular and one with reversed arguments. */
1854
1855static PyObject *
1856wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1857{
1858 inquiry func = (inquiry)wrapped;
1859 int res;
1860
1861 if (!PyArg_ParseTuple(args, ""))
1862 return NULL;
1863 res = (*func)(self);
1864 if (res == -1 && PyErr_Occurred())
1865 return NULL;
1866 return PyInt_FromLong((long)res);
1867}
1868
1869static struct wrapperbase tab_len[] = {
1870 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1871 {0}
1872};
1873
1874static PyObject *
1875wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1876{
1877 binaryfunc func = (binaryfunc)wrapped;
1878 PyObject *other;
1879
1880 if (!PyArg_ParseTuple(args, "O", &other))
1881 return NULL;
1882 return (*func)(self, other);
1883}
1884
1885static PyObject *
1886wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1887{
1888 binaryfunc func = (binaryfunc)wrapped;
1889 PyObject *other;
1890
1891 if (!PyArg_ParseTuple(args, "O", &other))
1892 return NULL;
1893 return (*func)(other, self);
1894}
1895
1896#undef BINARY
1897#define BINARY(NAME, OP) \
1898static struct wrapperbase tab_##NAME[] = { \
1899 {"__" #NAME "__", \
1900 (wrapperfunc)wrap_binaryfunc, \
1901 "x.__" #NAME "__(y) <==> " #OP}, \
1902 {"__r" #NAME "__", \
1903 (wrapperfunc)wrap_binaryfunc_r, \
1904 "y.__r" #NAME "__(x) <==> " #OP}, \
1905 {0} \
1906}
1907
1908BINARY(add, "x+y");
1909BINARY(sub, "x-y");
1910BINARY(mul, "x*y");
1911BINARY(div, "x/y");
1912BINARY(mod, "x%y");
1913BINARY(divmod, "divmod(x,y)");
1914BINARY(lshift, "x<<y");
1915BINARY(rshift, "x>>y");
1916BINARY(and, "x&y");
1917BINARY(xor, "x^y");
1918BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00001919
1920static PyObject *
1921wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
1922{
1923 coercion func = (coercion)wrapped;
1924 PyObject *other, *res;
1925 int ok;
1926
1927 if (!PyArg_ParseTuple(args, "O", &other))
1928 return NULL;
1929 ok = func(&self, &other);
1930 if (ok < 0)
1931 return NULL;
1932 if (ok > 0) {
1933 Py_INCREF(Py_NotImplemented);
1934 return Py_NotImplemented;
1935 }
1936 res = PyTuple_New(2);
1937 if (res == NULL) {
1938 Py_DECREF(self);
1939 Py_DECREF(other);
1940 return NULL;
1941 }
1942 PyTuple_SET_ITEM(res, 0, self);
1943 PyTuple_SET_ITEM(res, 1, other);
1944 return res;
1945}
1946
1947static struct wrapperbase tab_coerce[] = {
1948 {"__coerce__", (wrapperfunc)wrap_coercefunc,
1949 "x.__coerce__(y) <==> coerce(x, y)"},
1950 {0}
1951};
1952
Guido van Rossum874f15a2001-09-25 21:16:33 +00001953BINARY(floordiv, "x//y");
1954BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001955
1956static PyObject *
1957wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1958{
1959 ternaryfunc func = (ternaryfunc)wrapped;
1960 PyObject *other;
1961 PyObject *third = Py_None;
1962
1963 /* Note: This wrapper only works for __pow__() */
1964
1965 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1966 return NULL;
1967 return (*func)(self, other, third);
1968}
1969
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00001970static PyObject *
1971wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1972{
1973 ternaryfunc func = (ternaryfunc)wrapped;
1974 PyObject *other;
1975 PyObject *third = Py_None;
1976
1977 /* Note: This wrapper only works for __pow__() */
1978
1979 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1980 return NULL;
1981 return (*func)(other, self, third);
1982}
1983
Tim Peters6d6c1a32001-08-02 04:15:00 +00001984#undef TERNARY
1985#define TERNARY(NAME, OP) \
1986static struct wrapperbase tab_##NAME[] = { \
1987 {"__" #NAME "__", \
1988 (wrapperfunc)wrap_ternaryfunc, \
1989 "x.__" #NAME "__(y, z) <==> " #OP}, \
1990 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00001991 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00001992 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1993 {0} \
1994}
1995
1996TERNARY(pow, "(x**y) % z");
1997
1998#undef UNARY
1999#define UNARY(NAME, OP) \
2000static struct wrapperbase tab_##NAME[] = { \
2001 {"__" #NAME "__", \
2002 (wrapperfunc)wrap_unaryfunc, \
2003 "x.__" #NAME "__() <==> " #OP}, \
2004 {0} \
2005}
2006
2007static PyObject *
2008wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2009{
2010 unaryfunc func = (unaryfunc)wrapped;
2011
2012 if (!PyArg_ParseTuple(args, ""))
2013 return NULL;
2014 return (*func)(self);
2015}
2016
2017UNARY(neg, "-x");
2018UNARY(pos, "+x");
2019UNARY(abs, "abs(x)");
2020UNARY(nonzero, "x != 0");
2021UNARY(invert, "~x");
2022UNARY(int, "int(x)");
2023UNARY(long, "long(x)");
2024UNARY(float, "float(x)");
2025UNARY(oct, "oct(x)");
2026UNARY(hex, "hex(x)");
2027
2028#undef IBINARY
2029#define IBINARY(NAME, OP) \
2030static struct wrapperbase tab_##NAME[] = { \
2031 {"__" #NAME "__", \
2032 (wrapperfunc)wrap_binaryfunc, \
2033 "x.__" #NAME "__(y) <==> " #OP}, \
2034 {0} \
2035}
2036
2037IBINARY(iadd, "x+=y");
2038IBINARY(isub, "x-=y");
2039IBINARY(imul, "x*=y");
2040IBINARY(idiv, "x/=y");
2041IBINARY(imod, "x%=y");
2042IBINARY(ilshift, "x<<=y");
2043IBINARY(irshift, "x>>=y");
2044IBINARY(iand, "x&=y");
2045IBINARY(ixor, "x^=y");
2046IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002047IBINARY(ifloordiv, "x//=y");
2048IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002049
2050#undef ITERNARY
2051#define ITERNARY(NAME, OP) \
2052static struct wrapperbase tab_##NAME[] = { \
2053 {"__" #NAME "__", \
2054 (wrapperfunc)wrap_ternaryfunc, \
2055 "x.__" #NAME "__(y) <==> " #OP}, \
2056 {0} \
2057}
2058
2059ITERNARY(ipow, "x = (x**y) % z");
2060
2061static struct wrapperbase tab_getitem[] = {
2062 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2063 "x.__getitem__(y) <==> x[y]"},
2064 {0}
2065};
2066
2067static PyObject *
2068wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2069{
2070 intargfunc func = (intargfunc)wrapped;
2071 int i;
2072
2073 if (!PyArg_ParseTuple(args, "i", &i))
2074 return NULL;
2075 return (*func)(self, i);
2076}
2077
2078static struct wrapperbase tab_mul_int[] = {
2079 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2080 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2081 {0}
2082};
2083
2084static struct wrapperbase tab_concat[] = {
2085 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2086 {0}
2087};
2088
2089static struct wrapperbase tab_imul_int[] = {
2090 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2091 {0}
2092};
2093
Guido van Rossum5d815f32001-08-17 21:57:47 +00002094static int
2095getindex(PyObject *self, PyObject *arg)
2096{
2097 int i;
2098
2099 i = PyInt_AsLong(arg);
2100 if (i == -1 && PyErr_Occurred())
2101 return -1;
2102 if (i < 0) {
2103 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2104 if (sq && sq->sq_length) {
2105 int n = (*sq->sq_length)(self);
2106 if (n < 0)
2107 return -1;
2108 i += n;
2109 }
2110 }
2111 return i;
2112}
2113
2114static PyObject *
2115wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2116{
2117 intargfunc func = (intargfunc)wrapped;
2118 PyObject *arg;
2119 int i;
2120
2121 if (!PyArg_ParseTuple(args, "O", &arg))
2122 return NULL;
2123 i = getindex(self, arg);
2124 if (i == -1 && PyErr_Occurred())
2125 return NULL;
2126 return (*func)(self, i);
2127}
2128
Tim Peters6d6c1a32001-08-02 04:15:00 +00002129static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002130 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002131 "x.__getitem__(i) <==> x[i]"},
2132 {0}
2133};
2134
2135static PyObject *
2136wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2137{
2138 intintargfunc func = (intintargfunc)wrapped;
2139 int i, j;
2140
2141 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2142 return NULL;
2143 return (*func)(self, i, j);
2144}
2145
2146static struct wrapperbase tab_getslice[] = {
2147 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2148 "x.__getslice__(i, j) <==> x[i:j]"},
2149 {0}
2150};
2151
2152static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002153wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002154{
2155 intobjargproc func = (intobjargproc)wrapped;
2156 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002157 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002158
Guido van Rossum5d815f32001-08-17 21:57:47 +00002159 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2160 return NULL;
2161 i = getindex(self, arg);
2162 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002163 return NULL;
2164 res = (*func)(self, i, value);
2165 if (res == -1 && PyErr_Occurred())
2166 return NULL;
2167 Py_INCREF(Py_None);
2168 return Py_None;
2169}
2170
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002171static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002172wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002173{
2174 intobjargproc func = (intobjargproc)wrapped;
2175 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002176 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002177
Guido van Rossum5d815f32001-08-17 21:57:47 +00002178 if (!PyArg_ParseTuple(args, "O", &arg))
2179 return NULL;
2180 i = getindex(self, arg);
2181 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002182 return NULL;
2183 res = (*func)(self, i, NULL);
2184 if (res == -1 && PyErr_Occurred())
2185 return NULL;
2186 Py_INCREF(Py_None);
2187 return Py_None;
2188}
2189
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002191 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002193 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002194 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002195 {0}
2196};
2197
2198static PyObject *
2199wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2200{
2201 intintobjargproc func = (intintobjargproc)wrapped;
2202 int i, j, res;
2203 PyObject *value;
2204
2205 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2206 return NULL;
2207 res = (*func)(self, i, j, value);
2208 if (res == -1 && PyErr_Occurred())
2209 return NULL;
2210 Py_INCREF(Py_None);
2211 return Py_None;
2212}
2213
2214static struct wrapperbase tab_setslice[] = {
2215 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2216 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
2217 {0}
2218};
2219
2220/* XXX objobjproc is a misnomer; should be objargpred */
2221static PyObject *
2222wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2223{
2224 objobjproc func = (objobjproc)wrapped;
2225 int res;
2226 PyObject *value;
2227
2228 if (!PyArg_ParseTuple(args, "O", &value))
2229 return NULL;
2230 res = (*func)(self, value);
2231 if (res == -1 && PyErr_Occurred())
2232 return NULL;
2233 return PyInt_FromLong((long)res);
2234}
2235
2236static struct wrapperbase tab_contains[] = {
2237 {"__contains__", (wrapperfunc)wrap_objobjproc,
2238 "x.__contains__(y) <==> y in x"},
2239 {0}
2240};
2241
2242static PyObject *
2243wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2244{
2245 objobjargproc func = (objobjargproc)wrapped;
2246 int res;
2247 PyObject *key, *value;
2248
2249 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2250 return NULL;
2251 res = (*func)(self, key, value);
2252 if (res == -1 && PyErr_Occurred())
2253 return NULL;
2254 Py_INCREF(Py_None);
2255 return Py_None;
2256}
2257
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002258static PyObject *
2259wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2260{
2261 objobjargproc func = (objobjargproc)wrapped;
2262 int res;
2263 PyObject *key;
2264
2265 if (!PyArg_ParseTuple(args, "O", &key))
2266 return NULL;
2267 res = (*func)(self, key, NULL);
2268 if (res == -1 && PyErr_Occurred())
2269 return NULL;
2270 Py_INCREF(Py_None);
2271 return Py_None;
2272}
2273
Tim Peters6d6c1a32001-08-02 04:15:00 +00002274static struct wrapperbase tab_setitem[] = {
2275 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2276 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002277 {"__delitem__", (wrapperfunc)wrap_delitem,
2278 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002279 {0}
2280};
2281
2282static PyObject *
2283wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2284{
2285 cmpfunc func = (cmpfunc)wrapped;
2286 int res;
2287 PyObject *other;
2288
2289 if (!PyArg_ParseTuple(args, "O", &other))
2290 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002291 if (other->ob_type->tp_compare != func &&
2292 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002293 PyErr_Format(
2294 PyExc_TypeError,
2295 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2296 self->ob_type->tp_name,
2297 self->ob_type->tp_name,
2298 other->ob_type->tp_name);
2299 return NULL;
2300 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002301 res = (*func)(self, other);
2302 if (PyErr_Occurred())
2303 return NULL;
2304 return PyInt_FromLong((long)res);
2305}
2306
2307static struct wrapperbase tab_cmp[] = {
2308 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2309 "x.__cmp__(y) <==> cmp(x,y)"},
2310 {0}
2311};
2312
2313static struct wrapperbase tab_repr[] = {
2314 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2315 "x.__repr__() <==> repr(x)"},
2316 {0}
2317};
2318
2319static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002320 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2321 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322 {0}
2323};
2324
2325static PyObject *
2326wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2327{
2328 setattrofunc func = (setattrofunc)wrapped;
2329 int res;
2330 PyObject *name, *value;
2331
2332 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2333 return NULL;
2334 res = (*func)(self, name, value);
2335 if (res < 0)
2336 return NULL;
2337 Py_INCREF(Py_None);
2338 return Py_None;
2339}
2340
2341static PyObject *
2342wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2343{
2344 setattrofunc func = (setattrofunc)wrapped;
2345 int res;
2346 PyObject *name;
2347
2348 if (!PyArg_ParseTuple(args, "O", &name))
2349 return NULL;
2350 res = (*func)(self, name, NULL);
2351 if (res < 0)
2352 return NULL;
2353 Py_INCREF(Py_None);
2354 return Py_None;
2355}
2356
2357static struct wrapperbase tab_setattr[] = {
2358 {"__setattr__", (wrapperfunc)wrap_setattr,
2359 "x.__setattr__('name', value) <==> x.name = value"},
2360 {"__delattr__", (wrapperfunc)wrap_delattr,
2361 "x.__delattr__('name') <==> del x.name"},
2362 {0}
2363};
2364
2365static PyObject *
2366wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2367{
2368 hashfunc func = (hashfunc)wrapped;
2369 long res;
2370
2371 if (!PyArg_ParseTuple(args, ""))
2372 return NULL;
2373 res = (*func)(self);
2374 if (res == -1 && PyErr_Occurred())
2375 return NULL;
2376 return PyInt_FromLong(res);
2377}
2378
2379static struct wrapperbase tab_hash[] = {
2380 {"__hash__", (wrapperfunc)wrap_hashfunc,
2381 "x.__hash__() <==> hash(x)"},
2382 {0}
2383};
2384
2385static PyObject *
2386wrap_call(PyObject *self, PyObject *args, void *wrapped)
2387{
2388 ternaryfunc func = (ternaryfunc)wrapped;
2389
2390 /* XXX What about keyword arguments? */
2391 return (*func)(self, args, NULL);
2392}
2393
2394static struct wrapperbase tab_call[] = {
2395 {"__call__", (wrapperfunc)wrap_call,
2396 "x.__call__(...) <==> x(...)"},
2397 {0}
2398};
2399
2400static struct wrapperbase tab_str[] = {
2401 {"__str__", (wrapperfunc)wrap_unaryfunc,
2402 "x.__str__() <==> str(x)"},
2403 {0}
2404};
2405
2406static PyObject *
2407wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2408{
2409 richcmpfunc func = (richcmpfunc)wrapped;
2410 PyObject *other;
2411
2412 if (!PyArg_ParseTuple(args, "O", &other))
2413 return NULL;
2414 return (*func)(self, other, op);
2415}
2416
2417#undef RICHCMP_WRAPPER
2418#define RICHCMP_WRAPPER(NAME, OP) \
2419static PyObject * \
2420richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2421{ \
2422 return wrap_richcmpfunc(self, args, wrapped, OP); \
2423}
2424
Jack Jansen8e938b42001-08-08 15:29:49 +00002425RICHCMP_WRAPPER(lt, Py_LT)
2426RICHCMP_WRAPPER(le, Py_LE)
2427RICHCMP_WRAPPER(eq, Py_EQ)
2428RICHCMP_WRAPPER(ne, Py_NE)
2429RICHCMP_WRAPPER(gt, Py_GT)
2430RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002431
2432#undef RICHCMP_ENTRY
2433#define RICHCMP_ENTRY(NAME, EXPR) \
2434 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2435 "x.__" #NAME "__(y) <==> " EXPR}
2436
2437static struct wrapperbase tab_richcmp[] = {
2438 RICHCMP_ENTRY(lt, "x<y"),
2439 RICHCMP_ENTRY(le, "x<=y"),
2440 RICHCMP_ENTRY(eq, "x==y"),
2441 RICHCMP_ENTRY(ne, "x!=y"),
2442 RICHCMP_ENTRY(gt, "x>y"),
2443 RICHCMP_ENTRY(ge, "x>=y"),
2444 {0}
2445};
2446
2447static struct wrapperbase tab_iter[] = {
2448 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2449 {0}
2450};
2451
2452static PyObject *
2453wrap_next(PyObject *self, PyObject *args, void *wrapped)
2454{
2455 unaryfunc func = (unaryfunc)wrapped;
2456 PyObject *res;
2457
2458 if (!PyArg_ParseTuple(args, ""))
2459 return NULL;
2460 res = (*func)(self);
2461 if (res == NULL && !PyErr_Occurred())
2462 PyErr_SetNone(PyExc_StopIteration);
2463 return res;
2464}
2465
2466static struct wrapperbase tab_next[] = {
2467 {"next", (wrapperfunc)wrap_next,
2468 "x.next() -> the next value, or raise StopIteration"},
2469 {0}
2470};
2471
2472static PyObject *
2473wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2474{
2475 descrgetfunc func = (descrgetfunc)wrapped;
2476 PyObject *obj;
2477 PyObject *type = NULL;
2478
2479 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2480 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002481 return (*func)(self, obj, type);
2482}
2483
2484static struct wrapperbase tab_descr_get[] = {
2485 {"__get__", (wrapperfunc)wrap_descr_get,
2486 "descr.__get__(obj, type) -> value"},
2487 {0}
2488};
2489
2490static PyObject *
2491wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2492{
2493 descrsetfunc func = (descrsetfunc)wrapped;
2494 PyObject *obj, *value;
2495 int ret;
2496
2497 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2498 return NULL;
2499 ret = (*func)(self, obj, value);
2500 if (ret < 0)
2501 return NULL;
2502 Py_INCREF(Py_None);
2503 return Py_None;
2504}
2505
2506static struct wrapperbase tab_descr_set[] = {
2507 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2508 "descr.__set__(obj, value)"},
2509 {0}
2510};
2511
2512static PyObject *
2513wrap_init(PyObject *self, PyObject *args, void *wrapped)
2514{
2515 initproc func = (initproc)wrapped;
2516
2517 /* XXX What about keyword arguments? */
2518 if (func(self, args, NULL) < 0)
2519 return NULL;
2520 Py_INCREF(Py_None);
2521 return Py_None;
2522}
2523
2524static struct wrapperbase tab_init[] = {
2525 {"__init__", (wrapperfunc)wrap_init,
2526 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002527 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002528 {0}
2529};
2530
2531static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002532tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002533{
Barry Warsaw60f01882001-08-22 19:24:42 +00002534 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002535 PyObject *arg0, *res;
2536
2537 if (self == NULL || !PyType_Check(self))
2538 Py_FatalError("__new__() called with non-type 'self'");
2539 type = (PyTypeObject *)self;
2540 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002541 PyErr_Format(PyExc_TypeError,
2542 "%s.__new__(): not enough arguments",
2543 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002544 return NULL;
2545 }
2546 arg0 = PyTuple_GET_ITEM(args, 0);
2547 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002548 PyErr_Format(PyExc_TypeError,
2549 "%s.__new__(X): X is not a type object (%s)",
2550 type->tp_name,
2551 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002552 return NULL;
2553 }
2554 subtype = (PyTypeObject *)arg0;
2555 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002556 PyErr_Format(PyExc_TypeError,
2557 "%s.__new__(%s): %s is not a subtype of %s",
2558 type->tp_name,
2559 subtype->tp_name,
2560 subtype->tp_name,
2561 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002562 return NULL;
2563 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002564
2565 /* Check that the use doesn't do something silly and unsafe like
2566 object.__new__(dictionary). To do this, we check that the
2567 most derived base that's not a heap type is this type. */
2568 staticbase = subtype;
2569 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2570 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002571 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002572 PyErr_Format(PyExc_TypeError,
2573 "%s.__new__(%s) is not safe, use %s.__new__()",
2574 type->tp_name,
2575 subtype->tp_name,
2576 staticbase == NULL ? "?" : staticbase->tp_name);
2577 return NULL;
2578 }
2579
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002580 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2581 if (args == NULL)
2582 return NULL;
2583 res = type->tp_new(subtype, args, kwds);
2584 Py_DECREF(args);
2585 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002586}
2587
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002588static struct PyMethodDef tp_new_methoddef[] = {
2589 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2590 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002591 {0}
2592};
2593
2594static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002595add_tp_new_wrapper(PyTypeObject *type)
2596{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002597 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002598
Guido van Rossumf040ede2001-08-07 16:40:56 +00002599 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2600 return 0;
2601 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002602 if (func == NULL)
2603 return -1;
2604 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2605}
2606
Guido van Rossum13d52f02001-08-10 21:24:08 +00002607static int
2608add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2609{
2610 PyObject *dict = type->tp_defined;
2611
2612 for (; wraps->name != NULL; wraps++) {
2613 PyObject *descr;
2614 if (PyDict_GetItemString(dict, wraps->name))
2615 continue;
2616 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2617 if (descr == NULL)
2618 return -1;
2619 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2620 return -1;
2621 Py_DECREF(descr);
2622 }
2623 return 0;
2624}
2625
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002626/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002627 dictionary with method descriptors for function slots. For each
2628 function slot (like tp_repr) that's defined in the type, one or
2629 more corresponding descriptors are added in the type's tp_defined
2630 dictionary under the appropriate name (like __repr__). Some
2631 function slots cause more than one descriptor to be added (for
2632 example, the nb_add slot adds both __add__ and __radd__
2633 descriptors) and some function slots compete for the same
2634 descriptor (for example both sq_item and mp_subscript generate a
2635 __getitem__ descriptor). This only adds new descriptors and
2636 doesn't overwrite entries in tp_defined that were previously
2637 defined. The descriptors contain a reference to the C function
2638 they must call, so that it's safe if they are copied into a
2639 subtype's __dict__ and the subtype has a different C function in
2640 its slot -- calling the method defined by the descriptor will call
2641 the C function that was used to create it, rather than the C
2642 function present in the slot when it is called. (This is important
2643 because a subtype may have a C function in the slot that calls the
2644 method from the dictionary, and we want to avoid infinite recursion
2645 here.) */
2646
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002647static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002648add_operators(PyTypeObject *type)
2649{
2650 PySequenceMethods *sq;
2651 PyMappingMethods *mp;
2652 PyNumberMethods *nb;
2653
2654#undef ADD
2655#define ADD(SLOT, TABLE) \
2656 if (SLOT) { \
2657 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2658 return -1; \
2659 }
2660
2661 if ((sq = type->tp_as_sequence) != NULL) {
2662 ADD(sq->sq_length, tab_len);
2663 ADD(sq->sq_concat, tab_concat);
2664 ADD(sq->sq_repeat, tab_mul_int);
2665 ADD(sq->sq_item, tab_getitem_int);
2666 ADD(sq->sq_slice, tab_getslice);
2667 ADD(sq->sq_ass_item, tab_setitem_int);
2668 ADD(sq->sq_ass_slice, tab_setslice);
2669 ADD(sq->sq_contains, tab_contains);
2670 ADD(sq->sq_inplace_concat, tab_iadd);
2671 ADD(sq->sq_inplace_repeat, tab_imul_int);
2672 }
2673
2674 if ((mp = type->tp_as_mapping) != NULL) {
2675 if (sq->sq_length == NULL)
2676 ADD(mp->mp_length, tab_len);
2677 ADD(mp->mp_subscript, tab_getitem);
2678 ADD(mp->mp_ass_subscript, tab_setitem);
2679 }
2680
2681 /* We don't support "old-style numbers" because their binary
2682 operators require that both arguments have the same type;
2683 the wrappers here only work for new-style numbers. */
2684 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2685 (nb = type->tp_as_number) != NULL) {
2686 ADD(nb->nb_add, tab_add);
2687 ADD(nb->nb_subtract, tab_sub);
2688 ADD(nb->nb_multiply, tab_mul);
2689 ADD(nb->nb_divide, tab_div);
2690 ADD(nb->nb_remainder, tab_mod);
2691 ADD(nb->nb_divmod, tab_divmod);
2692 ADD(nb->nb_power, tab_pow);
2693 ADD(nb->nb_negative, tab_neg);
2694 ADD(nb->nb_positive, tab_pos);
2695 ADD(nb->nb_absolute, tab_abs);
2696 ADD(nb->nb_nonzero, tab_nonzero);
2697 ADD(nb->nb_invert, tab_invert);
2698 ADD(nb->nb_lshift, tab_lshift);
2699 ADD(nb->nb_rshift, tab_rshift);
2700 ADD(nb->nb_and, tab_and);
2701 ADD(nb->nb_xor, tab_xor);
2702 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002703 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002704 ADD(nb->nb_int, tab_int);
2705 ADD(nb->nb_long, tab_long);
2706 ADD(nb->nb_float, tab_float);
2707 ADD(nb->nb_oct, tab_oct);
2708 ADD(nb->nb_hex, tab_hex);
2709 ADD(nb->nb_inplace_add, tab_iadd);
2710 ADD(nb->nb_inplace_subtract, tab_isub);
2711 ADD(nb->nb_inplace_multiply, tab_imul);
2712 ADD(nb->nb_inplace_divide, tab_idiv);
2713 ADD(nb->nb_inplace_remainder, tab_imod);
2714 ADD(nb->nb_inplace_power, tab_ipow);
2715 ADD(nb->nb_inplace_lshift, tab_ilshift);
2716 ADD(nb->nb_inplace_rshift, tab_irshift);
2717 ADD(nb->nb_inplace_and, tab_iand);
2718 ADD(nb->nb_inplace_xor, tab_ixor);
2719 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum874f15a2001-09-25 21:16:33 +00002720 if (type->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2721 ADD(nb->nb_floor_divide, tab_floordiv);
2722 ADD(nb->nb_true_divide, tab_truediv);
2723 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2724 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2725 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726 }
2727
2728 ADD(type->tp_getattro, tab_getattr);
2729 ADD(type->tp_setattro, tab_setattr);
2730 ADD(type->tp_compare, tab_cmp);
2731 ADD(type->tp_repr, tab_repr);
2732 ADD(type->tp_hash, tab_hash);
2733 ADD(type->tp_call, tab_call);
2734 ADD(type->tp_str, tab_str);
2735 ADD(type->tp_richcompare, tab_richcmp);
2736 ADD(type->tp_iter, tab_iter);
2737 ADD(type->tp_iternext, tab_next);
2738 ADD(type->tp_descr_get, tab_descr_get);
2739 ADD(type->tp_descr_set, tab_descr_set);
2740 ADD(type->tp_init, tab_init);
2741
Guido van Rossumf040ede2001-08-07 16:40:56 +00002742 if (type->tp_new != NULL) {
2743 if (add_tp_new_wrapper(type) < 0)
2744 return -1;
2745 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002746
2747 return 0;
2748}
2749
Guido van Rossumf040ede2001-08-07 16:40:56 +00002750/* Slot wrappers that call the corresponding __foo__ slot. See comments
2751 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002752
Guido van Rossumdc91b992001-08-08 22:26:22 +00002753#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002754static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002755FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002756{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002757 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002758 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759}
2760
Guido van Rossumdc91b992001-08-08 22:26:22 +00002761#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002762static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002763FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002764{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002765 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002766 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767}
2768
Guido van Rossumdc91b992001-08-08 22:26:22 +00002769
2770#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002772FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002773{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002774 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002775 int do_other = self->ob_type != other->ob_type && \
2776 other->ob_type->tp_as_number != NULL && \
2777 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002778 if (self->ob_type->tp_as_number != NULL && \
2779 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2780 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002781 if (do_other && \
2782 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2783 r = call_maybe( \
2784 other, ROPSTR, &rcache_str, "(O)", self); \
2785 if (r != Py_NotImplemented) \
2786 return r; \
2787 Py_DECREF(r); \
2788 do_other = 0; \
2789 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002790 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002791 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002792 if (r != Py_NotImplemented || \
2793 other->ob_type == self->ob_type) \
2794 return r; \
2795 Py_DECREF(r); \
2796 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002797 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002798 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002799 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002800 } \
2801 Py_INCREF(Py_NotImplemented); \
2802 return Py_NotImplemented; \
2803}
2804
2805#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2806 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2807
2808#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2809static PyObject * \
2810FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2811{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002812 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002813 return call_method(self, OPSTR, &cache_str, \
2814 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002815}
2816
2817static int
2818slot_sq_length(PyObject *self)
2819{
Guido van Rossum2730b132001-08-28 18:22:14 +00002820 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002821 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002822 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002823
2824 if (res == NULL)
2825 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002826 len = (int)PyInt_AsLong(res);
2827 Py_DECREF(res);
2828 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002829}
2830
Guido van Rossumdc91b992001-08-08 22:26:22 +00002831SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2832SLOT1(slot_sq_repeat, "__mul__", int, "i")
2833SLOT1(slot_sq_item, "__getitem__", int, "i")
2834SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002835
2836static int
2837slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2838{
2839 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002840 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002841
2842 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002843 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002844 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002845 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002846 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002847 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002848 if (res == NULL)
2849 return -1;
2850 Py_DECREF(res);
2851 return 0;
2852}
2853
2854static int
2855slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2856{
2857 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002858 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002859
2860 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002861 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002862 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002863 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002864 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002865 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002866 if (res == NULL)
2867 return -1;
2868 Py_DECREF(res);
2869 return 0;
2870}
2871
2872static int
2873slot_sq_contains(PyObject *self, PyObject *value)
2874{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002875 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002876 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002877
Guido van Rossum55f20992001-10-01 17:18:22 +00002878 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002879
2880 if (func != NULL) {
2881 args = Py_BuildValue("(O)", value);
2882 if (args == NULL)
2883 res = NULL;
2884 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002885 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002886 Py_DECREF(args);
2887 }
2888 Py_DECREF(func);
2889 if (res == NULL)
2890 return -1;
2891 return PyObject_IsTrue(res);
2892 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002893 else if (PyErr_Occurred())
2894 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002895 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002896 return _PySequence_IterSearch(self, value,
2897 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002898 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002899}
2900
Guido van Rossumdc91b992001-08-08 22:26:22 +00002901SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2902SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002903
2904#define slot_mp_length slot_sq_length
2905
Guido van Rossumdc91b992001-08-08 22:26:22 +00002906SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002907
2908static int
2909slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2910{
2911 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002912 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002913
2914 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002915 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002916 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002917 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002918 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002919 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002920 if (res == NULL)
2921 return -1;
2922 Py_DECREF(res);
2923 return 0;
2924}
2925
Guido van Rossumdc91b992001-08-08 22:26:22 +00002926SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2927SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2928SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2929SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2930SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2931SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2932
2933staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2934
2935SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2936 nb_power, "__pow__", "__rpow__")
2937
2938static PyObject *
2939slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2940{
Guido van Rossum2730b132001-08-28 18:22:14 +00002941 static PyObject *pow_str;
2942
Guido van Rossumdc91b992001-08-08 22:26:22 +00002943 if (modulus == Py_None)
2944 return slot_nb_power_binary(self, other);
2945 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002946 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002947 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002948}
2949
2950SLOT0(slot_nb_negative, "__neg__")
2951SLOT0(slot_nb_positive, "__pos__")
2952SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002953
2954static int
2955slot_nb_nonzero(PyObject *self)
2956{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002957 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002958 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002959
Guido van Rossum55f20992001-10-01 17:18:22 +00002960 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002961 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00002962 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00002963 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00002964 func = lookup_maybe(self, "__len__", &len_str);
2965 if (func == NULL) {
2966 if (PyErr_Occurred())
2967 return -1;
2968 else
2969 return 1;
2970 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00002971 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002972 res = PyObject_CallObject(func, NULL);
2973 Py_DECREF(func);
2974 if (res == NULL)
2975 return -1;
2976 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002977}
2978
Guido van Rossumdc91b992001-08-08 22:26:22 +00002979SLOT0(slot_nb_invert, "__invert__")
2980SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2981SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2982SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2983SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2984SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002985
2986static int
2987slot_nb_coerce(PyObject **a, PyObject **b)
2988{
2989 static PyObject *coerce_str;
2990 PyObject *self = *a, *other = *b;
2991
2992 if (self->ob_type->tp_as_number != NULL &&
2993 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
2994 PyObject *r;
2995 r = call_maybe(
2996 self, "__coerce__", &coerce_str, "(O)", other);
2997 if (r == NULL)
2998 return -1;
2999 if (r == Py_NotImplemented) {
3000 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003001 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003002 else {
3003 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3004 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003005 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003006 Py_DECREF(r);
3007 return -1;
3008 }
3009 *a = PyTuple_GET_ITEM(r, 0);
3010 Py_INCREF(*a);
3011 *b = PyTuple_GET_ITEM(r, 1);
3012 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003013 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003014 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003015 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003016 }
3017 if (other->ob_type->tp_as_number != NULL &&
3018 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3019 PyObject *r;
3020 r = call_maybe(
3021 other, "__coerce__", &coerce_str, "(O)", self);
3022 if (r == NULL)
3023 return -1;
3024 if (r == Py_NotImplemented) {
3025 Py_DECREF(r);
3026 return 1;
3027 }
3028 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3029 PyErr_SetString(PyExc_TypeError,
3030 "__coerce__ didn't return a 2-tuple");
3031 Py_DECREF(r);
3032 return -1;
3033 }
3034 *a = PyTuple_GET_ITEM(r, 1);
3035 Py_INCREF(*a);
3036 *b = PyTuple_GET_ITEM(r, 0);
3037 Py_INCREF(*b);
3038 Py_DECREF(r);
3039 return 0;
3040 }
3041 return 1;
3042}
3043
Guido van Rossumdc91b992001-08-08 22:26:22 +00003044SLOT0(slot_nb_int, "__int__")
3045SLOT0(slot_nb_long, "__long__")
3046SLOT0(slot_nb_float, "__float__")
3047SLOT0(slot_nb_oct, "__oct__")
3048SLOT0(slot_nb_hex, "__hex__")
3049SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3050SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3051SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3052SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3053SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3054SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3055SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3056SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3057SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3058SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3059SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3060SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3061 "__floordiv__", "__rfloordiv__")
3062SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3063SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3064SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003065
3066static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003067half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003068{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003069 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003070 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003071 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003072
Guido van Rossum60718732001-08-28 17:47:51 +00003073 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003074 if (func == NULL) {
3075 PyErr_Clear();
3076 }
3077 else {
3078 args = Py_BuildValue("(O)", other);
3079 if (args == NULL)
3080 res = NULL;
3081 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003082 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003083 Py_DECREF(args);
3084 }
3085 if (res != Py_NotImplemented) {
3086 if (res == NULL)
3087 return -2;
3088 c = PyInt_AsLong(res);
3089 Py_DECREF(res);
3090 if (c == -1 && PyErr_Occurred())
3091 return -2;
3092 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3093 }
3094 Py_DECREF(res);
3095 }
3096 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003097}
3098
Guido van Rossumab3b0342001-09-18 20:38:53 +00003099/* This slot is published for the benefit of try_3way_compare in object.c */
3100int
3101_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003102{
3103 int c;
3104
Guido van Rossumab3b0342001-09-18 20:38:53 +00003105 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003106 c = half_compare(self, other);
3107 if (c <= 1)
3108 return c;
3109 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003110 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003111 c = half_compare(other, self);
3112 if (c < -1)
3113 return -2;
3114 if (c <= 1)
3115 return -c;
3116 }
3117 return (void *)self < (void *)other ? -1 :
3118 (void *)self > (void *)other ? 1 : 0;
3119}
3120
3121static PyObject *
3122slot_tp_repr(PyObject *self)
3123{
3124 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003125 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003126
Guido van Rossum60718732001-08-28 17:47:51 +00003127 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003128 if (func != NULL) {
3129 res = PyEval_CallObject(func, NULL);
3130 Py_DECREF(func);
3131 return res;
3132 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003133 PyErr_Clear();
3134 return PyString_FromFormat("<%s object at %p>",
3135 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003136}
3137
3138static PyObject *
3139slot_tp_str(PyObject *self)
3140{
3141 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003142 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003143
Guido van Rossum60718732001-08-28 17:47:51 +00003144 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003145 if (func != NULL) {
3146 res = PyEval_CallObject(func, NULL);
3147 Py_DECREF(func);
3148 return res;
3149 }
3150 else {
3151 PyErr_Clear();
3152 return slot_tp_repr(self);
3153 }
3154}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003155
3156static long
3157slot_tp_hash(PyObject *self)
3158{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003159 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003160 static PyObject *hash_str, *eq_str, *cmp_str;
3161
Tim Peters6d6c1a32001-08-02 04:15:00 +00003162 long h;
3163
Guido van Rossum60718732001-08-28 17:47:51 +00003164 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003165
3166 if (func != NULL) {
3167 res = PyEval_CallObject(func, NULL);
3168 Py_DECREF(func);
3169 if (res == NULL)
3170 return -1;
3171 h = PyInt_AsLong(res);
3172 }
3173 else {
3174 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003175 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003176 if (func == NULL) {
3177 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003178 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003179 }
3180 if (func != NULL) {
3181 Py_DECREF(func);
3182 PyErr_SetString(PyExc_TypeError, "unhashable type");
3183 return -1;
3184 }
3185 PyErr_Clear();
3186 h = _Py_HashPointer((void *)self);
3187 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188 if (h == -1 && !PyErr_Occurred())
3189 h = -2;
3190 return h;
3191}
3192
3193static PyObject *
3194slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3195{
Guido van Rossum60718732001-08-28 17:47:51 +00003196 static PyObject *call_str;
3197 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003198 PyObject *res;
3199
3200 if (meth == NULL)
3201 return NULL;
3202 res = PyObject_Call(meth, args, kwds);
3203 Py_DECREF(meth);
3204 return res;
3205}
3206
Tim Peters6d6c1a32001-08-02 04:15:00 +00003207static PyObject *
3208slot_tp_getattro(PyObject *self, PyObject *name)
3209{
3210 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003211 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003212 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003213
Guido van Rossum8e248182001-08-12 05:17:56 +00003214 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003215 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003216 if (getattr_str == NULL)
3217 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003219 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003220 if (getattr == NULL) {
3221 /* Avoid further slowdowns */
3222 if (tp->tp_getattro == slot_tp_getattro)
3223 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003224 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003225 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003226 return PyObject_CallFunction(getattr, "OO", self, name);
3227}
3228
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003229static PyObject *
3230slot_tp_getattr_hook(PyObject *self, PyObject *name)
3231{
3232 PyTypeObject *tp = self->ob_type;
3233 PyObject *getattr, *getattribute, *res;
3234 static PyObject *getattribute_str = NULL;
3235 static PyObject *getattr_str = NULL;
3236
3237 if (getattr_str == NULL) {
3238 getattr_str = PyString_InternFromString("__getattr__");
3239 if (getattr_str == NULL)
3240 return NULL;
3241 }
3242 if (getattribute_str == NULL) {
3243 getattribute_str =
3244 PyString_InternFromString("__getattribute__");
3245 if (getattribute_str == NULL)
3246 return NULL;
3247 }
3248 getattr = _PyType_Lookup(tp, getattr_str);
3249 getattribute = _PyType_Lookup(tp, getattribute_str);
3250 if (getattr == NULL && getattribute == NULL) {
3251 /* Avoid further slowdowns */
3252 if (tp->tp_getattro == slot_tp_getattr_hook)
3253 tp->tp_getattro = PyObject_GenericGetAttr;
3254 return PyObject_GenericGetAttr(self, name);
3255 }
3256 if (getattribute == NULL)
3257 res = PyObject_GenericGetAttr(self, name);
3258 else
3259 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003260 if (getattr != NULL &&
3261 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003262 PyErr_Clear();
3263 res = PyObject_CallFunction(getattr, "OO", self, name);
3264 }
3265 return res;
3266}
3267
Tim Peters6d6c1a32001-08-02 04:15:00 +00003268static int
3269slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3270{
3271 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003272 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003273
3274 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003275 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003276 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003277 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003278 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003279 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003280 if (res == NULL)
3281 return -1;
3282 Py_DECREF(res);
3283 return 0;
3284}
3285
3286/* Map rich comparison operators to their __xx__ namesakes */
3287static char *name_op[] = {
3288 "__lt__",
3289 "__le__",
3290 "__eq__",
3291 "__ne__",
3292 "__gt__",
3293 "__ge__",
3294};
3295
3296static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003297half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003298{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003299 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003300 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003301
Guido van Rossum60718732001-08-28 17:47:51 +00003302 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003303 if (func == NULL) {
3304 PyErr_Clear();
3305 Py_INCREF(Py_NotImplemented);
3306 return Py_NotImplemented;
3307 }
3308 args = Py_BuildValue("(O)", other);
3309 if (args == NULL)
3310 res = NULL;
3311 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003312 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003313 Py_DECREF(args);
3314 }
3315 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003316 return res;
3317}
3318
Guido van Rossumb8f63662001-08-15 23:57:02 +00003319/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3320static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3321
3322static PyObject *
3323slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3324{
3325 PyObject *res;
3326
3327 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3328 res = half_richcompare(self, other, op);
3329 if (res != Py_NotImplemented)
3330 return res;
3331 Py_DECREF(res);
3332 }
3333 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3334 res = half_richcompare(other, self, swapped_op[op]);
3335 if (res != Py_NotImplemented) {
3336 return res;
3337 }
3338 Py_DECREF(res);
3339 }
3340 Py_INCREF(Py_NotImplemented);
3341 return Py_NotImplemented;
3342}
3343
3344static PyObject *
3345slot_tp_iter(PyObject *self)
3346{
3347 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003348 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003349
Guido van Rossum60718732001-08-28 17:47:51 +00003350 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003351 if (func != NULL) {
3352 res = PyObject_CallObject(func, NULL);
3353 Py_DECREF(func);
3354 return res;
3355 }
3356 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003357 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003358 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003359 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003360 return NULL;
3361 }
3362 Py_DECREF(func);
3363 return PySeqIter_New(self);
3364}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365
3366static PyObject *
3367slot_tp_iternext(PyObject *self)
3368{
Guido van Rossum2730b132001-08-28 18:22:14 +00003369 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003370 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003371}
3372
Guido van Rossum1a493502001-08-17 16:47:50 +00003373static PyObject *
3374slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3375{
3376 PyTypeObject *tp = self->ob_type;
3377 PyObject *get;
3378 static PyObject *get_str = NULL;
3379
3380 if (get_str == NULL) {
3381 get_str = PyString_InternFromString("__get__");
3382 if (get_str == NULL)
3383 return NULL;
3384 }
3385 get = _PyType_Lookup(tp, get_str);
3386 if (get == NULL) {
3387 /* Avoid further slowdowns */
3388 if (tp->tp_descr_get == slot_tp_descr_get)
3389 tp->tp_descr_get = NULL;
3390 Py_INCREF(self);
3391 return self;
3392 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003393 if (obj == NULL)
3394 obj = Py_None;
3395 if (type == NULL)
3396 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003397 return PyObject_CallFunction(get, "OOO", self, obj, type);
3398}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003399
3400static int
3401slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3402{
Guido van Rossum2c252392001-08-24 10:13:31 +00003403 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003404 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003405
3406 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003407 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003408 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003409 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003410 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003411 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003412 if (res == NULL)
3413 return -1;
3414 Py_DECREF(res);
3415 return 0;
3416}
3417
3418static int
3419slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3420{
Guido van Rossum60718732001-08-28 17:47:51 +00003421 static PyObject *init_str;
3422 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423 PyObject *res;
3424
3425 if (meth == NULL)
3426 return -1;
3427 res = PyObject_Call(meth, args, kwds);
3428 Py_DECREF(meth);
3429 if (res == NULL)
3430 return -1;
3431 Py_DECREF(res);
3432 return 0;
3433}
3434
3435static PyObject *
3436slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3437{
3438 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3439 PyObject *newargs, *x;
3440 int i, n;
3441
3442 if (func == NULL)
3443 return NULL;
3444 assert(PyTuple_Check(args));
3445 n = PyTuple_GET_SIZE(args);
3446 newargs = PyTuple_New(n+1);
3447 if (newargs == NULL)
3448 return NULL;
3449 Py_INCREF(type);
3450 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3451 for (i = 0; i < n; i++) {
3452 x = PyTuple_GET_ITEM(args, i);
3453 Py_INCREF(x);
3454 PyTuple_SET_ITEM(newargs, i+1, x);
3455 }
3456 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003457 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003458 Py_DECREF(func);
3459 return x;
3460}
3461
Guido van Rossumf040ede2001-08-07 16:40:56 +00003462/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003463 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003464 The dict argument is the dictionary argument passed to type_new(),
3465 which is the local namespace of the class statement, in other
3466 words, it contains the methods. For each special method (like
3467 __repr__) defined in the dictionary, the corresponding function
3468 slot in the type object (like tp_repr) is set to a special function
3469 whose name is 'slot_' followed by the slot name and whose signature
3470 is whatever is required for that slot. These slot functions look
3471 up the corresponding method in the type's dictionary and call it.
3472 The slot functions have to take care of the various peculiarities
3473 of the mapping between slots and special methods, such as mapping
3474 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3475 etc.) or mapping multiple slots to a single method (sq_item,
3476 mp_subscript <--> __getitem__). */
3477
Tim Peters6d6c1a32001-08-02 04:15:00 +00003478static void
3479override_slots(PyTypeObject *type, PyObject *dict)
3480{
3481 PySequenceMethods *sq = type->tp_as_sequence;
3482 PyMappingMethods *mp = type->tp_as_mapping;
3483 PyNumberMethods *nb = type->tp_as_number;
3484
Guido van Rossumdc91b992001-08-08 22:26:22 +00003485#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003486 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003487 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003488 }
3489
Guido van Rossumdc91b992001-08-08 22:26:22 +00003490#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003491 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003492 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003493 }
3494
Guido van Rossumdc91b992001-08-08 22:26:22 +00003495#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003496 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003497 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003498 }
3499
Guido van Rossumdc91b992001-08-08 22:26:22 +00003500#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003501 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003502 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003503 }
3504
Guido van Rossumdc91b992001-08-08 22:26:22 +00003505 SQSLOT("__len__", sq_length, slot_sq_length);
3506 SQSLOT("__add__", sq_concat, slot_sq_concat);
3507 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3508 SQSLOT("__getitem__", sq_item, slot_sq_item);
3509 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3510 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3511 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3512 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3513 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3514 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3515 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3516 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003517
Guido van Rossumdc91b992001-08-08 22:26:22 +00003518 MPSLOT("__len__", mp_length, slot_mp_length);
3519 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3520 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3521 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003522
Guido van Rossumdc91b992001-08-08 22:26:22 +00003523 NBSLOT("__add__", nb_add, slot_nb_add);
3524 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3525 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3526 NBSLOT("__div__", nb_divide, slot_nb_divide);
3527 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3528 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3529 NBSLOT("__pow__", nb_power, slot_nb_power);
3530 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3531 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3532 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3533 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3534 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3535 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3536 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3537 NBSLOT("__and__", nb_and, slot_nb_and);
3538 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3539 NBSLOT("__or__", nb_or, slot_nb_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003540 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003541 NBSLOT("__int__", nb_int, slot_nb_int);
3542 NBSLOT("__long__", nb_long, slot_nb_long);
3543 NBSLOT("__float__", nb_float, slot_nb_float);
3544 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3545 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3546 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3547 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3548 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3549 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3550 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3551 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3552 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3553 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3554 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3555 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3556 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3557 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3558 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3559 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3560 slot_nb_inplace_floor_divide);
3561 NBSLOT("__itruediv__", nb_inplace_true_divide,
3562 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003563
Guido van Rossum8e248182001-08-12 05:17:56 +00003564 if (dict == NULL ||
3565 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003566 PyDict_GetItemString(dict, "__repr__"))
3567 type->tp_print = NULL;
3568
Guido van Rossumab3b0342001-09-18 20:38:53 +00003569 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003570 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3571 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3572 TPSLOT("__call__", tp_call, slot_tp_call);
3573 TPSLOT("__str__", tp_str, slot_tp_str);
Guido van Rossum867a8d22001-09-21 19:29:08 +00003574 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003575 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003576 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3577 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3578 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3579 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3580 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3581 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3582 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3583 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3584 TPSLOT("next", tp_iternext, slot_tp_iternext);
3585 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3586 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3587 TPSLOT("__init__", tp_init, slot_tp_init);
3588 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003589}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003590
3591
3592/* Cooperative 'super' */
3593
3594typedef struct {
3595 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003596 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003597 PyObject *obj;
3598} superobject;
3599
Guido van Rossum6f799372001-09-20 20:46:19 +00003600static PyMemberDef super_members[] = {
3601 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3602 "the class invoking super()"},
3603 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3604 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003605 {0}
3606};
3607
Guido van Rossum705f0f52001-08-24 16:47:00 +00003608static void
3609super_dealloc(PyObject *self)
3610{
3611 superobject *su = (superobject *)self;
3612
Guido van Rossum048eb752001-10-02 21:24:57 +00003613 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003614 Py_XDECREF(su->obj);
3615 Py_XDECREF(su->type);
3616 self->ob_type->tp_free(self);
3617}
3618
3619static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003620super_repr(PyObject *self)
3621{
3622 superobject *su = (superobject *)self;
3623
3624 if (su->obj)
3625 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003626 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003627 su->type ? su->type->tp_name : "NULL",
3628 su->obj->ob_type->tp_name);
3629 else
3630 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003631 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003632 su->type ? su->type->tp_name : "NULL");
3633}
3634
3635static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003636super_getattro(PyObject *self, PyObject *name)
3637{
3638 superobject *su = (superobject *)self;
3639
3640 if (su->obj != NULL) {
3641 PyObject *mro, *res, *tmp;
3642 descrgetfunc f;
3643 int i, n;
3644
Guido van Rossume705ef12001-08-29 15:47:06 +00003645 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003646 if (mro == NULL)
3647 n = 0;
3648 else {
3649 assert(PyTuple_Check(mro));
3650 n = PyTuple_GET_SIZE(mro);
3651 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003652 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003653 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003654 break;
3655 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003656 if (i >= n && PyType_Check(su->obj)) {
3657 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003658 if (mro == NULL)
3659 n = 0;
3660 else {
3661 assert(PyTuple_Check(mro));
3662 n = PyTuple_GET_SIZE(mro);
3663 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003664 for (i = 0; i < n; i++) {
3665 if ((PyObject *)(su->type) ==
3666 PyTuple_GET_ITEM(mro, i))
3667 break;
3668 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003669 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003670 i++;
3671 res = NULL;
3672 for (; i < n; i++) {
3673 tmp = PyTuple_GET_ITEM(mro, i);
3674 assert(PyType_Check(tmp));
3675 res = PyDict_GetItem(
3676 ((PyTypeObject *)tmp)->tp_defined, name);
3677 if (res != NULL) {
3678 Py_INCREF(res);
3679 f = res->ob_type->tp_descr_get;
3680 if (f != NULL) {
3681 tmp = f(res, su->obj, res);
3682 Py_DECREF(res);
3683 res = tmp;
3684 }
3685 return res;
3686 }
3687 }
3688 }
3689 return PyObject_GenericGetAttr(self, name);
3690}
3691
3692static PyObject *
3693super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3694{
3695 superobject *su = (superobject *)self;
3696 superobject *new;
3697
3698 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3699 /* Not binding to an object, or already bound */
3700 Py_INCREF(self);
3701 return self;
3702 }
3703 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3704 if (new == NULL)
3705 return NULL;
3706 Py_INCREF(su->type);
3707 Py_INCREF(obj);
3708 new->type = su->type;
3709 new->obj = obj;
3710 return (PyObject *)new;
3711}
3712
3713static int
3714super_init(PyObject *self, PyObject *args, PyObject *kwds)
3715{
3716 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003717 PyTypeObject *type;
3718 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003719
3720 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3721 return -1;
3722 if (obj == Py_None)
3723 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003724 if (obj != NULL &&
3725 !PyType_IsSubtype(obj->ob_type, type) &&
3726 !(PyType_Check(obj) &&
3727 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003728 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003729 "super(type, obj): "
3730 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003731 return -1;
3732 }
3733 Py_INCREF(type);
3734 Py_XINCREF(obj);
3735 su->type = type;
3736 su->obj = obj;
3737 return 0;
3738}
3739
3740static char super_doc[] =
3741"super(type) -> unbound super object\n"
3742"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003743"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003744"Typical use to call a cooperative superclass method:\n"
3745"class C(B):\n"
3746" def meth(self, arg):\n"
3747" super(C, self).meth(arg)";
3748
Guido van Rossum048eb752001-10-02 21:24:57 +00003749static int
3750super_traverse(PyObject *self, visitproc visit, void *arg)
3751{
3752 superobject *su = (superobject *)self;
3753 int err;
3754
3755#define VISIT(SLOT) \
3756 if (SLOT) { \
3757 err = visit((PyObject *)(SLOT), arg); \
3758 if (err) \
3759 return err; \
3760 }
3761
3762 VISIT(su->obj);
3763 VISIT(su->type);
3764
3765#undef VISIT
3766
3767 return 0;
3768}
3769
Guido van Rossum705f0f52001-08-24 16:47:00 +00003770PyTypeObject PySuper_Type = {
3771 PyObject_HEAD_INIT(&PyType_Type)
3772 0, /* ob_size */
3773 "super", /* tp_name */
3774 sizeof(superobject), /* tp_basicsize */
3775 0, /* tp_itemsize */
3776 /* methods */
3777 super_dealloc, /* tp_dealloc */
3778 0, /* tp_print */
3779 0, /* tp_getattr */
3780 0, /* tp_setattr */
3781 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003782 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003783 0, /* tp_as_number */
3784 0, /* tp_as_sequence */
3785 0, /* tp_as_mapping */
3786 0, /* tp_hash */
3787 0, /* tp_call */
3788 0, /* tp_str */
3789 super_getattro, /* tp_getattro */
3790 0, /* tp_setattro */
3791 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00003792 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3793 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003794 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00003795 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003796 0, /* tp_clear */
3797 0, /* tp_richcompare */
3798 0, /* tp_weaklistoffset */
3799 0, /* tp_iter */
3800 0, /* tp_iternext */
3801 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003802 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003803 0, /* tp_getset */
3804 0, /* tp_base */
3805 0, /* tp_dict */
3806 super_descr_get, /* tp_descr_get */
3807 0, /* tp_descr_set */
3808 0, /* tp_dictoffset */
3809 super_init, /* tp_init */
3810 PyType_GenericAlloc, /* tp_alloc */
3811 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00003812 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003813};