blob: 66eecec6d167f62e206afa751a3d20bc372a7b7a [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__");
Guido van Rossum687ae002001-10-15 22:03:32 +000047 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000048 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{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000059 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000060 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 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000081}
82
Guido van Rossum32d34c82001-09-20 21:45:26 +000083PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000084 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +000085 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000086 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 {0}
88};
89
Martin v. Löwis0163d6d2001-06-09 07:34:05 +000090static int
91type_compare(PyObject *v, PyObject *w)
92{
93 /* This is called with type objects only. So we
94 can just compare the addresses. */
95 Py_uintptr_t vv = (Py_uintptr_t)v;
96 Py_uintptr_t ww = (Py_uintptr_t)w;
97 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
98}
99
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000100static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000101type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000102{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000103 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000104 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000105
106 mod = type_module(type, NULL);
107 if (mod == NULL)
108 PyErr_Clear();
109 else if (!PyString_Check(mod)) {
110 Py_DECREF(mod);
111 mod = NULL;
112 }
113 name = type_name(type, NULL);
114 if (name == NULL)
115 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000116
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000117 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
118 kind = "class";
119 else
120 kind = "type";
121
Barry Warsaw7ce36942001-08-24 18:34:26 +0000122 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000123 rtn = PyString_FromFormat("<%s '%s.%s'>",
124 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000125 PyString_AS_STRING(mod),
126 PyString_AS_STRING(name));
127 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000128 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000129 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000130
Guido van Rossumc3542212001-08-16 09:18:56 +0000131 Py_XDECREF(mod);
132 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000133 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000134}
135
Tim Peters6d6c1a32001-08-02 04:15:00 +0000136static PyObject *
137type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
138{
139 PyObject *obj;
140
141 if (type->tp_new == NULL) {
142 PyErr_Format(PyExc_TypeError,
143 "cannot create '%.100s' instances",
144 type->tp_name);
145 return NULL;
146 }
147
Tim Peters3f996e72001-09-13 19:18:27 +0000148 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000149 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000150 /* Ugly exception: when the call was type(something),
151 don't call tp_init on the result. */
152 if (type == &PyType_Type &&
153 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
154 (kwds == NULL ||
155 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
156 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000157 type = obj->ob_type;
158 if (type->tp_init != NULL &&
159 type->tp_init(obj, args, kwds) < 0) {
160 Py_DECREF(obj);
161 obj = NULL;
162 }
163 }
164 return obj;
165}
166
167PyObject *
168PyType_GenericAlloc(PyTypeObject *type, int nitems)
169{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000170 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000171 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000172
173 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000174 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000175 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000176 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000177
Neil Schemenauerc806c882001-08-29 23:54:54 +0000178 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000180
Neil Schemenauerc806c882001-08-29 23:54:54 +0000181 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000182
Tim Peters6d6c1a32001-08-02 04:15:00 +0000183 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
184 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000185
Tim Peters6d6c1a32001-08-02 04:15:00 +0000186 if (type->tp_itemsize == 0)
187 PyObject_INIT(obj, type);
188 else
189 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000190
Tim Peters6d6c1a32001-08-02 04:15:00 +0000191 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000192 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000193 return obj;
194}
195
196PyObject *
197PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
198{
199 return type->tp_alloc(type, 0);
200}
201
Guido van Rossum9475a232001-10-05 20:51:39 +0000202/* Helpers for subtyping */
203
204static int
205subtype_traverse(PyObject *self, visitproc visit, void *arg)
206{
207 PyTypeObject *type, *base;
208 traverseproc f;
209 int err;
210
211 /* Find the nearest base with a different tp_traverse */
212 type = self->ob_type;
213 base = type->tp_base;
214 while ((f = base->tp_traverse) == subtype_traverse) {
215 base = base->tp_base;
216 assert(base);
217 }
218
219 if (type->tp_dictoffset != base->tp_dictoffset) {
220 PyObject **dictptr = _PyObject_GetDictPtr(self);
221 if (dictptr && *dictptr) {
222 err = visit(*dictptr, arg);
223 if (err)
224 return err;
225 }
226 }
227
228 if (f)
229 return f(self, visit, arg);
230 return 0;
231}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000232
233static void
234subtype_dealloc(PyObject *self)
235{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000236 PyTypeObject *type, *base;
237 destructor f;
238
239 /* This exists so we can DECREF self->ob_type */
240
241 /* Find the nearest base with a different tp_dealloc */
242 type = self->ob_type;
243 base = type->tp_base;
244 while ((f = base->tp_dealloc) == subtype_dealloc) {
245 base = base->tp_base;
246 assert(base);
247 }
248
249 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000250 if (type->tp_dictoffset && !base->tp_dictoffset) {
251 PyObject **dictptr = _PyObject_GetDictPtr(self);
252 if (dictptr != NULL) {
253 PyObject *dict = *dictptr;
254 if (dict != NULL) {
255 Py_DECREF(dict);
256 *dictptr = NULL;
257 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000258 }
259 }
260
Guido van Rossum9676b222001-08-17 20:32:36 +0000261 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000262 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000263 PyObject_ClearWeakRefs(self);
264
Tim Peters6d6c1a32001-08-02 04:15:00 +0000265 /* Finalize GC if the base doesn't do GC and we do */
266 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000267 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000268
269 /* Call the base tp_dealloc() */
270 assert(f);
271 f(self);
272
273 /* Can't reference self beyond this point */
274 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
275 Py_DECREF(type);
276 }
277}
278
Tim Peters6d6c1a32001-08-02 04:15:00 +0000279staticforward PyTypeObject *solid_base(PyTypeObject *type);
280
281typedef struct {
282 PyTypeObject type;
283 PyNumberMethods as_number;
284 PySequenceMethods as_sequence;
285 PyMappingMethods as_mapping;
286 PyBufferProcs as_buffer;
287 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000288 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000289} etype;
290
291/* type test with subclassing support */
292
293int
294PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
295{
296 PyObject *mro;
297
Guido van Rossum9478d072001-09-07 18:52:13 +0000298 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
299 return b == a || b == &PyBaseObject_Type;
300
Tim Peters6d6c1a32001-08-02 04:15:00 +0000301 mro = a->tp_mro;
302 if (mro != NULL) {
303 /* Deal with multiple inheritance without recursion
304 by walking the MRO tuple */
305 int i, n;
306 assert(PyTuple_Check(mro));
307 n = PyTuple_GET_SIZE(mro);
308 for (i = 0; i < n; i++) {
309 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
310 return 1;
311 }
312 return 0;
313 }
314 else {
315 /* a is not completely initilized yet; follow tp_base */
316 do {
317 if (a == b)
318 return 1;
319 a = a->tp_base;
320 } while (a != NULL);
321 return b == &PyBaseObject_Type;
322 }
323}
324
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000325/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000326 without looking in the instance dictionary
327 (so we can't use PyObject_GetAttr) but still binding
328 it to the instance. The arguments are the object,
329 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000330 static variable used to cache the interned Python string.
331
332 Two variants:
333
334 - lookup_maybe() returns NULL without raising an exception
335 when the _PyType_Lookup() call fails;
336
337 - lookup_method() always raises an exception upon errors.
338*/
Guido van Rossum60718732001-08-28 17:47:51 +0000339
340static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000341lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000342{
343 PyObject *res;
344
345 if (*attrobj == NULL) {
346 *attrobj = PyString_InternFromString(attrstr);
347 if (*attrobj == NULL)
348 return NULL;
349 }
350 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000351 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000352 descrgetfunc f;
353 if ((f = res->ob_type->tp_descr_get) == NULL)
354 Py_INCREF(res);
355 else
356 res = f(res, self, (PyObject *)(self->ob_type));
357 }
358 return res;
359}
360
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000361static PyObject *
362lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
363{
364 PyObject *res = lookup_maybe(self, attrstr, attrobj);
365 if (res == NULL && !PyErr_Occurred())
366 PyErr_SetObject(PyExc_AttributeError, *attrobj);
367 return res;
368}
369
Guido van Rossum2730b132001-08-28 18:22:14 +0000370/* A variation of PyObject_CallMethod that uses lookup_method()
371 instead of PyObject_GetAttrString(). This uses the same convention
372 as lookup_method to cache the interned name string object. */
373
374PyObject *
375call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
376{
377 va_list va;
378 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000379 va_start(va, format);
380
Guido van Rossumda21c012001-10-03 00:50:18 +0000381 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000382 if (func == NULL) {
383 va_end(va);
384 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000385 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000386 return NULL;
387 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000388
389 if (format && *format)
390 args = Py_VaBuildValue(format, va);
391 else
392 args = PyTuple_New(0);
393
394 va_end(va);
395
396 if (args == NULL)
397 return NULL;
398
399 assert(PyTuple_Check(args));
400 retval = PyObject_Call(func, args, NULL);
401
402 Py_DECREF(args);
403 Py_DECREF(func);
404
405 return retval;
406}
407
408/* Clone of call_method() that returns NotImplemented when the lookup fails. */
409
410PyObject *
411call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
412{
413 va_list va;
414 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000415 va_start(va, format);
416
Guido van Rossumda21c012001-10-03 00:50:18 +0000417 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000418 if (func == NULL) {
419 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000420 if (!PyErr_Occurred()) {
421 Py_INCREF(Py_NotImplemented);
422 return Py_NotImplemented;
423 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000424 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000425 }
426
427 if (format && *format)
428 args = Py_VaBuildValue(format, va);
429 else
430 args = PyTuple_New(0);
431
432 va_end(va);
433
Guido van Rossum717ce002001-09-14 16:58:08 +0000434 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000435 return NULL;
436
Guido van Rossum717ce002001-09-14 16:58:08 +0000437 assert(PyTuple_Check(args));
438 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000439
440 Py_DECREF(args);
441 Py_DECREF(func);
442
443 return retval;
444}
445
Tim Peters6d6c1a32001-08-02 04:15:00 +0000446/* Method resolution order algorithm from "Putting Metaclasses to Work"
447 by Forman and Danforth (Addison-Wesley 1999). */
448
449static int
450conservative_merge(PyObject *left, PyObject *right)
451{
452 int left_size;
453 int right_size;
454 int i, j, r, ok;
455 PyObject *temp, *rr;
456
457 assert(PyList_Check(left));
458 assert(PyList_Check(right));
459
460 again:
461 left_size = PyList_GET_SIZE(left);
462 right_size = PyList_GET_SIZE(right);
463 for (i = 0; i < left_size; i++) {
464 for (j = 0; j < right_size; j++) {
465 if (PyList_GET_ITEM(left, i) ==
466 PyList_GET_ITEM(right, j)) {
467 /* found a merge point */
468 temp = PyList_New(0);
469 if (temp == NULL)
470 return -1;
471 for (r = 0; r < j; r++) {
472 rr = PyList_GET_ITEM(right, r);
473 ok = PySequence_Contains(left, rr);
474 if (ok < 0) {
475 Py_DECREF(temp);
476 return -1;
477 }
478 if (!ok) {
479 ok = PyList_Append(temp, rr);
480 if (ok < 0) {
481 Py_DECREF(temp);
482 return -1;
483 }
484 }
485 }
486 ok = PyList_SetSlice(left, i, i, temp);
487 Py_DECREF(temp);
488 if (ok < 0)
489 return -1;
490 ok = PyList_SetSlice(right, 0, j+1, NULL);
491 if (ok < 0)
492 return -1;
493 goto again;
494 }
495 }
496 }
497 return PyList_SetSlice(left, left_size, left_size, right);
498}
499
500static int
501serious_order_disagreements(PyObject *left, PyObject *right)
502{
503 return 0; /* XXX later -- for now, we cheat: "don't do that" */
504}
505
506static PyObject *
507mro_implementation(PyTypeObject *type)
508{
509 int i, n, ok;
510 PyObject *bases, *result;
511
512 bases = type->tp_bases;
513 n = PyTuple_GET_SIZE(bases);
514 result = Py_BuildValue("[O]", (PyObject *)type);
515 if (result == NULL)
516 return NULL;
517 for (i = 0; i < n; i++) {
518 PyTypeObject *base =
519 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
520 PyObject *parentMRO = PySequence_List(base->tp_mro);
521 if (parentMRO == NULL) {
522 Py_DECREF(result);
523 return NULL;
524 }
525 if (serious_order_disagreements(result, parentMRO)) {
526 Py_DECREF(result);
527 return NULL;
528 }
529 ok = conservative_merge(result, parentMRO);
530 Py_DECREF(parentMRO);
531 if (ok < 0) {
532 Py_DECREF(result);
533 return NULL;
534 }
535 }
536 return result;
537}
538
539static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000540mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000541{
542 PyTypeObject *type = (PyTypeObject *)self;
543
Tim Peters6d6c1a32001-08-02 04:15:00 +0000544 return mro_implementation(type);
545}
546
547static int
548mro_internal(PyTypeObject *type)
549{
550 PyObject *mro, *result, *tuple;
551
552 if (type->ob_type == &PyType_Type) {
553 result = mro_implementation(type);
554 }
555 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000556 static PyObject *mro_str;
557 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000558 if (mro == NULL)
559 return -1;
560 result = PyObject_CallObject(mro, NULL);
561 Py_DECREF(mro);
562 }
563 if (result == NULL)
564 return -1;
565 tuple = PySequence_Tuple(result);
566 Py_DECREF(result);
567 type->tp_mro = tuple;
568 return 0;
569}
570
571
572/* Calculate the best base amongst multiple base classes.
573 This is the first one that's on the path to the "solid base". */
574
575static PyTypeObject *
576best_base(PyObject *bases)
577{
578 int i, n;
579 PyTypeObject *base, *winner, *candidate, *base_i;
580
581 assert(PyTuple_Check(bases));
582 n = PyTuple_GET_SIZE(bases);
583 assert(n > 0);
584 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
585 winner = &PyBaseObject_Type;
586 for (i = 0; i < n; i++) {
587 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
588 if (!PyType_Check((PyObject *)base_i)) {
589 PyErr_SetString(
590 PyExc_TypeError,
591 "bases must be types");
592 return NULL;
593 }
594 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000595 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000596 return NULL;
597 }
598 candidate = solid_base(base_i);
599 if (PyType_IsSubtype(winner, candidate))
600 ;
601 else if (PyType_IsSubtype(candidate, winner)) {
602 winner = candidate;
603 base = base_i;
604 }
605 else {
606 PyErr_SetString(
607 PyExc_TypeError,
608 "multiple bases have "
609 "instance lay-out conflict");
610 return NULL;
611 }
612 }
613 assert(base != NULL);
614 return base;
615}
616
617static int
618extra_ivars(PyTypeObject *type, PyTypeObject *base)
619{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000620 size_t t_size = type->tp_basicsize;
621 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000622
Guido van Rossum9676b222001-08-17 20:32:36 +0000623 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000624 if (type->tp_itemsize || base->tp_itemsize) {
625 /* If itemsize is involved, stricter rules */
626 return t_size != b_size ||
627 type->tp_itemsize != base->tp_itemsize;
628 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000629 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
630 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
631 t_size -= sizeof(PyObject *);
632 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
633 type->tp_dictoffset + sizeof(PyObject *) == t_size)
634 t_size -= sizeof(PyObject *);
635
636 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000637}
638
639static PyTypeObject *
640solid_base(PyTypeObject *type)
641{
642 PyTypeObject *base;
643
644 if (type->tp_base)
645 base = solid_base(type->tp_base);
646 else
647 base = &PyBaseObject_Type;
648 if (extra_ivars(type, base))
649 return type;
650 else
651 return base;
652}
653
654staticforward void object_dealloc(PyObject *);
655staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000656staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000657staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000658
659static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000660subtype_dict(PyObject *obj, void *context)
661{
662 PyObject **dictptr = _PyObject_GetDictPtr(obj);
663 PyObject *dict;
664
665 if (dictptr == NULL) {
666 PyErr_SetString(PyExc_AttributeError,
667 "This object has no __dict__");
668 return NULL;
669 }
670 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000671 if (dict == NULL)
672 *dictptr = dict = PyDict_New();
673 Py_XINCREF(dict);
674 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000675}
676
Guido van Rossum32d34c82001-09-20 21:45:26 +0000677PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000678 {"__dict__", subtype_dict, NULL, NULL},
679 {0},
680};
681
682static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000683type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
684{
685 PyObject *name, *bases, *dict;
686 static char *kwlist[] = {"name", "bases", "dict", 0};
687 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000688 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000689 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000690 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000691 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000692
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000693 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000694 if (metatype == &PyType_Type &&
695 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
696 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000697 PyObject *x = PyTuple_GET_ITEM(args, 0);
698 Py_INCREF(x->ob_type);
699 return (PyObject *) x->ob_type;
700 }
701
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000702 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000703 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
704 &name,
705 &PyTuple_Type, &bases,
706 &PyDict_Type, &dict))
707 return NULL;
708
709 /* Determine the proper metatype to deal with this,
710 and check for metatype conflicts while we're at it.
711 Note that if some other metatype wins to contract,
712 it's possible that its instances are not types. */
713 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000714 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000715 for (i = 0; i < nbases; i++) {
716 tmp = PyTuple_GET_ITEM(bases, i);
717 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000718 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000719 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000720 if (PyType_IsSubtype(tmptype, winner)) {
721 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000722 continue;
723 }
724 PyErr_SetString(PyExc_TypeError,
725 "metatype conflict among bases");
726 return NULL;
727 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000728 if (winner != metatype) {
729 if (winner->tp_new != type_new) /* Pass it to the winner */
730 return winner->tp_new(winner, args, kwds);
731 metatype = winner;
732 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000733
734 /* Adjust for empty tuple bases */
735 if (nbases == 0) {
736 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
737 if (bases == NULL)
738 return NULL;
739 nbases = 1;
740 }
741 else
742 Py_INCREF(bases);
743
744 /* XXX From here until type is allocated, "return NULL" leaks bases! */
745
746 /* Calculate best base, and check that all bases are type objects */
747 base = best_base(bases);
748 if (base == NULL)
749 return NULL;
750 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
751 PyErr_Format(PyExc_TypeError,
752 "type '%.100s' is not an acceptable base type",
753 base->tp_name);
754 return NULL;
755 }
756
Tim Peters6d6c1a32001-08-02 04:15:00 +0000757 /* Check for a __slots__ sequence variable in dict, and count it */
758 slots = PyDict_GetItemString(dict, "__slots__");
759 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000760 add_dict = 0;
761 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000762 if (slots != NULL) {
763 /* Make it into a tuple */
764 if (PyString_Check(slots))
765 slots = Py_BuildValue("(O)", slots);
766 else
767 slots = PySequence_Tuple(slots);
768 if (slots == NULL)
769 return NULL;
770 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000771 if (nslots > 0 && base->tp_itemsize != 0) {
772 PyErr_Format(PyExc_TypeError,
773 "nonempty __slots__ "
774 "not supported for subtype of '%s'",
775 base->tp_name);
776 return NULL;
777 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778 for (i = 0; i < nslots; i++) {
779 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
780 PyErr_SetString(PyExc_TypeError,
781 "__slots__ must be a sequence of strings");
782 Py_DECREF(slots);
783 return NULL;
784 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000785 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000786 }
787 }
788 if (slots == NULL && base->tp_dictoffset == 0 &&
789 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000790 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000791 add_dict++;
792 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000793 if (slots == NULL && base->tp_weaklistoffset == 0 &&
794 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000795 nslots++;
796 add_weak++;
797 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000798
799 /* XXX From here until type is safely allocated,
800 "return NULL" may leak slots! */
801
802 /* Allocate the type object */
803 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
804 if (type == NULL)
805 return NULL;
806
807 /* Keep name and slots alive in the extended type object */
808 et = (etype *)type;
809 Py_INCREF(name);
810 et->name = name;
811 et->slots = slots;
812
Guido van Rossumdc91b992001-08-08 22:26:22 +0000813 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000814 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
815 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000816 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
817 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000818
819 /* It's a new-style number unless it specifically inherits any
820 old-style numeric behavior */
821 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
822 (base->tp_as_number == NULL))
823 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
824
825 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000826 type->tp_as_number = &et->as_number;
827 type->tp_as_sequence = &et->as_sequence;
828 type->tp_as_mapping = &et->as_mapping;
829 type->tp_as_buffer = &et->as_buffer;
830 type->tp_name = PyString_AS_STRING(name);
831
832 /* Set tp_base and tp_bases */
833 type->tp_bases = bases;
834 Py_INCREF(base);
835 type->tp_base = base;
836
Guido van Rossum687ae002001-10-15 22:03:32 +0000837 /* Initialize tp_dict from passed-in dict */
838 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839 if (dict == NULL) {
840 Py_DECREF(type);
841 return NULL;
842 }
843
Guido van Rossumc3542212001-08-16 09:18:56 +0000844 /* Set __module__ in the dict */
845 if (PyDict_GetItemString(dict, "__module__") == NULL) {
846 tmp = PyEval_GetGlobals();
847 if (tmp != NULL) {
848 tmp = PyDict_GetItemString(tmp, "__name__");
849 if (tmp != NULL) {
850 if (PyDict_SetItemString(dict, "__module__",
851 tmp) < 0)
852 return NULL;
853 }
854 }
855 }
856
Tim Peters2f93e282001-10-04 05:27:00 +0000857 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
858 and is a string (tp_doc is a char* -- can't copy a general object
859 into it).
860 XXX What if it's a Unicode string? Don't know -- this ignores it.
861 */
862 {
863 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
864 if (doc != NULL && PyString_Check(doc)) {
865 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +0000866 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +0000867 if (type->tp_doc == NULL) {
868 Py_DECREF(type);
869 return NULL;
870 }
871 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
872 }
873 }
874
Tim Peters6d6c1a32001-08-02 04:15:00 +0000875 /* Special-case __new__: if it's a plain function,
876 make it a static function */
877 tmp = PyDict_GetItemString(dict, "__new__");
878 if (tmp != NULL && PyFunction_Check(tmp)) {
879 tmp = PyStaticMethod_New(tmp);
880 if (tmp == NULL) {
881 Py_DECREF(type);
882 return NULL;
883 }
884 PyDict_SetItemString(dict, "__new__", tmp);
885 Py_DECREF(tmp);
886 }
887
888 /* Add descriptors for custom slots from __slots__, or for __dict__ */
889 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000890 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000891 if (slots != NULL) {
892 for (i = 0; i < nslots; i++, mp++) {
893 mp->name = PyString_AS_STRING(
894 PyTuple_GET_ITEM(slots, i));
895 mp->type = T_OBJECT;
896 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000897 if (base->tp_weaklistoffset == 0 &&
898 strcmp(mp->name, "__weakref__") == 0)
899 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000900 slotoffset += sizeof(PyObject *);
901 }
902 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000903 else {
904 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000905 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +0000906 type->tp_dictoffset =
907 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000908 else
909 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000910 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000911 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000912 }
913 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000914 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000915 type->tp_weaklistoffset = slotoffset;
916 mp->name = "__weakref__";
917 mp->type = T_OBJECT;
918 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000919 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000920 mp++;
921 slotoffset += sizeof(PyObject *);
922 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000923 }
924 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000925 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000926 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000927
928 /* Special case some slots */
929 if (type->tp_dictoffset != 0 || nslots > 0) {
930 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
931 type->tp_getattro = PyObject_GenericGetAttr;
932 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
933 type->tp_setattro = PyObject_GenericSetAttr;
934 }
935 type->tp_dealloc = subtype_dealloc;
936
Guido van Rossum9475a232001-10-05 20:51:39 +0000937 /* Enable GC unless there are really no instance variables possible */
938 if (!(type->tp_basicsize == sizeof(PyObject) &&
939 type->tp_itemsize == 0))
940 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
941
Tim Peters6d6c1a32001-08-02 04:15:00 +0000942 /* Always override allocation strategy to use regular heap */
943 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +0000944 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
945 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +0000946 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +0000947 type->tp_clear = base->tp_clear;
948 }
949 else
950 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000951
952 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000953 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000954 Py_DECREF(type);
955 return NULL;
956 }
957
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000958 /* Put the proper slots in place */
959 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000960
Tim Peters6d6c1a32001-08-02 04:15:00 +0000961 return (PyObject *)type;
962}
963
964/* Internal API to look for a name through the MRO.
965 This returns a borrowed reference, and doesn't set an exception! */
966PyObject *
967_PyType_Lookup(PyTypeObject *type, PyObject *name)
968{
969 int i, n;
970 PyObject *mro, *res, *dict;
971
Guido van Rossum687ae002001-10-15 22:03:32 +0000972 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000973 mro = type->tp_mro;
974 assert(PyTuple_Check(mro));
975 n = PyTuple_GET_SIZE(mro);
976 for (i = 0; i < n; i++) {
977 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
978 assert(PyType_Check(type));
Guido van Rossum687ae002001-10-15 22:03:32 +0000979 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000980 assert(dict && PyDict_Check(dict));
981 res = PyDict_GetItem(dict, name);
982 if (res != NULL)
983 return res;
984 }
985 return NULL;
986}
987
988/* This is similar to PyObject_GenericGetAttr(),
989 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
990static PyObject *
991type_getattro(PyTypeObject *type, PyObject *name)
992{
993 PyTypeObject *metatype = type->ob_type;
994 PyObject *descr, *res;
995 descrgetfunc f;
996
997 /* Initialize this type (we'll assume the metatype is initialized) */
998 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000999 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000 return NULL;
1001 }
1002
1003 /* Get a descriptor from the metatype */
1004 descr = _PyType_Lookup(metatype, name);
1005 f = NULL;
1006 if (descr != NULL) {
1007 f = descr->ob_type->tp_descr_get;
1008 if (f != NULL && PyDescr_IsData(descr))
1009 return f(descr,
1010 (PyObject *)type, (PyObject *)metatype);
1011 }
1012
Guido van Rossum687ae002001-10-15 22:03:32 +00001013 /* Look in tp_dict of this type and its bases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014 res = _PyType_Lookup(type, name);
1015 if (res != NULL) {
1016 f = res->ob_type->tp_descr_get;
1017 if (f != NULL)
1018 return f(res, (PyObject *)NULL, (PyObject *)type);
1019 Py_INCREF(res);
1020 return res;
1021 }
1022
1023 /* Use the descriptor from the metatype */
1024 if (f != NULL) {
1025 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1026 return res;
1027 }
1028 if (descr != NULL) {
1029 Py_INCREF(descr);
1030 return descr;
1031 }
1032
1033 /* Give up */
1034 PyErr_Format(PyExc_AttributeError,
1035 "type object '%.50s' has no attribute '%.400s'",
1036 type->tp_name, PyString_AS_STRING(name));
1037 return NULL;
1038}
1039
1040static int
1041type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1042{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001043 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1044 PyErr_Format(
1045 PyExc_TypeError,
1046 "can't set attributes of built-in/extension type '%s'",
1047 type->tp_name);
1048 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001049 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001050 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1051 return -1;
1052 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001053}
1054
1055static void
1056type_dealloc(PyTypeObject *type)
1057{
1058 etype *et;
1059
1060 /* Assert this is a heap-allocated type object */
1061 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001062 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001063 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001064 et = (etype *)type;
1065 Py_XDECREF(type->tp_base);
1066 Py_XDECREF(type->tp_dict);
1067 Py_XDECREF(type->tp_bases);
1068 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001069 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001070 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001071 Py_XDECREF(et->name);
1072 Py_XDECREF(et->slots);
1073 type->ob_type->tp_free((PyObject *)type);
1074}
1075
Guido van Rossum1c450732001-10-08 15:18:27 +00001076static PyObject *
1077type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1078{
1079 PyObject *list, *raw, *ref;
1080 int i, n;
1081
1082 list = PyList_New(0);
1083 if (list == NULL)
1084 return NULL;
1085 raw = type->tp_subclasses;
1086 if (raw == NULL)
1087 return list;
1088 assert(PyList_Check(raw));
1089 n = PyList_GET_SIZE(raw);
1090 for (i = 0; i < n; i++) {
1091 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001092 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001093 ref = PyWeakref_GET_OBJECT(ref);
1094 if (ref != Py_None) {
1095 if (PyList_Append(list, ref) < 0) {
1096 Py_DECREF(list);
1097 return NULL;
1098 }
1099 }
1100 }
1101 return list;
1102}
1103
Tim Peters6d6c1a32001-08-02 04:15:00 +00001104static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001105 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001106 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001107 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1108 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001109 {0}
1110};
1111
1112static char type_doc[] =
1113"type(object) -> the object's type\n"
1114"type(name, bases, dict) -> a new type";
1115
Guido van Rossum048eb752001-10-02 21:24:57 +00001116static int
1117type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1118{
1119 etype *et;
1120 int err;
1121
1122 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1123 return 0;
1124
1125 et = (etype *)type;
1126
1127#define VISIT(SLOT) \
1128 if (SLOT) { \
1129 err = visit((PyObject *)(SLOT), arg); \
1130 if (err) \
1131 return err; \
1132 }
1133
1134 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001135 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001136 VISIT(type->tp_mro);
1137 VISIT(type->tp_bases);
1138 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001139 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001140 VISIT(et->slots);
1141
1142#undef VISIT
1143
1144 return 0;
1145}
1146
1147static int
1148type_clear(PyTypeObject *type)
1149{
1150 etype *et;
1151 PyObject *tmp;
1152
1153 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1154 return 0;
1155
1156 et = (etype *)type;
1157
1158#define CLEAR(SLOT) \
1159 if (SLOT) { \
1160 tmp = (PyObject *)(SLOT); \
1161 SLOT = NULL; \
1162 Py_DECREF(tmp); \
1163 }
1164
1165 CLEAR(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001166 CLEAR(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001167 CLEAR(type->tp_mro);
1168 CLEAR(type->tp_bases);
1169 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001170 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001171 CLEAR(et->slots);
1172
Tim Peters2f93e282001-10-04 05:27:00 +00001173 if (type->tp_doc != NULL) {
1174 PyObject_FREE(type->tp_doc);
1175 type->tp_doc = NULL;
1176 }
1177
Guido van Rossum048eb752001-10-02 21:24:57 +00001178#undef CLEAR
1179
1180 return 0;
1181}
1182
1183static int
1184type_is_gc(PyTypeObject *type)
1185{
1186 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1187}
1188
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001189PyTypeObject PyType_Type = {
1190 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001191 0, /* ob_size */
1192 "type", /* tp_name */
1193 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001194 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 (destructor)type_dealloc, /* tp_dealloc */
1196 0, /* tp_print */
1197 0, /* tp_getattr */
1198 0, /* tp_setattr */
1199 type_compare, /* tp_compare */
1200 (reprfunc)type_repr, /* tp_repr */
1201 0, /* tp_as_number */
1202 0, /* tp_as_sequence */
1203 0, /* tp_as_mapping */
1204 (hashfunc)_Py_HashPointer, /* tp_hash */
1205 (ternaryfunc)type_call, /* tp_call */
1206 0, /* tp_str */
1207 (getattrofunc)type_getattro, /* tp_getattro */
1208 (setattrofunc)type_setattro, /* tp_setattro */
1209 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001210 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1211 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001213 (traverseproc)type_traverse, /* tp_traverse */
1214 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001216 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001217 0, /* tp_iter */
1218 0, /* tp_iternext */
1219 type_methods, /* tp_methods */
1220 type_members, /* tp_members */
1221 type_getsets, /* tp_getset */
1222 0, /* tp_base */
1223 0, /* tp_dict */
1224 0, /* tp_descr_get */
1225 0, /* tp_descr_set */
1226 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1227 0, /* tp_init */
1228 0, /* tp_alloc */
1229 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001230 _PyObject_GC_Del, /* tp_free */
1231 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001232};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001233
1234
1235/* The base type of all types (eventually)... except itself. */
1236
1237static int
1238object_init(PyObject *self, PyObject *args, PyObject *kwds)
1239{
1240 return 0;
1241}
1242
1243static void
1244object_dealloc(PyObject *self)
1245{
1246 self->ob_type->tp_free(self);
1247}
1248
Guido van Rossum8e248182001-08-12 05:17:56 +00001249static PyObject *
1250object_repr(PyObject *self)
1251{
Guido van Rossum76e69632001-08-16 18:52:43 +00001252 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001253 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001254
Guido van Rossum76e69632001-08-16 18:52:43 +00001255 type = self->ob_type;
1256 mod = type_module(type, NULL);
1257 if (mod == NULL)
1258 PyErr_Clear();
1259 else if (!PyString_Check(mod)) {
1260 Py_DECREF(mod);
1261 mod = NULL;
1262 }
1263 name = type_name(type, NULL);
1264 if (name == NULL)
1265 return NULL;
1266 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001267 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001268 PyString_AS_STRING(mod),
1269 PyString_AS_STRING(name),
1270 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001271 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001272 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001273 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001274 Py_XDECREF(mod);
1275 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001276 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001277}
1278
Guido van Rossumb8f63662001-08-15 23:57:02 +00001279static PyObject *
1280object_str(PyObject *self)
1281{
1282 unaryfunc f;
1283
1284 f = self->ob_type->tp_repr;
1285 if (f == NULL)
1286 f = object_repr;
1287 return f(self);
1288}
1289
Guido van Rossum8e248182001-08-12 05:17:56 +00001290static long
1291object_hash(PyObject *self)
1292{
1293 return _Py_HashPointer(self);
1294}
Guido van Rossum8e248182001-08-12 05:17:56 +00001295
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001296static PyObject *
1297object_get_class(PyObject *self, void *closure)
1298{
1299 Py_INCREF(self->ob_type);
1300 return (PyObject *)(self->ob_type);
1301}
1302
1303static int
1304equiv_structs(PyTypeObject *a, PyTypeObject *b)
1305{
1306 return a == b ||
1307 (a != NULL &&
1308 b != NULL &&
1309 a->tp_basicsize == b->tp_basicsize &&
1310 a->tp_itemsize == b->tp_itemsize &&
1311 a->tp_dictoffset == b->tp_dictoffset &&
1312 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1313 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1314 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1315}
1316
1317static int
1318same_slots_added(PyTypeObject *a, PyTypeObject *b)
1319{
1320 PyTypeObject *base = a->tp_base;
1321 int size;
1322
1323 if (base != b->tp_base)
1324 return 0;
1325 if (equiv_structs(a, base) && equiv_structs(b, base))
1326 return 1;
1327 size = base->tp_basicsize;
1328 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1329 size += sizeof(PyObject *);
1330 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1331 size += sizeof(PyObject *);
1332 return size == a->tp_basicsize && size == b->tp_basicsize;
1333}
1334
1335static int
1336object_set_class(PyObject *self, PyObject *value, void *closure)
1337{
1338 PyTypeObject *old = self->ob_type;
1339 PyTypeObject *new, *newbase, *oldbase;
1340
1341 if (!PyType_Check(value)) {
1342 PyErr_Format(PyExc_TypeError,
1343 "__class__ must be set to new-style class, not '%s' object",
1344 value->ob_type->tp_name);
1345 return -1;
1346 }
1347 new = (PyTypeObject *)value;
1348 newbase = new;
1349 oldbase = old;
1350 while (equiv_structs(newbase, newbase->tp_base))
1351 newbase = newbase->tp_base;
1352 while (equiv_structs(oldbase, oldbase->tp_base))
1353 oldbase = oldbase->tp_base;
1354 if (newbase != oldbase &&
1355 (newbase->tp_base != oldbase->tp_base ||
1356 !same_slots_added(newbase, oldbase))) {
1357 PyErr_Format(PyExc_TypeError,
1358 "__class__ assignment: "
1359 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001360 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001361 old->tp_name);
1362 return -1;
1363 }
1364 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1365 Py_INCREF(new);
1366 }
1367 self->ob_type = new;
1368 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1369 Py_DECREF(old);
1370 }
1371 return 0;
1372}
1373
1374static PyGetSetDef object_getsets[] = {
1375 {"__class__", object_get_class, object_set_class,
1376 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001377 {0}
1378};
1379
Guido van Rossum3926a632001-09-25 16:25:58 +00001380static PyObject *
1381object_reduce(PyObject *self, PyObject *args)
1382{
1383 /* Call copy_reg._reduce(self) */
1384 static PyObject *copy_reg_str;
1385 PyObject *copy_reg, *res;
1386
1387 if (!copy_reg_str) {
1388 copy_reg_str = PyString_InternFromString("copy_reg");
1389 if (copy_reg_str == NULL)
1390 return NULL;
1391 }
1392 copy_reg = PyImport_Import(copy_reg_str);
1393 if (!copy_reg)
1394 return NULL;
1395 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1396 Py_DECREF(copy_reg);
1397 return res;
1398}
1399
1400static PyMethodDef object_methods[] = {
1401 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1402 {0}
1403};
1404
Tim Peters6d6c1a32001-08-02 04:15:00 +00001405PyTypeObject PyBaseObject_Type = {
1406 PyObject_HEAD_INIT(&PyType_Type)
1407 0, /* ob_size */
1408 "object", /* tp_name */
1409 sizeof(PyObject), /* tp_basicsize */
1410 0, /* tp_itemsize */
1411 (destructor)object_dealloc, /* tp_dealloc */
1412 0, /* tp_print */
1413 0, /* tp_getattr */
1414 0, /* tp_setattr */
1415 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001416 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001417 0, /* tp_as_number */
1418 0, /* tp_as_sequence */
1419 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001420 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001421 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001422 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001423 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001424 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001425 0, /* tp_as_buffer */
1426 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1427 "The most base type", /* tp_doc */
1428 0, /* tp_traverse */
1429 0, /* tp_clear */
1430 0, /* tp_richcompare */
1431 0, /* tp_weaklistoffset */
1432 0, /* tp_iter */
1433 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001434 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001435 0, /* tp_members */
1436 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001437 0, /* tp_base */
1438 0, /* tp_dict */
1439 0, /* tp_descr_get */
1440 0, /* tp_descr_set */
1441 0, /* tp_dictoffset */
1442 object_init, /* tp_init */
1443 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001444 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001445 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001446};
1447
1448
1449/* Initialize the __dict__ in a type object */
1450
1451static int
1452add_methods(PyTypeObject *type, PyMethodDef *meth)
1453{
Guido van Rossum687ae002001-10-15 22:03:32 +00001454 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001455
1456 for (; meth->ml_name != NULL; meth++) {
1457 PyObject *descr;
1458 if (PyDict_GetItemString(dict, meth->ml_name))
1459 continue;
1460 descr = PyDescr_NewMethod(type, meth);
1461 if (descr == NULL)
1462 return -1;
1463 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1464 return -1;
1465 Py_DECREF(descr);
1466 }
1467 return 0;
1468}
1469
1470static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001471add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472{
Guido van Rossum687ae002001-10-15 22:03:32 +00001473 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001474
1475 for (; memb->name != NULL; memb++) {
1476 PyObject *descr;
1477 if (PyDict_GetItemString(dict, memb->name))
1478 continue;
1479 descr = PyDescr_NewMember(type, memb);
1480 if (descr == NULL)
1481 return -1;
1482 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1483 return -1;
1484 Py_DECREF(descr);
1485 }
1486 return 0;
1487}
1488
1489static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001490add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001491{
Guido van Rossum687ae002001-10-15 22:03:32 +00001492 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001493
1494 for (; gsp->name != NULL; gsp++) {
1495 PyObject *descr;
1496 if (PyDict_GetItemString(dict, gsp->name))
1497 continue;
1498 descr = PyDescr_NewGetSet(type, gsp);
1499
1500 if (descr == NULL)
1501 return -1;
1502 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1503 return -1;
1504 Py_DECREF(descr);
1505 }
1506 return 0;
1507}
1508
Guido van Rossum13d52f02001-08-10 21:24:08 +00001509static void
1510inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001511{
1512 int oldsize, newsize;
1513
Guido van Rossum13d52f02001-08-10 21:24:08 +00001514 /* Special flag magic */
1515 if (!type->tp_as_buffer && base->tp_as_buffer) {
1516 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1517 type->tp_flags |=
1518 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1519 }
1520 if (!type->tp_as_sequence && base->tp_as_sequence) {
1521 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1522 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1523 }
1524 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1525 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1526 if ((!type->tp_as_number && base->tp_as_number) ||
1527 (!type->tp_as_sequence && base->tp_as_sequence)) {
1528 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1529 if (!type->tp_as_number && !type->tp_as_sequence) {
1530 type->tp_flags |= base->tp_flags &
1531 Py_TPFLAGS_HAVE_INPLACEOPS;
1532 }
1533 }
1534 /* Wow */
1535 }
1536 if (!type->tp_as_number && base->tp_as_number) {
1537 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1538 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1539 }
1540
1541 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001542 oldsize = base->tp_basicsize;
1543 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1544 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1545 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001546 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1547 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001548 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001549 if (type->tp_traverse == NULL)
1550 type->tp_traverse = base->tp_traverse;
1551 if (type->tp_clear == NULL)
1552 type->tp_clear = base->tp_clear;
1553 }
1554 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1555 if (base != &PyBaseObject_Type ||
1556 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1557 if (type->tp_new == NULL)
1558 type->tp_new = base->tp_new;
1559 }
1560 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001561 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001562
1563 /* Copy other non-function slots */
1564
1565#undef COPYVAL
1566#define COPYVAL(SLOT) \
1567 if (type->SLOT == 0) type->SLOT = base->SLOT
1568
1569 COPYVAL(tp_itemsize);
1570 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1571 COPYVAL(tp_weaklistoffset);
1572 }
1573 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1574 COPYVAL(tp_dictoffset);
1575 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001576}
1577
1578static void
1579inherit_slots(PyTypeObject *type, PyTypeObject *base)
1580{
1581 PyTypeObject *basebase;
1582
1583#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001584#undef COPYSLOT
1585#undef COPYNUM
1586#undef COPYSEQ
1587#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001588#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001589
1590#define SLOTDEFINED(SLOT) \
1591 (base->SLOT != 0 && \
1592 (basebase == NULL || base->SLOT != basebase->SLOT))
1593
Tim Peters6d6c1a32001-08-02 04:15:00 +00001594#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001595 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001596
1597#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1598#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1599#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001600#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001601
Guido van Rossum13d52f02001-08-10 21:24:08 +00001602 /* This won't inherit indirect slots (from tp_as_number etc.)
1603 if type doesn't provide the space. */
1604
1605 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1606 basebase = base->tp_base;
1607 if (basebase->tp_as_number == NULL)
1608 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001609 COPYNUM(nb_add);
1610 COPYNUM(nb_subtract);
1611 COPYNUM(nb_multiply);
1612 COPYNUM(nb_divide);
1613 COPYNUM(nb_remainder);
1614 COPYNUM(nb_divmod);
1615 COPYNUM(nb_power);
1616 COPYNUM(nb_negative);
1617 COPYNUM(nb_positive);
1618 COPYNUM(nb_absolute);
1619 COPYNUM(nb_nonzero);
1620 COPYNUM(nb_invert);
1621 COPYNUM(nb_lshift);
1622 COPYNUM(nb_rshift);
1623 COPYNUM(nb_and);
1624 COPYNUM(nb_xor);
1625 COPYNUM(nb_or);
1626 COPYNUM(nb_coerce);
1627 COPYNUM(nb_int);
1628 COPYNUM(nb_long);
1629 COPYNUM(nb_float);
1630 COPYNUM(nb_oct);
1631 COPYNUM(nb_hex);
1632 COPYNUM(nb_inplace_add);
1633 COPYNUM(nb_inplace_subtract);
1634 COPYNUM(nb_inplace_multiply);
1635 COPYNUM(nb_inplace_divide);
1636 COPYNUM(nb_inplace_remainder);
1637 COPYNUM(nb_inplace_power);
1638 COPYNUM(nb_inplace_lshift);
1639 COPYNUM(nb_inplace_rshift);
1640 COPYNUM(nb_inplace_and);
1641 COPYNUM(nb_inplace_xor);
1642 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001643 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1644 COPYNUM(nb_true_divide);
1645 COPYNUM(nb_floor_divide);
1646 COPYNUM(nb_inplace_true_divide);
1647 COPYNUM(nb_inplace_floor_divide);
1648 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001649 }
1650
Guido van Rossum13d52f02001-08-10 21:24:08 +00001651 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1652 basebase = base->tp_base;
1653 if (basebase->tp_as_sequence == NULL)
1654 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655 COPYSEQ(sq_length);
1656 COPYSEQ(sq_concat);
1657 COPYSEQ(sq_repeat);
1658 COPYSEQ(sq_item);
1659 COPYSEQ(sq_slice);
1660 COPYSEQ(sq_ass_item);
1661 COPYSEQ(sq_ass_slice);
1662 COPYSEQ(sq_contains);
1663 COPYSEQ(sq_inplace_concat);
1664 COPYSEQ(sq_inplace_repeat);
1665 }
1666
Guido van Rossum13d52f02001-08-10 21:24:08 +00001667 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1668 basebase = base->tp_base;
1669 if (basebase->tp_as_mapping == NULL)
1670 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001671 COPYMAP(mp_length);
1672 COPYMAP(mp_subscript);
1673 COPYMAP(mp_ass_subscript);
1674 }
1675
Tim Petersfc57ccb2001-10-12 02:38:24 +00001676 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1677 basebase = base->tp_base;
1678 if (basebase->tp_as_buffer == NULL)
1679 basebase = NULL;
1680 COPYBUF(bf_getreadbuffer);
1681 COPYBUF(bf_getwritebuffer);
1682 COPYBUF(bf_getsegcount);
1683 COPYBUF(bf_getcharbuffer);
1684 }
1685
Guido van Rossum13d52f02001-08-10 21:24:08 +00001686 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001687
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688 COPYSLOT(tp_dealloc);
1689 COPYSLOT(tp_print);
1690 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1691 type->tp_getattr = base->tp_getattr;
1692 type->tp_getattro = base->tp_getattro;
1693 }
1694 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1695 type->tp_setattr = base->tp_setattr;
1696 type->tp_setattro = base->tp_setattro;
1697 }
1698 /* tp_compare see tp_richcompare */
1699 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001700 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001701 COPYSLOT(tp_call);
1702 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001703 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001704 if (type->tp_compare == NULL &&
1705 type->tp_richcompare == NULL &&
1706 type->tp_hash == NULL)
1707 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001708 type->tp_compare = base->tp_compare;
1709 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001710 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001711 }
1712 }
1713 else {
1714 COPYSLOT(tp_compare);
1715 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001716 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1717 COPYSLOT(tp_iter);
1718 COPYSLOT(tp_iternext);
1719 }
1720 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1721 COPYSLOT(tp_descr_get);
1722 COPYSLOT(tp_descr_set);
1723 COPYSLOT(tp_dictoffset);
1724 COPYSLOT(tp_init);
1725 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726 COPYSLOT(tp_free);
1727 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001728}
1729
Guido van Rossum13d52f02001-08-10 21:24:08 +00001730staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00001731staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001732
Tim Peters6d6c1a32001-08-02 04:15:00 +00001733int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001734PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001735{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001736 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001737 PyTypeObject *base;
1738 int i, n;
1739
Guido van Rossumd614f972001-08-10 17:39:49 +00001740 if (type->tp_flags & Py_TPFLAGS_READY) {
1741 assert(type->tp_dict != NULL);
1742 return 0;
1743 }
1744 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00001745
1746 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001747
1748 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1749 base = type->tp_base;
1750 if (base == NULL && type != &PyBaseObject_Type)
1751 base = type->tp_base = &PyBaseObject_Type;
1752
1753 /* Initialize tp_bases */
1754 bases = type->tp_bases;
1755 if (bases == NULL) {
1756 if (base == NULL)
1757 bases = PyTuple_New(0);
1758 else
1759 bases = Py_BuildValue("(O)", base);
1760 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001761 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762 type->tp_bases = bases;
1763 }
1764
1765 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001766 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001767 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001768 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001769 }
1770
Guido van Rossum687ae002001-10-15 22:03:32 +00001771 /* Initialize tp_dict */
1772 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001773 if (dict == NULL) {
1774 dict = PyDict_New();
1775 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001776 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00001777 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778 }
1779
Guido van Rossum687ae002001-10-15 22:03:32 +00001780 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001781 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001782 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783 if (type->tp_methods != NULL) {
1784 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001785 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001786 }
1787 if (type->tp_members != NULL) {
1788 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001789 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001790 }
1791 if (type->tp_getset != NULL) {
1792 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001793 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001794 }
1795
Tim Peters6d6c1a32001-08-02 04:15:00 +00001796 /* Calculate method resolution order */
1797 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001798 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799 }
1800
Guido van Rossum13d52f02001-08-10 21:24:08 +00001801 /* Inherit special flags from dominant base */
1802 if (type->tp_base != NULL)
1803 inherit_special(type, type->tp_base);
1804
Tim Peters6d6c1a32001-08-02 04:15:00 +00001805 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001806 bases = type->tp_mro;
1807 assert(bases != NULL);
1808 assert(PyTuple_Check(bases));
1809 n = PyTuple_GET_SIZE(bases);
1810 for (i = 1; i < n; i++) {
1811 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1812 assert(PyType_Check(base));
1813 inherit_slots(type, base);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001814 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815
Guido van Rossum13d52f02001-08-10 21:24:08 +00001816 /* Some more special stuff */
1817 base = type->tp_base;
1818 if (base != NULL) {
1819 if (type->tp_as_number == NULL)
1820 type->tp_as_number = base->tp_as_number;
1821 if (type->tp_as_sequence == NULL)
1822 type->tp_as_sequence = base->tp_as_sequence;
1823 if (type->tp_as_mapping == NULL)
1824 type->tp_as_mapping = base->tp_as_mapping;
1825 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826
Guido van Rossum1c450732001-10-08 15:18:27 +00001827 /* Link into each base class's list of subclasses */
1828 bases = type->tp_bases;
1829 n = PyTuple_GET_SIZE(bases);
1830 for (i = 0; i < n; i++) {
1831 base = (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
1832 if (add_subclass((PyTypeObject *)base, type) < 0)
1833 goto error;
1834 }
1835
Guido van Rossum13d52f02001-08-10 21:24:08 +00001836 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001837 assert(type->tp_dict != NULL);
1838 type->tp_flags =
1839 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001840 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001841
1842 error:
1843 type->tp_flags &= ~Py_TPFLAGS_READYING;
1844 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845}
1846
Guido van Rossum1c450732001-10-08 15:18:27 +00001847static int
1848add_subclass(PyTypeObject *base, PyTypeObject *type)
1849{
1850 int i;
1851 PyObject *list, *ref, *new;
1852
1853 list = base->tp_subclasses;
1854 if (list == NULL) {
1855 base->tp_subclasses = list = PyList_New(0);
1856 if (list == NULL)
1857 return -1;
1858 }
1859 assert(PyList_Check(list));
1860 new = PyWeakref_NewRef((PyObject *)type, NULL);
1861 i = PyList_GET_SIZE(list);
1862 while (--i >= 0) {
1863 ref = PyList_GET_ITEM(list, i);
1864 assert(PyWeakref_CheckRef(ref));
1865 if (PyWeakref_GET_OBJECT(ref) == Py_None)
1866 return PyList_SetItem(list, i, new);
1867 }
1868 i = PyList_Append(list, new);
1869 Py_DECREF(new);
1870 return i;
1871}
1872
Tim Peters6d6c1a32001-08-02 04:15:00 +00001873
1874/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1875
1876/* There's a wrapper *function* for each distinct function typedef used
1877 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1878 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1879 Most tables have only one entry; the tables for binary operators have two
1880 entries, one regular and one with reversed arguments. */
1881
1882static PyObject *
1883wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1884{
1885 inquiry func = (inquiry)wrapped;
1886 int res;
1887
1888 if (!PyArg_ParseTuple(args, ""))
1889 return NULL;
1890 res = (*func)(self);
1891 if (res == -1 && PyErr_Occurred())
1892 return NULL;
1893 return PyInt_FromLong((long)res);
1894}
1895
1896static struct wrapperbase tab_len[] = {
1897 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1898 {0}
1899};
1900
1901static PyObject *
1902wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1903{
1904 binaryfunc func = (binaryfunc)wrapped;
1905 PyObject *other;
1906
1907 if (!PyArg_ParseTuple(args, "O", &other))
1908 return NULL;
1909 return (*func)(self, other);
1910}
1911
1912static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001913wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
1914{
1915 binaryfunc func = (binaryfunc)wrapped;
1916 PyObject *other;
1917
1918 if (!PyArg_ParseTuple(args, "O", &other))
1919 return NULL;
1920 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001921 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001922 Py_INCREF(Py_NotImplemented);
1923 return Py_NotImplemented;
1924 }
1925 return (*func)(self, other);
1926}
1927
1928static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001929wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1930{
1931 binaryfunc func = (binaryfunc)wrapped;
1932 PyObject *other;
1933
1934 if (!PyArg_ParseTuple(args, "O", &other))
1935 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001936 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001937 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001938 Py_INCREF(Py_NotImplemented);
1939 return Py_NotImplemented;
1940 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001941 return (*func)(other, self);
1942}
1943
1944#undef BINARY
1945#define BINARY(NAME, OP) \
1946static struct wrapperbase tab_##NAME[] = { \
1947 {"__" #NAME "__", \
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001948 (wrapperfunc)wrap_binaryfunc_l, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00001949 "x.__" #NAME "__(y) <==> " #OP}, \
1950 {"__r" #NAME "__", \
1951 (wrapperfunc)wrap_binaryfunc_r, \
1952 "y.__r" #NAME "__(x) <==> " #OP}, \
1953 {0} \
1954}
1955
1956BINARY(add, "x+y");
1957BINARY(sub, "x-y");
1958BINARY(mul, "x*y");
1959BINARY(div, "x/y");
1960BINARY(mod, "x%y");
1961BINARY(divmod, "divmod(x,y)");
1962BINARY(lshift, "x<<y");
1963BINARY(rshift, "x>>y");
1964BINARY(and, "x&y");
1965BINARY(xor, "x^y");
1966BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00001967
1968static PyObject *
1969wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
1970{
1971 coercion func = (coercion)wrapped;
1972 PyObject *other, *res;
1973 int ok;
1974
1975 if (!PyArg_ParseTuple(args, "O", &other))
1976 return NULL;
1977 ok = func(&self, &other);
1978 if (ok < 0)
1979 return NULL;
1980 if (ok > 0) {
1981 Py_INCREF(Py_NotImplemented);
1982 return Py_NotImplemented;
1983 }
1984 res = PyTuple_New(2);
1985 if (res == NULL) {
1986 Py_DECREF(self);
1987 Py_DECREF(other);
1988 return NULL;
1989 }
1990 PyTuple_SET_ITEM(res, 0, self);
1991 PyTuple_SET_ITEM(res, 1, other);
1992 return res;
1993}
1994
1995static struct wrapperbase tab_coerce[] = {
1996 {"__coerce__", (wrapperfunc)wrap_coercefunc,
1997 "x.__coerce__(y) <==> coerce(x, y)"},
1998 {0}
1999};
2000
Guido van Rossum874f15a2001-09-25 21:16:33 +00002001BINARY(floordiv, "x//y");
2002BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003
2004static PyObject *
2005wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2006{
2007 ternaryfunc func = (ternaryfunc)wrapped;
2008 PyObject *other;
2009 PyObject *third = Py_None;
2010
2011 /* Note: This wrapper only works for __pow__() */
2012
2013 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2014 return NULL;
2015 return (*func)(self, other, third);
2016}
2017
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002018static PyObject *
2019wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2020{
2021 ternaryfunc func = (ternaryfunc)wrapped;
2022 PyObject *other;
2023 PyObject *third = Py_None;
2024
2025 /* Note: This wrapper only works for __pow__() */
2026
2027 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2028 return NULL;
2029 return (*func)(other, self, third);
2030}
2031
Tim Peters6d6c1a32001-08-02 04:15:00 +00002032#undef TERNARY
2033#define TERNARY(NAME, OP) \
2034static struct wrapperbase tab_##NAME[] = { \
2035 {"__" #NAME "__", \
2036 (wrapperfunc)wrap_ternaryfunc, \
2037 "x.__" #NAME "__(y, z) <==> " #OP}, \
2038 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002039 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040 "y.__r" #NAME "__(x, z) <==> " #OP}, \
2041 {0} \
2042}
2043
2044TERNARY(pow, "(x**y) % z");
2045
2046#undef UNARY
2047#define UNARY(NAME, OP) \
2048static struct wrapperbase tab_##NAME[] = { \
2049 {"__" #NAME "__", \
2050 (wrapperfunc)wrap_unaryfunc, \
2051 "x.__" #NAME "__() <==> " #OP}, \
2052 {0} \
2053}
2054
2055static PyObject *
2056wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2057{
2058 unaryfunc func = (unaryfunc)wrapped;
2059
2060 if (!PyArg_ParseTuple(args, ""))
2061 return NULL;
2062 return (*func)(self);
2063}
2064
2065UNARY(neg, "-x");
2066UNARY(pos, "+x");
2067UNARY(abs, "abs(x)");
2068UNARY(nonzero, "x != 0");
2069UNARY(invert, "~x");
2070UNARY(int, "int(x)");
2071UNARY(long, "long(x)");
2072UNARY(float, "float(x)");
2073UNARY(oct, "oct(x)");
2074UNARY(hex, "hex(x)");
2075
2076#undef IBINARY
2077#define IBINARY(NAME, OP) \
2078static struct wrapperbase tab_##NAME[] = { \
2079 {"__" #NAME "__", \
2080 (wrapperfunc)wrap_binaryfunc, \
2081 "x.__" #NAME "__(y) <==> " #OP}, \
2082 {0} \
2083}
2084
2085IBINARY(iadd, "x+=y");
2086IBINARY(isub, "x-=y");
2087IBINARY(imul, "x*=y");
2088IBINARY(idiv, "x/=y");
2089IBINARY(imod, "x%=y");
2090IBINARY(ilshift, "x<<=y");
2091IBINARY(irshift, "x>>=y");
2092IBINARY(iand, "x&=y");
2093IBINARY(ixor, "x^=y");
2094IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002095IBINARY(ifloordiv, "x//=y");
2096IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097
2098#undef ITERNARY
2099#define ITERNARY(NAME, OP) \
2100static struct wrapperbase tab_##NAME[] = { \
2101 {"__" #NAME "__", \
2102 (wrapperfunc)wrap_ternaryfunc, \
2103 "x.__" #NAME "__(y) <==> " #OP}, \
2104 {0} \
2105}
2106
2107ITERNARY(ipow, "x = (x**y) % z");
2108
2109static struct wrapperbase tab_getitem[] = {
2110 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2111 "x.__getitem__(y) <==> x[y]"},
2112 {0}
2113};
2114
2115static PyObject *
2116wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2117{
2118 intargfunc func = (intargfunc)wrapped;
2119 int i;
2120
2121 if (!PyArg_ParseTuple(args, "i", &i))
2122 return NULL;
2123 return (*func)(self, i);
2124}
2125
2126static struct wrapperbase tab_mul_int[] = {
2127 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2128 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2129 {0}
2130};
2131
2132static struct wrapperbase tab_concat[] = {
2133 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2134 {0}
2135};
2136
2137static struct wrapperbase tab_imul_int[] = {
2138 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2139 {0}
2140};
2141
Guido van Rossum5d815f32001-08-17 21:57:47 +00002142static int
2143getindex(PyObject *self, PyObject *arg)
2144{
2145 int i;
2146
2147 i = PyInt_AsLong(arg);
2148 if (i == -1 && PyErr_Occurred())
2149 return -1;
2150 if (i < 0) {
2151 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2152 if (sq && sq->sq_length) {
2153 int n = (*sq->sq_length)(self);
2154 if (n < 0)
2155 return -1;
2156 i += n;
2157 }
2158 }
2159 return i;
2160}
2161
2162static PyObject *
2163wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2164{
2165 intargfunc func = (intargfunc)wrapped;
2166 PyObject *arg;
2167 int i;
2168
Guido van Rossumf4593e02001-10-03 12:09:30 +00002169 if (PyTuple_GET_SIZE(args) == 1) {
2170 arg = PyTuple_GET_ITEM(args, 0);
2171 i = getindex(self, arg);
2172 if (i == -1 && PyErr_Occurred())
2173 return NULL;
2174 return (*func)(self, i);
2175 }
2176 PyArg_ParseTuple(args, "O", &arg);
2177 assert(PyErr_Occurred());
2178 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002179}
2180
Tim Peters6d6c1a32001-08-02 04:15:00 +00002181static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002182 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002183 "x.__getitem__(i) <==> x[i]"},
2184 {0}
2185};
2186
2187static PyObject *
2188wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2189{
2190 intintargfunc func = (intintargfunc)wrapped;
2191 int i, j;
2192
2193 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2194 return NULL;
2195 return (*func)(self, i, j);
2196}
2197
2198static struct wrapperbase tab_getslice[] = {
2199 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2200 "x.__getslice__(i, j) <==> x[i:j]"},
2201 {0}
2202};
2203
2204static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002205wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002206{
2207 intobjargproc func = (intobjargproc)wrapped;
2208 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002209 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002210
Guido van Rossum5d815f32001-08-17 21:57:47 +00002211 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2212 return NULL;
2213 i = getindex(self, arg);
2214 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002215 return NULL;
2216 res = (*func)(self, i, value);
2217 if (res == -1 && PyErr_Occurred())
2218 return NULL;
2219 Py_INCREF(Py_None);
2220 return Py_None;
2221}
2222
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002223static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002224wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002225{
2226 intobjargproc func = (intobjargproc)wrapped;
2227 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002228 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002229
Guido van Rossum5d815f32001-08-17 21:57:47 +00002230 if (!PyArg_ParseTuple(args, "O", &arg))
2231 return NULL;
2232 i = getindex(self, arg);
2233 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002234 return NULL;
2235 res = (*func)(self, i, NULL);
2236 if (res == -1 && PyErr_Occurred())
2237 return NULL;
2238 Py_INCREF(Py_None);
2239 return Py_None;
2240}
2241
Tim Peters6d6c1a32001-08-02 04:15:00 +00002242static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002243 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002244 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002245 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002246 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002247 {0}
2248};
2249
2250static PyObject *
2251wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2252{
2253 intintobjargproc func = (intintobjargproc)wrapped;
2254 int i, j, res;
2255 PyObject *value;
2256
2257 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2258 return NULL;
2259 res = (*func)(self, i, j, value);
2260 if (res == -1 && PyErr_Occurred())
2261 return NULL;
2262 Py_INCREF(Py_None);
2263 return Py_None;
2264}
2265
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002266static PyObject *
2267wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2268{
2269 intintobjargproc func = (intintobjargproc)wrapped;
2270 int i, j, res;
2271
2272 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2273 return NULL;
2274 res = (*func)(self, i, j, NULL);
2275 if (res == -1 && PyErr_Occurred())
2276 return NULL;
2277 Py_INCREF(Py_None);
2278 return Py_None;
2279}
2280
Tim Peters6d6c1a32001-08-02 04:15:00 +00002281static struct wrapperbase tab_setslice[] = {
2282 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2283 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002284 {"__delslice__", (wrapperfunc)wrap_delslice,
2285 "x.__delslice__(i, j) <==> del x[i:j]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002286 {0}
2287};
2288
2289/* XXX objobjproc is a misnomer; should be objargpred */
2290static PyObject *
2291wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2292{
2293 objobjproc func = (objobjproc)wrapped;
2294 int res;
2295 PyObject *value;
2296
2297 if (!PyArg_ParseTuple(args, "O", &value))
2298 return NULL;
2299 res = (*func)(self, value);
2300 if (res == -1 && PyErr_Occurred())
2301 return NULL;
2302 return PyInt_FromLong((long)res);
2303}
2304
2305static struct wrapperbase tab_contains[] = {
2306 {"__contains__", (wrapperfunc)wrap_objobjproc,
2307 "x.__contains__(y) <==> y in x"},
2308 {0}
2309};
2310
2311static PyObject *
2312wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2313{
2314 objobjargproc func = (objobjargproc)wrapped;
2315 int res;
2316 PyObject *key, *value;
2317
2318 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2319 return NULL;
2320 res = (*func)(self, key, value);
2321 if (res == -1 && PyErr_Occurred())
2322 return NULL;
2323 Py_INCREF(Py_None);
2324 return Py_None;
2325}
2326
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002327static PyObject *
2328wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2329{
2330 objobjargproc func = (objobjargproc)wrapped;
2331 int res;
2332 PyObject *key;
2333
2334 if (!PyArg_ParseTuple(args, "O", &key))
2335 return NULL;
2336 res = (*func)(self, key, NULL);
2337 if (res == -1 && PyErr_Occurred())
2338 return NULL;
2339 Py_INCREF(Py_None);
2340 return Py_None;
2341}
2342
Tim Peters6d6c1a32001-08-02 04:15:00 +00002343static struct wrapperbase tab_setitem[] = {
2344 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2345 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002346 {"__delitem__", (wrapperfunc)wrap_delitem,
2347 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002348 {0}
2349};
2350
2351static PyObject *
2352wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2353{
2354 cmpfunc func = (cmpfunc)wrapped;
2355 int res;
2356 PyObject *other;
2357
2358 if (!PyArg_ParseTuple(args, "O", &other))
2359 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002360 if (other->ob_type->tp_compare != func &&
2361 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002362 PyErr_Format(
2363 PyExc_TypeError,
2364 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2365 self->ob_type->tp_name,
2366 self->ob_type->tp_name,
2367 other->ob_type->tp_name);
2368 return NULL;
2369 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002370 res = (*func)(self, other);
2371 if (PyErr_Occurred())
2372 return NULL;
2373 return PyInt_FromLong((long)res);
2374}
2375
2376static struct wrapperbase tab_cmp[] = {
2377 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2378 "x.__cmp__(y) <==> cmp(x,y)"},
2379 {0}
2380};
2381
2382static struct wrapperbase tab_repr[] = {
2383 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2384 "x.__repr__() <==> repr(x)"},
2385 {0}
2386};
2387
2388static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002389 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2390 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002391 {0}
2392};
2393
2394static PyObject *
2395wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2396{
2397 setattrofunc func = (setattrofunc)wrapped;
2398 int res;
2399 PyObject *name, *value;
2400
2401 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2402 return NULL;
2403 res = (*func)(self, name, value);
2404 if (res < 0)
2405 return NULL;
2406 Py_INCREF(Py_None);
2407 return Py_None;
2408}
2409
2410static PyObject *
2411wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2412{
2413 setattrofunc func = (setattrofunc)wrapped;
2414 int res;
2415 PyObject *name;
2416
2417 if (!PyArg_ParseTuple(args, "O", &name))
2418 return NULL;
2419 res = (*func)(self, name, NULL);
2420 if (res < 0)
2421 return NULL;
2422 Py_INCREF(Py_None);
2423 return Py_None;
2424}
2425
2426static struct wrapperbase tab_setattr[] = {
2427 {"__setattr__", (wrapperfunc)wrap_setattr,
2428 "x.__setattr__('name', value) <==> x.name = value"},
2429 {"__delattr__", (wrapperfunc)wrap_delattr,
2430 "x.__delattr__('name') <==> del x.name"},
2431 {0}
2432};
2433
2434static PyObject *
2435wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2436{
2437 hashfunc func = (hashfunc)wrapped;
2438 long res;
2439
2440 if (!PyArg_ParseTuple(args, ""))
2441 return NULL;
2442 res = (*func)(self);
2443 if (res == -1 && PyErr_Occurred())
2444 return NULL;
2445 return PyInt_FromLong(res);
2446}
2447
2448static struct wrapperbase tab_hash[] = {
2449 {"__hash__", (wrapperfunc)wrap_hashfunc,
2450 "x.__hash__() <==> hash(x)"},
2451 {0}
2452};
2453
2454static PyObject *
2455wrap_call(PyObject *self, PyObject *args, void *wrapped)
2456{
2457 ternaryfunc func = (ternaryfunc)wrapped;
2458
2459 /* XXX What about keyword arguments? */
2460 return (*func)(self, args, NULL);
2461}
2462
2463static struct wrapperbase tab_call[] = {
2464 {"__call__", (wrapperfunc)wrap_call,
2465 "x.__call__(...) <==> x(...)"},
2466 {0}
2467};
2468
2469static struct wrapperbase tab_str[] = {
2470 {"__str__", (wrapperfunc)wrap_unaryfunc,
2471 "x.__str__() <==> str(x)"},
2472 {0}
2473};
2474
2475static PyObject *
2476wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2477{
2478 richcmpfunc func = (richcmpfunc)wrapped;
2479 PyObject *other;
2480
2481 if (!PyArg_ParseTuple(args, "O", &other))
2482 return NULL;
2483 return (*func)(self, other, op);
2484}
2485
2486#undef RICHCMP_WRAPPER
2487#define RICHCMP_WRAPPER(NAME, OP) \
2488static PyObject * \
2489richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2490{ \
2491 return wrap_richcmpfunc(self, args, wrapped, OP); \
2492}
2493
Jack Jansen8e938b42001-08-08 15:29:49 +00002494RICHCMP_WRAPPER(lt, Py_LT)
2495RICHCMP_WRAPPER(le, Py_LE)
2496RICHCMP_WRAPPER(eq, Py_EQ)
2497RICHCMP_WRAPPER(ne, Py_NE)
2498RICHCMP_WRAPPER(gt, Py_GT)
2499RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002500
2501#undef RICHCMP_ENTRY
2502#define RICHCMP_ENTRY(NAME, EXPR) \
2503 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2504 "x.__" #NAME "__(y) <==> " EXPR}
2505
2506static struct wrapperbase tab_richcmp[] = {
2507 RICHCMP_ENTRY(lt, "x<y"),
2508 RICHCMP_ENTRY(le, "x<=y"),
2509 RICHCMP_ENTRY(eq, "x==y"),
2510 RICHCMP_ENTRY(ne, "x!=y"),
2511 RICHCMP_ENTRY(gt, "x>y"),
2512 RICHCMP_ENTRY(ge, "x>=y"),
2513 {0}
2514};
2515
2516static struct wrapperbase tab_iter[] = {
2517 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2518 {0}
2519};
2520
2521static PyObject *
2522wrap_next(PyObject *self, PyObject *args, void *wrapped)
2523{
2524 unaryfunc func = (unaryfunc)wrapped;
2525 PyObject *res;
2526
2527 if (!PyArg_ParseTuple(args, ""))
2528 return NULL;
2529 res = (*func)(self);
2530 if (res == NULL && !PyErr_Occurred())
2531 PyErr_SetNone(PyExc_StopIteration);
2532 return res;
2533}
2534
2535static struct wrapperbase tab_next[] = {
2536 {"next", (wrapperfunc)wrap_next,
2537 "x.next() -> the next value, or raise StopIteration"},
2538 {0}
2539};
2540
2541static PyObject *
2542wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2543{
2544 descrgetfunc func = (descrgetfunc)wrapped;
2545 PyObject *obj;
2546 PyObject *type = NULL;
2547
2548 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2549 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002550 return (*func)(self, obj, type);
2551}
2552
2553static struct wrapperbase tab_descr_get[] = {
2554 {"__get__", (wrapperfunc)wrap_descr_get,
2555 "descr.__get__(obj, type) -> value"},
2556 {0}
2557};
2558
2559static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002560wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561{
2562 descrsetfunc func = (descrsetfunc)wrapped;
2563 PyObject *obj, *value;
2564 int ret;
2565
2566 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2567 return NULL;
2568 ret = (*func)(self, obj, value);
2569 if (ret < 0)
2570 return NULL;
2571 Py_INCREF(Py_None);
2572 return Py_None;
2573}
2574
2575static struct wrapperbase tab_descr_set[] = {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002576 {"__set__", (wrapperfunc)wrap_descr_set,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002577 "descr.__set__(obj, value)"},
2578 {0}
2579};
2580
2581static PyObject *
2582wrap_init(PyObject *self, PyObject *args, void *wrapped)
2583{
2584 initproc func = (initproc)wrapped;
2585
2586 /* XXX What about keyword arguments? */
2587 if (func(self, args, NULL) < 0)
2588 return NULL;
2589 Py_INCREF(Py_None);
2590 return Py_None;
2591}
2592
2593static struct wrapperbase tab_init[] = {
2594 {"__init__", (wrapperfunc)wrap_init,
2595 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002596 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002597 {0}
2598};
2599
2600static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002601tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002602{
Barry Warsaw60f01882001-08-22 19:24:42 +00002603 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002604 PyObject *arg0, *res;
2605
2606 if (self == NULL || !PyType_Check(self))
2607 Py_FatalError("__new__() called with non-type 'self'");
2608 type = (PyTypeObject *)self;
2609 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002610 PyErr_Format(PyExc_TypeError,
2611 "%s.__new__(): not enough arguments",
2612 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002613 return NULL;
2614 }
2615 arg0 = PyTuple_GET_ITEM(args, 0);
2616 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002617 PyErr_Format(PyExc_TypeError,
2618 "%s.__new__(X): X is not a type object (%s)",
2619 type->tp_name,
2620 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002621 return NULL;
2622 }
2623 subtype = (PyTypeObject *)arg0;
2624 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002625 PyErr_Format(PyExc_TypeError,
2626 "%s.__new__(%s): %s is not a subtype of %s",
2627 type->tp_name,
2628 subtype->tp_name,
2629 subtype->tp_name,
2630 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002631 return NULL;
2632 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002633
2634 /* Check that the use doesn't do something silly and unsafe like
2635 object.__new__(dictionary). To do this, we check that the
2636 most derived base that's not a heap type is this type. */
2637 staticbase = subtype;
2638 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2639 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002640 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002641 PyErr_Format(PyExc_TypeError,
2642 "%s.__new__(%s) is not safe, use %s.__new__()",
2643 type->tp_name,
2644 subtype->tp_name,
2645 staticbase == NULL ? "?" : staticbase->tp_name);
2646 return NULL;
2647 }
2648
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002649 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2650 if (args == NULL)
2651 return NULL;
2652 res = type->tp_new(subtype, args, kwds);
2653 Py_DECREF(args);
2654 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002655}
2656
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002657static struct PyMethodDef tp_new_methoddef[] = {
2658 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2659 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002660 {0}
2661};
2662
2663static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002664add_tp_new_wrapper(PyTypeObject *type)
2665{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002666 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002667
Guido van Rossum687ae002001-10-15 22:03:32 +00002668 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002669 return 0;
2670 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002671 if (func == NULL)
2672 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002673 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002674}
2675
Guido van Rossum13d52f02001-08-10 21:24:08 +00002676static int
2677add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2678{
Guido van Rossum687ae002001-10-15 22:03:32 +00002679 PyObject *dict = type->tp_dict;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002680
2681 for (; wraps->name != NULL; wraps++) {
2682 PyObject *descr;
2683 if (PyDict_GetItemString(dict, wraps->name))
2684 continue;
2685 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2686 if (descr == NULL)
2687 return -1;
2688 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2689 return -1;
2690 Py_DECREF(descr);
2691 }
2692 return 0;
2693}
2694
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002695/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002696 dictionary with method descriptors for function slots. For each
2697 function slot (like tp_repr) that's defined in the type, one or
Guido van Rossum687ae002001-10-15 22:03:32 +00002698 more corresponding descriptors are added in the type's tp_dict
Guido van Rossumf040ede2001-08-07 16:40:56 +00002699 dictionary under the appropriate name (like __repr__). Some
2700 function slots cause more than one descriptor to be added (for
2701 example, the nb_add slot adds both __add__ and __radd__
2702 descriptors) and some function slots compete for the same
2703 descriptor (for example both sq_item and mp_subscript generate a
2704 __getitem__ descriptor). This only adds new descriptors and
Guido van Rossum687ae002001-10-15 22:03:32 +00002705 doesn't overwrite entries in tp_dict that were previously
Guido van Rossumf040ede2001-08-07 16:40:56 +00002706 defined. The descriptors contain a reference to the C function
2707 they must call, so that it's safe if they are copied into a
2708 subtype's __dict__ and the subtype has a different C function in
2709 its slot -- calling the method defined by the descriptor will call
2710 the C function that was used to create it, rather than the C
2711 function present in the slot when it is called. (This is important
2712 because a subtype may have a C function in the slot that calls the
2713 method from the dictionary, and we want to avoid infinite recursion
2714 here.) */
2715
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002716static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717add_operators(PyTypeObject *type)
2718{
2719 PySequenceMethods *sq;
2720 PyMappingMethods *mp;
2721 PyNumberMethods *nb;
2722
2723#undef ADD
2724#define ADD(SLOT, TABLE) \
2725 if (SLOT) { \
2726 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2727 return -1; \
2728 }
2729
2730 if ((sq = type->tp_as_sequence) != NULL) {
2731 ADD(sq->sq_length, tab_len);
2732 ADD(sq->sq_concat, tab_concat);
2733 ADD(sq->sq_repeat, tab_mul_int);
2734 ADD(sq->sq_item, tab_getitem_int);
2735 ADD(sq->sq_slice, tab_getslice);
2736 ADD(sq->sq_ass_item, tab_setitem_int);
2737 ADD(sq->sq_ass_slice, tab_setslice);
2738 ADD(sq->sq_contains, tab_contains);
2739 ADD(sq->sq_inplace_concat, tab_iadd);
2740 ADD(sq->sq_inplace_repeat, tab_imul_int);
2741 }
2742
2743 if ((mp = type->tp_as_mapping) != NULL) {
2744 if (sq->sq_length == NULL)
2745 ADD(mp->mp_length, tab_len);
2746 ADD(mp->mp_subscript, tab_getitem);
2747 ADD(mp->mp_ass_subscript, tab_setitem);
2748 }
2749
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002750 if ((nb = type->tp_as_number) != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751 ADD(nb->nb_add, tab_add);
2752 ADD(nb->nb_subtract, tab_sub);
2753 ADD(nb->nb_multiply, tab_mul);
2754 ADD(nb->nb_divide, tab_div);
2755 ADD(nb->nb_remainder, tab_mod);
2756 ADD(nb->nb_divmod, tab_divmod);
2757 ADD(nb->nb_power, tab_pow);
2758 ADD(nb->nb_negative, tab_neg);
2759 ADD(nb->nb_positive, tab_pos);
2760 ADD(nb->nb_absolute, tab_abs);
2761 ADD(nb->nb_nonzero, tab_nonzero);
2762 ADD(nb->nb_invert, tab_invert);
2763 ADD(nb->nb_lshift, tab_lshift);
2764 ADD(nb->nb_rshift, tab_rshift);
2765 ADD(nb->nb_and, tab_and);
2766 ADD(nb->nb_xor, tab_xor);
2767 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002768 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769 ADD(nb->nb_int, tab_int);
2770 ADD(nb->nb_long, tab_long);
2771 ADD(nb->nb_float, tab_float);
2772 ADD(nb->nb_oct, tab_oct);
2773 ADD(nb->nb_hex, tab_hex);
2774 ADD(nb->nb_inplace_add, tab_iadd);
2775 ADD(nb->nb_inplace_subtract, tab_isub);
2776 ADD(nb->nb_inplace_multiply, tab_imul);
2777 ADD(nb->nb_inplace_divide, tab_idiv);
2778 ADD(nb->nb_inplace_remainder, tab_imod);
2779 ADD(nb->nb_inplace_power, tab_ipow);
2780 ADD(nb->nb_inplace_lshift, tab_ilshift);
2781 ADD(nb->nb_inplace_rshift, tab_irshift);
2782 ADD(nb->nb_inplace_and, tab_iand);
2783 ADD(nb->nb_inplace_xor, tab_ixor);
2784 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002785 if (type->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossum874f15a2001-09-25 21:16:33 +00002786 ADD(nb->nb_floor_divide, tab_floordiv);
2787 ADD(nb->nb_true_divide, tab_truediv);
2788 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2789 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2790 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791 }
2792
2793 ADD(type->tp_getattro, tab_getattr);
2794 ADD(type->tp_setattro, tab_setattr);
2795 ADD(type->tp_compare, tab_cmp);
2796 ADD(type->tp_repr, tab_repr);
2797 ADD(type->tp_hash, tab_hash);
2798 ADD(type->tp_call, tab_call);
2799 ADD(type->tp_str, tab_str);
2800 ADD(type->tp_richcompare, tab_richcmp);
2801 ADD(type->tp_iter, tab_iter);
2802 ADD(type->tp_iternext, tab_next);
2803 ADD(type->tp_descr_get, tab_descr_get);
2804 ADD(type->tp_descr_set, tab_descr_set);
2805 ADD(type->tp_init, tab_init);
2806
Guido van Rossumf040ede2001-08-07 16:40:56 +00002807 if (type->tp_new != NULL) {
2808 if (add_tp_new_wrapper(type) < 0)
2809 return -1;
2810 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002811
2812 return 0;
2813}
2814
Guido van Rossumf040ede2001-08-07 16:40:56 +00002815/* Slot wrappers that call the corresponding __foo__ slot. See comments
2816 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817
Guido van Rossumdc91b992001-08-08 22:26:22 +00002818#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002819static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002820FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002821{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002822 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002823 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002824}
2825
Guido van Rossumdc91b992001-08-08 22:26:22 +00002826#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002827static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002828FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002829{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002830 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002831 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002832}
2833
Guido van Rossumdc91b992001-08-08 22:26:22 +00002834
2835#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002836static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002837FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002838{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002839 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002840 int do_other = self->ob_type != other->ob_type && \
2841 other->ob_type->tp_as_number != NULL && \
2842 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002843 if (self->ob_type->tp_as_number != NULL && \
2844 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2845 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002846 if (do_other && \
2847 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2848 r = call_maybe( \
2849 other, ROPSTR, &rcache_str, "(O)", self); \
2850 if (r != Py_NotImplemented) \
2851 return r; \
2852 Py_DECREF(r); \
2853 do_other = 0; \
2854 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002855 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002856 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002857 if (r != Py_NotImplemented || \
2858 other->ob_type == self->ob_type) \
2859 return r; \
2860 Py_DECREF(r); \
2861 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002862 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002863 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002864 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002865 } \
2866 Py_INCREF(Py_NotImplemented); \
2867 return Py_NotImplemented; \
2868}
2869
2870#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2871 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2872
2873#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2874static PyObject * \
2875FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2876{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002877 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002878 return call_method(self, OPSTR, &cache_str, \
2879 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002880}
2881
2882static int
2883slot_sq_length(PyObject *self)
2884{
Guido van Rossum2730b132001-08-28 18:22:14 +00002885 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002886 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002887 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888
2889 if (res == NULL)
2890 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002891 len = (int)PyInt_AsLong(res);
2892 Py_DECREF(res);
2893 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002894}
2895
Guido van Rossumdc91b992001-08-08 22:26:22 +00002896SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2897SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002898
2899/* Super-optimized version of slot_sq_item.
2900 Other slots could do the same... */
2901static PyObject *
2902slot_sq_item(PyObject *self, int i)
2903{
2904 static PyObject *getitem_str;
2905 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2906 descrgetfunc f;
2907
2908 if (getitem_str == NULL) {
2909 getitem_str = PyString_InternFromString("__getitem__");
2910 if (getitem_str == NULL)
2911 return NULL;
2912 }
2913 func = _PyType_Lookup(self->ob_type, getitem_str);
2914 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002915 if ((f = func->ob_type->tp_descr_get) == NULL)
2916 Py_INCREF(func);
2917 else
2918 func = f(func, self, (PyObject *)(self->ob_type));
2919 ival = PyInt_FromLong(i);
2920 if (ival != NULL) {
2921 args = PyTuple_New(1);
2922 if (args != NULL) {
2923 PyTuple_SET_ITEM(args, 0, ival);
2924 retval = PyObject_Call(func, args, NULL);
2925 Py_XDECREF(args);
2926 Py_XDECREF(func);
2927 return retval;
2928 }
2929 }
2930 }
2931 else {
2932 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2933 }
2934 Py_XDECREF(args);
2935 Py_XDECREF(ival);
2936 Py_XDECREF(func);
2937 return NULL;
2938}
2939
Guido van Rossumdc91b992001-08-08 22:26:22 +00002940SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002941
2942static int
2943slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2944{
2945 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002946 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002947
2948 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002949 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002950 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002951 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002952 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002953 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002954 if (res == NULL)
2955 return -1;
2956 Py_DECREF(res);
2957 return 0;
2958}
2959
2960static int
2961slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2962{
2963 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002964 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002965
2966 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002967 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002968 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002969 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002970 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002971 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002972 if (res == NULL)
2973 return -1;
2974 Py_DECREF(res);
2975 return 0;
2976}
2977
2978static int
2979slot_sq_contains(PyObject *self, PyObject *value)
2980{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002981 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002982 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002983
Guido van Rossum55f20992001-10-01 17:18:22 +00002984 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002985
2986 if (func != NULL) {
2987 args = Py_BuildValue("(O)", value);
2988 if (args == NULL)
2989 res = NULL;
2990 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002991 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002992 Py_DECREF(args);
2993 }
2994 Py_DECREF(func);
2995 if (res == NULL)
2996 return -1;
2997 return PyObject_IsTrue(res);
2998 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002999 else if (PyErr_Occurred())
3000 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003001 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003002 return _PySequence_IterSearch(self, value,
3003 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003004 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003005}
3006
Guido van Rossumdc91b992001-08-08 22:26:22 +00003007SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3008SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003009
3010#define slot_mp_length slot_sq_length
3011
Guido van Rossumdc91b992001-08-08 22:26:22 +00003012SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003013
3014static int
3015slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3016{
3017 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003018 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003019
3020 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003021 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003022 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003024 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003025 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003026 if (res == NULL)
3027 return -1;
3028 Py_DECREF(res);
3029 return 0;
3030}
3031
Guido van Rossumdc91b992001-08-08 22:26:22 +00003032SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3033SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3034SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3035SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3036SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3037SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3038
3039staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3040
3041SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3042 nb_power, "__pow__", "__rpow__")
3043
3044static PyObject *
3045slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3046{
Guido van Rossum2730b132001-08-28 18:22:14 +00003047 static PyObject *pow_str;
3048
Guido van Rossumdc91b992001-08-08 22:26:22 +00003049 if (modulus == Py_None)
3050 return slot_nb_power_binary(self, other);
3051 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003052 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003053 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003054}
3055
3056SLOT0(slot_nb_negative, "__neg__")
3057SLOT0(slot_nb_positive, "__pos__")
3058SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003059
3060static int
3061slot_nb_nonzero(PyObject *self)
3062{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003063 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003064 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003065
Guido van Rossum55f20992001-10-01 17:18:22 +00003066 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003067 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003068 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003069 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003070 func = lookup_maybe(self, "__len__", &len_str);
3071 if (func == NULL) {
3072 if (PyErr_Occurred())
3073 return -1;
3074 else
3075 return 1;
3076 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003077 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003078 res = PyObject_CallObject(func, NULL);
3079 Py_DECREF(func);
3080 if (res == NULL)
3081 return -1;
3082 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003083}
3084
Guido van Rossumdc91b992001-08-08 22:26:22 +00003085SLOT0(slot_nb_invert, "__invert__")
3086SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3087SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3088SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3089SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3090SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003091
3092static int
3093slot_nb_coerce(PyObject **a, PyObject **b)
3094{
3095 static PyObject *coerce_str;
3096 PyObject *self = *a, *other = *b;
3097
3098 if (self->ob_type->tp_as_number != NULL &&
3099 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3100 PyObject *r;
3101 r = call_maybe(
3102 self, "__coerce__", &coerce_str, "(O)", other);
3103 if (r == NULL)
3104 return -1;
3105 if (r == Py_NotImplemented) {
3106 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003107 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003108 else {
3109 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3110 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003111 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003112 Py_DECREF(r);
3113 return -1;
3114 }
3115 *a = PyTuple_GET_ITEM(r, 0);
3116 Py_INCREF(*a);
3117 *b = PyTuple_GET_ITEM(r, 1);
3118 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003119 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003120 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003121 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003122 }
3123 if (other->ob_type->tp_as_number != NULL &&
3124 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3125 PyObject *r;
3126 r = call_maybe(
3127 other, "__coerce__", &coerce_str, "(O)", self);
3128 if (r == NULL)
3129 return -1;
3130 if (r == Py_NotImplemented) {
3131 Py_DECREF(r);
3132 return 1;
3133 }
3134 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3135 PyErr_SetString(PyExc_TypeError,
3136 "__coerce__ didn't return a 2-tuple");
3137 Py_DECREF(r);
3138 return -1;
3139 }
3140 *a = PyTuple_GET_ITEM(r, 1);
3141 Py_INCREF(*a);
3142 *b = PyTuple_GET_ITEM(r, 0);
3143 Py_INCREF(*b);
3144 Py_DECREF(r);
3145 return 0;
3146 }
3147 return 1;
3148}
3149
Guido van Rossumdc91b992001-08-08 22:26:22 +00003150SLOT0(slot_nb_int, "__int__")
3151SLOT0(slot_nb_long, "__long__")
3152SLOT0(slot_nb_float, "__float__")
3153SLOT0(slot_nb_oct, "__oct__")
3154SLOT0(slot_nb_hex, "__hex__")
3155SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3156SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3157SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3158SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3159SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3160SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3161SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3162SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3163SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3164SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3165SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3166SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3167 "__floordiv__", "__rfloordiv__")
3168SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3169SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3170SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003171
3172static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003173half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003174{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003175 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003176 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003177 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003178
Guido van Rossum60718732001-08-28 17:47:51 +00003179 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003180 if (func == NULL) {
3181 PyErr_Clear();
3182 }
3183 else {
3184 args = Py_BuildValue("(O)", other);
3185 if (args == NULL)
3186 res = NULL;
3187 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003188 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003189 Py_DECREF(args);
3190 }
3191 if (res != Py_NotImplemented) {
3192 if (res == NULL)
3193 return -2;
3194 c = PyInt_AsLong(res);
3195 Py_DECREF(res);
3196 if (c == -1 && PyErr_Occurred())
3197 return -2;
3198 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3199 }
3200 Py_DECREF(res);
3201 }
3202 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003203}
3204
Guido van Rossumab3b0342001-09-18 20:38:53 +00003205/* This slot is published for the benefit of try_3way_compare in object.c */
3206int
3207_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003208{
3209 int c;
3210
Guido van Rossumab3b0342001-09-18 20:38:53 +00003211 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003212 c = half_compare(self, other);
3213 if (c <= 1)
3214 return c;
3215 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003216 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003217 c = half_compare(other, self);
3218 if (c < -1)
3219 return -2;
3220 if (c <= 1)
3221 return -c;
3222 }
3223 return (void *)self < (void *)other ? -1 :
3224 (void *)self > (void *)other ? 1 : 0;
3225}
3226
3227static PyObject *
3228slot_tp_repr(PyObject *self)
3229{
3230 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003231 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003232
Guido van Rossum60718732001-08-28 17:47:51 +00003233 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003234 if (func != NULL) {
3235 res = PyEval_CallObject(func, NULL);
3236 Py_DECREF(func);
3237 return res;
3238 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003239 PyErr_Clear();
3240 return PyString_FromFormat("<%s object at %p>",
3241 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003242}
3243
3244static PyObject *
3245slot_tp_str(PyObject *self)
3246{
3247 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003248 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003249
Guido van Rossum60718732001-08-28 17:47:51 +00003250 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003251 if (func != NULL) {
3252 res = PyEval_CallObject(func, NULL);
3253 Py_DECREF(func);
3254 return res;
3255 }
3256 else {
3257 PyErr_Clear();
3258 return slot_tp_repr(self);
3259 }
3260}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003261
3262static long
3263slot_tp_hash(PyObject *self)
3264{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003265 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003266 static PyObject *hash_str, *eq_str, *cmp_str;
3267
Tim Peters6d6c1a32001-08-02 04:15:00 +00003268 long h;
3269
Guido van Rossum60718732001-08-28 17:47:51 +00003270 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003271
3272 if (func != NULL) {
3273 res = PyEval_CallObject(func, NULL);
3274 Py_DECREF(func);
3275 if (res == NULL)
3276 return -1;
3277 h = PyInt_AsLong(res);
3278 }
3279 else {
3280 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003281 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003282 if (func == NULL) {
3283 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003284 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003285 }
3286 if (func != NULL) {
3287 Py_DECREF(func);
3288 PyErr_SetString(PyExc_TypeError, "unhashable type");
3289 return -1;
3290 }
3291 PyErr_Clear();
3292 h = _Py_HashPointer((void *)self);
3293 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003294 if (h == -1 && !PyErr_Occurred())
3295 h = -2;
3296 return h;
3297}
3298
3299static PyObject *
3300slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3301{
Guido van Rossum60718732001-08-28 17:47:51 +00003302 static PyObject *call_str;
3303 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003304 PyObject *res;
3305
3306 if (meth == NULL)
3307 return NULL;
3308 res = PyObject_Call(meth, args, kwds);
3309 Py_DECREF(meth);
3310 return res;
3311}
3312
Guido van Rossum14a6f832001-10-17 13:59:09 +00003313/* There are two slot dispatch functions for tp_getattro.
3314
3315 - slot_tp_getattro() is used when __getattribute__ is overridden
3316 but no __getattr__ hook is present;
3317
3318 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3319
3320 The code in update_slot() and fixup_slot_dispatchers() always installs
3321 slot_tp_getattr_hook(); this detects the absence of __getattr__ and then
3322 installs the simpler slot if necessary. */
3323
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324static PyObject *
3325slot_tp_getattro(PyObject *self, PyObject *name)
3326{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003327 static PyObject *getattribute_str = NULL;
3328 return call_method(self, "__getattribute__", &getattribute_str,
3329 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003330}
3331
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003332static PyObject *
3333slot_tp_getattr_hook(PyObject *self, PyObject *name)
3334{
3335 PyTypeObject *tp = self->ob_type;
3336 PyObject *getattr, *getattribute, *res;
3337 static PyObject *getattribute_str = NULL;
3338 static PyObject *getattr_str = NULL;
3339
3340 if (getattr_str == NULL) {
3341 getattr_str = PyString_InternFromString("__getattr__");
3342 if (getattr_str == NULL)
3343 return NULL;
3344 }
3345 if (getattribute_str == NULL) {
3346 getattribute_str =
3347 PyString_InternFromString("__getattribute__");
3348 if (getattribute_str == NULL)
3349 return NULL;
3350 }
3351 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003352 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003353 /* No __getattr__ hook: use a simpler dispatcher */
3354 tp->tp_getattro = slot_tp_getattro;
3355 return slot_tp_getattro(self, name);
3356 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003357 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003358 if (getattribute == NULL ||
3359 (getattribute->ob_type == &PyWrapperDescr_Type &&
3360 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3361 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003362 res = PyObject_GenericGetAttr(self, name);
3363 else
3364 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003365 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003366 PyErr_Clear();
3367 res = PyObject_CallFunction(getattr, "OO", self, name);
3368 }
3369 return res;
3370}
3371
Tim Peters6d6c1a32001-08-02 04:15:00 +00003372static int
3373slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3374{
3375 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003376 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377
3378 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003379 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003380 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003381 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003382 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003383 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003384 if (res == NULL)
3385 return -1;
3386 Py_DECREF(res);
3387 return 0;
3388}
3389
3390/* Map rich comparison operators to their __xx__ namesakes */
3391static char *name_op[] = {
3392 "__lt__",
3393 "__le__",
3394 "__eq__",
3395 "__ne__",
3396 "__gt__",
3397 "__ge__",
3398};
3399
3400static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003401half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003402{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003403 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003404 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003405
Guido van Rossum60718732001-08-28 17:47:51 +00003406 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003407 if (func == NULL) {
3408 PyErr_Clear();
3409 Py_INCREF(Py_NotImplemented);
3410 return Py_NotImplemented;
3411 }
3412 args = Py_BuildValue("(O)", other);
3413 if (args == NULL)
3414 res = NULL;
3415 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003416 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003417 Py_DECREF(args);
3418 }
3419 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003420 return res;
3421}
3422
Guido van Rossumb8f63662001-08-15 23:57:02 +00003423/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3424static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3425
3426static PyObject *
3427slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3428{
3429 PyObject *res;
3430
3431 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3432 res = half_richcompare(self, other, op);
3433 if (res != Py_NotImplemented)
3434 return res;
3435 Py_DECREF(res);
3436 }
3437 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3438 res = half_richcompare(other, self, swapped_op[op]);
3439 if (res != Py_NotImplemented) {
3440 return res;
3441 }
3442 Py_DECREF(res);
3443 }
3444 Py_INCREF(Py_NotImplemented);
3445 return Py_NotImplemented;
3446}
3447
3448static PyObject *
3449slot_tp_iter(PyObject *self)
3450{
3451 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003452 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003453
Guido van Rossum60718732001-08-28 17:47:51 +00003454 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003455 if (func != NULL) {
3456 res = PyObject_CallObject(func, NULL);
3457 Py_DECREF(func);
3458 return res;
3459 }
3460 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003461 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003462 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003463 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003464 return NULL;
3465 }
3466 Py_DECREF(func);
3467 return PySeqIter_New(self);
3468}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003469
3470static PyObject *
3471slot_tp_iternext(PyObject *self)
3472{
Guido van Rossum2730b132001-08-28 18:22:14 +00003473 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003474 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003475}
3476
Guido van Rossum1a493502001-08-17 16:47:50 +00003477static PyObject *
3478slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3479{
3480 PyTypeObject *tp = self->ob_type;
3481 PyObject *get;
3482 static PyObject *get_str = NULL;
3483
3484 if (get_str == NULL) {
3485 get_str = PyString_InternFromString("__get__");
3486 if (get_str == NULL)
3487 return NULL;
3488 }
3489 get = _PyType_Lookup(tp, get_str);
3490 if (get == NULL) {
3491 /* Avoid further slowdowns */
3492 if (tp->tp_descr_get == slot_tp_descr_get)
3493 tp->tp_descr_get = NULL;
3494 Py_INCREF(self);
3495 return self;
3496 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003497 if (obj == NULL)
3498 obj = Py_None;
3499 if (type == NULL)
3500 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003501 return PyObject_CallFunction(get, "OOO", self, obj, type);
3502}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003503
3504static int
3505slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3506{
Guido van Rossum2c252392001-08-24 10:13:31 +00003507 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003508 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003509
3510 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003511 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003512 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003513 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003514 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003515 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003516 if (res == NULL)
3517 return -1;
3518 Py_DECREF(res);
3519 return 0;
3520}
3521
3522static int
3523slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3524{
Guido van Rossum60718732001-08-28 17:47:51 +00003525 static PyObject *init_str;
3526 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527 PyObject *res;
3528
3529 if (meth == NULL)
3530 return -1;
3531 res = PyObject_Call(meth, args, kwds);
3532 Py_DECREF(meth);
3533 if (res == NULL)
3534 return -1;
3535 Py_DECREF(res);
3536 return 0;
3537}
3538
3539static PyObject *
3540slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3541{
3542 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3543 PyObject *newargs, *x;
3544 int i, n;
3545
3546 if (func == NULL)
3547 return NULL;
3548 assert(PyTuple_Check(args));
3549 n = PyTuple_GET_SIZE(args);
3550 newargs = PyTuple_New(n+1);
3551 if (newargs == NULL)
3552 return NULL;
3553 Py_INCREF(type);
3554 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3555 for (i = 0; i < n; i++) {
3556 x = PyTuple_GET_ITEM(args, i);
3557 Py_INCREF(x);
3558 PyTuple_SET_ITEM(newargs, i+1, x);
3559 }
3560 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003561 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003562 Py_DECREF(func);
3563 return x;
3564}
3565
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003566
3567/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3568 functions. The offsets here are relative to the 'etype' structure, which
3569 incorporates the additional structures used for numbers, sequences and
3570 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3571 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3572 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3573
3574typedef struct {
3575 char *name;
3576 int offset;
3577 void *function;
3578 wrapperfunc wrapper;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003579 PyObject *name_strobj;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003580} slotdef;
3581
3582#undef TPSLOT
3583#undef ETSLOT
3584#undef SQSLOT
3585#undef MPSLOT
3586#undef NBSLOT
3587#undef BINSLOT
3588#undef RBINSLOT
3589
3590#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
Guido van Rossum825d8752001-10-15 19:44:24 +00003591 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003592#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
Guido van Rossum825d8752001-10-15 19:44:24 +00003593 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER}
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003594#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3595 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER)
3596#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3597 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER)
3598#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER) \
3599 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER)
3600#define BINSLOT(NAME, SLOT, FUNCTION) \
3601 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l)
3602#define RBINSLOT(NAME, SLOT, FUNCTION) \
3603 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r)
3604
3605static slotdef slotdefs[] = {
3606 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry),
3607 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc),
3608 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3609 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc),
3610 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item),
3611 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc),
3612 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem),
3613 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem),
3614 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
3615 wrap_intintobjargproc),
3616 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice),
3617 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc),
3618 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
3619 wrap_binaryfunc),
3620 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
3621 wrap_intargfunc),
3622
3623 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003624 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
3625 wrap_binaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003626 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
3627 wrap_objobjargproc),
3628 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
3629 wrap_delitem),
3630
3631 BINSLOT("__add__", nb_add, slot_nb_add),
3632 RBINSLOT("__radd__", nb_add, slot_nb_add),
3633 BINSLOT("__sub__", nb_subtract, slot_nb_subtract),
3634 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract),
3635 BINSLOT("__mul__", nb_multiply, slot_nb_multiply),
3636 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply),
3637 BINSLOT("__div__", nb_divide, slot_nb_divide),
3638 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide),
3639 BINSLOT("__mod__", nb_remainder, slot_nb_remainder),
3640 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder),
3641 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod),
3642 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod),
3643 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc),
3644 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r),
3645 NBSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc),
3646 NBSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc),
3647 NBSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc),
3648 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_unaryfunc),
3649 NBSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc),
3650 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift),
3651 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift),
3652 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift),
3653 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift),
3654 BINSLOT("__and__", nb_and, slot_nb_and),
3655 RBINSLOT("__rand__", nb_and, slot_nb_and),
3656 BINSLOT("__xor__", nb_xor, slot_nb_xor),
3657 RBINSLOT("__rxor__", nb_xor, slot_nb_xor),
3658 BINSLOT("__or__", nb_or, slot_nb_or),
3659 RBINSLOT("__ror__", nb_or, slot_nb_or),
3660 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc),
3661 NBSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc),
3662 NBSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc),
3663 NBSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc),
3664 NBSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc),
3665 NBSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc),
3666 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3667 wrap_binaryfunc),
3668 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3669 wrap_binaryfunc),
3670 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3671 wrap_binaryfunc),
3672 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3673 wrap_binaryfunc),
3674 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3675 wrap_binaryfunc),
3676 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3677 wrap_ternaryfunc),
3678 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3679 wrap_binaryfunc),
3680 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3681 wrap_binaryfunc),
3682 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3683 wrap_binaryfunc),
3684 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3685 wrap_binaryfunc),
3686 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3687 wrap_binaryfunc),
3688 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide),
3689 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide),
3690 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide),
3691 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide),
3692 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3693 slot_nb_inplace_floor_divide, wrap_binaryfunc),
3694 NBSLOT("__itruediv__", nb_inplace_true_divide,
3695 slot_nb_inplace_true_divide, wrap_binaryfunc),
3696
3697 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003698 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003699 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc),
3700 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc),
3701 TPSLOT("__call__", tp_call, slot_tp_call, wrap_call),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003702 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003703 wrap_binaryfunc),
3704 TPSLOT("__getattribute__", tp_getattr, NULL, NULL),
3705 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL),
3706 TPSLOT("__getattr__", tp_getattr, NULL, NULL),
3707 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr),
3708 TPSLOT("__setattr__", tp_setattr, NULL, NULL),
3709 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr),
3710 TPSLOT("__delattr__", tp_setattr, NULL, NULL),
3711 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt),
3712 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le),
3713 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq),
3714 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne),
3715 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt),
3716 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge),
3717 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc),
3718 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next),
3719 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get),
3720 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set),
3721 TPSLOT("__init__", tp_init, slot_tp_init, wrap_init),
3722 TPSLOT("__new__", tp_new, slot_tp_new, NULL),
3723 {NULL}
3724};
3725
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003726static void **
3727slotptr(PyTypeObject *type, int offset)
3728{
3729 char *ptr;
3730
3731 assert(offset >= 0);
3732 assert(offset < offsetof(etype, as_buffer));
3733 if (offset >= offsetof(etype, as_mapping)) {
3734 ptr = (void *)type->tp_as_mapping;
3735 offset -= offsetof(etype, as_mapping);
3736 }
3737 else if (offset >= offsetof(etype, as_sequence)) {
3738 ptr = (void *)type->tp_as_sequence;
3739 offset -= offsetof(etype, as_sequence);
3740 }
3741 else if (offset >= offsetof(etype, as_number)) {
3742 ptr = (void *)type->tp_as_number;
3743 offset -= offsetof(etype, as_number);
3744 }
3745 else {
3746 ptr = (void *)type;
3747 }
3748 if (ptr != NULL)
3749 ptr += offset;
3750 return (void **)ptr;
3751}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003752
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003753staticforward int recurse_down_subclasses(PyTypeObject *type,
3754 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003755
3756static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003757update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003758{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003759 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003760
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003761 for (pp = pp0; *pp; pp++) {
3762 slotdef *p = *pp;
3763 PyObject *descr;
3764 PyWrapperDescrObject *d;
3765 void *generic = NULL, *specific = NULL;
3766 int use_generic = 0;
3767 int offset = p->offset;
3768 void **ptr = slotptr(type, offset);
3769 if (ptr == NULL)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003770 continue;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003771 do {
3772 descr = _PyType_Lookup(type, p->name_strobj);
3773 if (descr == NULL)
3774 continue;
3775 generic = p->function;
3776 if (descr->ob_type == &PyWrapperDescr_Type) {
3777 d = (PyWrapperDescrObject *)descr;
3778 if (d->d_base->wrapper == p->wrapper &&
3779 PyType_IsSubtype(type, d->d_type)) {
3780 if (specific == NULL ||
3781 specific == d->d_wrapped)
3782 specific = d->d_wrapped;
3783 else
3784 use_generic = 1;
3785 }
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003786 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003787 else
3788 use_generic = 1;
3789 } while ((++p)->offset == offset);
3790 if (specific && !use_generic)
3791 *ptr = specific;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003792 else
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003793 *ptr = generic;
3794 }
3795 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003796}
3797
3798static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003799recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003800{
3801 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003802 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003803 int i, n;
3804
3805 subclasses = type->tp_subclasses;
3806 if (subclasses == NULL)
3807 return 0;
3808 assert(PyList_Check(subclasses));
3809 n = PyList_GET_SIZE(subclasses);
3810 for (i = 0; i < n; i++) {
3811 ref = PyList_GET_ITEM(subclasses, i);
3812 assert(PyWeakref_CheckRef(ref));
3813 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3814 if (subclass == NULL)
3815 continue;
3816 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003817 /* Avoid recursing down into unaffected classes */
3818 dict = subclass->tp_dict;
3819 if (dict != NULL && PyDict_Check(dict) &&
3820 PyDict_GetItem(dict, name) != NULL)
3821 continue;
3822 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003823 return -1;
3824 }
3825 return 0;
3826}
3827
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003828static int
3829slotdef_cmp(const void *aa, const void *bb)
3830{
3831 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3832 int c = a->offset - b->offset;
3833 if (c != 0)
3834 return c;
3835 else
3836 return a - b;
3837}
3838
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003839static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003840init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003841{
3842 slotdef *p;
3843 static int initialized = 0;
3844
3845 if (initialized)
3846 return;
3847 for (p = slotdefs; p->name; p++) {
3848 p->name_strobj = PyString_InternFromString(p->name);
3849 if (!p->name_strobj)
3850 Py_FatalError("XXX ouch");
3851 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003852 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3853 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003854 initialized = 1;
3855}
3856
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003857static int
3858update_slot(PyTypeObject *type, PyObject *name)
3859{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003860 slotdef *ptrs[10];
3861 slotdef *p;
3862 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003863 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003864
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003865 init_slotdefs();
3866 pp = ptrs;
3867 for (p = slotdefs; p->name; p++) {
3868 /* XXX assume name is interned! */
3869 if (p->name_strobj == name)
3870 *pp++ = p;
3871 }
3872 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003873 for (pp = ptrs; *pp; pp++) {
3874 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003875 offset = p->offset;
3876 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003877 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003878 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003879 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003880 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003881}
3882
Tim Peters6d6c1a32001-08-02 04:15:00 +00003883static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003884fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003885{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003886 slotdef *p;
3887 PyObject *mro, *descr;
3888 PyTypeObject *base;
3889 PyWrapperDescrObject *d;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003890 int i, n, offset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003891 void **ptr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003892 void *generic, *specific;
3893 int use_generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003895 init_slotdefs();
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003896 mro = type->tp_mro;
3897 assert(PyTuple_Check(mro));
3898 n = PyTuple_GET_SIZE(mro);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003899 for (p = slotdefs; p->name; ) {
3900 offset = p->offset;
3901 ptr = slotptr(type, offset);
3902 if (!ptr) {
3903 do {
3904 ++p;
3905 } while (p->offset == offset);
3906 continue;
3907 }
3908 generic = specific = NULL;
3909 use_generic = 0;
3910 do {
3911 descr = NULL;
3912 for (i = 0; i < n; i++) {
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003913 base = (PyTypeObject *)
3914 PyTuple_GET_ITEM(mro, i);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003915 assert(PyType_Check(base));
3916 descr = PyDict_GetItem(
Guido van Rossum687ae002001-10-15 22:03:32 +00003917 base->tp_dict, p->name_strobj);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003918 if (descr != NULL)
3919 break;
3920 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003921 if (descr == NULL)
3922 continue;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003923 generic = p->function;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003924 if (descr->ob_type == &PyWrapperDescr_Type) {
3925 d = (PyWrapperDescrObject *)descr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003926 if (d->d_base->wrapper == p->wrapper &&
Guido van Rossumcaf59042001-10-17 07:15:43 +00003927 PyType_IsSubtype(type, d->d_type))
3928 {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003929 if (specific == NULL ||
Guido van Rossumcaf59042001-10-17 07:15:43 +00003930 specific == d->d_wrapped)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003931 specific = d->d_wrapped;
3932 else
3933 use_generic = 1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003934 }
3935 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003936 else
3937 use_generic = 1;
3938 } while ((++p)->offset == offset);
3939 if (specific && !use_generic)
3940 *ptr = specific;
3941 else
3942 *ptr = generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003943 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003944}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003945
3946
3947/* Cooperative 'super' */
3948
3949typedef struct {
3950 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003951 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003952 PyObject *obj;
3953} superobject;
3954
Guido van Rossum6f799372001-09-20 20:46:19 +00003955static PyMemberDef super_members[] = {
3956 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3957 "the class invoking super()"},
3958 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3959 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003960 {0}
3961};
3962
Guido van Rossum705f0f52001-08-24 16:47:00 +00003963static void
3964super_dealloc(PyObject *self)
3965{
3966 superobject *su = (superobject *)self;
3967
Guido van Rossum048eb752001-10-02 21:24:57 +00003968 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003969 Py_XDECREF(su->obj);
3970 Py_XDECREF(su->type);
3971 self->ob_type->tp_free(self);
3972}
3973
3974static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003975super_repr(PyObject *self)
3976{
3977 superobject *su = (superobject *)self;
3978
3979 if (su->obj)
3980 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003981 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003982 su->type ? su->type->tp_name : "NULL",
3983 su->obj->ob_type->tp_name);
3984 else
3985 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003986 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003987 su->type ? su->type->tp_name : "NULL");
3988}
3989
3990static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003991super_getattro(PyObject *self, PyObject *name)
3992{
3993 superobject *su = (superobject *)self;
3994
3995 if (su->obj != NULL) {
3996 PyObject *mro, *res, *tmp;
3997 descrgetfunc f;
3998 int i, n;
3999
Guido van Rossume705ef12001-08-29 15:47:06 +00004000 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004001 if (mro == NULL)
4002 n = 0;
4003 else {
4004 assert(PyTuple_Check(mro));
4005 n = PyTuple_GET_SIZE(mro);
4006 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004007 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004008 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004009 break;
4010 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004011 if (i >= n && PyType_Check(su->obj)) {
4012 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004013 if (mro == NULL)
4014 n = 0;
4015 else {
4016 assert(PyTuple_Check(mro));
4017 n = PyTuple_GET_SIZE(mro);
4018 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004019 for (i = 0; i < n; i++) {
4020 if ((PyObject *)(su->type) ==
4021 PyTuple_GET_ITEM(mro, i))
4022 break;
4023 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004024 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004025 i++;
4026 res = NULL;
4027 for (; i < n; i++) {
4028 tmp = PyTuple_GET_ITEM(mro, i);
4029 assert(PyType_Check(tmp));
4030 res = PyDict_GetItem(
Guido van Rossum687ae002001-10-15 22:03:32 +00004031 ((PyTypeObject *)tmp)->tp_dict, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004032 if (res != NULL) {
4033 Py_INCREF(res);
4034 f = res->ob_type->tp_descr_get;
4035 if (f != NULL) {
4036 tmp = f(res, su->obj, res);
4037 Py_DECREF(res);
4038 res = tmp;
4039 }
4040 return res;
4041 }
4042 }
4043 }
4044 return PyObject_GenericGetAttr(self, name);
4045}
4046
4047static PyObject *
4048super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4049{
4050 superobject *su = (superobject *)self;
4051 superobject *new;
4052
4053 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4054 /* Not binding to an object, or already bound */
4055 Py_INCREF(self);
4056 return self;
4057 }
4058 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
4059 if (new == NULL)
4060 return NULL;
4061 Py_INCREF(su->type);
4062 Py_INCREF(obj);
4063 new->type = su->type;
4064 new->obj = obj;
4065 return (PyObject *)new;
4066}
4067
4068static int
4069super_init(PyObject *self, PyObject *args, PyObject *kwds)
4070{
4071 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004072 PyTypeObject *type;
4073 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004074
4075 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4076 return -1;
4077 if (obj == Py_None)
4078 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00004079 if (obj != NULL &&
4080 !PyType_IsSubtype(obj->ob_type, type) &&
4081 !(PyType_Check(obj) &&
4082 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004083 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00004084 "super(type, obj): "
4085 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00004086 return -1;
4087 }
4088 Py_INCREF(type);
4089 Py_XINCREF(obj);
4090 su->type = type;
4091 su->obj = obj;
4092 return 0;
4093}
4094
4095static char super_doc[] =
4096"super(type) -> unbound super object\n"
4097"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004098"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004099"Typical use to call a cooperative superclass method:\n"
4100"class C(B):\n"
4101" def meth(self, arg):\n"
4102" super(C, self).meth(arg)";
4103
Guido van Rossum048eb752001-10-02 21:24:57 +00004104static int
4105super_traverse(PyObject *self, visitproc visit, void *arg)
4106{
4107 superobject *su = (superobject *)self;
4108 int err;
4109
4110#define VISIT(SLOT) \
4111 if (SLOT) { \
4112 err = visit((PyObject *)(SLOT), arg); \
4113 if (err) \
4114 return err; \
4115 }
4116
4117 VISIT(su->obj);
4118 VISIT(su->type);
4119
4120#undef VISIT
4121
4122 return 0;
4123}
4124
Guido van Rossum705f0f52001-08-24 16:47:00 +00004125PyTypeObject PySuper_Type = {
4126 PyObject_HEAD_INIT(&PyType_Type)
4127 0, /* ob_size */
4128 "super", /* tp_name */
4129 sizeof(superobject), /* tp_basicsize */
4130 0, /* tp_itemsize */
4131 /* methods */
4132 super_dealloc, /* tp_dealloc */
4133 0, /* tp_print */
4134 0, /* tp_getattr */
4135 0, /* tp_setattr */
4136 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004137 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004138 0, /* tp_as_number */
4139 0, /* tp_as_sequence */
4140 0, /* tp_as_mapping */
4141 0, /* tp_hash */
4142 0, /* tp_call */
4143 0, /* tp_str */
4144 super_getattro, /* tp_getattro */
4145 0, /* tp_setattro */
4146 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004147 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4148 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004149 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004150 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004151 0, /* tp_clear */
4152 0, /* tp_richcompare */
4153 0, /* tp_weaklistoffset */
4154 0, /* tp_iter */
4155 0, /* tp_iternext */
4156 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004157 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004158 0, /* tp_getset */
4159 0, /* tp_base */
4160 0, /* tp_dict */
4161 super_descr_get, /* tp_descr_get */
4162 0, /* tp_descr_set */
4163 0, /* tp_dictoffset */
4164 super_init, /* tp_init */
4165 PyType_GenericAlloc, /* tp_alloc */
4166 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004167 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004168};