blob: fed6c438faeac2d22adc0d1061d602fa2621f29e [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Type object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum6f799372001-09-20 20:46:19 +00007static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00008 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
9 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
10 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
11 {"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
17 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
18 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
25 char *s;
26
27 s = strrchr(type->tp_name, '.');
28 if (s == NULL)
29 s = type->tp_name;
30 else
31 s++;
32 return PyString_FromString(s);
33}
34
35static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000036type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000037{
Guido van Rossumc3542212001-08-16 09:18:56 +000038 PyObject *mod;
39 char *s;
40
41 s = strrchr(type->tp_name, '.');
42 if (s != NULL)
43 return PyString_FromStringAndSize(type->tp_name,
44 (int)(s - type->tp_name));
45 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
46 return PyString_FromString("__builtin__");
47 mod = PyDict_GetItemString(type->tp_defined, "__module__");
48 if (mod != NULL && PyString_Check(mod)) {
49 Py_INCREF(mod);
50 return mod;
51 }
52 PyErr_SetString(PyExc_AttributeError, "__module__");
53 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000054}
55
Guido van Rossum3926a632001-09-25 16:25:58 +000056static int
57type_set_module(PyTypeObject *type, PyObject *value, void *context)
58{
59 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ||
60 strrchr(type->tp_name, '.')) {
61 PyErr_Format(PyExc_TypeError,
62 "can't set %s.__module__", type->tp_name);
63 return -1;
64 }
65 if (!value) {
66 PyErr_Format(PyExc_TypeError,
67 "can't delete %s.__module__", type->tp_name);
68 return -1;
69 }
70 return PyDict_SetItemString(type->tp_dict, "__module__", value);
71}
72
Tim Peters6d6c1a32001-08-02 04:15:00 +000073static PyObject *
74type_dict(PyTypeObject *type, void *context)
75{
76 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077 Py_INCREF(Py_None);
78 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000079 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000080 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
81 Py_INCREF(type->tp_dict);
82 return type->tp_dict;
83 }
84 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000085}
86
Tim Peters6d6c1a32001-08-02 04:15:00 +000087static PyObject *
88type_defined(PyTypeObject *type, void *context)
89{
90 if (type->tp_defined == NULL) {
91 Py_INCREF(Py_None);
92 return Py_None;
93 }
94 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
95 Py_INCREF(type->tp_defined);
96 return type->tp_defined;
97 }
98 return PyDictProxy_New(type->tp_defined);
99}
100
101static PyObject *
102type_dynamic(PyTypeObject *type, void *context)
103{
104 PyObject *res;
105
106 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
107 Py_INCREF(res);
108 return res;
109}
110
Guido van Rossum32d34c82001-09-20 21:45:26 +0000111PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000112 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000113 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000114 {"__dict__", (getter)type_dict, NULL, NULL},
115 {"__defined__", (getter)type_defined, NULL, NULL},
116 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
117 {0}
118};
119
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000120static int
121type_compare(PyObject *v, PyObject *w)
122{
123 /* This is called with type objects only. So we
124 can just compare the addresses. */
125 Py_uintptr_t vv = (Py_uintptr_t)v;
126 Py_uintptr_t ww = (Py_uintptr_t)w;
127 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
128}
129
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000131type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000133 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000134 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000135
136 mod = type_module(type, NULL);
137 if (mod == NULL)
138 PyErr_Clear();
139 else if (!PyString_Check(mod)) {
140 Py_DECREF(mod);
141 mod = NULL;
142 }
143 name = type_name(type, NULL);
144 if (name == NULL)
145 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000146
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000147 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
148 kind = "class";
149 else
150 kind = "type";
151
Barry Warsaw7ce36942001-08-24 18:34:26 +0000152 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000153 rtn = PyString_FromFormat("<%s '%s.%s'>",
154 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000155 PyString_AS_STRING(mod),
156 PyString_AS_STRING(name));
157 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000158 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000159 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000160
Guido van Rossumc3542212001-08-16 09:18:56 +0000161 Py_XDECREF(mod);
162 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000163 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
Tim Peters6d6c1a32001-08-02 04:15:00 +0000166static PyObject *
167type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
168{
169 PyObject *obj;
170
171 if (type->tp_new == NULL) {
172 PyErr_Format(PyExc_TypeError,
173 "cannot create '%.100s' instances",
174 type->tp_name);
175 return NULL;
176 }
177
Tim Peters3f996e72001-09-13 19:18:27 +0000178 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 if (obj != NULL) {
180 type = obj->ob_type;
181 if (type->tp_init != NULL &&
182 type->tp_init(obj, args, kwds) < 0) {
183 Py_DECREF(obj);
184 obj = NULL;
185 }
186 }
187 return obj;
188}
189
190PyObject *
191PyType_GenericAlloc(PyTypeObject *type, int nitems)
192{
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000193#define PTRSIZE (sizeof(PyObject *))
194
Tim Peters6d6c1a32001-08-02 04:15:00 +0000195 int size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000196 PyObject *obj;
197
198 /* Inline PyObject_New() so we can zero the memory */
199 size = _PyObject_VAR_SIZE(type, nitems);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000200 /* Round up size, if necessary, so we fully zero out __dict__ */
201 if (type->tp_itemsize % PTRSIZE != 0) {
202 size += PTRSIZE - 1;
203 size /= PTRSIZE;
204 size *= PTRSIZE;
205 }
Neil Schemenauerc806c882001-08-29 23:54:54 +0000206 if (PyType_IS_GC(type)) {
207 obj = _PyObject_GC_Malloc(type, nitems);
208 }
209 else {
210 obj = PyObject_MALLOC(size);
211 }
212 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000213 return PyErr_NoMemory();
Neil Schemenauerc806c882001-08-29 23:54:54 +0000214 memset(obj, '\0', size);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000215 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
216 Py_INCREF(type);
217 if (type->tp_itemsize == 0)
218 PyObject_INIT(obj, type);
219 else
220 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
221 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000222 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000223 return obj;
224}
225
226PyObject *
227PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
228{
229 return type->tp_alloc(type, 0);
230}
231
Guido van Rossum9475a232001-10-05 20:51:39 +0000232/* Helpers for subtyping */
233
234static int
235subtype_traverse(PyObject *self, visitproc visit, void *arg)
236{
237 PyTypeObject *type, *base;
238 traverseproc f;
239 int err;
240
241 /* Find the nearest base with a different tp_traverse */
242 type = self->ob_type;
243 base = type->tp_base;
244 while ((f = base->tp_traverse) == subtype_traverse) {
245 base = base->tp_base;
246 assert(base);
247 }
248
249 if (type->tp_dictoffset != base->tp_dictoffset) {
250 PyObject **dictptr = _PyObject_GetDictPtr(self);
251 if (dictptr && *dictptr) {
252 err = visit(*dictptr, arg);
253 if (err)
254 return err;
255 }
256 }
257
258 if (f)
259 return f(self, visit, arg);
260 return 0;
261}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000262
263static void
264subtype_dealloc(PyObject *self)
265{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000266 PyTypeObject *type, *base;
267 destructor f;
268
269 /* This exists so we can DECREF self->ob_type */
270
271 /* Find the nearest base with a different tp_dealloc */
272 type = self->ob_type;
273 base = type->tp_base;
274 while ((f = base->tp_dealloc) == subtype_dealloc) {
275 base = base->tp_base;
276 assert(base);
277 }
278
279 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000280 if (type->tp_dictoffset && !base->tp_dictoffset) {
281 PyObject **dictptr = _PyObject_GetDictPtr(self);
282 if (dictptr != NULL) {
283 PyObject *dict = *dictptr;
284 if (dict != NULL) {
285 Py_DECREF(dict);
286 *dictptr = NULL;
287 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000288 }
289 }
290
Guido van Rossum9676b222001-08-17 20:32:36 +0000291 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000292 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000293 PyObject_ClearWeakRefs(self);
294
Tim Peters6d6c1a32001-08-02 04:15:00 +0000295 /* Finalize GC if the base doesn't do GC and we do */
296 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000297 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000298
299 /* Call the base tp_dealloc() */
300 assert(f);
301 f(self);
302
303 /* Can't reference self beyond this point */
304 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
305 Py_DECREF(type);
306 }
307}
308
309staticforward void override_slots(PyTypeObject *type, PyObject *dict);
310staticforward PyTypeObject *solid_base(PyTypeObject *type);
311
312typedef struct {
313 PyTypeObject type;
314 PyNumberMethods as_number;
315 PySequenceMethods as_sequence;
316 PyMappingMethods as_mapping;
317 PyBufferProcs as_buffer;
318 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000319 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000320} etype;
321
322/* type test with subclassing support */
323
324int
325PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
326{
327 PyObject *mro;
328
Guido van Rossum9478d072001-09-07 18:52:13 +0000329 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
330 return b == a || b == &PyBaseObject_Type;
331
Tim Peters6d6c1a32001-08-02 04:15:00 +0000332 mro = a->tp_mro;
333 if (mro != NULL) {
334 /* Deal with multiple inheritance without recursion
335 by walking the MRO tuple */
336 int i, n;
337 assert(PyTuple_Check(mro));
338 n = PyTuple_GET_SIZE(mro);
339 for (i = 0; i < n; i++) {
340 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
341 return 1;
342 }
343 return 0;
344 }
345 else {
346 /* a is not completely initilized yet; follow tp_base */
347 do {
348 if (a == b)
349 return 1;
350 a = a->tp_base;
351 } while (a != NULL);
352 return b == &PyBaseObject_Type;
353 }
354}
355
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000356/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000357 without looking in the instance dictionary
358 (so we can't use PyObject_GetAttr) but still binding
359 it to the instance. The arguments are the object,
360 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000361 static variable used to cache the interned Python string.
362
363 Two variants:
364
365 - lookup_maybe() returns NULL without raising an exception
366 when the _PyType_Lookup() call fails;
367
368 - lookup_method() always raises an exception upon errors.
369*/
Guido van Rossum60718732001-08-28 17:47:51 +0000370
371static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000372lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000373{
374 PyObject *res;
375
376 if (*attrobj == NULL) {
377 *attrobj = PyString_InternFromString(attrstr);
378 if (*attrobj == NULL)
379 return NULL;
380 }
381 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000382 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000383 descrgetfunc f;
384 if ((f = res->ob_type->tp_descr_get) == NULL)
385 Py_INCREF(res);
386 else
387 res = f(res, self, (PyObject *)(self->ob_type));
388 }
389 return res;
390}
391
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000392static PyObject *
393lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
394{
395 PyObject *res = lookup_maybe(self, attrstr, attrobj);
396 if (res == NULL && !PyErr_Occurred())
397 PyErr_SetObject(PyExc_AttributeError, *attrobj);
398 return res;
399}
400
Guido van Rossum2730b132001-08-28 18:22:14 +0000401/* A variation of PyObject_CallMethod that uses lookup_method()
402 instead of PyObject_GetAttrString(). This uses the same convention
403 as lookup_method to cache the interned name string object. */
404
405PyObject *
406call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
407{
408 va_list va;
409 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000410 va_start(va, format);
411
Guido van Rossumda21c012001-10-03 00:50:18 +0000412 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000413 if (func == NULL) {
414 va_end(va);
415 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000416 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000417 return NULL;
418 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000419
420 if (format && *format)
421 args = Py_VaBuildValue(format, va);
422 else
423 args = PyTuple_New(0);
424
425 va_end(va);
426
427 if (args == NULL)
428 return NULL;
429
430 assert(PyTuple_Check(args));
431 retval = PyObject_Call(func, args, NULL);
432
433 Py_DECREF(args);
434 Py_DECREF(func);
435
436 return retval;
437}
438
439/* Clone of call_method() that returns NotImplemented when the lookup fails. */
440
441PyObject *
442call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
443{
444 va_list va;
445 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000446 va_start(va, format);
447
Guido van Rossumda21c012001-10-03 00:50:18 +0000448 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000449 if (func == NULL) {
450 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000451 if (!PyErr_Occurred()) {
452 Py_INCREF(Py_NotImplemented);
453 return Py_NotImplemented;
454 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000455 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000456 }
457
458 if (format && *format)
459 args = Py_VaBuildValue(format, va);
460 else
461 args = PyTuple_New(0);
462
463 va_end(va);
464
Guido van Rossum717ce002001-09-14 16:58:08 +0000465 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000466 return NULL;
467
Guido van Rossum717ce002001-09-14 16:58:08 +0000468 assert(PyTuple_Check(args));
469 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000470
471 Py_DECREF(args);
472 Py_DECREF(func);
473
474 return retval;
475}
476
Tim Peters6d6c1a32001-08-02 04:15:00 +0000477/* Method resolution order algorithm from "Putting Metaclasses to Work"
478 by Forman and Danforth (Addison-Wesley 1999). */
479
480static int
481conservative_merge(PyObject *left, PyObject *right)
482{
483 int left_size;
484 int right_size;
485 int i, j, r, ok;
486 PyObject *temp, *rr;
487
488 assert(PyList_Check(left));
489 assert(PyList_Check(right));
490
491 again:
492 left_size = PyList_GET_SIZE(left);
493 right_size = PyList_GET_SIZE(right);
494 for (i = 0; i < left_size; i++) {
495 for (j = 0; j < right_size; j++) {
496 if (PyList_GET_ITEM(left, i) ==
497 PyList_GET_ITEM(right, j)) {
498 /* found a merge point */
499 temp = PyList_New(0);
500 if (temp == NULL)
501 return -1;
502 for (r = 0; r < j; r++) {
503 rr = PyList_GET_ITEM(right, r);
504 ok = PySequence_Contains(left, rr);
505 if (ok < 0) {
506 Py_DECREF(temp);
507 return -1;
508 }
509 if (!ok) {
510 ok = PyList_Append(temp, rr);
511 if (ok < 0) {
512 Py_DECREF(temp);
513 return -1;
514 }
515 }
516 }
517 ok = PyList_SetSlice(left, i, i, temp);
518 Py_DECREF(temp);
519 if (ok < 0)
520 return -1;
521 ok = PyList_SetSlice(right, 0, j+1, NULL);
522 if (ok < 0)
523 return -1;
524 goto again;
525 }
526 }
527 }
528 return PyList_SetSlice(left, left_size, left_size, right);
529}
530
531static int
532serious_order_disagreements(PyObject *left, PyObject *right)
533{
534 return 0; /* XXX later -- for now, we cheat: "don't do that" */
535}
536
537static PyObject *
538mro_implementation(PyTypeObject *type)
539{
540 int i, n, ok;
541 PyObject *bases, *result;
542
543 bases = type->tp_bases;
544 n = PyTuple_GET_SIZE(bases);
545 result = Py_BuildValue("[O]", (PyObject *)type);
546 if (result == NULL)
547 return NULL;
548 for (i = 0; i < n; i++) {
549 PyTypeObject *base =
550 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
551 PyObject *parentMRO = PySequence_List(base->tp_mro);
552 if (parentMRO == NULL) {
553 Py_DECREF(result);
554 return NULL;
555 }
556 if (serious_order_disagreements(result, parentMRO)) {
557 Py_DECREF(result);
558 return NULL;
559 }
560 ok = conservative_merge(result, parentMRO);
561 Py_DECREF(parentMRO);
562 if (ok < 0) {
563 Py_DECREF(result);
564 return NULL;
565 }
566 }
567 return result;
568}
569
570static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000571mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000572{
573 PyTypeObject *type = (PyTypeObject *)self;
574
Tim Peters6d6c1a32001-08-02 04:15:00 +0000575 return mro_implementation(type);
576}
577
578static int
579mro_internal(PyTypeObject *type)
580{
581 PyObject *mro, *result, *tuple;
582
583 if (type->ob_type == &PyType_Type) {
584 result = mro_implementation(type);
585 }
586 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000587 static PyObject *mro_str;
588 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589 if (mro == NULL)
590 return -1;
591 result = PyObject_CallObject(mro, NULL);
592 Py_DECREF(mro);
593 }
594 if (result == NULL)
595 return -1;
596 tuple = PySequence_Tuple(result);
597 Py_DECREF(result);
598 type->tp_mro = tuple;
599 return 0;
600}
601
602
603/* Calculate the best base amongst multiple base classes.
604 This is the first one that's on the path to the "solid base". */
605
606static PyTypeObject *
607best_base(PyObject *bases)
608{
609 int i, n;
610 PyTypeObject *base, *winner, *candidate, *base_i;
611
612 assert(PyTuple_Check(bases));
613 n = PyTuple_GET_SIZE(bases);
614 assert(n > 0);
615 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
616 winner = &PyBaseObject_Type;
617 for (i = 0; i < n; i++) {
618 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
619 if (!PyType_Check((PyObject *)base_i)) {
620 PyErr_SetString(
621 PyExc_TypeError,
622 "bases must be types");
623 return NULL;
624 }
625 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000626 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000627 return NULL;
628 }
629 candidate = solid_base(base_i);
630 if (PyType_IsSubtype(winner, candidate))
631 ;
632 else if (PyType_IsSubtype(candidate, winner)) {
633 winner = candidate;
634 base = base_i;
635 }
636 else {
637 PyErr_SetString(
638 PyExc_TypeError,
639 "multiple bases have "
640 "instance lay-out conflict");
641 return NULL;
642 }
643 }
644 assert(base != NULL);
645 return base;
646}
647
648static int
649extra_ivars(PyTypeObject *type, PyTypeObject *base)
650{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000651 size_t t_size = type->tp_basicsize;
652 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000653
Guido van Rossum9676b222001-08-17 20:32:36 +0000654 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000655 if (type->tp_itemsize || base->tp_itemsize) {
656 /* If itemsize is involved, stricter rules */
657 return t_size != b_size ||
658 type->tp_itemsize != base->tp_itemsize;
659 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000660 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
661 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
662 t_size -= sizeof(PyObject *);
663 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
664 type->tp_dictoffset + sizeof(PyObject *) == t_size)
665 t_size -= sizeof(PyObject *);
666
667 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000668}
669
670static PyTypeObject *
671solid_base(PyTypeObject *type)
672{
673 PyTypeObject *base;
674
675 if (type->tp_base)
676 base = solid_base(type->tp_base);
677 else
678 base = &PyBaseObject_Type;
679 if (extra_ivars(type, base))
680 return type;
681 else
682 return base;
683}
684
685staticforward void object_dealloc(PyObject *);
686staticforward int object_init(PyObject *, PyObject *, PyObject *);
687
688static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000689subtype_dict(PyObject *obj, void *context)
690{
691 PyObject **dictptr = _PyObject_GetDictPtr(obj);
692 PyObject *dict;
693
694 if (dictptr == NULL) {
695 PyErr_SetString(PyExc_AttributeError,
696 "This object has no __dict__");
697 return NULL;
698 }
699 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000700 if (dict == NULL)
701 *dictptr = dict = PyDict_New();
702 Py_XINCREF(dict);
703 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000704}
705
Guido van Rossum32d34c82001-09-20 21:45:26 +0000706PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000707 {"__dict__", subtype_dict, NULL, NULL},
708 {0},
709};
710
711static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000712type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
713{
714 PyObject *name, *bases, *dict;
715 static char *kwlist[] = {"name", "bases", "dict", 0};
716 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000717 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000719 PyMemberDef *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000720 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000721
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000722 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000723 if (metatype == &PyType_Type &&
724 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
725 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000726 PyObject *x = PyTuple_GET_ITEM(args, 0);
727 Py_INCREF(x->ob_type);
728 return (PyObject *) x->ob_type;
729 }
730
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000731 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000732 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
733 &name,
734 &PyTuple_Type, &bases,
735 &PyDict_Type, &dict))
736 return NULL;
737
738 /* Determine the proper metatype to deal with this,
739 and check for metatype conflicts while we're at it.
740 Note that if some other metatype wins to contract,
741 it's possible that its instances are not types. */
742 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000743 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000744 for (i = 0; i < nbases; i++) {
745 tmp = PyTuple_GET_ITEM(bases, i);
746 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000747 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000748 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000749 if (PyType_IsSubtype(tmptype, winner)) {
750 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000751 continue;
752 }
753 PyErr_SetString(PyExc_TypeError,
754 "metatype conflict among bases");
755 return NULL;
756 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000757 if (winner != metatype) {
758 if (winner->tp_new != type_new) /* Pass it to the winner */
759 return winner->tp_new(winner, args, kwds);
760 metatype = winner;
761 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000762
763 /* Adjust for empty tuple bases */
764 if (nbases == 0) {
765 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
766 if (bases == NULL)
767 return NULL;
768 nbases = 1;
769 }
770 else
771 Py_INCREF(bases);
772
773 /* XXX From here until type is allocated, "return NULL" leaks bases! */
774
775 /* Calculate best base, and check that all bases are type objects */
776 base = best_base(bases);
777 if (base == NULL)
778 return NULL;
779 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
780 PyErr_Format(PyExc_TypeError,
781 "type '%.100s' is not an acceptable base type",
782 base->tp_name);
783 return NULL;
784 }
785
Guido van Rossum1a493502001-08-17 16:47:50 +0000786 /* Should this be a dynamic class (i.e. modifiable __dict__)?
787 Look in two places for a variable named __dynamic__:
788 1) in the class dict
789 2) in the module dict (globals)
790 The first variable that is an int >= 0 is used.
Guido van Rossum50fda3b2001-10-04 19:46:06 +0000791 Otherwise, the default is dynamic. */
Guido van Rossum1a493502001-08-17 16:47:50 +0000792 dynamic = -1; /* Not yet determined */
793 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000794 tmp = PyDict_GetItemString(dict, "__dynamic__");
795 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000796 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000797 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000798 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000799 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000800 if (dynamic < 0) {
801 /* Look in the module globals */
802 tmp = PyEval_GetGlobals();
803 if (tmp != NULL) {
804 tmp = PyDict_GetItemString(tmp, "__dynamic__");
805 if (tmp != NULL) {
806 dynamic = PyInt_AsLong(tmp);
807 if (dynamic < 0)
808 PyErr_Clear();
809 }
810 }
811 }
812 if (dynamic < 0) {
Guido van Rossum50fda3b2001-10-04 19:46:06 +0000813 /* Default to dynamic */
814 dynamic = 1;
815
Tim Peters6d6c1a32001-08-02 04:15:00 +0000816 }
817
818 /* Check for a __slots__ sequence variable in dict, and count it */
819 slots = PyDict_GetItemString(dict, "__slots__");
820 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000821 add_dict = 0;
822 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000823 if (slots != NULL) {
824 /* Make it into a tuple */
825 if (PyString_Check(slots))
826 slots = Py_BuildValue("(O)", slots);
827 else
828 slots = PySequence_Tuple(slots);
829 if (slots == NULL)
830 return NULL;
831 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000832 if (nslots > 0 && base->tp_itemsize != 0) {
833 PyErr_Format(PyExc_TypeError,
834 "nonempty __slots__ "
835 "not supported for subtype of '%s'",
836 base->tp_name);
837 return NULL;
838 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839 for (i = 0; i < nslots; i++) {
840 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
841 PyErr_SetString(PyExc_TypeError,
842 "__slots__ must be a sequence of strings");
843 Py_DECREF(slots);
844 return NULL;
845 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000846 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000847 }
848 }
849 if (slots == NULL && base->tp_dictoffset == 0 &&
850 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000851 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000852 add_dict++;
853 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000854 if (slots == NULL && base->tp_weaklistoffset == 0 &&
855 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000856 nslots++;
857 add_weak++;
858 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000859
860 /* XXX From here until type is safely allocated,
861 "return NULL" may leak slots! */
862
863 /* Allocate the type object */
864 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
865 if (type == NULL)
866 return NULL;
867
868 /* Keep name and slots alive in the extended type object */
869 et = (etype *)type;
870 Py_INCREF(name);
871 et->name = name;
872 et->slots = slots;
873
Guido van Rossumdc91b992001-08-08 22:26:22 +0000874 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000875 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
876 Py_TPFLAGS_BASETYPE;
877 if (dynamic)
878 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000879 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
880 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000881
882 /* It's a new-style number unless it specifically inherits any
883 old-style numeric behavior */
884 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
885 (base->tp_as_number == NULL))
886 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
887
888 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000889 type->tp_as_number = &et->as_number;
890 type->tp_as_sequence = &et->as_sequence;
891 type->tp_as_mapping = &et->as_mapping;
892 type->tp_as_buffer = &et->as_buffer;
893 type->tp_name = PyString_AS_STRING(name);
894
895 /* Set tp_base and tp_bases */
896 type->tp_bases = bases;
897 Py_INCREF(base);
898 type->tp_base = base;
899
900 /* Initialize tp_defined from passed-in dict */
901 type->tp_defined = dict = PyDict_Copy(dict);
902 if (dict == NULL) {
903 Py_DECREF(type);
904 return NULL;
905 }
906
Guido van Rossumc3542212001-08-16 09:18:56 +0000907 /* Set __module__ in the dict */
908 if (PyDict_GetItemString(dict, "__module__") == NULL) {
909 tmp = PyEval_GetGlobals();
910 if (tmp != NULL) {
911 tmp = PyDict_GetItemString(tmp, "__name__");
912 if (tmp != NULL) {
913 if (PyDict_SetItemString(dict, "__module__",
914 tmp) < 0)
915 return NULL;
916 }
917 }
918 }
919
Tim Peters2f93e282001-10-04 05:27:00 +0000920 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
921 and is a string (tp_doc is a char* -- can't copy a general object
922 into it).
923 XXX What if it's a Unicode string? Don't know -- this ignores it.
924 */
925 {
926 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
927 if (doc != NULL && PyString_Check(doc)) {
928 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +0000929 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +0000930 if (type->tp_doc == NULL) {
931 Py_DECREF(type);
932 return NULL;
933 }
934 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
935 }
936 }
937
Tim Peters6d6c1a32001-08-02 04:15:00 +0000938 /* Special-case __new__: if it's a plain function,
939 make it a static function */
940 tmp = PyDict_GetItemString(dict, "__new__");
941 if (tmp != NULL && PyFunction_Check(tmp)) {
942 tmp = PyStaticMethod_New(tmp);
943 if (tmp == NULL) {
944 Py_DECREF(type);
945 return NULL;
946 }
947 PyDict_SetItemString(dict, "__new__", tmp);
948 Py_DECREF(tmp);
949 }
950
951 /* Add descriptors for custom slots from __slots__, or for __dict__ */
952 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000953 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000954 if (slots != NULL) {
955 for (i = 0; i < nslots; i++, mp++) {
956 mp->name = PyString_AS_STRING(
957 PyTuple_GET_ITEM(slots, i));
958 mp->type = T_OBJECT;
959 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000960 if (base->tp_weaklistoffset == 0 &&
961 strcmp(mp->name, "__weakref__") == 0)
962 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000963 slotoffset += sizeof(PyObject *);
964 }
965 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000966 else {
967 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000968 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +0000969 type->tp_dictoffset =
970 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000971 else
972 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000973 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000974 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000975 }
976 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000977 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000978 type->tp_weaklistoffset = slotoffset;
979 mp->name = "__weakref__";
980 mp->type = T_OBJECT;
981 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000982 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000983 mp++;
984 slotoffset += sizeof(PyObject *);
985 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000986 }
987 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000988 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000989 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000990
991 /* Special case some slots */
992 if (type->tp_dictoffset != 0 || nslots > 0) {
993 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
994 type->tp_getattro = PyObject_GenericGetAttr;
995 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
996 type->tp_setattro = PyObject_GenericSetAttr;
997 }
998 type->tp_dealloc = subtype_dealloc;
999
Guido van Rossum9475a232001-10-05 20:51:39 +00001000 /* Enable GC unless there are really no instance variables possible */
1001 if (!(type->tp_basicsize == sizeof(PyObject) &&
1002 type->tp_itemsize == 0))
1003 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1004
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005 /* Always override allocation strategy to use regular heap */
1006 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001007 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1008 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001009 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001010 type->tp_clear = base->tp_clear;
1011 }
1012 else
1013 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014
1015 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001016 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001017 Py_DECREF(type);
1018 return NULL;
1019 }
1020
1021 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +00001022 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
1023 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001024
Tim Peters6d6c1a32001-08-02 04:15:00 +00001025 return (PyObject *)type;
1026}
1027
1028/* Internal API to look for a name through the MRO.
1029 This returns a borrowed reference, and doesn't set an exception! */
1030PyObject *
1031_PyType_Lookup(PyTypeObject *type, PyObject *name)
1032{
1033 int i, n;
1034 PyObject *mro, *res, *dict;
1035
1036 /* For static types, look in tp_dict */
1037 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
1038 dict = type->tp_dict;
1039 assert(dict && PyDict_Check(dict));
1040 return PyDict_GetItem(dict, name);
1041 }
1042
1043 /* For dynamic types, look in tp_defined of types in MRO */
1044 mro = type->tp_mro;
1045 assert(PyTuple_Check(mro));
1046 n = PyTuple_GET_SIZE(mro);
1047 for (i = 0; i < n; i++) {
1048 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
1049 assert(PyType_Check(type));
1050 dict = type->tp_defined;
1051 assert(dict && PyDict_Check(dict));
1052 res = PyDict_GetItem(dict, name);
1053 if (res != NULL)
1054 return res;
1055 }
1056 return NULL;
1057}
1058
1059/* This is similar to PyObject_GenericGetAttr(),
1060 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1061static PyObject *
1062type_getattro(PyTypeObject *type, PyObject *name)
1063{
1064 PyTypeObject *metatype = type->ob_type;
1065 PyObject *descr, *res;
1066 descrgetfunc f;
1067
1068 /* Initialize this type (we'll assume the metatype is initialized) */
1069 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001070 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001071 return NULL;
1072 }
1073
1074 /* Get a descriptor from the metatype */
1075 descr = _PyType_Lookup(metatype, name);
1076 f = NULL;
1077 if (descr != NULL) {
1078 f = descr->ob_type->tp_descr_get;
1079 if (f != NULL && PyDescr_IsData(descr))
1080 return f(descr,
1081 (PyObject *)type, (PyObject *)metatype);
1082 }
1083
1084 /* Look in tp_defined of this type and its bases */
1085 res = _PyType_Lookup(type, name);
1086 if (res != NULL) {
1087 f = res->ob_type->tp_descr_get;
1088 if (f != NULL)
1089 return f(res, (PyObject *)NULL, (PyObject *)type);
1090 Py_INCREF(res);
1091 return res;
1092 }
1093
1094 /* Use the descriptor from the metatype */
1095 if (f != NULL) {
1096 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1097 return res;
1098 }
1099 if (descr != NULL) {
1100 Py_INCREF(descr);
1101 return descr;
1102 }
1103
1104 /* Give up */
1105 PyErr_Format(PyExc_AttributeError,
1106 "type object '%.50s' has no attribute '%.400s'",
1107 type->tp_name, PyString_AS_STRING(name));
1108 return NULL;
1109}
1110
1111static int
1112type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1113{
1114 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
1115 return PyObject_GenericSetAttr((PyObject *)type, name, value);
1116 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
1117 return -1;
1118}
1119
1120static void
1121type_dealloc(PyTypeObject *type)
1122{
1123 etype *et;
1124
1125 /* Assert this is a heap-allocated type object */
1126 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001127 _PyObject_GC_UNTRACK(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001128 et = (etype *)type;
1129 Py_XDECREF(type->tp_base);
1130 Py_XDECREF(type->tp_dict);
1131 Py_XDECREF(type->tp_bases);
1132 Py_XDECREF(type->tp_mro);
1133 Py_XDECREF(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001134 Py_XDECREF(et->name);
1135 Py_XDECREF(et->slots);
1136 type->ob_type->tp_free((PyObject *)type);
1137}
1138
1139static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001140 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001141 "mro() -> list\nreturn a type's method resolution order"},
1142 {0}
1143};
1144
1145static char type_doc[] =
1146"type(object) -> the object's type\n"
1147"type(name, bases, dict) -> a new type";
1148
Guido van Rossum048eb752001-10-02 21:24:57 +00001149static int
1150type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1151{
1152 etype *et;
1153 int err;
1154
1155 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1156 return 0;
1157
1158 et = (etype *)type;
1159
1160#define VISIT(SLOT) \
1161 if (SLOT) { \
1162 err = visit((PyObject *)(SLOT), arg); \
1163 if (err) \
1164 return err; \
1165 }
1166
1167 VISIT(type->tp_dict);
1168 VISIT(type->tp_defined);
1169 VISIT(type->tp_mro);
1170 VISIT(type->tp_bases);
1171 VISIT(type->tp_base);
1172 VISIT(et->slots);
1173
1174#undef VISIT
1175
1176 return 0;
1177}
1178
1179static int
1180type_clear(PyTypeObject *type)
1181{
1182 etype *et;
1183 PyObject *tmp;
1184
1185 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1186 return 0;
1187
1188 et = (etype *)type;
1189
1190#define CLEAR(SLOT) \
1191 if (SLOT) { \
1192 tmp = (PyObject *)(SLOT); \
1193 SLOT = NULL; \
1194 Py_DECREF(tmp); \
1195 }
1196
1197 CLEAR(type->tp_dict);
1198 CLEAR(type->tp_defined);
1199 CLEAR(type->tp_mro);
1200 CLEAR(type->tp_bases);
1201 CLEAR(type->tp_base);
1202 CLEAR(et->slots);
1203
Tim Peters2f93e282001-10-04 05:27:00 +00001204 if (type->tp_doc != NULL) {
1205 PyObject_FREE(type->tp_doc);
1206 type->tp_doc = NULL;
1207 }
1208
Guido van Rossum048eb752001-10-02 21:24:57 +00001209#undef CLEAR
1210
1211 return 0;
1212}
1213
1214static int
1215type_is_gc(PyTypeObject *type)
1216{
1217 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1218}
1219
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001220PyTypeObject PyType_Type = {
1221 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001222 0, /* ob_size */
1223 "type", /* tp_name */
1224 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001225 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001226 (destructor)type_dealloc, /* tp_dealloc */
1227 0, /* tp_print */
1228 0, /* tp_getattr */
1229 0, /* tp_setattr */
1230 type_compare, /* tp_compare */
1231 (reprfunc)type_repr, /* tp_repr */
1232 0, /* tp_as_number */
1233 0, /* tp_as_sequence */
1234 0, /* tp_as_mapping */
1235 (hashfunc)_Py_HashPointer, /* tp_hash */
1236 (ternaryfunc)type_call, /* tp_call */
1237 0, /* tp_str */
1238 (getattrofunc)type_getattro, /* tp_getattro */
1239 (setattrofunc)type_setattro, /* tp_setattro */
1240 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001241 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1242 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001243 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001244 (traverseproc)type_traverse, /* tp_traverse */
1245 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246 0, /* tp_richcompare */
1247 0, /* tp_weaklistoffset */
1248 0, /* tp_iter */
1249 0, /* tp_iternext */
1250 type_methods, /* tp_methods */
1251 type_members, /* tp_members */
1252 type_getsets, /* tp_getset */
1253 0, /* tp_base */
1254 0, /* tp_dict */
1255 0, /* tp_descr_get */
1256 0, /* tp_descr_set */
1257 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1258 0, /* tp_init */
1259 0, /* tp_alloc */
1260 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001261 _PyObject_GC_Del, /* tp_free */
1262 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001263};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001264
1265
1266/* The base type of all types (eventually)... except itself. */
1267
1268static int
1269object_init(PyObject *self, PyObject *args, PyObject *kwds)
1270{
1271 return 0;
1272}
1273
1274static void
1275object_dealloc(PyObject *self)
1276{
1277 self->ob_type->tp_free(self);
1278}
1279
Guido van Rossum8e248182001-08-12 05:17:56 +00001280static PyObject *
1281object_repr(PyObject *self)
1282{
Guido van Rossum76e69632001-08-16 18:52:43 +00001283 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001284 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001285
Guido van Rossum76e69632001-08-16 18:52:43 +00001286 type = self->ob_type;
1287 mod = type_module(type, NULL);
1288 if (mod == NULL)
1289 PyErr_Clear();
1290 else if (!PyString_Check(mod)) {
1291 Py_DECREF(mod);
1292 mod = NULL;
1293 }
1294 name = type_name(type, NULL);
1295 if (name == NULL)
1296 return NULL;
1297 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001298 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001299 PyString_AS_STRING(mod),
1300 PyString_AS_STRING(name),
1301 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001302 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001303 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001304 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001305 Py_XDECREF(mod);
1306 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001307 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001308}
1309
Guido van Rossumb8f63662001-08-15 23:57:02 +00001310static PyObject *
1311object_str(PyObject *self)
1312{
1313 unaryfunc f;
1314
1315 f = self->ob_type->tp_repr;
1316 if (f == NULL)
1317 f = object_repr;
1318 return f(self);
1319}
1320
Guido van Rossum8e248182001-08-12 05:17:56 +00001321static long
1322object_hash(PyObject *self)
1323{
1324 return _Py_HashPointer(self);
1325}
Guido van Rossum8e248182001-08-12 05:17:56 +00001326
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001327static PyObject *
1328object_get_class(PyObject *self, void *closure)
1329{
1330 Py_INCREF(self->ob_type);
1331 return (PyObject *)(self->ob_type);
1332}
1333
1334static int
1335equiv_structs(PyTypeObject *a, PyTypeObject *b)
1336{
1337 return a == b ||
1338 (a != NULL &&
1339 b != NULL &&
1340 a->tp_basicsize == b->tp_basicsize &&
1341 a->tp_itemsize == b->tp_itemsize &&
1342 a->tp_dictoffset == b->tp_dictoffset &&
1343 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1344 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1345 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1346}
1347
1348static int
1349same_slots_added(PyTypeObject *a, PyTypeObject *b)
1350{
1351 PyTypeObject *base = a->tp_base;
1352 int size;
1353
1354 if (base != b->tp_base)
1355 return 0;
1356 if (equiv_structs(a, base) && equiv_structs(b, base))
1357 return 1;
1358 size = base->tp_basicsize;
1359 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1360 size += sizeof(PyObject *);
1361 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1362 size += sizeof(PyObject *);
1363 return size == a->tp_basicsize && size == b->tp_basicsize;
1364}
1365
1366static int
1367object_set_class(PyObject *self, PyObject *value, void *closure)
1368{
1369 PyTypeObject *old = self->ob_type;
1370 PyTypeObject *new, *newbase, *oldbase;
1371
1372 if (!PyType_Check(value)) {
1373 PyErr_Format(PyExc_TypeError,
1374 "__class__ must be set to new-style class, not '%s' object",
1375 value->ob_type->tp_name);
1376 return -1;
1377 }
1378 new = (PyTypeObject *)value;
1379 newbase = new;
1380 oldbase = old;
1381 while (equiv_structs(newbase, newbase->tp_base))
1382 newbase = newbase->tp_base;
1383 while (equiv_structs(oldbase, oldbase->tp_base))
1384 oldbase = oldbase->tp_base;
1385 if (newbase != oldbase &&
1386 (newbase->tp_base != oldbase->tp_base ||
1387 !same_slots_added(newbase, oldbase))) {
1388 PyErr_Format(PyExc_TypeError,
1389 "__class__ assignment: "
1390 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001391 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001392 old->tp_name);
1393 return -1;
1394 }
1395 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1396 Py_INCREF(new);
1397 }
1398 self->ob_type = new;
1399 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1400 Py_DECREF(old);
1401 }
1402 return 0;
1403}
1404
1405static PyGetSetDef object_getsets[] = {
1406 {"__class__", object_get_class, object_set_class,
1407 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001408 {0}
1409};
1410
Guido van Rossum3926a632001-09-25 16:25:58 +00001411static PyObject *
1412object_reduce(PyObject *self, PyObject *args)
1413{
1414 /* Call copy_reg._reduce(self) */
1415 static PyObject *copy_reg_str;
1416 PyObject *copy_reg, *res;
1417
1418 if (!copy_reg_str) {
1419 copy_reg_str = PyString_InternFromString("copy_reg");
1420 if (copy_reg_str == NULL)
1421 return NULL;
1422 }
1423 copy_reg = PyImport_Import(copy_reg_str);
1424 if (!copy_reg)
1425 return NULL;
1426 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1427 Py_DECREF(copy_reg);
1428 return res;
1429}
1430
1431static PyMethodDef object_methods[] = {
1432 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1433 {0}
1434};
1435
Tim Peters6d6c1a32001-08-02 04:15:00 +00001436PyTypeObject PyBaseObject_Type = {
1437 PyObject_HEAD_INIT(&PyType_Type)
1438 0, /* ob_size */
1439 "object", /* tp_name */
1440 sizeof(PyObject), /* tp_basicsize */
1441 0, /* tp_itemsize */
1442 (destructor)object_dealloc, /* tp_dealloc */
1443 0, /* tp_print */
1444 0, /* tp_getattr */
1445 0, /* tp_setattr */
1446 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001447 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001448 0, /* tp_as_number */
1449 0, /* tp_as_sequence */
1450 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001451 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001452 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001453 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001454 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001455 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001456 0, /* tp_as_buffer */
1457 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1458 "The most base type", /* tp_doc */
1459 0, /* tp_traverse */
1460 0, /* tp_clear */
1461 0, /* tp_richcompare */
1462 0, /* tp_weaklistoffset */
1463 0, /* tp_iter */
1464 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001465 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001466 0, /* tp_members */
1467 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468 0, /* tp_base */
1469 0, /* tp_dict */
1470 0, /* tp_descr_get */
1471 0, /* tp_descr_set */
1472 0, /* tp_dictoffset */
1473 object_init, /* tp_init */
1474 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001475 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001476 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001477};
1478
1479
1480/* Initialize the __dict__ in a type object */
1481
1482static int
1483add_methods(PyTypeObject *type, PyMethodDef *meth)
1484{
1485 PyObject *dict = type->tp_defined;
1486
1487 for (; meth->ml_name != NULL; meth++) {
1488 PyObject *descr;
1489 if (PyDict_GetItemString(dict, meth->ml_name))
1490 continue;
1491 descr = PyDescr_NewMethod(type, meth);
1492 if (descr == NULL)
1493 return -1;
1494 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1495 return -1;
1496 Py_DECREF(descr);
1497 }
1498 return 0;
1499}
1500
1501static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001502add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001503{
1504 PyObject *dict = type->tp_defined;
1505
1506 for (; memb->name != NULL; memb++) {
1507 PyObject *descr;
1508 if (PyDict_GetItemString(dict, memb->name))
1509 continue;
1510 descr = PyDescr_NewMember(type, memb);
1511 if (descr == NULL)
1512 return -1;
1513 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1514 return -1;
1515 Py_DECREF(descr);
1516 }
1517 return 0;
1518}
1519
1520static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001521add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001522{
1523 PyObject *dict = type->tp_defined;
1524
1525 for (; gsp->name != NULL; gsp++) {
1526 PyObject *descr;
1527 if (PyDict_GetItemString(dict, gsp->name))
1528 continue;
1529 descr = PyDescr_NewGetSet(type, gsp);
1530
1531 if (descr == NULL)
1532 return -1;
1533 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1534 return -1;
1535 Py_DECREF(descr);
1536 }
1537 return 0;
1538}
1539
Guido van Rossum13d52f02001-08-10 21:24:08 +00001540static void
1541inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001542{
1543 int oldsize, newsize;
1544
Guido van Rossum13d52f02001-08-10 21:24:08 +00001545 /* Special flag magic */
1546 if (!type->tp_as_buffer && base->tp_as_buffer) {
1547 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1548 type->tp_flags |=
1549 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1550 }
1551 if (!type->tp_as_sequence && base->tp_as_sequence) {
1552 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1553 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1554 }
1555 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1556 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1557 if ((!type->tp_as_number && base->tp_as_number) ||
1558 (!type->tp_as_sequence && base->tp_as_sequence)) {
1559 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1560 if (!type->tp_as_number && !type->tp_as_sequence) {
1561 type->tp_flags |= base->tp_flags &
1562 Py_TPFLAGS_HAVE_INPLACEOPS;
1563 }
1564 }
1565 /* Wow */
1566 }
1567 if (!type->tp_as_number && base->tp_as_number) {
1568 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1569 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1570 }
1571
1572 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001573 oldsize = base->tp_basicsize;
1574 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1575 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1576 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001577 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1578 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001579 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001580 if (type->tp_traverse == NULL)
1581 type->tp_traverse = base->tp_traverse;
1582 if (type->tp_clear == NULL)
1583 type->tp_clear = base->tp_clear;
1584 }
1585 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1586 if (base != &PyBaseObject_Type ||
1587 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1588 if (type->tp_new == NULL)
1589 type->tp_new = base->tp_new;
1590 }
1591 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001592 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001593
1594 /* Copy other non-function slots */
1595
1596#undef COPYVAL
1597#define COPYVAL(SLOT) \
1598 if (type->SLOT == 0) type->SLOT = base->SLOT
1599
1600 COPYVAL(tp_itemsize);
1601 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1602 COPYVAL(tp_weaklistoffset);
1603 }
1604 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1605 COPYVAL(tp_dictoffset);
1606 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001607}
1608
1609static void
1610inherit_slots(PyTypeObject *type, PyTypeObject *base)
1611{
1612 PyTypeObject *basebase;
1613
1614#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001615#undef COPYSLOT
1616#undef COPYNUM
1617#undef COPYSEQ
1618#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001619
1620#define SLOTDEFINED(SLOT) \
1621 (base->SLOT != 0 && \
1622 (basebase == NULL || base->SLOT != basebase->SLOT))
1623
Tim Peters6d6c1a32001-08-02 04:15:00 +00001624#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001625 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001626
1627#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1628#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1629#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1630
Guido van Rossum13d52f02001-08-10 21:24:08 +00001631 /* This won't inherit indirect slots (from tp_as_number etc.)
1632 if type doesn't provide the space. */
1633
1634 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1635 basebase = base->tp_base;
1636 if (basebase->tp_as_number == NULL)
1637 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001638 COPYNUM(nb_add);
1639 COPYNUM(nb_subtract);
1640 COPYNUM(nb_multiply);
1641 COPYNUM(nb_divide);
1642 COPYNUM(nb_remainder);
1643 COPYNUM(nb_divmod);
1644 COPYNUM(nb_power);
1645 COPYNUM(nb_negative);
1646 COPYNUM(nb_positive);
1647 COPYNUM(nb_absolute);
1648 COPYNUM(nb_nonzero);
1649 COPYNUM(nb_invert);
1650 COPYNUM(nb_lshift);
1651 COPYNUM(nb_rshift);
1652 COPYNUM(nb_and);
1653 COPYNUM(nb_xor);
1654 COPYNUM(nb_or);
1655 COPYNUM(nb_coerce);
1656 COPYNUM(nb_int);
1657 COPYNUM(nb_long);
1658 COPYNUM(nb_float);
1659 COPYNUM(nb_oct);
1660 COPYNUM(nb_hex);
1661 COPYNUM(nb_inplace_add);
1662 COPYNUM(nb_inplace_subtract);
1663 COPYNUM(nb_inplace_multiply);
1664 COPYNUM(nb_inplace_divide);
1665 COPYNUM(nb_inplace_remainder);
1666 COPYNUM(nb_inplace_power);
1667 COPYNUM(nb_inplace_lshift);
1668 COPYNUM(nb_inplace_rshift);
1669 COPYNUM(nb_inplace_and);
1670 COPYNUM(nb_inplace_xor);
1671 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001672 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1673 COPYNUM(nb_true_divide);
1674 COPYNUM(nb_floor_divide);
1675 COPYNUM(nb_inplace_true_divide);
1676 COPYNUM(nb_inplace_floor_divide);
1677 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001678 }
1679
Guido van Rossum13d52f02001-08-10 21:24:08 +00001680 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1681 basebase = base->tp_base;
1682 if (basebase->tp_as_sequence == NULL)
1683 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684 COPYSEQ(sq_length);
1685 COPYSEQ(sq_concat);
1686 COPYSEQ(sq_repeat);
1687 COPYSEQ(sq_item);
1688 COPYSEQ(sq_slice);
1689 COPYSEQ(sq_ass_item);
1690 COPYSEQ(sq_ass_slice);
1691 COPYSEQ(sq_contains);
1692 COPYSEQ(sq_inplace_concat);
1693 COPYSEQ(sq_inplace_repeat);
1694 }
1695
Guido van Rossum13d52f02001-08-10 21:24:08 +00001696 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1697 basebase = base->tp_base;
1698 if (basebase->tp_as_mapping == NULL)
1699 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001700 COPYMAP(mp_length);
1701 COPYMAP(mp_subscript);
1702 COPYMAP(mp_ass_subscript);
1703 }
1704
Guido van Rossum13d52f02001-08-10 21:24:08 +00001705 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001706
Tim Peters6d6c1a32001-08-02 04:15:00 +00001707 COPYSLOT(tp_dealloc);
1708 COPYSLOT(tp_print);
1709 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1710 type->tp_getattr = base->tp_getattr;
1711 type->tp_getattro = base->tp_getattro;
1712 }
1713 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1714 type->tp_setattr = base->tp_setattr;
1715 type->tp_setattro = base->tp_setattro;
1716 }
1717 /* tp_compare see tp_richcompare */
1718 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001719 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001720 COPYSLOT(tp_call);
1721 COPYSLOT(tp_str);
1722 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001723 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001724 if (type->tp_compare == NULL &&
1725 type->tp_richcompare == NULL &&
1726 type->tp_hash == NULL)
1727 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001728 type->tp_compare = base->tp_compare;
1729 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001730 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001731 }
1732 }
1733 else {
1734 COPYSLOT(tp_compare);
1735 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001736 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1737 COPYSLOT(tp_iter);
1738 COPYSLOT(tp_iternext);
1739 }
1740 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1741 COPYSLOT(tp_descr_get);
1742 COPYSLOT(tp_descr_set);
1743 COPYSLOT(tp_dictoffset);
1744 COPYSLOT(tp_init);
1745 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001746 COPYSLOT(tp_free);
1747 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001748}
1749
Guido van Rossum13d52f02001-08-10 21:24:08 +00001750staticforward int add_operators(PyTypeObject *);
1751
Tim Peters6d6c1a32001-08-02 04:15:00 +00001752int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001753PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001754{
1755 PyObject *dict, *bases, *x;
1756 PyTypeObject *base;
1757 int i, n;
1758
Guido van Rossumd614f972001-08-10 17:39:49 +00001759 if (type->tp_flags & Py_TPFLAGS_READY) {
1760 assert(type->tp_dict != NULL);
1761 return 0;
1762 }
1763 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1764 assert(type->tp_dict == NULL);
1765
1766 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001767
1768 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1769 base = type->tp_base;
1770 if (base == NULL && type != &PyBaseObject_Type)
1771 base = type->tp_base = &PyBaseObject_Type;
1772
1773 /* Initialize tp_bases */
1774 bases = type->tp_bases;
1775 if (bases == NULL) {
1776 if (base == NULL)
1777 bases = PyTuple_New(0);
1778 else
1779 bases = Py_BuildValue("(O)", base);
1780 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001781 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001782 type->tp_bases = bases;
1783 }
1784
1785 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001786 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001787 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001788 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001789 }
1790
1791 /* Initialize tp_defined */
1792 dict = type->tp_defined;
1793 if (dict == NULL) {
1794 dict = PyDict_New();
1795 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001796 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001797 type->tp_defined = dict;
1798 }
1799
1800 /* Add type-specific descriptors to tp_defined */
1801 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001802 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001803 if (type->tp_methods != NULL) {
1804 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001805 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001806 }
1807 if (type->tp_members != NULL) {
1808 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001809 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810 }
1811 if (type->tp_getset != NULL) {
1812 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001813 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001814 }
1815
1816 /* Temporarily make tp_dict the same object as tp_defined.
1817 (This is needed to call mro(), and can stay this way for
1818 dynamic types). */
1819 Py_INCREF(type->tp_defined);
1820 type->tp_dict = type->tp_defined;
1821
1822 /* Calculate method resolution order */
1823 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001824 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001825 }
1826
Guido van Rossum13d52f02001-08-10 21:24:08 +00001827 /* Inherit special flags from dominant base */
1828 if (type->tp_base != NULL)
1829 inherit_special(type, type->tp_base);
1830
Tim Peters6d6c1a32001-08-02 04:15:00 +00001831 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001832 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001833 /* For a dynamic type, all slots are overridden */
1834 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001835 }
1836 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001837 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001838 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001839 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001840 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001841 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001842 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001843 bases = type->tp_mro;
1844 assert(bases != NULL);
1845 assert(PyTuple_Check(bases));
1846 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001847 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1849 assert(PyType_Check(base));
1850 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001851 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001852 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001853 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001854 }
1855 }
1856
Guido van Rossum13d52f02001-08-10 21:24:08 +00001857 /* Some more special stuff */
1858 base = type->tp_base;
1859 if (base != NULL) {
1860 if (type->tp_as_number == NULL)
1861 type->tp_as_number = base->tp_as_number;
1862 if (type->tp_as_sequence == NULL)
1863 type->tp_as_sequence = base->tp_as_sequence;
1864 if (type->tp_as_mapping == NULL)
1865 type->tp_as_mapping = base->tp_as_mapping;
1866 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867
Guido van Rossum13d52f02001-08-10 21:24:08 +00001868 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001869 assert(type->tp_dict != NULL);
1870 type->tp_flags =
1871 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001872 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001873
1874 error:
1875 type->tp_flags &= ~Py_TPFLAGS_READYING;
1876 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001877}
1878
1879
1880/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1881
1882/* There's a wrapper *function* for each distinct function typedef used
1883 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1884 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1885 Most tables have only one entry; the tables for binary operators have two
1886 entries, one regular and one with reversed arguments. */
1887
1888static PyObject *
1889wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1890{
1891 inquiry func = (inquiry)wrapped;
1892 int res;
1893
1894 if (!PyArg_ParseTuple(args, ""))
1895 return NULL;
1896 res = (*func)(self);
1897 if (res == -1 && PyErr_Occurred())
1898 return NULL;
1899 return PyInt_FromLong((long)res);
1900}
1901
1902static struct wrapperbase tab_len[] = {
1903 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1904 {0}
1905};
1906
1907static PyObject *
1908wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1909{
1910 binaryfunc func = (binaryfunc)wrapped;
1911 PyObject *other;
1912
1913 if (!PyArg_ParseTuple(args, "O", &other))
1914 return NULL;
1915 return (*func)(self, other);
1916}
1917
1918static PyObject *
1919wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1920{
1921 binaryfunc func = (binaryfunc)wrapped;
1922 PyObject *other;
1923
1924 if (!PyArg_ParseTuple(args, "O", &other))
1925 return NULL;
1926 return (*func)(other, self);
1927}
1928
1929#undef BINARY
1930#define BINARY(NAME, OP) \
1931static struct wrapperbase tab_##NAME[] = { \
1932 {"__" #NAME "__", \
1933 (wrapperfunc)wrap_binaryfunc, \
1934 "x.__" #NAME "__(y) <==> " #OP}, \
1935 {"__r" #NAME "__", \
1936 (wrapperfunc)wrap_binaryfunc_r, \
1937 "y.__r" #NAME "__(x) <==> " #OP}, \
1938 {0} \
1939}
1940
1941BINARY(add, "x+y");
1942BINARY(sub, "x-y");
1943BINARY(mul, "x*y");
1944BINARY(div, "x/y");
1945BINARY(mod, "x%y");
1946BINARY(divmod, "divmod(x,y)");
1947BINARY(lshift, "x<<y");
1948BINARY(rshift, "x>>y");
1949BINARY(and, "x&y");
1950BINARY(xor, "x^y");
1951BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00001952
1953static PyObject *
1954wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
1955{
1956 coercion func = (coercion)wrapped;
1957 PyObject *other, *res;
1958 int ok;
1959
1960 if (!PyArg_ParseTuple(args, "O", &other))
1961 return NULL;
1962 ok = func(&self, &other);
1963 if (ok < 0)
1964 return NULL;
1965 if (ok > 0) {
1966 Py_INCREF(Py_NotImplemented);
1967 return Py_NotImplemented;
1968 }
1969 res = PyTuple_New(2);
1970 if (res == NULL) {
1971 Py_DECREF(self);
1972 Py_DECREF(other);
1973 return NULL;
1974 }
1975 PyTuple_SET_ITEM(res, 0, self);
1976 PyTuple_SET_ITEM(res, 1, other);
1977 return res;
1978}
1979
1980static struct wrapperbase tab_coerce[] = {
1981 {"__coerce__", (wrapperfunc)wrap_coercefunc,
1982 "x.__coerce__(y) <==> coerce(x, y)"},
1983 {0}
1984};
1985
Guido van Rossum874f15a2001-09-25 21:16:33 +00001986BINARY(floordiv, "x//y");
1987BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001988
1989static PyObject *
1990wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1991{
1992 ternaryfunc func = (ternaryfunc)wrapped;
1993 PyObject *other;
1994 PyObject *third = Py_None;
1995
1996 /* Note: This wrapper only works for __pow__() */
1997
1998 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1999 return NULL;
2000 return (*func)(self, other, third);
2001}
2002
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002003static PyObject *
2004wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2005{
2006 ternaryfunc func = (ternaryfunc)wrapped;
2007 PyObject *other;
2008 PyObject *third = Py_None;
2009
2010 /* Note: This wrapper only works for __pow__() */
2011
2012 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2013 return NULL;
2014 return (*func)(other, self, third);
2015}
2016
Tim Peters6d6c1a32001-08-02 04:15:00 +00002017#undef TERNARY
2018#define TERNARY(NAME, OP) \
2019static struct wrapperbase tab_##NAME[] = { \
2020 {"__" #NAME "__", \
2021 (wrapperfunc)wrap_ternaryfunc, \
2022 "x.__" #NAME "__(y, z) <==> " #OP}, \
2023 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002024 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025 "y.__r" #NAME "__(x, z) <==> " #OP}, \
2026 {0} \
2027}
2028
2029TERNARY(pow, "(x**y) % z");
2030
2031#undef UNARY
2032#define UNARY(NAME, OP) \
2033static struct wrapperbase tab_##NAME[] = { \
2034 {"__" #NAME "__", \
2035 (wrapperfunc)wrap_unaryfunc, \
2036 "x.__" #NAME "__() <==> " #OP}, \
2037 {0} \
2038}
2039
2040static PyObject *
2041wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2042{
2043 unaryfunc func = (unaryfunc)wrapped;
2044
2045 if (!PyArg_ParseTuple(args, ""))
2046 return NULL;
2047 return (*func)(self);
2048}
2049
2050UNARY(neg, "-x");
2051UNARY(pos, "+x");
2052UNARY(abs, "abs(x)");
2053UNARY(nonzero, "x != 0");
2054UNARY(invert, "~x");
2055UNARY(int, "int(x)");
2056UNARY(long, "long(x)");
2057UNARY(float, "float(x)");
2058UNARY(oct, "oct(x)");
2059UNARY(hex, "hex(x)");
2060
2061#undef IBINARY
2062#define IBINARY(NAME, OP) \
2063static struct wrapperbase tab_##NAME[] = { \
2064 {"__" #NAME "__", \
2065 (wrapperfunc)wrap_binaryfunc, \
2066 "x.__" #NAME "__(y) <==> " #OP}, \
2067 {0} \
2068}
2069
2070IBINARY(iadd, "x+=y");
2071IBINARY(isub, "x-=y");
2072IBINARY(imul, "x*=y");
2073IBINARY(idiv, "x/=y");
2074IBINARY(imod, "x%=y");
2075IBINARY(ilshift, "x<<=y");
2076IBINARY(irshift, "x>>=y");
2077IBINARY(iand, "x&=y");
2078IBINARY(ixor, "x^=y");
2079IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002080IBINARY(ifloordiv, "x//=y");
2081IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002082
2083#undef ITERNARY
2084#define ITERNARY(NAME, OP) \
2085static struct wrapperbase tab_##NAME[] = { \
2086 {"__" #NAME "__", \
2087 (wrapperfunc)wrap_ternaryfunc, \
2088 "x.__" #NAME "__(y) <==> " #OP}, \
2089 {0} \
2090}
2091
2092ITERNARY(ipow, "x = (x**y) % z");
2093
2094static struct wrapperbase tab_getitem[] = {
2095 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2096 "x.__getitem__(y) <==> x[y]"},
2097 {0}
2098};
2099
2100static PyObject *
2101wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2102{
2103 intargfunc func = (intargfunc)wrapped;
2104 int i;
2105
2106 if (!PyArg_ParseTuple(args, "i", &i))
2107 return NULL;
2108 return (*func)(self, i);
2109}
2110
2111static struct wrapperbase tab_mul_int[] = {
2112 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2113 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2114 {0}
2115};
2116
2117static struct wrapperbase tab_concat[] = {
2118 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2119 {0}
2120};
2121
2122static struct wrapperbase tab_imul_int[] = {
2123 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2124 {0}
2125};
2126
Guido van Rossum5d815f32001-08-17 21:57:47 +00002127static int
2128getindex(PyObject *self, PyObject *arg)
2129{
2130 int i;
2131
2132 i = PyInt_AsLong(arg);
2133 if (i == -1 && PyErr_Occurred())
2134 return -1;
2135 if (i < 0) {
2136 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2137 if (sq && sq->sq_length) {
2138 int n = (*sq->sq_length)(self);
2139 if (n < 0)
2140 return -1;
2141 i += n;
2142 }
2143 }
2144 return i;
2145}
2146
2147static PyObject *
2148wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2149{
2150 intargfunc func = (intargfunc)wrapped;
2151 PyObject *arg;
2152 int i;
2153
Guido van Rossumf4593e02001-10-03 12:09:30 +00002154 if (PyTuple_GET_SIZE(args) == 1) {
2155 arg = PyTuple_GET_ITEM(args, 0);
2156 i = getindex(self, arg);
2157 if (i == -1 && PyErr_Occurred())
2158 return NULL;
2159 return (*func)(self, i);
2160 }
2161 PyArg_ParseTuple(args, "O", &arg);
2162 assert(PyErr_Occurred());
2163 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002164}
2165
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002167 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002168 "x.__getitem__(i) <==> x[i]"},
2169 {0}
2170};
2171
2172static PyObject *
2173wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2174{
2175 intintargfunc func = (intintargfunc)wrapped;
2176 int i, j;
2177
2178 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2179 return NULL;
2180 return (*func)(self, i, j);
2181}
2182
2183static struct wrapperbase tab_getslice[] = {
2184 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2185 "x.__getslice__(i, j) <==> x[i:j]"},
2186 {0}
2187};
2188
2189static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002190wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002191{
2192 intobjargproc func = (intobjargproc)wrapped;
2193 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002194 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002195
Guido van Rossum5d815f32001-08-17 21:57:47 +00002196 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2197 return NULL;
2198 i = getindex(self, arg);
2199 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002200 return NULL;
2201 res = (*func)(self, i, value);
2202 if (res == -1 && PyErr_Occurred())
2203 return NULL;
2204 Py_INCREF(Py_None);
2205 return Py_None;
2206}
2207
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002208static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002209wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002210{
2211 intobjargproc func = (intobjargproc)wrapped;
2212 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002213 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002214
Guido van Rossum5d815f32001-08-17 21:57:47 +00002215 if (!PyArg_ParseTuple(args, "O", &arg))
2216 return NULL;
2217 i = getindex(self, arg);
2218 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002219 return NULL;
2220 res = (*func)(self, i, NULL);
2221 if (res == -1 && PyErr_Occurred())
2222 return NULL;
2223 Py_INCREF(Py_None);
2224 return Py_None;
2225}
2226
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002228 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002229 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002230 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002231 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002232 {0}
2233};
2234
2235static PyObject *
2236wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2237{
2238 intintobjargproc func = (intintobjargproc)wrapped;
2239 int i, j, res;
2240 PyObject *value;
2241
2242 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2243 return NULL;
2244 res = (*func)(self, i, j, value);
2245 if (res == -1 && PyErr_Occurred())
2246 return NULL;
2247 Py_INCREF(Py_None);
2248 return Py_None;
2249}
2250
2251static struct wrapperbase tab_setslice[] = {
2252 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2253 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
2254 {0}
2255};
2256
2257/* XXX objobjproc is a misnomer; should be objargpred */
2258static PyObject *
2259wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2260{
2261 objobjproc func = (objobjproc)wrapped;
2262 int res;
2263 PyObject *value;
2264
2265 if (!PyArg_ParseTuple(args, "O", &value))
2266 return NULL;
2267 res = (*func)(self, value);
2268 if (res == -1 && PyErr_Occurred())
2269 return NULL;
2270 return PyInt_FromLong((long)res);
2271}
2272
2273static struct wrapperbase tab_contains[] = {
2274 {"__contains__", (wrapperfunc)wrap_objobjproc,
2275 "x.__contains__(y) <==> y in x"},
2276 {0}
2277};
2278
2279static PyObject *
2280wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2281{
2282 objobjargproc func = (objobjargproc)wrapped;
2283 int res;
2284 PyObject *key, *value;
2285
2286 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2287 return NULL;
2288 res = (*func)(self, key, value);
2289 if (res == -1 && PyErr_Occurred())
2290 return NULL;
2291 Py_INCREF(Py_None);
2292 return Py_None;
2293}
2294
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002295static PyObject *
2296wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2297{
2298 objobjargproc func = (objobjargproc)wrapped;
2299 int res;
2300 PyObject *key;
2301
2302 if (!PyArg_ParseTuple(args, "O", &key))
2303 return NULL;
2304 res = (*func)(self, key, NULL);
2305 if (res == -1 && PyErr_Occurred())
2306 return NULL;
2307 Py_INCREF(Py_None);
2308 return Py_None;
2309}
2310
Tim Peters6d6c1a32001-08-02 04:15:00 +00002311static struct wrapperbase tab_setitem[] = {
2312 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2313 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002314 {"__delitem__", (wrapperfunc)wrap_delitem,
2315 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002316 {0}
2317};
2318
2319static PyObject *
2320wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2321{
2322 cmpfunc func = (cmpfunc)wrapped;
2323 int res;
2324 PyObject *other;
2325
2326 if (!PyArg_ParseTuple(args, "O", &other))
2327 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002328 if (other->ob_type->tp_compare != func &&
2329 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002330 PyErr_Format(
2331 PyExc_TypeError,
2332 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2333 self->ob_type->tp_name,
2334 self->ob_type->tp_name,
2335 other->ob_type->tp_name);
2336 return NULL;
2337 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002338 res = (*func)(self, other);
2339 if (PyErr_Occurred())
2340 return NULL;
2341 return PyInt_FromLong((long)res);
2342}
2343
2344static struct wrapperbase tab_cmp[] = {
2345 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2346 "x.__cmp__(y) <==> cmp(x,y)"},
2347 {0}
2348};
2349
2350static struct wrapperbase tab_repr[] = {
2351 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2352 "x.__repr__() <==> repr(x)"},
2353 {0}
2354};
2355
2356static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002357 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2358 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002359 {0}
2360};
2361
2362static PyObject *
2363wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2364{
2365 setattrofunc func = (setattrofunc)wrapped;
2366 int res;
2367 PyObject *name, *value;
2368
2369 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2370 return NULL;
2371 res = (*func)(self, name, value);
2372 if (res < 0)
2373 return NULL;
2374 Py_INCREF(Py_None);
2375 return Py_None;
2376}
2377
2378static PyObject *
2379wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2380{
2381 setattrofunc func = (setattrofunc)wrapped;
2382 int res;
2383 PyObject *name;
2384
2385 if (!PyArg_ParseTuple(args, "O", &name))
2386 return NULL;
2387 res = (*func)(self, name, NULL);
2388 if (res < 0)
2389 return NULL;
2390 Py_INCREF(Py_None);
2391 return Py_None;
2392}
2393
2394static struct wrapperbase tab_setattr[] = {
2395 {"__setattr__", (wrapperfunc)wrap_setattr,
2396 "x.__setattr__('name', value) <==> x.name = value"},
2397 {"__delattr__", (wrapperfunc)wrap_delattr,
2398 "x.__delattr__('name') <==> del x.name"},
2399 {0}
2400};
2401
2402static PyObject *
2403wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2404{
2405 hashfunc func = (hashfunc)wrapped;
2406 long res;
2407
2408 if (!PyArg_ParseTuple(args, ""))
2409 return NULL;
2410 res = (*func)(self);
2411 if (res == -1 && PyErr_Occurred())
2412 return NULL;
2413 return PyInt_FromLong(res);
2414}
2415
2416static struct wrapperbase tab_hash[] = {
2417 {"__hash__", (wrapperfunc)wrap_hashfunc,
2418 "x.__hash__() <==> hash(x)"},
2419 {0}
2420};
2421
2422static PyObject *
2423wrap_call(PyObject *self, PyObject *args, void *wrapped)
2424{
2425 ternaryfunc func = (ternaryfunc)wrapped;
2426
2427 /* XXX What about keyword arguments? */
2428 return (*func)(self, args, NULL);
2429}
2430
2431static struct wrapperbase tab_call[] = {
2432 {"__call__", (wrapperfunc)wrap_call,
2433 "x.__call__(...) <==> x(...)"},
2434 {0}
2435};
2436
2437static struct wrapperbase tab_str[] = {
2438 {"__str__", (wrapperfunc)wrap_unaryfunc,
2439 "x.__str__() <==> str(x)"},
2440 {0}
2441};
2442
2443static PyObject *
2444wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2445{
2446 richcmpfunc func = (richcmpfunc)wrapped;
2447 PyObject *other;
2448
2449 if (!PyArg_ParseTuple(args, "O", &other))
2450 return NULL;
2451 return (*func)(self, other, op);
2452}
2453
2454#undef RICHCMP_WRAPPER
2455#define RICHCMP_WRAPPER(NAME, OP) \
2456static PyObject * \
2457richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2458{ \
2459 return wrap_richcmpfunc(self, args, wrapped, OP); \
2460}
2461
Jack Jansen8e938b42001-08-08 15:29:49 +00002462RICHCMP_WRAPPER(lt, Py_LT)
2463RICHCMP_WRAPPER(le, Py_LE)
2464RICHCMP_WRAPPER(eq, Py_EQ)
2465RICHCMP_WRAPPER(ne, Py_NE)
2466RICHCMP_WRAPPER(gt, Py_GT)
2467RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002468
2469#undef RICHCMP_ENTRY
2470#define RICHCMP_ENTRY(NAME, EXPR) \
2471 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2472 "x.__" #NAME "__(y) <==> " EXPR}
2473
2474static struct wrapperbase tab_richcmp[] = {
2475 RICHCMP_ENTRY(lt, "x<y"),
2476 RICHCMP_ENTRY(le, "x<=y"),
2477 RICHCMP_ENTRY(eq, "x==y"),
2478 RICHCMP_ENTRY(ne, "x!=y"),
2479 RICHCMP_ENTRY(gt, "x>y"),
2480 RICHCMP_ENTRY(ge, "x>=y"),
2481 {0}
2482};
2483
2484static struct wrapperbase tab_iter[] = {
2485 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2486 {0}
2487};
2488
2489static PyObject *
2490wrap_next(PyObject *self, PyObject *args, void *wrapped)
2491{
2492 unaryfunc func = (unaryfunc)wrapped;
2493 PyObject *res;
2494
2495 if (!PyArg_ParseTuple(args, ""))
2496 return NULL;
2497 res = (*func)(self);
2498 if (res == NULL && !PyErr_Occurred())
2499 PyErr_SetNone(PyExc_StopIteration);
2500 return res;
2501}
2502
2503static struct wrapperbase tab_next[] = {
2504 {"next", (wrapperfunc)wrap_next,
2505 "x.next() -> the next value, or raise StopIteration"},
2506 {0}
2507};
2508
2509static PyObject *
2510wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2511{
2512 descrgetfunc func = (descrgetfunc)wrapped;
2513 PyObject *obj;
2514 PyObject *type = NULL;
2515
2516 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2517 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002518 return (*func)(self, obj, type);
2519}
2520
2521static struct wrapperbase tab_descr_get[] = {
2522 {"__get__", (wrapperfunc)wrap_descr_get,
2523 "descr.__get__(obj, type) -> value"},
2524 {0}
2525};
2526
2527static PyObject *
2528wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2529{
2530 descrsetfunc func = (descrsetfunc)wrapped;
2531 PyObject *obj, *value;
2532 int ret;
2533
2534 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2535 return NULL;
2536 ret = (*func)(self, obj, value);
2537 if (ret < 0)
2538 return NULL;
2539 Py_INCREF(Py_None);
2540 return Py_None;
2541}
2542
2543static struct wrapperbase tab_descr_set[] = {
2544 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2545 "descr.__set__(obj, value)"},
2546 {0}
2547};
2548
2549static PyObject *
2550wrap_init(PyObject *self, PyObject *args, void *wrapped)
2551{
2552 initproc func = (initproc)wrapped;
2553
2554 /* XXX What about keyword arguments? */
2555 if (func(self, args, NULL) < 0)
2556 return NULL;
2557 Py_INCREF(Py_None);
2558 return Py_None;
2559}
2560
2561static struct wrapperbase tab_init[] = {
2562 {"__init__", (wrapperfunc)wrap_init,
2563 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002564 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002565 {0}
2566};
2567
2568static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002569tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002570{
Barry Warsaw60f01882001-08-22 19:24:42 +00002571 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002572 PyObject *arg0, *res;
2573
2574 if (self == NULL || !PyType_Check(self))
2575 Py_FatalError("__new__() called with non-type 'self'");
2576 type = (PyTypeObject *)self;
2577 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002578 PyErr_Format(PyExc_TypeError,
2579 "%s.__new__(): not enough arguments",
2580 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002581 return NULL;
2582 }
2583 arg0 = PyTuple_GET_ITEM(args, 0);
2584 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002585 PyErr_Format(PyExc_TypeError,
2586 "%s.__new__(X): X is not a type object (%s)",
2587 type->tp_name,
2588 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002589 return NULL;
2590 }
2591 subtype = (PyTypeObject *)arg0;
2592 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002593 PyErr_Format(PyExc_TypeError,
2594 "%s.__new__(%s): %s is not a subtype of %s",
2595 type->tp_name,
2596 subtype->tp_name,
2597 subtype->tp_name,
2598 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002599 return NULL;
2600 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002601
2602 /* Check that the use doesn't do something silly and unsafe like
2603 object.__new__(dictionary). To do this, we check that the
2604 most derived base that's not a heap type is this type. */
2605 staticbase = subtype;
2606 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2607 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002608 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002609 PyErr_Format(PyExc_TypeError,
2610 "%s.__new__(%s) is not safe, use %s.__new__()",
2611 type->tp_name,
2612 subtype->tp_name,
2613 staticbase == NULL ? "?" : staticbase->tp_name);
2614 return NULL;
2615 }
2616
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002617 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2618 if (args == NULL)
2619 return NULL;
2620 res = type->tp_new(subtype, args, kwds);
2621 Py_DECREF(args);
2622 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002623}
2624
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002625static struct PyMethodDef tp_new_methoddef[] = {
2626 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2627 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002628 {0}
2629};
2630
2631static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002632add_tp_new_wrapper(PyTypeObject *type)
2633{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002634 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002635
Guido van Rossumf040ede2001-08-07 16:40:56 +00002636 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2637 return 0;
2638 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002639 if (func == NULL)
2640 return -1;
2641 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2642}
2643
Guido van Rossum13d52f02001-08-10 21:24:08 +00002644static int
2645add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2646{
2647 PyObject *dict = type->tp_defined;
2648
2649 for (; wraps->name != NULL; wraps++) {
2650 PyObject *descr;
2651 if (PyDict_GetItemString(dict, wraps->name))
2652 continue;
2653 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2654 if (descr == NULL)
2655 return -1;
2656 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2657 return -1;
2658 Py_DECREF(descr);
2659 }
2660 return 0;
2661}
2662
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002663/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002664 dictionary with method descriptors for function slots. For each
2665 function slot (like tp_repr) that's defined in the type, one or
2666 more corresponding descriptors are added in the type's tp_defined
2667 dictionary under the appropriate name (like __repr__). Some
2668 function slots cause more than one descriptor to be added (for
2669 example, the nb_add slot adds both __add__ and __radd__
2670 descriptors) and some function slots compete for the same
2671 descriptor (for example both sq_item and mp_subscript generate a
2672 __getitem__ descriptor). This only adds new descriptors and
2673 doesn't overwrite entries in tp_defined that were previously
2674 defined. The descriptors contain a reference to the C function
2675 they must call, so that it's safe if they are copied into a
2676 subtype's __dict__ and the subtype has a different C function in
2677 its slot -- calling the method defined by the descriptor will call
2678 the C function that was used to create it, rather than the C
2679 function present in the slot when it is called. (This is important
2680 because a subtype may have a C function in the slot that calls the
2681 method from the dictionary, and we want to avoid infinite recursion
2682 here.) */
2683
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002684static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002685add_operators(PyTypeObject *type)
2686{
2687 PySequenceMethods *sq;
2688 PyMappingMethods *mp;
2689 PyNumberMethods *nb;
2690
2691#undef ADD
2692#define ADD(SLOT, TABLE) \
2693 if (SLOT) { \
2694 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2695 return -1; \
2696 }
2697
2698 if ((sq = type->tp_as_sequence) != NULL) {
2699 ADD(sq->sq_length, tab_len);
2700 ADD(sq->sq_concat, tab_concat);
2701 ADD(sq->sq_repeat, tab_mul_int);
2702 ADD(sq->sq_item, tab_getitem_int);
2703 ADD(sq->sq_slice, tab_getslice);
2704 ADD(sq->sq_ass_item, tab_setitem_int);
2705 ADD(sq->sq_ass_slice, tab_setslice);
2706 ADD(sq->sq_contains, tab_contains);
2707 ADD(sq->sq_inplace_concat, tab_iadd);
2708 ADD(sq->sq_inplace_repeat, tab_imul_int);
2709 }
2710
2711 if ((mp = type->tp_as_mapping) != NULL) {
2712 if (sq->sq_length == NULL)
2713 ADD(mp->mp_length, tab_len);
2714 ADD(mp->mp_subscript, tab_getitem);
2715 ADD(mp->mp_ass_subscript, tab_setitem);
2716 }
2717
2718 /* We don't support "old-style numbers" because their binary
2719 operators require that both arguments have the same type;
2720 the wrappers here only work for new-style numbers. */
2721 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2722 (nb = type->tp_as_number) != NULL) {
2723 ADD(nb->nb_add, tab_add);
2724 ADD(nb->nb_subtract, tab_sub);
2725 ADD(nb->nb_multiply, tab_mul);
2726 ADD(nb->nb_divide, tab_div);
2727 ADD(nb->nb_remainder, tab_mod);
2728 ADD(nb->nb_divmod, tab_divmod);
2729 ADD(nb->nb_power, tab_pow);
2730 ADD(nb->nb_negative, tab_neg);
2731 ADD(nb->nb_positive, tab_pos);
2732 ADD(nb->nb_absolute, tab_abs);
2733 ADD(nb->nb_nonzero, tab_nonzero);
2734 ADD(nb->nb_invert, tab_invert);
2735 ADD(nb->nb_lshift, tab_lshift);
2736 ADD(nb->nb_rshift, tab_rshift);
2737 ADD(nb->nb_and, tab_and);
2738 ADD(nb->nb_xor, tab_xor);
2739 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002740 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002741 ADD(nb->nb_int, tab_int);
2742 ADD(nb->nb_long, tab_long);
2743 ADD(nb->nb_float, tab_float);
2744 ADD(nb->nb_oct, tab_oct);
2745 ADD(nb->nb_hex, tab_hex);
2746 ADD(nb->nb_inplace_add, tab_iadd);
2747 ADD(nb->nb_inplace_subtract, tab_isub);
2748 ADD(nb->nb_inplace_multiply, tab_imul);
2749 ADD(nb->nb_inplace_divide, tab_idiv);
2750 ADD(nb->nb_inplace_remainder, tab_imod);
2751 ADD(nb->nb_inplace_power, tab_ipow);
2752 ADD(nb->nb_inplace_lshift, tab_ilshift);
2753 ADD(nb->nb_inplace_rshift, tab_irshift);
2754 ADD(nb->nb_inplace_and, tab_iand);
2755 ADD(nb->nb_inplace_xor, tab_ixor);
2756 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum874f15a2001-09-25 21:16:33 +00002757 if (type->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2758 ADD(nb->nb_floor_divide, tab_floordiv);
2759 ADD(nb->nb_true_divide, tab_truediv);
2760 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2761 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2762 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002763 }
2764
2765 ADD(type->tp_getattro, tab_getattr);
2766 ADD(type->tp_setattro, tab_setattr);
2767 ADD(type->tp_compare, tab_cmp);
2768 ADD(type->tp_repr, tab_repr);
2769 ADD(type->tp_hash, tab_hash);
2770 ADD(type->tp_call, tab_call);
2771 ADD(type->tp_str, tab_str);
2772 ADD(type->tp_richcompare, tab_richcmp);
2773 ADD(type->tp_iter, tab_iter);
2774 ADD(type->tp_iternext, tab_next);
2775 ADD(type->tp_descr_get, tab_descr_get);
2776 ADD(type->tp_descr_set, tab_descr_set);
2777 ADD(type->tp_init, tab_init);
2778
Guido van Rossumf040ede2001-08-07 16:40:56 +00002779 if (type->tp_new != NULL) {
2780 if (add_tp_new_wrapper(type) < 0)
2781 return -1;
2782 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002783
2784 return 0;
2785}
2786
Guido van Rossumf040ede2001-08-07 16:40:56 +00002787/* Slot wrappers that call the corresponding __foo__ slot. See comments
2788 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002789
Guido van Rossumdc91b992001-08-08 22:26:22 +00002790#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002792FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002793{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002794 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002795 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796}
2797
Guido van Rossumdc91b992001-08-08 22:26:22 +00002798#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002800FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002802 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002803 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002804}
2805
Guido van Rossumdc91b992001-08-08 22:26:22 +00002806
2807#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002808static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002809FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002811 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002812 int do_other = self->ob_type != other->ob_type && \
2813 other->ob_type->tp_as_number != NULL && \
2814 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002815 if (self->ob_type->tp_as_number != NULL && \
2816 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2817 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002818 if (do_other && \
2819 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2820 r = call_maybe( \
2821 other, ROPSTR, &rcache_str, "(O)", self); \
2822 if (r != Py_NotImplemented) \
2823 return r; \
2824 Py_DECREF(r); \
2825 do_other = 0; \
2826 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002827 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002828 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002829 if (r != Py_NotImplemented || \
2830 other->ob_type == self->ob_type) \
2831 return r; \
2832 Py_DECREF(r); \
2833 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002834 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002835 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002836 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002837 } \
2838 Py_INCREF(Py_NotImplemented); \
2839 return Py_NotImplemented; \
2840}
2841
2842#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2843 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2844
2845#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2846static PyObject * \
2847FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2848{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002849 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002850 return call_method(self, OPSTR, &cache_str, \
2851 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002852}
2853
2854static int
2855slot_sq_length(PyObject *self)
2856{
Guido van Rossum2730b132001-08-28 18:22:14 +00002857 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002858 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002859 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002860
2861 if (res == NULL)
2862 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002863 len = (int)PyInt_AsLong(res);
2864 Py_DECREF(res);
2865 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002866}
2867
Guido van Rossumdc91b992001-08-08 22:26:22 +00002868SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2869SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002870
2871/* Super-optimized version of slot_sq_item.
2872 Other slots could do the same... */
2873static PyObject *
2874slot_sq_item(PyObject *self, int i)
2875{
2876 static PyObject *getitem_str;
2877 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2878 descrgetfunc f;
2879
2880 if (getitem_str == NULL) {
2881 getitem_str = PyString_InternFromString("__getitem__");
2882 if (getitem_str == NULL)
2883 return NULL;
2884 }
2885 func = _PyType_Lookup(self->ob_type, getitem_str);
2886 if (func != NULL) {
2887 if (func->ob_type == &PyWrapperDescr_Type) {
2888 PyWrapperDescrObject *wrapper =
2889 (PyWrapperDescrObject *)func;
2890 if (wrapper->d_base->wrapper == wrap_sq_item) {
2891 intargfunc f;
2892 f = (intargfunc)(wrapper->d_wrapped);
2893 return f(self, i);
2894 }
2895 }
2896 if ((f = func->ob_type->tp_descr_get) == NULL)
2897 Py_INCREF(func);
2898 else
2899 func = f(func, self, (PyObject *)(self->ob_type));
2900 ival = PyInt_FromLong(i);
2901 if (ival != NULL) {
2902 args = PyTuple_New(1);
2903 if (args != NULL) {
2904 PyTuple_SET_ITEM(args, 0, ival);
2905 retval = PyObject_Call(func, args, NULL);
2906 Py_XDECREF(args);
2907 Py_XDECREF(func);
2908 return retval;
2909 }
2910 }
2911 }
2912 else {
2913 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2914 }
2915 Py_XDECREF(args);
2916 Py_XDECREF(ival);
2917 Py_XDECREF(func);
2918 return NULL;
2919}
2920
Guido van Rossumdc91b992001-08-08 22:26:22 +00002921SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002922
2923static int
2924slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2925{
2926 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002927 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002928
2929 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002930 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002931 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002932 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002933 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002934 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002935 if (res == NULL)
2936 return -1;
2937 Py_DECREF(res);
2938 return 0;
2939}
2940
2941static int
2942slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2943{
2944 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002945 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946
2947 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002948 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002949 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002950 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002951 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002952 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002953 if (res == NULL)
2954 return -1;
2955 Py_DECREF(res);
2956 return 0;
2957}
2958
2959static int
2960slot_sq_contains(PyObject *self, PyObject *value)
2961{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002962 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002963 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002964
Guido van Rossum55f20992001-10-01 17:18:22 +00002965 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002966
2967 if (func != NULL) {
2968 args = Py_BuildValue("(O)", value);
2969 if (args == NULL)
2970 res = NULL;
2971 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002972 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002973 Py_DECREF(args);
2974 }
2975 Py_DECREF(func);
2976 if (res == NULL)
2977 return -1;
2978 return PyObject_IsTrue(res);
2979 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002980 else if (PyErr_Occurred())
2981 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002982 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002983 return _PySequence_IterSearch(self, value,
2984 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002985 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002986}
2987
Guido van Rossumdc91b992001-08-08 22:26:22 +00002988SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2989SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002990
2991#define slot_mp_length slot_sq_length
2992
Guido van Rossumdc91b992001-08-08 22:26:22 +00002993SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002994
2995static int
2996slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2997{
2998 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002999 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003000
3001 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003002 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003003 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003004 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003005 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003006 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003007 if (res == NULL)
3008 return -1;
3009 Py_DECREF(res);
3010 return 0;
3011}
3012
Guido van Rossumdc91b992001-08-08 22:26:22 +00003013SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3014SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3015SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3016SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3017SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3018SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3019
3020staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3021
3022SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3023 nb_power, "__pow__", "__rpow__")
3024
3025static PyObject *
3026slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3027{
Guido van Rossum2730b132001-08-28 18:22:14 +00003028 static PyObject *pow_str;
3029
Guido van Rossumdc91b992001-08-08 22:26:22 +00003030 if (modulus == Py_None)
3031 return slot_nb_power_binary(self, other);
3032 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003033 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003034 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003035}
3036
3037SLOT0(slot_nb_negative, "__neg__")
3038SLOT0(slot_nb_positive, "__pos__")
3039SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040
3041static int
3042slot_nb_nonzero(PyObject *self)
3043{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003044 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003045 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003046
Guido van Rossum55f20992001-10-01 17:18:22 +00003047 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003048 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003049 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003050 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003051 func = lookup_maybe(self, "__len__", &len_str);
3052 if (func == NULL) {
3053 if (PyErr_Occurred())
3054 return -1;
3055 else
3056 return 1;
3057 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003058 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003059 res = PyObject_CallObject(func, NULL);
3060 Py_DECREF(func);
3061 if (res == NULL)
3062 return -1;
3063 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003064}
3065
Guido van Rossumdc91b992001-08-08 22:26:22 +00003066SLOT0(slot_nb_invert, "__invert__")
3067SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3068SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3069SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3070SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3071SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003072
3073static int
3074slot_nb_coerce(PyObject **a, PyObject **b)
3075{
3076 static PyObject *coerce_str;
3077 PyObject *self = *a, *other = *b;
3078
3079 if (self->ob_type->tp_as_number != NULL &&
3080 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3081 PyObject *r;
3082 r = call_maybe(
3083 self, "__coerce__", &coerce_str, "(O)", other);
3084 if (r == NULL)
3085 return -1;
3086 if (r == Py_NotImplemented) {
3087 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003088 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003089 else {
3090 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3091 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003092 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003093 Py_DECREF(r);
3094 return -1;
3095 }
3096 *a = PyTuple_GET_ITEM(r, 0);
3097 Py_INCREF(*a);
3098 *b = PyTuple_GET_ITEM(r, 1);
3099 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003100 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003101 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003102 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003103 }
3104 if (other->ob_type->tp_as_number != NULL &&
3105 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3106 PyObject *r;
3107 r = call_maybe(
3108 other, "__coerce__", &coerce_str, "(O)", self);
3109 if (r == NULL)
3110 return -1;
3111 if (r == Py_NotImplemented) {
3112 Py_DECREF(r);
3113 return 1;
3114 }
3115 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3116 PyErr_SetString(PyExc_TypeError,
3117 "__coerce__ didn't return a 2-tuple");
3118 Py_DECREF(r);
3119 return -1;
3120 }
3121 *a = PyTuple_GET_ITEM(r, 1);
3122 Py_INCREF(*a);
3123 *b = PyTuple_GET_ITEM(r, 0);
3124 Py_INCREF(*b);
3125 Py_DECREF(r);
3126 return 0;
3127 }
3128 return 1;
3129}
3130
Guido van Rossumdc91b992001-08-08 22:26:22 +00003131SLOT0(slot_nb_int, "__int__")
3132SLOT0(slot_nb_long, "__long__")
3133SLOT0(slot_nb_float, "__float__")
3134SLOT0(slot_nb_oct, "__oct__")
3135SLOT0(slot_nb_hex, "__hex__")
3136SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3137SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3138SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3139SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3140SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3141SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3142SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3143SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3144SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3145SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3146SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3147SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3148 "__floordiv__", "__rfloordiv__")
3149SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3150SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3151SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152
3153static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003154half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003155{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003156 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003157 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003158 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003159
Guido van Rossum60718732001-08-28 17:47:51 +00003160 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003161 if (func == NULL) {
3162 PyErr_Clear();
3163 }
3164 else {
3165 args = Py_BuildValue("(O)", other);
3166 if (args == NULL)
3167 res = NULL;
3168 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003169 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003170 Py_DECREF(args);
3171 }
3172 if (res != Py_NotImplemented) {
3173 if (res == NULL)
3174 return -2;
3175 c = PyInt_AsLong(res);
3176 Py_DECREF(res);
3177 if (c == -1 && PyErr_Occurred())
3178 return -2;
3179 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3180 }
3181 Py_DECREF(res);
3182 }
3183 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003184}
3185
Guido van Rossumab3b0342001-09-18 20:38:53 +00003186/* This slot is published for the benefit of try_3way_compare in object.c */
3187int
3188_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003189{
3190 int c;
3191
Guido van Rossumab3b0342001-09-18 20:38:53 +00003192 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003193 c = half_compare(self, other);
3194 if (c <= 1)
3195 return c;
3196 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003197 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003198 c = half_compare(other, self);
3199 if (c < -1)
3200 return -2;
3201 if (c <= 1)
3202 return -c;
3203 }
3204 return (void *)self < (void *)other ? -1 :
3205 (void *)self > (void *)other ? 1 : 0;
3206}
3207
3208static PyObject *
3209slot_tp_repr(PyObject *self)
3210{
3211 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003212 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003213
Guido van Rossum60718732001-08-28 17:47:51 +00003214 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003215 if (func != NULL) {
3216 res = PyEval_CallObject(func, NULL);
3217 Py_DECREF(func);
3218 return res;
3219 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003220 PyErr_Clear();
3221 return PyString_FromFormat("<%s object at %p>",
3222 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003223}
3224
3225static PyObject *
3226slot_tp_str(PyObject *self)
3227{
3228 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003229 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003230
Guido van Rossum60718732001-08-28 17:47:51 +00003231 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003232 if (func != NULL) {
3233 res = PyEval_CallObject(func, NULL);
3234 Py_DECREF(func);
3235 return res;
3236 }
3237 else {
3238 PyErr_Clear();
3239 return slot_tp_repr(self);
3240 }
3241}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003242
3243static long
3244slot_tp_hash(PyObject *self)
3245{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003246 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003247 static PyObject *hash_str, *eq_str, *cmp_str;
3248
Tim Peters6d6c1a32001-08-02 04:15:00 +00003249 long h;
3250
Guido van Rossum60718732001-08-28 17:47:51 +00003251 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003252
3253 if (func != NULL) {
3254 res = PyEval_CallObject(func, NULL);
3255 Py_DECREF(func);
3256 if (res == NULL)
3257 return -1;
3258 h = PyInt_AsLong(res);
3259 }
3260 else {
3261 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003262 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003263 if (func == NULL) {
3264 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003265 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003266 }
3267 if (func != NULL) {
3268 Py_DECREF(func);
3269 PyErr_SetString(PyExc_TypeError, "unhashable type");
3270 return -1;
3271 }
3272 PyErr_Clear();
3273 h = _Py_HashPointer((void *)self);
3274 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003275 if (h == -1 && !PyErr_Occurred())
3276 h = -2;
3277 return h;
3278}
3279
3280static PyObject *
3281slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3282{
Guido van Rossum60718732001-08-28 17:47:51 +00003283 static PyObject *call_str;
3284 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003285 PyObject *res;
3286
3287 if (meth == NULL)
3288 return NULL;
3289 res = PyObject_Call(meth, args, kwds);
3290 Py_DECREF(meth);
3291 return res;
3292}
3293
Tim Peters6d6c1a32001-08-02 04:15:00 +00003294static PyObject *
3295slot_tp_getattro(PyObject *self, PyObject *name)
3296{
3297 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003298 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003299 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003300
Guido van Rossum8e248182001-08-12 05:17:56 +00003301 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003302 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003303 if (getattr_str == NULL)
3304 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003305 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003306 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003307 if (getattr == NULL) {
3308 /* Avoid further slowdowns */
3309 if (tp->tp_getattro == slot_tp_getattro)
3310 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003311 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003312 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003313 return PyObject_CallFunction(getattr, "OO", self, name);
3314}
3315
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003316static PyObject *
3317slot_tp_getattr_hook(PyObject *self, PyObject *name)
3318{
3319 PyTypeObject *tp = self->ob_type;
3320 PyObject *getattr, *getattribute, *res;
3321 static PyObject *getattribute_str = NULL;
3322 static PyObject *getattr_str = NULL;
3323
3324 if (getattr_str == NULL) {
3325 getattr_str = PyString_InternFromString("__getattr__");
3326 if (getattr_str == NULL)
3327 return NULL;
3328 }
3329 if (getattribute_str == NULL) {
3330 getattribute_str =
3331 PyString_InternFromString("__getattribute__");
3332 if (getattribute_str == NULL)
3333 return NULL;
3334 }
3335 getattr = _PyType_Lookup(tp, getattr_str);
3336 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003337 if (getattribute != NULL &&
3338 getattribute->ob_type == &PyWrapperDescr_Type &&
3339 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3340 PyObject_GenericGetAttr)
3341 getattribute = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003342 if (getattr == NULL && getattribute == NULL) {
3343 /* Avoid further slowdowns */
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003344 /* XXX This is questionable: it means that a class that
3345 isn't born with __getattr__ or __getattribute__ cannot
3346 acquire them in later life. But it's a relatively big
3347 speedup, so I'm keeping it in for now. If this is
3348 removed, you can also remove the "def __getattr__" from
3349 class C (marked with another XXX comment) in dynamics()
3350 in Lib/test/test_descr.py. */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003351 if (tp->tp_getattro == slot_tp_getattr_hook)
3352 tp->tp_getattro = PyObject_GenericGetAttr;
3353 return PyObject_GenericGetAttr(self, name);
3354 }
3355 if (getattribute == NULL)
3356 res = PyObject_GenericGetAttr(self, name);
3357 else
3358 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003359 if (getattr != NULL &&
3360 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003361 PyErr_Clear();
3362 res = PyObject_CallFunction(getattr, "OO", self, name);
3363 }
3364 return res;
3365}
3366
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367static int
3368slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3369{
3370 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003371 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003372
3373 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003374 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003375 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003376 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003377 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003378 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003379 if (res == NULL)
3380 return -1;
3381 Py_DECREF(res);
3382 return 0;
3383}
3384
3385/* Map rich comparison operators to their __xx__ namesakes */
3386static char *name_op[] = {
3387 "__lt__",
3388 "__le__",
3389 "__eq__",
3390 "__ne__",
3391 "__gt__",
3392 "__ge__",
3393};
3394
3395static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003396half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003397{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003398 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003399 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003400
Guido van Rossum60718732001-08-28 17:47:51 +00003401 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003402 if (func == NULL) {
3403 PyErr_Clear();
3404 Py_INCREF(Py_NotImplemented);
3405 return Py_NotImplemented;
3406 }
3407 args = Py_BuildValue("(O)", other);
3408 if (args == NULL)
3409 res = NULL;
3410 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003411 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003412 Py_DECREF(args);
3413 }
3414 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003415 return res;
3416}
3417
Guido van Rossumb8f63662001-08-15 23:57:02 +00003418/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3419static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3420
3421static PyObject *
3422slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3423{
3424 PyObject *res;
3425
3426 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3427 res = half_richcompare(self, other, op);
3428 if (res != Py_NotImplemented)
3429 return res;
3430 Py_DECREF(res);
3431 }
3432 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3433 res = half_richcompare(other, self, swapped_op[op]);
3434 if (res != Py_NotImplemented) {
3435 return res;
3436 }
3437 Py_DECREF(res);
3438 }
3439 Py_INCREF(Py_NotImplemented);
3440 return Py_NotImplemented;
3441}
3442
3443static PyObject *
3444slot_tp_iter(PyObject *self)
3445{
3446 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003447 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003448
Guido van Rossum60718732001-08-28 17:47:51 +00003449 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003450 if (func != NULL) {
3451 res = PyObject_CallObject(func, NULL);
3452 Py_DECREF(func);
3453 return res;
3454 }
3455 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003456 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003457 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003458 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003459 return NULL;
3460 }
3461 Py_DECREF(func);
3462 return PySeqIter_New(self);
3463}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003464
3465static PyObject *
3466slot_tp_iternext(PyObject *self)
3467{
Guido van Rossum2730b132001-08-28 18:22:14 +00003468 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003469 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003470}
3471
Guido van Rossum1a493502001-08-17 16:47:50 +00003472static PyObject *
3473slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3474{
3475 PyTypeObject *tp = self->ob_type;
3476 PyObject *get;
3477 static PyObject *get_str = NULL;
3478
3479 if (get_str == NULL) {
3480 get_str = PyString_InternFromString("__get__");
3481 if (get_str == NULL)
3482 return NULL;
3483 }
3484 get = _PyType_Lookup(tp, get_str);
3485 if (get == NULL) {
3486 /* Avoid further slowdowns */
3487 if (tp->tp_descr_get == slot_tp_descr_get)
3488 tp->tp_descr_get = NULL;
3489 Py_INCREF(self);
3490 return self;
3491 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003492 if (obj == NULL)
3493 obj = Py_None;
3494 if (type == NULL)
3495 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003496 return PyObject_CallFunction(get, "OOO", self, obj, type);
3497}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003498
3499static int
3500slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3501{
Guido van Rossum2c252392001-08-24 10:13:31 +00003502 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003503 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003504
3505 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003506 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003507 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003508 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003509 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003510 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003511 if (res == NULL)
3512 return -1;
3513 Py_DECREF(res);
3514 return 0;
3515}
3516
3517static int
3518slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3519{
Guido van Rossum60718732001-08-28 17:47:51 +00003520 static PyObject *init_str;
3521 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003522 PyObject *res;
3523
3524 if (meth == NULL)
3525 return -1;
3526 res = PyObject_Call(meth, args, kwds);
3527 Py_DECREF(meth);
3528 if (res == NULL)
3529 return -1;
3530 Py_DECREF(res);
3531 return 0;
3532}
3533
3534static PyObject *
3535slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3536{
3537 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3538 PyObject *newargs, *x;
3539 int i, n;
3540
3541 if (func == NULL)
3542 return NULL;
3543 assert(PyTuple_Check(args));
3544 n = PyTuple_GET_SIZE(args);
3545 newargs = PyTuple_New(n+1);
3546 if (newargs == NULL)
3547 return NULL;
3548 Py_INCREF(type);
3549 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3550 for (i = 0; i < n; i++) {
3551 x = PyTuple_GET_ITEM(args, i);
3552 Py_INCREF(x);
3553 PyTuple_SET_ITEM(newargs, i+1, x);
3554 }
3555 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003556 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003557 Py_DECREF(func);
3558 return x;
3559}
3560
Guido van Rossumf040ede2001-08-07 16:40:56 +00003561/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003562 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003563 The dict argument is the dictionary argument passed to type_new(),
3564 which is the local namespace of the class statement, in other
3565 words, it contains the methods. For each special method (like
3566 __repr__) defined in the dictionary, the corresponding function
3567 slot in the type object (like tp_repr) is set to a special function
3568 whose name is 'slot_' followed by the slot name and whose signature
3569 is whatever is required for that slot. These slot functions look
3570 up the corresponding method in the type's dictionary and call it.
3571 The slot functions have to take care of the various peculiarities
3572 of the mapping between slots and special methods, such as mapping
3573 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3574 etc.) or mapping multiple slots to a single method (sq_item,
3575 mp_subscript <--> __getitem__). */
3576
Tim Peters6d6c1a32001-08-02 04:15:00 +00003577static void
3578override_slots(PyTypeObject *type, PyObject *dict)
3579{
3580 PySequenceMethods *sq = type->tp_as_sequence;
3581 PyMappingMethods *mp = type->tp_as_mapping;
3582 PyNumberMethods *nb = type->tp_as_number;
3583
Guido van Rossumdc91b992001-08-08 22:26:22 +00003584#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003585 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003586 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003587 }
3588
Guido van Rossumdc91b992001-08-08 22:26:22 +00003589#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003590 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003591 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003592 }
3593
Guido van Rossumdc91b992001-08-08 22:26:22 +00003594#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003595 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003596 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003597 }
3598
Guido van Rossumdc91b992001-08-08 22:26:22 +00003599#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003600 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003601 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602 }
3603
Guido van Rossumdc91b992001-08-08 22:26:22 +00003604 SQSLOT("__len__", sq_length, slot_sq_length);
3605 SQSLOT("__add__", sq_concat, slot_sq_concat);
3606 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3607 SQSLOT("__getitem__", sq_item, slot_sq_item);
3608 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3609 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3610 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3611 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3612 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3613 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3614 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3615 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003616
Guido van Rossumdc91b992001-08-08 22:26:22 +00003617 MPSLOT("__len__", mp_length, slot_mp_length);
3618 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3619 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3620 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003621
Guido van Rossumdc91b992001-08-08 22:26:22 +00003622 NBSLOT("__add__", nb_add, slot_nb_add);
3623 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3624 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3625 NBSLOT("__div__", nb_divide, slot_nb_divide);
3626 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3627 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3628 NBSLOT("__pow__", nb_power, slot_nb_power);
3629 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3630 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3631 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3632 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3633 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3634 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3635 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3636 NBSLOT("__and__", nb_and, slot_nb_and);
3637 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3638 NBSLOT("__or__", nb_or, slot_nb_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003639 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003640 NBSLOT("__int__", nb_int, slot_nb_int);
3641 NBSLOT("__long__", nb_long, slot_nb_long);
3642 NBSLOT("__float__", nb_float, slot_nb_float);
3643 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3644 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3645 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3646 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3647 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3648 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3649 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3650 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3651 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3652 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3653 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3654 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3655 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3656 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3657 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3658 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3659 slot_nb_inplace_floor_divide);
3660 NBSLOT("__itruediv__", nb_inplace_true_divide,
3661 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003662
Guido van Rossum8e248182001-08-12 05:17:56 +00003663 if (dict == NULL ||
3664 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003665 PyDict_GetItemString(dict, "__repr__"))
3666 type->tp_print = NULL;
3667
Guido van Rossumab3b0342001-09-18 20:38:53 +00003668 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003669 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3670 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3671 TPSLOT("__call__", tp_call, slot_tp_call);
3672 TPSLOT("__str__", tp_str, slot_tp_str);
Guido van Rossum867a8d22001-09-21 19:29:08 +00003673 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003674 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003675 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3676 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3677 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3678 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3679 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3680 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3681 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3682 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3683 TPSLOT("next", tp_iternext, slot_tp_iternext);
3684 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3685 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3686 TPSLOT("__init__", tp_init, slot_tp_init);
3687 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003689
3690
3691/* Cooperative 'super' */
3692
3693typedef struct {
3694 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003695 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003696 PyObject *obj;
3697} superobject;
3698
Guido van Rossum6f799372001-09-20 20:46:19 +00003699static PyMemberDef super_members[] = {
3700 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3701 "the class invoking super()"},
3702 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3703 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003704 {0}
3705};
3706
Guido van Rossum705f0f52001-08-24 16:47:00 +00003707static void
3708super_dealloc(PyObject *self)
3709{
3710 superobject *su = (superobject *)self;
3711
Guido van Rossum048eb752001-10-02 21:24:57 +00003712 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003713 Py_XDECREF(su->obj);
3714 Py_XDECREF(su->type);
3715 self->ob_type->tp_free(self);
3716}
3717
3718static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003719super_repr(PyObject *self)
3720{
3721 superobject *su = (superobject *)self;
3722
3723 if (su->obj)
3724 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003725 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003726 su->type ? su->type->tp_name : "NULL",
3727 su->obj->ob_type->tp_name);
3728 else
3729 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003730 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003731 su->type ? su->type->tp_name : "NULL");
3732}
3733
3734static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003735super_getattro(PyObject *self, PyObject *name)
3736{
3737 superobject *su = (superobject *)self;
3738
3739 if (su->obj != NULL) {
3740 PyObject *mro, *res, *tmp;
3741 descrgetfunc f;
3742 int i, n;
3743
Guido van Rossume705ef12001-08-29 15:47:06 +00003744 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003745 if (mro == NULL)
3746 n = 0;
3747 else {
3748 assert(PyTuple_Check(mro));
3749 n = PyTuple_GET_SIZE(mro);
3750 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003751 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003752 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003753 break;
3754 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003755 if (i >= n && PyType_Check(su->obj)) {
3756 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003757 if (mro == NULL)
3758 n = 0;
3759 else {
3760 assert(PyTuple_Check(mro));
3761 n = PyTuple_GET_SIZE(mro);
3762 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003763 for (i = 0; i < n; i++) {
3764 if ((PyObject *)(su->type) ==
3765 PyTuple_GET_ITEM(mro, i))
3766 break;
3767 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003768 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003769 i++;
3770 res = NULL;
3771 for (; i < n; i++) {
3772 tmp = PyTuple_GET_ITEM(mro, i);
3773 assert(PyType_Check(tmp));
3774 res = PyDict_GetItem(
3775 ((PyTypeObject *)tmp)->tp_defined, name);
3776 if (res != NULL) {
3777 Py_INCREF(res);
3778 f = res->ob_type->tp_descr_get;
3779 if (f != NULL) {
3780 tmp = f(res, su->obj, res);
3781 Py_DECREF(res);
3782 res = tmp;
3783 }
3784 return res;
3785 }
3786 }
3787 }
3788 return PyObject_GenericGetAttr(self, name);
3789}
3790
3791static PyObject *
3792super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3793{
3794 superobject *su = (superobject *)self;
3795 superobject *new;
3796
3797 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3798 /* Not binding to an object, or already bound */
3799 Py_INCREF(self);
3800 return self;
3801 }
3802 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3803 if (new == NULL)
3804 return NULL;
3805 Py_INCREF(su->type);
3806 Py_INCREF(obj);
3807 new->type = su->type;
3808 new->obj = obj;
3809 return (PyObject *)new;
3810}
3811
3812static int
3813super_init(PyObject *self, PyObject *args, PyObject *kwds)
3814{
3815 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003816 PyTypeObject *type;
3817 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003818
3819 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3820 return -1;
3821 if (obj == Py_None)
3822 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003823 if (obj != NULL &&
3824 !PyType_IsSubtype(obj->ob_type, type) &&
3825 !(PyType_Check(obj) &&
3826 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003827 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003828 "super(type, obj): "
3829 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003830 return -1;
3831 }
3832 Py_INCREF(type);
3833 Py_XINCREF(obj);
3834 su->type = type;
3835 su->obj = obj;
3836 return 0;
3837}
3838
3839static char super_doc[] =
3840"super(type) -> unbound super object\n"
3841"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003842"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003843"Typical use to call a cooperative superclass method:\n"
3844"class C(B):\n"
3845" def meth(self, arg):\n"
3846" super(C, self).meth(arg)";
3847
Guido van Rossum048eb752001-10-02 21:24:57 +00003848static int
3849super_traverse(PyObject *self, visitproc visit, void *arg)
3850{
3851 superobject *su = (superobject *)self;
3852 int err;
3853
3854#define VISIT(SLOT) \
3855 if (SLOT) { \
3856 err = visit((PyObject *)(SLOT), arg); \
3857 if (err) \
3858 return err; \
3859 }
3860
3861 VISIT(su->obj);
3862 VISIT(su->type);
3863
3864#undef VISIT
3865
3866 return 0;
3867}
3868
Guido van Rossum705f0f52001-08-24 16:47:00 +00003869PyTypeObject PySuper_Type = {
3870 PyObject_HEAD_INIT(&PyType_Type)
3871 0, /* ob_size */
3872 "super", /* tp_name */
3873 sizeof(superobject), /* tp_basicsize */
3874 0, /* tp_itemsize */
3875 /* methods */
3876 super_dealloc, /* tp_dealloc */
3877 0, /* tp_print */
3878 0, /* tp_getattr */
3879 0, /* tp_setattr */
3880 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003881 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003882 0, /* tp_as_number */
3883 0, /* tp_as_sequence */
3884 0, /* tp_as_mapping */
3885 0, /* tp_hash */
3886 0, /* tp_call */
3887 0, /* tp_str */
3888 super_getattro, /* tp_getattro */
3889 0, /* tp_setattro */
3890 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00003891 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3892 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003893 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00003894 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003895 0, /* tp_clear */
3896 0, /* tp_richcompare */
3897 0, /* tp_weaklistoffset */
3898 0, /* tp_iter */
3899 0, /* tp_iternext */
3900 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003901 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003902 0, /* tp_getset */
3903 0, /* tp_base */
3904 0, /* tp_dict */
3905 super_descr_get, /* tp_descr_get */
3906 0, /* tp_descr_set */
3907 0, /* tp_dictoffset */
3908 super_init, /* tp_init */
3909 PyType_GenericAlloc, /* tp_alloc */
3910 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00003911 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003912};