blob: a498f0f64bf4224090c7ed579d1e304a77775216 [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 Rossum13d52f02001-08-10 21:24:08 +00001649
1650#define SLOTDEFINED(SLOT) \
1651 (base->SLOT != 0 && \
1652 (basebase == NULL || base->SLOT != basebase->SLOT))
1653
Tim Peters6d6c1a32001-08-02 04:15:00 +00001654#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001655 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001656
1657#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1658#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1659#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001660#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001661
Guido van Rossum13d52f02001-08-10 21:24:08 +00001662 /* This won't inherit indirect slots (from tp_as_number etc.)
1663 if type doesn't provide the space. */
1664
1665 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1666 basebase = base->tp_base;
1667 if (basebase->tp_as_number == NULL)
1668 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001669 COPYNUM(nb_add);
1670 COPYNUM(nb_subtract);
1671 COPYNUM(nb_multiply);
1672 COPYNUM(nb_divide);
1673 COPYNUM(nb_remainder);
1674 COPYNUM(nb_divmod);
1675 COPYNUM(nb_power);
1676 COPYNUM(nb_negative);
1677 COPYNUM(nb_positive);
1678 COPYNUM(nb_absolute);
1679 COPYNUM(nb_nonzero);
1680 COPYNUM(nb_invert);
1681 COPYNUM(nb_lshift);
1682 COPYNUM(nb_rshift);
1683 COPYNUM(nb_and);
1684 COPYNUM(nb_xor);
1685 COPYNUM(nb_or);
1686 COPYNUM(nb_coerce);
1687 COPYNUM(nb_int);
1688 COPYNUM(nb_long);
1689 COPYNUM(nb_float);
1690 COPYNUM(nb_oct);
1691 COPYNUM(nb_hex);
1692 COPYNUM(nb_inplace_add);
1693 COPYNUM(nb_inplace_subtract);
1694 COPYNUM(nb_inplace_multiply);
1695 COPYNUM(nb_inplace_divide);
1696 COPYNUM(nb_inplace_remainder);
1697 COPYNUM(nb_inplace_power);
1698 COPYNUM(nb_inplace_lshift);
1699 COPYNUM(nb_inplace_rshift);
1700 COPYNUM(nb_inplace_and);
1701 COPYNUM(nb_inplace_xor);
1702 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001703 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1704 COPYNUM(nb_true_divide);
1705 COPYNUM(nb_floor_divide);
1706 COPYNUM(nb_inplace_true_divide);
1707 COPYNUM(nb_inplace_floor_divide);
1708 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001709 }
1710
Guido van Rossum13d52f02001-08-10 21:24:08 +00001711 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1712 basebase = base->tp_base;
1713 if (basebase->tp_as_sequence == NULL)
1714 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715 COPYSEQ(sq_length);
1716 COPYSEQ(sq_concat);
1717 COPYSEQ(sq_repeat);
1718 COPYSEQ(sq_item);
1719 COPYSEQ(sq_slice);
1720 COPYSEQ(sq_ass_item);
1721 COPYSEQ(sq_ass_slice);
1722 COPYSEQ(sq_contains);
1723 COPYSEQ(sq_inplace_concat);
1724 COPYSEQ(sq_inplace_repeat);
1725 }
1726
Guido van Rossum13d52f02001-08-10 21:24:08 +00001727 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1728 basebase = base->tp_base;
1729 if (basebase->tp_as_mapping == NULL)
1730 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001731 COPYMAP(mp_length);
1732 COPYMAP(mp_subscript);
1733 COPYMAP(mp_ass_subscript);
1734 }
1735
Tim Petersfc57ccb2001-10-12 02:38:24 +00001736 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1737 basebase = base->tp_base;
1738 if (basebase->tp_as_buffer == NULL)
1739 basebase = NULL;
1740 COPYBUF(bf_getreadbuffer);
1741 COPYBUF(bf_getwritebuffer);
1742 COPYBUF(bf_getsegcount);
1743 COPYBUF(bf_getcharbuffer);
1744 }
1745
Guido van Rossum13d52f02001-08-10 21:24:08 +00001746 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001747
Tim Peters6d6c1a32001-08-02 04:15:00 +00001748 COPYSLOT(tp_dealloc);
1749 COPYSLOT(tp_print);
1750 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1751 type->tp_getattr = base->tp_getattr;
1752 type->tp_getattro = base->tp_getattro;
1753 }
1754 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1755 type->tp_setattr = base->tp_setattr;
1756 type->tp_setattro = base->tp_setattro;
1757 }
1758 /* tp_compare see tp_richcompare */
1759 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001760 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001761 COPYSLOT(tp_call);
1762 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001763 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001764 if (type->tp_compare == NULL &&
1765 type->tp_richcompare == NULL &&
1766 type->tp_hash == NULL)
1767 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768 type->tp_compare = base->tp_compare;
1769 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001770 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771 }
1772 }
1773 else {
1774 COPYSLOT(tp_compare);
1775 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1777 COPYSLOT(tp_iter);
1778 COPYSLOT(tp_iternext);
1779 }
1780 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1781 COPYSLOT(tp_descr_get);
1782 COPYSLOT(tp_descr_set);
1783 COPYSLOT(tp_dictoffset);
1784 COPYSLOT(tp_init);
1785 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001786 COPYSLOT(tp_free);
1787 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788}
1789
Guido van Rossum13d52f02001-08-10 21:24:08 +00001790staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00001791staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001792
Tim Peters6d6c1a32001-08-02 04:15:00 +00001793int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001794PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795{
1796 PyObject *dict, *bases, *x;
1797 PyTypeObject *base;
1798 int i, n;
1799
Guido van Rossumd614f972001-08-10 17:39:49 +00001800 if (type->tp_flags & Py_TPFLAGS_READY) {
1801 assert(type->tp_dict != NULL);
1802 return 0;
1803 }
1804 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1805 assert(type->tp_dict == NULL);
1806
1807 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001808
1809 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1810 base = type->tp_base;
1811 if (base == NULL && type != &PyBaseObject_Type)
1812 base = type->tp_base = &PyBaseObject_Type;
1813
1814 /* Initialize tp_bases */
1815 bases = type->tp_bases;
1816 if (bases == NULL) {
1817 if (base == NULL)
1818 bases = PyTuple_New(0);
1819 else
1820 bases = Py_BuildValue("(O)", base);
1821 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001822 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001823 type->tp_bases = bases;
1824 }
1825
1826 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001827 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001828 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001829 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001830 }
1831
1832 /* Initialize tp_defined */
1833 dict = type->tp_defined;
1834 if (dict == NULL) {
1835 dict = PyDict_New();
1836 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001837 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001838 type->tp_defined = dict;
1839 }
1840
1841 /* Add type-specific descriptors to tp_defined */
1842 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001843 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 if (type->tp_methods != NULL) {
1845 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001846 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847 }
1848 if (type->tp_members != NULL) {
1849 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001850 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851 }
1852 if (type->tp_getset != NULL) {
1853 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001854 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855 }
1856
1857 /* Temporarily make tp_dict the same object as tp_defined.
1858 (This is needed to call mro(), and can stay this way for
1859 dynamic types). */
1860 Py_INCREF(type->tp_defined);
1861 type->tp_dict = type->tp_defined;
1862
1863 /* Calculate method resolution order */
1864 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001865 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001866 }
1867
Guido van Rossum13d52f02001-08-10 21:24:08 +00001868 /* Inherit special flags from dominant base */
1869 if (type->tp_base != NULL)
1870 inherit_special(type, type->tp_base);
1871
Tim Peters6d6c1a32001-08-02 04:15:00 +00001872 /* Initialize tp_dict properly */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001873 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001874 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001875 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001876 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001877 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001878 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001879 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001880 bases = type->tp_mro;
1881 assert(bases != NULL);
1882 assert(PyTuple_Check(bases));
1883 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001884 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001885 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1886 assert(PyType_Check(base));
1887 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001888 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001889 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001890 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001891 }
1892 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001893 else {
1894 /* For a dynamic type, we simply inherit the base slots. */
1895 bases = type->tp_mro;
1896 assert(bases != NULL);
1897 assert(PyTuple_Check(bases));
1898 n = PyTuple_GET_SIZE(bases);
1899 for (i = 1; i < n; i++) {
1900 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1901 assert(PyType_Check(base));
1902 inherit_slots(type, base);
1903 }
1904 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001905
Guido van Rossum13d52f02001-08-10 21:24:08 +00001906 /* Some more special stuff */
1907 base = type->tp_base;
1908 if (base != NULL) {
1909 if (type->tp_as_number == NULL)
1910 type->tp_as_number = base->tp_as_number;
1911 if (type->tp_as_sequence == NULL)
1912 type->tp_as_sequence = base->tp_as_sequence;
1913 if (type->tp_as_mapping == NULL)
1914 type->tp_as_mapping = base->tp_as_mapping;
1915 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001916
Guido van Rossum1c450732001-10-08 15:18:27 +00001917 /* Link into each base class's list of subclasses */
1918 bases = type->tp_bases;
1919 n = PyTuple_GET_SIZE(bases);
1920 for (i = 0; i < n; i++) {
1921 base = (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
1922 if (add_subclass((PyTypeObject *)base, type) < 0)
1923 goto error;
1924 }
1925
Guido van Rossum13d52f02001-08-10 21:24:08 +00001926 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001927 assert(type->tp_dict != NULL);
1928 type->tp_flags =
1929 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001930 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001931
1932 error:
1933 type->tp_flags &= ~Py_TPFLAGS_READYING;
1934 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001935}
1936
Guido van Rossum1c450732001-10-08 15:18:27 +00001937static int
1938add_subclass(PyTypeObject *base, PyTypeObject *type)
1939{
1940 int i;
1941 PyObject *list, *ref, *new;
1942
1943 list = base->tp_subclasses;
1944 if (list == NULL) {
1945 base->tp_subclasses = list = PyList_New(0);
1946 if (list == NULL)
1947 return -1;
1948 }
1949 assert(PyList_Check(list));
1950 new = PyWeakref_NewRef((PyObject *)type, NULL);
1951 i = PyList_GET_SIZE(list);
1952 while (--i >= 0) {
1953 ref = PyList_GET_ITEM(list, i);
1954 assert(PyWeakref_CheckRef(ref));
1955 if (PyWeakref_GET_OBJECT(ref) == Py_None)
1956 return PyList_SetItem(list, i, new);
1957 }
1958 i = PyList_Append(list, new);
1959 Py_DECREF(new);
1960 return i;
1961}
1962
Tim Peters6d6c1a32001-08-02 04:15:00 +00001963
1964/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1965
1966/* There's a wrapper *function* for each distinct function typedef used
1967 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1968 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1969 Most tables have only one entry; the tables for binary operators have two
1970 entries, one regular and one with reversed arguments. */
1971
1972static PyObject *
1973wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1974{
1975 inquiry func = (inquiry)wrapped;
1976 int res;
1977
1978 if (!PyArg_ParseTuple(args, ""))
1979 return NULL;
1980 res = (*func)(self);
1981 if (res == -1 && PyErr_Occurred())
1982 return NULL;
1983 return PyInt_FromLong((long)res);
1984}
1985
1986static struct wrapperbase tab_len[] = {
1987 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1988 {0}
1989};
1990
1991static PyObject *
1992wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1993{
1994 binaryfunc func = (binaryfunc)wrapped;
1995 PyObject *other;
1996
1997 if (!PyArg_ParseTuple(args, "O", &other))
1998 return NULL;
1999 return (*func)(self, other);
2000}
2001
2002static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002003wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2004{
2005 binaryfunc func = (binaryfunc)wrapped;
2006 PyObject *other;
2007
2008 if (!PyArg_ParseTuple(args, "O", &other))
2009 return NULL;
2010 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002011 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002012 Py_INCREF(Py_NotImplemented);
2013 return Py_NotImplemented;
2014 }
2015 return (*func)(self, other);
2016}
2017
2018static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2020{
2021 binaryfunc func = (binaryfunc)wrapped;
2022 PyObject *other;
2023
2024 if (!PyArg_ParseTuple(args, "O", &other))
2025 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002026 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002027 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002028 Py_INCREF(Py_NotImplemented);
2029 return Py_NotImplemented;
2030 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031 return (*func)(other, self);
2032}
2033
2034#undef BINARY
2035#define BINARY(NAME, OP) \
2036static struct wrapperbase tab_##NAME[] = { \
2037 {"__" #NAME "__", \
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002038 (wrapperfunc)wrap_binaryfunc_l, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002039 "x.__" #NAME "__(y) <==> " #OP}, \
2040 {"__r" #NAME "__", \
2041 (wrapperfunc)wrap_binaryfunc_r, \
2042 "y.__r" #NAME "__(x) <==> " #OP}, \
2043 {0} \
2044}
2045
2046BINARY(add, "x+y");
2047BINARY(sub, "x-y");
2048BINARY(mul, "x*y");
2049BINARY(div, "x/y");
2050BINARY(mod, "x%y");
2051BINARY(divmod, "divmod(x,y)");
2052BINARY(lshift, "x<<y");
2053BINARY(rshift, "x>>y");
2054BINARY(and, "x&y");
2055BINARY(xor, "x^y");
2056BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002057
2058static PyObject *
2059wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2060{
2061 coercion func = (coercion)wrapped;
2062 PyObject *other, *res;
2063 int ok;
2064
2065 if (!PyArg_ParseTuple(args, "O", &other))
2066 return NULL;
2067 ok = func(&self, &other);
2068 if (ok < 0)
2069 return NULL;
2070 if (ok > 0) {
2071 Py_INCREF(Py_NotImplemented);
2072 return Py_NotImplemented;
2073 }
2074 res = PyTuple_New(2);
2075 if (res == NULL) {
2076 Py_DECREF(self);
2077 Py_DECREF(other);
2078 return NULL;
2079 }
2080 PyTuple_SET_ITEM(res, 0, self);
2081 PyTuple_SET_ITEM(res, 1, other);
2082 return res;
2083}
2084
2085static struct wrapperbase tab_coerce[] = {
2086 {"__coerce__", (wrapperfunc)wrap_coercefunc,
2087 "x.__coerce__(y) <==> coerce(x, y)"},
2088 {0}
2089};
2090
Guido van Rossum874f15a2001-09-25 21:16:33 +00002091BINARY(floordiv, "x//y");
2092BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002093
2094static PyObject *
2095wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2096{
2097 ternaryfunc func = (ternaryfunc)wrapped;
2098 PyObject *other;
2099 PyObject *third = Py_None;
2100
2101 /* Note: This wrapper only works for __pow__() */
2102
2103 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2104 return NULL;
2105 return (*func)(self, other, third);
2106}
2107
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002108static PyObject *
2109wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2110{
2111 ternaryfunc func = (ternaryfunc)wrapped;
2112 PyObject *other;
2113 PyObject *third = Py_None;
2114
2115 /* Note: This wrapper only works for __pow__() */
2116
2117 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2118 return NULL;
2119 return (*func)(other, self, third);
2120}
2121
Tim Peters6d6c1a32001-08-02 04:15:00 +00002122#undef TERNARY
2123#define TERNARY(NAME, OP) \
2124static struct wrapperbase tab_##NAME[] = { \
2125 {"__" #NAME "__", \
2126 (wrapperfunc)wrap_ternaryfunc, \
2127 "x.__" #NAME "__(y, z) <==> " #OP}, \
2128 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002129 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002130 "y.__r" #NAME "__(x, z) <==> " #OP}, \
2131 {0} \
2132}
2133
2134TERNARY(pow, "(x**y) % z");
2135
2136#undef UNARY
2137#define UNARY(NAME, OP) \
2138static struct wrapperbase tab_##NAME[] = { \
2139 {"__" #NAME "__", \
2140 (wrapperfunc)wrap_unaryfunc, \
2141 "x.__" #NAME "__() <==> " #OP}, \
2142 {0} \
2143}
2144
2145static PyObject *
2146wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2147{
2148 unaryfunc func = (unaryfunc)wrapped;
2149
2150 if (!PyArg_ParseTuple(args, ""))
2151 return NULL;
2152 return (*func)(self);
2153}
2154
2155UNARY(neg, "-x");
2156UNARY(pos, "+x");
2157UNARY(abs, "abs(x)");
2158UNARY(nonzero, "x != 0");
2159UNARY(invert, "~x");
2160UNARY(int, "int(x)");
2161UNARY(long, "long(x)");
2162UNARY(float, "float(x)");
2163UNARY(oct, "oct(x)");
2164UNARY(hex, "hex(x)");
2165
2166#undef IBINARY
2167#define IBINARY(NAME, OP) \
2168static struct wrapperbase tab_##NAME[] = { \
2169 {"__" #NAME "__", \
2170 (wrapperfunc)wrap_binaryfunc, \
2171 "x.__" #NAME "__(y) <==> " #OP}, \
2172 {0} \
2173}
2174
2175IBINARY(iadd, "x+=y");
2176IBINARY(isub, "x-=y");
2177IBINARY(imul, "x*=y");
2178IBINARY(idiv, "x/=y");
2179IBINARY(imod, "x%=y");
2180IBINARY(ilshift, "x<<=y");
2181IBINARY(irshift, "x>>=y");
2182IBINARY(iand, "x&=y");
2183IBINARY(ixor, "x^=y");
2184IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002185IBINARY(ifloordiv, "x//=y");
2186IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002187
2188#undef ITERNARY
2189#define ITERNARY(NAME, OP) \
2190static struct wrapperbase tab_##NAME[] = { \
2191 {"__" #NAME "__", \
2192 (wrapperfunc)wrap_ternaryfunc, \
2193 "x.__" #NAME "__(y) <==> " #OP}, \
2194 {0} \
2195}
2196
2197ITERNARY(ipow, "x = (x**y) % z");
2198
2199static struct wrapperbase tab_getitem[] = {
2200 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2201 "x.__getitem__(y) <==> x[y]"},
2202 {0}
2203};
2204
2205static PyObject *
2206wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2207{
2208 intargfunc func = (intargfunc)wrapped;
2209 int i;
2210
2211 if (!PyArg_ParseTuple(args, "i", &i))
2212 return NULL;
2213 return (*func)(self, i);
2214}
2215
2216static struct wrapperbase tab_mul_int[] = {
2217 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2218 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2219 {0}
2220};
2221
2222static struct wrapperbase tab_concat[] = {
2223 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2224 {0}
2225};
2226
2227static struct wrapperbase tab_imul_int[] = {
2228 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2229 {0}
2230};
2231
Guido van Rossum5d815f32001-08-17 21:57:47 +00002232static int
2233getindex(PyObject *self, PyObject *arg)
2234{
2235 int i;
2236
2237 i = PyInt_AsLong(arg);
2238 if (i == -1 && PyErr_Occurred())
2239 return -1;
2240 if (i < 0) {
2241 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2242 if (sq && sq->sq_length) {
2243 int n = (*sq->sq_length)(self);
2244 if (n < 0)
2245 return -1;
2246 i += n;
2247 }
2248 }
2249 return i;
2250}
2251
2252static PyObject *
2253wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2254{
2255 intargfunc func = (intargfunc)wrapped;
2256 PyObject *arg;
2257 int i;
2258
Guido van Rossumf4593e02001-10-03 12:09:30 +00002259 if (PyTuple_GET_SIZE(args) == 1) {
2260 arg = PyTuple_GET_ITEM(args, 0);
2261 i = getindex(self, arg);
2262 if (i == -1 && PyErr_Occurred())
2263 return NULL;
2264 return (*func)(self, i);
2265 }
2266 PyArg_ParseTuple(args, "O", &arg);
2267 assert(PyErr_Occurred());
2268 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002269}
2270
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002272 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002273 "x.__getitem__(i) <==> x[i]"},
2274 {0}
2275};
2276
2277static PyObject *
2278wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2279{
2280 intintargfunc func = (intintargfunc)wrapped;
2281 int i, j;
2282
2283 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2284 return NULL;
2285 return (*func)(self, i, j);
2286}
2287
2288static struct wrapperbase tab_getslice[] = {
2289 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2290 "x.__getslice__(i, j) <==> x[i:j]"},
2291 {0}
2292};
2293
2294static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002295wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002296{
2297 intobjargproc func = (intobjargproc)wrapped;
2298 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002299 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002300
Guido van Rossum5d815f32001-08-17 21:57:47 +00002301 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2302 return NULL;
2303 i = getindex(self, arg);
2304 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002305 return NULL;
2306 res = (*func)(self, i, value);
2307 if (res == -1 && PyErr_Occurred())
2308 return NULL;
2309 Py_INCREF(Py_None);
2310 return Py_None;
2311}
2312
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002313static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002314wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002315{
2316 intobjargproc func = (intobjargproc)wrapped;
2317 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002318 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002319
Guido van Rossum5d815f32001-08-17 21:57:47 +00002320 if (!PyArg_ParseTuple(args, "O", &arg))
2321 return NULL;
2322 i = getindex(self, arg);
2323 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002324 return NULL;
2325 res = (*func)(self, i, NULL);
2326 if (res == -1 && PyErr_Occurred())
2327 return NULL;
2328 Py_INCREF(Py_None);
2329 return Py_None;
2330}
2331
Tim Peters6d6c1a32001-08-02 04:15:00 +00002332static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002333 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002334 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002335 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002336 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002337 {0}
2338};
2339
2340static PyObject *
2341wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2342{
2343 intintobjargproc func = (intintobjargproc)wrapped;
2344 int i, j, res;
2345 PyObject *value;
2346
2347 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2348 return NULL;
2349 res = (*func)(self, i, j, value);
2350 if (res == -1 && PyErr_Occurred())
2351 return NULL;
2352 Py_INCREF(Py_None);
2353 return Py_None;
2354}
2355
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002356static PyObject *
2357wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2358{
2359 intintobjargproc func = (intintobjargproc)wrapped;
2360 int i, j, res;
2361
2362 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2363 return NULL;
2364 res = (*func)(self, i, j, NULL);
2365 if (res == -1 && PyErr_Occurred())
2366 return NULL;
2367 Py_INCREF(Py_None);
2368 return Py_None;
2369}
2370
Tim Peters6d6c1a32001-08-02 04:15:00 +00002371static struct wrapperbase tab_setslice[] = {
2372 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2373 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002374 {"__delslice__", (wrapperfunc)wrap_delslice,
2375 "x.__delslice__(i, j) <==> del x[i:j]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002376 {0}
2377};
2378
2379/* XXX objobjproc is a misnomer; should be objargpred */
2380static PyObject *
2381wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2382{
2383 objobjproc func = (objobjproc)wrapped;
2384 int res;
2385 PyObject *value;
2386
2387 if (!PyArg_ParseTuple(args, "O", &value))
2388 return NULL;
2389 res = (*func)(self, value);
2390 if (res == -1 && PyErr_Occurred())
2391 return NULL;
2392 return PyInt_FromLong((long)res);
2393}
2394
2395static struct wrapperbase tab_contains[] = {
2396 {"__contains__", (wrapperfunc)wrap_objobjproc,
2397 "x.__contains__(y) <==> y in x"},
2398 {0}
2399};
2400
2401static PyObject *
2402wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2403{
2404 objobjargproc func = (objobjargproc)wrapped;
2405 int res;
2406 PyObject *key, *value;
2407
2408 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2409 return NULL;
2410 res = (*func)(self, key, value);
2411 if (res == -1 && PyErr_Occurred())
2412 return NULL;
2413 Py_INCREF(Py_None);
2414 return Py_None;
2415}
2416
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002417static PyObject *
2418wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2419{
2420 objobjargproc func = (objobjargproc)wrapped;
2421 int res;
2422 PyObject *key;
2423
2424 if (!PyArg_ParseTuple(args, "O", &key))
2425 return NULL;
2426 res = (*func)(self, key, NULL);
2427 if (res == -1 && PyErr_Occurred())
2428 return NULL;
2429 Py_INCREF(Py_None);
2430 return Py_None;
2431}
2432
Tim Peters6d6c1a32001-08-02 04:15:00 +00002433static struct wrapperbase tab_setitem[] = {
2434 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2435 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002436 {"__delitem__", (wrapperfunc)wrap_delitem,
2437 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438 {0}
2439};
2440
2441static PyObject *
2442wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2443{
2444 cmpfunc func = (cmpfunc)wrapped;
2445 int res;
2446 PyObject *other;
2447
2448 if (!PyArg_ParseTuple(args, "O", &other))
2449 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002450 if (other->ob_type->tp_compare != func &&
2451 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002452 PyErr_Format(
2453 PyExc_TypeError,
2454 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2455 self->ob_type->tp_name,
2456 self->ob_type->tp_name,
2457 other->ob_type->tp_name);
2458 return NULL;
2459 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002460 res = (*func)(self, other);
2461 if (PyErr_Occurred())
2462 return NULL;
2463 return PyInt_FromLong((long)res);
2464}
2465
2466static struct wrapperbase tab_cmp[] = {
2467 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2468 "x.__cmp__(y) <==> cmp(x,y)"},
2469 {0}
2470};
2471
2472static struct wrapperbase tab_repr[] = {
2473 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2474 "x.__repr__() <==> repr(x)"},
2475 {0}
2476};
2477
2478static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002479 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2480 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002481 {0}
2482};
2483
2484static PyObject *
2485wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2486{
2487 setattrofunc func = (setattrofunc)wrapped;
2488 int res;
2489 PyObject *name, *value;
2490
2491 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2492 return NULL;
2493 res = (*func)(self, name, value);
2494 if (res < 0)
2495 return NULL;
2496 Py_INCREF(Py_None);
2497 return Py_None;
2498}
2499
2500static PyObject *
2501wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2502{
2503 setattrofunc func = (setattrofunc)wrapped;
2504 int res;
2505 PyObject *name;
2506
2507 if (!PyArg_ParseTuple(args, "O", &name))
2508 return NULL;
2509 res = (*func)(self, name, NULL);
2510 if (res < 0)
2511 return NULL;
2512 Py_INCREF(Py_None);
2513 return Py_None;
2514}
2515
2516static struct wrapperbase tab_setattr[] = {
2517 {"__setattr__", (wrapperfunc)wrap_setattr,
2518 "x.__setattr__('name', value) <==> x.name = value"},
2519 {"__delattr__", (wrapperfunc)wrap_delattr,
2520 "x.__delattr__('name') <==> del x.name"},
2521 {0}
2522};
2523
2524static PyObject *
2525wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2526{
2527 hashfunc func = (hashfunc)wrapped;
2528 long res;
2529
2530 if (!PyArg_ParseTuple(args, ""))
2531 return NULL;
2532 res = (*func)(self);
2533 if (res == -1 && PyErr_Occurred())
2534 return NULL;
2535 return PyInt_FromLong(res);
2536}
2537
2538static struct wrapperbase tab_hash[] = {
2539 {"__hash__", (wrapperfunc)wrap_hashfunc,
2540 "x.__hash__() <==> hash(x)"},
2541 {0}
2542};
2543
2544static PyObject *
2545wrap_call(PyObject *self, PyObject *args, void *wrapped)
2546{
2547 ternaryfunc func = (ternaryfunc)wrapped;
2548
2549 /* XXX What about keyword arguments? */
2550 return (*func)(self, args, NULL);
2551}
2552
2553static struct wrapperbase tab_call[] = {
2554 {"__call__", (wrapperfunc)wrap_call,
2555 "x.__call__(...) <==> x(...)"},
2556 {0}
2557};
2558
2559static struct wrapperbase tab_str[] = {
2560 {"__str__", (wrapperfunc)wrap_unaryfunc,
2561 "x.__str__() <==> str(x)"},
2562 {0}
2563};
2564
2565static PyObject *
2566wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2567{
2568 richcmpfunc func = (richcmpfunc)wrapped;
2569 PyObject *other;
2570
2571 if (!PyArg_ParseTuple(args, "O", &other))
2572 return NULL;
2573 return (*func)(self, other, op);
2574}
2575
2576#undef RICHCMP_WRAPPER
2577#define RICHCMP_WRAPPER(NAME, OP) \
2578static PyObject * \
2579richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2580{ \
2581 return wrap_richcmpfunc(self, args, wrapped, OP); \
2582}
2583
Jack Jansen8e938b42001-08-08 15:29:49 +00002584RICHCMP_WRAPPER(lt, Py_LT)
2585RICHCMP_WRAPPER(le, Py_LE)
2586RICHCMP_WRAPPER(eq, Py_EQ)
2587RICHCMP_WRAPPER(ne, Py_NE)
2588RICHCMP_WRAPPER(gt, Py_GT)
2589RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002590
2591#undef RICHCMP_ENTRY
2592#define RICHCMP_ENTRY(NAME, EXPR) \
2593 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2594 "x.__" #NAME "__(y) <==> " EXPR}
2595
2596static struct wrapperbase tab_richcmp[] = {
2597 RICHCMP_ENTRY(lt, "x<y"),
2598 RICHCMP_ENTRY(le, "x<=y"),
2599 RICHCMP_ENTRY(eq, "x==y"),
2600 RICHCMP_ENTRY(ne, "x!=y"),
2601 RICHCMP_ENTRY(gt, "x>y"),
2602 RICHCMP_ENTRY(ge, "x>=y"),
2603 {0}
2604};
2605
2606static struct wrapperbase tab_iter[] = {
2607 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2608 {0}
2609};
2610
2611static PyObject *
2612wrap_next(PyObject *self, PyObject *args, void *wrapped)
2613{
2614 unaryfunc func = (unaryfunc)wrapped;
2615 PyObject *res;
2616
2617 if (!PyArg_ParseTuple(args, ""))
2618 return NULL;
2619 res = (*func)(self);
2620 if (res == NULL && !PyErr_Occurred())
2621 PyErr_SetNone(PyExc_StopIteration);
2622 return res;
2623}
2624
2625static struct wrapperbase tab_next[] = {
2626 {"next", (wrapperfunc)wrap_next,
2627 "x.next() -> the next value, or raise StopIteration"},
2628 {0}
2629};
2630
2631static PyObject *
2632wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2633{
2634 descrgetfunc func = (descrgetfunc)wrapped;
2635 PyObject *obj;
2636 PyObject *type = NULL;
2637
2638 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2639 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002640 return (*func)(self, obj, type);
2641}
2642
2643static struct wrapperbase tab_descr_get[] = {
2644 {"__get__", (wrapperfunc)wrap_descr_get,
2645 "descr.__get__(obj, type) -> value"},
2646 {0}
2647};
2648
2649static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002650wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002651{
2652 descrsetfunc func = (descrsetfunc)wrapped;
2653 PyObject *obj, *value;
2654 int ret;
2655
2656 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2657 return NULL;
2658 ret = (*func)(self, obj, value);
2659 if (ret < 0)
2660 return NULL;
2661 Py_INCREF(Py_None);
2662 return Py_None;
2663}
2664
2665static struct wrapperbase tab_descr_set[] = {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002666 {"__set__", (wrapperfunc)wrap_descr_set,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667 "descr.__set__(obj, value)"},
2668 {0}
2669};
2670
2671static PyObject *
2672wrap_init(PyObject *self, PyObject *args, void *wrapped)
2673{
2674 initproc func = (initproc)wrapped;
2675
2676 /* XXX What about keyword arguments? */
2677 if (func(self, args, NULL) < 0)
2678 return NULL;
2679 Py_INCREF(Py_None);
2680 return Py_None;
2681}
2682
2683static struct wrapperbase tab_init[] = {
2684 {"__init__", (wrapperfunc)wrap_init,
2685 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002686 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002687 {0}
2688};
2689
2690static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002691tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002692{
Barry Warsaw60f01882001-08-22 19:24:42 +00002693 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002694 PyObject *arg0, *res;
2695
2696 if (self == NULL || !PyType_Check(self))
2697 Py_FatalError("__new__() called with non-type 'self'");
2698 type = (PyTypeObject *)self;
2699 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002700 PyErr_Format(PyExc_TypeError,
2701 "%s.__new__(): not enough arguments",
2702 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002703 return NULL;
2704 }
2705 arg0 = PyTuple_GET_ITEM(args, 0);
2706 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002707 PyErr_Format(PyExc_TypeError,
2708 "%s.__new__(X): X is not a type object (%s)",
2709 type->tp_name,
2710 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002711 return NULL;
2712 }
2713 subtype = (PyTypeObject *)arg0;
2714 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002715 PyErr_Format(PyExc_TypeError,
2716 "%s.__new__(%s): %s is not a subtype of %s",
2717 type->tp_name,
2718 subtype->tp_name,
2719 subtype->tp_name,
2720 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002721 return NULL;
2722 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002723
2724 /* Check that the use doesn't do something silly and unsafe like
2725 object.__new__(dictionary). To do this, we check that the
2726 most derived base that's not a heap type is this type. */
2727 staticbase = subtype;
2728 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2729 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002730 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002731 PyErr_Format(PyExc_TypeError,
2732 "%s.__new__(%s) is not safe, use %s.__new__()",
2733 type->tp_name,
2734 subtype->tp_name,
2735 staticbase == NULL ? "?" : staticbase->tp_name);
2736 return NULL;
2737 }
2738
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002739 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2740 if (args == NULL)
2741 return NULL;
2742 res = type->tp_new(subtype, args, kwds);
2743 Py_DECREF(args);
2744 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745}
2746
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002747static struct PyMethodDef tp_new_methoddef[] = {
2748 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2749 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002750 {0}
2751};
2752
2753static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002754add_tp_new_wrapper(PyTypeObject *type)
2755{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002756 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002757
Guido van Rossumf040ede2001-08-07 16:40:56 +00002758 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2759 return 0;
2760 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002761 if (func == NULL)
2762 return -1;
2763 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2764}
2765
Guido van Rossum13d52f02001-08-10 21:24:08 +00002766static int
2767add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2768{
2769 PyObject *dict = type->tp_defined;
2770
2771 for (; wraps->name != NULL; wraps++) {
2772 PyObject *descr;
2773 if (PyDict_GetItemString(dict, wraps->name))
2774 continue;
2775 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2776 if (descr == NULL)
2777 return -1;
2778 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2779 return -1;
2780 Py_DECREF(descr);
2781 }
2782 return 0;
2783}
2784
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002785/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002786 dictionary with method descriptors for function slots. For each
2787 function slot (like tp_repr) that's defined in the type, one or
2788 more corresponding descriptors are added in the type's tp_defined
2789 dictionary under the appropriate name (like __repr__). Some
2790 function slots cause more than one descriptor to be added (for
2791 example, the nb_add slot adds both __add__ and __radd__
2792 descriptors) and some function slots compete for the same
2793 descriptor (for example both sq_item and mp_subscript generate a
2794 __getitem__ descriptor). This only adds new descriptors and
2795 doesn't overwrite entries in tp_defined that were previously
2796 defined. The descriptors contain a reference to the C function
2797 they must call, so that it's safe if they are copied into a
2798 subtype's __dict__ and the subtype has a different C function in
2799 its slot -- calling the method defined by the descriptor will call
2800 the C function that was used to create it, rather than the C
2801 function present in the slot when it is called. (This is important
2802 because a subtype may have a C function in the slot that calls the
2803 method from the dictionary, and we want to avoid infinite recursion
2804 here.) */
2805
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002806static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002807add_operators(PyTypeObject *type)
2808{
2809 PySequenceMethods *sq;
2810 PyMappingMethods *mp;
2811 PyNumberMethods *nb;
2812
2813#undef ADD
2814#define ADD(SLOT, TABLE) \
2815 if (SLOT) { \
2816 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2817 return -1; \
2818 }
2819
2820 if ((sq = type->tp_as_sequence) != NULL) {
2821 ADD(sq->sq_length, tab_len);
2822 ADD(sq->sq_concat, tab_concat);
2823 ADD(sq->sq_repeat, tab_mul_int);
2824 ADD(sq->sq_item, tab_getitem_int);
2825 ADD(sq->sq_slice, tab_getslice);
2826 ADD(sq->sq_ass_item, tab_setitem_int);
2827 ADD(sq->sq_ass_slice, tab_setslice);
2828 ADD(sq->sq_contains, tab_contains);
2829 ADD(sq->sq_inplace_concat, tab_iadd);
2830 ADD(sq->sq_inplace_repeat, tab_imul_int);
2831 }
2832
2833 if ((mp = type->tp_as_mapping) != NULL) {
2834 if (sq->sq_length == NULL)
2835 ADD(mp->mp_length, tab_len);
2836 ADD(mp->mp_subscript, tab_getitem);
2837 ADD(mp->mp_ass_subscript, tab_setitem);
2838 }
2839
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002840 if ((nb = type->tp_as_number) != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002841 ADD(nb->nb_add, tab_add);
2842 ADD(nb->nb_subtract, tab_sub);
2843 ADD(nb->nb_multiply, tab_mul);
2844 ADD(nb->nb_divide, tab_div);
2845 ADD(nb->nb_remainder, tab_mod);
2846 ADD(nb->nb_divmod, tab_divmod);
2847 ADD(nb->nb_power, tab_pow);
2848 ADD(nb->nb_negative, tab_neg);
2849 ADD(nb->nb_positive, tab_pos);
2850 ADD(nb->nb_absolute, tab_abs);
2851 ADD(nb->nb_nonzero, tab_nonzero);
2852 ADD(nb->nb_invert, tab_invert);
2853 ADD(nb->nb_lshift, tab_lshift);
2854 ADD(nb->nb_rshift, tab_rshift);
2855 ADD(nb->nb_and, tab_and);
2856 ADD(nb->nb_xor, tab_xor);
2857 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002858 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002859 ADD(nb->nb_int, tab_int);
2860 ADD(nb->nb_long, tab_long);
2861 ADD(nb->nb_float, tab_float);
2862 ADD(nb->nb_oct, tab_oct);
2863 ADD(nb->nb_hex, tab_hex);
2864 ADD(nb->nb_inplace_add, tab_iadd);
2865 ADD(nb->nb_inplace_subtract, tab_isub);
2866 ADD(nb->nb_inplace_multiply, tab_imul);
2867 ADD(nb->nb_inplace_divide, tab_idiv);
2868 ADD(nb->nb_inplace_remainder, tab_imod);
2869 ADD(nb->nb_inplace_power, tab_ipow);
2870 ADD(nb->nb_inplace_lshift, tab_ilshift);
2871 ADD(nb->nb_inplace_rshift, tab_irshift);
2872 ADD(nb->nb_inplace_and, tab_iand);
2873 ADD(nb->nb_inplace_xor, tab_ixor);
2874 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002875 if (type->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossum874f15a2001-09-25 21:16:33 +00002876 ADD(nb->nb_floor_divide, tab_floordiv);
2877 ADD(nb->nb_true_divide, tab_truediv);
2878 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2879 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2880 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002881 }
2882
2883 ADD(type->tp_getattro, tab_getattr);
2884 ADD(type->tp_setattro, tab_setattr);
2885 ADD(type->tp_compare, tab_cmp);
2886 ADD(type->tp_repr, tab_repr);
2887 ADD(type->tp_hash, tab_hash);
2888 ADD(type->tp_call, tab_call);
2889 ADD(type->tp_str, tab_str);
2890 ADD(type->tp_richcompare, tab_richcmp);
2891 ADD(type->tp_iter, tab_iter);
2892 ADD(type->tp_iternext, tab_next);
2893 ADD(type->tp_descr_get, tab_descr_get);
2894 ADD(type->tp_descr_set, tab_descr_set);
2895 ADD(type->tp_init, tab_init);
2896
Guido van Rossumf040ede2001-08-07 16:40:56 +00002897 if (type->tp_new != NULL) {
2898 if (add_tp_new_wrapper(type) < 0)
2899 return -1;
2900 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002901
2902 return 0;
2903}
2904
Guido van Rossumf040ede2001-08-07 16:40:56 +00002905/* Slot wrappers that call the corresponding __foo__ slot. See comments
2906 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002907
Guido van Rossumdc91b992001-08-08 22:26:22 +00002908#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002909static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002910FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002911{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002912 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002913 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002914}
2915
Guido van Rossumdc91b992001-08-08 22:26:22 +00002916#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002917static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002918FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002919{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002920 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002921 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002922}
2923
Guido van Rossumdc91b992001-08-08 22:26:22 +00002924
2925#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002926static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002927FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002928{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002929 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002930 int do_other = self->ob_type != other->ob_type && \
2931 other->ob_type->tp_as_number != NULL && \
2932 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002933 if (self->ob_type->tp_as_number != NULL && \
2934 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2935 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002936 if (do_other && \
2937 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2938 r = call_maybe( \
2939 other, ROPSTR, &rcache_str, "(O)", self); \
2940 if (r != Py_NotImplemented) \
2941 return r; \
2942 Py_DECREF(r); \
2943 do_other = 0; \
2944 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002945 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002946 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002947 if (r != Py_NotImplemented || \
2948 other->ob_type == self->ob_type) \
2949 return r; \
2950 Py_DECREF(r); \
2951 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002952 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002953 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002954 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002955 } \
2956 Py_INCREF(Py_NotImplemented); \
2957 return Py_NotImplemented; \
2958}
2959
2960#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2961 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2962
2963#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2964static PyObject * \
2965FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2966{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002967 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002968 return call_method(self, OPSTR, &cache_str, \
2969 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970}
2971
2972static int
2973slot_sq_length(PyObject *self)
2974{
Guido van Rossum2730b132001-08-28 18:22:14 +00002975 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002976 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002977 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002978
2979 if (res == NULL)
2980 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002981 len = (int)PyInt_AsLong(res);
2982 Py_DECREF(res);
2983 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002984}
2985
Guido van Rossumdc91b992001-08-08 22:26:22 +00002986SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2987SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002988
2989/* Super-optimized version of slot_sq_item.
2990 Other slots could do the same... */
2991static PyObject *
2992slot_sq_item(PyObject *self, int i)
2993{
2994 static PyObject *getitem_str;
2995 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2996 descrgetfunc f;
2997
2998 if (getitem_str == NULL) {
2999 getitem_str = PyString_InternFromString("__getitem__");
3000 if (getitem_str == NULL)
3001 return NULL;
3002 }
3003 func = _PyType_Lookup(self->ob_type, getitem_str);
3004 if (func != NULL) {
3005 if (func->ob_type == &PyWrapperDescr_Type) {
3006 PyWrapperDescrObject *wrapper =
3007 (PyWrapperDescrObject *)func;
3008 if (wrapper->d_base->wrapper == wrap_sq_item) {
3009 intargfunc f;
3010 f = (intargfunc)(wrapper->d_wrapped);
3011 return f(self, i);
3012 }
3013 }
3014 if ((f = func->ob_type->tp_descr_get) == NULL)
3015 Py_INCREF(func);
3016 else
3017 func = f(func, self, (PyObject *)(self->ob_type));
3018 ival = PyInt_FromLong(i);
3019 if (ival != NULL) {
3020 args = PyTuple_New(1);
3021 if (args != NULL) {
3022 PyTuple_SET_ITEM(args, 0, ival);
3023 retval = PyObject_Call(func, args, NULL);
3024 Py_XDECREF(args);
3025 Py_XDECREF(func);
3026 return retval;
3027 }
3028 }
3029 }
3030 else {
3031 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3032 }
3033 Py_XDECREF(args);
3034 Py_XDECREF(ival);
3035 Py_XDECREF(func);
3036 return NULL;
3037}
3038
Guido van Rossumdc91b992001-08-08 22:26:22 +00003039SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040
3041static int
3042slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3043{
3044 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003045 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003046
3047 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003048 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003049 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003050 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003051 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003052 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003053 if (res == NULL)
3054 return -1;
3055 Py_DECREF(res);
3056 return 0;
3057}
3058
3059static int
3060slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3061{
3062 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003063 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003064
3065 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003066 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003067 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003068 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003069 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003070 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003071 if (res == NULL)
3072 return -1;
3073 Py_DECREF(res);
3074 return 0;
3075}
3076
3077static int
3078slot_sq_contains(PyObject *self, PyObject *value)
3079{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003080 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003081 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003082
Guido van Rossum55f20992001-10-01 17:18:22 +00003083 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003084
3085 if (func != NULL) {
3086 args = Py_BuildValue("(O)", value);
3087 if (args == NULL)
3088 res = NULL;
3089 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003090 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003091 Py_DECREF(args);
3092 }
3093 Py_DECREF(func);
3094 if (res == NULL)
3095 return -1;
3096 return PyObject_IsTrue(res);
3097 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003098 else if (PyErr_Occurred())
3099 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003100 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003101 return _PySequence_IterSearch(self, value,
3102 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104}
3105
Guido van Rossumdc91b992001-08-08 22:26:22 +00003106SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3107SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003108
3109#define slot_mp_length slot_sq_length
3110
Guido van Rossumdc91b992001-08-08 22:26:22 +00003111SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112
3113static int
3114slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3115{
3116 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003117 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118
3119 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003120 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003121 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003122 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003123 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003124 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003125 if (res == NULL)
3126 return -1;
3127 Py_DECREF(res);
3128 return 0;
3129}
3130
Guido van Rossumdc91b992001-08-08 22:26:22 +00003131SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3132SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3133SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3134SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3135SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3136SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3137
3138staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3139
3140SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3141 nb_power, "__pow__", "__rpow__")
3142
3143static PyObject *
3144slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3145{
Guido van Rossum2730b132001-08-28 18:22:14 +00003146 static PyObject *pow_str;
3147
Guido van Rossumdc91b992001-08-08 22:26:22 +00003148 if (modulus == Py_None)
3149 return slot_nb_power_binary(self, other);
3150 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003151 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003152 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003153}
3154
3155SLOT0(slot_nb_negative, "__neg__")
3156SLOT0(slot_nb_positive, "__pos__")
3157SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003158
3159static int
3160slot_nb_nonzero(PyObject *self)
3161{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003162 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003163 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003164
Guido van Rossum55f20992001-10-01 17:18:22 +00003165 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003166 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003167 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003168 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003169 func = lookup_maybe(self, "__len__", &len_str);
3170 if (func == NULL) {
3171 if (PyErr_Occurred())
3172 return -1;
3173 else
3174 return 1;
3175 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003176 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003177 res = PyObject_CallObject(func, NULL);
3178 Py_DECREF(func);
3179 if (res == NULL)
3180 return -1;
3181 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003182}
3183
Guido van Rossumdc91b992001-08-08 22:26:22 +00003184SLOT0(slot_nb_invert, "__invert__")
3185SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3186SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3187SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3188SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3189SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003190
3191static int
3192slot_nb_coerce(PyObject **a, PyObject **b)
3193{
3194 static PyObject *coerce_str;
3195 PyObject *self = *a, *other = *b;
3196
3197 if (self->ob_type->tp_as_number != NULL &&
3198 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3199 PyObject *r;
3200 r = call_maybe(
3201 self, "__coerce__", &coerce_str, "(O)", other);
3202 if (r == NULL)
3203 return -1;
3204 if (r == Py_NotImplemented) {
3205 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003206 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003207 else {
3208 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3209 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003210 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003211 Py_DECREF(r);
3212 return -1;
3213 }
3214 *a = PyTuple_GET_ITEM(r, 0);
3215 Py_INCREF(*a);
3216 *b = PyTuple_GET_ITEM(r, 1);
3217 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003218 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003219 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003220 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003221 }
3222 if (other->ob_type->tp_as_number != NULL &&
3223 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3224 PyObject *r;
3225 r = call_maybe(
3226 other, "__coerce__", &coerce_str, "(O)", self);
3227 if (r == NULL)
3228 return -1;
3229 if (r == Py_NotImplemented) {
3230 Py_DECREF(r);
3231 return 1;
3232 }
3233 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3234 PyErr_SetString(PyExc_TypeError,
3235 "__coerce__ didn't return a 2-tuple");
3236 Py_DECREF(r);
3237 return -1;
3238 }
3239 *a = PyTuple_GET_ITEM(r, 1);
3240 Py_INCREF(*a);
3241 *b = PyTuple_GET_ITEM(r, 0);
3242 Py_INCREF(*b);
3243 Py_DECREF(r);
3244 return 0;
3245 }
3246 return 1;
3247}
3248
Guido van Rossumdc91b992001-08-08 22:26:22 +00003249SLOT0(slot_nb_int, "__int__")
3250SLOT0(slot_nb_long, "__long__")
3251SLOT0(slot_nb_float, "__float__")
3252SLOT0(slot_nb_oct, "__oct__")
3253SLOT0(slot_nb_hex, "__hex__")
3254SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3255SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3256SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3257SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3258SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3259SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3260SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3261SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3262SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3263SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3264SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3265SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3266 "__floordiv__", "__rfloordiv__")
3267SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3268SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3269SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003270
3271static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003272half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003273{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003274 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003275 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003276 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003277
Guido van Rossum60718732001-08-28 17:47:51 +00003278 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003279 if (func == NULL) {
3280 PyErr_Clear();
3281 }
3282 else {
3283 args = Py_BuildValue("(O)", other);
3284 if (args == NULL)
3285 res = NULL;
3286 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003287 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003288 Py_DECREF(args);
3289 }
3290 if (res != Py_NotImplemented) {
3291 if (res == NULL)
3292 return -2;
3293 c = PyInt_AsLong(res);
3294 Py_DECREF(res);
3295 if (c == -1 && PyErr_Occurred())
3296 return -2;
3297 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3298 }
3299 Py_DECREF(res);
3300 }
3301 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003302}
3303
Guido van Rossumab3b0342001-09-18 20:38:53 +00003304/* This slot is published for the benefit of try_3way_compare in object.c */
3305int
3306_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003307{
3308 int c;
3309
Guido van Rossumab3b0342001-09-18 20:38:53 +00003310 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003311 c = half_compare(self, other);
3312 if (c <= 1)
3313 return c;
3314 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003315 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003316 c = half_compare(other, self);
3317 if (c < -1)
3318 return -2;
3319 if (c <= 1)
3320 return -c;
3321 }
3322 return (void *)self < (void *)other ? -1 :
3323 (void *)self > (void *)other ? 1 : 0;
3324}
3325
3326static PyObject *
3327slot_tp_repr(PyObject *self)
3328{
3329 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003330 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003331
Guido van Rossum60718732001-08-28 17:47:51 +00003332 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003333 if (func != NULL) {
3334 res = PyEval_CallObject(func, NULL);
3335 Py_DECREF(func);
3336 return res;
3337 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003338 PyErr_Clear();
3339 return PyString_FromFormat("<%s object at %p>",
3340 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003341}
3342
3343static PyObject *
3344slot_tp_str(PyObject *self)
3345{
3346 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003347 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003348
Guido van Rossum60718732001-08-28 17:47:51 +00003349 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003350 if (func != NULL) {
3351 res = PyEval_CallObject(func, NULL);
3352 Py_DECREF(func);
3353 return res;
3354 }
3355 else {
3356 PyErr_Clear();
3357 return slot_tp_repr(self);
3358 }
3359}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003360
3361static long
3362slot_tp_hash(PyObject *self)
3363{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003364 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003365 static PyObject *hash_str, *eq_str, *cmp_str;
3366
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367 long h;
3368
Guido van Rossum60718732001-08-28 17:47:51 +00003369 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003370
3371 if (func != NULL) {
3372 res = PyEval_CallObject(func, NULL);
3373 Py_DECREF(func);
3374 if (res == NULL)
3375 return -1;
3376 h = PyInt_AsLong(res);
3377 }
3378 else {
3379 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003380 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003381 if (func == NULL) {
3382 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003383 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003384 }
3385 if (func != NULL) {
3386 Py_DECREF(func);
3387 PyErr_SetString(PyExc_TypeError, "unhashable type");
3388 return -1;
3389 }
3390 PyErr_Clear();
3391 h = _Py_HashPointer((void *)self);
3392 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393 if (h == -1 && !PyErr_Occurred())
3394 h = -2;
3395 return h;
3396}
3397
3398static PyObject *
3399slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3400{
Guido van Rossum60718732001-08-28 17:47:51 +00003401 static PyObject *call_str;
3402 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003403 PyObject *res;
3404
3405 if (meth == NULL)
3406 return NULL;
3407 res = PyObject_Call(meth, args, kwds);
3408 Py_DECREF(meth);
3409 return res;
3410}
3411
Tim Peters6d6c1a32001-08-02 04:15:00 +00003412static PyObject *
3413slot_tp_getattro(PyObject *self, PyObject *name)
3414{
3415 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003417 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003418
Guido van Rossum8e248182001-08-12 05:17:56 +00003419 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003420 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003421 if (getattr_str == NULL)
3422 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003424 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003425 if (getattr == NULL) {
3426 /* Avoid further slowdowns */
3427 if (tp->tp_getattro == slot_tp_getattro)
3428 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003429 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003430 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003431 return PyObject_CallFunction(getattr, "OO", self, name);
3432}
3433
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003434static PyObject *
3435slot_tp_getattr_hook(PyObject *self, PyObject *name)
3436{
3437 PyTypeObject *tp = self->ob_type;
3438 PyObject *getattr, *getattribute, *res;
3439 static PyObject *getattribute_str = NULL;
3440 static PyObject *getattr_str = NULL;
3441
3442 if (getattr_str == NULL) {
3443 getattr_str = PyString_InternFromString("__getattr__");
3444 if (getattr_str == NULL)
3445 return NULL;
3446 }
3447 if (getattribute_str == NULL) {
3448 getattribute_str =
3449 PyString_InternFromString("__getattribute__");
3450 if (getattribute_str == NULL)
3451 return NULL;
3452 }
3453 getattr = _PyType_Lookup(tp, getattr_str);
3454 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003455 if (getattribute != NULL &&
3456 getattribute->ob_type == &PyWrapperDescr_Type &&
3457 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3458 PyObject_GenericGetAttr)
3459 getattribute = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003460 if (getattr == NULL && getattribute == NULL) {
3461 /* Avoid further slowdowns */
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003462 /* XXX This is questionable: it means that a class that
3463 isn't born with __getattr__ or __getattribute__ cannot
3464 acquire them in later life. But it's a relatively big
3465 speedup, so I'm keeping it in for now. If this is
3466 removed, you can also remove the "def __getattr__" from
3467 class C (marked with another XXX comment) in dynamics()
3468 in Lib/test/test_descr.py. */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003469 if (tp->tp_getattro == slot_tp_getattr_hook)
3470 tp->tp_getattro = PyObject_GenericGetAttr;
3471 return PyObject_GenericGetAttr(self, name);
3472 }
3473 if (getattribute == NULL)
3474 res = PyObject_GenericGetAttr(self, name);
3475 else
3476 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003477 if (getattr != NULL &&
3478 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003479 PyErr_Clear();
3480 res = PyObject_CallFunction(getattr, "OO", self, name);
3481 }
3482 return res;
3483}
3484
Tim Peters6d6c1a32001-08-02 04:15:00 +00003485static int
3486slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3487{
3488 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003489 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003490
3491 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003492 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003493 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003494 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003495 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003496 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003497 if (res == NULL)
3498 return -1;
3499 Py_DECREF(res);
3500 return 0;
3501}
3502
3503/* Map rich comparison operators to their __xx__ namesakes */
3504static char *name_op[] = {
3505 "__lt__",
3506 "__le__",
3507 "__eq__",
3508 "__ne__",
3509 "__gt__",
3510 "__ge__",
3511};
3512
3513static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003514half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003515{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003516 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003517 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003518
Guido van Rossum60718732001-08-28 17:47:51 +00003519 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003520 if (func == NULL) {
3521 PyErr_Clear();
3522 Py_INCREF(Py_NotImplemented);
3523 return Py_NotImplemented;
3524 }
3525 args = Py_BuildValue("(O)", other);
3526 if (args == NULL)
3527 res = NULL;
3528 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003529 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003530 Py_DECREF(args);
3531 }
3532 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003533 return res;
3534}
3535
Guido van Rossumb8f63662001-08-15 23:57:02 +00003536/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3537static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3538
3539static PyObject *
3540slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3541{
3542 PyObject *res;
3543
3544 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3545 res = half_richcompare(self, other, op);
3546 if (res != Py_NotImplemented)
3547 return res;
3548 Py_DECREF(res);
3549 }
3550 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3551 res = half_richcompare(other, self, swapped_op[op]);
3552 if (res != Py_NotImplemented) {
3553 return res;
3554 }
3555 Py_DECREF(res);
3556 }
3557 Py_INCREF(Py_NotImplemented);
3558 return Py_NotImplemented;
3559}
3560
3561static PyObject *
3562slot_tp_iter(PyObject *self)
3563{
3564 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003565 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003566
Guido van Rossum60718732001-08-28 17:47:51 +00003567 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003568 if (func != NULL) {
3569 res = PyObject_CallObject(func, NULL);
3570 Py_DECREF(func);
3571 return res;
3572 }
3573 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003574 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003575 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003576 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003577 return NULL;
3578 }
3579 Py_DECREF(func);
3580 return PySeqIter_New(self);
3581}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003582
3583static PyObject *
3584slot_tp_iternext(PyObject *self)
3585{
Guido van Rossum2730b132001-08-28 18:22:14 +00003586 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003587 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003588}
3589
Guido van Rossum1a493502001-08-17 16:47:50 +00003590static PyObject *
3591slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3592{
3593 PyTypeObject *tp = self->ob_type;
3594 PyObject *get;
3595 static PyObject *get_str = NULL;
3596
3597 if (get_str == NULL) {
3598 get_str = PyString_InternFromString("__get__");
3599 if (get_str == NULL)
3600 return NULL;
3601 }
3602 get = _PyType_Lookup(tp, get_str);
3603 if (get == NULL) {
3604 /* Avoid further slowdowns */
3605 if (tp->tp_descr_get == slot_tp_descr_get)
3606 tp->tp_descr_get = NULL;
3607 Py_INCREF(self);
3608 return self;
3609 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003610 if (obj == NULL)
3611 obj = Py_None;
3612 if (type == NULL)
3613 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003614 return PyObject_CallFunction(get, "OOO", self, obj, type);
3615}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003616
3617static int
3618slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3619{
Guido van Rossum2c252392001-08-24 10:13:31 +00003620 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003621 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003622
3623 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003624 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003625 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003626 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003627 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003628 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003629 if (res == NULL)
3630 return -1;
3631 Py_DECREF(res);
3632 return 0;
3633}
3634
3635static int
3636slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3637{
Guido van Rossum60718732001-08-28 17:47:51 +00003638 static PyObject *init_str;
3639 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003640 PyObject *res;
3641
3642 if (meth == NULL)
3643 return -1;
3644 res = PyObject_Call(meth, args, kwds);
3645 Py_DECREF(meth);
3646 if (res == NULL)
3647 return -1;
3648 Py_DECREF(res);
3649 return 0;
3650}
3651
3652static PyObject *
3653slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3654{
3655 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3656 PyObject *newargs, *x;
3657 int i, n;
3658
3659 if (func == NULL)
3660 return NULL;
3661 assert(PyTuple_Check(args));
3662 n = PyTuple_GET_SIZE(args);
3663 newargs = PyTuple_New(n+1);
3664 if (newargs == NULL)
3665 return NULL;
3666 Py_INCREF(type);
3667 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3668 for (i = 0; i < n; i++) {
3669 x = PyTuple_GET_ITEM(args, i);
3670 Py_INCREF(x);
3671 PyTuple_SET_ITEM(newargs, i+1, x);
3672 }
3673 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003674 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003675 Py_DECREF(func);
3676 return x;
3677}
3678
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003679
3680/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3681 functions. The offsets here are relative to the 'etype' structure, which
3682 incorporates the additional structures used for numbers, sequences and
3683 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3684 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3685 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3686
3687typedef struct {
3688 char *name;
3689 int offset;
3690 void *function;
3691 wrapperfunc wrapper;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003692 PyObject *name_strobj;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003693} slotdef;
3694
3695#undef TPSLOT
3696#undef ETSLOT
3697#undef SQSLOT
3698#undef MPSLOT
3699#undef NBSLOT
3700#undef BINSLOT
3701#undef RBINSLOT
3702
3703#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3704 {NAME, offsetof(PyTypeObject, SLOT), FUNCTION, WRAPPER}
3705#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3706 {NAME, offsetof(etype, SLOT), FUNCTION, WRAPPER}
3707#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3708 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER)
3709#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3710 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER)
3711#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3712 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER)
3713#define BINSLOT(NAME, SLOT, FUNCTION) \
3714 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l)
3715#define RBINSLOT(NAME, SLOT, FUNCTION) \
3716 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r)
3717
3718static slotdef slotdefs[] = {
3719 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry),
3720 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc),
3721 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3722 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3723 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item),
3724 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc),
3725 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem),
3726 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem),
3727 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
3728 wrap_intintobjargproc),
3729 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice),
3730 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc),
3731 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
3732 wrap_binaryfunc),
3733 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
3734 wrap_intargfunc),
3735
3736 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003737 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
3738 wrap_binaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003739 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
3740 wrap_objobjargproc),
3741 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
3742 wrap_delitem),
3743
3744 BINSLOT("__add__", nb_add, slot_nb_add),
3745 RBINSLOT("__radd__", nb_add, slot_nb_add),
3746 BINSLOT("__sub__", nb_subtract, slot_nb_subtract),
3747 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract),
3748 BINSLOT("__mul__", nb_multiply, slot_nb_multiply),
3749 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply),
3750 BINSLOT("__div__", nb_divide, slot_nb_divide),
3751 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide),
3752 BINSLOT("__mod__", nb_remainder, slot_nb_remainder),
3753 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder),
3754 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod),
3755 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod),
3756 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc),
3757 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r),
3758 NBSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc),
3759 NBSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc),
3760 NBSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc),
3761 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_unaryfunc),
3762 NBSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc),
3763 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift),
3764 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift),
3765 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift),
3766 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift),
3767 BINSLOT("__and__", nb_and, slot_nb_and),
3768 RBINSLOT("__rand__", nb_and, slot_nb_and),
3769 BINSLOT("__xor__", nb_xor, slot_nb_xor),
3770 RBINSLOT("__rxor__", nb_xor, slot_nb_xor),
3771 BINSLOT("__or__", nb_or, slot_nb_or),
3772 RBINSLOT("__ror__", nb_or, slot_nb_or),
3773 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc),
3774 NBSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc),
3775 NBSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc),
3776 NBSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc),
3777 NBSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc),
3778 NBSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc),
3779 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3780 wrap_binaryfunc),
3781 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3782 wrap_binaryfunc),
3783 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3784 wrap_binaryfunc),
3785 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3786 wrap_binaryfunc),
3787 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3788 wrap_binaryfunc),
3789 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3790 wrap_ternaryfunc),
3791 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3792 wrap_binaryfunc),
3793 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3794 wrap_binaryfunc),
3795 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3796 wrap_binaryfunc),
3797 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3798 wrap_binaryfunc),
3799 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3800 wrap_binaryfunc),
3801 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide),
3802 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide),
3803 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide),
3804 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide),
3805 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3806 slot_nb_inplace_floor_divide, wrap_binaryfunc),
3807 NBSLOT("__itruediv__", nb_inplace_true_divide,
3808 slot_nb_inplace_true_divide, wrap_binaryfunc),
3809
3810 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003811 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003812 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc),
3813 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc),
3814 TPSLOT("__call__", tp_call, slot_tp_call, wrap_call),
3815 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro,
3816 wrap_binaryfunc),
3817 TPSLOT("__getattribute__", tp_getattr, NULL, NULL),
3818 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL),
3819 TPSLOT("__getattr__", tp_getattr, NULL, NULL),
3820 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr),
3821 TPSLOT("__setattr__", tp_setattr, NULL, NULL),
3822 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr),
3823 TPSLOT("__delattr__", tp_setattr, NULL, NULL),
3824 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt),
3825 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le),
3826 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq),
3827 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne),
3828 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt),
3829 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge),
3830 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc),
3831 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next),
3832 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get),
3833 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set),
3834 TPSLOT("__init__", tp_init, slot_tp_init, wrap_init),
3835 TPSLOT("__new__", tp_new, slot_tp_new, NULL),
3836 {NULL}
3837};
3838
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003839static void **
3840slotptr(PyTypeObject *type, int offset)
3841{
3842 char *ptr;
3843
3844 assert(offset >= 0);
3845 assert(offset < offsetof(etype, as_buffer));
3846 if (offset >= offsetof(etype, as_mapping)) {
3847 ptr = (void *)type->tp_as_mapping;
3848 offset -= offsetof(etype, as_mapping);
3849 }
3850 else if (offset >= offsetof(etype, as_sequence)) {
3851 ptr = (void *)type->tp_as_sequence;
3852 offset -= offsetof(etype, as_sequence);
3853 }
3854 else if (offset >= offsetof(etype, as_number)) {
3855 ptr = (void *)type->tp_as_number;
3856 offset -= offsetof(etype, as_number);
3857 }
3858 else {
3859 ptr = (void *)type;
3860 }
3861 if (ptr != NULL)
3862 ptr += offset;
3863 return (void **)ptr;
3864}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003865
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003866staticforward int recurse_down_subclasses(PyTypeObject *type, int offset);
3867
3868static int
3869update_one_slot(PyTypeObject *type, int offset)
3870{
3871 slotdef *p;
3872 PyObject *descr;
3873 PyWrapperDescrObject *d;
3874 void *generic = NULL, *specific = NULL;
3875 int use_generic = 0;
3876 void **ptr;
3877
3878 for (p = slotdefs; p->name; p++) {
3879 if (p->offset != offset)
3880 continue;
3881 descr = _PyType_Lookup(type, p->name_strobj);
3882 if (descr == NULL)
3883 continue;
3884 ptr = slotptr(type, p->offset);
3885 if (ptr == NULL)
3886 continue;
3887 generic = p->function;
3888 if (descr->ob_type == &PyWrapperDescr_Type) {
3889 d = (PyWrapperDescrObject *)descr;
3890 if (d->d_base->wrapper == p->wrapper &&
3891 PyType_IsSubtype(type, d->d_type)) {
3892 if (specific == NULL ||
3893 specific == d->d_wrapped)
3894 specific = d->d_wrapped;
3895 else
3896 use_generic = 1;
3897 }
3898 }
3899 else
3900 use_generic = 1;
3901 if (specific && !use_generic)
3902 *ptr = specific;
3903 else
3904 *ptr = generic;
3905 }
3906 if (recurse_down_subclasses(type, offset) < 0)
3907 return -1;
3908 return 0;
3909}
3910
3911static int
3912recurse_down_subclasses(PyTypeObject *type, int offset)
3913{
3914 PyTypeObject *subclass;
3915 PyObject *ref, *subclasses;
3916 int i, n;
3917
3918 subclasses = type->tp_subclasses;
3919 if (subclasses == NULL)
3920 return 0;
3921 assert(PyList_Check(subclasses));
3922 n = PyList_GET_SIZE(subclasses);
3923 for (i = 0; i < n; i++) {
3924 ref = PyList_GET_ITEM(subclasses, i);
3925 assert(PyWeakref_CheckRef(ref));
3926 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3927 if (subclass == NULL)
3928 continue;
3929 assert(PyType_Check(subclass));
3930 if (update_one_slot(subclass, offset) < 0)
3931 return -1;
3932 }
3933 return 0;
3934}
3935
3936static void
3937init_name_strobj(void)
3938{
3939 slotdef *p;
3940 static int initialized = 0;
3941
3942 if (initialized)
3943 return;
3944 for (p = slotdefs; p->name; p++) {
3945 p->name_strobj = PyString_InternFromString(p->name);
3946 if (!p->name_strobj)
3947 Py_FatalError("XXX ouch");
3948 }
3949 initialized = 1;
3950}
3951
3952static void
3953collect_offsets(PyObject *name, int offsets[])
3954{
3955 slotdef *p;
3956
3957 init_name_strobj();
3958 for (p = slotdefs; p->name; p++) {
3959 if (name == p->name_strobj)
3960 *offsets++ = p->offset;
3961 }
3962 *offsets = 0;
3963}
3964
3965static int
3966update_slot(PyTypeObject *type, PyObject *name)
3967{
3968 int offsets[10];
3969 int *ip;
3970
3971 collect_offsets(name, offsets);
3972 for (ip = offsets; *ip; ip++) {
3973 if (update_one_slot(type, *ip) < 0)
3974 return -1;
3975 }
3976 return 0;
3977}
3978
Tim Peters6d6c1a32001-08-02 04:15:00 +00003979static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003980fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003982 slotdef *p;
3983 PyObject *mro, *descr;
3984 PyTypeObject *base;
3985 PyWrapperDescrObject *d;
3986 int i, n;
3987 void **ptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003988
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003989 for (p = slotdefs; p->name; p++) {
3990 ptr = slotptr(type, p->offset);
3991 if (ptr)
3992 *ptr = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003993 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003994 mro = type->tp_mro;
3995 assert(PyTuple_Check(mro));
3996 n = PyTuple_GET_SIZE(mro);
3997 for (p = slotdefs; p->name; p++) {
3998 for (i = 0; i < n; i++) {
3999 base = (PyTypeObject *)PyTuple_GET_ITEM(mro, i);
4000 assert(PyType_Check(base));
4001 descr = PyDict_GetItemString(
4002 base->tp_defined, p->name);
4003 if (descr == NULL)
4004 continue;
4005 ptr = slotptr(type, p->offset);
4006 if (ptr == NULL)
4007 continue;
4008 if (descr->ob_type == &PyWrapperDescr_Type) {
4009 d = (PyWrapperDescrObject *)descr;
4010 if (d->d_base->wrapper == p->wrapper) {
4011 if (*ptr == NULL) {
4012 *ptr = d->d_wrapped;
4013 continue;
4014 }
4015 if (p->wrapper == wrap_binaryfunc_r)
4016 continue;
4017 }
4018 }
4019 *ptr = p->function;
4020 break;
4021 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004022 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004023}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004024
4025
4026/* Cooperative 'super' */
4027
4028typedef struct {
4029 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004030 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004031 PyObject *obj;
4032} superobject;
4033
Guido van Rossum6f799372001-09-20 20:46:19 +00004034static PyMemberDef super_members[] = {
4035 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4036 "the class invoking super()"},
4037 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4038 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004039 {0}
4040};
4041
Guido van Rossum705f0f52001-08-24 16:47:00 +00004042static void
4043super_dealloc(PyObject *self)
4044{
4045 superobject *su = (superobject *)self;
4046
Guido van Rossum048eb752001-10-02 21:24:57 +00004047 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004048 Py_XDECREF(su->obj);
4049 Py_XDECREF(su->type);
4050 self->ob_type->tp_free(self);
4051}
4052
4053static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004054super_repr(PyObject *self)
4055{
4056 superobject *su = (superobject *)self;
4057
4058 if (su->obj)
4059 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004060 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004061 su->type ? su->type->tp_name : "NULL",
4062 su->obj->ob_type->tp_name);
4063 else
4064 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004065 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004066 su->type ? su->type->tp_name : "NULL");
4067}
4068
4069static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004070super_getattro(PyObject *self, PyObject *name)
4071{
4072 superobject *su = (superobject *)self;
4073
4074 if (su->obj != NULL) {
4075 PyObject *mro, *res, *tmp;
4076 descrgetfunc f;
4077 int i, n;
4078
Guido van Rossume705ef12001-08-29 15:47:06 +00004079 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004080 if (mro == NULL)
4081 n = 0;
4082 else {
4083 assert(PyTuple_Check(mro));
4084 n = PyTuple_GET_SIZE(mro);
4085 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004086 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004087 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004088 break;
4089 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004090 if (i >= n && PyType_Check(su->obj)) {
4091 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004092 if (mro == NULL)
4093 n = 0;
4094 else {
4095 assert(PyTuple_Check(mro));
4096 n = PyTuple_GET_SIZE(mro);
4097 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004098 for (i = 0; i < n; i++) {
4099 if ((PyObject *)(su->type) ==
4100 PyTuple_GET_ITEM(mro, i))
4101 break;
4102 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004103 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004104 i++;
4105 res = NULL;
4106 for (; i < n; i++) {
4107 tmp = PyTuple_GET_ITEM(mro, i);
4108 assert(PyType_Check(tmp));
4109 res = PyDict_GetItem(
4110 ((PyTypeObject *)tmp)->tp_defined, name);
4111 if (res != NULL) {
4112 Py_INCREF(res);
4113 f = res->ob_type->tp_descr_get;
4114 if (f != NULL) {
4115 tmp = f(res, su->obj, res);
4116 Py_DECREF(res);
4117 res = tmp;
4118 }
4119 return res;
4120 }
4121 }
4122 }
4123 return PyObject_GenericGetAttr(self, name);
4124}
4125
4126static PyObject *
4127super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4128{
4129 superobject *su = (superobject *)self;
4130 superobject *new;
4131
4132 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4133 /* Not binding to an object, or already bound */
4134 Py_INCREF(self);
4135 return self;
4136 }
4137 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
4138 if (new == NULL)
4139 return NULL;
4140 Py_INCREF(su->type);
4141 Py_INCREF(obj);
4142 new->type = su->type;
4143 new->obj = obj;
4144 return (PyObject *)new;
4145}
4146
4147static int
4148super_init(PyObject *self, PyObject *args, PyObject *kwds)
4149{
4150 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004151 PyTypeObject *type;
4152 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004153
4154 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4155 return -1;
4156 if (obj == Py_None)
4157 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00004158 if (obj != NULL &&
4159 !PyType_IsSubtype(obj->ob_type, type) &&
4160 !(PyType_Check(obj) &&
4161 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004162 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00004163 "super(type, obj): "
4164 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004165 return -1;
4166 }
4167 Py_INCREF(type);
4168 Py_XINCREF(obj);
4169 su->type = type;
4170 su->obj = obj;
4171 return 0;
4172}
4173
4174static char super_doc[] =
4175"super(type) -> unbound super object\n"
4176"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004177"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004178"Typical use to call a cooperative superclass method:\n"
4179"class C(B):\n"
4180" def meth(self, arg):\n"
4181" super(C, self).meth(arg)";
4182
Guido van Rossum048eb752001-10-02 21:24:57 +00004183static int
4184super_traverse(PyObject *self, visitproc visit, void *arg)
4185{
4186 superobject *su = (superobject *)self;
4187 int err;
4188
4189#define VISIT(SLOT) \
4190 if (SLOT) { \
4191 err = visit((PyObject *)(SLOT), arg); \
4192 if (err) \
4193 return err; \
4194 }
4195
4196 VISIT(su->obj);
4197 VISIT(su->type);
4198
4199#undef VISIT
4200
4201 return 0;
4202}
4203
Guido van Rossum705f0f52001-08-24 16:47:00 +00004204PyTypeObject PySuper_Type = {
4205 PyObject_HEAD_INIT(&PyType_Type)
4206 0, /* ob_size */
4207 "super", /* tp_name */
4208 sizeof(superobject), /* tp_basicsize */
4209 0, /* tp_itemsize */
4210 /* methods */
4211 super_dealloc, /* tp_dealloc */
4212 0, /* tp_print */
4213 0, /* tp_getattr */
4214 0, /* tp_setattr */
4215 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004216 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004217 0, /* tp_as_number */
4218 0, /* tp_as_sequence */
4219 0, /* tp_as_mapping */
4220 0, /* tp_hash */
4221 0, /* tp_call */
4222 0, /* tp_str */
4223 super_getattro, /* tp_getattro */
4224 0, /* tp_setattro */
4225 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004226 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4227 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004228 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004229 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004230 0, /* tp_clear */
4231 0, /* tp_richcompare */
4232 0, /* tp_weaklistoffset */
4233 0, /* tp_iter */
4234 0, /* tp_iternext */
4235 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004236 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004237 0, /* tp_getset */
4238 0, /* tp_base */
4239 0, /* tp_dict */
4240 super_descr_get, /* tp_descr_get */
4241 0, /* tp_descr_set */
4242 0, /* tp_dictoffset */
4243 super_init, /* tp_init */
4244 PyType_GenericAlloc, /* tp_alloc */
4245 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004246 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004247};