blob: 63843c53dc7c545210fb0adc760fa82b2ce51313 [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 Rossum7b9144b2001-10-09 19:39:46 +0000679staticforward int update_slot(PyTypeObject *, PyObject *, PyObject *);
680staticforward 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;
1110 return update_slot(type, name, value);
1111 }
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)
1660
Guido van Rossum13d52f02001-08-10 21:24:08 +00001661 /* This won't inherit indirect slots (from tp_as_number etc.)
1662 if type doesn't provide the space. */
1663
1664 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1665 basebase = base->tp_base;
1666 if (basebase->tp_as_number == NULL)
1667 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668 COPYNUM(nb_add);
1669 COPYNUM(nb_subtract);
1670 COPYNUM(nb_multiply);
1671 COPYNUM(nb_divide);
1672 COPYNUM(nb_remainder);
1673 COPYNUM(nb_divmod);
1674 COPYNUM(nb_power);
1675 COPYNUM(nb_negative);
1676 COPYNUM(nb_positive);
1677 COPYNUM(nb_absolute);
1678 COPYNUM(nb_nonzero);
1679 COPYNUM(nb_invert);
1680 COPYNUM(nb_lshift);
1681 COPYNUM(nb_rshift);
1682 COPYNUM(nb_and);
1683 COPYNUM(nb_xor);
1684 COPYNUM(nb_or);
1685 COPYNUM(nb_coerce);
1686 COPYNUM(nb_int);
1687 COPYNUM(nb_long);
1688 COPYNUM(nb_float);
1689 COPYNUM(nb_oct);
1690 COPYNUM(nb_hex);
1691 COPYNUM(nb_inplace_add);
1692 COPYNUM(nb_inplace_subtract);
1693 COPYNUM(nb_inplace_multiply);
1694 COPYNUM(nb_inplace_divide);
1695 COPYNUM(nb_inplace_remainder);
1696 COPYNUM(nb_inplace_power);
1697 COPYNUM(nb_inplace_lshift);
1698 COPYNUM(nb_inplace_rshift);
1699 COPYNUM(nb_inplace_and);
1700 COPYNUM(nb_inplace_xor);
1701 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001702 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1703 COPYNUM(nb_true_divide);
1704 COPYNUM(nb_floor_divide);
1705 COPYNUM(nb_inplace_true_divide);
1706 COPYNUM(nb_inplace_floor_divide);
1707 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001708 }
1709
Guido van Rossum13d52f02001-08-10 21:24:08 +00001710 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1711 basebase = base->tp_base;
1712 if (basebase->tp_as_sequence == NULL)
1713 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001714 COPYSEQ(sq_length);
1715 COPYSEQ(sq_concat);
1716 COPYSEQ(sq_repeat);
1717 COPYSEQ(sq_item);
1718 COPYSEQ(sq_slice);
1719 COPYSEQ(sq_ass_item);
1720 COPYSEQ(sq_ass_slice);
1721 COPYSEQ(sq_contains);
1722 COPYSEQ(sq_inplace_concat);
1723 COPYSEQ(sq_inplace_repeat);
1724 }
1725
Guido van Rossum13d52f02001-08-10 21:24:08 +00001726 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1727 basebase = base->tp_base;
1728 if (basebase->tp_as_mapping == NULL)
1729 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001730 COPYMAP(mp_length);
1731 COPYMAP(mp_subscript);
1732 COPYMAP(mp_ass_subscript);
1733 }
1734
Guido van Rossum13d52f02001-08-10 21:24:08 +00001735 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001736
Tim Peters6d6c1a32001-08-02 04:15:00 +00001737 COPYSLOT(tp_dealloc);
1738 COPYSLOT(tp_print);
1739 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1740 type->tp_getattr = base->tp_getattr;
1741 type->tp_getattro = base->tp_getattro;
1742 }
1743 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1744 type->tp_setattr = base->tp_setattr;
1745 type->tp_setattro = base->tp_setattro;
1746 }
1747 /* tp_compare see tp_richcompare */
1748 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001749 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001750 COPYSLOT(tp_call);
1751 COPYSLOT(tp_str);
1752 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001753 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001754 if (type->tp_compare == NULL &&
1755 type->tp_richcompare == NULL &&
1756 type->tp_hash == NULL)
1757 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001758 type->tp_compare = base->tp_compare;
1759 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001760 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001761 }
1762 }
1763 else {
1764 COPYSLOT(tp_compare);
1765 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1767 COPYSLOT(tp_iter);
1768 COPYSLOT(tp_iternext);
1769 }
1770 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1771 COPYSLOT(tp_descr_get);
1772 COPYSLOT(tp_descr_set);
1773 COPYSLOT(tp_dictoffset);
1774 COPYSLOT(tp_init);
1775 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776 COPYSLOT(tp_free);
1777 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778}
1779
Guido van Rossum13d52f02001-08-10 21:24:08 +00001780staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00001781staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001782
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001784PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001785{
1786 PyObject *dict, *bases, *x;
1787 PyTypeObject *base;
1788 int i, n;
1789
Guido van Rossumd614f972001-08-10 17:39:49 +00001790 if (type->tp_flags & Py_TPFLAGS_READY) {
1791 assert(type->tp_dict != NULL);
1792 return 0;
1793 }
1794 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1795 assert(type->tp_dict == NULL);
1796
1797 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798
1799 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1800 base = type->tp_base;
1801 if (base == NULL && type != &PyBaseObject_Type)
1802 base = type->tp_base = &PyBaseObject_Type;
1803
1804 /* Initialize tp_bases */
1805 bases = type->tp_bases;
1806 if (bases == NULL) {
1807 if (base == NULL)
1808 bases = PyTuple_New(0);
1809 else
1810 bases = Py_BuildValue("(O)", base);
1811 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001812 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001813 type->tp_bases = bases;
1814 }
1815
1816 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001817 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001818 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001819 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001820 }
1821
1822 /* Initialize tp_defined */
1823 dict = type->tp_defined;
1824 if (dict == NULL) {
1825 dict = PyDict_New();
1826 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001827 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001828 type->tp_defined = dict;
1829 }
1830
1831 /* Add type-specific descriptors to tp_defined */
1832 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001833 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834 if (type->tp_methods != NULL) {
1835 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001836 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001837 }
1838 if (type->tp_members != NULL) {
1839 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001840 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001841 }
1842 if (type->tp_getset != NULL) {
1843 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001844 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845 }
1846
1847 /* Temporarily make tp_dict the same object as tp_defined.
1848 (This is needed to call mro(), and can stay this way for
1849 dynamic types). */
1850 Py_INCREF(type->tp_defined);
1851 type->tp_dict = type->tp_defined;
1852
1853 /* Calculate method resolution order */
1854 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001855 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001856 }
1857
Guido van Rossum13d52f02001-08-10 21:24:08 +00001858 /* Inherit special flags from dominant base */
1859 if (type->tp_base != NULL)
1860 inherit_special(type, type->tp_base);
1861
Tim Peters6d6c1a32001-08-02 04:15:00 +00001862 /* Initialize tp_dict properly */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001863 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001864 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001865 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001866 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001867 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001868 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001869 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001870 bases = type->tp_mro;
1871 assert(bases != NULL);
1872 assert(PyTuple_Check(bases));
1873 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001874 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001875 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1876 assert(PyType_Check(base));
1877 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001878 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001879 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001880 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001881 }
1882 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001883 else {
1884 /* For a dynamic type, we simply inherit the base slots. */
1885 bases = type->tp_mro;
1886 assert(bases != NULL);
1887 assert(PyTuple_Check(bases));
1888 n = PyTuple_GET_SIZE(bases);
1889 for (i = 1; i < n; i++) {
1890 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1891 assert(PyType_Check(base));
1892 inherit_slots(type, base);
1893 }
1894 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001895
Guido van Rossum13d52f02001-08-10 21:24:08 +00001896 /* Some more special stuff */
1897 base = type->tp_base;
1898 if (base != NULL) {
1899 if (type->tp_as_number == NULL)
1900 type->tp_as_number = base->tp_as_number;
1901 if (type->tp_as_sequence == NULL)
1902 type->tp_as_sequence = base->tp_as_sequence;
1903 if (type->tp_as_mapping == NULL)
1904 type->tp_as_mapping = base->tp_as_mapping;
1905 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906
Guido van Rossum1c450732001-10-08 15:18:27 +00001907 /* Link into each base class's list of subclasses */
1908 bases = type->tp_bases;
1909 n = PyTuple_GET_SIZE(bases);
1910 for (i = 0; i < n; i++) {
1911 base = (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
1912 if (add_subclass((PyTypeObject *)base, type) < 0)
1913 goto error;
1914 }
1915
Guido van Rossum13d52f02001-08-10 21:24:08 +00001916 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001917 assert(type->tp_dict != NULL);
1918 type->tp_flags =
1919 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001920 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001921
1922 error:
1923 type->tp_flags &= ~Py_TPFLAGS_READYING;
1924 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001925}
1926
Guido van Rossum1c450732001-10-08 15:18:27 +00001927static int
1928add_subclass(PyTypeObject *base, PyTypeObject *type)
1929{
1930 int i;
1931 PyObject *list, *ref, *new;
1932
1933 list = base->tp_subclasses;
1934 if (list == NULL) {
1935 base->tp_subclasses = list = PyList_New(0);
1936 if (list == NULL)
1937 return -1;
1938 }
1939 assert(PyList_Check(list));
1940 new = PyWeakref_NewRef((PyObject *)type, NULL);
1941 i = PyList_GET_SIZE(list);
1942 while (--i >= 0) {
1943 ref = PyList_GET_ITEM(list, i);
1944 assert(PyWeakref_CheckRef(ref));
1945 if (PyWeakref_GET_OBJECT(ref) == Py_None)
1946 return PyList_SetItem(list, i, new);
1947 }
1948 i = PyList_Append(list, new);
1949 Py_DECREF(new);
1950 return i;
1951}
1952
Tim Peters6d6c1a32001-08-02 04:15:00 +00001953
1954/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1955
1956/* There's a wrapper *function* for each distinct function typedef used
1957 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1958 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1959 Most tables have only one entry; the tables for binary operators have two
1960 entries, one regular and one with reversed arguments. */
1961
1962static PyObject *
1963wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1964{
1965 inquiry func = (inquiry)wrapped;
1966 int res;
1967
1968 if (!PyArg_ParseTuple(args, ""))
1969 return NULL;
1970 res = (*func)(self);
1971 if (res == -1 && PyErr_Occurred())
1972 return NULL;
1973 return PyInt_FromLong((long)res);
1974}
1975
1976static struct wrapperbase tab_len[] = {
1977 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1978 {0}
1979};
1980
1981static PyObject *
1982wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1983{
1984 binaryfunc func = (binaryfunc)wrapped;
1985 PyObject *other;
1986
1987 if (!PyArg_ParseTuple(args, "O", &other))
1988 return NULL;
1989 return (*func)(self, other);
1990}
1991
1992static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001993wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
1994{
1995 binaryfunc func = (binaryfunc)wrapped;
1996 PyObject *other;
1997
1998 if (!PyArg_ParseTuple(args, "O", &other))
1999 return NULL;
2000 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002001 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002002 Py_INCREF(Py_NotImplemented);
2003 return Py_NotImplemented;
2004 }
2005 return (*func)(self, other);
2006}
2007
2008static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2010{
2011 binaryfunc func = (binaryfunc)wrapped;
2012 PyObject *other;
2013
2014 if (!PyArg_ParseTuple(args, "O", &other))
2015 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002016 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002017 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002018 Py_INCREF(Py_NotImplemented);
2019 return Py_NotImplemented;
2020 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021 return (*func)(other, self);
2022}
2023
2024#undef BINARY
2025#define BINARY(NAME, OP) \
2026static struct wrapperbase tab_##NAME[] = { \
2027 {"__" #NAME "__", \
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002028 (wrapperfunc)wrap_binaryfunc_l, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029 "x.__" #NAME "__(y) <==> " #OP}, \
2030 {"__r" #NAME "__", \
2031 (wrapperfunc)wrap_binaryfunc_r, \
2032 "y.__r" #NAME "__(x) <==> " #OP}, \
2033 {0} \
2034}
2035
2036BINARY(add, "x+y");
2037BINARY(sub, "x-y");
2038BINARY(mul, "x*y");
2039BINARY(div, "x/y");
2040BINARY(mod, "x%y");
2041BINARY(divmod, "divmod(x,y)");
2042BINARY(lshift, "x<<y");
2043BINARY(rshift, "x>>y");
2044BINARY(and, "x&y");
2045BINARY(xor, "x^y");
2046BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002047
2048static PyObject *
2049wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2050{
2051 coercion func = (coercion)wrapped;
2052 PyObject *other, *res;
2053 int ok;
2054
2055 if (!PyArg_ParseTuple(args, "O", &other))
2056 return NULL;
2057 ok = func(&self, &other);
2058 if (ok < 0)
2059 return NULL;
2060 if (ok > 0) {
2061 Py_INCREF(Py_NotImplemented);
2062 return Py_NotImplemented;
2063 }
2064 res = PyTuple_New(2);
2065 if (res == NULL) {
2066 Py_DECREF(self);
2067 Py_DECREF(other);
2068 return NULL;
2069 }
2070 PyTuple_SET_ITEM(res, 0, self);
2071 PyTuple_SET_ITEM(res, 1, other);
2072 return res;
2073}
2074
2075static struct wrapperbase tab_coerce[] = {
2076 {"__coerce__", (wrapperfunc)wrap_coercefunc,
2077 "x.__coerce__(y) <==> coerce(x, y)"},
2078 {0}
2079};
2080
Guido van Rossum874f15a2001-09-25 21:16:33 +00002081BINARY(floordiv, "x//y");
2082BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002083
2084static PyObject *
2085wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2086{
2087 ternaryfunc func = (ternaryfunc)wrapped;
2088 PyObject *other;
2089 PyObject *third = Py_None;
2090
2091 /* Note: This wrapper only works for __pow__() */
2092
2093 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2094 return NULL;
2095 return (*func)(self, other, third);
2096}
2097
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002098static PyObject *
2099wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2100{
2101 ternaryfunc func = (ternaryfunc)wrapped;
2102 PyObject *other;
2103 PyObject *third = Py_None;
2104
2105 /* Note: This wrapper only works for __pow__() */
2106
2107 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2108 return NULL;
2109 return (*func)(other, self, third);
2110}
2111
Tim Peters6d6c1a32001-08-02 04:15:00 +00002112#undef TERNARY
2113#define TERNARY(NAME, OP) \
2114static struct wrapperbase tab_##NAME[] = { \
2115 {"__" #NAME "__", \
2116 (wrapperfunc)wrap_ternaryfunc, \
2117 "x.__" #NAME "__(y, z) <==> " #OP}, \
2118 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002119 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002120 "y.__r" #NAME "__(x, z) <==> " #OP}, \
2121 {0} \
2122}
2123
2124TERNARY(pow, "(x**y) % z");
2125
2126#undef UNARY
2127#define UNARY(NAME, OP) \
2128static struct wrapperbase tab_##NAME[] = { \
2129 {"__" #NAME "__", \
2130 (wrapperfunc)wrap_unaryfunc, \
2131 "x.__" #NAME "__() <==> " #OP}, \
2132 {0} \
2133}
2134
2135static PyObject *
2136wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2137{
2138 unaryfunc func = (unaryfunc)wrapped;
2139
2140 if (!PyArg_ParseTuple(args, ""))
2141 return NULL;
2142 return (*func)(self);
2143}
2144
2145UNARY(neg, "-x");
2146UNARY(pos, "+x");
2147UNARY(abs, "abs(x)");
2148UNARY(nonzero, "x != 0");
2149UNARY(invert, "~x");
2150UNARY(int, "int(x)");
2151UNARY(long, "long(x)");
2152UNARY(float, "float(x)");
2153UNARY(oct, "oct(x)");
2154UNARY(hex, "hex(x)");
2155
2156#undef IBINARY
2157#define IBINARY(NAME, OP) \
2158static struct wrapperbase tab_##NAME[] = { \
2159 {"__" #NAME "__", \
2160 (wrapperfunc)wrap_binaryfunc, \
2161 "x.__" #NAME "__(y) <==> " #OP}, \
2162 {0} \
2163}
2164
2165IBINARY(iadd, "x+=y");
2166IBINARY(isub, "x-=y");
2167IBINARY(imul, "x*=y");
2168IBINARY(idiv, "x/=y");
2169IBINARY(imod, "x%=y");
2170IBINARY(ilshift, "x<<=y");
2171IBINARY(irshift, "x>>=y");
2172IBINARY(iand, "x&=y");
2173IBINARY(ixor, "x^=y");
2174IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002175IBINARY(ifloordiv, "x//=y");
2176IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002177
2178#undef ITERNARY
2179#define ITERNARY(NAME, OP) \
2180static struct wrapperbase tab_##NAME[] = { \
2181 {"__" #NAME "__", \
2182 (wrapperfunc)wrap_ternaryfunc, \
2183 "x.__" #NAME "__(y) <==> " #OP}, \
2184 {0} \
2185}
2186
2187ITERNARY(ipow, "x = (x**y) % z");
2188
2189static struct wrapperbase tab_getitem[] = {
2190 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2191 "x.__getitem__(y) <==> x[y]"},
2192 {0}
2193};
2194
2195static PyObject *
2196wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2197{
2198 intargfunc func = (intargfunc)wrapped;
2199 int i;
2200
2201 if (!PyArg_ParseTuple(args, "i", &i))
2202 return NULL;
2203 return (*func)(self, i);
2204}
2205
2206static struct wrapperbase tab_mul_int[] = {
2207 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2208 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2209 {0}
2210};
2211
2212static struct wrapperbase tab_concat[] = {
2213 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2214 {0}
2215};
2216
2217static struct wrapperbase tab_imul_int[] = {
2218 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2219 {0}
2220};
2221
Guido van Rossum5d815f32001-08-17 21:57:47 +00002222static int
2223getindex(PyObject *self, PyObject *arg)
2224{
2225 int i;
2226
2227 i = PyInt_AsLong(arg);
2228 if (i == -1 && PyErr_Occurred())
2229 return -1;
2230 if (i < 0) {
2231 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2232 if (sq && sq->sq_length) {
2233 int n = (*sq->sq_length)(self);
2234 if (n < 0)
2235 return -1;
2236 i += n;
2237 }
2238 }
2239 return i;
2240}
2241
2242static PyObject *
2243wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2244{
2245 intargfunc func = (intargfunc)wrapped;
2246 PyObject *arg;
2247 int i;
2248
Guido van Rossumf4593e02001-10-03 12:09:30 +00002249 if (PyTuple_GET_SIZE(args) == 1) {
2250 arg = PyTuple_GET_ITEM(args, 0);
2251 i = getindex(self, arg);
2252 if (i == -1 && PyErr_Occurred())
2253 return NULL;
2254 return (*func)(self, i);
2255 }
2256 PyArg_ParseTuple(args, "O", &arg);
2257 assert(PyErr_Occurred());
2258 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002259}
2260
Tim Peters6d6c1a32001-08-02 04:15:00 +00002261static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002262 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002263 "x.__getitem__(i) <==> x[i]"},
2264 {0}
2265};
2266
2267static PyObject *
2268wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2269{
2270 intintargfunc func = (intintargfunc)wrapped;
2271 int i, j;
2272
2273 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2274 return NULL;
2275 return (*func)(self, i, j);
2276}
2277
2278static struct wrapperbase tab_getslice[] = {
2279 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2280 "x.__getslice__(i, j) <==> x[i:j]"},
2281 {0}
2282};
2283
2284static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002285wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002286{
2287 intobjargproc func = (intobjargproc)wrapped;
2288 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002289 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002290
Guido van Rossum5d815f32001-08-17 21:57:47 +00002291 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2292 return NULL;
2293 i = getindex(self, arg);
2294 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295 return NULL;
2296 res = (*func)(self, i, value);
2297 if (res == -1 && PyErr_Occurred())
2298 return NULL;
2299 Py_INCREF(Py_None);
2300 return Py_None;
2301}
2302
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002303static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002304wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002305{
2306 intobjargproc func = (intobjargproc)wrapped;
2307 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002308 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002309
Guido van Rossum5d815f32001-08-17 21:57:47 +00002310 if (!PyArg_ParseTuple(args, "O", &arg))
2311 return NULL;
2312 i = getindex(self, arg);
2313 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002314 return NULL;
2315 res = (*func)(self, i, NULL);
2316 if (res == -1 && PyErr_Occurred())
2317 return NULL;
2318 Py_INCREF(Py_None);
2319 return Py_None;
2320}
2321
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002323 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002324 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002325 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002326 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002327 {0}
2328};
2329
2330static PyObject *
2331wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2332{
2333 intintobjargproc func = (intintobjargproc)wrapped;
2334 int i, j, res;
2335 PyObject *value;
2336
2337 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2338 return NULL;
2339 res = (*func)(self, i, j, value);
2340 if (res == -1 && PyErr_Occurred())
2341 return NULL;
2342 Py_INCREF(Py_None);
2343 return Py_None;
2344}
2345
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002346static PyObject *
2347wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2348{
2349 intintobjargproc func = (intintobjargproc)wrapped;
2350 int i, j, res;
2351
2352 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2353 return NULL;
2354 res = (*func)(self, i, j, NULL);
2355 if (res == -1 && PyErr_Occurred())
2356 return NULL;
2357 Py_INCREF(Py_None);
2358 return Py_None;
2359}
2360
Tim Peters6d6c1a32001-08-02 04:15:00 +00002361static struct wrapperbase tab_setslice[] = {
2362 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2363 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002364 {"__delslice__", (wrapperfunc)wrap_delslice,
2365 "x.__delslice__(i, j) <==> del x[i:j]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002366 {0}
2367};
2368
2369/* XXX objobjproc is a misnomer; should be objargpred */
2370static PyObject *
2371wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2372{
2373 objobjproc func = (objobjproc)wrapped;
2374 int res;
2375 PyObject *value;
2376
2377 if (!PyArg_ParseTuple(args, "O", &value))
2378 return NULL;
2379 res = (*func)(self, value);
2380 if (res == -1 && PyErr_Occurred())
2381 return NULL;
2382 return PyInt_FromLong((long)res);
2383}
2384
2385static struct wrapperbase tab_contains[] = {
2386 {"__contains__", (wrapperfunc)wrap_objobjproc,
2387 "x.__contains__(y) <==> y in x"},
2388 {0}
2389};
2390
2391static PyObject *
2392wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2393{
2394 objobjargproc func = (objobjargproc)wrapped;
2395 int res;
2396 PyObject *key, *value;
2397
2398 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2399 return NULL;
2400 res = (*func)(self, key, value);
2401 if (res == -1 && PyErr_Occurred())
2402 return NULL;
2403 Py_INCREF(Py_None);
2404 return Py_None;
2405}
2406
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002407static PyObject *
2408wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2409{
2410 objobjargproc func = (objobjargproc)wrapped;
2411 int res;
2412 PyObject *key;
2413
2414 if (!PyArg_ParseTuple(args, "O", &key))
2415 return NULL;
2416 res = (*func)(self, key, NULL);
2417 if (res == -1 && PyErr_Occurred())
2418 return NULL;
2419 Py_INCREF(Py_None);
2420 return Py_None;
2421}
2422
Tim Peters6d6c1a32001-08-02 04:15:00 +00002423static struct wrapperbase tab_setitem[] = {
2424 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2425 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002426 {"__delitem__", (wrapperfunc)wrap_delitem,
2427 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002428 {0}
2429};
2430
2431static PyObject *
2432wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2433{
2434 cmpfunc func = (cmpfunc)wrapped;
2435 int res;
2436 PyObject *other;
2437
2438 if (!PyArg_ParseTuple(args, "O", &other))
2439 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002440 if (other->ob_type->tp_compare != func &&
2441 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002442 PyErr_Format(
2443 PyExc_TypeError,
2444 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2445 self->ob_type->tp_name,
2446 self->ob_type->tp_name,
2447 other->ob_type->tp_name);
2448 return NULL;
2449 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002450 res = (*func)(self, other);
2451 if (PyErr_Occurred())
2452 return NULL;
2453 return PyInt_FromLong((long)res);
2454}
2455
2456static struct wrapperbase tab_cmp[] = {
2457 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2458 "x.__cmp__(y) <==> cmp(x,y)"},
2459 {0}
2460};
2461
2462static struct wrapperbase tab_repr[] = {
2463 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2464 "x.__repr__() <==> repr(x)"},
2465 {0}
2466};
2467
2468static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002469 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2470 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002471 {0}
2472};
2473
2474static PyObject *
2475wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2476{
2477 setattrofunc func = (setattrofunc)wrapped;
2478 int res;
2479 PyObject *name, *value;
2480
2481 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2482 return NULL;
2483 res = (*func)(self, name, value);
2484 if (res < 0)
2485 return NULL;
2486 Py_INCREF(Py_None);
2487 return Py_None;
2488}
2489
2490static PyObject *
2491wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2492{
2493 setattrofunc func = (setattrofunc)wrapped;
2494 int res;
2495 PyObject *name;
2496
2497 if (!PyArg_ParseTuple(args, "O", &name))
2498 return NULL;
2499 res = (*func)(self, name, NULL);
2500 if (res < 0)
2501 return NULL;
2502 Py_INCREF(Py_None);
2503 return Py_None;
2504}
2505
2506static struct wrapperbase tab_setattr[] = {
2507 {"__setattr__", (wrapperfunc)wrap_setattr,
2508 "x.__setattr__('name', value) <==> x.name = value"},
2509 {"__delattr__", (wrapperfunc)wrap_delattr,
2510 "x.__delattr__('name') <==> del x.name"},
2511 {0}
2512};
2513
2514static PyObject *
2515wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2516{
2517 hashfunc func = (hashfunc)wrapped;
2518 long res;
2519
2520 if (!PyArg_ParseTuple(args, ""))
2521 return NULL;
2522 res = (*func)(self);
2523 if (res == -1 && PyErr_Occurred())
2524 return NULL;
2525 return PyInt_FromLong(res);
2526}
2527
2528static struct wrapperbase tab_hash[] = {
2529 {"__hash__", (wrapperfunc)wrap_hashfunc,
2530 "x.__hash__() <==> hash(x)"},
2531 {0}
2532};
2533
2534static PyObject *
2535wrap_call(PyObject *self, PyObject *args, void *wrapped)
2536{
2537 ternaryfunc func = (ternaryfunc)wrapped;
2538
2539 /* XXX What about keyword arguments? */
2540 return (*func)(self, args, NULL);
2541}
2542
2543static struct wrapperbase tab_call[] = {
2544 {"__call__", (wrapperfunc)wrap_call,
2545 "x.__call__(...) <==> x(...)"},
2546 {0}
2547};
2548
2549static struct wrapperbase tab_str[] = {
2550 {"__str__", (wrapperfunc)wrap_unaryfunc,
2551 "x.__str__() <==> str(x)"},
2552 {0}
2553};
2554
2555static PyObject *
2556wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2557{
2558 richcmpfunc func = (richcmpfunc)wrapped;
2559 PyObject *other;
2560
2561 if (!PyArg_ParseTuple(args, "O", &other))
2562 return NULL;
2563 return (*func)(self, other, op);
2564}
2565
2566#undef RICHCMP_WRAPPER
2567#define RICHCMP_WRAPPER(NAME, OP) \
2568static PyObject * \
2569richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2570{ \
2571 return wrap_richcmpfunc(self, args, wrapped, OP); \
2572}
2573
Jack Jansen8e938b42001-08-08 15:29:49 +00002574RICHCMP_WRAPPER(lt, Py_LT)
2575RICHCMP_WRAPPER(le, Py_LE)
2576RICHCMP_WRAPPER(eq, Py_EQ)
2577RICHCMP_WRAPPER(ne, Py_NE)
2578RICHCMP_WRAPPER(gt, Py_GT)
2579RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002580
2581#undef RICHCMP_ENTRY
2582#define RICHCMP_ENTRY(NAME, EXPR) \
2583 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2584 "x.__" #NAME "__(y) <==> " EXPR}
2585
2586static struct wrapperbase tab_richcmp[] = {
2587 RICHCMP_ENTRY(lt, "x<y"),
2588 RICHCMP_ENTRY(le, "x<=y"),
2589 RICHCMP_ENTRY(eq, "x==y"),
2590 RICHCMP_ENTRY(ne, "x!=y"),
2591 RICHCMP_ENTRY(gt, "x>y"),
2592 RICHCMP_ENTRY(ge, "x>=y"),
2593 {0}
2594};
2595
2596static struct wrapperbase tab_iter[] = {
2597 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2598 {0}
2599};
2600
2601static PyObject *
2602wrap_next(PyObject *self, PyObject *args, void *wrapped)
2603{
2604 unaryfunc func = (unaryfunc)wrapped;
2605 PyObject *res;
2606
2607 if (!PyArg_ParseTuple(args, ""))
2608 return NULL;
2609 res = (*func)(self);
2610 if (res == NULL && !PyErr_Occurred())
2611 PyErr_SetNone(PyExc_StopIteration);
2612 return res;
2613}
2614
2615static struct wrapperbase tab_next[] = {
2616 {"next", (wrapperfunc)wrap_next,
2617 "x.next() -> the next value, or raise StopIteration"},
2618 {0}
2619};
2620
2621static PyObject *
2622wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2623{
2624 descrgetfunc func = (descrgetfunc)wrapped;
2625 PyObject *obj;
2626 PyObject *type = NULL;
2627
2628 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2629 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002630 return (*func)(self, obj, type);
2631}
2632
2633static struct wrapperbase tab_descr_get[] = {
2634 {"__get__", (wrapperfunc)wrap_descr_get,
2635 "descr.__get__(obj, type) -> value"},
2636 {0}
2637};
2638
2639static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002640wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002641{
2642 descrsetfunc func = (descrsetfunc)wrapped;
2643 PyObject *obj, *value;
2644 int ret;
2645
2646 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2647 return NULL;
2648 ret = (*func)(self, obj, value);
2649 if (ret < 0)
2650 return NULL;
2651 Py_INCREF(Py_None);
2652 return Py_None;
2653}
2654
2655static struct wrapperbase tab_descr_set[] = {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002656 {"__set__", (wrapperfunc)wrap_descr_set,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002657 "descr.__set__(obj, value)"},
2658 {0}
2659};
2660
2661static PyObject *
2662wrap_init(PyObject *self, PyObject *args, void *wrapped)
2663{
2664 initproc func = (initproc)wrapped;
2665
2666 /* XXX What about keyword arguments? */
2667 if (func(self, args, NULL) < 0)
2668 return NULL;
2669 Py_INCREF(Py_None);
2670 return Py_None;
2671}
2672
2673static struct wrapperbase tab_init[] = {
2674 {"__init__", (wrapperfunc)wrap_init,
2675 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002676 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002677 {0}
2678};
2679
2680static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002681tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682{
Barry Warsaw60f01882001-08-22 19:24:42 +00002683 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002684 PyObject *arg0, *res;
2685
2686 if (self == NULL || !PyType_Check(self))
2687 Py_FatalError("__new__() called with non-type 'self'");
2688 type = (PyTypeObject *)self;
2689 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002690 PyErr_Format(PyExc_TypeError,
2691 "%s.__new__(): not enough arguments",
2692 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002693 return NULL;
2694 }
2695 arg0 = PyTuple_GET_ITEM(args, 0);
2696 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002697 PyErr_Format(PyExc_TypeError,
2698 "%s.__new__(X): X is not a type object (%s)",
2699 type->tp_name,
2700 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002701 return NULL;
2702 }
2703 subtype = (PyTypeObject *)arg0;
2704 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002705 PyErr_Format(PyExc_TypeError,
2706 "%s.__new__(%s): %s is not a subtype of %s",
2707 type->tp_name,
2708 subtype->tp_name,
2709 subtype->tp_name,
2710 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002711 return NULL;
2712 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002713
2714 /* Check that the use doesn't do something silly and unsafe like
2715 object.__new__(dictionary). To do this, we check that the
2716 most derived base that's not a heap type is this type. */
2717 staticbase = subtype;
2718 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2719 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002720 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002721 PyErr_Format(PyExc_TypeError,
2722 "%s.__new__(%s) is not safe, use %s.__new__()",
2723 type->tp_name,
2724 subtype->tp_name,
2725 staticbase == NULL ? "?" : staticbase->tp_name);
2726 return NULL;
2727 }
2728
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002729 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2730 if (args == NULL)
2731 return NULL;
2732 res = type->tp_new(subtype, args, kwds);
2733 Py_DECREF(args);
2734 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002735}
2736
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002737static struct PyMethodDef tp_new_methoddef[] = {
2738 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2739 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002740 {0}
2741};
2742
2743static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002744add_tp_new_wrapper(PyTypeObject *type)
2745{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002746 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002747
Guido van Rossumf040ede2001-08-07 16:40:56 +00002748 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2749 return 0;
2750 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002751 if (func == NULL)
2752 return -1;
2753 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2754}
2755
Guido van Rossum13d52f02001-08-10 21:24:08 +00002756static int
2757add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2758{
2759 PyObject *dict = type->tp_defined;
2760
2761 for (; wraps->name != NULL; wraps++) {
2762 PyObject *descr;
2763 if (PyDict_GetItemString(dict, wraps->name))
2764 continue;
2765 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2766 if (descr == NULL)
2767 return -1;
2768 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2769 return -1;
2770 Py_DECREF(descr);
2771 }
2772 return 0;
2773}
2774
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002775/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002776 dictionary with method descriptors for function slots. For each
2777 function slot (like tp_repr) that's defined in the type, one or
2778 more corresponding descriptors are added in the type's tp_defined
2779 dictionary under the appropriate name (like __repr__). Some
2780 function slots cause more than one descriptor to be added (for
2781 example, the nb_add slot adds both __add__ and __radd__
2782 descriptors) and some function slots compete for the same
2783 descriptor (for example both sq_item and mp_subscript generate a
2784 __getitem__ descriptor). This only adds new descriptors and
2785 doesn't overwrite entries in tp_defined that were previously
2786 defined. The descriptors contain a reference to the C function
2787 they must call, so that it's safe if they are copied into a
2788 subtype's __dict__ and the subtype has a different C function in
2789 its slot -- calling the method defined by the descriptor will call
2790 the C function that was used to create it, rather than the C
2791 function present in the slot when it is called. (This is important
2792 because a subtype may have a C function in the slot that calls the
2793 method from the dictionary, and we want to avoid infinite recursion
2794 here.) */
2795
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002796static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002797add_operators(PyTypeObject *type)
2798{
2799 PySequenceMethods *sq;
2800 PyMappingMethods *mp;
2801 PyNumberMethods *nb;
2802
2803#undef ADD
2804#define ADD(SLOT, TABLE) \
2805 if (SLOT) { \
2806 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2807 return -1; \
2808 }
2809
2810 if ((sq = type->tp_as_sequence) != NULL) {
2811 ADD(sq->sq_length, tab_len);
2812 ADD(sq->sq_concat, tab_concat);
2813 ADD(sq->sq_repeat, tab_mul_int);
2814 ADD(sq->sq_item, tab_getitem_int);
2815 ADD(sq->sq_slice, tab_getslice);
2816 ADD(sq->sq_ass_item, tab_setitem_int);
2817 ADD(sq->sq_ass_slice, tab_setslice);
2818 ADD(sq->sq_contains, tab_contains);
2819 ADD(sq->sq_inplace_concat, tab_iadd);
2820 ADD(sq->sq_inplace_repeat, tab_imul_int);
2821 }
2822
2823 if ((mp = type->tp_as_mapping) != NULL) {
2824 if (sq->sq_length == NULL)
2825 ADD(mp->mp_length, tab_len);
2826 ADD(mp->mp_subscript, tab_getitem);
2827 ADD(mp->mp_ass_subscript, tab_setitem);
2828 }
2829
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002830 if ((nb = type->tp_as_number) != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002831 ADD(nb->nb_add, tab_add);
2832 ADD(nb->nb_subtract, tab_sub);
2833 ADD(nb->nb_multiply, tab_mul);
2834 ADD(nb->nb_divide, tab_div);
2835 ADD(nb->nb_remainder, tab_mod);
2836 ADD(nb->nb_divmod, tab_divmod);
2837 ADD(nb->nb_power, tab_pow);
2838 ADD(nb->nb_negative, tab_neg);
2839 ADD(nb->nb_positive, tab_pos);
2840 ADD(nb->nb_absolute, tab_abs);
2841 ADD(nb->nb_nonzero, tab_nonzero);
2842 ADD(nb->nb_invert, tab_invert);
2843 ADD(nb->nb_lshift, tab_lshift);
2844 ADD(nb->nb_rshift, tab_rshift);
2845 ADD(nb->nb_and, tab_and);
2846 ADD(nb->nb_xor, tab_xor);
2847 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002848 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002849 ADD(nb->nb_int, tab_int);
2850 ADD(nb->nb_long, tab_long);
2851 ADD(nb->nb_float, tab_float);
2852 ADD(nb->nb_oct, tab_oct);
2853 ADD(nb->nb_hex, tab_hex);
2854 ADD(nb->nb_inplace_add, tab_iadd);
2855 ADD(nb->nb_inplace_subtract, tab_isub);
2856 ADD(nb->nb_inplace_multiply, tab_imul);
2857 ADD(nb->nb_inplace_divide, tab_idiv);
2858 ADD(nb->nb_inplace_remainder, tab_imod);
2859 ADD(nb->nb_inplace_power, tab_ipow);
2860 ADD(nb->nb_inplace_lshift, tab_ilshift);
2861 ADD(nb->nb_inplace_rshift, tab_irshift);
2862 ADD(nb->nb_inplace_and, tab_iand);
2863 ADD(nb->nb_inplace_xor, tab_ixor);
2864 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002865 if (type->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossum874f15a2001-09-25 21:16:33 +00002866 ADD(nb->nb_floor_divide, tab_floordiv);
2867 ADD(nb->nb_true_divide, tab_truediv);
2868 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2869 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2870 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002871 }
2872
2873 ADD(type->tp_getattro, tab_getattr);
2874 ADD(type->tp_setattro, tab_setattr);
2875 ADD(type->tp_compare, tab_cmp);
2876 ADD(type->tp_repr, tab_repr);
2877 ADD(type->tp_hash, tab_hash);
2878 ADD(type->tp_call, tab_call);
2879 ADD(type->tp_str, tab_str);
2880 ADD(type->tp_richcompare, tab_richcmp);
2881 ADD(type->tp_iter, tab_iter);
2882 ADD(type->tp_iternext, tab_next);
2883 ADD(type->tp_descr_get, tab_descr_get);
2884 ADD(type->tp_descr_set, tab_descr_set);
2885 ADD(type->tp_init, tab_init);
2886
Guido van Rossumf040ede2001-08-07 16:40:56 +00002887 if (type->tp_new != NULL) {
2888 if (add_tp_new_wrapper(type) < 0)
2889 return -1;
2890 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002891
2892 return 0;
2893}
2894
Guido van Rossumf040ede2001-08-07 16:40:56 +00002895/* Slot wrappers that call the corresponding __foo__ slot. See comments
2896 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002897
Guido van Rossumdc91b992001-08-08 22:26:22 +00002898#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002899static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002900FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002901{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002902 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002903 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002904}
2905
Guido van Rossumdc91b992001-08-08 22:26:22 +00002906#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002907static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002908FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002909{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002910 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002911 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002912}
2913
Guido van Rossumdc91b992001-08-08 22:26:22 +00002914
2915#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002916static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002917FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002918{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002919 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002920 int do_other = self->ob_type != other->ob_type && \
2921 other->ob_type->tp_as_number != NULL && \
2922 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002923 if (self->ob_type->tp_as_number != NULL && \
2924 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2925 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002926 if (do_other && \
2927 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2928 r = call_maybe( \
2929 other, ROPSTR, &rcache_str, "(O)", self); \
2930 if (r != Py_NotImplemented) \
2931 return r; \
2932 Py_DECREF(r); \
2933 do_other = 0; \
2934 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002935 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002936 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002937 if (r != Py_NotImplemented || \
2938 other->ob_type == self->ob_type) \
2939 return r; \
2940 Py_DECREF(r); \
2941 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002942 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002943 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002944 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002945 } \
2946 Py_INCREF(Py_NotImplemented); \
2947 return Py_NotImplemented; \
2948}
2949
2950#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2951 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2952
2953#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2954static PyObject * \
2955FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2956{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002957 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002958 return call_method(self, OPSTR, &cache_str, \
2959 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002960}
2961
2962static int
2963slot_sq_length(PyObject *self)
2964{
Guido van Rossum2730b132001-08-28 18:22:14 +00002965 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002966 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002967 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002968
2969 if (res == NULL)
2970 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002971 len = (int)PyInt_AsLong(res);
2972 Py_DECREF(res);
2973 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974}
2975
Guido van Rossumdc91b992001-08-08 22:26:22 +00002976SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2977SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002978
2979/* Super-optimized version of slot_sq_item.
2980 Other slots could do the same... */
2981static PyObject *
2982slot_sq_item(PyObject *self, int i)
2983{
2984 static PyObject *getitem_str;
2985 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2986 descrgetfunc f;
2987
2988 if (getitem_str == NULL) {
2989 getitem_str = PyString_InternFromString("__getitem__");
2990 if (getitem_str == NULL)
2991 return NULL;
2992 }
2993 func = _PyType_Lookup(self->ob_type, getitem_str);
2994 if (func != NULL) {
2995 if (func->ob_type == &PyWrapperDescr_Type) {
2996 PyWrapperDescrObject *wrapper =
2997 (PyWrapperDescrObject *)func;
2998 if (wrapper->d_base->wrapper == wrap_sq_item) {
2999 intargfunc f;
3000 f = (intargfunc)(wrapper->d_wrapped);
3001 return f(self, i);
3002 }
3003 }
3004 if ((f = func->ob_type->tp_descr_get) == NULL)
3005 Py_INCREF(func);
3006 else
3007 func = f(func, self, (PyObject *)(self->ob_type));
3008 ival = PyInt_FromLong(i);
3009 if (ival != NULL) {
3010 args = PyTuple_New(1);
3011 if (args != NULL) {
3012 PyTuple_SET_ITEM(args, 0, ival);
3013 retval = PyObject_Call(func, args, NULL);
3014 Py_XDECREF(args);
3015 Py_XDECREF(func);
3016 return retval;
3017 }
3018 }
3019 }
3020 else {
3021 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3022 }
3023 Py_XDECREF(args);
3024 Py_XDECREF(ival);
3025 Py_XDECREF(func);
3026 return NULL;
3027}
3028
Guido van Rossumdc91b992001-08-08 22:26:22 +00003029SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030
3031static int
3032slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3033{
3034 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003035 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003036
3037 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003038 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003039 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003041 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003042 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043 if (res == NULL)
3044 return -1;
3045 Py_DECREF(res);
3046 return 0;
3047}
3048
3049static int
3050slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3051{
3052 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003053 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054
3055 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003056 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003057 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003058 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003059 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003060 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003061 if (res == NULL)
3062 return -1;
3063 Py_DECREF(res);
3064 return 0;
3065}
3066
3067static int
3068slot_sq_contains(PyObject *self, PyObject *value)
3069{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003070 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003071 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003072
Guido van Rossum55f20992001-10-01 17:18:22 +00003073 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003074
3075 if (func != NULL) {
3076 args = Py_BuildValue("(O)", value);
3077 if (args == NULL)
3078 res = NULL;
3079 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003080 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003081 Py_DECREF(args);
3082 }
3083 Py_DECREF(func);
3084 if (res == NULL)
3085 return -1;
3086 return PyObject_IsTrue(res);
3087 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003088 else if (PyErr_Occurred())
3089 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003090 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003091 return _PySequence_IterSearch(self, value,
3092 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003093 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003094}
3095
Guido van Rossumdc91b992001-08-08 22:26:22 +00003096SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3097SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098
3099#define slot_mp_length slot_sq_length
3100
Guido van Rossumdc91b992001-08-08 22:26:22 +00003101SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003102
3103static int
3104slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3105{
3106 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003107 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003108
3109 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003110 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003111 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003113 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003114 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115 if (res == NULL)
3116 return -1;
3117 Py_DECREF(res);
3118 return 0;
3119}
3120
Guido van Rossumdc91b992001-08-08 22:26:22 +00003121SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3122SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3123SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3124SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3125SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3126SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3127
3128staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3129
3130SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3131 nb_power, "__pow__", "__rpow__")
3132
3133static PyObject *
3134slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3135{
Guido van Rossum2730b132001-08-28 18:22:14 +00003136 static PyObject *pow_str;
3137
Guido van Rossumdc91b992001-08-08 22:26:22 +00003138 if (modulus == Py_None)
3139 return slot_nb_power_binary(self, other);
3140 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003141 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003142 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003143}
3144
3145SLOT0(slot_nb_negative, "__neg__")
3146SLOT0(slot_nb_positive, "__pos__")
3147SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003148
3149static int
3150slot_nb_nonzero(PyObject *self)
3151{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003152 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003153 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003154
Guido van Rossum55f20992001-10-01 17:18:22 +00003155 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003156 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003157 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003158 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003159 func = lookup_maybe(self, "__len__", &len_str);
3160 if (func == NULL) {
3161 if (PyErr_Occurred())
3162 return -1;
3163 else
3164 return 1;
3165 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003166 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003167 res = PyObject_CallObject(func, NULL);
3168 Py_DECREF(func);
3169 if (res == NULL)
3170 return -1;
3171 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003172}
3173
Guido van Rossumdc91b992001-08-08 22:26:22 +00003174SLOT0(slot_nb_invert, "__invert__")
3175SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3176SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3177SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3178SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3179SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003180
3181static int
3182slot_nb_coerce(PyObject **a, PyObject **b)
3183{
3184 static PyObject *coerce_str;
3185 PyObject *self = *a, *other = *b;
3186
3187 if (self->ob_type->tp_as_number != NULL &&
3188 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3189 PyObject *r;
3190 r = call_maybe(
3191 self, "__coerce__", &coerce_str, "(O)", other);
3192 if (r == NULL)
3193 return -1;
3194 if (r == Py_NotImplemented) {
3195 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003196 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003197 else {
3198 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3199 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003200 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003201 Py_DECREF(r);
3202 return -1;
3203 }
3204 *a = PyTuple_GET_ITEM(r, 0);
3205 Py_INCREF(*a);
3206 *b = PyTuple_GET_ITEM(r, 1);
3207 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003208 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003209 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003210 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003211 }
3212 if (other->ob_type->tp_as_number != NULL &&
3213 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3214 PyObject *r;
3215 r = call_maybe(
3216 other, "__coerce__", &coerce_str, "(O)", self);
3217 if (r == NULL)
3218 return -1;
3219 if (r == Py_NotImplemented) {
3220 Py_DECREF(r);
3221 return 1;
3222 }
3223 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3224 PyErr_SetString(PyExc_TypeError,
3225 "__coerce__ didn't return a 2-tuple");
3226 Py_DECREF(r);
3227 return -1;
3228 }
3229 *a = PyTuple_GET_ITEM(r, 1);
3230 Py_INCREF(*a);
3231 *b = PyTuple_GET_ITEM(r, 0);
3232 Py_INCREF(*b);
3233 Py_DECREF(r);
3234 return 0;
3235 }
3236 return 1;
3237}
3238
Guido van Rossumdc91b992001-08-08 22:26:22 +00003239SLOT0(slot_nb_int, "__int__")
3240SLOT0(slot_nb_long, "__long__")
3241SLOT0(slot_nb_float, "__float__")
3242SLOT0(slot_nb_oct, "__oct__")
3243SLOT0(slot_nb_hex, "__hex__")
3244SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3245SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3246SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3247SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3248SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3249SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3250SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3251SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3252SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3253SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3254SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3255SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3256 "__floordiv__", "__rfloordiv__")
3257SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3258SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3259SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003260
3261static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003262half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003263{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003264 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003265 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003266 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003267
Guido van Rossum60718732001-08-28 17:47:51 +00003268 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003269 if (func == NULL) {
3270 PyErr_Clear();
3271 }
3272 else {
3273 args = Py_BuildValue("(O)", other);
3274 if (args == NULL)
3275 res = NULL;
3276 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003277 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003278 Py_DECREF(args);
3279 }
3280 if (res != Py_NotImplemented) {
3281 if (res == NULL)
3282 return -2;
3283 c = PyInt_AsLong(res);
3284 Py_DECREF(res);
3285 if (c == -1 && PyErr_Occurred())
3286 return -2;
3287 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3288 }
3289 Py_DECREF(res);
3290 }
3291 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003292}
3293
Guido van Rossumab3b0342001-09-18 20:38:53 +00003294/* This slot is published for the benefit of try_3way_compare in object.c */
3295int
3296_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003297{
3298 int c;
3299
Guido van Rossumab3b0342001-09-18 20:38:53 +00003300 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003301 c = half_compare(self, other);
3302 if (c <= 1)
3303 return c;
3304 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003305 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003306 c = half_compare(other, self);
3307 if (c < -1)
3308 return -2;
3309 if (c <= 1)
3310 return -c;
3311 }
3312 return (void *)self < (void *)other ? -1 :
3313 (void *)self > (void *)other ? 1 : 0;
3314}
3315
3316static PyObject *
3317slot_tp_repr(PyObject *self)
3318{
3319 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003320 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003321
Guido van Rossum60718732001-08-28 17:47:51 +00003322 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003323 if (func != NULL) {
3324 res = PyEval_CallObject(func, NULL);
3325 Py_DECREF(func);
3326 return res;
3327 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003328 PyErr_Clear();
3329 return PyString_FromFormat("<%s object at %p>",
3330 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003331}
3332
3333static PyObject *
3334slot_tp_str(PyObject *self)
3335{
3336 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003337 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003338
Guido van Rossum60718732001-08-28 17:47:51 +00003339 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003340 if (func != NULL) {
3341 res = PyEval_CallObject(func, NULL);
3342 Py_DECREF(func);
3343 return res;
3344 }
3345 else {
3346 PyErr_Clear();
3347 return slot_tp_repr(self);
3348 }
3349}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003350
3351static long
3352slot_tp_hash(PyObject *self)
3353{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003354 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003355 static PyObject *hash_str, *eq_str, *cmp_str;
3356
Tim Peters6d6c1a32001-08-02 04:15:00 +00003357 long h;
3358
Guido van Rossum60718732001-08-28 17:47:51 +00003359 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003360
3361 if (func != NULL) {
3362 res = PyEval_CallObject(func, NULL);
3363 Py_DECREF(func);
3364 if (res == NULL)
3365 return -1;
3366 h = PyInt_AsLong(res);
3367 }
3368 else {
3369 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003370 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003371 if (func == NULL) {
3372 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003373 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003374 }
3375 if (func != NULL) {
3376 Py_DECREF(func);
3377 PyErr_SetString(PyExc_TypeError, "unhashable type");
3378 return -1;
3379 }
3380 PyErr_Clear();
3381 h = _Py_HashPointer((void *)self);
3382 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003383 if (h == -1 && !PyErr_Occurred())
3384 h = -2;
3385 return h;
3386}
3387
3388static PyObject *
3389slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3390{
Guido van Rossum60718732001-08-28 17:47:51 +00003391 static PyObject *call_str;
3392 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393 PyObject *res;
3394
3395 if (meth == NULL)
3396 return NULL;
3397 res = PyObject_Call(meth, args, kwds);
3398 Py_DECREF(meth);
3399 return res;
3400}
3401
Tim Peters6d6c1a32001-08-02 04:15:00 +00003402static PyObject *
3403slot_tp_getattro(PyObject *self, PyObject *name)
3404{
3405 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003406 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003407 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003408
Guido van Rossum8e248182001-08-12 05:17:56 +00003409 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003410 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003411 if (getattr_str == NULL)
3412 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003414 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003415 if (getattr == NULL) {
3416 /* Avoid further slowdowns */
3417 if (tp->tp_getattro == slot_tp_getattro)
3418 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003419 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003420 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003421 return PyObject_CallFunction(getattr, "OO", self, name);
3422}
3423
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003424static PyObject *
3425slot_tp_getattr_hook(PyObject *self, PyObject *name)
3426{
3427 PyTypeObject *tp = self->ob_type;
3428 PyObject *getattr, *getattribute, *res;
3429 static PyObject *getattribute_str = NULL;
3430 static PyObject *getattr_str = NULL;
3431
3432 if (getattr_str == NULL) {
3433 getattr_str = PyString_InternFromString("__getattr__");
3434 if (getattr_str == NULL)
3435 return NULL;
3436 }
3437 if (getattribute_str == NULL) {
3438 getattribute_str =
3439 PyString_InternFromString("__getattribute__");
3440 if (getattribute_str == NULL)
3441 return NULL;
3442 }
3443 getattr = _PyType_Lookup(tp, getattr_str);
3444 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003445 if (getattribute != NULL &&
3446 getattribute->ob_type == &PyWrapperDescr_Type &&
3447 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3448 PyObject_GenericGetAttr)
3449 getattribute = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003450 if (getattr == NULL && getattribute == NULL) {
3451 /* Avoid further slowdowns */
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003452 /* XXX This is questionable: it means that a class that
3453 isn't born with __getattr__ or __getattribute__ cannot
3454 acquire them in later life. But it's a relatively big
3455 speedup, so I'm keeping it in for now. If this is
3456 removed, you can also remove the "def __getattr__" from
3457 class C (marked with another XXX comment) in dynamics()
3458 in Lib/test/test_descr.py. */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003459 if (tp->tp_getattro == slot_tp_getattr_hook)
3460 tp->tp_getattro = PyObject_GenericGetAttr;
3461 return PyObject_GenericGetAttr(self, name);
3462 }
3463 if (getattribute == NULL)
3464 res = PyObject_GenericGetAttr(self, name);
3465 else
3466 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003467 if (getattr != NULL &&
3468 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003469 PyErr_Clear();
3470 res = PyObject_CallFunction(getattr, "OO", self, name);
3471 }
3472 return res;
3473}
3474
Tim Peters6d6c1a32001-08-02 04:15:00 +00003475static int
3476slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3477{
3478 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003479 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480
3481 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003482 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003483 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003484 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003485 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003486 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003487 if (res == NULL)
3488 return -1;
3489 Py_DECREF(res);
3490 return 0;
3491}
3492
3493/* Map rich comparison operators to their __xx__ namesakes */
3494static char *name_op[] = {
3495 "__lt__",
3496 "__le__",
3497 "__eq__",
3498 "__ne__",
3499 "__gt__",
3500 "__ge__",
3501};
3502
3503static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003504half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003505{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003506 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003507 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003508
Guido van Rossum60718732001-08-28 17:47:51 +00003509 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003510 if (func == NULL) {
3511 PyErr_Clear();
3512 Py_INCREF(Py_NotImplemented);
3513 return Py_NotImplemented;
3514 }
3515 args = Py_BuildValue("(O)", other);
3516 if (args == NULL)
3517 res = NULL;
3518 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003519 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003520 Py_DECREF(args);
3521 }
3522 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003523 return res;
3524}
3525
Guido van Rossumb8f63662001-08-15 23:57:02 +00003526/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3527static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3528
3529static PyObject *
3530slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3531{
3532 PyObject *res;
3533
3534 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3535 res = half_richcompare(self, other, op);
3536 if (res != Py_NotImplemented)
3537 return res;
3538 Py_DECREF(res);
3539 }
3540 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3541 res = half_richcompare(other, self, swapped_op[op]);
3542 if (res != Py_NotImplemented) {
3543 return res;
3544 }
3545 Py_DECREF(res);
3546 }
3547 Py_INCREF(Py_NotImplemented);
3548 return Py_NotImplemented;
3549}
3550
3551static PyObject *
3552slot_tp_iter(PyObject *self)
3553{
3554 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003555 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003556
Guido van Rossum60718732001-08-28 17:47:51 +00003557 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003558 if (func != NULL) {
3559 res = PyObject_CallObject(func, NULL);
3560 Py_DECREF(func);
3561 return res;
3562 }
3563 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003564 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003565 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003566 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003567 return NULL;
3568 }
3569 Py_DECREF(func);
3570 return PySeqIter_New(self);
3571}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003572
3573static PyObject *
3574slot_tp_iternext(PyObject *self)
3575{
Guido van Rossum2730b132001-08-28 18:22:14 +00003576 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003577 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003578}
3579
Guido van Rossum1a493502001-08-17 16:47:50 +00003580static PyObject *
3581slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3582{
3583 PyTypeObject *tp = self->ob_type;
3584 PyObject *get;
3585 static PyObject *get_str = NULL;
3586
3587 if (get_str == NULL) {
3588 get_str = PyString_InternFromString("__get__");
3589 if (get_str == NULL)
3590 return NULL;
3591 }
3592 get = _PyType_Lookup(tp, get_str);
3593 if (get == NULL) {
3594 /* Avoid further slowdowns */
3595 if (tp->tp_descr_get == slot_tp_descr_get)
3596 tp->tp_descr_get = NULL;
3597 Py_INCREF(self);
3598 return self;
3599 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003600 if (obj == NULL)
3601 obj = Py_None;
3602 if (type == NULL)
3603 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003604 return PyObject_CallFunction(get, "OOO", self, obj, type);
3605}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003606
3607static int
3608slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3609{
Guido van Rossum2c252392001-08-24 10:13:31 +00003610 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003611 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003612
3613 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003614 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003615 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003616 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003617 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003618 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003619 if (res == NULL)
3620 return -1;
3621 Py_DECREF(res);
3622 return 0;
3623}
3624
3625static int
3626slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3627{
Guido van Rossum60718732001-08-28 17:47:51 +00003628 static PyObject *init_str;
3629 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630 PyObject *res;
3631
3632 if (meth == NULL)
3633 return -1;
3634 res = PyObject_Call(meth, args, kwds);
3635 Py_DECREF(meth);
3636 if (res == NULL)
3637 return -1;
3638 Py_DECREF(res);
3639 return 0;
3640}
3641
3642static PyObject *
3643slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3644{
3645 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3646 PyObject *newargs, *x;
3647 int i, n;
3648
3649 if (func == NULL)
3650 return NULL;
3651 assert(PyTuple_Check(args));
3652 n = PyTuple_GET_SIZE(args);
3653 newargs = PyTuple_New(n+1);
3654 if (newargs == NULL)
3655 return NULL;
3656 Py_INCREF(type);
3657 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3658 for (i = 0; i < n; i++) {
3659 x = PyTuple_GET_ITEM(args, i);
3660 Py_INCREF(x);
3661 PyTuple_SET_ITEM(newargs, i+1, x);
3662 }
3663 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003664 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003665 Py_DECREF(func);
3666 return x;
3667}
3668
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003669
3670/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3671 functions. The offsets here are relative to the 'etype' structure, which
3672 incorporates the additional structures used for numbers, sequences and
3673 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3674 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3675 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3676
3677typedef struct {
3678 char *name;
3679 int offset;
3680 void *function;
3681 wrapperfunc wrapper;
3682} slotdef;
3683
3684#undef TPSLOT
3685#undef ETSLOT
3686#undef SQSLOT
3687#undef MPSLOT
3688#undef NBSLOT
3689#undef BINSLOT
3690#undef RBINSLOT
3691
3692#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3693 {NAME, offsetof(PyTypeObject, SLOT), FUNCTION, WRAPPER}
3694#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3695 {NAME, offsetof(etype, SLOT), FUNCTION, WRAPPER}
3696#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3697 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER)
3698#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3699 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER)
3700#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3701 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER)
3702#define BINSLOT(NAME, SLOT, FUNCTION) \
3703 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l)
3704#define RBINSLOT(NAME, SLOT, FUNCTION) \
3705 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r)
3706
3707static slotdef slotdefs[] = {
3708 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry),
3709 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc),
3710 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3711 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3712 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item),
3713 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc),
3714 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem),
3715 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem),
3716 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
3717 wrap_intintobjargproc),
3718 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice),
3719 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc),
3720 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
3721 wrap_binaryfunc),
3722 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
3723 wrap_intargfunc),
3724
3725 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry),
3726 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript, wrap_sq_item),
3727 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
3728 wrap_objobjargproc),
3729 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
3730 wrap_delitem),
3731
3732 BINSLOT("__add__", nb_add, slot_nb_add),
3733 RBINSLOT("__radd__", nb_add, slot_nb_add),
3734 BINSLOT("__sub__", nb_subtract, slot_nb_subtract),
3735 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract),
3736 BINSLOT("__mul__", nb_multiply, slot_nb_multiply),
3737 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply),
3738 BINSLOT("__div__", nb_divide, slot_nb_divide),
3739 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide),
3740 BINSLOT("__mod__", nb_remainder, slot_nb_remainder),
3741 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder),
3742 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod),
3743 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod),
3744 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc),
3745 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r),
3746 NBSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc),
3747 NBSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc),
3748 NBSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc),
3749 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_unaryfunc),
3750 NBSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc),
3751 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift),
3752 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift),
3753 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift),
3754 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift),
3755 BINSLOT("__and__", nb_and, slot_nb_and),
3756 RBINSLOT("__rand__", nb_and, slot_nb_and),
3757 BINSLOT("__xor__", nb_xor, slot_nb_xor),
3758 RBINSLOT("__rxor__", nb_xor, slot_nb_xor),
3759 BINSLOT("__or__", nb_or, slot_nb_or),
3760 RBINSLOT("__ror__", nb_or, slot_nb_or),
3761 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc),
3762 NBSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc),
3763 NBSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc),
3764 NBSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc),
3765 NBSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc),
3766 NBSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc),
3767 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3768 wrap_binaryfunc),
3769 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3770 wrap_binaryfunc),
3771 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3772 wrap_binaryfunc),
3773 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3774 wrap_binaryfunc),
3775 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3776 wrap_binaryfunc),
3777 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3778 wrap_ternaryfunc),
3779 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3780 wrap_binaryfunc),
3781 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3782 wrap_binaryfunc),
3783 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3784 wrap_binaryfunc),
3785 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3786 wrap_binaryfunc),
3787 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3788 wrap_binaryfunc),
3789 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide),
3790 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide),
3791 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide),
3792 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide),
3793 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3794 slot_nb_inplace_floor_divide, wrap_binaryfunc),
3795 NBSLOT("__itruediv__", nb_inplace_true_divide,
3796 slot_nb_inplace_true_divide, wrap_binaryfunc),
3797
3798 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc),
3799 TPSLOT("__str__", tp_print, NULL, NULL),
3800 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc),
3801 TPSLOT("__repr__", tp_print, NULL, NULL),
3802 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc),
3803 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc),
3804 TPSLOT("__call__", tp_call, slot_tp_call, wrap_call),
3805 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro,
3806 wrap_binaryfunc),
3807 TPSLOT("__getattribute__", tp_getattr, NULL, NULL),
3808 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL),
3809 TPSLOT("__getattr__", tp_getattr, NULL, NULL),
3810 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr),
3811 TPSLOT("__setattr__", tp_setattr, NULL, NULL),
3812 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr),
3813 TPSLOT("__delattr__", tp_setattr, NULL, NULL),
3814 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt),
3815 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le),
3816 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq),
3817 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne),
3818 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt),
3819 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge),
3820 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc),
3821 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next),
3822 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get),
3823 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set),
3824 TPSLOT("__init__", tp_init, slot_tp_init, wrap_init),
3825 TPSLOT("__new__", tp_new, slot_tp_new, NULL),
3826 {NULL}
3827};
3828
3829static int
3830update_slot(PyTypeObject *type, PyObject *name, PyObject *value)
3831{
3832 char *s;
3833 int n;
3834 slotdef *p;
3835 void **ptr;
3836
3837 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
3838 if (value == NULL)
3839 return 0; /* Can't unset a slot */
3840 s = PyString_AsString(name);
3841 n = PyString_Size(name);
3842 if (s == NULL || n < 0) {
3843 /* Shouldn't happen, but can't be bothered */
3844 PyErr_Clear();
3845 return 0;
3846 }
3847 if (!(s[0] == '_' && s[1] == '_' && s[n-1] == '_' && s[n-2] == '_'))
3848 return 0;
3849 for (p = slotdefs; p->name; p++) {
3850 if (!strcmp(p->name, s)) {
3851 ptr = (void **) ((char *)type + p->offset);
3852 *ptr = p->function;
3853 }
3854 }
3855 return 0;
3856}
3857
3858static void **
3859slotptr(PyTypeObject *type, int offset)
3860{
3861 char *ptr;
3862
3863 assert(offset >= 0);
3864 assert(offset < offsetof(etype, as_buffer));
3865 if (offset >= offsetof(etype, as_mapping)) {
3866 ptr = (void *)type->tp_as_mapping;
3867 offset -= offsetof(etype, as_mapping);
3868 }
3869 else if (offset >= offsetof(etype, as_sequence)) {
3870 ptr = (void *)type->tp_as_sequence;
3871 offset -= offsetof(etype, as_sequence);
3872 }
3873 else if (offset >= offsetof(etype, as_number)) {
3874 ptr = (void *)type->tp_as_number;
3875 offset -= offsetof(etype, as_number);
3876 }
3877 else {
3878 ptr = (void *)type;
3879 }
3880 if (ptr != NULL)
3881 ptr += offset;
3882 return (void **)ptr;
3883}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003884
Tim Peters6d6c1a32001-08-02 04:15:00 +00003885static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003886fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003887{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003888 slotdef *p;
3889 PyObject *mro, *descr;
3890 PyTypeObject *base;
3891 PyWrapperDescrObject *d;
3892 int i, n;
3893 void **ptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003895 for (p = slotdefs; p->name; p++) {
3896 ptr = slotptr(type, p->offset);
3897 if (ptr)
3898 *ptr = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003899 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003900 mro = type->tp_mro;
3901 assert(PyTuple_Check(mro));
3902 n = PyTuple_GET_SIZE(mro);
3903 for (p = slotdefs; p->name; p++) {
3904 for (i = 0; i < n; i++) {
3905 base = (PyTypeObject *)PyTuple_GET_ITEM(mro, i);
3906 assert(PyType_Check(base));
3907 descr = PyDict_GetItemString(
3908 base->tp_defined, p->name);
3909 if (descr == NULL)
3910 continue;
3911 ptr = slotptr(type, p->offset);
3912 if (ptr == NULL)
3913 continue;
3914 if (descr->ob_type == &PyWrapperDescr_Type) {
3915 d = (PyWrapperDescrObject *)descr;
3916 if (d->d_base->wrapper == p->wrapper) {
3917 if (*ptr == NULL) {
3918 *ptr = d->d_wrapped;
3919 continue;
3920 }
3921 if (p->wrapper == wrap_binaryfunc_r)
3922 continue;
3923 }
3924 }
3925 *ptr = p->function;
3926 break;
3927 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003928 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003929}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003930
3931
3932/* Cooperative 'super' */
3933
3934typedef struct {
3935 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003936 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003937 PyObject *obj;
3938} superobject;
3939
Guido van Rossum6f799372001-09-20 20:46:19 +00003940static PyMemberDef super_members[] = {
3941 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3942 "the class invoking super()"},
3943 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3944 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003945 {0}
3946};
3947
Guido van Rossum705f0f52001-08-24 16:47:00 +00003948static void
3949super_dealloc(PyObject *self)
3950{
3951 superobject *su = (superobject *)self;
3952
Guido van Rossum048eb752001-10-02 21:24:57 +00003953 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003954 Py_XDECREF(su->obj);
3955 Py_XDECREF(su->type);
3956 self->ob_type->tp_free(self);
3957}
3958
3959static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003960super_repr(PyObject *self)
3961{
3962 superobject *su = (superobject *)self;
3963
3964 if (su->obj)
3965 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003966 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003967 su->type ? su->type->tp_name : "NULL",
3968 su->obj->ob_type->tp_name);
3969 else
3970 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003971 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003972 su->type ? su->type->tp_name : "NULL");
3973}
3974
3975static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003976super_getattro(PyObject *self, PyObject *name)
3977{
3978 superobject *su = (superobject *)self;
3979
3980 if (su->obj != NULL) {
3981 PyObject *mro, *res, *tmp;
3982 descrgetfunc f;
3983 int i, n;
3984
Guido van Rossume705ef12001-08-29 15:47:06 +00003985 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003986 if (mro == NULL)
3987 n = 0;
3988 else {
3989 assert(PyTuple_Check(mro));
3990 n = PyTuple_GET_SIZE(mro);
3991 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003992 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003993 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003994 break;
3995 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003996 if (i >= n && PyType_Check(su->obj)) {
3997 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003998 if (mro == NULL)
3999 n = 0;
4000 else {
4001 assert(PyTuple_Check(mro));
4002 n = PyTuple_GET_SIZE(mro);
4003 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004004 for (i = 0; i < n; i++) {
4005 if ((PyObject *)(su->type) ==
4006 PyTuple_GET_ITEM(mro, i))
4007 break;
4008 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004009 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004010 i++;
4011 res = NULL;
4012 for (; i < n; i++) {
4013 tmp = PyTuple_GET_ITEM(mro, i);
4014 assert(PyType_Check(tmp));
4015 res = PyDict_GetItem(
4016 ((PyTypeObject *)tmp)->tp_defined, name);
4017 if (res != NULL) {
4018 Py_INCREF(res);
4019 f = res->ob_type->tp_descr_get;
4020 if (f != NULL) {
4021 tmp = f(res, su->obj, res);
4022 Py_DECREF(res);
4023 res = tmp;
4024 }
4025 return res;
4026 }
4027 }
4028 }
4029 return PyObject_GenericGetAttr(self, name);
4030}
4031
4032static PyObject *
4033super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4034{
4035 superobject *su = (superobject *)self;
4036 superobject *new;
4037
4038 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4039 /* Not binding to an object, or already bound */
4040 Py_INCREF(self);
4041 return self;
4042 }
4043 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
4044 if (new == NULL)
4045 return NULL;
4046 Py_INCREF(su->type);
4047 Py_INCREF(obj);
4048 new->type = su->type;
4049 new->obj = obj;
4050 return (PyObject *)new;
4051}
4052
4053static int
4054super_init(PyObject *self, PyObject *args, PyObject *kwds)
4055{
4056 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004057 PyTypeObject *type;
4058 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004059
4060 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4061 return -1;
4062 if (obj == Py_None)
4063 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00004064 if (obj != NULL &&
4065 !PyType_IsSubtype(obj->ob_type, type) &&
4066 !(PyType_Check(obj) &&
4067 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004068 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00004069 "super(type, obj): "
4070 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004071 return -1;
4072 }
4073 Py_INCREF(type);
4074 Py_XINCREF(obj);
4075 su->type = type;
4076 su->obj = obj;
4077 return 0;
4078}
4079
4080static char super_doc[] =
4081"super(type) -> unbound super object\n"
4082"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004083"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004084"Typical use to call a cooperative superclass method:\n"
4085"class C(B):\n"
4086" def meth(self, arg):\n"
4087" super(C, self).meth(arg)";
4088
Guido van Rossum048eb752001-10-02 21:24:57 +00004089static int
4090super_traverse(PyObject *self, visitproc visit, void *arg)
4091{
4092 superobject *su = (superobject *)self;
4093 int err;
4094
4095#define VISIT(SLOT) \
4096 if (SLOT) { \
4097 err = visit((PyObject *)(SLOT), arg); \
4098 if (err) \
4099 return err; \
4100 }
4101
4102 VISIT(su->obj);
4103 VISIT(su->type);
4104
4105#undef VISIT
4106
4107 return 0;
4108}
4109
Guido van Rossum705f0f52001-08-24 16:47:00 +00004110PyTypeObject PySuper_Type = {
4111 PyObject_HEAD_INIT(&PyType_Type)
4112 0, /* ob_size */
4113 "super", /* tp_name */
4114 sizeof(superobject), /* tp_basicsize */
4115 0, /* tp_itemsize */
4116 /* methods */
4117 super_dealloc, /* tp_dealloc */
4118 0, /* tp_print */
4119 0, /* tp_getattr */
4120 0, /* tp_setattr */
4121 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004122 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004123 0, /* tp_as_number */
4124 0, /* tp_as_sequence */
4125 0, /* tp_as_mapping */
4126 0, /* tp_hash */
4127 0, /* tp_call */
4128 0, /* tp_str */
4129 super_getattro, /* tp_getattro */
4130 0, /* tp_setattro */
4131 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004132 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4133 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004134 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004135 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004136 0, /* tp_clear */
4137 0, /* tp_richcompare */
4138 0, /* tp_weaklistoffset */
4139 0, /* tp_iter */
4140 0, /* tp_iternext */
4141 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004142 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004143 0, /* tp_getset */
4144 0, /* tp_base */
4145 0, /* tp_dict */
4146 super_descr_get, /* tp_descr_get */
4147 0, /* tp_descr_set */
4148 0, /* tp_dictoffset */
4149 super_init, /* tp_init */
4150 PyType_GenericAlloc, /* tp_alloc */
4151 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004152 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004153};