blob: 9d1a3158463c8d9a8fb44b026a7f18273bf917aa [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
Tim Peters6d6c1a32001-08-02 04:15:00 +00007static struct memberlist type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00008 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
9 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
10 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
11 {"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
17 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
18 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
25 char *s;
26
27 s = strrchr(type->tp_name, '.');
28 if (s == NULL)
29 s = type->tp_name;
30 else
31 s++;
32 return PyString_FromString(s);
33}
34
35static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000036type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000037{
Guido van Rossumc3542212001-08-16 09:18:56 +000038 PyObject *mod;
39 char *s;
40
41 s = strrchr(type->tp_name, '.');
42 if (s != NULL)
43 return PyString_FromStringAndSize(type->tp_name,
44 (int)(s - type->tp_name));
45 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
46 return PyString_FromString("__builtin__");
47 mod = PyDict_GetItemString(type->tp_defined, "__module__");
48 if (mod != NULL && PyString_Check(mod)) {
49 Py_INCREF(mod);
50 return mod;
51 }
52 PyErr_SetString(PyExc_AttributeError, "__module__");
53 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000054}
55
56static PyObject *
57type_dict(PyTypeObject *type, void *context)
58{
59 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000060 Py_INCREF(Py_None);
61 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000062 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000063 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
64 Py_INCREF(type->tp_dict);
65 return type->tp_dict;
66 }
67 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000068}
69
Tim Peters6d6c1a32001-08-02 04:15:00 +000070static PyObject *
71type_defined(PyTypeObject *type, void *context)
72{
73 if (type->tp_defined == NULL) {
74 Py_INCREF(Py_None);
75 return Py_None;
76 }
77 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
78 Py_INCREF(type->tp_defined);
79 return type->tp_defined;
80 }
81 return PyDictProxy_New(type->tp_defined);
82}
83
84static PyObject *
85type_dynamic(PyTypeObject *type, void *context)
86{
87 PyObject *res;
88
89 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
90 Py_INCREF(res);
91 return res;
92}
93
94struct getsetlist type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000095 {"__name__", (getter)type_name, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000096 {"__module__", (getter)type_module, NULL, NULL},
97 {"__dict__", (getter)type_dict, NULL, NULL},
98 {"__defined__", (getter)type_defined, NULL, NULL},
99 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
100 {0}
101};
102
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000103static int
104type_compare(PyObject *v, PyObject *w)
105{
106 /* This is called with type objects only. So we
107 can just compare the addresses. */
108 Py_uintptr_t vv = (Py_uintptr_t)v;
109 Py_uintptr_t ww = (Py_uintptr_t)w;
110 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
111}
112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000114type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000115{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000116 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000117
118 mod = type_module(type, NULL);
119 if (mod == NULL)
120 PyErr_Clear();
121 else if (!PyString_Check(mod)) {
122 Py_DECREF(mod);
123 mod = NULL;
124 }
125 name = type_name(type, NULL);
126 if (name == NULL)
127 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000128
129 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
130 rtn = PyString_FromFormat("<type '%s.%s'>",
131 PyString_AS_STRING(mod),
132 PyString_AS_STRING(name));
133 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000134 else
Barry Warsaw7ce36942001-08-24 18:34:26 +0000135 rtn = PyString_FromFormat("<type '%s'>", type->tp_name);
136
Guido van Rossumc3542212001-08-16 09:18:56 +0000137 Py_XDECREF(mod);
138 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000139 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140}
141
Tim Peters6d6c1a32001-08-02 04:15:00 +0000142static PyObject *
143type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
144{
145 PyObject *obj;
146
147 if (type->tp_new == NULL) {
148 PyErr_Format(PyExc_TypeError,
149 "cannot create '%.100s' instances",
150 type->tp_name);
151 return NULL;
152 }
153
154 obj = type->tp_new(type, args, NULL);
155 if (obj != NULL) {
156 type = obj->ob_type;
157 if (type->tp_init != NULL &&
158 type->tp_init(obj, args, kwds) < 0) {
159 Py_DECREF(obj);
160 obj = NULL;
161 }
162 }
163 return obj;
164}
165
166PyObject *
167PyType_GenericAlloc(PyTypeObject *type, int nitems)
168{
169 int size;
170 void *mem;
171 PyObject *obj;
172
173 /* Inline PyObject_New() so we can zero the memory */
174 size = _PyObject_VAR_SIZE(type, nitems);
175 mem = PyObject_MALLOC(size);
176 if (mem == NULL)
177 return PyErr_NoMemory();
178 memset(mem, '\0', size);
179 if (PyType_IS_GC(type))
180 obj = PyObject_FROM_GC(mem);
181 else
182 obj = (PyObject *)mem;
183 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
184 Py_INCREF(type);
185 if (type->tp_itemsize == 0)
186 PyObject_INIT(obj, type);
187 else
188 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
189 if (PyType_IS_GC(type))
190 PyObject_GC_Init(obj);
191 return obj;
192}
193
194PyObject *
195PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
196{
197 return type->tp_alloc(type, 0);
198}
199
200/* Helper for subtyping */
201
202static void
203subtype_dealloc(PyObject *self)
204{
205 int dictoffset = self->ob_type->tp_dictoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000206 int weaklistoffset = self->ob_type->tp_weaklistoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000207 PyTypeObject *type, *base;
208 destructor f;
209
210 /* This exists so we can DECREF self->ob_type */
211
212 /* Find the nearest base with a different tp_dealloc */
213 type = self->ob_type;
214 base = type->tp_base;
215 while ((f = base->tp_dealloc) == subtype_dealloc) {
216 base = base->tp_base;
217 assert(base);
218 }
219
220 /* If we added a dict, DECREF it */
221 if (dictoffset && !base->tp_dictoffset) {
222 PyObject **dictptr = (PyObject **) ((char *)self + dictoffset);
223 PyObject *dict = *dictptr;
224 if (dict != NULL) {
225 Py_DECREF(dict);
226 *dictptr = NULL;
227 }
228 }
229
Guido van Rossum9676b222001-08-17 20:32:36 +0000230 /* If we added weaklist, we clear it */
231 if (weaklistoffset && !base->tp_weaklistoffset)
232 PyObject_ClearWeakRefs(self);
233
Tim Peters6d6c1a32001-08-02 04:15:00 +0000234 /* Finalize GC if the base doesn't do GC and we do */
235 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
236 PyObject_GC_Fini(self);
237
238 /* Call the base tp_dealloc() */
239 assert(f);
240 f(self);
241
242 /* Can't reference self beyond this point */
243 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
244 Py_DECREF(type);
245 }
246}
247
248staticforward void override_slots(PyTypeObject *type, PyObject *dict);
249staticforward PyTypeObject *solid_base(PyTypeObject *type);
250
251typedef struct {
252 PyTypeObject type;
253 PyNumberMethods as_number;
254 PySequenceMethods as_sequence;
255 PyMappingMethods as_mapping;
256 PyBufferProcs as_buffer;
257 PyObject *name, *slots;
258 struct memberlist members[1];
259} etype;
260
261/* type test with subclassing support */
262
263int
264PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
265{
266 PyObject *mro;
267
268 mro = a->tp_mro;
269 if (mro != NULL) {
270 /* Deal with multiple inheritance without recursion
271 by walking the MRO tuple */
272 int i, n;
273 assert(PyTuple_Check(mro));
274 n = PyTuple_GET_SIZE(mro);
275 for (i = 0; i < n; i++) {
276 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
277 return 1;
278 }
279 return 0;
280 }
281 else {
282 /* a is not completely initilized yet; follow tp_base */
283 do {
284 if (a == b)
285 return 1;
286 a = a->tp_base;
287 } while (a != NULL);
288 return b == &PyBaseObject_Type;
289 }
290}
291
Guido van Rossum60718732001-08-28 17:47:51 +0000292/* Internal routine to do a method lookup in the type
293 without looking in the instance dictionary
294 (so we can't use PyObject_GetAttr) but still binding
295 it to the instance. The arguments are the object,
296 the method name as a C string, and the address of a
297 static variable used to cache the interned Python string. */
298
299static PyObject *
300lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
301{
302 PyObject *res;
303
304 if (*attrobj == NULL) {
305 *attrobj = PyString_InternFromString(attrstr);
306 if (*attrobj == NULL)
307 return NULL;
308 }
309 res = _PyType_Lookup(self->ob_type, *attrobj);
310 if (res == NULL)
311 PyErr_SetObject(PyExc_AttributeError, *attrobj);
312 else {
313 descrgetfunc f;
314 if ((f = res->ob_type->tp_descr_get) == NULL)
315 Py_INCREF(res);
316 else
317 res = f(res, self, (PyObject *)(self->ob_type));
318 }
319 return res;
320}
321
Guido van Rossum2730b132001-08-28 18:22:14 +0000322/* A variation of PyObject_CallMethod that uses lookup_method()
323 instead of PyObject_GetAttrString(). This uses the same convention
324 as lookup_method to cache the interned name string object. */
325
326PyObject *
327call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
328{
329 va_list va;
330 PyObject *args, *func = 0, *retval;
331 PyObject *dummy_str = NULL;
332 va_start(va, format);
333
334 func = lookup_method(o, name, &dummy_str);
335 Py_XDECREF(dummy_str);
336 if (func == NULL) {
337 va_end(va);
338 PyErr_SetString(PyExc_AttributeError, name);
339 return 0;
340 }
341
342 if (format && *format)
343 args = Py_VaBuildValue(format, va);
344 else
345 args = PyTuple_New(0);
346
347 va_end(va);
348
349 if (!args)
350 return NULL;
351
352 if (!PyTuple_Check(args)) {
353 PyObject *a;
354
355 a = PyTuple_New(1);
356 if (a == NULL)
357 return NULL;
358 if (PyTuple_SetItem(a, 0, args) < 0)
359 return NULL;
360 args = a;
361 }
362
363 retval = PyObject_CallObject(func, args);
364
365 Py_DECREF(args);
366 Py_DECREF(func);
367
368 return retval;
369}
370
Tim Peters6d6c1a32001-08-02 04:15:00 +0000371/* Method resolution order algorithm from "Putting Metaclasses to Work"
372 by Forman and Danforth (Addison-Wesley 1999). */
373
374static int
375conservative_merge(PyObject *left, PyObject *right)
376{
377 int left_size;
378 int right_size;
379 int i, j, r, ok;
380 PyObject *temp, *rr;
381
382 assert(PyList_Check(left));
383 assert(PyList_Check(right));
384
385 again:
386 left_size = PyList_GET_SIZE(left);
387 right_size = PyList_GET_SIZE(right);
388 for (i = 0; i < left_size; i++) {
389 for (j = 0; j < right_size; j++) {
390 if (PyList_GET_ITEM(left, i) ==
391 PyList_GET_ITEM(right, j)) {
392 /* found a merge point */
393 temp = PyList_New(0);
394 if (temp == NULL)
395 return -1;
396 for (r = 0; r < j; r++) {
397 rr = PyList_GET_ITEM(right, r);
398 ok = PySequence_Contains(left, rr);
399 if (ok < 0) {
400 Py_DECREF(temp);
401 return -1;
402 }
403 if (!ok) {
404 ok = PyList_Append(temp, rr);
405 if (ok < 0) {
406 Py_DECREF(temp);
407 return -1;
408 }
409 }
410 }
411 ok = PyList_SetSlice(left, i, i, temp);
412 Py_DECREF(temp);
413 if (ok < 0)
414 return -1;
415 ok = PyList_SetSlice(right, 0, j+1, NULL);
416 if (ok < 0)
417 return -1;
418 goto again;
419 }
420 }
421 }
422 return PyList_SetSlice(left, left_size, left_size, right);
423}
424
425static int
426serious_order_disagreements(PyObject *left, PyObject *right)
427{
428 return 0; /* XXX later -- for now, we cheat: "don't do that" */
429}
430
431static PyObject *
432mro_implementation(PyTypeObject *type)
433{
434 int i, n, ok;
435 PyObject *bases, *result;
436
437 bases = type->tp_bases;
438 n = PyTuple_GET_SIZE(bases);
439 result = Py_BuildValue("[O]", (PyObject *)type);
440 if (result == NULL)
441 return NULL;
442 for (i = 0; i < n; i++) {
443 PyTypeObject *base =
444 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
445 PyObject *parentMRO = PySequence_List(base->tp_mro);
446 if (parentMRO == NULL) {
447 Py_DECREF(result);
448 return NULL;
449 }
450 if (serious_order_disagreements(result, parentMRO)) {
451 Py_DECREF(result);
452 return NULL;
453 }
454 ok = conservative_merge(result, parentMRO);
455 Py_DECREF(parentMRO);
456 if (ok < 0) {
457 Py_DECREF(result);
458 return NULL;
459 }
460 }
461 return result;
462}
463
464static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000465mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000466{
467 PyTypeObject *type = (PyTypeObject *)self;
468
Tim Peters6d6c1a32001-08-02 04:15:00 +0000469 return mro_implementation(type);
470}
471
472static int
473mro_internal(PyTypeObject *type)
474{
475 PyObject *mro, *result, *tuple;
476
477 if (type->ob_type == &PyType_Type) {
478 result = mro_implementation(type);
479 }
480 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000481 static PyObject *mro_str;
482 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000483 if (mro == NULL)
484 return -1;
485 result = PyObject_CallObject(mro, NULL);
486 Py_DECREF(mro);
487 }
488 if (result == NULL)
489 return -1;
490 tuple = PySequence_Tuple(result);
491 Py_DECREF(result);
492 type->tp_mro = tuple;
493 return 0;
494}
495
496
497/* Calculate the best base amongst multiple base classes.
498 This is the first one that's on the path to the "solid base". */
499
500static PyTypeObject *
501best_base(PyObject *bases)
502{
503 int i, n;
504 PyTypeObject *base, *winner, *candidate, *base_i;
505
506 assert(PyTuple_Check(bases));
507 n = PyTuple_GET_SIZE(bases);
508 assert(n > 0);
509 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
510 winner = &PyBaseObject_Type;
511 for (i = 0; i < n; i++) {
512 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
513 if (!PyType_Check((PyObject *)base_i)) {
514 PyErr_SetString(
515 PyExc_TypeError,
516 "bases must be types");
517 return NULL;
518 }
519 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000520 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000521 return NULL;
522 }
523 candidate = solid_base(base_i);
524 if (PyType_IsSubtype(winner, candidate))
525 ;
526 else if (PyType_IsSubtype(candidate, winner)) {
527 winner = candidate;
528 base = base_i;
529 }
530 else {
531 PyErr_SetString(
532 PyExc_TypeError,
533 "multiple bases have "
534 "instance lay-out conflict");
535 return NULL;
536 }
537 }
538 assert(base != NULL);
539 return base;
540}
541
542static int
543extra_ivars(PyTypeObject *type, PyTypeObject *base)
544{
Guido van Rossum9676b222001-08-17 20:32:36 +0000545 size_t t_size = PyType_BASICSIZE(type);
546 size_t b_size = PyType_BASICSIZE(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000547
Guido van Rossum9676b222001-08-17 20:32:36 +0000548 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000549 if (type->tp_itemsize || base->tp_itemsize) {
550 /* If itemsize is involved, stricter rules */
551 return t_size != b_size ||
552 type->tp_itemsize != base->tp_itemsize;
553 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000554 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
555 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
556 t_size -= sizeof(PyObject *);
557 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
558 type->tp_dictoffset + sizeof(PyObject *) == t_size)
559 t_size -= sizeof(PyObject *);
560
561 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000562}
563
564static PyTypeObject *
565solid_base(PyTypeObject *type)
566{
567 PyTypeObject *base;
568
569 if (type->tp_base)
570 base = solid_base(type->tp_base);
571 else
572 base = &PyBaseObject_Type;
573 if (extra_ivars(type, base))
574 return type;
575 else
576 return base;
577}
578
579staticforward void object_dealloc(PyObject *);
580staticforward int object_init(PyObject *, PyObject *, PyObject *);
581
582static PyObject *
583type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
584{
585 PyObject *name, *bases, *dict;
586 static char *kwlist[] = {"name", "bases", "dict", 0};
587 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000588 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589 etype *et;
590 struct memberlist *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000591 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000592
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000593 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594 if (metatype == &PyType_Type &&
595 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
596 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000597 PyObject *x = PyTuple_GET_ITEM(args, 0);
598 Py_INCREF(x->ob_type);
599 return (PyObject *) x->ob_type;
600 }
601
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000602 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000603 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
604 &name,
605 &PyTuple_Type, &bases,
606 &PyDict_Type, &dict))
607 return NULL;
608
609 /* Determine the proper metatype to deal with this,
610 and check for metatype conflicts while we're at it.
611 Note that if some other metatype wins to contract,
612 it's possible that its instances are not types. */
613 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000614 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000615 for (i = 0; i < nbases; i++) {
616 tmp = PyTuple_GET_ITEM(bases, i);
617 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000618 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000619 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000620 if (PyType_IsSubtype(tmptype, winner)) {
621 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000622 continue;
623 }
624 PyErr_SetString(PyExc_TypeError,
625 "metatype conflict among bases");
626 return NULL;
627 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000628 if (winner != metatype) {
629 if (winner->tp_new != type_new) /* Pass it to the winner */
630 return winner->tp_new(winner, args, kwds);
631 metatype = winner;
632 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000633
634 /* Adjust for empty tuple bases */
635 if (nbases == 0) {
636 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
637 if (bases == NULL)
638 return NULL;
639 nbases = 1;
640 }
641 else
642 Py_INCREF(bases);
643
644 /* XXX From here until type is allocated, "return NULL" leaks bases! */
645
646 /* Calculate best base, and check that all bases are type objects */
647 base = best_base(bases);
648 if (base == NULL)
649 return NULL;
650 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
651 PyErr_Format(PyExc_TypeError,
652 "type '%.100s' is not an acceptable base type",
653 base->tp_name);
654 return NULL;
655 }
656
Guido van Rossum1a493502001-08-17 16:47:50 +0000657 /* Should this be a dynamic class (i.e. modifiable __dict__)?
658 Look in two places for a variable named __dynamic__:
659 1) in the class dict
660 2) in the module dict (globals)
661 The first variable that is an int >= 0 is used.
662 Otherwise, a default is calculated from the base classes:
663 if any base class is dynamic, this class is dynamic; otherwise
664 it is static. */
665 dynamic = -1; /* Not yet determined */
666 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000667 tmp = PyDict_GetItemString(dict, "__dynamic__");
668 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000669 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000670 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000671 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000672 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000673 if (dynamic < 0) {
674 /* Look in the module globals */
675 tmp = PyEval_GetGlobals();
676 if (tmp != NULL) {
677 tmp = PyDict_GetItemString(tmp, "__dynamic__");
678 if (tmp != NULL) {
679 dynamic = PyInt_AsLong(tmp);
680 if (dynamic < 0)
681 PyErr_Clear();
682 }
683 }
684 }
685 if (dynamic < 0) {
686 /* Make a new class dynamic if any of its bases is
687 dynamic. This is not always the same as inheriting
688 the __dynamic__ class attribute! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000689 dynamic = 0;
690 for (i = 0; i < nbases; i++) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000691 tmptype = (PyTypeObject *)
692 PyTuple_GET_ITEM(bases, i);
693 if (tmptype->tp_flags &
694 Py_TPFLAGS_DYNAMICTYPE) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000695 dynamic = 1;
696 break;
697 }
698 }
699 }
700
701 /* Check for a __slots__ sequence variable in dict, and count it */
702 slots = PyDict_GetItemString(dict, "__slots__");
703 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000704 add_dict = 0;
705 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000706 if (slots != NULL) {
707 /* Make it into a tuple */
708 if (PyString_Check(slots))
709 slots = Py_BuildValue("(O)", slots);
710 else
711 slots = PySequence_Tuple(slots);
712 if (slots == NULL)
713 return NULL;
714 nslots = PyTuple_GET_SIZE(slots);
715 for (i = 0; i < nslots; i++) {
716 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
717 PyErr_SetString(PyExc_TypeError,
718 "__slots__ must be a sequence of strings");
719 Py_DECREF(slots);
720 return NULL;
721 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000722 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000723 }
724 }
725 if (slots == NULL && base->tp_dictoffset == 0 &&
726 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000727 base->tp_setattro == NULL)) {
728 nslots++;
729 add_dict++;
730 }
731 if (slots == NULL && base->tp_weaklistoffset == 0) {
732 nslots++;
733 add_weak++;
734 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000735
736 /* XXX From here until type is safely allocated,
737 "return NULL" may leak slots! */
738
739 /* Allocate the type object */
740 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
741 if (type == NULL)
742 return NULL;
743
744 /* Keep name and slots alive in the extended type object */
745 et = (etype *)type;
746 Py_INCREF(name);
747 et->name = name;
748 et->slots = slots;
749
Guido van Rossumdc91b992001-08-08 22:26:22 +0000750 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000751 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
752 Py_TPFLAGS_BASETYPE;
753 if (dynamic)
754 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000755
756 /* It's a new-style number unless it specifically inherits any
757 old-style numeric behavior */
758 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
759 (base->tp_as_number == NULL))
760 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
761
762 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000763 type->tp_as_number = &et->as_number;
764 type->tp_as_sequence = &et->as_sequence;
765 type->tp_as_mapping = &et->as_mapping;
766 type->tp_as_buffer = &et->as_buffer;
767 type->tp_name = PyString_AS_STRING(name);
768
769 /* Set tp_base and tp_bases */
770 type->tp_bases = bases;
771 Py_INCREF(base);
772 type->tp_base = base;
773
774 /* Initialize tp_defined from passed-in dict */
775 type->tp_defined = dict = PyDict_Copy(dict);
776 if (dict == NULL) {
777 Py_DECREF(type);
778 return NULL;
779 }
780
Guido van Rossumc3542212001-08-16 09:18:56 +0000781 /* Set __module__ in the dict */
782 if (PyDict_GetItemString(dict, "__module__") == NULL) {
783 tmp = PyEval_GetGlobals();
784 if (tmp != NULL) {
785 tmp = PyDict_GetItemString(tmp, "__name__");
786 if (tmp != NULL) {
787 if (PyDict_SetItemString(dict, "__module__",
788 tmp) < 0)
789 return NULL;
790 }
791 }
792 }
793
Tim Peters6d6c1a32001-08-02 04:15:00 +0000794 /* Special-case __new__: if it's a plain function,
795 make it a static function */
796 tmp = PyDict_GetItemString(dict, "__new__");
797 if (tmp != NULL && PyFunction_Check(tmp)) {
798 tmp = PyStaticMethod_New(tmp);
799 if (tmp == NULL) {
800 Py_DECREF(type);
801 return NULL;
802 }
803 PyDict_SetItemString(dict, "__new__", tmp);
804 Py_DECREF(tmp);
805 }
806
807 /* Add descriptors for custom slots from __slots__, or for __dict__ */
808 mp = et->members;
809 slotoffset = PyType_BASICSIZE(base);
810 if (slots != NULL) {
811 for (i = 0; i < nslots; i++, mp++) {
812 mp->name = PyString_AS_STRING(
813 PyTuple_GET_ITEM(slots, i));
814 mp->type = T_OBJECT;
815 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000816 if (base->tp_weaklistoffset == 0 &&
817 strcmp(mp->name, "__weakref__") == 0)
818 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819 slotoffset += sizeof(PyObject *);
820 }
821 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000822 else {
823 if (add_dict) {
824 type->tp_dictoffset = slotoffset;
825 mp->name = "__dict__";
826 mp->type = T_OBJECT;
827 mp->offset = slotoffset;
828 mp->readonly = 1;
829 mp++;
830 slotoffset += sizeof(PyObject *);
831 }
832 if (add_weak) {
833 type->tp_weaklistoffset = slotoffset;
834 mp->name = "__weakref__";
835 mp->type = T_OBJECT;
836 mp->offset = slotoffset;
837 mp->readonly = 1;
838 mp++;
839 slotoffset += sizeof(PyObject *);
840 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000841 }
842 type->tp_basicsize = slotoffset;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000843 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000844
845 /* Special case some slots */
846 if (type->tp_dictoffset != 0 || nslots > 0) {
847 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
848 type->tp_getattro = PyObject_GenericGetAttr;
849 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
850 type->tp_setattro = PyObject_GenericSetAttr;
851 }
852 type->tp_dealloc = subtype_dealloc;
853
854 /* Always override allocation strategy to use regular heap */
855 type->tp_alloc = PyType_GenericAlloc;
856 type->tp_free = _PyObject_Del;
857
858 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000859 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000860 Py_DECREF(type);
861 return NULL;
862 }
863
864 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +0000865 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
866 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000867
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 return (PyObject *)type;
869}
870
871/* Internal API to look for a name through the MRO.
872 This returns a borrowed reference, and doesn't set an exception! */
873PyObject *
874_PyType_Lookup(PyTypeObject *type, PyObject *name)
875{
876 int i, n;
877 PyObject *mro, *res, *dict;
878
879 /* For static types, look in tp_dict */
880 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
881 dict = type->tp_dict;
882 assert(dict && PyDict_Check(dict));
883 return PyDict_GetItem(dict, name);
884 }
885
886 /* For dynamic types, look in tp_defined of types in MRO */
887 mro = type->tp_mro;
888 assert(PyTuple_Check(mro));
889 n = PyTuple_GET_SIZE(mro);
890 for (i = 0; i < n; i++) {
891 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
892 assert(PyType_Check(type));
893 dict = type->tp_defined;
894 assert(dict && PyDict_Check(dict));
895 res = PyDict_GetItem(dict, name);
896 if (res != NULL)
897 return res;
898 }
899 return NULL;
900}
901
902/* This is similar to PyObject_GenericGetAttr(),
903 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
904static PyObject *
905type_getattro(PyTypeObject *type, PyObject *name)
906{
907 PyTypeObject *metatype = type->ob_type;
908 PyObject *descr, *res;
909 descrgetfunc f;
910
911 /* Initialize this type (we'll assume the metatype is initialized) */
912 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000913 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000914 return NULL;
915 }
916
917 /* Get a descriptor from the metatype */
918 descr = _PyType_Lookup(metatype, name);
919 f = NULL;
920 if (descr != NULL) {
921 f = descr->ob_type->tp_descr_get;
922 if (f != NULL && PyDescr_IsData(descr))
923 return f(descr,
924 (PyObject *)type, (PyObject *)metatype);
925 }
926
927 /* Look in tp_defined of this type and its bases */
928 res = _PyType_Lookup(type, name);
929 if (res != NULL) {
930 f = res->ob_type->tp_descr_get;
931 if (f != NULL)
932 return f(res, (PyObject *)NULL, (PyObject *)type);
933 Py_INCREF(res);
934 return res;
935 }
936
937 /* Use the descriptor from the metatype */
938 if (f != NULL) {
939 res = f(descr, (PyObject *)type, (PyObject *)metatype);
940 return res;
941 }
942 if (descr != NULL) {
943 Py_INCREF(descr);
944 return descr;
945 }
946
947 /* Give up */
948 PyErr_Format(PyExc_AttributeError,
949 "type object '%.50s' has no attribute '%.400s'",
950 type->tp_name, PyString_AS_STRING(name));
951 return NULL;
952}
953
954static int
955type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
956{
957 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
958 return PyObject_GenericSetAttr((PyObject *)type, name, value);
959 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
960 return -1;
961}
962
963static void
964type_dealloc(PyTypeObject *type)
965{
966 etype *et;
967
968 /* Assert this is a heap-allocated type object */
969 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
970 et = (etype *)type;
971 Py_XDECREF(type->tp_base);
972 Py_XDECREF(type->tp_dict);
973 Py_XDECREF(type->tp_bases);
974 Py_XDECREF(type->tp_mro);
975 Py_XDECREF(type->tp_defined);
976 /* XXX more? */
977 Py_XDECREF(et->name);
978 Py_XDECREF(et->slots);
979 type->ob_type->tp_free((PyObject *)type);
980}
981
982static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000983 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000984 "mro() -> list\nreturn a type's method resolution order"},
985 {0}
986};
987
988static char type_doc[] =
989"type(object) -> the object's type\n"
990"type(name, bases, dict) -> a new type";
991
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000992PyTypeObject PyType_Type = {
993 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000994 0, /* ob_size */
995 "type", /* tp_name */
996 sizeof(etype), /* tp_basicsize */
997 sizeof(struct memberlist), /* tp_itemsize */
998 (destructor)type_dealloc, /* tp_dealloc */
999 0, /* tp_print */
1000 0, /* tp_getattr */
1001 0, /* tp_setattr */
1002 type_compare, /* tp_compare */
1003 (reprfunc)type_repr, /* tp_repr */
1004 0, /* tp_as_number */
1005 0, /* tp_as_sequence */
1006 0, /* tp_as_mapping */
1007 (hashfunc)_Py_HashPointer, /* tp_hash */
1008 (ternaryfunc)type_call, /* tp_call */
1009 0, /* tp_str */
1010 (getattrofunc)type_getattro, /* tp_getattro */
1011 (setattrofunc)type_setattro, /* tp_setattro */
1012 0, /* tp_as_buffer */
1013 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1014 type_doc, /* tp_doc */
1015 0, /* tp_traverse */
1016 0, /* tp_clear */
1017 0, /* tp_richcompare */
1018 0, /* tp_weaklistoffset */
1019 0, /* tp_iter */
1020 0, /* tp_iternext */
1021 type_methods, /* tp_methods */
1022 type_members, /* tp_members */
1023 type_getsets, /* tp_getset */
1024 0, /* tp_base */
1025 0, /* tp_dict */
1026 0, /* tp_descr_get */
1027 0, /* tp_descr_set */
1028 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1029 0, /* tp_init */
1030 0, /* tp_alloc */
1031 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001032};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001033
1034
1035/* The base type of all types (eventually)... except itself. */
1036
1037static int
1038object_init(PyObject *self, PyObject *args, PyObject *kwds)
1039{
1040 return 0;
1041}
1042
1043static void
1044object_dealloc(PyObject *self)
1045{
1046 self->ob_type->tp_free(self);
1047}
1048
Guido van Rossum8e248182001-08-12 05:17:56 +00001049static PyObject *
1050object_repr(PyObject *self)
1051{
Guido van Rossum76e69632001-08-16 18:52:43 +00001052 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001053 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001054
Guido van Rossum76e69632001-08-16 18:52:43 +00001055 type = self->ob_type;
1056 mod = type_module(type, NULL);
1057 if (mod == NULL)
1058 PyErr_Clear();
1059 else if (!PyString_Check(mod)) {
1060 Py_DECREF(mod);
1061 mod = NULL;
1062 }
1063 name = type_name(type, NULL);
1064 if (name == NULL)
1065 return NULL;
1066 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Barry Warsaw7ce36942001-08-24 18:34:26 +00001067 rtn = PyString_FromFormat("<%s.%s instance at %p>",
1068 PyString_AS_STRING(mod),
1069 PyString_AS_STRING(name),
1070 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001071 else
Barry Warsaw7ce36942001-08-24 18:34:26 +00001072 rtn = PyString_FromFormat("<%s instance at %p>",
1073 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001074 Py_XDECREF(mod);
1075 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001076 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001077}
1078
Guido van Rossumb8f63662001-08-15 23:57:02 +00001079static PyObject *
1080object_str(PyObject *self)
1081{
1082 unaryfunc f;
1083
1084 f = self->ob_type->tp_repr;
1085 if (f == NULL)
1086 f = object_repr;
1087 return f(self);
1088}
1089
Guido van Rossum8e248182001-08-12 05:17:56 +00001090static long
1091object_hash(PyObject *self)
1092{
1093 return _Py_HashPointer(self);
1094}
Guido van Rossum8e248182001-08-12 05:17:56 +00001095
Tim Peters6d6c1a32001-08-02 04:15:00 +00001096static void
1097object_free(PyObject *self)
1098{
1099 PyObject_Del(self);
1100}
1101
1102static struct memberlist object_members[] = {
1103 {"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
1104 {0}
1105};
1106
1107PyTypeObject PyBaseObject_Type = {
1108 PyObject_HEAD_INIT(&PyType_Type)
1109 0, /* ob_size */
1110 "object", /* tp_name */
1111 sizeof(PyObject), /* tp_basicsize */
1112 0, /* tp_itemsize */
1113 (destructor)object_dealloc, /* tp_dealloc */
1114 0, /* tp_print */
1115 0, /* tp_getattr */
1116 0, /* tp_setattr */
1117 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001118 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119 0, /* tp_as_number */
1120 0, /* tp_as_sequence */
1121 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001122 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001124 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001125 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001126 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001127 0, /* tp_as_buffer */
1128 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1129 "The most base type", /* tp_doc */
1130 0, /* tp_traverse */
1131 0, /* tp_clear */
1132 0, /* tp_richcompare */
1133 0, /* tp_weaklistoffset */
1134 0, /* tp_iter */
1135 0, /* tp_iternext */
1136 0, /* tp_methods */
1137 object_members, /* tp_members */
1138 0, /* tp_getset */
1139 0, /* tp_base */
1140 0, /* tp_dict */
1141 0, /* tp_descr_get */
1142 0, /* tp_descr_set */
1143 0, /* tp_dictoffset */
1144 object_init, /* tp_init */
1145 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001146 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001147 object_free, /* tp_free */
1148};
1149
1150
1151/* Initialize the __dict__ in a type object */
1152
1153static int
1154add_methods(PyTypeObject *type, PyMethodDef *meth)
1155{
1156 PyObject *dict = type->tp_defined;
1157
1158 for (; meth->ml_name != NULL; meth++) {
1159 PyObject *descr;
1160 if (PyDict_GetItemString(dict, meth->ml_name))
1161 continue;
1162 descr = PyDescr_NewMethod(type, meth);
1163 if (descr == NULL)
1164 return -1;
1165 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1166 return -1;
1167 Py_DECREF(descr);
1168 }
1169 return 0;
1170}
1171
1172static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173add_members(PyTypeObject *type, struct memberlist *memb)
1174{
1175 PyObject *dict = type->tp_defined;
1176
1177 for (; memb->name != NULL; memb++) {
1178 PyObject *descr;
1179 if (PyDict_GetItemString(dict, memb->name))
1180 continue;
1181 descr = PyDescr_NewMember(type, memb);
1182 if (descr == NULL)
1183 return -1;
1184 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1185 return -1;
1186 Py_DECREF(descr);
1187 }
1188 return 0;
1189}
1190
1191static int
1192add_getset(PyTypeObject *type, struct getsetlist *gsp)
1193{
1194 PyObject *dict = type->tp_defined;
1195
1196 for (; gsp->name != NULL; gsp++) {
1197 PyObject *descr;
1198 if (PyDict_GetItemString(dict, gsp->name))
1199 continue;
1200 descr = PyDescr_NewGetSet(type, gsp);
1201
1202 if (descr == NULL)
1203 return -1;
1204 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1205 return -1;
1206 Py_DECREF(descr);
1207 }
1208 return 0;
1209}
1210
Guido van Rossum13d52f02001-08-10 21:24:08 +00001211static void
1212inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213{
1214 int oldsize, newsize;
1215
Guido van Rossum13d52f02001-08-10 21:24:08 +00001216 /* Special flag magic */
1217 if (!type->tp_as_buffer && base->tp_as_buffer) {
1218 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1219 type->tp_flags |=
1220 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1221 }
1222 if (!type->tp_as_sequence && base->tp_as_sequence) {
1223 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1224 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1225 }
1226 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1227 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1228 if ((!type->tp_as_number && base->tp_as_number) ||
1229 (!type->tp_as_sequence && base->tp_as_sequence)) {
1230 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1231 if (!type->tp_as_number && !type->tp_as_sequence) {
1232 type->tp_flags |= base->tp_flags &
1233 Py_TPFLAGS_HAVE_INPLACEOPS;
1234 }
1235 }
1236 /* Wow */
1237 }
1238 if (!type->tp_as_number && base->tp_as_number) {
1239 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1240 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1241 }
1242
1243 /* Copying basicsize is connected to the GC flags */
1244 oldsize = PyType_BASICSIZE(base);
1245 newsize = type->tp_basicsize ? PyType_BASICSIZE(type) : oldsize;
1246 if (!(type->tp_flags & Py_TPFLAGS_GC) &&
1247 (base->tp_flags & Py_TPFLAGS_GC) &&
1248 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1249 (!type->tp_traverse && !type->tp_clear)) {
1250 type->tp_flags |= Py_TPFLAGS_GC;
1251 if (type->tp_traverse == NULL)
1252 type->tp_traverse = base->tp_traverse;
1253 if (type->tp_clear == NULL)
1254 type->tp_clear = base->tp_clear;
1255 }
1256 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1257 if (base != &PyBaseObject_Type ||
1258 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1259 if (type->tp_new == NULL)
1260 type->tp_new = base->tp_new;
1261 }
1262 }
1263 PyType_SET_BASICSIZE(type, newsize);
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001264
1265 /* Copy other non-function slots */
1266
1267#undef COPYVAL
1268#define COPYVAL(SLOT) \
1269 if (type->SLOT == 0) type->SLOT = base->SLOT
1270
1271 COPYVAL(tp_itemsize);
1272 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1273 COPYVAL(tp_weaklistoffset);
1274 }
1275 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1276 COPYVAL(tp_dictoffset);
1277 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001278}
1279
1280static void
1281inherit_slots(PyTypeObject *type, PyTypeObject *base)
1282{
1283 PyTypeObject *basebase;
1284
1285#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286#undef COPYSLOT
1287#undef COPYNUM
1288#undef COPYSEQ
1289#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001290
1291#define SLOTDEFINED(SLOT) \
1292 (base->SLOT != 0 && \
1293 (basebase == NULL || base->SLOT != basebase->SLOT))
1294
Tim Peters6d6c1a32001-08-02 04:15:00 +00001295#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001296 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297
1298#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1299#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1300#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1301
Guido van Rossum13d52f02001-08-10 21:24:08 +00001302 /* This won't inherit indirect slots (from tp_as_number etc.)
1303 if type doesn't provide the space. */
1304
1305 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1306 basebase = base->tp_base;
1307 if (basebase->tp_as_number == NULL)
1308 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001309 COPYNUM(nb_add);
1310 COPYNUM(nb_subtract);
1311 COPYNUM(nb_multiply);
1312 COPYNUM(nb_divide);
1313 COPYNUM(nb_remainder);
1314 COPYNUM(nb_divmod);
1315 COPYNUM(nb_power);
1316 COPYNUM(nb_negative);
1317 COPYNUM(nb_positive);
1318 COPYNUM(nb_absolute);
1319 COPYNUM(nb_nonzero);
1320 COPYNUM(nb_invert);
1321 COPYNUM(nb_lshift);
1322 COPYNUM(nb_rshift);
1323 COPYNUM(nb_and);
1324 COPYNUM(nb_xor);
1325 COPYNUM(nb_or);
1326 COPYNUM(nb_coerce);
1327 COPYNUM(nb_int);
1328 COPYNUM(nb_long);
1329 COPYNUM(nb_float);
1330 COPYNUM(nb_oct);
1331 COPYNUM(nb_hex);
1332 COPYNUM(nb_inplace_add);
1333 COPYNUM(nb_inplace_subtract);
1334 COPYNUM(nb_inplace_multiply);
1335 COPYNUM(nb_inplace_divide);
1336 COPYNUM(nb_inplace_remainder);
1337 COPYNUM(nb_inplace_power);
1338 COPYNUM(nb_inplace_lshift);
1339 COPYNUM(nb_inplace_rshift);
1340 COPYNUM(nb_inplace_and);
1341 COPYNUM(nb_inplace_xor);
1342 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001343 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1344 COPYNUM(nb_true_divide);
1345 COPYNUM(nb_floor_divide);
1346 COPYNUM(nb_inplace_true_divide);
1347 COPYNUM(nb_inplace_floor_divide);
1348 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001349 }
1350
Guido van Rossum13d52f02001-08-10 21:24:08 +00001351 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1352 basebase = base->tp_base;
1353 if (basebase->tp_as_sequence == NULL)
1354 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355 COPYSEQ(sq_length);
1356 COPYSEQ(sq_concat);
1357 COPYSEQ(sq_repeat);
1358 COPYSEQ(sq_item);
1359 COPYSEQ(sq_slice);
1360 COPYSEQ(sq_ass_item);
1361 COPYSEQ(sq_ass_slice);
1362 COPYSEQ(sq_contains);
1363 COPYSEQ(sq_inplace_concat);
1364 COPYSEQ(sq_inplace_repeat);
1365 }
1366
Guido van Rossum13d52f02001-08-10 21:24:08 +00001367 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1368 basebase = base->tp_base;
1369 if (basebase->tp_as_mapping == NULL)
1370 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371 COPYMAP(mp_length);
1372 COPYMAP(mp_subscript);
1373 COPYMAP(mp_ass_subscript);
1374 }
1375
Guido van Rossum13d52f02001-08-10 21:24:08 +00001376 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001377
Tim Peters6d6c1a32001-08-02 04:15:00 +00001378 COPYSLOT(tp_dealloc);
1379 COPYSLOT(tp_print);
1380 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1381 type->tp_getattr = base->tp_getattr;
1382 type->tp_getattro = base->tp_getattro;
1383 }
1384 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1385 type->tp_setattr = base->tp_setattr;
1386 type->tp_setattro = base->tp_setattro;
1387 }
1388 /* tp_compare see tp_richcompare */
1389 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001390 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001391 COPYSLOT(tp_call);
1392 COPYSLOT(tp_str);
1393 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001394 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001395 if (type->tp_compare == NULL &&
1396 type->tp_richcompare == NULL &&
1397 type->tp_hash == NULL)
1398 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001399 type->tp_compare = base->tp_compare;
1400 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001401 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402 }
1403 }
1404 else {
1405 COPYSLOT(tp_compare);
1406 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1408 COPYSLOT(tp_iter);
1409 COPYSLOT(tp_iternext);
1410 }
1411 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1412 COPYSLOT(tp_descr_get);
1413 COPYSLOT(tp_descr_set);
1414 COPYSLOT(tp_dictoffset);
1415 COPYSLOT(tp_init);
1416 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001417 COPYSLOT(tp_free);
1418 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001419}
1420
Guido van Rossum13d52f02001-08-10 21:24:08 +00001421staticforward int add_operators(PyTypeObject *);
1422
Tim Peters6d6c1a32001-08-02 04:15:00 +00001423int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001424PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001425{
1426 PyObject *dict, *bases, *x;
1427 PyTypeObject *base;
1428 int i, n;
1429
Guido van Rossumd614f972001-08-10 17:39:49 +00001430 if (type->tp_flags & Py_TPFLAGS_READY) {
1431 assert(type->tp_dict != NULL);
1432 return 0;
1433 }
1434 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1435 assert(type->tp_dict == NULL);
1436
1437 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001438
1439 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1440 base = type->tp_base;
1441 if (base == NULL && type != &PyBaseObject_Type)
1442 base = type->tp_base = &PyBaseObject_Type;
1443
1444 /* Initialize tp_bases */
1445 bases = type->tp_bases;
1446 if (bases == NULL) {
1447 if (base == NULL)
1448 bases = PyTuple_New(0);
1449 else
1450 bases = Py_BuildValue("(O)", base);
1451 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001452 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453 type->tp_bases = bases;
1454 }
1455
1456 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001457 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001458 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001459 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001460 }
1461
1462 /* Initialize tp_defined */
1463 dict = type->tp_defined;
1464 if (dict == NULL) {
1465 dict = PyDict_New();
1466 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001467 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468 type->tp_defined = dict;
1469 }
1470
1471 /* Add type-specific descriptors to tp_defined */
1472 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001473 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001474 if (type->tp_methods != NULL) {
1475 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001476 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001477 }
1478 if (type->tp_members != NULL) {
1479 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001480 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001481 }
1482 if (type->tp_getset != NULL) {
1483 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001484 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001485 }
1486
1487 /* Temporarily make tp_dict the same object as tp_defined.
1488 (This is needed to call mro(), and can stay this way for
1489 dynamic types). */
1490 Py_INCREF(type->tp_defined);
1491 type->tp_dict = type->tp_defined;
1492
1493 /* Calculate method resolution order */
1494 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001495 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496 }
1497
Guido van Rossum13d52f02001-08-10 21:24:08 +00001498 /* Inherit special flags from dominant base */
1499 if (type->tp_base != NULL)
1500 inherit_special(type, type->tp_base);
1501
Tim Peters6d6c1a32001-08-02 04:15:00 +00001502 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001503 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001504 /* For a dynamic type, all slots are overridden */
1505 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001506 }
1507 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001508 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001509 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001510 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001511 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001512 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001513 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001514 bases = type->tp_mro;
1515 assert(bases != NULL);
1516 assert(PyTuple_Check(bases));
1517 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001518 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1520 assert(PyType_Check(base));
1521 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001522 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001523 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001524 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525 }
1526 }
1527
Guido van Rossum13d52f02001-08-10 21:24:08 +00001528 /* Some more special stuff */
1529 base = type->tp_base;
1530 if (base != NULL) {
1531 if (type->tp_as_number == NULL)
1532 type->tp_as_number = base->tp_as_number;
1533 if (type->tp_as_sequence == NULL)
1534 type->tp_as_sequence = base->tp_as_sequence;
1535 if (type->tp_as_mapping == NULL)
1536 type->tp_as_mapping = base->tp_as_mapping;
1537 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001538
Guido van Rossum13d52f02001-08-10 21:24:08 +00001539 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001540 assert(type->tp_dict != NULL);
1541 type->tp_flags =
1542 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001543 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001544
1545 error:
1546 type->tp_flags &= ~Py_TPFLAGS_READYING;
1547 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001548}
1549
1550
1551/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1552
1553/* There's a wrapper *function* for each distinct function typedef used
1554 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1555 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1556 Most tables have only one entry; the tables for binary operators have two
1557 entries, one regular and one with reversed arguments. */
1558
1559static PyObject *
1560wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1561{
1562 inquiry func = (inquiry)wrapped;
1563 int res;
1564
1565 if (!PyArg_ParseTuple(args, ""))
1566 return NULL;
1567 res = (*func)(self);
1568 if (res == -1 && PyErr_Occurred())
1569 return NULL;
1570 return PyInt_FromLong((long)res);
1571}
1572
1573static struct wrapperbase tab_len[] = {
1574 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1575 {0}
1576};
1577
1578static PyObject *
1579wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1580{
1581 binaryfunc func = (binaryfunc)wrapped;
1582 PyObject *other;
1583
1584 if (!PyArg_ParseTuple(args, "O", &other))
1585 return NULL;
1586 return (*func)(self, other);
1587}
1588
1589static PyObject *
1590wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1591{
1592 binaryfunc func = (binaryfunc)wrapped;
1593 PyObject *other;
1594
1595 if (!PyArg_ParseTuple(args, "O", &other))
1596 return NULL;
1597 return (*func)(other, self);
1598}
1599
1600#undef BINARY
1601#define BINARY(NAME, OP) \
1602static struct wrapperbase tab_##NAME[] = { \
1603 {"__" #NAME "__", \
1604 (wrapperfunc)wrap_binaryfunc, \
1605 "x.__" #NAME "__(y) <==> " #OP}, \
1606 {"__r" #NAME "__", \
1607 (wrapperfunc)wrap_binaryfunc_r, \
1608 "y.__r" #NAME "__(x) <==> " #OP}, \
1609 {0} \
1610}
1611
1612BINARY(add, "x+y");
1613BINARY(sub, "x-y");
1614BINARY(mul, "x*y");
1615BINARY(div, "x/y");
1616BINARY(mod, "x%y");
1617BINARY(divmod, "divmod(x,y)");
1618BINARY(lshift, "x<<y");
1619BINARY(rshift, "x>>y");
1620BINARY(and, "x&y");
1621BINARY(xor, "x^y");
1622BINARY(or, "x|y");
1623
1624static PyObject *
1625wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1626{
1627 ternaryfunc func = (ternaryfunc)wrapped;
1628 PyObject *other;
1629 PyObject *third = Py_None;
1630
1631 /* Note: This wrapper only works for __pow__() */
1632
1633 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1634 return NULL;
1635 return (*func)(self, other, third);
1636}
1637
1638#undef TERNARY
1639#define TERNARY(NAME, OP) \
1640static struct wrapperbase tab_##NAME[] = { \
1641 {"__" #NAME "__", \
1642 (wrapperfunc)wrap_ternaryfunc, \
1643 "x.__" #NAME "__(y, z) <==> " #OP}, \
1644 {"__r" #NAME "__", \
1645 (wrapperfunc)wrap_ternaryfunc, \
1646 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1647 {0} \
1648}
1649
1650TERNARY(pow, "(x**y) % z");
1651
1652#undef UNARY
1653#define UNARY(NAME, OP) \
1654static struct wrapperbase tab_##NAME[] = { \
1655 {"__" #NAME "__", \
1656 (wrapperfunc)wrap_unaryfunc, \
1657 "x.__" #NAME "__() <==> " #OP}, \
1658 {0} \
1659}
1660
1661static PyObject *
1662wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1663{
1664 unaryfunc func = (unaryfunc)wrapped;
1665
1666 if (!PyArg_ParseTuple(args, ""))
1667 return NULL;
1668 return (*func)(self);
1669}
1670
1671UNARY(neg, "-x");
1672UNARY(pos, "+x");
1673UNARY(abs, "abs(x)");
1674UNARY(nonzero, "x != 0");
1675UNARY(invert, "~x");
1676UNARY(int, "int(x)");
1677UNARY(long, "long(x)");
1678UNARY(float, "float(x)");
1679UNARY(oct, "oct(x)");
1680UNARY(hex, "hex(x)");
1681
1682#undef IBINARY
1683#define IBINARY(NAME, OP) \
1684static struct wrapperbase tab_##NAME[] = { \
1685 {"__" #NAME "__", \
1686 (wrapperfunc)wrap_binaryfunc, \
1687 "x.__" #NAME "__(y) <==> " #OP}, \
1688 {0} \
1689}
1690
1691IBINARY(iadd, "x+=y");
1692IBINARY(isub, "x-=y");
1693IBINARY(imul, "x*=y");
1694IBINARY(idiv, "x/=y");
1695IBINARY(imod, "x%=y");
1696IBINARY(ilshift, "x<<=y");
1697IBINARY(irshift, "x>>=y");
1698IBINARY(iand, "x&=y");
1699IBINARY(ixor, "x^=y");
1700IBINARY(ior, "x|=y");
1701
1702#undef ITERNARY
1703#define ITERNARY(NAME, OP) \
1704static struct wrapperbase tab_##NAME[] = { \
1705 {"__" #NAME "__", \
1706 (wrapperfunc)wrap_ternaryfunc, \
1707 "x.__" #NAME "__(y) <==> " #OP}, \
1708 {0} \
1709}
1710
1711ITERNARY(ipow, "x = (x**y) % z");
1712
1713static struct wrapperbase tab_getitem[] = {
1714 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1715 "x.__getitem__(y) <==> x[y]"},
1716 {0}
1717};
1718
1719static PyObject *
1720wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1721{
1722 intargfunc func = (intargfunc)wrapped;
1723 int i;
1724
1725 if (!PyArg_ParseTuple(args, "i", &i))
1726 return NULL;
1727 return (*func)(self, i);
1728}
1729
1730static struct wrapperbase tab_mul_int[] = {
1731 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1732 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1733 {0}
1734};
1735
1736static struct wrapperbase tab_concat[] = {
1737 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1738 {0}
1739};
1740
1741static struct wrapperbase tab_imul_int[] = {
1742 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1743 {0}
1744};
1745
Guido van Rossum5d815f32001-08-17 21:57:47 +00001746static int
1747getindex(PyObject *self, PyObject *arg)
1748{
1749 int i;
1750
1751 i = PyInt_AsLong(arg);
1752 if (i == -1 && PyErr_Occurred())
1753 return -1;
1754 if (i < 0) {
1755 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
1756 if (sq && sq->sq_length) {
1757 int n = (*sq->sq_length)(self);
1758 if (n < 0)
1759 return -1;
1760 i += n;
1761 }
1762 }
1763 return i;
1764}
1765
1766static PyObject *
1767wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
1768{
1769 intargfunc func = (intargfunc)wrapped;
1770 PyObject *arg;
1771 int i;
1772
1773 if (!PyArg_ParseTuple(args, "O", &arg))
1774 return NULL;
1775 i = getindex(self, arg);
1776 if (i == -1 && PyErr_Occurred())
1777 return NULL;
1778 return (*func)(self, i);
1779}
1780
Tim Peters6d6c1a32001-08-02 04:15:00 +00001781static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001782 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783 "x.__getitem__(i) <==> x[i]"},
1784 {0}
1785};
1786
1787static PyObject *
1788wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1789{
1790 intintargfunc func = (intintargfunc)wrapped;
1791 int i, j;
1792
1793 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1794 return NULL;
1795 return (*func)(self, i, j);
1796}
1797
1798static struct wrapperbase tab_getslice[] = {
1799 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1800 "x.__getslice__(i, j) <==> x[i:j]"},
1801 {0}
1802};
1803
1804static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001805wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001806{
1807 intobjargproc func = (intobjargproc)wrapped;
1808 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001809 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810
Guido van Rossum5d815f32001-08-17 21:57:47 +00001811 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
1812 return NULL;
1813 i = getindex(self, arg);
1814 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815 return NULL;
1816 res = (*func)(self, i, value);
1817 if (res == -1 && PyErr_Occurred())
1818 return NULL;
1819 Py_INCREF(Py_None);
1820 return Py_None;
1821}
1822
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001823static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001824wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001825{
1826 intobjargproc func = (intobjargproc)wrapped;
1827 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001828 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001829
Guido van Rossum5d815f32001-08-17 21:57:47 +00001830 if (!PyArg_ParseTuple(args, "O", &arg))
1831 return NULL;
1832 i = getindex(self, arg);
1833 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001834 return NULL;
1835 res = (*func)(self, i, NULL);
1836 if (res == -1 && PyErr_Occurred())
1837 return NULL;
1838 Py_INCREF(Py_None);
1839 return Py_None;
1840}
1841
Tim Peters6d6c1a32001-08-02 04:15:00 +00001842static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001843 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00001845 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001846 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847 {0}
1848};
1849
1850static PyObject *
1851wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1852{
1853 intintobjargproc func = (intintobjargproc)wrapped;
1854 int i, j, res;
1855 PyObject *value;
1856
1857 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1858 return NULL;
1859 res = (*func)(self, i, j, value);
1860 if (res == -1 && PyErr_Occurred())
1861 return NULL;
1862 Py_INCREF(Py_None);
1863 return Py_None;
1864}
1865
1866static struct wrapperbase tab_setslice[] = {
1867 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1868 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1869 {0}
1870};
1871
1872/* XXX objobjproc is a misnomer; should be objargpred */
1873static PyObject *
1874wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1875{
1876 objobjproc func = (objobjproc)wrapped;
1877 int res;
1878 PyObject *value;
1879
1880 if (!PyArg_ParseTuple(args, "O", &value))
1881 return NULL;
1882 res = (*func)(self, value);
1883 if (res == -1 && PyErr_Occurred())
1884 return NULL;
1885 return PyInt_FromLong((long)res);
1886}
1887
1888static struct wrapperbase tab_contains[] = {
1889 {"__contains__", (wrapperfunc)wrap_objobjproc,
1890 "x.__contains__(y) <==> y in x"},
1891 {0}
1892};
1893
1894static PyObject *
1895wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1896{
1897 objobjargproc func = (objobjargproc)wrapped;
1898 int res;
1899 PyObject *key, *value;
1900
1901 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1902 return NULL;
1903 res = (*func)(self, key, value);
1904 if (res == -1 && PyErr_Occurred())
1905 return NULL;
1906 Py_INCREF(Py_None);
1907 return Py_None;
1908}
1909
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001910static PyObject *
1911wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1912{
1913 objobjargproc func = (objobjargproc)wrapped;
1914 int res;
1915 PyObject *key;
1916
1917 if (!PyArg_ParseTuple(args, "O", &key))
1918 return NULL;
1919 res = (*func)(self, key, NULL);
1920 if (res == -1 && PyErr_Occurred())
1921 return NULL;
1922 Py_INCREF(Py_None);
1923 return Py_None;
1924}
1925
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926static struct wrapperbase tab_setitem[] = {
1927 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1928 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001929 {"__delitem__", (wrapperfunc)wrap_delitem,
1930 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001931 {0}
1932};
1933
1934static PyObject *
1935wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1936{
1937 cmpfunc func = (cmpfunc)wrapped;
1938 int res;
1939 PyObject *other;
1940
1941 if (!PyArg_ParseTuple(args, "O", &other))
1942 return NULL;
1943 res = (*func)(self, other);
1944 if (PyErr_Occurred())
1945 return NULL;
1946 return PyInt_FromLong((long)res);
1947}
1948
1949static struct wrapperbase tab_cmp[] = {
1950 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1951 "x.__cmp__(y) <==> cmp(x,y)"},
1952 {0}
1953};
1954
1955static struct wrapperbase tab_repr[] = {
1956 {"__repr__", (wrapperfunc)wrap_unaryfunc,
1957 "x.__repr__() <==> repr(x)"},
1958 {0}
1959};
1960
1961static struct wrapperbase tab_getattr[] = {
1962 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
1963 "x.__getattr__('name') <==> x.name"},
1964 {0}
1965};
1966
1967static PyObject *
1968wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
1969{
1970 setattrofunc func = (setattrofunc)wrapped;
1971 int res;
1972 PyObject *name, *value;
1973
1974 if (!PyArg_ParseTuple(args, "OO", &name, &value))
1975 return NULL;
1976 res = (*func)(self, name, value);
1977 if (res < 0)
1978 return NULL;
1979 Py_INCREF(Py_None);
1980 return Py_None;
1981}
1982
1983static PyObject *
1984wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
1985{
1986 setattrofunc func = (setattrofunc)wrapped;
1987 int res;
1988 PyObject *name;
1989
1990 if (!PyArg_ParseTuple(args, "O", &name))
1991 return NULL;
1992 res = (*func)(self, name, NULL);
1993 if (res < 0)
1994 return NULL;
1995 Py_INCREF(Py_None);
1996 return Py_None;
1997}
1998
1999static struct wrapperbase tab_setattr[] = {
2000 {"__setattr__", (wrapperfunc)wrap_setattr,
2001 "x.__setattr__('name', value) <==> x.name = value"},
2002 {"__delattr__", (wrapperfunc)wrap_delattr,
2003 "x.__delattr__('name') <==> del x.name"},
2004 {0}
2005};
2006
2007static PyObject *
2008wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2009{
2010 hashfunc func = (hashfunc)wrapped;
2011 long res;
2012
2013 if (!PyArg_ParseTuple(args, ""))
2014 return NULL;
2015 res = (*func)(self);
2016 if (res == -1 && PyErr_Occurred())
2017 return NULL;
2018 return PyInt_FromLong(res);
2019}
2020
2021static struct wrapperbase tab_hash[] = {
2022 {"__hash__", (wrapperfunc)wrap_hashfunc,
2023 "x.__hash__() <==> hash(x)"},
2024 {0}
2025};
2026
2027static PyObject *
2028wrap_call(PyObject *self, PyObject *args, void *wrapped)
2029{
2030 ternaryfunc func = (ternaryfunc)wrapped;
2031
2032 /* XXX What about keyword arguments? */
2033 return (*func)(self, args, NULL);
2034}
2035
2036static struct wrapperbase tab_call[] = {
2037 {"__call__", (wrapperfunc)wrap_call,
2038 "x.__call__(...) <==> x(...)"},
2039 {0}
2040};
2041
2042static struct wrapperbase tab_str[] = {
2043 {"__str__", (wrapperfunc)wrap_unaryfunc,
2044 "x.__str__() <==> str(x)"},
2045 {0}
2046};
2047
2048static PyObject *
2049wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2050{
2051 richcmpfunc func = (richcmpfunc)wrapped;
2052 PyObject *other;
2053
2054 if (!PyArg_ParseTuple(args, "O", &other))
2055 return NULL;
2056 return (*func)(self, other, op);
2057}
2058
2059#undef RICHCMP_WRAPPER
2060#define RICHCMP_WRAPPER(NAME, OP) \
2061static PyObject * \
2062richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2063{ \
2064 return wrap_richcmpfunc(self, args, wrapped, OP); \
2065}
2066
Jack Jansen8e938b42001-08-08 15:29:49 +00002067RICHCMP_WRAPPER(lt, Py_LT)
2068RICHCMP_WRAPPER(le, Py_LE)
2069RICHCMP_WRAPPER(eq, Py_EQ)
2070RICHCMP_WRAPPER(ne, Py_NE)
2071RICHCMP_WRAPPER(gt, Py_GT)
2072RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002073
2074#undef RICHCMP_ENTRY
2075#define RICHCMP_ENTRY(NAME, EXPR) \
2076 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2077 "x.__" #NAME "__(y) <==> " EXPR}
2078
2079static struct wrapperbase tab_richcmp[] = {
2080 RICHCMP_ENTRY(lt, "x<y"),
2081 RICHCMP_ENTRY(le, "x<=y"),
2082 RICHCMP_ENTRY(eq, "x==y"),
2083 RICHCMP_ENTRY(ne, "x!=y"),
2084 RICHCMP_ENTRY(gt, "x>y"),
2085 RICHCMP_ENTRY(ge, "x>=y"),
2086 {0}
2087};
2088
2089static struct wrapperbase tab_iter[] = {
2090 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2091 {0}
2092};
2093
2094static PyObject *
2095wrap_next(PyObject *self, PyObject *args, void *wrapped)
2096{
2097 unaryfunc func = (unaryfunc)wrapped;
2098 PyObject *res;
2099
2100 if (!PyArg_ParseTuple(args, ""))
2101 return NULL;
2102 res = (*func)(self);
2103 if (res == NULL && !PyErr_Occurred())
2104 PyErr_SetNone(PyExc_StopIteration);
2105 return res;
2106}
2107
2108static struct wrapperbase tab_next[] = {
2109 {"next", (wrapperfunc)wrap_next,
2110 "x.next() -> the next value, or raise StopIteration"},
2111 {0}
2112};
2113
2114static PyObject *
2115wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2116{
2117 descrgetfunc func = (descrgetfunc)wrapped;
2118 PyObject *obj;
2119 PyObject *type = NULL;
2120
2121 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2122 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002123 return (*func)(self, obj, type);
2124}
2125
2126static struct wrapperbase tab_descr_get[] = {
2127 {"__get__", (wrapperfunc)wrap_descr_get,
2128 "descr.__get__(obj, type) -> value"},
2129 {0}
2130};
2131
2132static PyObject *
2133wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2134{
2135 descrsetfunc func = (descrsetfunc)wrapped;
2136 PyObject *obj, *value;
2137 int ret;
2138
2139 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2140 return NULL;
2141 ret = (*func)(self, obj, value);
2142 if (ret < 0)
2143 return NULL;
2144 Py_INCREF(Py_None);
2145 return Py_None;
2146}
2147
2148static struct wrapperbase tab_descr_set[] = {
2149 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2150 "descr.__set__(obj, value)"},
2151 {0}
2152};
2153
2154static PyObject *
2155wrap_init(PyObject *self, PyObject *args, void *wrapped)
2156{
2157 initproc func = (initproc)wrapped;
2158
2159 /* XXX What about keyword arguments? */
2160 if (func(self, args, NULL) < 0)
2161 return NULL;
2162 Py_INCREF(Py_None);
2163 return Py_None;
2164}
2165
2166static struct wrapperbase tab_init[] = {
2167 {"__init__", (wrapperfunc)wrap_init,
2168 "x.__init__(...) initializes x; "
2169 "see x.__type__.__doc__ for signature"},
2170 {0}
2171};
2172
2173static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002174tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002175{
Barry Warsaw60f01882001-08-22 19:24:42 +00002176 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002177 PyObject *arg0, *res;
2178
2179 if (self == NULL || !PyType_Check(self))
2180 Py_FatalError("__new__() called with non-type 'self'");
2181 type = (PyTypeObject *)self;
2182 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002183 PyErr_Format(PyExc_TypeError,
2184 "%s.__new__(): not enough arguments",
2185 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002186 return NULL;
2187 }
2188 arg0 = PyTuple_GET_ITEM(args, 0);
2189 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002190 PyErr_Format(PyExc_TypeError,
2191 "%s.__new__(X): X is not a type object (%s)",
2192 type->tp_name,
2193 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002194 return NULL;
2195 }
2196 subtype = (PyTypeObject *)arg0;
2197 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002198 PyErr_Format(PyExc_TypeError,
2199 "%s.__new__(%s): %s is not a subtype of %s",
2200 type->tp_name,
2201 subtype->tp_name,
2202 subtype->tp_name,
2203 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002204 return NULL;
2205 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002206
2207 /* Check that the use doesn't do something silly and unsafe like
2208 object.__new__(dictionary). To do this, we check that the
2209 most derived base that's not a heap type is this type. */
2210 staticbase = subtype;
2211 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2212 staticbase = staticbase->tp_base;
2213 if (staticbase != type) {
2214 PyErr_Format(PyExc_TypeError,
2215 "%s.__new__(%s) is not safe, use %s.__new__()",
2216 type->tp_name,
2217 subtype->tp_name,
2218 staticbase == NULL ? "?" : staticbase->tp_name);
2219 return NULL;
2220 }
2221
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002222 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2223 if (args == NULL)
2224 return NULL;
2225 res = type->tp_new(subtype, args, kwds);
2226 Py_DECREF(args);
2227 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228}
2229
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002230static struct PyMethodDef tp_new_methoddef[] = {
2231 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2232 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002233 {0}
2234};
2235
2236static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002237add_tp_new_wrapper(PyTypeObject *type)
2238{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002239 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002240
Guido van Rossumf040ede2001-08-07 16:40:56 +00002241 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2242 return 0;
2243 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002244 if (func == NULL)
2245 return -1;
2246 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2247}
2248
Guido van Rossum13d52f02001-08-10 21:24:08 +00002249static int
2250add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2251{
2252 PyObject *dict = type->tp_defined;
2253
2254 for (; wraps->name != NULL; wraps++) {
2255 PyObject *descr;
2256 if (PyDict_GetItemString(dict, wraps->name))
2257 continue;
2258 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2259 if (descr == NULL)
2260 return -1;
2261 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2262 return -1;
2263 Py_DECREF(descr);
2264 }
2265 return 0;
2266}
2267
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002268/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002269 dictionary with method descriptors for function slots. For each
2270 function slot (like tp_repr) that's defined in the type, one or
2271 more corresponding descriptors are added in the type's tp_defined
2272 dictionary under the appropriate name (like __repr__). Some
2273 function slots cause more than one descriptor to be added (for
2274 example, the nb_add slot adds both __add__ and __radd__
2275 descriptors) and some function slots compete for the same
2276 descriptor (for example both sq_item and mp_subscript generate a
2277 __getitem__ descriptor). This only adds new descriptors and
2278 doesn't overwrite entries in tp_defined that were previously
2279 defined. The descriptors contain a reference to the C function
2280 they must call, so that it's safe if they are copied into a
2281 subtype's __dict__ and the subtype has a different C function in
2282 its slot -- calling the method defined by the descriptor will call
2283 the C function that was used to create it, rather than the C
2284 function present in the slot when it is called. (This is important
2285 because a subtype may have a C function in the slot that calls the
2286 method from the dictionary, and we want to avoid infinite recursion
2287 here.) */
2288
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002289static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002290add_operators(PyTypeObject *type)
2291{
2292 PySequenceMethods *sq;
2293 PyMappingMethods *mp;
2294 PyNumberMethods *nb;
2295
2296#undef ADD
2297#define ADD(SLOT, TABLE) \
2298 if (SLOT) { \
2299 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2300 return -1; \
2301 }
2302
2303 if ((sq = type->tp_as_sequence) != NULL) {
2304 ADD(sq->sq_length, tab_len);
2305 ADD(sq->sq_concat, tab_concat);
2306 ADD(sq->sq_repeat, tab_mul_int);
2307 ADD(sq->sq_item, tab_getitem_int);
2308 ADD(sq->sq_slice, tab_getslice);
2309 ADD(sq->sq_ass_item, tab_setitem_int);
2310 ADD(sq->sq_ass_slice, tab_setslice);
2311 ADD(sq->sq_contains, tab_contains);
2312 ADD(sq->sq_inplace_concat, tab_iadd);
2313 ADD(sq->sq_inplace_repeat, tab_imul_int);
2314 }
2315
2316 if ((mp = type->tp_as_mapping) != NULL) {
2317 if (sq->sq_length == NULL)
2318 ADD(mp->mp_length, tab_len);
2319 ADD(mp->mp_subscript, tab_getitem);
2320 ADD(mp->mp_ass_subscript, tab_setitem);
2321 }
2322
2323 /* We don't support "old-style numbers" because their binary
2324 operators require that both arguments have the same type;
2325 the wrappers here only work for new-style numbers. */
2326 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2327 (nb = type->tp_as_number) != NULL) {
2328 ADD(nb->nb_add, tab_add);
2329 ADD(nb->nb_subtract, tab_sub);
2330 ADD(nb->nb_multiply, tab_mul);
2331 ADD(nb->nb_divide, tab_div);
2332 ADD(nb->nb_remainder, tab_mod);
2333 ADD(nb->nb_divmod, tab_divmod);
2334 ADD(nb->nb_power, tab_pow);
2335 ADD(nb->nb_negative, tab_neg);
2336 ADD(nb->nb_positive, tab_pos);
2337 ADD(nb->nb_absolute, tab_abs);
2338 ADD(nb->nb_nonzero, tab_nonzero);
2339 ADD(nb->nb_invert, tab_invert);
2340 ADD(nb->nb_lshift, tab_lshift);
2341 ADD(nb->nb_rshift, tab_rshift);
2342 ADD(nb->nb_and, tab_and);
2343 ADD(nb->nb_xor, tab_xor);
2344 ADD(nb->nb_or, tab_or);
2345 /* We don't support coerce() -- see above comment */
2346 ADD(nb->nb_int, tab_int);
2347 ADD(nb->nb_long, tab_long);
2348 ADD(nb->nb_float, tab_float);
2349 ADD(nb->nb_oct, tab_oct);
2350 ADD(nb->nb_hex, tab_hex);
2351 ADD(nb->nb_inplace_add, tab_iadd);
2352 ADD(nb->nb_inplace_subtract, tab_isub);
2353 ADD(nb->nb_inplace_multiply, tab_imul);
2354 ADD(nb->nb_inplace_divide, tab_idiv);
2355 ADD(nb->nb_inplace_remainder, tab_imod);
2356 ADD(nb->nb_inplace_power, tab_ipow);
2357 ADD(nb->nb_inplace_lshift, tab_ilshift);
2358 ADD(nb->nb_inplace_rshift, tab_irshift);
2359 ADD(nb->nb_inplace_and, tab_iand);
2360 ADD(nb->nb_inplace_xor, tab_ixor);
2361 ADD(nb->nb_inplace_or, tab_ior);
2362 }
2363
2364 ADD(type->tp_getattro, tab_getattr);
2365 ADD(type->tp_setattro, tab_setattr);
2366 ADD(type->tp_compare, tab_cmp);
2367 ADD(type->tp_repr, tab_repr);
2368 ADD(type->tp_hash, tab_hash);
2369 ADD(type->tp_call, tab_call);
2370 ADD(type->tp_str, tab_str);
2371 ADD(type->tp_richcompare, tab_richcmp);
2372 ADD(type->tp_iter, tab_iter);
2373 ADD(type->tp_iternext, tab_next);
2374 ADD(type->tp_descr_get, tab_descr_get);
2375 ADD(type->tp_descr_set, tab_descr_set);
2376 ADD(type->tp_init, tab_init);
2377
Guido van Rossumf040ede2001-08-07 16:40:56 +00002378 if (type->tp_new != NULL) {
2379 if (add_tp_new_wrapper(type) < 0)
2380 return -1;
2381 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002382
2383 return 0;
2384}
2385
Guido van Rossumf040ede2001-08-07 16:40:56 +00002386/* Slot wrappers that call the corresponding __foo__ slot. See comments
2387 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002388
Guido van Rossumdc91b992001-08-08 22:26:22 +00002389#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002391FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002392{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002393 static PyObject *cache_str; \
Guido van Rossum2730b132001-08-28 18:22:14 +00002394 return call_method(self, OPSTR, &cache_str, ""); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002395}
2396
Guido van Rossumdc91b992001-08-08 22:26:22 +00002397#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002398static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002399FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002400{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002401 static PyObject *cache_str; \
2402 return call_method(self, OPSTR, &cache_str, ARGCODES, arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002403}
2404
Guido van Rossumdc91b992001-08-08 22:26:22 +00002405
2406#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002407static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002408FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002409{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002410 static PyObject *cache_str, *rcache_str; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002411 if (self->ob_type->tp_as_number != NULL && \
2412 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2413 PyObject *r; \
Guido van Rossum2730b132001-08-28 18:22:14 +00002414 r = call_method( \
2415 self, OPSTR, &cache_str, "O", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002416 if (r != Py_NotImplemented || \
2417 other->ob_type == self->ob_type) \
2418 return r; \
2419 Py_DECREF(r); \
2420 } \
2421 if (other->ob_type->tp_as_number != NULL && \
2422 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossum2730b132001-08-28 18:22:14 +00002423 return call_method( \
2424 other, ROPSTR, &rcache_str, "O", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002425 } \
2426 Py_INCREF(Py_NotImplemented); \
2427 return Py_NotImplemented; \
2428}
2429
2430#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2431 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2432
2433#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2434static PyObject * \
2435FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2436{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002437 static PyObject *cache_str; \
2438 return call_method(self, OPSTR, &cache_str, ARGCODES, arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002439}
2440
2441static int
2442slot_sq_length(PyObject *self)
2443{
Guido van Rossum2730b132001-08-28 18:22:14 +00002444 static PyObject *len_str;
2445 PyObject *res = call_method(self, "__len__", &len_str, "");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002446
2447 if (res == NULL)
2448 return -1;
2449 return (int)PyInt_AsLong(res);
2450}
2451
Guido van Rossumdc91b992001-08-08 22:26:22 +00002452SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2453SLOT1(slot_sq_repeat, "__mul__", int, "i")
2454SLOT1(slot_sq_item, "__getitem__", int, "i")
2455SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002456
2457static int
2458slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2459{
2460 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002461 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002462
2463 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002464 res = call_method(self, "__delitem__", &delitem_str,
2465 "i", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002466 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002467 res = call_method(self, "__setitem__", &setitem_str,
2468 "iO", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002469 if (res == NULL)
2470 return -1;
2471 Py_DECREF(res);
2472 return 0;
2473}
2474
2475static int
2476slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2477{
2478 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002479 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002480
2481 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002482 res = call_method(self, "__delslice__", &delslice_str,
2483 "ii", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002485 res = call_method(self, "__setslice__", &setslice_str,
2486 "iiO", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002487 if (res == NULL)
2488 return -1;
2489 Py_DECREF(res);
2490 return 0;
2491}
2492
2493static int
2494slot_sq_contains(PyObject *self, PyObject *value)
2495{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002496 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002497 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002498
Guido van Rossum60718732001-08-28 17:47:51 +00002499 func = lookup_method(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002500
2501 if (func != NULL) {
2502 args = Py_BuildValue("(O)", value);
2503 if (args == NULL)
2504 res = NULL;
2505 else {
2506 res = PyEval_CallObject(func, args);
2507 Py_DECREF(args);
2508 }
2509 Py_DECREF(func);
2510 if (res == NULL)
2511 return -1;
2512 return PyObject_IsTrue(res);
2513 }
2514 else {
2515 PyErr_Clear();
2516 return _PySequence_IterContains(self, value);
2517 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002518}
2519
Guido van Rossumdc91b992001-08-08 22:26:22 +00002520SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2521SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002522
2523#define slot_mp_length slot_sq_length
2524
Guido van Rossumdc91b992001-08-08 22:26:22 +00002525SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002526
2527static int
2528slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2529{
2530 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002531 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002532
2533 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002534 res = call_method(self, "__delitem__", &delitem_str,
2535 "O", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002536 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002537 res = call_method(self, "__setitem__", &setitem_str,
2538 "OO", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002539 if (res == NULL)
2540 return -1;
2541 Py_DECREF(res);
2542 return 0;
2543}
2544
Guido van Rossumdc91b992001-08-08 22:26:22 +00002545SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2546SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2547SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2548SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2549SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2550SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2551
2552staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2553
2554SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2555 nb_power, "__pow__", "__rpow__")
2556
2557static PyObject *
2558slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2559{
Guido van Rossum2730b132001-08-28 18:22:14 +00002560 static PyObject *pow_str;
2561
Guido van Rossumdc91b992001-08-08 22:26:22 +00002562 if (modulus == Py_None)
2563 return slot_nb_power_binary(self, other);
2564 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002565 return call_method(self, "__pow__", &pow_str,
2566 "OO", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002567}
2568
2569SLOT0(slot_nb_negative, "__neg__")
2570SLOT0(slot_nb_positive, "__pos__")
2571SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002572
2573static int
2574slot_nb_nonzero(PyObject *self)
2575{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002576 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002577 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002578
Guido van Rossum60718732001-08-28 17:47:51 +00002579 func = lookup_method(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002580 if (func == NULL) {
2581 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002582 func = lookup_method(self, "__len__", &len_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002583 }
2584
2585 if (func != NULL) {
2586 res = PyEval_CallObject(func, NULL);
2587 Py_DECREF(func);
2588 if (res == NULL)
2589 return -1;
2590 return PyObject_IsTrue(res);
2591 }
2592 else {
2593 PyErr_Clear();
2594 return 1;
2595 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002596}
2597
Guido van Rossumdc91b992001-08-08 22:26:22 +00002598SLOT0(slot_nb_invert, "__invert__")
2599SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2600SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2601SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2602SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2603SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002604/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002605SLOT0(slot_nb_int, "__int__")
2606SLOT0(slot_nb_long, "__long__")
2607SLOT0(slot_nb_float, "__float__")
2608SLOT0(slot_nb_oct, "__oct__")
2609SLOT0(slot_nb_hex, "__hex__")
2610SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2611SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2612SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2613SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2614SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2615SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2616SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2617SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2618SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2619SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2620SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2621SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2622 "__floordiv__", "__rfloordiv__")
2623SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2624SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2625SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002626
2627static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002628half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002629{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002630 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002631 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002632 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002633
Guido van Rossum60718732001-08-28 17:47:51 +00002634 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002635 if (func == NULL) {
2636 PyErr_Clear();
2637 }
2638 else {
2639 args = Py_BuildValue("(O)", other);
2640 if (args == NULL)
2641 res = NULL;
2642 else {
2643 res = PyObject_CallObject(func, args);
2644 Py_DECREF(args);
2645 }
2646 if (res != Py_NotImplemented) {
2647 if (res == NULL)
2648 return -2;
2649 c = PyInt_AsLong(res);
2650 Py_DECREF(res);
2651 if (c == -1 && PyErr_Occurred())
2652 return -2;
2653 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2654 }
2655 Py_DECREF(res);
2656 }
2657 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002658}
2659
Guido van Rossumb8f63662001-08-15 23:57:02 +00002660static int
2661slot_tp_compare(PyObject *self, PyObject *other)
2662{
2663 int c;
2664
2665 if (self->ob_type->tp_compare == slot_tp_compare) {
2666 c = half_compare(self, other);
2667 if (c <= 1)
2668 return c;
2669 }
2670 if (other->ob_type->tp_compare == slot_tp_compare) {
2671 c = half_compare(other, self);
2672 if (c < -1)
2673 return -2;
2674 if (c <= 1)
2675 return -c;
2676 }
2677 return (void *)self < (void *)other ? -1 :
2678 (void *)self > (void *)other ? 1 : 0;
2679}
2680
2681static PyObject *
2682slot_tp_repr(PyObject *self)
2683{
2684 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002685 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002686
Guido van Rossum60718732001-08-28 17:47:51 +00002687 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002688 if (func != NULL) {
2689 res = PyEval_CallObject(func, NULL);
2690 Py_DECREF(func);
2691 return res;
2692 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00002693 PyErr_Clear();
2694 return PyString_FromFormat("<%s object at %p>",
2695 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002696}
2697
2698static PyObject *
2699slot_tp_str(PyObject *self)
2700{
2701 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002702 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002703
Guido van Rossum60718732001-08-28 17:47:51 +00002704 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002705 if (func != NULL) {
2706 res = PyEval_CallObject(func, NULL);
2707 Py_DECREF(func);
2708 return res;
2709 }
2710 else {
2711 PyErr_Clear();
2712 return slot_tp_repr(self);
2713 }
2714}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002715
2716static long
2717slot_tp_hash(PyObject *self)
2718{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002719 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002720 static PyObject *hash_str, *eq_str, *cmp_str;
2721
Tim Peters6d6c1a32001-08-02 04:15:00 +00002722 long h;
2723
Guido van Rossum60718732001-08-28 17:47:51 +00002724 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002725
2726 if (func != NULL) {
2727 res = PyEval_CallObject(func, NULL);
2728 Py_DECREF(func);
2729 if (res == NULL)
2730 return -1;
2731 h = PyInt_AsLong(res);
2732 }
2733 else {
2734 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002735 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002736 if (func == NULL) {
2737 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002738 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002739 }
2740 if (func != NULL) {
2741 Py_DECREF(func);
2742 PyErr_SetString(PyExc_TypeError, "unhashable type");
2743 return -1;
2744 }
2745 PyErr_Clear();
2746 h = _Py_HashPointer((void *)self);
2747 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748 if (h == -1 && !PyErr_Occurred())
2749 h = -2;
2750 return h;
2751}
2752
2753static PyObject *
2754slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2755{
Guido van Rossum60718732001-08-28 17:47:51 +00002756 static PyObject *call_str;
2757 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758 PyObject *res;
2759
2760 if (meth == NULL)
2761 return NULL;
2762 res = PyObject_Call(meth, args, kwds);
2763 Py_DECREF(meth);
2764 return res;
2765}
2766
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767static PyObject *
2768slot_tp_getattro(PyObject *self, PyObject *name)
2769{
2770 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002772 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002773
Guido van Rossum8e248182001-08-12 05:17:56 +00002774 if (getattr_str == NULL) {
2775 getattr_str = PyString_InternFromString("__getattr__");
2776 if (getattr_str == NULL)
2777 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778 }
Guido van Rossum8e248182001-08-12 05:17:56 +00002779 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00002780 if (getattr == NULL) {
2781 /* Avoid further slowdowns */
2782 if (tp->tp_getattro == slot_tp_getattro)
2783 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002784 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00002785 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786 return PyObject_CallFunction(getattr, "OO", self, name);
2787}
2788
2789static int
2790slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2791{
2792 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002793 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794
2795 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002796 res = call_method(self, "__delattr__", &delattr_str,
2797 "O", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002798 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002799 res = call_method(self, "__setattr__", &setattr_str,
2800 "OO", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801 if (res == NULL)
2802 return -1;
2803 Py_DECREF(res);
2804 return 0;
2805}
2806
2807/* Map rich comparison operators to their __xx__ namesakes */
2808static char *name_op[] = {
2809 "__lt__",
2810 "__le__",
2811 "__eq__",
2812 "__ne__",
2813 "__gt__",
2814 "__ge__",
2815};
2816
2817static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00002818half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002819{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002820 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002821 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00002822
Guido van Rossum60718732001-08-28 17:47:51 +00002823 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002824 if (func == NULL) {
2825 PyErr_Clear();
2826 Py_INCREF(Py_NotImplemented);
2827 return Py_NotImplemented;
2828 }
2829 args = Py_BuildValue("(O)", other);
2830 if (args == NULL)
2831 res = NULL;
2832 else {
2833 res = PyObject_CallObject(func, args);
2834 Py_DECREF(args);
2835 }
2836 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002837 return res;
2838}
2839
Guido van Rossumb8f63662001-08-15 23:57:02 +00002840/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
2841static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
2842
2843static PyObject *
2844slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2845{
2846 PyObject *res;
2847
2848 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
2849 res = half_richcompare(self, other, op);
2850 if (res != Py_NotImplemented)
2851 return res;
2852 Py_DECREF(res);
2853 }
2854 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
2855 res = half_richcompare(other, self, swapped_op[op]);
2856 if (res != Py_NotImplemented) {
2857 return res;
2858 }
2859 Py_DECREF(res);
2860 }
2861 Py_INCREF(Py_NotImplemented);
2862 return Py_NotImplemented;
2863}
2864
2865static PyObject *
2866slot_tp_iter(PyObject *self)
2867{
2868 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002869 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002870
Guido van Rossum60718732001-08-28 17:47:51 +00002871 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002872 if (func != NULL) {
2873 res = PyObject_CallObject(func, NULL);
2874 Py_DECREF(func);
2875 return res;
2876 }
2877 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002878 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002879 if (func == NULL) {
2880 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
2881 return NULL;
2882 }
2883 Py_DECREF(func);
2884 return PySeqIter_New(self);
2885}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002886
2887static PyObject *
2888slot_tp_iternext(PyObject *self)
2889{
Guido van Rossum2730b132001-08-28 18:22:14 +00002890 static PyObject *next_str;
2891 return call_method(self, "next", &next_str, "");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002892}
2893
Guido van Rossum1a493502001-08-17 16:47:50 +00002894static PyObject *
2895slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
2896{
2897 PyTypeObject *tp = self->ob_type;
2898 PyObject *get;
2899 static PyObject *get_str = NULL;
2900
2901 if (get_str == NULL) {
2902 get_str = PyString_InternFromString("__get__");
2903 if (get_str == NULL)
2904 return NULL;
2905 }
2906 get = _PyType_Lookup(tp, get_str);
2907 if (get == NULL) {
2908 /* Avoid further slowdowns */
2909 if (tp->tp_descr_get == slot_tp_descr_get)
2910 tp->tp_descr_get = NULL;
2911 Py_INCREF(self);
2912 return self;
2913 }
Guido van Rossum2c252392001-08-24 10:13:31 +00002914 if (obj == NULL)
2915 obj = Py_None;
2916 if (type == NULL)
2917 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00002918 return PyObject_CallFunction(get, "OOO", self, obj, type);
2919}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002920
2921static int
2922slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2923{
Guido van Rossum2c252392001-08-24 10:13:31 +00002924 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002925 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00002926
2927 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002928 res = call_method(self, "__del__", &del_str,
2929 "O", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00002930 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002931 res = call_method(self, "__set__", &set_str,
2932 "OO", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002933 if (res == NULL)
2934 return -1;
2935 Py_DECREF(res);
2936 return 0;
2937}
2938
2939static int
2940slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2941{
Guido van Rossum60718732001-08-28 17:47:51 +00002942 static PyObject *init_str;
2943 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002944 PyObject *res;
2945
2946 if (meth == NULL)
2947 return -1;
2948 res = PyObject_Call(meth, args, kwds);
2949 Py_DECREF(meth);
2950 if (res == NULL)
2951 return -1;
2952 Py_DECREF(res);
2953 return 0;
2954}
2955
2956static PyObject *
2957slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2958{
2959 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
2960 PyObject *newargs, *x;
2961 int i, n;
2962
2963 if (func == NULL)
2964 return NULL;
2965 assert(PyTuple_Check(args));
2966 n = PyTuple_GET_SIZE(args);
2967 newargs = PyTuple_New(n+1);
2968 if (newargs == NULL)
2969 return NULL;
2970 Py_INCREF(type);
2971 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
2972 for (i = 0; i < n; i++) {
2973 x = PyTuple_GET_ITEM(args, i);
2974 Py_INCREF(x);
2975 PyTuple_SET_ITEM(newargs, i+1, x);
2976 }
2977 x = PyObject_Call(func, newargs, kwds);
2978 Py_DECREF(func);
2979 return x;
2980}
2981
Guido van Rossumf040ede2001-08-07 16:40:56 +00002982/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002983 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00002984 The dict argument is the dictionary argument passed to type_new(),
2985 which is the local namespace of the class statement, in other
2986 words, it contains the methods. For each special method (like
2987 __repr__) defined in the dictionary, the corresponding function
2988 slot in the type object (like tp_repr) is set to a special function
2989 whose name is 'slot_' followed by the slot name and whose signature
2990 is whatever is required for that slot. These slot functions look
2991 up the corresponding method in the type's dictionary and call it.
2992 The slot functions have to take care of the various peculiarities
2993 of the mapping between slots and special methods, such as mapping
2994 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
2995 etc.) or mapping multiple slots to a single method (sq_item,
2996 mp_subscript <--> __getitem__). */
2997
Tim Peters6d6c1a32001-08-02 04:15:00 +00002998static void
2999override_slots(PyTypeObject *type, PyObject *dict)
3000{
3001 PySequenceMethods *sq = type->tp_as_sequence;
3002 PyMappingMethods *mp = type->tp_as_mapping;
3003 PyNumberMethods *nb = type->tp_as_number;
3004
Guido van Rossumdc91b992001-08-08 22:26:22 +00003005#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003006 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003007 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003008 }
3009
Guido van Rossumdc91b992001-08-08 22:26:22 +00003010#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003011 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003012 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003013 }
3014
Guido van Rossumdc91b992001-08-08 22:26:22 +00003015#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003016 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003017 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003018 }
3019
Guido van Rossumdc91b992001-08-08 22:26:22 +00003020#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003021 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003022 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023 }
3024
Guido van Rossumdc91b992001-08-08 22:26:22 +00003025 SQSLOT("__len__", sq_length, slot_sq_length);
3026 SQSLOT("__add__", sq_concat, slot_sq_concat);
3027 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3028 SQSLOT("__getitem__", sq_item, slot_sq_item);
3029 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3030 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3031 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3032 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3033 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3034 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3035 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3036 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003037
Guido van Rossumdc91b992001-08-08 22:26:22 +00003038 MPSLOT("__len__", mp_length, slot_mp_length);
3039 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3040 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3041 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042
Guido van Rossumdc91b992001-08-08 22:26:22 +00003043 NBSLOT("__add__", nb_add, slot_nb_add);
3044 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3045 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3046 NBSLOT("__div__", nb_divide, slot_nb_divide);
3047 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3048 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3049 NBSLOT("__pow__", nb_power, slot_nb_power);
3050 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3051 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3052 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3053 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3054 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3055 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3056 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3057 NBSLOT("__and__", nb_and, slot_nb_and);
3058 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3059 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003060 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00003061 NBSLOT("__int__", nb_int, slot_nb_int);
3062 NBSLOT("__long__", nb_long, slot_nb_long);
3063 NBSLOT("__float__", nb_float, slot_nb_float);
3064 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3065 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3066 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3067 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3068 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3069 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3070 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3071 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3072 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3073 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3074 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3075 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3076 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3077 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3078 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3079 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3080 slot_nb_inplace_floor_divide);
3081 NBSLOT("__itruediv__", nb_inplace_true_divide,
3082 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003083
Guido van Rossum8e248182001-08-12 05:17:56 +00003084 if (dict == NULL ||
3085 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003086 PyDict_GetItemString(dict, "__repr__"))
3087 type->tp_print = NULL;
3088
Guido van Rossumdc91b992001-08-08 22:26:22 +00003089 TPSLOT("__cmp__", tp_compare, slot_tp_compare);
3090 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3091 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3092 TPSLOT("__call__", tp_call, slot_tp_call);
3093 TPSLOT("__str__", tp_str, slot_tp_str);
3094 TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
3095 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3096 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3097 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3098 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3099 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3100 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3101 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3102 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3103 TPSLOT("next", tp_iternext, slot_tp_iternext);
3104 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3105 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3106 TPSLOT("__init__", tp_init, slot_tp_init);
3107 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003108}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003109
3110
3111/* Cooperative 'super' */
3112
3113typedef struct {
3114 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003115 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003116 PyObject *obj;
3117} superobject;
3118
3119static void
3120super_dealloc(PyObject *self)
3121{
3122 superobject *su = (superobject *)self;
3123
3124 Py_XDECREF(su->obj);
3125 Py_XDECREF(su->type);
3126 self->ob_type->tp_free(self);
3127}
3128
3129static PyObject *
3130super_getattro(PyObject *self, PyObject *name)
3131{
3132 superobject *su = (superobject *)self;
3133
3134 if (su->obj != NULL) {
3135 PyObject *mro, *res, *tmp;
3136 descrgetfunc f;
3137 int i, n;
3138
Guido van Rossume705ef12001-08-29 15:47:06 +00003139 mro = su->obj->ob_type->tp_mro;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003140 assert(mro != NULL && PyTuple_Check(mro));
3141 n = PyTuple_GET_SIZE(mro);
3142 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003143 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003144 break;
3145 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003146 if (i >= n && PyType_Check(su->obj)) {
3147 mro = ((PyTypeObject *)(su->obj))->tp_mro;
3148 assert(mro != NULL && PyTuple_Check(mro));
3149 n = PyTuple_GET_SIZE(mro);
3150 for (i = 0; i < n; i++) {
3151 if ((PyObject *)(su->type) ==
3152 PyTuple_GET_ITEM(mro, i))
3153 break;
3154 }
3155 if (i >= n) {
3156 PyErr_SetString(PyExc_TypeError,
3157 "bogus super object");
3158 return NULL;
3159 }
3160 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003161 i++;
3162 res = NULL;
3163 for (; i < n; i++) {
3164 tmp = PyTuple_GET_ITEM(mro, i);
3165 assert(PyType_Check(tmp));
3166 res = PyDict_GetItem(
3167 ((PyTypeObject *)tmp)->tp_defined, name);
3168 if (res != NULL) {
3169 Py_INCREF(res);
3170 f = res->ob_type->tp_descr_get;
3171 if (f != NULL) {
3172 tmp = f(res, su->obj, res);
3173 Py_DECREF(res);
3174 res = tmp;
3175 }
3176 return res;
3177 }
3178 }
3179 }
3180 return PyObject_GenericGetAttr(self, name);
3181}
3182
3183static PyObject *
3184super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3185{
3186 superobject *su = (superobject *)self;
3187 superobject *new;
3188
3189 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3190 /* Not binding to an object, or already bound */
3191 Py_INCREF(self);
3192 return self;
3193 }
3194 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3195 if (new == NULL)
3196 return NULL;
3197 Py_INCREF(su->type);
3198 Py_INCREF(obj);
3199 new->type = su->type;
3200 new->obj = obj;
3201 return (PyObject *)new;
3202}
3203
3204static int
3205super_init(PyObject *self, PyObject *args, PyObject *kwds)
3206{
3207 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003208 PyTypeObject *type;
3209 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003210
3211 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3212 return -1;
3213 if (obj == Py_None)
3214 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003215 if (obj != NULL &&
3216 !PyType_IsSubtype(obj->ob_type, type) &&
3217 !(PyType_Check(obj) &&
3218 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003219 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003220 "super(type, obj): "
3221 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003222 return -1;
3223 }
3224 Py_INCREF(type);
3225 Py_XINCREF(obj);
3226 su->type = type;
3227 su->obj = obj;
3228 return 0;
3229}
3230
3231static char super_doc[] =
3232"super(type) -> unbound super object\n"
3233"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003234"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003235"Typical use to call a cooperative superclass method:\n"
3236"class C(B):\n"
3237" def meth(self, arg):\n"
3238" super(C, self).meth(arg)";
3239
3240PyTypeObject PySuper_Type = {
3241 PyObject_HEAD_INIT(&PyType_Type)
3242 0, /* ob_size */
3243 "super", /* tp_name */
3244 sizeof(superobject), /* tp_basicsize */
3245 0, /* tp_itemsize */
3246 /* methods */
3247 super_dealloc, /* tp_dealloc */
3248 0, /* tp_print */
3249 0, /* tp_getattr */
3250 0, /* tp_setattr */
3251 0, /* tp_compare */
3252 0, /* tp_repr */
3253 0, /* tp_as_number */
3254 0, /* tp_as_sequence */
3255 0, /* tp_as_mapping */
3256 0, /* tp_hash */
3257 0, /* tp_call */
3258 0, /* tp_str */
3259 super_getattro, /* tp_getattro */
3260 0, /* tp_setattro */
3261 0, /* tp_as_buffer */
3262 Py_TPFLAGS_DEFAULT, /* tp_flags */
3263 super_doc, /* tp_doc */
3264 0, /* tp_traverse */
3265 0, /* tp_clear */
3266 0, /* tp_richcompare */
3267 0, /* tp_weaklistoffset */
3268 0, /* tp_iter */
3269 0, /* tp_iternext */
3270 0, /* tp_methods */
3271 0, /* tp_members */
3272 0, /* tp_getset */
3273 0, /* tp_base */
3274 0, /* tp_dict */
3275 super_descr_get, /* tp_descr_get */
3276 0, /* tp_descr_set */
3277 0, /* tp_dictoffset */
3278 super_init, /* tp_init */
3279 PyType_GenericAlloc, /* tp_alloc */
3280 PyType_GenericNew, /* tp_new */
3281 _PyObject_Del, /* tp_free */
3282};