blob: 8f372292986f950ae543865261272f06aad4e70f [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{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000193 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000194 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000195
196 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000197 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000198 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000199 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000200
Neil Schemenauerc806c882001-08-29 23:54:54 +0000201 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000202 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000203
Neil Schemenauerc806c882001-08-29 23:54:54 +0000204 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000205
Tim Peters6d6c1a32001-08-02 04:15:00 +0000206 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
207 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000208
Tim Peters6d6c1a32001-08-02 04:15:00 +0000209 if (type->tp_itemsize == 0)
210 PyObject_INIT(obj, type);
211 else
212 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000213
Tim Peters6d6c1a32001-08-02 04:15:00 +0000214 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000215 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000216 return obj;
217}
218
219PyObject *
220PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
221{
222 return type->tp_alloc(type, 0);
223}
224
Guido van Rossum9475a232001-10-05 20:51:39 +0000225/* Helpers for subtyping */
226
227static int
228subtype_traverse(PyObject *self, visitproc visit, void *arg)
229{
230 PyTypeObject *type, *base;
231 traverseproc f;
232 int err;
233
234 /* Find the nearest base with a different tp_traverse */
235 type = self->ob_type;
236 base = type->tp_base;
237 while ((f = base->tp_traverse) == subtype_traverse) {
238 base = base->tp_base;
239 assert(base);
240 }
241
242 if (type->tp_dictoffset != base->tp_dictoffset) {
243 PyObject **dictptr = _PyObject_GetDictPtr(self);
244 if (dictptr && *dictptr) {
245 err = visit(*dictptr, arg);
246 if (err)
247 return err;
248 }
249 }
250
251 if (f)
252 return f(self, visit, arg);
253 return 0;
254}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000255
256static void
257subtype_dealloc(PyObject *self)
258{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000259 PyTypeObject *type, *base;
260 destructor f;
261
262 /* This exists so we can DECREF self->ob_type */
263
264 /* Find the nearest base with a different tp_dealloc */
265 type = self->ob_type;
266 base = type->tp_base;
267 while ((f = base->tp_dealloc) == subtype_dealloc) {
268 base = base->tp_base;
269 assert(base);
270 }
271
272 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000273 if (type->tp_dictoffset && !base->tp_dictoffset) {
274 PyObject **dictptr = _PyObject_GetDictPtr(self);
275 if (dictptr != NULL) {
276 PyObject *dict = *dictptr;
277 if (dict != NULL) {
278 Py_DECREF(dict);
279 *dictptr = NULL;
280 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000281 }
282 }
283
Guido van Rossum9676b222001-08-17 20:32:36 +0000284 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000285 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000286 PyObject_ClearWeakRefs(self);
287
Tim Peters6d6c1a32001-08-02 04:15:00 +0000288 /* Finalize GC if the base doesn't do GC and we do */
289 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000290 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000291
292 /* Call the base tp_dealloc() */
293 assert(f);
294 f(self);
295
296 /* Can't reference self beyond this point */
297 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
298 Py_DECREF(type);
299 }
300}
301
Tim Peters6d6c1a32001-08-02 04:15:00 +0000302staticforward PyTypeObject *solid_base(PyTypeObject *type);
303
304typedef struct {
305 PyTypeObject type;
306 PyNumberMethods as_number;
307 PySequenceMethods as_sequence;
308 PyMappingMethods as_mapping;
309 PyBufferProcs as_buffer;
310 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000311 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000312} etype;
313
314/* type test with subclassing support */
315
316int
317PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
318{
319 PyObject *mro;
320
Guido van Rossum9478d072001-09-07 18:52:13 +0000321 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
322 return b == a || b == &PyBaseObject_Type;
323
Tim Peters6d6c1a32001-08-02 04:15:00 +0000324 mro = a->tp_mro;
325 if (mro != NULL) {
326 /* Deal with multiple inheritance without recursion
327 by walking the MRO tuple */
328 int i, n;
329 assert(PyTuple_Check(mro));
330 n = PyTuple_GET_SIZE(mro);
331 for (i = 0; i < n; i++) {
332 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
333 return 1;
334 }
335 return 0;
336 }
337 else {
338 /* a is not completely initilized yet; follow tp_base */
339 do {
340 if (a == b)
341 return 1;
342 a = a->tp_base;
343 } while (a != NULL);
344 return b == &PyBaseObject_Type;
345 }
346}
347
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000348/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000349 without looking in the instance dictionary
350 (so we can't use PyObject_GetAttr) but still binding
351 it to the instance. The arguments are the object,
352 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000353 static variable used to cache the interned Python string.
354
355 Two variants:
356
357 - lookup_maybe() returns NULL without raising an exception
358 when the _PyType_Lookup() call fails;
359
360 - lookup_method() always raises an exception upon errors.
361*/
Guido van Rossum60718732001-08-28 17:47:51 +0000362
363static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000364lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000365{
366 PyObject *res;
367
368 if (*attrobj == NULL) {
369 *attrobj = PyString_InternFromString(attrstr);
370 if (*attrobj == NULL)
371 return NULL;
372 }
373 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000374 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000375 descrgetfunc f;
376 if ((f = res->ob_type->tp_descr_get) == NULL)
377 Py_INCREF(res);
378 else
379 res = f(res, self, (PyObject *)(self->ob_type));
380 }
381 return res;
382}
383
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000384static PyObject *
385lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
386{
387 PyObject *res = lookup_maybe(self, attrstr, attrobj);
388 if (res == NULL && !PyErr_Occurred())
389 PyErr_SetObject(PyExc_AttributeError, *attrobj);
390 return res;
391}
392
Guido van Rossum2730b132001-08-28 18:22:14 +0000393/* A variation of PyObject_CallMethod that uses lookup_method()
394 instead of PyObject_GetAttrString(). This uses the same convention
395 as lookup_method to cache the interned name string object. */
396
397PyObject *
398call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
399{
400 va_list va;
401 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000402 va_start(va, format);
403
Guido van Rossumda21c012001-10-03 00:50:18 +0000404 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000405 if (func == NULL) {
406 va_end(va);
407 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000408 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000409 return NULL;
410 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000411
412 if (format && *format)
413 args = Py_VaBuildValue(format, va);
414 else
415 args = PyTuple_New(0);
416
417 va_end(va);
418
419 if (args == NULL)
420 return NULL;
421
422 assert(PyTuple_Check(args));
423 retval = PyObject_Call(func, args, NULL);
424
425 Py_DECREF(args);
426 Py_DECREF(func);
427
428 return retval;
429}
430
431/* Clone of call_method() that returns NotImplemented when the lookup fails. */
432
433PyObject *
434call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
435{
436 va_list va;
437 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000438 va_start(va, format);
439
Guido van Rossumda21c012001-10-03 00:50:18 +0000440 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000441 if (func == NULL) {
442 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000443 if (!PyErr_Occurred()) {
444 Py_INCREF(Py_NotImplemented);
445 return Py_NotImplemented;
446 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000447 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000448 }
449
450 if (format && *format)
451 args = Py_VaBuildValue(format, va);
452 else
453 args = PyTuple_New(0);
454
455 va_end(va);
456
Guido van Rossum717ce002001-09-14 16:58:08 +0000457 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000458 return NULL;
459
Guido van Rossum717ce002001-09-14 16:58:08 +0000460 assert(PyTuple_Check(args));
461 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000462
463 Py_DECREF(args);
464 Py_DECREF(func);
465
466 return retval;
467}
468
Tim Peters6d6c1a32001-08-02 04:15:00 +0000469/* Method resolution order algorithm from "Putting Metaclasses to Work"
470 by Forman and Danforth (Addison-Wesley 1999). */
471
472static int
473conservative_merge(PyObject *left, PyObject *right)
474{
475 int left_size;
476 int right_size;
477 int i, j, r, ok;
478 PyObject *temp, *rr;
479
480 assert(PyList_Check(left));
481 assert(PyList_Check(right));
482
483 again:
484 left_size = PyList_GET_SIZE(left);
485 right_size = PyList_GET_SIZE(right);
486 for (i = 0; i < left_size; i++) {
487 for (j = 0; j < right_size; j++) {
488 if (PyList_GET_ITEM(left, i) ==
489 PyList_GET_ITEM(right, j)) {
490 /* found a merge point */
491 temp = PyList_New(0);
492 if (temp == NULL)
493 return -1;
494 for (r = 0; r < j; r++) {
495 rr = PyList_GET_ITEM(right, r);
496 ok = PySequence_Contains(left, rr);
497 if (ok < 0) {
498 Py_DECREF(temp);
499 return -1;
500 }
501 if (!ok) {
502 ok = PyList_Append(temp, rr);
503 if (ok < 0) {
504 Py_DECREF(temp);
505 return -1;
506 }
507 }
508 }
509 ok = PyList_SetSlice(left, i, i, temp);
510 Py_DECREF(temp);
511 if (ok < 0)
512 return -1;
513 ok = PyList_SetSlice(right, 0, j+1, NULL);
514 if (ok < 0)
515 return -1;
516 goto again;
517 }
518 }
519 }
520 return PyList_SetSlice(left, left_size, left_size, right);
521}
522
523static int
524serious_order_disagreements(PyObject *left, PyObject *right)
525{
526 return 0; /* XXX later -- for now, we cheat: "don't do that" */
527}
528
529static PyObject *
530mro_implementation(PyTypeObject *type)
531{
532 int i, n, ok;
533 PyObject *bases, *result;
534
535 bases = type->tp_bases;
536 n = PyTuple_GET_SIZE(bases);
537 result = Py_BuildValue("[O]", (PyObject *)type);
538 if (result == NULL)
539 return NULL;
540 for (i = 0; i < n; i++) {
541 PyTypeObject *base =
542 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
543 PyObject *parentMRO = PySequence_List(base->tp_mro);
544 if (parentMRO == NULL) {
545 Py_DECREF(result);
546 return NULL;
547 }
548 if (serious_order_disagreements(result, parentMRO)) {
549 Py_DECREF(result);
550 return NULL;
551 }
552 ok = conservative_merge(result, parentMRO);
553 Py_DECREF(parentMRO);
554 if (ok < 0) {
555 Py_DECREF(result);
556 return NULL;
557 }
558 }
559 return result;
560}
561
562static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000563mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000564{
565 PyTypeObject *type = (PyTypeObject *)self;
566
Tim Peters6d6c1a32001-08-02 04:15:00 +0000567 return mro_implementation(type);
568}
569
570static int
571mro_internal(PyTypeObject *type)
572{
573 PyObject *mro, *result, *tuple;
574
575 if (type->ob_type == &PyType_Type) {
576 result = mro_implementation(type);
577 }
578 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000579 static PyObject *mro_str;
580 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000581 if (mro == NULL)
582 return -1;
583 result = PyObject_CallObject(mro, NULL);
584 Py_DECREF(mro);
585 }
586 if (result == NULL)
587 return -1;
588 tuple = PySequence_Tuple(result);
589 Py_DECREF(result);
590 type->tp_mro = tuple;
591 return 0;
592}
593
594
595/* Calculate the best base amongst multiple base classes.
596 This is the first one that's on the path to the "solid base". */
597
598static PyTypeObject *
599best_base(PyObject *bases)
600{
601 int i, n;
602 PyTypeObject *base, *winner, *candidate, *base_i;
603
604 assert(PyTuple_Check(bases));
605 n = PyTuple_GET_SIZE(bases);
606 assert(n > 0);
607 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
608 winner = &PyBaseObject_Type;
609 for (i = 0; i < n; i++) {
610 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
611 if (!PyType_Check((PyObject *)base_i)) {
612 PyErr_SetString(
613 PyExc_TypeError,
614 "bases must be types");
615 return NULL;
616 }
617 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000618 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000619 return NULL;
620 }
621 candidate = solid_base(base_i);
622 if (PyType_IsSubtype(winner, candidate))
623 ;
624 else if (PyType_IsSubtype(candidate, winner)) {
625 winner = candidate;
626 base = base_i;
627 }
628 else {
629 PyErr_SetString(
630 PyExc_TypeError,
631 "multiple bases have "
632 "instance lay-out conflict");
633 return NULL;
634 }
635 }
636 assert(base != NULL);
637 return base;
638}
639
640static int
641extra_ivars(PyTypeObject *type, PyTypeObject *base)
642{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000643 size_t t_size = type->tp_basicsize;
644 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000645
Guido van Rossum9676b222001-08-17 20:32:36 +0000646 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000647 if (type->tp_itemsize || base->tp_itemsize) {
648 /* If itemsize is involved, stricter rules */
649 return t_size != b_size ||
650 type->tp_itemsize != base->tp_itemsize;
651 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000652 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
653 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
654 t_size -= sizeof(PyObject *);
655 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
656 type->tp_dictoffset + sizeof(PyObject *) == t_size)
657 t_size -= sizeof(PyObject *);
658
659 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000660}
661
662static PyTypeObject *
663solid_base(PyTypeObject *type)
664{
665 PyTypeObject *base;
666
667 if (type->tp_base)
668 base = solid_base(type->tp_base);
669 else
670 base = &PyBaseObject_Type;
671 if (extra_ivars(type, base))
672 return type;
673 else
674 return base;
675}
676
677staticforward void object_dealloc(PyObject *);
678staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000679staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000680staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000681
682static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000683subtype_dict(PyObject *obj, void *context)
684{
685 PyObject **dictptr = _PyObject_GetDictPtr(obj);
686 PyObject *dict;
687
688 if (dictptr == NULL) {
689 PyErr_SetString(PyExc_AttributeError,
690 "This object has no __dict__");
691 return NULL;
692 }
693 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000694 if (dict == NULL)
695 *dictptr = dict = PyDict_New();
696 Py_XINCREF(dict);
697 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000698}
699
Guido van Rossum32d34c82001-09-20 21:45:26 +0000700PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000701 {"__dict__", subtype_dict, NULL, NULL},
702 {0},
703};
704
705static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000706type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
707{
708 PyObject *name, *bases, *dict;
709 static char *kwlist[] = {"name", "bases", "dict", 0};
710 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000711 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000712 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000713 PyMemberDef *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000714 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000715
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000716 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000717 if (metatype == &PyType_Type &&
718 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
719 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000720 PyObject *x = PyTuple_GET_ITEM(args, 0);
721 Py_INCREF(x->ob_type);
722 return (PyObject *) x->ob_type;
723 }
724
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000725 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000726 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
727 &name,
728 &PyTuple_Type, &bases,
729 &PyDict_Type, &dict))
730 return NULL;
731
732 /* Determine the proper metatype to deal with this,
733 and check for metatype conflicts while we're at it.
734 Note that if some other metatype wins to contract,
735 it's possible that its instances are not types. */
736 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000737 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000738 for (i = 0; i < nbases; i++) {
739 tmp = PyTuple_GET_ITEM(bases, i);
740 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000741 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000742 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000743 if (PyType_IsSubtype(tmptype, winner)) {
744 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000745 continue;
746 }
747 PyErr_SetString(PyExc_TypeError,
748 "metatype conflict among bases");
749 return NULL;
750 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000751 if (winner != metatype) {
752 if (winner->tp_new != type_new) /* Pass it to the winner */
753 return winner->tp_new(winner, args, kwds);
754 metatype = winner;
755 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000756
757 /* Adjust for empty tuple bases */
758 if (nbases == 0) {
759 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
760 if (bases == NULL)
761 return NULL;
762 nbases = 1;
763 }
764 else
765 Py_INCREF(bases);
766
767 /* XXX From here until type is allocated, "return NULL" leaks bases! */
768
769 /* Calculate best base, and check that all bases are type objects */
770 base = best_base(bases);
771 if (base == NULL)
772 return NULL;
773 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
774 PyErr_Format(PyExc_TypeError,
775 "type '%.100s' is not an acceptable base type",
776 base->tp_name);
777 return NULL;
778 }
779
Guido van Rossum1a493502001-08-17 16:47:50 +0000780 /* Should this be a dynamic class (i.e. modifiable __dict__)?
781 Look in two places for a variable named __dynamic__:
782 1) in the class dict
783 2) in the module dict (globals)
784 The first variable that is an int >= 0 is used.
Guido van Rossum50fda3b2001-10-04 19:46:06 +0000785 Otherwise, the default is dynamic. */
Guido van Rossum1a493502001-08-17 16:47:50 +0000786 dynamic = -1; /* Not yet determined */
787 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000788 tmp = PyDict_GetItemString(dict, "__dynamic__");
789 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000790 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000791 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000792 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000793 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000794 if (dynamic < 0) {
795 /* Look in the module globals */
796 tmp = PyEval_GetGlobals();
797 if (tmp != NULL) {
798 tmp = PyDict_GetItemString(tmp, "__dynamic__");
799 if (tmp != NULL) {
800 dynamic = PyInt_AsLong(tmp);
801 if (dynamic < 0)
802 PyErr_Clear();
803 }
804 }
805 }
806 if (dynamic < 0) {
Guido van Rossum50fda3b2001-10-04 19:46:06 +0000807 /* Default to dynamic */
808 dynamic = 1;
809
Tim Peters6d6c1a32001-08-02 04:15:00 +0000810 }
811
812 /* Check for a __slots__ sequence variable in dict, and count it */
813 slots = PyDict_GetItemString(dict, "__slots__");
814 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000815 add_dict = 0;
816 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000817 if (slots != NULL) {
818 /* Make it into a tuple */
819 if (PyString_Check(slots))
820 slots = Py_BuildValue("(O)", slots);
821 else
822 slots = PySequence_Tuple(slots);
823 if (slots == NULL)
824 return NULL;
825 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000826 if (nslots > 0 && base->tp_itemsize != 0) {
827 PyErr_Format(PyExc_TypeError,
828 "nonempty __slots__ "
829 "not supported for subtype of '%s'",
830 base->tp_name);
831 return NULL;
832 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000833 for (i = 0; i < nslots; i++) {
834 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
835 PyErr_SetString(PyExc_TypeError,
836 "__slots__ must be a sequence of strings");
837 Py_DECREF(slots);
838 return NULL;
839 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000840 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000841 }
842 }
843 if (slots == NULL && base->tp_dictoffset == 0 &&
844 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000845 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000846 add_dict++;
847 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000848 if (slots == NULL && base->tp_weaklistoffset == 0 &&
849 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000850 nslots++;
851 add_weak++;
852 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000853
854 /* XXX From here until type is safely allocated,
855 "return NULL" may leak slots! */
856
857 /* Allocate the type object */
858 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
859 if (type == NULL)
860 return NULL;
861
862 /* Keep name and slots alive in the extended type object */
863 et = (etype *)type;
864 Py_INCREF(name);
865 et->name = name;
866 et->slots = slots;
867
Guido van Rossumdc91b992001-08-08 22:26:22 +0000868 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000869 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
870 Py_TPFLAGS_BASETYPE;
871 if (dynamic)
872 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000873 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
874 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000875
876 /* It's a new-style number unless it specifically inherits any
877 old-style numeric behavior */
878 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
879 (base->tp_as_number == NULL))
880 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
881
882 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000883 type->tp_as_number = &et->as_number;
884 type->tp_as_sequence = &et->as_sequence;
885 type->tp_as_mapping = &et->as_mapping;
886 type->tp_as_buffer = &et->as_buffer;
887 type->tp_name = PyString_AS_STRING(name);
888
889 /* Set tp_base and tp_bases */
890 type->tp_bases = bases;
891 Py_INCREF(base);
892 type->tp_base = base;
893
894 /* Initialize tp_defined from passed-in dict */
895 type->tp_defined = dict = PyDict_Copy(dict);
896 if (dict == NULL) {
897 Py_DECREF(type);
898 return NULL;
899 }
900
Guido van Rossumc3542212001-08-16 09:18:56 +0000901 /* Set __module__ in the dict */
902 if (PyDict_GetItemString(dict, "__module__") == NULL) {
903 tmp = PyEval_GetGlobals();
904 if (tmp != NULL) {
905 tmp = PyDict_GetItemString(tmp, "__name__");
906 if (tmp != NULL) {
907 if (PyDict_SetItemString(dict, "__module__",
908 tmp) < 0)
909 return NULL;
910 }
911 }
912 }
913
Tim Peters2f93e282001-10-04 05:27:00 +0000914 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
915 and is a string (tp_doc is a char* -- can't copy a general object
916 into it).
917 XXX What if it's a Unicode string? Don't know -- this ignores it.
918 */
919 {
920 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
921 if (doc != NULL && PyString_Check(doc)) {
922 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +0000923 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +0000924 if (type->tp_doc == NULL) {
925 Py_DECREF(type);
926 return NULL;
927 }
928 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
929 }
930 }
931
Tim Peters6d6c1a32001-08-02 04:15:00 +0000932 /* Special-case __new__: if it's a plain function,
933 make it a static function */
934 tmp = PyDict_GetItemString(dict, "__new__");
935 if (tmp != NULL && PyFunction_Check(tmp)) {
936 tmp = PyStaticMethod_New(tmp);
937 if (tmp == NULL) {
938 Py_DECREF(type);
939 return NULL;
940 }
941 PyDict_SetItemString(dict, "__new__", tmp);
942 Py_DECREF(tmp);
943 }
944
945 /* Add descriptors for custom slots from __slots__, or for __dict__ */
946 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000947 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000948 if (slots != NULL) {
949 for (i = 0; i < nslots; i++, mp++) {
950 mp->name = PyString_AS_STRING(
951 PyTuple_GET_ITEM(slots, i));
952 mp->type = T_OBJECT;
953 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000954 if (base->tp_weaklistoffset == 0 &&
955 strcmp(mp->name, "__weakref__") == 0)
956 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000957 slotoffset += sizeof(PyObject *);
958 }
959 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000960 else {
961 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000962 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +0000963 type->tp_dictoffset =
964 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000965 else
966 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000967 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000968 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000969 }
970 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000971 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000972 type->tp_weaklistoffset = slotoffset;
973 mp->name = "__weakref__";
974 mp->type = T_OBJECT;
975 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000976 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000977 mp++;
978 slotoffset += sizeof(PyObject *);
979 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000980 }
981 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000982 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000983 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000984
985 /* Special case some slots */
986 if (type->tp_dictoffset != 0 || nslots > 0) {
987 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
988 type->tp_getattro = PyObject_GenericGetAttr;
989 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
990 type->tp_setattro = PyObject_GenericSetAttr;
991 }
992 type->tp_dealloc = subtype_dealloc;
993
Guido van Rossum9475a232001-10-05 20:51:39 +0000994 /* Enable GC unless there are really no instance variables possible */
995 if (!(type->tp_basicsize == sizeof(PyObject) &&
996 type->tp_itemsize == 0))
997 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
998
Tim Peters6d6c1a32001-08-02 04:15:00 +0000999 /* Always override allocation strategy to use regular heap */
1000 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001001 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1002 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001003 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001004 type->tp_clear = base->tp_clear;
1005 }
1006 else
1007 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001008
1009 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001010 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001011 Py_DECREF(type);
1012 return NULL;
1013 }
1014
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001015 /* Put the proper slots in place */
1016 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001017
Tim Peters6d6c1a32001-08-02 04:15:00 +00001018 return (PyObject *)type;
1019}
1020
1021/* Internal API to look for a name through the MRO.
1022 This returns a borrowed reference, and doesn't set an exception! */
1023PyObject *
1024_PyType_Lookup(PyTypeObject *type, PyObject *name)
1025{
1026 int i, n;
1027 PyObject *mro, *res, *dict;
1028
1029 /* For static types, look in tp_dict */
1030 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
1031 dict = type->tp_dict;
1032 assert(dict && PyDict_Check(dict));
1033 return PyDict_GetItem(dict, name);
1034 }
1035
1036 /* For dynamic types, look in tp_defined of types in MRO */
1037 mro = type->tp_mro;
1038 assert(PyTuple_Check(mro));
1039 n = PyTuple_GET_SIZE(mro);
1040 for (i = 0; i < n; i++) {
1041 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
1042 assert(PyType_Check(type));
1043 dict = type->tp_defined;
1044 assert(dict && PyDict_Check(dict));
1045 res = PyDict_GetItem(dict, name);
1046 if (res != NULL)
1047 return res;
1048 }
1049 return NULL;
1050}
1051
1052/* This is similar to PyObject_GenericGetAttr(),
1053 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1054static PyObject *
1055type_getattro(PyTypeObject *type, PyObject *name)
1056{
1057 PyTypeObject *metatype = type->ob_type;
1058 PyObject *descr, *res;
1059 descrgetfunc f;
1060
1061 /* Initialize this type (we'll assume the metatype is initialized) */
1062 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001063 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001064 return NULL;
1065 }
1066
1067 /* Get a descriptor from the metatype */
1068 descr = _PyType_Lookup(metatype, name);
1069 f = NULL;
1070 if (descr != NULL) {
1071 f = descr->ob_type->tp_descr_get;
1072 if (f != NULL && PyDescr_IsData(descr))
1073 return f(descr,
1074 (PyObject *)type, (PyObject *)metatype);
1075 }
1076
1077 /* Look in tp_defined of this type and its bases */
1078 res = _PyType_Lookup(type, name);
1079 if (res != NULL) {
1080 f = res->ob_type->tp_descr_get;
1081 if (f != NULL)
1082 return f(res, (PyObject *)NULL, (PyObject *)type);
1083 Py_INCREF(res);
1084 return res;
1085 }
1086
1087 /* Use the descriptor from the metatype */
1088 if (f != NULL) {
1089 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1090 return res;
1091 }
1092 if (descr != NULL) {
1093 Py_INCREF(descr);
1094 return descr;
1095 }
1096
1097 /* Give up */
1098 PyErr_Format(PyExc_AttributeError,
1099 "type object '%.50s' has no attribute '%.400s'",
1100 type->tp_name, PyString_AS_STRING(name));
1101 return NULL;
1102}
1103
1104static int
1105type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1106{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001107 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
1108 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1109 return -1;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00001110 return update_slot(type, name);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001111 }
1112 PyErr_SetString(PyExc_TypeError, "can't set static type attributes");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113 return -1;
1114}
1115
1116static void
1117type_dealloc(PyTypeObject *type)
1118{
1119 etype *et;
1120
1121 /* Assert this is a heap-allocated type object */
1122 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001123 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001124 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001125 et = (etype *)type;
1126 Py_XDECREF(type->tp_base);
1127 Py_XDECREF(type->tp_dict);
1128 Py_XDECREF(type->tp_bases);
1129 Py_XDECREF(type->tp_mro);
1130 Py_XDECREF(type->tp_defined);
Guido van Rossum1c450732001-10-08 15:18:27 +00001131 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001132 Py_XDECREF(et->name);
1133 Py_XDECREF(et->slots);
1134 type->ob_type->tp_free((PyObject *)type);
1135}
1136
Guido van Rossum1c450732001-10-08 15:18:27 +00001137static PyObject *
1138type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1139{
1140 PyObject *list, *raw, *ref;
1141 int i, n;
1142
1143 list = PyList_New(0);
1144 if (list == NULL)
1145 return NULL;
1146 raw = type->tp_subclasses;
1147 if (raw == NULL)
1148 return list;
1149 assert(PyList_Check(raw));
1150 n = PyList_GET_SIZE(raw);
1151 for (i = 0; i < n; i++) {
1152 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001153 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001154 ref = PyWeakref_GET_OBJECT(ref);
1155 if (ref != Py_None) {
1156 if (PyList_Append(list, ref) < 0) {
1157 Py_DECREF(list);
1158 return NULL;
1159 }
1160 }
1161 }
1162 return list;
1163}
1164
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001166 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001167 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001168 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1169 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001170 {0}
1171};
1172
1173static char type_doc[] =
1174"type(object) -> the object's type\n"
1175"type(name, bases, dict) -> a new type";
1176
Guido van Rossum048eb752001-10-02 21:24:57 +00001177static int
1178type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1179{
1180 etype *et;
1181 int err;
1182
1183 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1184 return 0;
1185
1186 et = (etype *)type;
1187
1188#define VISIT(SLOT) \
1189 if (SLOT) { \
1190 err = visit((PyObject *)(SLOT), arg); \
1191 if (err) \
1192 return err; \
1193 }
1194
1195 VISIT(type->tp_dict);
1196 VISIT(type->tp_defined);
1197 VISIT(type->tp_mro);
1198 VISIT(type->tp_bases);
1199 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001200 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001201 VISIT(et->slots);
1202
1203#undef VISIT
1204
1205 return 0;
1206}
1207
1208static int
1209type_clear(PyTypeObject *type)
1210{
1211 etype *et;
1212 PyObject *tmp;
1213
1214 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1215 return 0;
1216
1217 et = (etype *)type;
1218
1219#define CLEAR(SLOT) \
1220 if (SLOT) { \
1221 tmp = (PyObject *)(SLOT); \
1222 SLOT = NULL; \
1223 Py_DECREF(tmp); \
1224 }
1225
1226 CLEAR(type->tp_dict);
1227 CLEAR(type->tp_defined);
1228 CLEAR(type->tp_mro);
1229 CLEAR(type->tp_bases);
1230 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001231 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001232 CLEAR(et->slots);
1233
Tim Peters2f93e282001-10-04 05:27:00 +00001234 if (type->tp_doc != NULL) {
1235 PyObject_FREE(type->tp_doc);
1236 type->tp_doc = NULL;
1237 }
1238
Guido van Rossum048eb752001-10-02 21:24:57 +00001239#undef CLEAR
1240
1241 return 0;
1242}
1243
1244static int
1245type_is_gc(PyTypeObject *type)
1246{
1247 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1248}
1249
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001250PyTypeObject PyType_Type = {
1251 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 0, /* ob_size */
1253 "type", /* tp_name */
1254 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001255 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001256 (destructor)type_dealloc, /* tp_dealloc */
1257 0, /* tp_print */
1258 0, /* tp_getattr */
1259 0, /* tp_setattr */
1260 type_compare, /* tp_compare */
1261 (reprfunc)type_repr, /* tp_repr */
1262 0, /* tp_as_number */
1263 0, /* tp_as_sequence */
1264 0, /* tp_as_mapping */
1265 (hashfunc)_Py_HashPointer, /* tp_hash */
1266 (ternaryfunc)type_call, /* tp_call */
1267 0, /* tp_str */
1268 (getattrofunc)type_getattro, /* tp_getattro */
1269 (setattrofunc)type_setattro, /* tp_setattro */
1270 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001271 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1272 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001274 (traverseproc)type_traverse, /* tp_traverse */
1275 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001276 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001277 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001278 0, /* tp_iter */
1279 0, /* tp_iternext */
1280 type_methods, /* tp_methods */
1281 type_members, /* tp_members */
1282 type_getsets, /* tp_getset */
1283 0, /* tp_base */
1284 0, /* tp_dict */
1285 0, /* tp_descr_get */
1286 0, /* tp_descr_set */
1287 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1288 0, /* tp_init */
1289 0, /* tp_alloc */
1290 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001291 _PyObject_GC_Del, /* tp_free */
1292 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001293};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294
1295
1296/* The base type of all types (eventually)... except itself. */
1297
1298static int
1299object_init(PyObject *self, PyObject *args, PyObject *kwds)
1300{
1301 return 0;
1302}
1303
1304static void
1305object_dealloc(PyObject *self)
1306{
1307 self->ob_type->tp_free(self);
1308}
1309
Guido van Rossum8e248182001-08-12 05:17:56 +00001310static PyObject *
1311object_repr(PyObject *self)
1312{
Guido van Rossum76e69632001-08-16 18:52:43 +00001313 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001314 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001315
Guido van Rossum76e69632001-08-16 18:52:43 +00001316 type = self->ob_type;
1317 mod = type_module(type, NULL);
1318 if (mod == NULL)
1319 PyErr_Clear();
1320 else if (!PyString_Check(mod)) {
1321 Py_DECREF(mod);
1322 mod = NULL;
1323 }
1324 name = type_name(type, NULL);
1325 if (name == NULL)
1326 return NULL;
1327 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001328 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001329 PyString_AS_STRING(mod),
1330 PyString_AS_STRING(name),
1331 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001332 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001333 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001334 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001335 Py_XDECREF(mod);
1336 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001337 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001338}
1339
Guido van Rossumb8f63662001-08-15 23:57:02 +00001340static PyObject *
1341object_str(PyObject *self)
1342{
1343 unaryfunc f;
1344
1345 f = self->ob_type->tp_repr;
1346 if (f == NULL)
1347 f = object_repr;
1348 return f(self);
1349}
1350
Guido van Rossum8e248182001-08-12 05:17:56 +00001351static long
1352object_hash(PyObject *self)
1353{
1354 return _Py_HashPointer(self);
1355}
Guido van Rossum8e248182001-08-12 05:17:56 +00001356
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001357static PyObject *
1358object_get_class(PyObject *self, void *closure)
1359{
1360 Py_INCREF(self->ob_type);
1361 return (PyObject *)(self->ob_type);
1362}
1363
1364static int
1365equiv_structs(PyTypeObject *a, PyTypeObject *b)
1366{
1367 return a == b ||
1368 (a != NULL &&
1369 b != NULL &&
1370 a->tp_basicsize == b->tp_basicsize &&
1371 a->tp_itemsize == b->tp_itemsize &&
1372 a->tp_dictoffset == b->tp_dictoffset &&
1373 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1374 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1375 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1376}
1377
1378static int
1379same_slots_added(PyTypeObject *a, PyTypeObject *b)
1380{
1381 PyTypeObject *base = a->tp_base;
1382 int size;
1383
1384 if (base != b->tp_base)
1385 return 0;
1386 if (equiv_structs(a, base) && equiv_structs(b, base))
1387 return 1;
1388 size = base->tp_basicsize;
1389 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1390 size += sizeof(PyObject *);
1391 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1392 size += sizeof(PyObject *);
1393 return size == a->tp_basicsize && size == b->tp_basicsize;
1394}
1395
1396static int
1397object_set_class(PyObject *self, PyObject *value, void *closure)
1398{
1399 PyTypeObject *old = self->ob_type;
1400 PyTypeObject *new, *newbase, *oldbase;
1401
1402 if (!PyType_Check(value)) {
1403 PyErr_Format(PyExc_TypeError,
1404 "__class__ must be set to new-style class, not '%s' object",
1405 value->ob_type->tp_name);
1406 return -1;
1407 }
1408 new = (PyTypeObject *)value;
1409 newbase = new;
1410 oldbase = old;
1411 while (equiv_structs(newbase, newbase->tp_base))
1412 newbase = newbase->tp_base;
1413 while (equiv_structs(oldbase, oldbase->tp_base))
1414 oldbase = oldbase->tp_base;
1415 if (newbase != oldbase &&
1416 (newbase->tp_base != oldbase->tp_base ||
1417 !same_slots_added(newbase, oldbase))) {
1418 PyErr_Format(PyExc_TypeError,
1419 "__class__ assignment: "
1420 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001421 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001422 old->tp_name);
1423 return -1;
1424 }
1425 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1426 Py_INCREF(new);
1427 }
1428 self->ob_type = new;
1429 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1430 Py_DECREF(old);
1431 }
1432 return 0;
1433}
1434
1435static PyGetSetDef object_getsets[] = {
1436 {"__class__", object_get_class, object_set_class,
1437 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001438 {0}
1439};
1440
Guido van Rossum3926a632001-09-25 16:25:58 +00001441static PyObject *
1442object_reduce(PyObject *self, PyObject *args)
1443{
1444 /* Call copy_reg._reduce(self) */
1445 static PyObject *copy_reg_str;
1446 PyObject *copy_reg, *res;
1447
1448 if (!copy_reg_str) {
1449 copy_reg_str = PyString_InternFromString("copy_reg");
1450 if (copy_reg_str == NULL)
1451 return NULL;
1452 }
1453 copy_reg = PyImport_Import(copy_reg_str);
1454 if (!copy_reg)
1455 return NULL;
1456 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1457 Py_DECREF(copy_reg);
1458 return res;
1459}
1460
1461static PyMethodDef object_methods[] = {
1462 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1463 {0}
1464};
1465
Tim Peters6d6c1a32001-08-02 04:15:00 +00001466PyTypeObject PyBaseObject_Type = {
1467 PyObject_HEAD_INIT(&PyType_Type)
1468 0, /* ob_size */
1469 "object", /* tp_name */
1470 sizeof(PyObject), /* tp_basicsize */
1471 0, /* tp_itemsize */
1472 (destructor)object_dealloc, /* tp_dealloc */
1473 0, /* tp_print */
1474 0, /* tp_getattr */
1475 0, /* tp_setattr */
1476 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001477 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001478 0, /* tp_as_number */
1479 0, /* tp_as_sequence */
1480 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001481 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001482 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001483 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001485 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001486 0, /* tp_as_buffer */
1487 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1488 "The most base type", /* tp_doc */
1489 0, /* tp_traverse */
1490 0, /* tp_clear */
1491 0, /* tp_richcompare */
1492 0, /* tp_weaklistoffset */
1493 0, /* tp_iter */
1494 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001495 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001496 0, /* tp_members */
1497 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001498 0, /* tp_base */
1499 0, /* tp_dict */
1500 0, /* tp_descr_get */
1501 0, /* tp_descr_set */
1502 0, /* tp_dictoffset */
1503 object_init, /* tp_init */
1504 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001505 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001506 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001507};
1508
1509
1510/* Initialize the __dict__ in a type object */
1511
1512static int
1513add_methods(PyTypeObject *type, PyMethodDef *meth)
1514{
1515 PyObject *dict = type->tp_defined;
1516
1517 for (; meth->ml_name != NULL; meth++) {
1518 PyObject *descr;
1519 if (PyDict_GetItemString(dict, meth->ml_name))
1520 continue;
1521 descr = PyDescr_NewMethod(type, meth);
1522 if (descr == NULL)
1523 return -1;
1524 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1525 return -1;
1526 Py_DECREF(descr);
1527 }
1528 return 0;
1529}
1530
1531static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001532add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001533{
1534 PyObject *dict = type->tp_defined;
1535
1536 for (; memb->name != NULL; memb++) {
1537 PyObject *descr;
1538 if (PyDict_GetItemString(dict, memb->name))
1539 continue;
1540 descr = PyDescr_NewMember(type, memb);
1541 if (descr == NULL)
1542 return -1;
1543 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1544 return -1;
1545 Py_DECREF(descr);
1546 }
1547 return 0;
1548}
1549
1550static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001551add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001552{
1553 PyObject *dict = type->tp_defined;
1554
1555 for (; gsp->name != NULL; gsp++) {
1556 PyObject *descr;
1557 if (PyDict_GetItemString(dict, gsp->name))
1558 continue;
1559 descr = PyDescr_NewGetSet(type, gsp);
1560
1561 if (descr == NULL)
1562 return -1;
1563 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1564 return -1;
1565 Py_DECREF(descr);
1566 }
1567 return 0;
1568}
1569
Guido van Rossum13d52f02001-08-10 21:24:08 +00001570static void
1571inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001572{
1573 int oldsize, newsize;
1574
Guido van Rossum13d52f02001-08-10 21:24:08 +00001575 /* Special flag magic */
1576 if (!type->tp_as_buffer && base->tp_as_buffer) {
1577 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1578 type->tp_flags |=
1579 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1580 }
1581 if (!type->tp_as_sequence && base->tp_as_sequence) {
1582 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1583 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1584 }
1585 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1586 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1587 if ((!type->tp_as_number && base->tp_as_number) ||
1588 (!type->tp_as_sequence && base->tp_as_sequence)) {
1589 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1590 if (!type->tp_as_number && !type->tp_as_sequence) {
1591 type->tp_flags |= base->tp_flags &
1592 Py_TPFLAGS_HAVE_INPLACEOPS;
1593 }
1594 }
1595 /* Wow */
1596 }
1597 if (!type->tp_as_number && base->tp_as_number) {
1598 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1599 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1600 }
1601
1602 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001603 oldsize = base->tp_basicsize;
1604 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1605 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1606 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001607 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1608 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001609 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001610 if (type->tp_traverse == NULL)
1611 type->tp_traverse = base->tp_traverse;
1612 if (type->tp_clear == NULL)
1613 type->tp_clear = base->tp_clear;
1614 }
1615 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1616 if (base != &PyBaseObject_Type ||
1617 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1618 if (type->tp_new == NULL)
1619 type->tp_new = base->tp_new;
1620 }
1621 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001622 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001623
1624 /* Copy other non-function slots */
1625
1626#undef COPYVAL
1627#define COPYVAL(SLOT) \
1628 if (type->SLOT == 0) type->SLOT = base->SLOT
1629
1630 COPYVAL(tp_itemsize);
1631 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1632 COPYVAL(tp_weaklistoffset);
1633 }
1634 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1635 COPYVAL(tp_dictoffset);
1636 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001637}
1638
1639static void
1640inherit_slots(PyTypeObject *type, PyTypeObject *base)
1641{
1642 PyTypeObject *basebase;
1643
1644#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645#undef COPYSLOT
1646#undef COPYNUM
1647#undef COPYSEQ
1648#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001649#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001650
1651#define SLOTDEFINED(SLOT) \
1652 (base->SLOT != 0 && \
1653 (basebase == NULL || base->SLOT != basebase->SLOT))
1654
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001656 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657
1658#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1659#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1660#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001661#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001662
Guido van Rossum13d52f02001-08-10 21:24:08 +00001663 /* This won't inherit indirect slots (from tp_as_number etc.)
1664 if type doesn't provide the space. */
1665
1666 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1667 basebase = base->tp_base;
1668 if (basebase->tp_as_number == NULL)
1669 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001670 COPYNUM(nb_add);
1671 COPYNUM(nb_subtract);
1672 COPYNUM(nb_multiply);
1673 COPYNUM(nb_divide);
1674 COPYNUM(nb_remainder);
1675 COPYNUM(nb_divmod);
1676 COPYNUM(nb_power);
1677 COPYNUM(nb_negative);
1678 COPYNUM(nb_positive);
1679 COPYNUM(nb_absolute);
1680 COPYNUM(nb_nonzero);
1681 COPYNUM(nb_invert);
1682 COPYNUM(nb_lshift);
1683 COPYNUM(nb_rshift);
1684 COPYNUM(nb_and);
1685 COPYNUM(nb_xor);
1686 COPYNUM(nb_or);
1687 COPYNUM(nb_coerce);
1688 COPYNUM(nb_int);
1689 COPYNUM(nb_long);
1690 COPYNUM(nb_float);
1691 COPYNUM(nb_oct);
1692 COPYNUM(nb_hex);
1693 COPYNUM(nb_inplace_add);
1694 COPYNUM(nb_inplace_subtract);
1695 COPYNUM(nb_inplace_multiply);
1696 COPYNUM(nb_inplace_divide);
1697 COPYNUM(nb_inplace_remainder);
1698 COPYNUM(nb_inplace_power);
1699 COPYNUM(nb_inplace_lshift);
1700 COPYNUM(nb_inplace_rshift);
1701 COPYNUM(nb_inplace_and);
1702 COPYNUM(nb_inplace_xor);
1703 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001704 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1705 COPYNUM(nb_true_divide);
1706 COPYNUM(nb_floor_divide);
1707 COPYNUM(nb_inplace_true_divide);
1708 COPYNUM(nb_inplace_floor_divide);
1709 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001710 }
1711
Guido van Rossum13d52f02001-08-10 21:24:08 +00001712 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1713 basebase = base->tp_base;
1714 if (basebase->tp_as_sequence == NULL)
1715 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001716 COPYSEQ(sq_length);
1717 COPYSEQ(sq_concat);
1718 COPYSEQ(sq_repeat);
1719 COPYSEQ(sq_item);
1720 COPYSEQ(sq_slice);
1721 COPYSEQ(sq_ass_item);
1722 COPYSEQ(sq_ass_slice);
1723 COPYSEQ(sq_contains);
1724 COPYSEQ(sq_inplace_concat);
1725 COPYSEQ(sq_inplace_repeat);
1726 }
1727
Guido van Rossum13d52f02001-08-10 21:24:08 +00001728 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1729 basebase = base->tp_base;
1730 if (basebase->tp_as_mapping == NULL)
1731 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001732 COPYMAP(mp_length);
1733 COPYMAP(mp_subscript);
1734 COPYMAP(mp_ass_subscript);
1735 }
1736
Tim Petersfc57ccb2001-10-12 02:38:24 +00001737 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1738 basebase = base->tp_base;
1739 if (basebase->tp_as_buffer == NULL)
1740 basebase = NULL;
1741 COPYBUF(bf_getreadbuffer);
1742 COPYBUF(bf_getwritebuffer);
1743 COPYBUF(bf_getsegcount);
1744 COPYBUF(bf_getcharbuffer);
1745 }
1746
Guido van Rossum13d52f02001-08-10 21:24:08 +00001747 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001748
Tim Peters6d6c1a32001-08-02 04:15:00 +00001749 COPYSLOT(tp_dealloc);
1750 COPYSLOT(tp_print);
1751 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1752 type->tp_getattr = base->tp_getattr;
1753 type->tp_getattro = base->tp_getattro;
1754 }
1755 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1756 type->tp_setattr = base->tp_setattr;
1757 type->tp_setattro = base->tp_setattro;
1758 }
1759 /* tp_compare see tp_richcompare */
1760 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001761 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762 COPYSLOT(tp_call);
1763 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001765 if (type->tp_compare == NULL &&
1766 type->tp_richcompare == NULL &&
1767 type->tp_hash == NULL)
1768 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001769 type->tp_compare = base->tp_compare;
1770 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001771 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001772 }
1773 }
1774 else {
1775 COPYSLOT(tp_compare);
1776 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1778 COPYSLOT(tp_iter);
1779 COPYSLOT(tp_iternext);
1780 }
1781 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1782 COPYSLOT(tp_descr_get);
1783 COPYSLOT(tp_descr_set);
1784 COPYSLOT(tp_dictoffset);
1785 COPYSLOT(tp_init);
1786 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001787 COPYSLOT(tp_free);
1788 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001789}
1790
Guido van Rossum13d52f02001-08-10 21:24:08 +00001791staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00001792staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001793
Tim Peters6d6c1a32001-08-02 04:15:00 +00001794int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001795PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001796{
1797 PyObject *dict, *bases, *x;
1798 PyTypeObject *base;
1799 int i, n;
1800
Guido van Rossumd614f972001-08-10 17:39:49 +00001801 if (type->tp_flags & Py_TPFLAGS_READY) {
1802 assert(type->tp_dict != NULL);
1803 return 0;
1804 }
1805 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1806 assert(type->tp_dict == NULL);
1807
1808 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001809
1810 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1811 base = type->tp_base;
1812 if (base == NULL && type != &PyBaseObject_Type)
1813 base = type->tp_base = &PyBaseObject_Type;
1814
1815 /* Initialize tp_bases */
1816 bases = type->tp_bases;
1817 if (bases == NULL) {
1818 if (base == NULL)
1819 bases = PyTuple_New(0);
1820 else
1821 bases = Py_BuildValue("(O)", base);
1822 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001823 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001824 type->tp_bases = bases;
1825 }
1826
1827 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001828 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001829 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001830 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001831 }
1832
1833 /* Initialize tp_defined */
1834 dict = type->tp_defined;
1835 if (dict == NULL) {
1836 dict = PyDict_New();
1837 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001838 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001839 type->tp_defined = dict;
1840 }
1841
1842 /* Add type-specific descriptors to tp_defined */
1843 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001844 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845 if (type->tp_methods != NULL) {
1846 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001847 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848 }
1849 if (type->tp_members != NULL) {
1850 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001851 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001852 }
1853 if (type->tp_getset != NULL) {
1854 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001855 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001856 }
1857
1858 /* Temporarily make tp_dict the same object as tp_defined.
1859 (This is needed to call mro(), and can stay this way for
1860 dynamic types). */
1861 Py_INCREF(type->tp_defined);
1862 type->tp_dict = type->tp_defined;
1863
1864 /* Calculate method resolution order */
1865 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001866 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867 }
1868
Guido van Rossum13d52f02001-08-10 21:24:08 +00001869 /* Inherit special flags from dominant base */
1870 if (type->tp_base != NULL)
1871 inherit_special(type, type->tp_base);
1872
Tim Peters6d6c1a32001-08-02 04:15:00 +00001873 /* Initialize tp_dict properly */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001874 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001875 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001876 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001877 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001878 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001880 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001881 bases = type->tp_mro;
1882 assert(bases != NULL);
1883 assert(PyTuple_Check(bases));
1884 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001885 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001886 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1887 assert(PyType_Check(base));
1888 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001889 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001890 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001891 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001892 }
1893 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001894 else {
1895 /* For a dynamic type, we simply inherit the base slots. */
1896 bases = type->tp_mro;
1897 assert(bases != NULL);
1898 assert(PyTuple_Check(bases));
1899 n = PyTuple_GET_SIZE(bases);
1900 for (i = 1; i < n; i++) {
1901 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1902 assert(PyType_Check(base));
1903 inherit_slots(type, base);
1904 }
1905 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906
Guido van Rossum13d52f02001-08-10 21:24:08 +00001907 /* Some more special stuff */
1908 base = type->tp_base;
1909 if (base != NULL) {
1910 if (type->tp_as_number == NULL)
1911 type->tp_as_number = base->tp_as_number;
1912 if (type->tp_as_sequence == NULL)
1913 type->tp_as_sequence = base->tp_as_sequence;
1914 if (type->tp_as_mapping == NULL)
1915 type->tp_as_mapping = base->tp_as_mapping;
1916 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001917
Guido van Rossum1c450732001-10-08 15:18:27 +00001918 /* Link into each base class's list of subclasses */
1919 bases = type->tp_bases;
1920 n = PyTuple_GET_SIZE(bases);
1921 for (i = 0; i < n; i++) {
1922 base = (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
1923 if (add_subclass((PyTypeObject *)base, type) < 0)
1924 goto error;
1925 }
1926
Guido van Rossum13d52f02001-08-10 21:24:08 +00001927 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001928 assert(type->tp_dict != NULL);
1929 type->tp_flags =
1930 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001931 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001932
1933 error:
1934 type->tp_flags &= ~Py_TPFLAGS_READYING;
1935 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001936}
1937
Guido van Rossum1c450732001-10-08 15:18:27 +00001938static int
1939add_subclass(PyTypeObject *base, PyTypeObject *type)
1940{
1941 int i;
1942 PyObject *list, *ref, *new;
1943
1944 list = base->tp_subclasses;
1945 if (list == NULL) {
1946 base->tp_subclasses = list = PyList_New(0);
1947 if (list == NULL)
1948 return -1;
1949 }
1950 assert(PyList_Check(list));
1951 new = PyWeakref_NewRef((PyObject *)type, NULL);
1952 i = PyList_GET_SIZE(list);
1953 while (--i >= 0) {
1954 ref = PyList_GET_ITEM(list, i);
1955 assert(PyWeakref_CheckRef(ref));
1956 if (PyWeakref_GET_OBJECT(ref) == Py_None)
1957 return PyList_SetItem(list, i, new);
1958 }
1959 i = PyList_Append(list, new);
1960 Py_DECREF(new);
1961 return i;
1962}
1963
Tim Peters6d6c1a32001-08-02 04:15:00 +00001964
1965/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1966
1967/* There's a wrapper *function* for each distinct function typedef used
1968 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1969 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1970 Most tables have only one entry; the tables for binary operators have two
1971 entries, one regular and one with reversed arguments. */
1972
1973static PyObject *
1974wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1975{
1976 inquiry func = (inquiry)wrapped;
1977 int res;
1978
1979 if (!PyArg_ParseTuple(args, ""))
1980 return NULL;
1981 res = (*func)(self);
1982 if (res == -1 && PyErr_Occurred())
1983 return NULL;
1984 return PyInt_FromLong((long)res);
1985}
1986
1987static struct wrapperbase tab_len[] = {
1988 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1989 {0}
1990};
1991
1992static PyObject *
1993wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1994{
1995 binaryfunc func = (binaryfunc)wrapped;
1996 PyObject *other;
1997
1998 if (!PyArg_ParseTuple(args, "O", &other))
1999 return NULL;
2000 return (*func)(self, other);
2001}
2002
2003static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002004wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2005{
2006 binaryfunc func = (binaryfunc)wrapped;
2007 PyObject *other;
2008
2009 if (!PyArg_ParseTuple(args, "O", &other))
2010 return NULL;
2011 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002012 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002013 Py_INCREF(Py_NotImplemented);
2014 return Py_NotImplemented;
2015 }
2016 return (*func)(self, other);
2017}
2018
2019static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2021{
2022 binaryfunc func = (binaryfunc)wrapped;
2023 PyObject *other;
2024
2025 if (!PyArg_ParseTuple(args, "O", &other))
2026 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002027 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002028 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002029 Py_INCREF(Py_NotImplemented);
2030 return Py_NotImplemented;
2031 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002032 return (*func)(other, self);
2033}
2034
2035#undef BINARY
2036#define BINARY(NAME, OP) \
2037static struct wrapperbase tab_##NAME[] = { \
2038 {"__" #NAME "__", \
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002039 (wrapperfunc)wrap_binaryfunc_l, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040 "x.__" #NAME "__(y) <==> " #OP}, \
2041 {"__r" #NAME "__", \
2042 (wrapperfunc)wrap_binaryfunc_r, \
2043 "y.__r" #NAME "__(x) <==> " #OP}, \
2044 {0} \
2045}
2046
2047BINARY(add, "x+y");
2048BINARY(sub, "x-y");
2049BINARY(mul, "x*y");
2050BINARY(div, "x/y");
2051BINARY(mod, "x%y");
2052BINARY(divmod, "divmod(x,y)");
2053BINARY(lshift, "x<<y");
2054BINARY(rshift, "x>>y");
2055BINARY(and, "x&y");
2056BINARY(xor, "x^y");
2057BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002058
2059static PyObject *
2060wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2061{
2062 coercion func = (coercion)wrapped;
2063 PyObject *other, *res;
2064 int ok;
2065
2066 if (!PyArg_ParseTuple(args, "O", &other))
2067 return NULL;
2068 ok = func(&self, &other);
2069 if (ok < 0)
2070 return NULL;
2071 if (ok > 0) {
2072 Py_INCREF(Py_NotImplemented);
2073 return Py_NotImplemented;
2074 }
2075 res = PyTuple_New(2);
2076 if (res == NULL) {
2077 Py_DECREF(self);
2078 Py_DECREF(other);
2079 return NULL;
2080 }
2081 PyTuple_SET_ITEM(res, 0, self);
2082 PyTuple_SET_ITEM(res, 1, other);
2083 return res;
2084}
2085
2086static struct wrapperbase tab_coerce[] = {
2087 {"__coerce__", (wrapperfunc)wrap_coercefunc,
2088 "x.__coerce__(y) <==> coerce(x, y)"},
2089 {0}
2090};
2091
Guido van Rossum874f15a2001-09-25 21:16:33 +00002092BINARY(floordiv, "x//y");
2093BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002094
2095static PyObject *
2096wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2097{
2098 ternaryfunc func = (ternaryfunc)wrapped;
2099 PyObject *other;
2100 PyObject *third = Py_None;
2101
2102 /* Note: This wrapper only works for __pow__() */
2103
2104 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2105 return NULL;
2106 return (*func)(self, other, third);
2107}
2108
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002109static PyObject *
2110wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2111{
2112 ternaryfunc func = (ternaryfunc)wrapped;
2113 PyObject *other;
2114 PyObject *third = Py_None;
2115
2116 /* Note: This wrapper only works for __pow__() */
2117
2118 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2119 return NULL;
2120 return (*func)(other, self, third);
2121}
2122
Tim Peters6d6c1a32001-08-02 04:15:00 +00002123#undef TERNARY
2124#define TERNARY(NAME, OP) \
2125static struct wrapperbase tab_##NAME[] = { \
2126 {"__" #NAME "__", \
2127 (wrapperfunc)wrap_ternaryfunc, \
2128 "x.__" #NAME "__(y, z) <==> " #OP}, \
2129 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002130 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002131 "y.__r" #NAME "__(x, z) <==> " #OP}, \
2132 {0} \
2133}
2134
2135TERNARY(pow, "(x**y) % z");
2136
2137#undef UNARY
2138#define UNARY(NAME, OP) \
2139static struct wrapperbase tab_##NAME[] = { \
2140 {"__" #NAME "__", \
2141 (wrapperfunc)wrap_unaryfunc, \
2142 "x.__" #NAME "__() <==> " #OP}, \
2143 {0} \
2144}
2145
2146static PyObject *
2147wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2148{
2149 unaryfunc func = (unaryfunc)wrapped;
2150
2151 if (!PyArg_ParseTuple(args, ""))
2152 return NULL;
2153 return (*func)(self);
2154}
2155
2156UNARY(neg, "-x");
2157UNARY(pos, "+x");
2158UNARY(abs, "abs(x)");
2159UNARY(nonzero, "x != 0");
2160UNARY(invert, "~x");
2161UNARY(int, "int(x)");
2162UNARY(long, "long(x)");
2163UNARY(float, "float(x)");
2164UNARY(oct, "oct(x)");
2165UNARY(hex, "hex(x)");
2166
2167#undef IBINARY
2168#define IBINARY(NAME, OP) \
2169static struct wrapperbase tab_##NAME[] = { \
2170 {"__" #NAME "__", \
2171 (wrapperfunc)wrap_binaryfunc, \
2172 "x.__" #NAME "__(y) <==> " #OP}, \
2173 {0} \
2174}
2175
2176IBINARY(iadd, "x+=y");
2177IBINARY(isub, "x-=y");
2178IBINARY(imul, "x*=y");
2179IBINARY(idiv, "x/=y");
2180IBINARY(imod, "x%=y");
2181IBINARY(ilshift, "x<<=y");
2182IBINARY(irshift, "x>>=y");
2183IBINARY(iand, "x&=y");
2184IBINARY(ixor, "x^=y");
2185IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002186IBINARY(ifloordiv, "x//=y");
2187IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002188
2189#undef ITERNARY
2190#define ITERNARY(NAME, OP) \
2191static struct wrapperbase tab_##NAME[] = { \
2192 {"__" #NAME "__", \
2193 (wrapperfunc)wrap_ternaryfunc, \
2194 "x.__" #NAME "__(y) <==> " #OP}, \
2195 {0} \
2196}
2197
2198ITERNARY(ipow, "x = (x**y) % z");
2199
2200static struct wrapperbase tab_getitem[] = {
2201 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2202 "x.__getitem__(y) <==> x[y]"},
2203 {0}
2204};
2205
2206static PyObject *
2207wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2208{
2209 intargfunc func = (intargfunc)wrapped;
2210 int i;
2211
2212 if (!PyArg_ParseTuple(args, "i", &i))
2213 return NULL;
2214 return (*func)(self, i);
2215}
2216
2217static struct wrapperbase tab_mul_int[] = {
2218 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2219 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2220 {0}
2221};
2222
2223static struct wrapperbase tab_concat[] = {
2224 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2225 {0}
2226};
2227
2228static struct wrapperbase tab_imul_int[] = {
2229 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2230 {0}
2231};
2232
Guido van Rossum5d815f32001-08-17 21:57:47 +00002233static int
2234getindex(PyObject *self, PyObject *arg)
2235{
2236 int i;
2237
2238 i = PyInt_AsLong(arg);
2239 if (i == -1 && PyErr_Occurred())
2240 return -1;
2241 if (i < 0) {
2242 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2243 if (sq && sq->sq_length) {
2244 int n = (*sq->sq_length)(self);
2245 if (n < 0)
2246 return -1;
2247 i += n;
2248 }
2249 }
2250 return i;
2251}
2252
2253static PyObject *
2254wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2255{
2256 intargfunc func = (intargfunc)wrapped;
2257 PyObject *arg;
2258 int i;
2259
Guido van Rossumf4593e02001-10-03 12:09:30 +00002260 if (PyTuple_GET_SIZE(args) == 1) {
2261 arg = PyTuple_GET_ITEM(args, 0);
2262 i = getindex(self, arg);
2263 if (i == -1 && PyErr_Occurred())
2264 return NULL;
2265 return (*func)(self, i);
2266 }
2267 PyArg_ParseTuple(args, "O", &arg);
2268 assert(PyErr_Occurred());
2269 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002270}
2271
Tim Peters6d6c1a32001-08-02 04:15:00 +00002272static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002273 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002274 "x.__getitem__(i) <==> x[i]"},
2275 {0}
2276};
2277
2278static PyObject *
2279wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2280{
2281 intintargfunc func = (intintargfunc)wrapped;
2282 int i, j;
2283
2284 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2285 return NULL;
2286 return (*func)(self, i, j);
2287}
2288
2289static struct wrapperbase tab_getslice[] = {
2290 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2291 "x.__getslice__(i, j) <==> x[i:j]"},
2292 {0}
2293};
2294
2295static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002296wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002297{
2298 intobjargproc func = (intobjargproc)wrapped;
2299 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002300 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002301
Guido van Rossum5d815f32001-08-17 21:57:47 +00002302 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2303 return NULL;
2304 i = getindex(self, arg);
2305 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002306 return NULL;
2307 res = (*func)(self, i, value);
2308 if (res == -1 && PyErr_Occurred())
2309 return NULL;
2310 Py_INCREF(Py_None);
2311 return Py_None;
2312}
2313
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002314static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002315wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002316{
2317 intobjargproc func = (intobjargproc)wrapped;
2318 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002319 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002320
Guido van Rossum5d815f32001-08-17 21:57:47 +00002321 if (!PyArg_ParseTuple(args, "O", &arg))
2322 return NULL;
2323 i = getindex(self, arg);
2324 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002325 return NULL;
2326 res = (*func)(self, i, NULL);
2327 if (res == -1 && PyErr_Occurred())
2328 return NULL;
2329 Py_INCREF(Py_None);
2330 return Py_None;
2331}
2332
Tim Peters6d6c1a32001-08-02 04:15:00 +00002333static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002334 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002335 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002336 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002337 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002338 {0}
2339};
2340
2341static PyObject *
2342wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2343{
2344 intintobjargproc func = (intintobjargproc)wrapped;
2345 int i, j, res;
2346 PyObject *value;
2347
2348 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2349 return NULL;
2350 res = (*func)(self, i, j, value);
2351 if (res == -1 && PyErr_Occurred())
2352 return NULL;
2353 Py_INCREF(Py_None);
2354 return Py_None;
2355}
2356
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002357static PyObject *
2358wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2359{
2360 intintobjargproc func = (intintobjargproc)wrapped;
2361 int i, j, res;
2362
2363 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2364 return NULL;
2365 res = (*func)(self, i, j, NULL);
2366 if (res == -1 && PyErr_Occurred())
2367 return NULL;
2368 Py_INCREF(Py_None);
2369 return Py_None;
2370}
2371
Tim Peters6d6c1a32001-08-02 04:15:00 +00002372static struct wrapperbase tab_setslice[] = {
2373 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2374 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002375 {"__delslice__", (wrapperfunc)wrap_delslice,
2376 "x.__delslice__(i, j) <==> del x[i:j]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002377 {0}
2378};
2379
2380/* XXX objobjproc is a misnomer; should be objargpred */
2381static PyObject *
2382wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2383{
2384 objobjproc func = (objobjproc)wrapped;
2385 int res;
2386 PyObject *value;
2387
2388 if (!PyArg_ParseTuple(args, "O", &value))
2389 return NULL;
2390 res = (*func)(self, value);
2391 if (res == -1 && PyErr_Occurred())
2392 return NULL;
2393 return PyInt_FromLong((long)res);
2394}
2395
2396static struct wrapperbase tab_contains[] = {
2397 {"__contains__", (wrapperfunc)wrap_objobjproc,
2398 "x.__contains__(y) <==> y in x"},
2399 {0}
2400};
2401
2402static PyObject *
2403wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2404{
2405 objobjargproc func = (objobjargproc)wrapped;
2406 int res;
2407 PyObject *key, *value;
2408
2409 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2410 return NULL;
2411 res = (*func)(self, key, value);
2412 if (res == -1 && PyErr_Occurred())
2413 return NULL;
2414 Py_INCREF(Py_None);
2415 return Py_None;
2416}
2417
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002418static PyObject *
2419wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2420{
2421 objobjargproc func = (objobjargproc)wrapped;
2422 int res;
2423 PyObject *key;
2424
2425 if (!PyArg_ParseTuple(args, "O", &key))
2426 return NULL;
2427 res = (*func)(self, key, NULL);
2428 if (res == -1 && PyErr_Occurred())
2429 return NULL;
2430 Py_INCREF(Py_None);
2431 return Py_None;
2432}
2433
Tim Peters6d6c1a32001-08-02 04:15:00 +00002434static struct wrapperbase tab_setitem[] = {
2435 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2436 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002437 {"__delitem__", (wrapperfunc)wrap_delitem,
2438 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002439 {0}
2440};
2441
2442static PyObject *
2443wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2444{
2445 cmpfunc func = (cmpfunc)wrapped;
2446 int res;
2447 PyObject *other;
2448
2449 if (!PyArg_ParseTuple(args, "O", &other))
2450 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002451 if (other->ob_type->tp_compare != func &&
2452 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002453 PyErr_Format(
2454 PyExc_TypeError,
2455 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2456 self->ob_type->tp_name,
2457 self->ob_type->tp_name,
2458 other->ob_type->tp_name);
2459 return NULL;
2460 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002461 res = (*func)(self, other);
2462 if (PyErr_Occurred())
2463 return NULL;
2464 return PyInt_FromLong((long)res);
2465}
2466
2467static struct wrapperbase tab_cmp[] = {
2468 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2469 "x.__cmp__(y) <==> cmp(x,y)"},
2470 {0}
2471};
2472
2473static struct wrapperbase tab_repr[] = {
2474 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2475 "x.__repr__() <==> repr(x)"},
2476 {0}
2477};
2478
2479static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002480 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2481 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002482 {0}
2483};
2484
2485static PyObject *
2486wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2487{
2488 setattrofunc func = (setattrofunc)wrapped;
2489 int res;
2490 PyObject *name, *value;
2491
2492 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2493 return NULL;
2494 res = (*func)(self, name, value);
2495 if (res < 0)
2496 return NULL;
2497 Py_INCREF(Py_None);
2498 return Py_None;
2499}
2500
2501static PyObject *
2502wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2503{
2504 setattrofunc func = (setattrofunc)wrapped;
2505 int res;
2506 PyObject *name;
2507
2508 if (!PyArg_ParseTuple(args, "O", &name))
2509 return NULL;
2510 res = (*func)(self, name, NULL);
2511 if (res < 0)
2512 return NULL;
2513 Py_INCREF(Py_None);
2514 return Py_None;
2515}
2516
2517static struct wrapperbase tab_setattr[] = {
2518 {"__setattr__", (wrapperfunc)wrap_setattr,
2519 "x.__setattr__('name', value) <==> x.name = value"},
2520 {"__delattr__", (wrapperfunc)wrap_delattr,
2521 "x.__delattr__('name') <==> del x.name"},
2522 {0}
2523};
2524
2525static PyObject *
2526wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2527{
2528 hashfunc func = (hashfunc)wrapped;
2529 long res;
2530
2531 if (!PyArg_ParseTuple(args, ""))
2532 return NULL;
2533 res = (*func)(self);
2534 if (res == -1 && PyErr_Occurred())
2535 return NULL;
2536 return PyInt_FromLong(res);
2537}
2538
2539static struct wrapperbase tab_hash[] = {
2540 {"__hash__", (wrapperfunc)wrap_hashfunc,
2541 "x.__hash__() <==> hash(x)"},
2542 {0}
2543};
2544
2545static PyObject *
2546wrap_call(PyObject *self, PyObject *args, void *wrapped)
2547{
2548 ternaryfunc func = (ternaryfunc)wrapped;
2549
2550 /* XXX What about keyword arguments? */
2551 return (*func)(self, args, NULL);
2552}
2553
2554static struct wrapperbase tab_call[] = {
2555 {"__call__", (wrapperfunc)wrap_call,
2556 "x.__call__(...) <==> x(...)"},
2557 {0}
2558};
2559
2560static struct wrapperbase tab_str[] = {
2561 {"__str__", (wrapperfunc)wrap_unaryfunc,
2562 "x.__str__() <==> str(x)"},
2563 {0}
2564};
2565
2566static PyObject *
2567wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2568{
2569 richcmpfunc func = (richcmpfunc)wrapped;
2570 PyObject *other;
2571
2572 if (!PyArg_ParseTuple(args, "O", &other))
2573 return NULL;
2574 return (*func)(self, other, op);
2575}
2576
2577#undef RICHCMP_WRAPPER
2578#define RICHCMP_WRAPPER(NAME, OP) \
2579static PyObject * \
2580richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2581{ \
2582 return wrap_richcmpfunc(self, args, wrapped, OP); \
2583}
2584
Jack Jansen8e938b42001-08-08 15:29:49 +00002585RICHCMP_WRAPPER(lt, Py_LT)
2586RICHCMP_WRAPPER(le, Py_LE)
2587RICHCMP_WRAPPER(eq, Py_EQ)
2588RICHCMP_WRAPPER(ne, Py_NE)
2589RICHCMP_WRAPPER(gt, Py_GT)
2590RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002591
2592#undef RICHCMP_ENTRY
2593#define RICHCMP_ENTRY(NAME, EXPR) \
2594 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2595 "x.__" #NAME "__(y) <==> " EXPR}
2596
2597static struct wrapperbase tab_richcmp[] = {
2598 RICHCMP_ENTRY(lt, "x<y"),
2599 RICHCMP_ENTRY(le, "x<=y"),
2600 RICHCMP_ENTRY(eq, "x==y"),
2601 RICHCMP_ENTRY(ne, "x!=y"),
2602 RICHCMP_ENTRY(gt, "x>y"),
2603 RICHCMP_ENTRY(ge, "x>=y"),
2604 {0}
2605};
2606
2607static struct wrapperbase tab_iter[] = {
2608 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2609 {0}
2610};
2611
2612static PyObject *
2613wrap_next(PyObject *self, PyObject *args, void *wrapped)
2614{
2615 unaryfunc func = (unaryfunc)wrapped;
2616 PyObject *res;
2617
2618 if (!PyArg_ParseTuple(args, ""))
2619 return NULL;
2620 res = (*func)(self);
2621 if (res == NULL && !PyErr_Occurred())
2622 PyErr_SetNone(PyExc_StopIteration);
2623 return res;
2624}
2625
2626static struct wrapperbase tab_next[] = {
2627 {"next", (wrapperfunc)wrap_next,
2628 "x.next() -> the next value, or raise StopIteration"},
2629 {0}
2630};
2631
2632static PyObject *
2633wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2634{
2635 descrgetfunc func = (descrgetfunc)wrapped;
2636 PyObject *obj;
2637 PyObject *type = NULL;
2638
2639 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2640 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002641 return (*func)(self, obj, type);
2642}
2643
2644static struct wrapperbase tab_descr_get[] = {
2645 {"__get__", (wrapperfunc)wrap_descr_get,
2646 "descr.__get__(obj, type) -> value"},
2647 {0}
2648};
2649
2650static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002651wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002652{
2653 descrsetfunc func = (descrsetfunc)wrapped;
2654 PyObject *obj, *value;
2655 int ret;
2656
2657 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2658 return NULL;
2659 ret = (*func)(self, obj, value);
2660 if (ret < 0)
2661 return NULL;
2662 Py_INCREF(Py_None);
2663 return Py_None;
2664}
2665
2666static struct wrapperbase tab_descr_set[] = {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002667 {"__set__", (wrapperfunc)wrap_descr_set,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002668 "descr.__set__(obj, value)"},
2669 {0}
2670};
2671
2672static PyObject *
2673wrap_init(PyObject *self, PyObject *args, void *wrapped)
2674{
2675 initproc func = (initproc)wrapped;
2676
2677 /* XXX What about keyword arguments? */
2678 if (func(self, args, NULL) < 0)
2679 return NULL;
2680 Py_INCREF(Py_None);
2681 return Py_None;
2682}
2683
2684static struct wrapperbase tab_init[] = {
2685 {"__init__", (wrapperfunc)wrap_init,
2686 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002687 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002688 {0}
2689};
2690
2691static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002692tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002693{
Barry Warsaw60f01882001-08-22 19:24:42 +00002694 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002695 PyObject *arg0, *res;
2696
2697 if (self == NULL || !PyType_Check(self))
2698 Py_FatalError("__new__() called with non-type 'self'");
2699 type = (PyTypeObject *)self;
2700 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002701 PyErr_Format(PyExc_TypeError,
2702 "%s.__new__(): not enough arguments",
2703 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002704 return NULL;
2705 }
2706 arg0 = PyTuple_GET_ITEM(args, 0);
2707 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002708 PyErr_Format(PyExc_TypeError,
2709 "%s.__new__(X): X is not a type object (%s)",
2710 type->tp_name,
2711 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002712 return NULL;
2713 }
2714 subtype = (PyTypeObject *)arg0;
2715 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002716 PyErr_Format(PyExc_TypeError,
2717 "%s.__new__(%s): %s is not a subtype of %s",
2718 type->tp_name,
2719 subtype->tp_name,
2720 subtype->tp_name,
2721 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002722 return NULL;
2723 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002724
2725 /* Check that the use doesn't do something silly and unsafe like
2726 object.__new__(dictionary). To do this, we check that the
2727 most derived base that's not a heap type is this type. */
2728 staticbase = subtype;
2729 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2730 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002731 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002732 PyErr_Format(PyExc_TypeError,
2733 "%s.__new__(%s) is not safe, use %s.__new__()",
2734 type->tp_name,
2735 subtype->tp_name,
2736 staticbase == NULL ? "?" : staticbase->tp_name);
2737 return NULL;
2738 }
2739
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002740 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2741 if (args == NULL)
2742 return NULL;
2743 res = type->tp_new(subtype, args, kwds);
2744 Py_DECREF(args);
2745 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002746}
2747
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002748static struct PyMethodDef tp_new_methoddef[] = {
2749 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2750 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751 {0}
2752};
2753
2754static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002755add_tp_new_wrapper(PyTypeObject *type)
2756{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002757 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002758
Guido van Rossumf040ede2001-08-07 16:40:56 +00002759 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2760 return 0;
2761 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002762 if (func == NULL)
2763 return -1;
2764 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2765}
2766
Guido van Rossum13d52f02001-08-10 21:24:08 +00002767static int
2768add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2769{
2770 PyObject *dict = type->tp_defined;
2771
2772 for (; wraps->name != NULL; wraps++) {
2773 PyObject *descr;
2774 if (PyDict_GetItemString(dict, wraps->name))
2775 continue;
2776 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2777 if (descr == NULL)
2778 return -1;
2779 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2780 return -1;
2781 Py_DECREF(descr);
2782 }
2783 return 0;
2784}
2785
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002786/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002787 dictionary with method descriptors for function slots. For each
2788 function slot (like tp_repr) that's defined in the type, one or
2789 more corresponding descriptors are added in the type's tp_defined
2790 dictionary under the appropriate name (like __repr__). Some
2791 function slots cause more than one descriptor to be added (for
2792 example, the nb_add slot adds both __add__ and __radd__
2793 descriptors) and some function slots compete for the same
2794 descriptor (for example both sq_item and mp_subscript generate a
2795 __getitem__ descriptor). This only adds new descriptors and
2796 doesn't overwrite entries in tp_defined that were previously
2797 defined. The descriptors contain a reference to the C function
2798 they must call, so that it's safe if they are copied into a
2799 subtype's __dict__ and the subtype has a different C function in
2800 its slot -- calling the method defined by the descriptor will call
2801 the C function that was used to create it, rather than the C
2802 function present in the slot when it is called. (This is important
2803 because a subtype may have a C function in the slot that calls the
2804 method from the dictionary, and we want to avoid infinite recursion
2805 here.) */
2806
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002807static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002808add_operators(PyTypeObject *type)
2809{
2810 PySequenceMethods *sq;
2811 PyMappingMethods *mp;
2812 PyNumberMethods *nb;
2813
2814#undef ADD
2815#define ADD(SLOT, TABLE) \
2816 if (SLOT) { \
2817 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2818 return -1; \
2819 }
2820
2821 if ((sq = type->tp_as_sequence) != NULL) {
2822 ADD(sq->sq_length, tab_len);
2823 ADD(sq->sq_concat, tab_concat);
2824 ADD(sq->sq_repeat, tab_mul_int);
2825 ADD(sq->sq_item, tab_getitem_int);
2826 ADD(sq->sq_slice, tab_getslice);
2827 ADD(sq->sq_ass_item, tab_setitem_int);
2828 ADD(sq->sq_ass_slice, tab_setslice);
2829 ADD(sq->sq_contains, tab_contains);
2830 ADD(sq->sq_inplace_concat, tab_iadd);
2831 ADD(sq->sq_inplace_repeat, tab_imul_int);
2832 }
2833
2834 if ((mp = type->tp_as_mapping) != NULL) {
2835 if (sq->sq_length == NULL)
2836 ADD(mp->mp_length, tab_len);
2837 ADD(mp->mp_subscript, tab_getitem);
2838 ADD(mp->mp_ass_subscript, tab_setitem);
2839 }
2840
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002841 if ((nb = type->tp_as_number) != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002842 ADD(nb->nb_add, tab_add);
2843 ADD(nb->nb_subtract, tab_sub);
2844 ADD(nb->nb_multiply, tab_mul);
2845 ADD(nb->nb_divide, tab_div);
2846 ADD(nb->nb_remainder, tab_mod);
2847 ADD(nb->nb_divmod, tab_divmod);
2848 ADD(nb->nb_power, tab_pow);
2849 ADD(nb->nb_negative, tab_neg);
2850 ADD(nb->nb_positive, tab_pos);
2851 ADD(nb->nb_absolute, tab_abs);
2852 ADD(nb->nb_nonzero, tab_nonzero);
2853 ADD(nb->nb_invert, tab_invert);
2854 ADD(nb->nb_lshift, tab_lshift);
2855 ADD(nb->nb_rshift, tab_rshift);
2856 ADD(nb->nb_and, tab_and);
2857 ADD(nb->nb_xor, tab_xor);
2858 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002859 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002860 ADD(nb->nb_int, tab_int);
2861 ADD(nb->nb_long, tab_long);
2862 ADD(nb->nb_float, tab_float);
2863 ADD(nb->nb_oct, tab_oct);
2864 ADD(nb->nb_hex, tab_hex);
2865 ADD(nb->nb_inplace_add, tab_iadd);
2866 ADD(nb->nb_inplace_subtract, tab_isub);
2867 ADD(nb->nb_inplace_multiply, tab_imul);
2868 ADD(nb->nb_inplace_divide, tab_idiv);
2869 ADD(nb->nb_inplace_remainder, tab_imod);
2870 ADD(nb->nb_inplace_power, tab_ipow);
2871 ADD(nb->nb_inplace_lshift, tab_ilshift);
2872 ADD(nb->nb_inplace_rshift, tab_irshift);
2873 ADD(nb->nb_inplace_and, tab_iand);
2874 ADD(nb->nb_inplace_xor, tab_ixor);
2875 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002876 if (type->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossum874f15a2001-09-25 21:16:33 +00002877 ADD(nb->nb_floor_divide, tab_floordiv);
2878 ADD(nb->nb_true_divide, tab_truediv);
2879 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2880 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2881 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002882 }
2883
2884 ADD(type->tp_getattro, tab_getattr);
2885 ADD(type->tp_setattro, tab_setattr);
2886 ADD(type->tp_compare, tab_cmp);
2887 ADD(type->tp_repr, tab_repr);
2888 ADD(type->tp_hash, tab_hash);
2889 ADD(type->tp_call, tab_call);
2890 ADD(type->tp_str, tab_str);
2891 ADD(type->tp_richcompare, tab_richcmp);
2892 ADD(type->tp_iter, tab_iter);
2893 ADD(type->tp_iternext, tab_next);
2894 ADD(type->tp_descr_get, tab_descr_get);
2895 ADD(type->tp_descr_set, tab_descr_set);
2896 ADD(type->tp_init, tab_init);
2897
Guido van Rossumf040ede2001-08-07 16:40:56 +00002898 if (type->tp_new != NULL) {
2899 if (add_tp_new_wrapper(type) < 0)
2900 return -1;
2901 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002902
2903 return 0;
2904}
2905
Guido van Rossumf040ede2001-08-07 16:40:56 +00002906/* Slot wrappers that call the corresponding __foo__ slot. See comments
2907 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002908
Guido van Rossumdc91b992001-08-08 22:26:22 +00002909#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002910static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002911FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002912{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002913 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002914 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002915}
2916
Guido van Rossumdc91b992001-08-08 22:26:22 +00002917#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002918static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002919FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002920{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002921 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002922 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002923}
2924
Guido van Rossumdc91b992001-08-08 22:26:22 +00002925
2926#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002928FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002929{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002930 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002931 int do_other = self->ob_type != other->ob_type && \
2932 other->ob_type->tp_as_number != NULL && \
2933 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002934 if (self->ob_type->tp_as_number != NULL && \
2935 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2936 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002937 if (do_other && \
2938 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2939 r = call_maybe( \
2940 other, ROPSTR, &rcache_str, "(O)", self); \
2941 if (r != Py_NotImplemented) \
2942 return r; \
2943 Py_DECREF(r); \
2944 do_other = 0; \
2945 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002946 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002947 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002948 if (r != Py_NotImplemented || \
2949 other->ob_type == self->ob_type) \
2950 return r; \
2951 Py_DECREF(r); \
2952 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002953 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002954 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002955 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002956 } \
2957 Py_INCREF(Py_NotImplemented); \
2958 return Py_NotImplemented; \
2959}
2960
2961#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2962 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2963
2964#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2965static PyObject * \
2966FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2967{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002968 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002969 return call_method(self, OPSTR, &cache_str, \
2970 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002971}
2972
2973static int
2974slot_sq_length(PyObject *self)
2975{
Guido van Rossum2730b132001-08-28 18:22:14 +00002976 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002977 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002978 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002979
2980 if (res == NULL)
2981 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002982 len = (int)PyInt_AsLong(res);
2983 Py_DECREF(res);
2984 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002985}
2986
Guido van Rossumdc91b992001-08-08 22:26:22 +00002987SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2988SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002989
2990/* Super-optimized version of slot_sq_item.
2991 Other slots could do the same... */
2992static PyObject *
2993slot_sq_item(PyObject *self, int i)
2994{
2995 static PyObject *getitem_str;
2996 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2997 descrgetfunc f;
2998
2999 if (getitem_str == NULL) {
3000 getitem_str = PyString_InternFromString("__getitem__");
3001 if (getitem_str == NULL)
3002 return NULL;
3003 }
3004 func = _PyType_Lookup(self->ob_type, getitem_str);
3005 if (func != NULL) {
3006 if (func->ob_type == &PyWrapperDescr_Type) {
3007 PyWrapperDescrObject *wrapper =
3008 (PyWrapperDescrObject *)func;
3009 if (wrapper->d_base->wrapper == wrap_sq_item) {
3010 intargfunc f;
3011 f = (intargfunc)(wrapper->d_wrapped);
3012 return f(self, i);
3013 }
3014 }
3015 if ((f = func->ob_type->tp_descr_get) == NULL)
3016 Py_INCREF(func);
3017 else
3018 func = f(func, self, (PyObject *)(self->ob_type));
3019 ival = PyInt_FromLong(i);
3020 if (ival != NULL) {
3021 args = PyTuple_New(1);
3022 if (args != NULL) {
3023 PyTuple_SET_ITEM(args, 0, ival);
3024 retval = PyObject_Call(func, args, NULL);
3025 Py_XDECREF(args);
3026 Py_XDECREF(func);
3027 return retval;
3028 }
3029 }
3030 }
3031 else {
3032 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3033 }
3034 Py_XDECREF(args);
3035 Py_XDECREF(ival);
3036 Py_XDECREF(func);
3037 return NULL;
3038}
3039
Guido van Rossumdc91b992001-08-08 22:26:22 +00003040SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003041
3042static int
3043slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3044{
3045 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003046 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003047
3048 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003049 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003050 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003051 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003052 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003053 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054 if (res == NULL)
3055 return -1;
3056 Py_DECREF(res);
3057 return 0;
3058}
3059
3060static int
3061slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3062{
3063 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003064 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003065
3066 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003067 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003068 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003070 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003071 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003072 if (res == NULL)
3073 return -1;
3074 Py_DECREF(res);
3075 return 0;
3076}
3077
3078static int
3079slot_sq_contains(PyObject *self, PyObject *value)
3080{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003081 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003082 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003083
Guido van Rossum55f20992001-10-01 17:18:22 +00003084 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003085
3086 if (func != NULL) {
3087 args = Py_BuildValue("(O)", value);
3088 if (args == NULL)
3089 res = NULL;
3090 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003091 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003092 Py_DECREF(args);
3093 }
3094 Py_DECREF(func);
3095 if (res == NULL)
3096 return -1;
3097 return PyObject_IsTrue(res);
3098 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003099 else if (PyErr_Occurred())
3100 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003101 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003102 return _PySequence_IterSearch(self, value,
3103 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003104 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105}
3106
Guido van Rossumdc91b992001-08-08 22:26:22 +00003107SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3108SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109
3110#define slot_mp_length slot_sq_length
3111
Guido van Rossumdc91b992001-08-08 22:26:22 +00003112SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003113
3114static int
3115slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3116{
3117 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003118 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003119
3120 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003121 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003122 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003123 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003124 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003125 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003126 if (res == NULL)
3127 return -1;
3128 Py_DECREF(res);
3129 return 0;
3130}
3131
Guido van Rossumdc91b992001-08-08 22:26:22 +00003132SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3133SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3134SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3135SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3136SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3137SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3138
3139staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3140
3141SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3142 nb_power, "__pow__", "__rpow__")
3143
3144static PyObject *
3145slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3146{
Guido van Rossum2730b132001-08-28 18:22:14 +00003147 static PyObject *pow_str;
3148
Guido van Rossumdc91b992001-08-08 22:26:22 +00003149 if (modulus == Py_None)
3150 return slot_nb_power_binary(self, other);
3151 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003152 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003153 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003154}
3155
3156SLOT0(slot_nb_negative, "__neg__")
3157SLOT0(slot_nb_positive, "__pos__")
3158SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003159
3160static int
3161slot_nb_nonzero(PyObject *self)
3162{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003163 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003164 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165
Guido van Rossum55f20992001-10-01 17:18:22 +00003166 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003167 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003168 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003169 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003170 func = lookup_maybe(self, "__len__", &len_str);
3171 if (func == NULL) {
3172 if (PyErr_Occurred())
3173 return -1;
3174 else
3175 return 1;
3176 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003177 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003178 res = PyObject_CallObject(func, NULL);
3179 Py_DECREF(func);
3180 if (res == NULL)
3181 return -1;
3182 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003183}
3184
Guido van Rossumdc91b992001-08-08 22:26:22 +00003185SLOT0(slot_nb_invert, "__invert__")
3186SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3187SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3188SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3189SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3190SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003191
3192static int
3193slot_nb_coerce(PyObject **a, PyObject **b)
3194{
3195 static PyObject *coerce_str;
3196 PyObject *self = *a, *other = *b;
3197
3198 if (self->ob_type->tp_as_number != NULL &&
3199 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3200 PyObject *r;
3201 r = call_maybe(
3202 self, "__coerce__", &coerce_str, "(O)", other);
3203 if (r == NULL)
3204 return -1;
3205 if (r == Py_NotImplemented) {
3206 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003207 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003208 else {
3209 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3210 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003211 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003212 Py_DECREF(r);
3213 return -1;
3214 }
3215 *a = PyTuple_GET_ITEM(r, 0);
3216 Py_INCREF(*a);
3217 *b = PyTuple_GET_ITEM(r, 1);
3218 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003219 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003220 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003221 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003222 }
3223 if (other->ob_type->tp_as_number != NULL &&
3224 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3225 PyObject *r;
3226 r = call_maybe(
3227 other, "__coerce__", &coerce_str, "(O)", self);
3228 if (r == NULL)
3229 return -1;
3230 if (r == Py_NotImplemented) {
3231 Py_DECREF(r);
3232 return 1;
3233 }
3234 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3235 PyErr_SetString(PyExc_TypeError,
3236 "__coerce__ didn't return a 2-tuple");
3237 Py_DECREF(r);
3238 return -1;
3239 }
3240 *a = PyTuple_GET_ITEM(r, 1);
3241 Py_INCREF(*a);
3242 *b = PyTuple_GET_ITEM(r, 0);
3243 Py_INCREF(*b);
3244 Py_DECREF(r);
3245 return 0;
3246 }
3247 return 1;
3248}
3249
Guido van Rossumdc91b992001-08-08 22:26:22 +00003250SLOT0(slot_nb_int, "__int__")
3251SLOT0(slot_nb_long, "__long__")
3252SLOT0(slot_nb_float, "__float__")
3253SLOT0(slot_nb_oct, "__oct__")
3254SLOT0(slot_nb_hex, "__hex__")
3255SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3256SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3257SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3258SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3259SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3260SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3261SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3262SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3263SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3264SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3265SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3266SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3267 "__floordiv__", "__rfloordiv__")
3268SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3269SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3270SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003271
3272static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003273half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003274{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003275 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003276 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003277 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003278
Guido van Rossum60718732001-08-28 17:47:51 +00003279 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003280 if (func == NULL) {
3281 PyErr_Clear();
3282 }
3283 else {
3284 args = Py_BuildValue("(O)", other);
3285 if (args == NULL)
3286 res = NULL;
3287 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003288 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003289 Py_DECREF(args);
3290 }
3291 if (res != Py_NotImplemented) {
3292 if (res == NULL)
3293 return -2;
3294 c = PyInt_AsLong(res);
3295 Py_DECREF(res);
3296 if (c == -1 && PyErr_Occurred())
3297 return -2;
3298 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3299 }
3300 Py_DECREF(res);
3301 }
3302 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003303}
3304
Guido van Rossumab3b0342001-09-18 20:38:53 +00003305/* This slot is published for the benefit of try_3way_compare in object.c */
3306int
3307_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003308{
3309 int c;
3310
Guido van Rossumab3b0342001-09-18 20:38:53 +00003311 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003312 c = half_compare(self, other);
3313 if (c <= 1)
3314 return c;
3315 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003316 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003317 c = half_compare(other, self);
3318 if (c < -1)
3319 return -2;
3320 if (c <= 1)
3321 return -c;
3322 }
3323 return (void *)self < (void *)other ? -1 :
3324 (void *)self > (void *)other ? 1 : 0;
3325}
3326
3327static PyObject *
3328slot_tp_repr(PyObject *self)
3329{
3330 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003331 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003332
Guido van Rossum60718732001-08-28 17:47:51 +00003333 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003334 if (func != NULL) {
3335 res = PyEval_CallObject(func, NULL);
3336 Py_DECREF(func);
3337 return res;
3338 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003339 PyErr_Clear();
3340 return PyString_FromFormat("<%s object at %p>",
3341 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003342}
3343
3344static PyObject *
3345slot_tp_str(PyObject *self)
3346{
3347 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003348 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003349
Guido van Rossum60718732001-08-28 17:47:51 +00003350 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003351 if (func != NULL) {
3352 res = PyEval_CallObject(func, NULL);
3353 Py_DECREF(func);
3354 return res;
3355 }
3356 else {
3357 PyErr_Clear();
3358 return slot_tp_repr(self);
3359 }
3360}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003361
3362static long
3363slot_tp_hash(PyObject *self)
3364{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003365 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003366 static PyObject *hash_str, *eq_str, *cmp_str;
3367
Tim Peters6d6c1a32001-08-02 04:15:00 +00003368 long h;
3369
Guido van Rossum60718732001-08-28 17:47:51 +00003370 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003371
3372 if (func != NULL) {
3373 res = PyEval_CallObject(func, NULL);
3374 Py_DECREF(func);
3375 if (res == NULL)
3376 return -1;
3377 h = PyInt_AsLong(res);
3378 }
3379 else {
3380 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003381 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003382 if (func == NULL) {
3383 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003384 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003385 }
3386 if (func != NULL) {
3387 Py_DECREF(func);
3388 PyErr_SetString(PyExc_TypeError, "unhashable type");
3389 return -1;
3390 }
3391 PyErr_Clear();
3392 h = _Py_HashPointer((void *)self);
3393 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003394 if (h == -1 && !PyErr_Occurred())
3395 h = -2;
3396 return h;
3397}
3398
3399static PyObject *
3400slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3401{
Guido van Rossum60718732001-08-28 17:47:51 +00003402 static PyObject *call_str;
3403 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003404 PyObject *res;
3405
3406 if (meth == NULL)
3407 return NULL;
3408 res = PyObject_Call(meth, args, kwds);
3409 Py_DECREF(meth);
3410 return res;
3411}
3412
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413static PyObject *
3414slot_tp_getattro(PyObject *self, PyObject *name)
3415{
3416 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003417 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003418 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419
Guido van Rossum8e248182001-08-12 05:17:56 +00003420 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003421 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003422 if (getattr_str == NULL)
3423 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003424 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003425 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003426 if (getattr == NULL) {
3427 /* Avoid further slowdowns */
3428 if (tp->tp_getattro == slot_tp_getattro)
3429 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003430 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003431 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003432 return PyObject_CallFunction(getattr, "OO", self, name);
3433}
3434
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003435static PyObject *
3436slot_tp_getattr_hook(PyObject *self, PyObject *name)
3437{
3438 PyTypeObject *tp = self->ob_type;
3439 PyObject *getattr, *getattribute, *res;
3440 static PyObject *getattribute_str = NULL;
3441 static PyObject *getattr_str = NULL;
3442
3443 if (getattr_str == NULL) {
3444 getattr_str = PyString_InternFromString("__getattr__");
3445 if (getattr_str == NULL)
3446 return NULL;
3447 }
3448 if (getattribute_str == NULL) {
3449 getattribute_str =
3450 PyString_InternFromString("__getattribute__");
3451 if (getattribute_str == NULL)
3452 return NULL;
3453 }
3454 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003455 if (getattr == NULL && tp->tp_getattro == slot_tp_getattr_hook) {
3456 /* No __getattr__ hook: use a simpler dispatcher */
3457 tp->tp_getattro = slot_tp_getattro;
3458 return slot_tp_getattro(self, name);
3459 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003460 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003461 if (getattribute != NULL &&
3462 getattribute->ob_type == &PyWrapperDescr_Type &&
3463 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3464 PyObject_GenericGetAttr)
3465 getattribute = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003466 if (getattr == NULL && getattribute == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003467 /* Use the default dispatcher */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003468 if (tp->tp_getattro == slot_tp_getattr_hook)
3469 tp->tp_getattro = PyObject_GenericGetAttr;
3470 return PyObject_GenericGetAttr(self, name);
3471 }
3472 if (getattribute == NULL)
3473 res = PyObject_GenericGetAttr(self, name);
3474 else
3475 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003476 if (getattr != NULL &&
3477 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003478 PyErr_Clear();
3479 res = PyObject_CallFunction(getattr, "OO", self, name);
3480 }
3481 return res;
3482}
3483
Tim Peters6d6c1a32001-08-02 04:15:00 +00003484static int
3485slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3486{
3487 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003488 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003489
3490 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003491 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003492 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003493 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003494 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003495 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003496 if (res == NULL)
3497 return -1;
3498 Py_DECREF(res);
3499 return 0;
3500}
3501
3502/* Map rich comparison operators to their __xx__ namesakes */
3503static char *name_op[] = {
3504 "__lt__",
3505 "__le__",
3506 "__eq__",
3507 "__ne__",
3508 "__gt__",
3509 "__ge__",
3510};
3511
3512static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003513half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003514{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003515 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003516 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003517
Guido van Rossum60718732001-08-28 17:47:51 +00003518 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003519 if (func == NULL) {
3520 PyErr_Clear();
3521 Py_INCREF(Py_NotImplemented);
3522 return Py_NotImplemented;
3523 }
3524 args = Py_BuildValue("(O)", other);
3525 if (args == NULL)
3526 res = NULL;
3527 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003528 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003529 Py_DECREF(args);
3530 }
3531 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003532 return res;
3533}
3534
Guido van Rossumb8f63662001-08-15 23:57:02 +00003535/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3536static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3537
3538static PyObject *
3539slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3540{
3541 PyObject *res;
3542
3543 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3544 res = half_richcompare(self, other, op);
3545 if (res != Py_NotImplemented)
3546 return res;
3547 Py_DECREF(res);
3548 }
3549 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3550 res = half_richcompare(other, self, swapped_op[op]);
3551 if (res != Py_NotImplemented) {
3552 return res;
3553 }
3554 Py_DECREF(res);
3555 }
3556 Py_INCREF(Py_NotImplemented);
3557 return Py_NotImplemented;
3558}
3559
3560static PyObject *
3561slot_tp_iter(PyObject *self)
3562{
3563 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003564 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003565
Guido van Rossum60718732001-08-28 17:47:51 +00003566 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003567 if (func != NULL) {
3568 res = PyObject_CallObject(func, NULL);
3569 Py_DECREF(func);
3570 return res;
3571 }
3572 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003573 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003574 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003575 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003576 return NULL;
3577 }
3578 Py_DECREF(func);
3579 return PySeqIter_New(self);
3580}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003581
3582static PyObject *
3583slot_tp_iternext(PyObject *self)
3584{
Guido van Rossum2730b132001-08-28 18:22:14 +00003585 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003586 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003587}
3588
Guido van Rossum1a493502001-08-17 16:47:50 +00003589static PyObject *
3590slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3591{
3592 PyTypeObject *tp = self->ob_type;
3593 PyObject *get;
3594 static PyObject *get_str = NULL;
3595
3596 if (get_str == NULL) {
3597 get_str = PyString_InternFromString("__get__");
3598 if (get_str == NULL)
3599 return NULL;
3600 }
3601 get = _PyType_Lookup(tp, get_str);
3602 if (get == NULL) {
3603 /* Avoid further slowdowns */
3604 if (tp->tp_descr_get == slot_tp_descr_get)
3605 tp->tp_descr_get = NULL;
3606 Py_INCREF(self);
3607 return self;
3608 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003609 if (obj == NULL)
3610 obj = Py_None;
3611 if (type == NULL)
3612 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003613 return PyObject_CallFunction(get, "OOO", self, obj, type);
3614}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003615
3616static int
3617slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3618{
Guido van Rossum2c252392001-08-24 10:13:31 +00003619 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003620 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003621
3622 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003623 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003624 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003625 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003626 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003627 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003628 if (res == NULL)
3629 return -1;
3630 Py_DECREF(res);
3631 return 0;
3632}
3633
3634static int
3635slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3636{
Guido van Rossum60718732001-08-28 17:47:51 +00003637 static PyObject *init_str;
3638 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639 PyObject *res;
3640
3641 if (meth == NULL)
3642 return -1;
3643 res = PyObject_Call(meth, args, kwds);
3644 Py_DECREF(meth);
3645 if (res == NULL)
3646 return -1;
3647 Py_DECREF(res);
3648 return 0;
3649}
3650
3651static PyObject *
3652slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3653{
3654 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3655 PyObject *newargs, *x;
3656 int i, n;
3657
3658 if (func == NULL)
3659 return NULL;
3660 assert(PyTuple_Check(args));
3661 n = PyTuple_GET_SIZE(args);
3662 newargs = PyTuple_New(n+1);
3663 if (newargs == NULL)
3664 return NULL;
3665 Py_INCREF(type);
3666 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3667 for (i = 0; i < n; i++) {
3668 x = PyTuple_GET_ITEM(args, i);
3669 Py_INCREF(x);
3670 PyTuple_SET_ITEM(newargs, i+1, x);
3671 }
3672 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003673 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674 Py_DECREF(func);
3675 return x;
3676}
3677
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003678
3679/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3680 functions. The offsets here are relative to the 'etype' structure, which
3681 incorporates the additional structures used for numbers, sequences and
3682 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3683 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3684 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3685
3686typedef struct {
3687 char *name;
3688 int offset;
3689 void *function;
3690 wrapperfunc wrapper;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003691 PyObject *name_strobj;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003692} slotdef;
3693
3694#undef TPSLOT
3695#undef ETSLOT
3696#undef SQSLOT
3697#undef MPSLOT
3698#undef NBSLOT
3699#undef BINSLOT
3700#undef RBINSLOT
3701
3702#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3703 {NAME, offsetof(PyTypeObject, SLOT), FUNCTION, WRAPPER}
3704#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3705 {NAME, offsetof(etype, SLOT), FUNCTION, WRAPPER}
3706#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3707 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER)
3708#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3709 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER)
3710#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3711 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER)
3712#define BINSLOT(NAME, SLOT, FUNCTION) \
3713 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l)
3714#define RBINSLOT(NAME, SLOT, FUNCTION) \
3715 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r)
3716
3717static slotdef slotdefs[] = {
3718 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry),
3719 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc),
3720 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3721 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3722 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item),
3723 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc),
3724 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem),
3725 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem),
3726 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
3727 wrap_intintobjargproc),
3728 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice),
3729 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc),
3730 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
3731 wrap_binaryfunc),
3732 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
3733 wrap_intargfunc),
3734
3735 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003736 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
3737 wrap_binaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003738 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
3739 wrap_objobjargproc),
3740 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
3741 wrap_delitem),
3742
3743 BINSLOT("__add__", nb_add, slot_nb_add),
3744 RBINSLOT("__radd__", nb_add, slot_nb_add),
3745 BINSLOT("__sub__", nb_subtract, slot_nb_subtract),
3746 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract),
3747 BINSLOT("__mul__", nb_multiply, slot_nb_multiply),
3748 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply),
3749 BINSLOT("__div__", nb_divide, slot_nb_divide),
3750 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide),
3751 BINSLOT("__mod__", nb_remainder, slot_nb_remainder),
3752 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder),
3753 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod),
3754 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod),
3755 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc),
3756 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r),
3757 NBSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc),
3758 NBSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc),
3759 NBSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc),
3760 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_unaryfunc),
3761 NBSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc),
3762 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift),
3763 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift),
3764 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift),
3765 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift),
3766 BINSLOT("__and__", nb_and, slot_nb_and),
3767 RBINSLOT("__rand__", nb_and, slot_nb_and),
3768 BINSLOT("__xor__", nb_xor, slot_nb_xor),
3769 RBINSLOT("__rxor__", nb_xor, slot_nb_xor),
3770 BINSLOT("__or__", nb_or, slot_nb_or),
3771 RBINSLOT("__ror__", nb_or, slot_nb_or),
3772 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc),
3773 NBSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc),
3774 NBSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc),
3775 NBSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc),
3776 NBSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc),
3777 NBSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc),
3778 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3779 wrap_binaryfunc),
3780 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3781 wrap_binaryfunc),
3782 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3783 wrap_binaryfunc),
3784 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3785 wrap_binaryfunc),
3786 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3787 wrap_binaryfunc),
3788 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3789 wrap_ternaryfunc),
3790 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3791 wrap_binaryfunc),
3792 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3793 wrap_binaryfunc),
3794 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3795 wrap_binaryfunc),
3796 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3797 wrap_binaryfunc),
3798 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3799 wrap_binaryfunc),
3800 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide),
3801 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide),
3802 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide),
3803 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide),
3804 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3805 slot_nb_inplace_floor_divide, wrap_binaryfunc),
3806 NBSLOT("__itruediv__", nb_inplace_true_divide,
3807 slot_nb_inplace_true_divide, wrap_binaryfunc),
3808
3809 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003810 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003811 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc),
3812 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc),
3813 TPSLOT("__call__", tp_call, slot_tp_call, wrap_call),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003814 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003815 wrap_binaryfunc),
3816 TPSLOT("__getattribute__", tp_getattr, NULL, NULL),
3817 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL),
3818 TPSLOT("__getattr__", tp_getattr, NULL, NULL),
3819 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr),
3820 TPSLOT("__setattr__", tp_setattr, NULL, NULL),
3821 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr),
3822 TPSLOT("__delattr__", tp_setattr, NULL, NULL),
3823 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt),
3824 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le),
3825 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq),
3826 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne),
3827 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt),
3828 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge),
3829 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc),
3830 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next),
3831 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get),
3832 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set),
3833 TPSLOT("__init__", tp_init, slot_tp_init, wrap_init),
3834 TPSLOT("__new__", tp_new, slot_tp_new, NULL),
3835 {NULL}
3836};
3837
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003838static void **
3839slotptr(PyTypeObject *type, int offset)
3840{
3841 char *ptr;
3842
3843 assert(offset >= 0);
3844 assert(offset < offsetof(etype, as_buffer));
3845 if (offset >= offsetof(etype, as_mapping)) {
3846 ptr = (void *)type->tp_as_mapping;
3847 offset -= offsetof(etype, as_mapping);
3848 }
3849 else if (offset >= offsetof(etype, as_sequence)) {
3850 ptr = (void *)type->tp_as_sequence;
3851 offset -= offsetof(etype, as_sequence);
3852 }
3853 else if (offset >= offsetof(etype, as_number)) {
3854 ptr = (void *)type->tp_as_number;
3855 offset -= offsetof(etype, as_number);
3856 }
3857 else {
3858 ptr = (void *)type;
3859 }
3860 if (ptr != NULL)
3861 ptr += offset;
3862 return (void **)ptr;
3863}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003864
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003865staticforward int recurse_down_subclasses(PyTypeObject *type, slotdef *p);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003866
3867static int
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003868update_one_slot(PyTypeObject *type, slotdef *p0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003869{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003870 slotdef *p = p0;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003871 PyObject *descr;
3872 PyWrapperDescrObject *d;
3873 void *generic = NULL, *specific = NULL;
3874 int use_generic = 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003875 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003876 void **ptr;
3877
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003878 offset = p->offset;
3879 ptr = slotptr(type, offset);
3880 if (ptr == NULL)
3881 return recurse_down_subclasses(type, p);
3882 do {
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003883 descr = _PyType_Lookup(type, p->name_strobj);
3884 if (descr == NULL)
3885 continue;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003886 generic = p->function;
3887 if (descr->ob_type == &PyWrapperDescr_Type) {
3888 d = (PyWrapperDescrObject *)descr;
3889 if (d->d_base->wrapper == p->wrapper &&
3890 PyType_IsSubtype(type, d->d_type)) {
3891 if (specific == NULL ||
3892 specific == d->d_wrapped)
3893 specific = d->d_wrapped;
3894 else
3895 use_generic = 1;
3896 }
3897 }
3898 else
3899 use_generic = 1;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003900 } while ((++p)->offset == offset);
3901 if (specific && !use_generic)
3902 *ptr = specific;
3903 else
3904 *ptr = generic;
3905 return recurse_down_subclasses(type, p0);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003906}
3907
3908static int
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003909recurse_down_subclasses(PyTypeObject *type, slotdef *p)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003910{
3911 PyTypeObject *subclass;
3912 PyObject *ref, *subclasses;
3913 int i, n;
3914
3915 subclasses = type->tp_subclasses;
3916 if (subclasses == NULL)
3917 return 0;
3918 assert(PyList_Check(subclasses));
3919 n = PyList_GET_SIZE(subclasses);
3920 for (i = 0; i < n; i++) {
3921 ref = PyList_GET_ITEM(subclasses, i);
3922 assert(PyWeakref_CheckRef(ref));
3923 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3924 if (subclass == NULL)
3925 continue;
3926 assert(PyType_Check(subclass));
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003927 if (update_one_slot(subclass, p) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003928 return -1;
3929 }
3930 return 0;
3931}
3932
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003933static int
3934slotdef_cmp(const void *aa, const void *bb)
3935{
3936 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3937 int c = a->offset - b->offset;
3938 if (c != 0)
3939 return c;
3940 else
3941 return a - b;
3942}
3943
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003944static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003945init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003946{
3947 slotdef *p;
3948 static int initialized = 0;
3949
3950 if (initialized)
3951 return;
3952 for (p = slotdefs; p->name; p++) {
3953 p->name_strobj = PyString_InternFromString(p->name);
3954 if (!p->name_strobj)
3955 Py_FatalError("XXX ouch");
3956 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003957 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef), slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003958 initialized = 1;
3959}
3960
3961static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003962collect_ptrs(PyObject *name, slotdef *ptrs[])
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003963{
3964 slotdef *p;
3965
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003966 init_slotdefs();
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003967 for (p = slotdefs; p->name; p++) {
3968 if (name == p->name_strobj)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003969 *ptrs++ = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003970 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003971 *ptrs = NULL;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003972}
3973
3974static int
3975update_slot(PyTypeObject *type, PyObject *name)
3976{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003977 slotdef *ptrs[10];
3978 slotdef *p;
3979 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003980
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003981 collect_ptrs(name, ptrs);
3982 for (pp = ptrs; *pp; pp++) {
3983 p = *pp;
3984 while (p > slotdefs && p->offset == (p-1)->offset)
3985 --p;
3986 if (update_one_slot(type, p) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003987 return -1;
3988 }
3989 return 0;
3990}
3991
Tim Peters6d6c1a32001-08-02 04:15:00 +00003992static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003993fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003994{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003995 slotdef *p;
3996 PyObject *mro, *descr;
3997 PyTypeObject *base;
3998 PyWrapperDescrObject *d;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003999 int i, n, offset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004000 void **ptr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004001 void *generic, *specific;
4002 int use_generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004003
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004004 init_slotdefs();
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004005 mro = type->tp_mro;
4006 assert(PyTuple_Check(mro));
4007 n = PyTuple_GET_SIZE(mro);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004008 for (p = slotdefs; p->name; ) {
4009 offset = p->offset;
4010 ptr = slotptr(type, offset);
4011 if (!ptr) {
4012 do {
4013 ++p;
4014 } while (p->offset == offset);
4015 continue;
4016 }
4017 generic = specific = NULL;
4018 use_generic = 0;
4019 do {
4020 descr = NULL;
4021 for (i = 0; i < n; i++) {
4022 base = (PyTypeObject *)PyTuple_GET_ITEM(mro, i);
4023 assert(PyType_Check(base));
4024 descr = PyDict_GetItem(
4025 base->tp_defined, p->name_strobj);
4026 if (descr != NULL)
4027 break;
4028 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004029 if (descr == NULL)
4030 continue;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004031 generic = p->function;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004032 if (descr->ob_type == &PyWrapperDescr_Type) {
4033 d = (PyWrapperDescrObject *)descr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004034 if (d->d_base->wrapper == p->wrapper &&
4035 PyType_IsSubtype(type, d->d_type)) {
4036 if (specific == NULL ||
4037 specific == d->d_wrapped)
4038 specific = d->d_wrapped;
4039 else
4040 use_generic = 1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004041 }
4042 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004043 else
4044 use_generic = 1;
4045 } while ((++p)->offset == offset);
4046 if (specific && !use_generic)
4047 *ptr = specific;
4048 else
4049 *ptr = generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004050 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004052
4053
4054/* Cooperative 'super' */
4055
4056typedef struct {
4057 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004058 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004059 PyObject *obj;
4060} superobject;
4061
Guido van Rossum6f799372001-09-20 20:46:19 +00004062static PyMemberDef super_members[] = {
4063 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4064 "the class invoking super()"},
4065 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4066 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004067 {0}
4068};
4069
Guido van Rossum705f0f52001-08-24 16:47:00 +00004070static void
4071super_dealloc(PyObject *self)
4072{
4073 superobject *su = (superobject *)self;
4074
Guido van Rossum048eb752001-10-02 21:24:57 +00004075 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004076 Py_XDECREF(su->obj);
4077 Py_XDECREF(su->type);
4078 self->ob_type->tp_free(self);
4079}
4080
4081static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004082super_repr(PyObject *self)
4083{
4084 superobject *su = (superobject *)self;
4085
4086 if (su->obj)
4087 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004088 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004089 su->type ? su->type->tp_name : "NULL",
4090 su->obj->ob_type->tp_name);
4091 else
4092 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004093 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004094 su->type ? su->type->tp_name : "NULL");
4095}
4096
4097static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004098super_getattro(PyObject *self, PyObject *name)
4099{
4100 superobject *su = (superobject *)self;
4101
4102 if (su->obj != NULL) {
4103 PyObject *mro, *res, *tmp;
4104 descrgetfunc f;
4105 int i, n;
4106
Guido van Rossume705ef12001-08-29 15:47:06 +00004107 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004108 if (mro == NULL)
4109 n = 0;
4110 else {
4111 assert(PyTuple_Check(mro));
4112 n = PyTuple_GET_SIZE(mro);
4113 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004114 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004115 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004116 break;
4117 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004118 if (i >= n && PyType_Check(su->obj)) {
4119 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004120 if (mro == NULL)
4121 n = 0;
4122 else {
4123 assert(PyTuple_Check(mro));
4124 n = PyTuple_GET_SIZE(mro);
4125 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004126 for (i = 0; i < n; i++) {
4127 if ((PyObject *)(su->type) ==
4128 PyTuple_GET_ITEM(mro, i))
4129 break;
4130 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004131 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004132 i++;
4133 res = NULL;
4134 for (; i < n; i++) {
4135 tmp = PyTuple_GET_ITEM(mro, i);
4136 assert(PyType_Check(tmp));
4137 res = PyDict_GetItem(
4138 ((PyTypeObject *)tmp)->tp_defined, name);
4139 if (res != NULL) {
4140 Py_INCREF(res);
4141 f = res->ob_type->tp_descr_get;
4142 if (f != NULL) {
4143 tmp = f(res, su->obj, res);
4144 Py_DECREF(res);
4145 res = tmp;
4146 }
4147 return res;
4148 }
4149 }
4150 }
4151 return PyObject_GenericGetAttr(self, name);
4152}
4153
4154static PyObject *
4155super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4156{
4157 superobject *su = (superobject *)self;
4158 superobject *new;
4159
4160 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4161 /* Not binding to an object, or already bound */
4162 Py_INCREF(self);
4163 return self;
4164 }
4165 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
4166 if (new == NULL)
4167 return NULL;
4168 Py_INCREF(su->type);
4169 Py_INCREF(obj);
4170 new->type = su->type;
4171 new->obj = obj;
4172 return (PyObject *)new;
4173}
4174
4175static int
4176super_init(PyObject *self, PyObject *args, PyObject *kwds)
4177{
4178 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004179 PyTypeObject *type;
4180 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004181
4182 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4183 return -1;
4184 if (obj == Py_None)
4185 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00004186 if (obj != NULL &&
4187 !PyType_IsSubtype(obj->ob_type, type) &&
4188 !(PyType_Check(obj) &&
4189 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004190 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00004191 "super(type, obj): "
4192 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004193 return -1;
4194 }
4195 Py_INCREF(type);
4196 Py_XINCREF(obj);
4197 su->type = type;
4198 su->obj = obj;
4199 return 0;
4200}
4201
4202static char super_doc[] =
4203"super(type) -> unbound super object\n"
4204"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004205"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004206"Typical use to call a cooperative superclass method:\n"
4207"class C(B):\n"
4208" def meth(self, arg):\n"
4209" super(C, self).meth(arg)";
4210
Guido van Rossum048eb752001-10-02 21:24:57 +00004211static int
4212super_traverse(PyObject *self, visitproc visit, void *arg)
4213{
4214 superobject *su = (superobject *)self;
4215 int err;
4216
4217#define VISIT(SLOT) \
4218 if (SLOT) { \
4219 err = visit((PyObject *)(SLOT), arg); \
4220 if (err) \
4221 return err; \
4222 }
4223
4224 VISIT(su->obj);
4225 VISIT(su->type);
4226
4227#undef VISIT
4228
4229 return 0;
4230}
4231
Guido van Rossum705f0f52001-08-24 16:47:00 +00004232PyTypeObject PySuper_Type = {
4233 PyObject_HEAD_INIT(&PyType_Type)
4234 0, /* ob_size */
4235 "super", /* tp_name */
4236 sizeof(superobject), /* tp_basicsize */
4237 0, /* tp_itemsize */
4238 /* methods */
4239 super_dealloc, /* tp_dealloc */
4240 0, /* tp_print */
4241 0, /* tp_getattr */
4242 0, /* tp_setattr */
4243 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004244 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004245 0, /* tp_as_number */
4246 0, /* tp_as_sequence */
4247 0, /* tp_as_mapping */
4248 0, /* tp_hash */
4249 0, /* tp_call */
4250 0, /* tp_str */
4251 super_getattro, /* tp_getattro */
4252 0, /* tp_setattro */
4253 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004254 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4255 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004256 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004257 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004258 0, /* tp_clear */
4259 0, /* tp_richcompare */
4260 0, /* tp_weaklistoffset */
4261 0, /* tp_iter */
4262 0, /* tp_iternext */
4263 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004264 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004265 0, /* tp_getset */
4266 0, /* tp_base */
4267 0, /* tp_dict */
4268 super_descr_get, /* tp_descr_get */
4269 0, /* tp_descr_set */
4270 0, /* tp_dictoffset */
4271 super_init, /* tp_init */
4272 PyType_GenericAlloc, /* tp_alloc */
4273 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004274 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004275};