blob: 65267d3338da8318c56be69fcc3bf2c962b513d8 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Type object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum6f799372001-09-20 20:46:19 +00007static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00008 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
9 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
10 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
11 {"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
17 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
18 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
25 char *s;
26
27 s = strrchr(type->tp_name, '.');
28 if (s == NULL)
29 s = type->tp_name;
30 else
31 s++;
32 return PyString_FromString(s);
33}
34
35static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000036type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000037{
Guido van Rossumc3542212001-08-16 09:18:56 +000038 PyObject *mod;
39 char *s;
40
41 s = strrchr(type->tp_name, '.');
42 if (s != NULL)
43 return PyString_FromStringAndSize(type->tp_name,
44 (int)(s - type->tp_name));
45 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
46 return PyString_FromString("__builtin__");
47 mod = PyDict_GetItemString(type->tp_defined, "__module__");
48 if (mod != NULL && PyString_Check(mod)) {
49 Py_INCREF(mod);
50 return mod;
51 }
52 PyErr_SetString(PyExc_AttributeError, "__module__");
53 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000054}
55
Guido van Rossum3926a632001-09-25 16:25:58 +000056static int
57type_set_module(PyTypeObject *type, PyObject *value, void *context)
58{
59 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ||
60 strrchr(type->tp_name, '.')) {
61 PyErr_Format(PyExc_TypeError,
62 "can't set %s.__module__", type->tp_name);
63 return -1;
64 }
65 if (!value) {
66 PyErr_Format(PyExc_TypeError,
67 "can't delete %s.__module__", type->tp_name);
68 return -1;
69 }
70 return PyDict_SetItemString(type->tp_dict, "__module__", value);
71}
72
Tim Peters6d6c1a32001-08-02 04:15:00 +000073static PyObject *
74type_dict(PyTypeObject *type, void *context)
75{
76 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077 Py_INCREF(Py_None);
78 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000079 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000080 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
81 Py_INCREF(type->tp_dict);
82 return type->tp_dict;
83 }
84 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000085}
86
Tim Peters6d6c1a32001-08-02 04:15:00 +000087static PyObject *
88type_defined(PyTypeObject *type, void *context)
89{
90 if (type->tp_defined == NULL) {
91 Py_INCREF(Py_None);
92 return Py_None;
93 }
94 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
95 Py_INCREF(type->tp_defined);
96 return type->tp_defined;
97 }
98 return PyDictProxy_New(type->tp_defined);
99}
100
101static PyObject *
102type_dynamic(PyTypeObject *type, void *context)
103{
104 PyObject *res;
105
106 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
107 Py_INCREF(res);
108 return res;
109}
110
Guido van Rossum32d34c82001-09-20 21:45:26 +0000111PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000112 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000113 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000114 {"__dict__", (getter)type_dict, NULL, NULL},
115 {"__defined__", (getter)type_defined, NULL, NULL},
116 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
117 {0}
118};
119
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000120static int
121type_compare(PyObject *v, PyObject *w)
122{
123 /* This is called with type objects only. So we
124 can just compare the addresses. */
125 Py_uintptr_t vv = (Py_uintptr_t)v;
126 Py_uintptr_t ww = (Py_uintptr_t)w;
127 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
128}
129
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000131type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000133 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000134 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000135
136 mod = type_module(type, NULL);
137 if (mod == NULL)
138 PyErr_Clear();
139 else if (!PyString_Check(mod)) {
140 Py_DECREF(mod);
141 mod = NULL;
142 }
143 name = type_name(type, NULL);
144 if (name == NULL)
145 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000146
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000147 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
148 kind = "class";
149 else
150 kind = "type";
151
Barry Warsaw7ce36942001-08-24 18:34:26 +0000152 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000153 rtn = PyString_FromFormat("<%s '%s.%s'>",
154 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000155 PyString_AS_STRING(mod),
156 PyString_AS_STRING(name));
157 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000158 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000159 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000160
Guido van Rossumc3542212001-08-16 09:18:56 +0000161 Py_XDECREF(mod);
162 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000163 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
Tim Peters6d6c1a32001-08-02 04:15:00 +0000166static PyObject *
167type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
168{
169 PyObject *obj;
170
171 if (type->tp_new == NULL) {
172 PyErr_Format(PyExc_TypeError,
173 "cannot create '%.100s' instances",
174 type->tp_name);
175 return NULL;
176 }
177
Tim Peters3f996e72001-09-13 19:18:27 +0000178 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 if (obj != NULL) {
180 type = obj->ob_type;
181 if (type->tp_init != NULL &&
182 type->tp_init(obj, args, kwds) < 0) {
183 Py_DECREF(obj);
184 obj = NULL;
185 }
186 }
187 return obj;
188}
189
190PyObject *
191PyType_GenericAlloc(PyTypeObject *type, int nitems)
192{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000193 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000194 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000195
196 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000197 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000198 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000199 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000200
Neil Schemenauerc806c882001-08-29 23:54:54 +0000201 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000202 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000203
Neil Schemenauerc806c882001-08-29 23:54:54 +0000204 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000205
Tim Peters6d6c1a32001-08-02 04:15:00 +0000206 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
207 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000208
Tim Peters6d6c1a32001-08-02 04:15:00 +0000209 if (type->tp_itemsize == 0)
210 PyObject_INIT(obj, type);
211 else
212 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000213
Tim Peters6d6c1a32001-08-02 04:15:00 +0000214 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000215 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000216 return obj;
217}
218
219PyObject *
220PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
221{
222 return type->tp_alloc(type, 0);
223}
224
Guido van Rossum9475a232001-10-05 20:51:39 +0000225/* Helpers for subtyping */
226
227static int
228subtype_traverse(PyObject *self, visitproc visit, void *arg)
229{
230 PyTypeObject *type, *base;
231 traverseproc f;
232 int err;
233
234 /* Find the nearest base with a different tp_traverse */
235 type = self->ob_type;
236 base = type->tp_base;
237 while ((f = base->tp_traverse) == subtype_traverse) {
238 base = base->tp_base;
239 assert(base);
240 }
241
242 if (type->tp_dictoffset != base->tp_dictoffset) {
243 PyObject **dictptr = _PyObject_GetDictPtr(self);
244 if (dictptr && *dictptr) {
245 err = visit(*dictptr, arg);
246 if (err)
247 return err;
248 }
249 }
250
251 if (f)
252 return f(self, visit, arg);
253 return 0;
254}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000255
256static void
257subtype_dealloc(PyObject *self)
258{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000259 PyTypeObject *type, *base;
260 destructor f;
261
262 /* This exists so we can DECREF self->ob_type */
263
264 /* Find the nearest base with a different tp_dealloc */
265 type = self->ob_type;
266 base = type->tp_base;
267 while ((f = base->tp_dealloc) == subtype_dealloc) {
268 base = base->tp_base;
269 assert(base);
270 }
271
272 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000273 if (type->tp_dictoffset && !base->tp_dictoffset) {
274 PyObject **dictptr = _PyObject_GetDictPtr(self);
275 if (dictptr != NULL) {
276 PyObject *dict = *dictptr;
277 if (dict != NULL) {
278 Py_DECREF(dict);
279 *dictptr = NULL;
280 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000281 }
282 }
283
Guido van Rossum9676b222001-08-17 20:32:36 +0000284 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000285 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000286 PyObject_ClearWeakRefs(self);
287
Tim Peters6d6c1a32001-08-02 04:15:00 +0000288 /* Finalize GC if the base doesn't do GC and we do */
289 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000290 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000291
292 /* Call the base tp_dealloc() */
293 assert(f);
294 f(self);
295
296 /* Can't reference self beyond this point */
297 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
298 Py_DECREF(type);
299 }
300}
301
302staticforward void override_slots(PyTypeObject *type, PyObject *dict);
303staticforward PyTypeObject *solid_base(PyTypeObject *type);
304
305typedef struct {
306 PyTypeObject type;
307 PyNumberMethods as_number;
308 PySequenceMethods as_sequence;
309 PyMappingMethods as_mapping;
310 PyBufferProcs as_buffer;
311 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000312 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000313} etype;
314
315/* type test with subclassing support */
316
317int
318PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
319{
320 PyObject *mro;
321
Guido van Rossum9478d072001-09-07 18:52:13 +0000322 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
323 return b == a || b == &PyBaseObject_Type;
324
Tim Peters6d6c1a32001-08-02 04:15:00 +0000325 mro = a->tp_mro;
326 if (mro != NULL) {
327 /* Deal with multiple inheritance without recursion
328 by walking the MRO tuple */
329 int i, n;
330 assert(PyTuple_Check(mro));
331 n = PyTuple_GET_SIZE(mro);
332 for (i = 0; i < n; i++) {
333 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
334 return 1;
335 }
336 return 0;
337 }
338 else {
339 /* a is not completely initilized yet; follow tp_base */
340 do {
341 if (a == b)
342 return 1;
343 a = a->tp_base;
344 } while (a != NULL);
345 return b == &PyBaseObject_Type;
346 }
347}
348
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000349/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000350 without looking in the instance dictionary
351 (so we can't use PyObject_GetAttr) but still binding
352 it to the instance. The arguments are the object,
353 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000354 static variable used to cache the interned Python string.
355
356 Two variants:
357
358 - lookup_maybe() returns NULL without raising an exception
359 when the _PyType_Lookup() call fails;
360
361 - lookup_method() always raises an exception upon errors.
362*/
Guido van Rossum60718732001-08-28 17:47:51 +0000363
364static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000365lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000366{
367 PyObject *res;
368
369 if (*attrobj == NULL) {
370 *attrobj = PyString_InternFromString(attrstr);
371 if (*attrobj == NULL)
372 return NULL;
373 }
374 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000375 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000376 descrgetfunc f;
377 if ((f = res->ob_type->tp_descr_get) == NULL)
378 Py_INCREF(res);
379 else
380 res = f(res, self, (PyObject *)(self->ob_type));
381 }
382 return res;
383}
384
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000385static PyObject *
386lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
387{
388 PyObject *res = lookup_maybe(self, attrstr, attrobj);
389 if (res == NULL && !PyErr_Occurred())
390 PyErr_SetObject(PyExc_AttributeError, *attrobj);
391 return res;
392}
393
Guido van Rossum2730b132001-08-28 18:22:14 +0000394/* A variation of PyObject_CallMethod that uses lookup_method()
395 instead of PyObject_GetAttrString(). This uses the same convention
396 as lookup_method to cache the interned name string object. */
397
398PyObject *
399call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
400{
401 va_list va;
402 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000403 va_start(va, format);
404
Guido van Rossumda21c012001-10-03 00:50:18 +0000405 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000406 if (func == NULL) {
407 va_end(va);
408 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000409 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000410 return NULL;
411 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000412
413 if (format && *format)
414 args = Py_VaBuildValue(format, va);
415 else
416 args = PyTuple_New(0);
417
418 va_end(va);
419
420 if (args == NULL)
421 return NULL;
422
423 assert(PyTuple_Check(args));
424 retval = PyObject_Call(func, args, NULL);
425
426 Py_DECREF(args);
427 Py_DECREF(func);
428
429 return retval;
430}
431
432/* Clone of call_method() that returns NotImplemented when the lookup fails. */
433
434PyObject *
435call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
436{
437 va_list va;
438 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000439 va_start(va, format);
440
Guido van Rossumda21c012001-10-03 00:50:18 +0000441 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000442 if (func == NULL) {
443 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000444 if (!PyErr_Occurred()) {
445 Py_INCREF(Py_NotImplemented);
446 return Py_NotImplemented;
447 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000448 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000449 }
450
451 if (format && *format)
452 args = Py_VaBuildValue(format, va);
453 else
454 args = PyTuple_New(0);
455
456 va_end(va);
457
Guido van Rossum717ce002001-09-14 16:58:08 +0000458 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000459 return NULL;
460
Guido van Rossum717ce002001-09-14 16:58:08 +0000461 assert(PyTuple_Check(args));
462 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000463
464 Py_DECREF(args);
465 Py_DECREF(func);
466
467 return retval;
468}
469
Tim Peters6d6c1a32001-08-02 04:15:00 +0000470/* Method resolution order algorithm from "Putting Metaclasses to Work"
471 by Forman and Danforth (Addison-Wesley 1999). */
472
473static int
474conservative_merge(PyObject *left, PyObject *right)
475{
476 int left_size;
477 int right_size;
478 int i, j, r, ok;
479 PyObject *temp, *rr;
480
481 assert(PyList_Check(left));
482 assert(PyList_Check(right));
483
484 again:
485 left_size = PyList_GET_SIZE(left);
486 right_size = PyList_GET_SIZE(right);
487 for (i = 0; i < left_size; i++) {
488 for (j = 0; j < right_size; j++) {
489 if (PyList_GET_ITEM(left, i) ==
490 PyList_GET_ITEM(right, j)) {
491 /* found a merge point */
492 temp = PyList_New(0);
493 if (temp == NULL)
494 return -1;
495 for (r = 0; r < j; r++) {
496 rr = PyList_GET_ITEM(right, r);
497 ok = PySequence_Contains(left, rr);
498 if (ok < 0) {
499 Py_DECREF(temp);
500 return -1;
501 }
502 if (!ok) {
503 ok = PyList_Append(temp, rr);
504 if (ok < 0) {
505 Py_DECREF(temp);
506 return -1;
507 }
508 }
509 }
510 ok = PyList_SetSlice(left, i, i, temp);
511 Py_DECREF(temp);
512 if (ok < 0)
513 return -1;
514 ok = PyList_SetSlice(right, 0, j+1, NULL);
515 if (ok < 0)
516 return -1;
517 goto again;
518 }
519 }
520 }
521 return PyList_SetSlice(left, left_size, left_size, right);
522}
523
524static int
525serious_order_disagreements(PyObject *left, PyObject *right)
526{
527 return 0; /* XXX later -- for now, we cheat: "don't do that" */
528}
529
530static PyObject *
531mro_implementation(PyTypeObject *type)
532{
533 int i, n, ok;
534 PyObject *bases, *result;
535
536 bases = type->tp_bases;
537 n = PyTuple_GET_SIZE(bases);
538 result = Py_BuildValue("[O]", (PyObject *)type);
539 if (result == NULL)
540 return NULL;
541 for (i = 0; i < n; i++) {
542 PyTypeObject *base =
543 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
544 PyObject *parentMRO = PySequence_List(base->tp_mro);
545 if (parentMRO == NULL) {
546 Py_DECREF(result);
547 return NULL;
548 }
549 if (serious_order_disagreements(result, parentMRO)) {
550 Py_DECREF(result);
551 return NULL;
552 }
553 ok = conservative_merge(result, parentMRO);
554 Py_DECREF(parentMRO);
555 if (ok < 0) {
556 Py_DECREF(result);
557 return NULL;
558 }
559 }
560 return result;
561}
562
563static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000564mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000565{
566 PyTypeObject *type = (PyTypeObject *)self;
567
Tim Peters6d6c1a32001-08-02 04:15:00 +0000568 return mro_implementation(type);
569}
570
571static int
572mro_internal(PyTypeObject *type)
573{
574 PyObject *mro, *result, *tuple;
575
576 if (type->ob_type == &PyType_Type) {
577 result = mro_implementation(type);
578 }
579 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000580 static PyObject *mro_str;
581 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000582 if (mro == NULL)
583 return -1;
584 result = PyObject_CallObject(mro, NULL);
585 Py_DECREF(mro);
586 }
587 if (result == NULL)
588 return -1;
589 tuple = PySequence_Tuple(result);
590 Py_DECREF(result);
591 type->tp_mro = tuple;
592 return 0;
593}
594
595
596/* Calculate the best base amongst multiple base classes.
597 This is the first one that's on the path to the "solid base". */
598
599static PyTypeObject *
600best_base(PyObject *bases)
601{
602 int i, n;
603 PyTypeObject *base, *winner, *candidate, *base_i;
604
605 assert(PyTuple_Check(bases));
606 n = PyTuple_GET_SIZE(bases);
607 assert(n > 0);
608 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
609 winner = &PyBaseObject_Type;
610 for (i = 0; i < n; i++) {
611 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
612 if (!PyType_Check((PyObject *)base_i)) {
613 PyErr_SetString(
614 PyExc_TypeError,
615 "bases must be types");
616 return NULL;
617 }
618 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000619 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000620 return NULL;
621 }
622 candidate = solid_base(base_i);
623 if (PyType_IsSubtype(winner, candidate))
624 ;
625 else if (PyType_IsSubtype(candidate, winner)) {
626 winner = candidate;
627 base = base_i;
628 }
629 else {
630 PyErr_SetString(
631 PyExc_TypeError,
632 "multiple bases have "
633 "instance lay-out conflict");
634 return NULL;
635 }
636 }
637 assert(base != NULL);
638 return base;
639}
640
641static int
642extra_ivars(PyTypeObject *type, PyTypeObject *base)
643{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000644 size_t t_size = type->tp_basicsize;
645 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000646
Guido van Rossum9676b222001-08-17 20:32:36 +0000647 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000648 if (type->tp_itemsize || base->tp_itemsize) {
649 /* If itemsize is involved, stricter rules */
650 return t_size != b_size ||
651 type->tp_itemsize != base->tp_itemsize;
652 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000653 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
654 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
655 t_size -= sizeof(PyObject *);
656 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
657 type->tp_dictoffset + sizeof(PyObject *) == t_size)
658 t_size -= sizeof(PyObject *);
659
660 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000661}
662
663static PyTypeObject *
664solid_base(PyTypeObject *type)
665{
666 PyTypeObject *base;
667
668 if (type->tp_base)
669 base = solid_base(type->tp_base);
670 else
671 base = &PyBaseObject_Type;
672 if (extra_ivars(type, base))
673 return type;
674 else
675 return base;
676}
677
678staticforward void object_dealloc(PyObject *);
679staticforward int object_init(PyObject *, PyObject *, PyObject *);
680
681static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000682subtype_dict(PyObject *obj, void *context)
683{
684 PyObject **dictptr = _PyObject_GetDictPtr(obj);
685 PyObject *dict;
686
687 if (dictptr == NULL) {
688 PyErr_SetString(PyExc_AttributeError,
689 "This object has no __dict__");
690 return NULL;
691 }
692 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000693 if (dict == NULL)
694 *dictptr = dict = PyDict_New();
695 Py_XINCREF(dict);
696 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000697}
698
Guido van Rossum32d34c82001-09-20 21:45:26 +0000699PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000700 {"__dict__", subtype_dict, NULL, NULL},
701 {0},
702};
703
704static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000705type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
706{
707 PyObject *name, *bases, *dict;
708 static char *kwlist[] = {"name", "bases", "dict", 0};
709 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000710 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000711 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000712 PyMemberDef *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000713 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000714
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000715 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000716 if (metatype == &PyType_Type &&
717 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
718 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000719 PyObject *x = PyTuple_GET_ITEM(args, 0);
720 Py_INCREF(x->ob_type);
721 return (PyObject *) x->ob_type;
722 }
723
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000724 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000725 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
726 &name,
727 &PyTuple_Type, &bases,
728 &PyDict_Type, &dict))
729 return NULL;
730
731 /* Determine the proper metatype to deal with this,
732 and check for metatype conflicts while we're at it.
733 Note that if some other metatype wins to contract,
734 it's possible that its instances are not types. */
735 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000736 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000737 for (i = 0; i < nbases; i++) {
738 tmp = PyTuple_GET_ITEM(bases, i);
739 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000740 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000742 if (PyType_IsSubtype(tmptype, winner)) {
743 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000744 continue;
745 }
746 PyErr_SetString(PyExc_TypeError,
747 "metatype conflict among bases");
748 return NULL;
749 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000750 if (winner != metatype) {
751 if (winner->tp_new != type_new) /* Pass it to the winner */
752 return winner->tp_new(winner, args, kwds);
753 metatype = winner;
754 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000755
756 /* Adjust for empty tuple bases */
757 if (nbases == 0) {
758 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
759 if (bases == NULL)
760 return NULL;
761 nbases = 1;
762 }
763 else
764 Py_INCREF(bases);
765
766 /* XXX From here until type is allocated, "return NULL" leaks bases! */
767
768 /* Calculate best base, and check that all bases are type objects */
769 base = best_base(bases);
770 if (base == NULL)
771 return NULL;
772 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
773 PyErr_Format(PyExc_TypeError,
774 "type '%.100s' is not an acceptable base type",
775 base->tp_name);
776 return NULL;
777 }
778
Guido van Rossum1a493502001-08-17 16:47:50 +0000779 /* Should this be a dynamic class (i.e. modifiable __dict__)?
780 Look in two places for a variable named __dynamic__:
781 1) in the class dict
782 2) in the module dict (globals)
783 The first variable that is an int >= 0 is used.
Guido van Rossum50fda3b2001-10-04 19:46:06 +0000784 Otherwise, the default is dynamic. */
Guido van Rossum1a493502001-08-17 16:47:50 +0000785 dynamic = -1; /* Not yet determined */
786 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000787 tmp = PyDict_GetItemString(dict, "__dynamic__");
788 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000789 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000790 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000791 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000792 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000793 if (dynamic < 0) {
794 /* Look in the module globals */
795 tmp = PyEval_GetGlobals();
796 if (tmp != NULL) {
797 tmp = PyDict_GetItemString(tmp, "__dynamic__");
798 if (tmp != NULL) {
799 dynamic = PyInt_AsLong(tmp);
800 if (dynamic < 0)
801 PyErr_Clear();
802 }
803 }
804 }
805 if (dynamic < 0) {
Guido van Rossum50fda3b2001-10-04 19:46:06 +0000806 /* Default to dynamic */
807 dynamic = 1;
808
Tim Peters6d6c1a32001-08-02 04:15:00 +0000809 }
810
811 /* Check for a __slots__ sequence variable in dict, and count it */
812 slots = PyDict_GetItemString(dict, "__slots__");
813 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000814 add_dict = 0;
815 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000816 if (slots != NULL) {
817 /* Make it into a tuple */
818 if (PyString_Check(slots))
819 slots = Py_BuildValue("(O)", slots);
820 else
821 slots = PySequence_Tuple(slots);
822 if (slots == NULL)
823 return NULL;
824 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000825 if (nslots > 0 && base->tp_itemsize != 0) {
826 PyErr_Format(PyExc_TypeError,
827 "nonempty __slots__ "
828 "not supported for subtype of '%s'",
829 base->tp_name);
830 return NULL;
831 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000832 for (i = 0; i < nslots; i++) {
833 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
834 PyErr_SetString(PyExc_TypeError,
835 "__slots__ must be a sequence of strings");
836 Py_DECREF(slots);
837 return NULL;
838 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000839 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000840 }
841 }
842 if (slots == NULL && base->tp_dictoffset == 0 &&
843 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000844 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000845 add_dict++;
846 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000847 if (slots == NULL && base->tp_weaklistoffset == 0 &&
848 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000849 nslots++;
850 add_weak++;
851 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852
853 /* XXX From here until type is safely allocated,
854 "return NULL" may leak slots! */
855
856 /* Allocate the type object */
857 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
858 if (type == NULL)
859 return NULL;
860
861 /* Keep name and slots alive in the extended type object */
862 et = (etype *)type;
863 Py_INCREF(name);
864 et->name = name;
865 et->slots = slots;
866
Guido van Rossumdc91b992001-08-08 22:26:22 +0000867 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
869 Py_TPFLAGS_BASETYPE;
870 if (dynamic)
871 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000872 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
873 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000874
875 /* It's a new-style number unless it specifically inherits any
876 old-style numeric behavior */
877 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
878 (base->tp_as_number == NULL))
879 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
880
881 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000882 type->tp_as_number = &et->as_number;
883 type->tp_as_sequence = &et->as_sequence;
884 type->tp_as_mapping = &et->as_mapping;
885 type->tp_as_buffer = &et->as_buffer;
886 type->tp_name = PyString_AS_STRING(name);
887
888 /* Set tp_base and tp_bases */
889 type->tp_bases = bases;
890 Py_INCREF(base);
891 type->tp_base = base;
892
893 /* Initialize tp_defined from passed-in dict */
894 type->tp_defined = dict = PyDict_Copy(dict);
895 if (dict == NULL) {
896 Py_DECREF(type);
897 return NULL;
898 }
899
Guido van Rossumc3542212001-08-16 09:18:56 +0000900 /* Set __module__ in the dict */
901 if (PyDict_GetItemString(dict, "__module__") == NULL) {
902 tmp = PyEval_GetGlobals();
903 if (tmp != NULL) {
904 tmp = PyDict_GetItemString(tmp, "__name__");
905 if (tmp != NULL) {
906 if (PyDict_SetItemString(dict, "__module__",
907 tmp) < 0)
908 return NULL;
909 }
910 }
911 }
912
Tim Peters2f93e282001-10-04 05:27:00 +0000913 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
914 and is a string (tp_doc is a char* -- can't copy a general object
915 into it).
916 XXX What if it's a Unicode string? Don't know -- this ignores it.
917 */
918 {
919 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
920 if (doc != NULL && PyString_Check(doc)) {
921 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +0000922 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +0000923 if (type->tp_doc == NULL) {
924 Py_DECREF(type);
925 return NULL;
926 }
927 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
928 }
929 }
930
Tim Peters6d6c1a32001-08-02 04:15:00 +0000931 /* Special-case __new__: if it's a plain function,
932 make it a static function */
933 tmp = PyDict_GetItemString(dict, "__new__");
934 if (tmp != NULL && PyFunction_Check(tmp)) {
935 tmp = PyStaticMethod_New(tmp);
936 if (tmp == NULL) {
937 Py_DECREF(type);
938 return NULL;
939 }
940 PyDict_SetItemString(dict, "__new__", tmp);
941 Py_DECREF(tmp);
942 }
943
944 /* Add descriptors for custom slots from __slots__, or for __dict__ */
945 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000946 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000947 if (slots != NULL) {
948 for (i = 0; i < nslots; i++, mp++) {
949 mp->name = PyString_AS_STRING(
950 PyTuple_GET_ITEM(slots, i));
951 mp->type = T_OBJECT;
952 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000953 if (base->tp_weaklistoffset == 0 &&
954 strcmp(mp->name, "__weakref__") == 0)
955 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000956 slotoffset += sizeof(PyObject *);
957 }
958 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000959 else {
960 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000961 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +0000962 type->tp_dictoffset =
963 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000964 else
965 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000966 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000967 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000968 }
969 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000970 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000971 type->tp_weaklistoffset = slotoffset;
972 mp->name = "__weakref__";
973 mp->type = T_OBJECT;
974 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000975 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000976 mp++;
977 slotoffset += sizeof(PyObject *);
978 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000979 }
980 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000981 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000982 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000983
984 /* Special case some slots */
985 if (type->tp_dictoffset != 0 || nslots > 0) {
986 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
987 type->tp_getattro = PyObject_GenericGetAttr;
988 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
989 type->tp_setattro = PyObject_GenericSetAttr;
990 }
991 type->tp_dealloc = subtype_dealloc;
992
Guido van Rossum9475a232001-10-05 20:51:39 +0000993 /* Enable GC unless there are really no instance variables possible */
994 if (!(type->tp_basicsize == sizeof(PyObject) &&
995 type->tp_itemsize == 0))
996 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
997
Tim Peters6d6c1a32001-08-02 04:15:00 +0000998 /* Always override allocation strategy to use regular heap */
999 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001000 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1001 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001002 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001003 type->tp_clear = base->tp_clear;
1004 }
1005 else
1006 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007
1008 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001009 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001010 Py_DECREF(type);
1011 return NULL;
1012 }
1013
1014 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +00001015 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
1016 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001017
Tim Peters6d6c1a32001-08-02 04:15:00 +00001018 return (PyObject *)type;
1019}
1020
1021/* Internal API to look for a name through the MRO.
1022 This returns a borrowed reference, and doesn't set an exception! */
1023PyObject *
1024_PyType_Lookup(PyTypeObject *type, PyObject *name)
1025{
1026 int i, n;
1027 PyObject *mro, *res, *dict;
1028
1029 /* For static types, look in tp_dict */
1030 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
1031 dict = type->tp_dict;
1032 assert(dict && PyDict_Check(dict));
1033 return PyDict_GetItem(dict, name);
1034 }
1035
1036 /* For dynamic types, look in tp_defined of types in MRO */
1037 mro = type->tp_mro;
1038 assert(PyTuple_Check(mro));
1039 n = PyTuple_GET_SIZE(mro);
1040 for (i = 0; i < n; i++) {
1041 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
1042 assert(PyType_Check(type));
1043 dict = type->tp_defined;
1044 assert(dict && PyDict_Check(dict));
1045 res = PyDict_GetItem(dict, name);
1046 if (res != NULL)
1047 return res;
1048 }
1049 return NULL;
1050}
1051
1052/* This is similar to PyObject_GenericGetAttr(),
1053 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1054static PyObject *
1055type_getattro(PyTypeObject *type, PyObject *name)
1056{
1057 PyTypeObject *metatype = type->ob_type;
1058 PyObject *descr, *res;
1059 descrgetfunc f;
1060
1061 /* Initialize this type (we'll assume the metatype is initialized) */
1062 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001063 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001064 return NULL;
1065 }
1066
1067 /* Get a descriptor from the metatype */
1068 descr = _PyType_Lookup(metatype, name);
1069 f = NULL;
1070 if (descr != NULL) {
1071 f = descr->ob_type->tp_descr_get;
1072 if (f != NULL && PyDescr_IsData(descr))
1073 return f(descr,
1074 (PyObject *)type, (PyObject *)metatype);
1075 }
1076
1077 /* Look in tp_defined of this type and its bases */
1078 res = _PyType_Lookup(type, name);
1079 if (res != NULL) {
1080 f = res->ob_type->tp_descr_get;
1081 if (f != NULL)
1082 return f(res, (PyObject *)NULL, (PyObject *)type);
1083 Py_INCREF(res);
1084 return res;
1085 }
1086
1087 /* Use the descriptor from the metatype */
1088 if (f != NULL) {
1089 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1090 return res;
1091 }
1092 if (descr != NULL) {
1093 Py_INCREF(descr);
1094 return descr;
1095 }
1096
1097 /* Give up */
1098 PyErr_Format(PyExc_AttributeError,
1099 "type object '%.50s' has no attribute '%.400s'",
1100 type->tp_name, PyString_AS_STRING(name));
1101 return NULL;
1102}
1103
1104static int
1105type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1106{
1107 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
1108 return PyObject_GenericSetAttr((PyObject *)type, name, value);
1109 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
1110 return -1;
1111}
1112
1113static void
1114type_dealloc(PyTypeObject *type)
1115{
1116 etype *et;
1117
1118 /* Assert this is a heap-allocated type object */
1119 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001120 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001121 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122 et = (etype *)type;
1123 Py_XDECREF(type->tp_base);
1124 Py_XDECREF(type->tp_dict);
1125 Py_XDECREF(type->tp_bases);
1126 Py_XDECREF(type->tp_mro);
1127 Py_XDECREF(type->tp_defined);
Guido van Rossum1c450732001-10-08 15:18:27 +00001128 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001129 Py_XDECREF(et->name);
1130 Py_XDECREF(et->slots);
1131 type->ob_type->tp_free((PyObject *)type);
1132}
1133
Guido van Rossum1c450732001-10-08 15:18:27 +00001134static PyObject *
1135type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1136{
1137 PyObject *list, *raw, *ref;
1138 int i, n;
1139
1140 list = PyList_New(0);
1141 if (list == NULL)
1142 return NULL;
1143 raw = type->tp_subclasses;
1144 if (raw == NULL)
1145 return list;
1146 assert(PyList_Check(raw));
1147 n = PyList_GET_SIZE(raw);
1148 for (i = 0; i < n; i++) {
1149 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001150 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001151 ref = PyWeakref_GET_OBJECT(ref);
1152 if (ref != Py_None) {
1153 if (PyList_Append(list, ref) < 0) {
1154 Py_DECREF(list);
1155 return NULL;
1156 }
1157 }
1158 }
1159 return list;
1160}
1161
Tim Peters6d6c1a32001-08-02 04:15:00 +00001162static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001163 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001164 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001165 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1166 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001167 {0}
1168};
1169
1170static char type_doc[] =
1171"type(object) -> the object's type\n"
1172"type(name, bases, dict) -> a new type";
1173
Guido van Rossum048eb752001-10-02 21:24:57 +00001174static int
1175type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1176{
1177 etype *et;
1178 int err;
1179
1180 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1181 return 0;
1182
1183 et = (etype *)type;
1184
1185#define VISIT(SLOT) \
1186 if (SLOT) { \
1187 err = visit((PyObject *)(SLOT), arg); \
1188 if (err) \
1189 return err; \
1190 }
1191
1192 VISIT(type->tp_dict);
1193 VISIT(type->tp_defined);
1194 VISIT(type->tp_mro);
1195 VISIT(type->tp_bases);
1196 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001197 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001198 VISIT(et->slots);
1199
1200#undef VISIT
1201
1202 return 0;
1203}
1204
1205static int
1206type_clear(PyTypeObject *type)
1207{
1208 etype *et;
1209 PyObject *tmp;
1210
1211 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1212 return 0;
1213
1214 et = (etype *)type;
1215
1216#define CLEAR(SLOT) \
1217 if (SLOT) { \
1218 tmp = (PyObject *)(SLOT); \
1219 SLOT = NULL; \
1220 Py_DECREF(tmp); \
1221 }
1222
1223 CLEAR(type->tp_dict);
1224 CLEAR(type->tp_defined);
1225 CLEAR(type->tp_mro);
1226 CLEAR(type->tp_bases);
1227 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001228 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001229 CLEAR(et->slots);
1230
Tim Peters2f93e282001-10-04 05:27:00 +00001231 if (type->tp_doc != NULL) {
1232 PyObject_FREE(type->tp_doc);
1233 type->tp_doc = NULL;
1234 }
1235
Guido van Rossum048eb752001-10-02 21:24:57 +00001236#undef CLEAR
1237
1238 return 0;
1239}
1240
1241static int
1242type_is_gc(PyTypeObject *type)
1243{
1244 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1245}
1246
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001247PyTypeObject PyType_Type = {
1248 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249 0, /* ob_size */
1250 "type", /* tp_name */
1251 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001252 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001253 (destructor)type_dealloc, /* tp_dealloc */
1254 0, /* tp_print */
1255 0, /* tp_getattr */
1256 0, /* tp_setattr */
1257 type_compare, /* tp_compare */
1258 (reprfunc)type_repr, /* tp_repr */
1259 0, /* tp_as_number */
1260 0, /* tp_as_sequence */
1261 0, /* tp_as_mapping */
1262 (hashfunc)_Py_HashPointer, /* tp_hash */
1263 (ternaryfunc)type_call, /* tp_call */
1264 0, /* tp_str */
1265 (getattrofunc)type_getattro, /* tp_getattro */
1266 (setattrofunc)type_setattro, /* tp_setattro */
1267 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001268 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1269 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001270 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001271 (traverseproc)type_traverse, /* tp_traverse */
1272 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001274 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 0, /* tp_iter */
1276 0, /* tp_iternext */
1277 type_methods, /* tp_methods */
1278 type_members, /* tp_members */
1279 type_getsets, /* tp_getset */
1280 0, /* tp_base */
1281 0, /* tp_dict */
1282 0, /* tp_descr_get */
1283 0, /* tp_descr_set */
1284 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1285 0, /* tp_init */
1286 0, /* tp_alloc */
1287 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001288 _PyObject_GC_Del, /* tp_free */
1289 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001290};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291
1292
1293/* The base type of all types (eventually)... except itself. */
1294
1295static int
1296object_init(PyObject *self, PyObject *args, PyObject *kwds)
1297{
1298 return 0;
1299}
1300
1301static void
1302object_dealloc(PyObject *self)
1303{
1304 self->ob_type->tp_free(self);
1305}
1306
Guido van Rossum8e248182001-08-12 05:17:56 +00001307static PyObject *
1308object_repr(PyObject *self)
1309{
Guido van Rossum76e69632001-08-16 18:52:43 +00001310 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001311 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001312
Guido van Rossum76e69632001-08-16 18:52:43 +00001313 type = self->ob_type;
1314 mod = type_module(type, NULL);
1315 if (mod == NULL)
1316 PyErr_Clear();
1317 else if (!PyString_Check(mod)) {
1318 Py_DECREF(mod);
1319 mod = NULL;
1320 }
1321 name = type_name(type, NULL);
1322 if (name == NULL)
1323 return NULL;
1324 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001325 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001326 PyString_AS_STRING(mod),
1327 PyString_AS_STRING(name),
1328 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001329 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001330 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001331 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001332 Py_XDECREF(mod);
1333 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001334 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001335}
1336
Guido van Rossumb8f63662001-08-15 23:57:02 +00001337static PyObject *
1338object_str(PyObject *self)
1339{
1340 unaryfunc f;
1341
1342 f = self->ob_type->tp_repr;
1343 if (f == NULL)
1344 f = object_repr;
1345 return f(self);
1346}
1347
Guido van Rossum8e248182001-08-12 05:17:56 +00001348static long
1349object_hash(PyObject *self)
1350{
1351 return _Py_HashPointer(self);
1352}
Guido van Rossum8e248182001-08-12 05:17:56 +00001353
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001354static PyObject *
1355object_get_class(PyObject *self, void *closure)
1356{
1357 Py_INCREF(self->ob_type);
1358 return (PyObject *)(self->ob_type);
1359}
1360
1361static int
1362equiv_structs(PyTypeObject *a, PyTypeObject *b)
1363{
1364 return a == b ||
1365 (a != NULL &&
1366 b != NULL &&
1367 a->tp_basicsize == b->tp_basicsize &&
1368 a->tp_itemsize == b->tp_itemsize &&
1369 a->tp_dictoffset == b->tp_dictoffset &&
1370 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1371 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1372 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1373}
1374
1375static int
1376same_slots_added(PyTypeObject *a, PyTypeObject *b)
1377{
1378 PyTypeObject *base = a->tp_base;
1379 int size;
1380
1381 if (base != b->tp_base)
1382 return 0;
1383 if (equiv_structs(a, base) && equiv_structs(b, base))
1384 return 1;
1385 size = base->tp_basicsize;
1386 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1387 size += sizeof(PyObject *);
1388 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1389 size += sizeof(PyObject *);
1390 return size == a->tp_basicsize && size == b->tp_basicsize;
1391}
1392
1393static int
1394object_set_class(PyObject *self, PyObject *value, void *closure)
1395{
1396 PyTypeObject *old = self->ob_type;
1397 PyTypeObject *new, *newbase, *oldbase;
1398
1399 if (!PyType_Check(value)) {
1400 PyErr_Format(PyExc_TypeError,
1401 "__class__ must be set to new-style class, not '%s' object",
1402 value->ob_type->tp_name);
1403 return -1;
1404 }
1405 new = (PyTypeObject *)value;
1406 newbase = new;
1407 oldbase = old;
1408 while (equiv_structs(newbase, newbase->tp_base))
1409 newbase = newbase->tp_base;
1410 while (equiv_structs(oldbase, oldbase->tp_base))
1411 oldbase = oldbase->tp_base;
1412 if (newbase != oldbase &&
1413 (newbase->tp_base != oldbase->tp_base ||
1414 !same_slots_added(newbase, oldbase))) {
1415 PyErr_Format(PyExc_TypeError,
1416 "__class__ assignment: "
1417 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001418 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001419 old->tp_name);
1420 return -1;
1421 }
1422 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1423 Py_INCREF(new);
1424 }
1425 self->ob_type = new;
1426 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1427 Py_DECREF(old);
1428 }
1429 return 0;
1430}
1431
1432static PyGetSetDef object_getsets[] = {
1433 {"__class__", object_get_class, object_set_class,
1434 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001435 {0}
1436};
1437
Guido van Rossum3926a632001-09-25 16:25:58 +00001438static PyObject *
1439object_reduce(PyObject *self, PyObject *args)
1440{
1441 /* Call copy_reg._reduce(self) */
1442 static PyObject *copy_reg_str;
1443 PyObject *copy_reg, *res;
1444
1445 if (!copy_reg_str) {
1446 copy_reg_str = PyString_InternFromString("copy_reg");
1447 if (copy_reg_str == NULL)
1448 return NULL;
1449 }
1450 copy_reg = PyImport_Import(copy_reg_str);
1451 if (!copy_reg)
1452 return NULL;
1453 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1454 Py_DECREF(copy_reg);
1455 return res;
1456}
1457
1458static PyMethodDef object_methods[] = {
1459 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1460 {0}
1461};
1462
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463PyTypeObject PyBaseObject_Type = {
1464 PyObject_HEAD_INIT(&PyType_Type)
1465 0, /* ob_size */
1466 "object", /* tp_name */
1467 sizeof(PyObject), /* tp_basicsize */
1468 0, /* tp_itemsize */
1469 (destructor)object_dealloc, /* tp_dealloc */
1470 0, /* tp_print */
1471 0, /* tp_getattr */
1472 0, /* tp_setattr */
1473 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001474 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001475 0, /* tp_as_number */
1476 0, /* tp_as_sequence */
1477 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001478 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001479 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001480 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001481 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001482 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001483 0, /* tp_as_buffer */
1484 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1485 "The most base type", /* tp_doc */
1486 0, /* tp_traverse */
1487 0, /* tp_clear */
1488 0, /* tp_richcompare */
1489 0, /* tp_weaklistoffset */
1490 0, /* tp_iter */
1491 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001492 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001493 0, /* tp_members */
1494 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001495 0, /* tp_base */
1496 0, /* tp_dict */
1497 0, /* tp_descr_get */
1498 0, /* tp_descr_set */
1499 0, /* tp_dictoffset */
1500 object_init, /* tp_init */
1501 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001502 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001503 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001504};
1505
1506
1507/* Initialize the __dict__ in a type object */
1508
1509static int
1510add_methods(PyTypeObject *type, PyMethodDef *meth)
1511{
1512 PyObject *dict = type->tp_defined;
1513
1514 for (; meth->ml_name != NULL; meth++) {
1515 PyObject *descr;
1516 if (PyDict_GetItemString(dict, meth->ml_name))
1517 continue;
1518 descr = PyDescr_NewMethod(type, meth);
1519 if (descr == NULL)
1520 return -1;
1521 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1522 return -1;
1523 Py_DECREF(descr);
1524 }
1525 return 0;
1526}
1527
1528static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001529add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001530{
1531 PyObject *dict = type->tp_defined;
1532
1533 for (; memb->name != NULL; memb++) {
1534 PyObject *descr;
1535 if (PyDict_GetItemString(dict, memb->name))
1536 continue;
1537 descr = PyDescr_NewMember(type, memb);
1538 if (descr == NULL)
1539 return -1;
1540 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1541 return -1;
1542 Py_DECREF(descr);
1543 }
1544 return 0;
1545}
1546
1547static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001548add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001549{
1550 PyObject *dict = type->tp_defined;
1551
1552 for (; gsp->name != NULL; gsp++) {
1553 PyObject *descr;
1554 if (PyDict_GetItemString(dict, gsp->name))
1555 continue;
1556 descr = PyDescr_NewGetSet(type, gsp);
1557
1558 if (descr == NULL)
1559 return -1;
1560 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1561 return -1;
1562 Py_DECREF(descr);
1563 }
1564 return 0;
1565}
1566
Guido van Rossum13d52f02001-08-10 21:24:08 +00001567static void
1568inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569{
1570 int oldsize, newsize;
1571
Guido van Rossum13d52f02001-08-10 21:24:08 +00001572 /* Special flag magic */
1573 if (!type->tp_as_buffer && base->tp_as_buffer) {
1574 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1575 type->tp_flags |=
1576 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1577 }
1578 if (!type->tp_as_sequence && base->tp_as_sequence) {
1579 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1580 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1581 }
1582 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1583 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1584 if ((!type->tp_as_number && base->tp_as_number) ||
1585 (!type->tp_as_sequence && base->tp_as_sequence)) {
1586 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1587 if (!type->tp_as_number && !type->tp_as_sequence) {
1588 type->tp_flags |= base->tp_flags &
1589 Py_TPFLAGS_HAVE_INPLACEOPS;
1590 }
1591 }
1592 /* Wow */
1593 }
1594 if (!type->tp_as_number && base->tp_as_number) {
1595 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1596 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1597 }
1598
1599 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001600 oldsize = base->tp_basicsize;
1601 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1602 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1603 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001604 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1605 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001606 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001607 if (type->tp_traverse == NULL)
1608 type->tp_traverse = base->tp_traverse;
1609 if (type->tp_clear == NULL)
1610 type->tp_clear = base->tp_clear;
1611 }
1612 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1613 if (base != &PyBaseObject_Type ||
1614 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1615 if (type->tp_new == NULL)
1616 type->tp_new = base->tp_new;
1617 }
1618 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001619 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001620
1621 /* Copy other non-function slots */
1622
1623#undef COPYVAL
1624#define COPYVAL(SLOT) \
1625 if (type->SLOT == 0) type->SLOT = base->SLOT
1626
1627 COPYVAL(tp_itemsize);
1628 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1629 COPYVAL(tp_weaklistoffset);
1630 }
1631 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1632 COPYVAL(tp_dictoffset);
1633 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001634}
1635
1636static void
1637inherit_slots(PyTypeObject *type, PyTypeObject *base)
1638{
1639 PyTypeObject *basebase;
1640
1641#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001642#undef COPYSLOT
1643#undef COPYNUM
1644#undef COPYSEQ
1645#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001646
1647#define SLOTDEFINED(SLOT) \
1648 (base->SLOT != 0 && \
1649 (basebase == NULL || base->SLOT != basebase->SLOT))
1650
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001652 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653
1654#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1655#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1656#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1657
Guido van Rossum13d52f02001-08-10 21:24:08 +00001658 /* This won't inherit indirect slots (from tp_as_number etc.)
1659 if type doesn't provide the space. */
1660
1661 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1662 basebase = base->tp_base;
1663 if (basebase->tp_as_number == NULL)
1664 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001665 COPYNUM(nb_add);
1666 COPYNUM(nb_subtract);
1667 COPYNUM(nb_multiply);
1668 COPYNUM(nb_divide);
1669 COPYNUM(nb_remainder);
1670 COPYNUM(nb_divmod);
1671 COPYNUM(nb_power);
1672 COPYNUM(nb_negative);
1673 COPYNUM(nb_positive);
1674 COPYNUM(nb_absolute);
1675 COPYNUM(nb_nonzero);
1676 COPYNUM(nb_invert);
1677 COPYNUM(nb_lshift);
1678 COPYNUM(nb_rshift);
1679 COPYNUM(nb_and);
1680 COPYNUM(nb_xor);
1681 COPYNUM(nb_or);
1682 COPYNUM(nb_coerce);
1683 COPYNUM(nb_int);
1684 COPYNUM(nb_long);
1685 COPYNUM(nb_float);
1686 COPYNUM(nb_oct);
1687 COPYNUM(nb_hex);
1688 COPYNUM(nb_inplace_add);
1689 COPYNUM(nb_inplace_subtract);
1690 COPYNUM(nb_inplace_multiply);
1691 COPYNUM(nb_inplace_divide);
1692 COPYNUM(nb_inplace_remainder);
1693 COPYNUM(nb_inplace_power);
1694 COPYNUM(nb_inplace_lshift);
1695 COPYNUM(nb_inplace_rshift);
1696 COPYNUM(nb_inplace_and);
1697 COPYNUM(nb_inplace_xor);
1698 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001699 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1700 COPYNUM(nb_true_divide);
1701 COPYNUM(nb_floor_divide);
1702 COPYNUM(nb_inplace_true_divide);
1703 COPYNUM(nb_inplace_floor_divide);
1704 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001705 }
1706
Guido van Rossum13d52f02001-08-10 21:24:08 +00001707 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1708 basebase = base->tp_base;
1709 if (basebase->tp_as_sequence == NULL)
1710 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001711 COPYSEQ(sq_length);
1712 COPYSEQ(sq_concat);
1713 COPYSEQ(sq_repeat);
1714 COPYSEQ(sq_item);
1715 COPYSEQ(sq_slice);
1716 COPYSEQ(sq_ass_item);
1717 COPYSEQ(sq_ass_slice);
1718 COPYSEQ(sq_contains);
1719 COPYSEQ(sq_inplace_concat);
1720 COPYSEQ(sq_inplace_repeat);
1721 }
1722
Guido van Rossum13d52f02001-08-10 21:24:08 +00001723 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1724 basebase = base->tp_base;
1725 if (basebase->tp_as_mapping == NULL)
1726 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001727 COPYMAP(mp_length);
1728 COPYMAP(mp_subscript);
1729 COPYMAP(mp_ass_subscript);
1730 }
1731
Guido van Rossum13d52f02001-08-10 21:24:08 +00001732 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001733
Tim Peters6d6c1a32001-08-02 04:15:00 +00001734 COPYSLOT(tp_dealloc);
1735 COPYSLOT(tp_print);
1736 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1737 type->tp_getattr = base->tp_getattr;
1738 type->tp_getattro = base->tp_getattro;
1739 }
1740 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1741 type->tp_setattr = base->tp_setattr;
1742 type->tp_setattro = base->tp_setattro;
1743 }
1744 /* tp_compare see tp_richcompare */
1745 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001746 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001747 COPYSLOT(tp_call);
1748 COPYSLOT(tp_str);
1749 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001750 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001751 if (type->tp_compare == NULL &&
1752 type->tp_richcompare == NULL &&
1753 type->tp_hash == NULL)
1754 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001755 type->tp_compare = base->tp_compare;
1756 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001757 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001758 }
1759 }
1760 else {
1761 COPYSLOT(tp_compare);
1762 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001763 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1764 COPYSLOT(tp_iter);
1765 COPYSLOT(tp_iternext);
1766 }
1767 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1768 COPYSLOT(tp_descr_get);
1769 COPYSLOT(tp_descr_set);
1770 COPYSLOT(tp_dictoffset);
1771 COPYSLOT(tp_init);
1772 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001773 COPYSLOT(tp_free);
1774 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775}
1776
Guido van Rossum13d52f02001-08-10 21:24:08 +00001777staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00001778staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001779
Tim Peters6d6c1a32001-08-02 04:15:00 +00001780int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001781PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001782{
1783 PyObject *dict, *bases, *x;
1784 PyTypeObject *base;
1785 int i, n;
1786
Guido van Rossumd614f972001-08-10 17:39:49 +00001787 if (type->tp_flags & Py_TPFLAGS_READY) {
1788 assert(type->tp_dict != NULL);
1789 return 0;
1790 }
1791 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1792 assert(type->tp_dict == NULL);
1793
1794 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795
1796 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1797 base = type->tp_base;
1798 if (base == NULL && type != &PyBaseObject_Type)
1799 base = type->tp_base = &PyBaseObject_Type;
1800
1801 /* Initialize tp_bases */
1802 bases = type->tp_bases;
1803 if (bases == NULL) {
1804 if (base == NULL)
1805 bases = PyTuple_New(0);
1806 else
1807 bases = Py_BuildValue("(O)", base);
1808 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001809 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810 type->tp_bases = bases;
1811 }
1812
1813 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001814 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001815 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001816 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001817 }
1818
1819 /* Initialize tp_defined */
1820 dict = type->tp_defined;
1821 if (dict == NULL) {
1822 dict = PyDict_New();
1823 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001824 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001825 type->tp_defined = dict;
1826 }
1827
1828 /* Add type-specific descriptors to tp_defined */
1829 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001830 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001831 if (type->tp_methods != NULL) {
1832 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001833 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834 }
1835 if (type->tp_members != NULL) {
1836 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001837 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001838 }
1839 if (type->tp_getset != NULL) {
1840 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001841 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001842 }
1843
1844 /* Temporarily make tp_dict the same object as tp_defined.
1845 (This is needed to call mro(), and can stay this way for
1846 dynamic types). */
1847 Py_INCREF(type->tp_defined);
1848 type->tp_dict = type->tp_defined;
1849
1850 /* Calculate method resolution order */
1851 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001852 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853 }
1854
Guido van Rossum13d52f02001-08-10 21:24:08 +00001855 /* Inherit special flags from dominant base */
1856 if (type->tp_base != NULL)
1857 inherit_special(type, type->tp_base);
1858
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001860 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001861 /* For a dynamic type, all slots are overridden */
1862 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001863 }
1864 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001866 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001868 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001869 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001870 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001871 bases = type->tp_mro;
1872 assert(bases != NULL);
1873 assert(PyTuple_Check(bases));
1874 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001875 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001876 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1877 assert(PyType_Check(base));
1878 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001879 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001880 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001881 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882 }
1883 }
1884
Guido van Rossum13d52f02001-08-10 21:24:08 +00001885 /* Some more special stuff */
1886 base = type->tp_base;
1887 if (base != NULL) {
1888 if (type->tp_as_number == NULL)
1889 type->tp_as_number = base->tp_as_number;
1890 if (type->tp_as_sequence == NULL)
1891 type->tp_as_sequence = base->tp_as_sequence;
1892 if (type->tp_as_mapping == NULL)
1893 type->tp_as_mapping = base->tp_as_mapping;
1894 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001895
Guido van Rossum1c450732001-10-08 15:18:27 +00001896 /* Link into each base class's list of subclasses */
1897 bases = type->tp_bases;
1898 n = PyTuple_GET_SIZE(bases);
1899 for (i = 0; i < n; i++) {
1900 base = (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
1901 if (add_subclass((PyTypeObject *)base, type) < 0)
1902 goto error;
1903 }
1904
Guido van Rossum13d52f02001-08-10 21:24:08 +00001905 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001906 assert(type->tp_dict != NULL);
1907 type->tp_flags =
1908 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001909 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001910
1911 error:
1912 type->tp_flags &= ~Py_TPFLAGS_READYING;
1913 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001914}
1915
Guido van Rossum1c450732001-10-08 15:18:27 +00001916static int
1917add_subclass(PyTypeObject *base, PyTypeObject *type)
1918{
1919 int i;
1920 PyObject *list, *ref, *new;
1921
1922 list = base->tp_subclasses;
1923 if (list == NULL) {
1924 base->tp_subclasses = list = PyList_New(0);
1925 if (list == NULL)
1926 return -1;
1927 }
1928 assert(PyList_Check(list));
1929 new = PyWeakref_NewRef((PyObject *)type, NULL);
1930 i = PyList_GET_SIZE(list);
1931 while (--i >= 0) {
1932 ref = PyList_GET_ITEM(list, i);
1933 assert(PyWeakref_CheckRef(ref));
1934 if (PyWeakref_GET_OBJECT(ref) == Py_None)
1935 return PyList_SetItem(list, i, new);
1936 }
1937 i = PyList_Append(list, new);
1938 Py_DECREF(new);
1939 return i;
1940}
1941
Tim Peters6d6c1a32001-08-02 04:15:00 +00001942
1943/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1944
1945/* There's a wrapper *function* for each distinct function typedef used
1946 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1947 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1948 Most tables have only one entry; the tables for binary operators have two
1949 entries, one regular and one with reversed arguments. */
1950
1951static PyObject *
1952wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1953{
1954 inquiry func = (inquiry)wrapped;
1955 int res;
1956
1957 if (!PyArg_ParseTuple(args, ""))
1958 return NULL;
1959 res = (*func)(self);
1960 if (res == -1 && PyErr_Occurred())
1961 return NULL;
1962 return PyInt_FromLong((long)res);
1963}
1964
1965static struct wrapperbase tab_len[] = {
1966 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1967 {0}
1968};
1969
1970static PyObject *
1971wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1972{
1973 binaryfunc func = (binaryfunc)wrapped;
1974 PyObject *other;
1975
1976 if (!PyArg_ParseTuple(args, "O", &other))
1977 return NULL;
1978 return (*func)(self, other);
1979}
1980
1981static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00001982wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
1983{
1984 binaryfunc func = (binaryfunc)wrapped;
1985 PyObject *other;
1986
1987 if (!PyArg_ParseTuple(args, "O", &other))
1988 return NULL;
1989 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
1990 self->ob_type != other->ob_type) {
1991 Py_INCREF(Py_NotImplemented);
1992 return Py_NotImplemented;
1993 }
1994 return (*func)(self, other);
1995}
1996
1997static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001998wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1999{
2000 binaryfunc func = (binaryfunc)wrapped;
2001 PyObject *other;
2002
2003 if (!PyArg_ParseTuple(args, "O", &other))
2004 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002005 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2006 self->ob_type != other->ob_type) {
2007 Py_INCREF(Py_NotImplemented);
2008 return Py_NotImplemented;
2009 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002010 return (*func)(other, self);
2011}
2012
2013#undef BINARY
2014#define BINARY(NAME, OP) \
2015static struct wrapperbase tab_##NAME[] = { \
2016 {"__" #NAME "__", \
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002017 (wrapperfunc)wrap_binaryfunc_l, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002018 "x.__" #NAME "__(y) <==> " #OP}, \
2019 {"__r" #NAME "__", \
2020 (wrapperfunc)wrap_binaryfunc_r, \
2021 "y.__r" #NAME "__(x) <==> " #OP}, \
2022 {0} \
2023}
2024
2025BINARY(add, "x+y");
2026BINARY(sub, "x-y");
2027BINARY(mul, "x*y");
2028BINARY(div, "x/y");
2029BINARY(mod, "x%y");
2030BINARY(divmod, "divmod(x,y)");
2031BINARY(lshift, "x<<y");
2032BINARY(rshift, "x>>y");
2033BINARY(and, "x&y");
2034BINARY(xor, "x^y");
2035BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002036
2037static PyObject *
2038wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2039{
2040 coercion func = (coercion)wrapped;
2041 PyObject *other, *res;
2042 int ok;
2043
2044 if (!PyArg_ParseTuple(args, "O", &other))
2045 return NULL;
2046 ok = func(&self, &other);
2047 if (ok < 0)
2048 return NULL;
2049 if (ok > 0) {
2050 Py_INCREF(Py_NotImplemented);
2051 return Py_NotImplemented;
2052 }
2053 res = PyTuple_New(2);
2054 if (res == NULL) {
2055 Py_DECREF(self);
2056 Py_DECREF(other);
2057 return NULL;
2058 }
2059 PyTuple_SET_ITEM(res, 0, self);
2060 PyTuple_SET_ITEM(res, 1, other);
2061 return res;
2062}
2063
2064static struct wrapperbase tab_coerce[] = {
2065 {"__coerce__", (wrapperfunc)wrap_coercefunc,
2066 "x.__coerce__(y) <==> coerce(x, y)"},
2067 {0}
2068};
2069
Guido van Rossum874f15a2001-09-25 21:16:33 +00002070BINARY(floordiv, "x//y");
2071BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002072
2073static PyObject *
2074wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2075{
2076 ternaryfunc func = (ternaryfunc)wrapped;
2077 PyObject *other;
2078 PyObject *third = Py_None;
2079
2080 /* Note: This wrapper only works for __pow__() */
2081
2082 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2083 return NULL;
2084 return (*func)(self, other, third);
2085}
2086
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002087static PyObject *
2088wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2089{
2090 ternaryfunc func = (ternaryfunc)wrapped;
2091 PyObject *other;
2092 PyObject *third = Py_None;
2093
2094 /* Note: This wrapper only works for __pow__() */
2095
2096 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2097 return NULL;
2098 return (*func)(other, self, third);
2099}
2100
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101#undef TERNARY
2102#define TERNARY(NAME, OP) \
2103static struct wrapperbase tab_##NAME[] = { \
2104 {"__" #NAME "__", \
2105 (wrapperfunc)wrap_ternaryfunc, \
2106 "x.__" #NAME "__(y, z) <==> " #OP}, \
2107 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002108 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002109 "y.__r" #NAME "__(x, z) <==> " #OP}, \
2110 {0} \
2111}
2112
2113TERNARY(pow, "(x**y) % z");
2114
2115#undef UNARY
2116#define UNARY(NAME, OP) \
2117static struct wrapperbase tab_##NAME[] = { \
2118 {"__" #NAME "__", \
2119 (wrapperfunc)wrap_unaryfunc, \
2120 "x.__" #NAME "__() <==> " #OP}, \
2121 {0} \
2122}
2123
2124static PyObject *
2125wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2126{
2127 unaryfunc func = (unaryfunc)wrapped;
2128
2129 if (!PyArg_ParseTuple(args, ""))
2130 return NULL;
2131 return (*func)(self);
2132}
2133
2134UNARY(neg, "-x");
2135UNARY(pos, "+x");
2136UNARY(abs, "abs(x)");
2137UNARY(nonzero, "x != 0");
2138UNARY(invert, "~x");
2139UNARY(int, "int(x)");
2140UNARY(long, "long(x)");
2141UNARY(float, "float(x)");
2142UNARY(oct, "oct(x)");
2143UNARY(hex, "hex(x)");
2144
2145#undef IBINARY
2146#define IBINARY(NAME, OP) \
2147static struct wrapperbase tab_##NAME[] = { \
2148 {"__" #NAME "__", \
2149 (wrapperfunc)wrap_binaryfunc, \
2150 "x.__" #NAME "__(y) <==> " #OP}, \
2151 {0} \
2152}
2153
2154IBINARY(iadd, "x+=y");
2155IBINARY(isub, "x-=y");
2156IBINARY(imul, "x*=y");
2157IBINARY(idiv, "x/=y");
2158IBINARY(imod, "x%=y");
2159IBINARY(ilshift, "x<<=y");
2160IBINARY(irshift, "x>>=y");
2161IBINARY(iand, "x&=y");
2162IBINARY(ixor, "x^=y");
2163IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002164IBINARY(ifloordiv, "x//=y");
2165IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166
2167#undef ITERNARY
2168#define ITERNARY(NAME, OP) \
2169static struct wrapperbase tab_##NAME[] = { \
2170 {"__" #NAME "__", \
2171 (wrapperfunc)wrap_ternaryfunc, \
2172 "x.__" #NAME "__(y) <==> " #OP}, \
2173 {0} \
2174}
2175
2176ITERNARY(ipow, "x = (x**y) % z");
2177
2178static struct wrapperbase tab_getitem[] = {
2179 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2180 "x.__getitem__(y) <==> x[y]"},
2181 {0}
2182};
2183
2184static PyObject *
2185wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2186{
2187 intargfunc func = (intargfunc)wrapped;
2188 int i;
2189
2190 if (!PyArg_ParseTuple(args, "i", &i))
2191 return NULL;
2192 return (*func)(self, i);
2193}
2194
2195static struct wrapperbase tab_mul_int[] = {
2196 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2197 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2198 {0}
2199};
2200
2201static struct wrapperbase tab_concat[] = {
2202 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2203 {0}
2204};
2205
2206static struct wrapperbase tab_imul_int[] = {
2207 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2208 {0}
2209};
2210
Guido van Rossum5d815f32001-08-17 21:57:47 +00002211static int
2212getindex(PyObject *self, PyObject *arg)
2213{
2214 int i;
2215
2216 i = PyInt_AsLong(arg);
2217 if (i == -1 && PyErr_Occurred())
2218 return -1;
2219 if (i < 0) {
2220 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2221 if (sq && sq->sq_length) {
2222 int n = (*sq->sq_length)(self);
2223 if (n < 0)
2224 return -1;
2225 i += n;
2226 }
2227 }
2228 return i;
2229}
2230
2231static PyObject *
2232wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2233{
2234 intargfunc func = (intargfunc)wrapped;
2235 PyObject *arg;
2236 int i;
2237
Guido van Rossumf4593e02001-10-03 12:09:30 +00002238 if (PyTuple_GET_SIZE(args) == 1) {
2239 arg = PyTuple_GET_ITEM(args, 0);
2240 i = getindex(self, arg);
2241 if (i == -1 && PyErr_Occurred())
2242 return NULL;
2243 return (*func)(self, i);
2244 }
2245 PyArg_ParseTuple(args, "O", &arg);
2246 assert(PyErr_Occurred());
2247 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002248}
2249
Tim Peters6d6c1a32001-08-02 04:15:00 +00002250static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002251 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002252 "x.__getitem__(i) <==> x[i]"},
2253 {0}
2254};
2255
2256static PyObject *
2257wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2258{
2259 intintargfunc func = (intintargfunc)wrapped;
2260 int i, j;
2261
2262 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2263 return NULL;
2264 return (*func)(self, i, j);
2265}
2266
2267static struct wrapperbase tab_getslice[] = {
2268 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2269 "x.__getslice__(i, j) <==> x[i:j]"},
2270 {0}
2271};
2272
2273static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002274wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002275{
2276 intobjargproc func = (intobjargproc)wrapped;
2277 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002278 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002279
Guido van Rossum5d815f32001-08-17 21:57:47 +00002280 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2281 return NULL;
2282 i = getindex(self, arg);
2283 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002284 return NULL;
2285 res = (*func)(self, i, value);
2286 if (res == -1 && PyErr_Occurred())
2287 return NULL;
2288 Py_INCREF(Py_None);
2289 return Py_None;
2290}
2291
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002292static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002293wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002294{
2295 intobjargproc func = (intobjargproc)wrapped;
2296 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002297 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002298
Guido van Rossum5d815f32001-08-17 21:57:47 +00002299 if (!PyArg_ParseTuple(args, "O", &arg))
2300 return NULL;
2301 i = getindex(self, arg);
2302 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002303 return NULL;
2304 res = (*func)(self, i, NULL);
2305 if (res == -1 && PyErr_Occurred())
2306 return NULL;
2307 Py_INCREF(Py_None);
2308 return Py_None;
2309}
2310
Tim Peters6d6c1a32001-08-02 04:15:00 +00002311static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002312 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002313 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002314 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002315 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002316 {0}
2317};
2318
2319static PyObject *
2320wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2321{
2322 intintobjargproc func = (intintobjargproc)wrapped;
2323 int i, j, res;
2324 PyObject *value;
2325
2326 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2327 return NULL;
2328 res = (*func)(self, i, j, value);
2329 if (res == -1 && PyErr_Occurred())
2330 return NULL;
2331 Py_INCREF(Py_None);
2332 return Py_None;
2333}
2334
2335static struct wrapperbase tab_setslice[] = {
2336 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2337 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
2338 {0}
2339};
2340
2341/* XXX objobjproc is a misnomer; should be objargpred */
2342static PyObject *
2343wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2344{
2345 objobjproc func = (objobjproc)wrapped;
2346 int res;
2347 PyObject *value;
2348
2349 if (!PyArg_ParseTuple(args, "O", &value))
2350 return NULL;
2351 res = (*func)(self, value);
2352 if (res == -1 && PyErr_Occurred())
2353 return NULL;
2354 return PyInt_FromLong((long)res);
2355}
2356
2357static struct wrapperbase tab_contains[] = {
2358 {"__contains__", (wrapperfunc)wrap_objobjproc,
2359 "x.__contains__(y) <==> y in x"},
2360 {0}
2361};
2362
2363static PyObject *
2364wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2365{
2366 objobjargproc func = (objobjargproc)wrapped;
2367 int res;
2368 PyObject *key, *value;
2369
2370 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2371 return NULL;
2372 res = (*func)(self, key, value);
2373 if (res == -1 && PyErr_Occurred())
2374 return NULL;
2375 Py_INCREF(Py_None);
2376 return Py_None;
2377}
2378
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002379static PyObject *
2380wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2381{
2382 objobjargproc func = (objobjargproc)wrapped;
2383 int res;
2384 PyObject *key;
2385
2386 if (!PyArg_ParseTuple(args, "O", &key))
2387 return NULL;
2388 res = (*func)(self, key, NULL);
2389 if (res == -1 && PyErr_Occurred())
2390 return NULL;
2391 Py_INCREF(Py_None);
2392 return Py_None;
2393}
2394
Tim Peters6d6c1a32001-08-02 04:15:00 +00002395static struct wrapperbase tab_setitem[] = {
2396 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2397 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002398 {"__delitem__", (wrapperfunc)wrap_delitem,
2399 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002400 {0}
2401};
2402
2403static PyObject *
2404wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2405{
2406 cmpfunc func = (cmpfunc)wrapped;
2407 int res;
2408 PyObject *other;
2409
2410 if (!PyArg_ParseTuple(args, "O", &other))
2411 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002412 if (other->ob_type->tp_compare != func &&
2413 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002414 PyErr_Format(
2415 PyExc_TypeError,
2416 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2417 self->ob_type->tp_name,
2418 self->ob_type->tp_name,
2419 other->ob_type->tp_name);
2420 return NULL;
2421 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002422 res = (*func)(self, other);
2423 if (PyErr_Occurred())
2424 return NULL;
2425 return PyInt_FromLong((long)res);
2426}
2427
2428static struct wrapperbase tab_cmp[] = {
2429 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2430 "x.__cmp__(y) <==> cmp(x,y)"},
2431 {0}
2432};
2433
2434static struct wrapperbase tab_repr[] = {
2435 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2436 "x.__repr__() <==> repr(x)"},
2437 {0}
2438};
2439
2440static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002441 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2442 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002443 {0}
2444};
2445
2446static PyObject *
2447wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2448{
2449 setattrofunc func = (setattrofunc)wrapped;
2450 int res;
2451 PyObject *name, *value;
2452
2453 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2454 return NULL;
2455 res = (*func)(self, name, value);
2456 if (res < 0)
2457 return NULL;
2458 Py_INCREF(Py_None);
2459 return Py_None;
2460}
2461
2462static PyObject *
2463wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2464{
2465 setattrofunc func = (setattrofunc)wrapped;
2466 int res;
2467 PyObject *name;
2468
2469 if (!PyArg_ParseTuple(args, "O", &name))
2470 return NULL;
2471 res = (*func)(self, name, NULL);
2472 if (res < 0)
2473 return NULL;
2474 Py_INCREF(Py_None);
2475 return Py_None;
2476}
2477
2478static struct wrapperbase tab_setattr[] = {
2479 {"__setattr__", (wrapperfunc)wrap_setattr,
2480 "x.__setattr__('name', value) <==> x.name = value"},
2481 {"__delattr__", (wrapperfunc)wrap_delattr,
2482 "x.__delattr__('name') <==> del x.name"},
2483 {0}
2484};
2485
2486static PyObject *
2487wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2488{
2489 hashfunc func = (hashfunc)wrapped;
2490 long res;
2491
2492 if (!PyArg_ParseTuple(args, ""))
2493 return NULL;
2494 res = (*func)(self);
2495 if (res == -1 && PyErr_Occurred())
2496 return NULL;
2497 return PyInt_FromLong(res);
2498}
2499
2500static struct wrapperbase tab_hash[] = {
2501 {"__hash__", (wrapperfunc)wrap_hashfunc,
2502 "x.__hash__() <==> hash(x)"},
2503 {0}
2504};
2505
2506static PyObject *
2507wrap_call(PyObject *self, PyObject *args, void *wrapped)
2508{
2509 ternaryfunc func = (ternaryfunc)wrapped;
2510
2511 /* XXX What about keyword arguments? */
2512 return (*func)(self, args, NULL);
2513}
2514
2515static struct wrapperbase tab_call[] = {
2516 {"__call__", (wrapperfunc)wrap_call,
2517 "x.__call__(...) <==> x(...)"},
2518 {0}
2519};
2520
2521static struct wrapperbase tab_str[] = {
2522 {"__str__", (wrapperfunc)wrap_unaryfunc,
2523 "x.__str__() <==> str(x)"},
2524 {0}
2525};
2526
2527static PyObject *
2528wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2529{
2530 richcmpfunc func = (richcmpfunc)wrapped;
2531 PyObject *other;
2532
2533 if (!PyArg_ParseTuple(args, "O", &other))
2534 return NULL;
2535 return (*func)(self, other, op);
2536}
2537
2538#undef RICHCMP_WRAPPER
2539#define RICHCMP_WRAPPER(NAME, OP) \
2540static PyObject * \
2541richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2542{ \
2543 return wrap_richcmpfunc(self, args, wrapped, OP); \
2544}
2545
Jack Jansen8e938b42001-08-08 15:29:49 +00002546RICHCMP_WRAPPER(lt, Py_LT)
2547RICHCMP_WRAPPER(le, Py_LE)
2548RICHCMP_WRAPPER(eq, Py_EQ)
2549RICHCMP_WRAPPER(ne, Py_NE)
2550RICHCMP_WRAPPER(gt, Py_GT)
2551RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002552
2553#undef RICHCMP_ENTRY
2554#define RICHCMP_ENTRY(NAME, EXPR) \
2555 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2556 "x.__" #NAME "__(y) <==> " EXPR}
2557
2558static struct wrapperbase tab_richcmp[] = {
2559 RICHCMP_ENTRY(lt, "x<y"),
2560 RICHCMP_ENTRY(le, "x<=y"),
2561 RICHCMP_ENTRY(eq, "x==y"),
2562 RICHCMP_ENTRY(ne, "x!=y"),
2563 RICHCMP_ENTRY(gt, "x>y"),
2564 RICHCMP_ENTRY(ge, "x>=y"),
2565 {0}
2566};
2567
2568static struct wrapperbase tab_iter[] = {
2569 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2570 {0}
2571};
2572
2573static PyObject *
2574wrap_next(PyObject *self, PyObject *args, void *wrapped)
2575{
2576 unaryfunc func = (unaryfunc)wrapped;
2577 PyObject *res;
2578
2579 if (!PyArg_ParseTuple(args, ""))
2580 return NULL;
2581 res = (*func)(self);
2582 if (res == NULL && !PyErr_Occurred())
2583 PyErr_SetNone(PyExc_StopIteration);
2584 return res;
2585}
2586
2587static struct wrapperbase tab_next[] = {
2588 {"next", (wrapperfunc)wrap_next,
2589 "x.next() -> the next value, or raise StopIteration"},
2590 {0}
2591};
2592
2593static PyObject *
2594wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2595{
2596 descrgetfunc func = (descrgetfunc)wrapped;
2597 PyObject *obj;
2598 PyObject *type = NULL;
2599
2600 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2601 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002602 return (*func)(self, obj, type);
2603}
2604
2605static struct wrapperbase tab_descr_get[] = {
2606 {"__get__", (wrapperfunc)wrap_descr_get,
2607 "descr.__get__(obj, type) -> value"},
2608 {0}
2609};
2610
2611static PyObject *
2612wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2613{
2614 descrsetfunc func = (descrsetfunc)wrapped;
2615 PyObject *obj, *value;
2616 int ret;
2617
2618 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2619 return NULL;
2620 ret = (*func)(self, obj, value);
2621 if (ret < 0)
2622 return NULL;
2623 Py_INCREF(Py_None);
2624 return Py_None;
2625}
2626
2627static struct wrapperbase tab_descr_set[] = {
2628 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2629 "descr.__set__(obj, value)"},
2630 {0}
2631};
2632
2633static PyObject *
2634wrap_init(PyObject *self, PyObject *args, void *wrapped)
2635{
2636 initproc func = (initproc)wrapped;
2637
2638 /* XXX What about keyword arguments? */
2639 if (func(self, args, NULL) < 0)
2640 return NULL;
2641 Py_INCREF(Py_None);
2642 return Py_None;
2643}
2644
2645static struct wrapperbase tab_init[] = {
2646 {"__init__", (wrapperfunc)wrap_init,
2647 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002648 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002649 {0}
2650};
2651
2652static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002653tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002654{
Barry Warsaw60f01882001-08-22 19:24:42 +00002655 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002656 PyObject *arg0, *res;
2657
2658 if (self == NULL || !PyType_Check(self))
2659 Py_FatalError("__new__() called with non-type 'self'");
2660 type = (PyTypeObject *)self;
2661 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002662 PyErr_Format(PyExc_TypeError,
2663 "%s.__new__(): not enough arguments",
2664 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002665 return NULL;
2666 }
2667 arg0 = PyTuple_GET_ITEM(args, 0);
2668 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002669 PyErr_Format(PyExc_TypeError,
2670 "%s.__new__(X): X is not a type object (%s)",
2671 type->tp_name,
2672 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002673 return NULL;
2674 }
2675 subtype = (PyTypeObject *)arg0;
2676 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002677 PyErr_Format(PyExc_TypeError,
2678 "%s.__new__(%s): %s is not a subtype of %s",
2679 type->tp_name,
2680 subtype->tp_name,
2681 subtype->tp_name,
2682 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002683 return NULL;
2684 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002685
2686 /* Check that the use doesn't do something silly and unsafe like
2687 object.__new__(dictionary). To do this, we check that the
2688 most derived base that's not a heap type is this type. */
2689 staticbase = subtype;
2690 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2691 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002692 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002693 PyErr_Format(PyExc_TypeError,
2694 "%s.__new__(%s) is not safe, use %s.__new__()",
2695 type->tp_name,
2696 subtype->tp_name,
2697 staticbase == NULL ? "?" : staticbase->tp_name);
2698 return NULL;
2699 }
2700
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002701 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2702 if (args == NULL)
2703 return NULL;
2704 res = type->tp_new(subtype, args, kwds);
2705 Py_DECREF(args);
2706 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002707}
2708
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002709static struct PyMethodDef tp_new_methoddef[] = {
2710 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2711 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712 {0}
2713};
2714
2715static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002716add_tp_new_wrapper(PyTypeObject *type)
2717{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002718 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002719
Guido van Rossumf040ede2001-08-07 16:40:56 +00002720 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2721 return 0;
2722 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002723 if (func == NULL)
2724 return -1;
2725 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2726}
2727
Guido van Rossum13d52f02001-08-10 21:24:08 +00002728static int
2729add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2730{
2731 PyObject *dict = type->tp_defined;
2732
2733 for (; wraps->name != NULL; wraps++) {
2734 PyObject *descr;
2735 if (PyDict_GetItemString(dict, wraps->name))
2736 continue;
2737 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2738 if (descr == NULL)
2739 return -1;
2740 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2741 return -1;
2742 Py_DECREF(descr);
2743 }
2744 return 0;
2745}
2746
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002747/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002748 dictionary with method descriptors for function slots. For each
2749 function slot (like tp_repr) that's defined in the type, one or
2750 more corresponding descriptors are added in the type's tp_defined
2751 dictionary under the appropriate name (like __repr__). Some
2752 function slots cause more than one descriptor to be added (for
2753 example, the nb_add slot adds both __add__ and __radd__
2754 descriptors) and some function slots compete for the same
2755 descriptor (for example both sq_item and mp_subscript generate a
2756 __getitem__ descriptor). This only adds new descriptors and
2757 doesn't overwrite entries in tp_defined that were previously
2758 defined. The descriptors contain a reference to the C function
2759 they must call, so that it's safe if they are copied into a
2760 subtype's __dict__ and the subtype has a different C function in
2761 its slot -- calling the method defined by the descriptor will call
2762 the C function that was used to create it, rather than the C
2763 function present in the slot when it is called. (This is important
2764 because a subtype may have a C function in the slot that calls the
2765 method from the dictionary, and we want to avoid infinite recursion
2766 here.) */
2767
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002768static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769add_operators(PyTypeObject *type)
2770{
2771 PySequenceMethods *sq;
2772 PyMappingMethods *mp;
2773 PyNumberMethods *nb;
2774
2775#undef ADD
2776#define ADD(SLOT, TABLE) \
2777 if (SLOT) { \
2778 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2779 return -1; \
2780 }
2781
2782 if ((sq = type->tp_as_sequence) != NULL) {
2783 ADD(sq->sq_length, tab_len);
2784 ADD(sq->sq_concat, tab_concat);
2785 ADD(sq->sq_repeat, tab_mul_int);
2786 ADD(sq->sq_item, tab_getitem_int);
2787 ADD(sq->sq_slice, tab_getslice);
2788 ADD(sq->sq_ass_item, tab_setitem_int);
2789 ADD(sq->sq_ass_slice, tab_setslice);
2790 ADD(sq->sq_contains, tab_contains);
2791 ADD(sq->sq_inplace_concat, tab_iadd);
2792 ADD(sq->sq_inplace_repeat, tab_imul_int);
2793 }
2794
2795 if ((mp = type->tp_as_mapping) != NULL) {
2796 if (sq->sq_length == NULL)
2797 ADD(mp->mp_length, tab_len);
2798 ADD(mp->mp_subscript, tab_getitem);
2799 ADD(mp->mp_ass_subscript, tab_setitem);
2800 }
2801
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002802 if ((nb = type->tp_as_number) != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803 ADD(nb->nb_add, tab_add);
2804 ADD(nb->nb_subtract, tab_sub);
2805 ADD(nb->nb_multiply, tab_mul);
2806 ADD(nb->nb_divide, tab_div);
2807 ADD(nb->nb_remainder, tab_mod);
2808 ADD(nb->nb_divmod, tab_divmod);
2809 ADD(nb->nb_power, tab_pow);
2810 ADD(nb->nb_negative, tab_neg);
2811 ADD(nb->nb_positive, tab_pos);
2812 ADD(nb->nb_absolute, tab_abs);
2813 ADD(nb->nb_nonzero, tab_nonzero);
2814 ADD(nb->nb_invert, tab_invert);
2815 ADD(nb->nb_lshift, tab_lshift);
2816 ADD(nb->nb_rshift, tab_rshift);
2817 ADD(nb->nb_and, tab_and);
2818 ADD(nb->nb_xor, tab_xor);
2819 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002820 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002821 ADD(nb->nb_int, tab_int);
2822 ADD(nb->nb_long, tab_long);
2823 ADD(nb->nb_float, tab_float);
2824 ADD(nb->nb_oct, tab_oct);
2825 ADD(nb->nb_hex, tab_hex);
2826 ADD(nb->nb_inplace_add, tab_iadd);
2827 ADD(nb->nb_inplace_subtract, tab_isub);
2828 ADD(nb->nb_inplace_multiply, tab_imul);
2829 ADD(nb->nb_inplace_divide, tab_idiv);
2830 ADD(nb->nb_inplace_remainder, tab_imod);
2831 ADD(nb->nb_inplace_power, tab_ipow);
2832 ADD(nb->nb_inplace_lshift, tab_ilshift);
2833 ADD(nb->nb_inplace_rshift, tab_irshift);
2834 ADD(nb->nb_inplace_and, tab_iand);
2835 ADD(nb->nb_inplace_xor, tab_ixor);
2836 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002837 if (type->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossum874f15a2001-09-25 21:16:33 +00002838 ADD(nb->nb_floor_divide, tab_floordiv);
2839 ADD(nb->nb_true_divide, tab_truediv);
2840 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2841 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2842 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002843 }
2844
2845 ADD(type->tp_getattro, tab_getattr);
2846 ADD(type->tp_setattro, tab_setattr);
2847 ADD(type->tp_compare, tab_cmp);
2848 ADD(type->tp_repr, tab_repr);
2849 ADD(type->tp_hash, tab_hash);
2850 ADD(type->tp_call, tab_call);
2851 ADD(type->tp_str, tab_str);
2852 ADD(type->tp_richcompare, tab_richcmp);
2853 ADD(type->tp_iter, tab_iter);
2854 ADD(type->tp_iternext, tab_next);
2855 ADD(type->tp_descr_get, tab_descr_get);
2856 ADD(type->tp_descr_set, tab_descr_set);
2857 ADD(type->tp_init, tab_init);
2858
Guido van Rossumf040ede2001-08-07 16:40:56 +00002859 if (type->tp_new != NULL) {
2860 if (add_tp_new_wrapper(type) < 0)
2861 return -1;
2862 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002863
2864 return 0;
2865}
2866
Guido van Rossumf040ede2001-08-07 16:40:56 +00002867/* Slot wrappers that call the corresponding __foo__ slot. See comments
2868 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002869
Guido van Rossumdc91b992001-08-08 22:26:22 +00002870#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002871static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002872FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002873{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002874 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002875 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002876}
2877
Guido van Rossumdc91b992001-08-08 22:26:22 +00002878#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002879static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002880FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002881{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002882 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002883 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002884}
2885
Guido van Rossumdc91b992001-08-08 22:26:22 +00002886
2887#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002889FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002890{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002891 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002892 int do_other = self->ob_type != other->ob_type && \
2893 other->ob_type->tp_as_number != NULL && \
2894 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002895 if (self->ob_type->tp_as_number != NULL && \
2896 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2897 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002898 if (do_other && \
2899 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2900 r = call_maybe( \
2901 other, ROPSTR, &rcache_str, "(O)", self); \
2902 if (r != Py_NotImplemented) \
2903 return r; \
2904 Py_DECREF(r); \
2905 do_other = 0; \
2906 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002907 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002908 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002909 if (r != Py_NotImplemented || \
2910 other->ob_type == self->ob_type) \
2911 return r; \
2912 Py_DECREF(r); \
2913 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002914 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002915 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002916 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002917 } \
2918 Py_INCREF(Py_NotImplemented); \
2919 return Py_NotImplemented; \
2920}
2921
2922#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2923 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2924
2925#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2926static PyObject * \
2927FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2928{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002929 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002930 return call_method(self, OPSTR, &cache_str, \
2931 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002932}
2933
2934static int
2935slot_sq_length(PyObject *self)
2936{
Guido van Rossum2730b132001-08-28 18:22:14 +00002937 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002938 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002939 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002940
2941 if (res == NULL)
2942 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002943 len = (int)PyInt_AsLong(res);
2944 Py_DECREF(res);
2945 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946}
2947
Guido van Rossumdc91b992001-08-08 22:26:22 +00002948SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2949SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002950
2951/* Super-optimized version of slot_sq_item.
2952 Other slots could do the same... */
2953static PyObject *
2954slot_sq_item(PyObject *self, int i)
2955{
2956 static PyObject *getitem_str;
2957 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2958 descrgetfunc f;
2959
2960 if (getitem_str == NULL) {
2961 getitem_str = PyString_InternFromString("__getitem__");
2962 if (getitem_str == NULL)
2963 return NULL;
2964 }
2965 func = _PyType_Lookup(self->ob_type, getitem_str);
2966 if (func != NULL) {
2967 if (func->ob_type == &PyWrapperDescr_Type) {
2968 PyWrapperDescrObject *wrapper =
2969 (PyWrapperDescrObject *)func;
2970 if (wrapper->d_base->wrapper == wrap_sq_item) {
2971 intargfunc f;
2972 f = (intargfunc)(wrapper->d_wrapped);
2973 return f(self, i);
2974 }
2975 }
2976 if ((f = func->ob_type->tp_descr_get) == NULL)
2977 Py_INCREF(func);
2978 else
2979 func = f(func, self, (PyObject *)(self->ob_type));
2980 ival = PyInt_FromLong(i);
2981 if (ival != NULL) {
2982 args = PyTuple_New(1);
2983 if (args != NULL) {
2984 PyTuple_SET_ITEM(args, 0, ival);
2985 retval = PyObject_Call(func, args, NULL);
2986 Py_XDECREF(args);
2987 Py_XDECREF(func);
2988 return retval;
2989 }
2990 }
2991 }
2992 else {
2993 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2994 }
2995 Py_XDECREF(args);
2996 Py_XDECREF(ival);
2997 Py_XDECREF(func);
2998 return NULL;
2999}
3000
Guido van Rossumdc91b992001-08-08 22:26:22 +00003001SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003002
3003static int
3004slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3005{
3006 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003007 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003008
3009 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003010 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003011 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003013 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003014 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015 if (res == NULL)
3016 return -1;
3017 Py_DECREF(res);
3018 return 0;
3019}
3020
3021static int
3022slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3023{
3024 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003025 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003026
3027 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003028 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003029 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003031 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003032 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003033 if (res == NULL)
3034 return -1;
3035 Py_DECREF(res);
3036 return 0;
3037}
3038
3039static int
3040slot_sq_contains(PyObject *self, PyObject *value)
3041{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003042 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003043 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044
Guido van Rossum55f20992001-10-01 17:18:22 +00003045 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003046
3047 if (func != NULL) {
3048 args = Py_BuildValue("(O)", value);
3049 if (args == NULL)
3050 res = NULL;
3051 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003052 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003053 Py_DECREF(args);
3054 }
3055 Py_DECREF(func);
3056 if (res == NULL)
3057 return -1;
3058 return PyObject_IsTrue(res);
3059 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003060 else if (PyErr_Occurred())
3061 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003062 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003063 return _PySequence_IterSearch(self, value,
3064 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003065 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003066}
3067
Guido van Rossumdc91b992001-08-08 22:26:22 +00003068SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3069SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003070
3071#define slot_mp_length slot_sq_length
3072
Guido van Rossumdc91b992001-08-08 22:26:22 +00003073SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003074
3075static int
3076slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3077{
3078 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003079 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003080
3081 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003082 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003083 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003084 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003085 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003086 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003087 if (res == NULL)
3088 return -1;
3089 Py_DECREF(res);
3090 return 0;
3091}
3092
Guido van Rossumdc91b992001-08-08 22:26:22 +00003093SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3094SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3095SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3096SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3097SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3098SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3099
3100staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3101
3102SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3103 nb_power, "__pow__", "__rpow__")
3104
3105static PyObject *
3106slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3107{
Guido van Rossum2730b132001-08-28 18:22:14 +00003108 static PyObject *pow_str;
3109
Guido van Rossumdc91b992001-08-08 22:26:22 +00003110 if (modulus == Py_None)
3111 return slot_nb_power_binary(self, other);
3112 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003113 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003114 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003115}
3116
3117SLOT0(slot_nb_negative, "__neg__")
3118SLOT0(slot_nb_positive, "__pos__")
3119SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003120
3121static int
3122slot_nb_nonzero(PyObject *self)
3123{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003124 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003125 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003126
Guido van Rossum55f20992001-10-01 17:18:22 +00003127 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003128 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003129 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003130 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003131 func = lookup_maybe(self, "__len__", &len_str);
3132 if (func == NULL) {
3133 if (PyErr_Occurred())
3134 return -1;
3135 else
3136 return 1;
3137 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003138 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003139 res = PyObject_CallObject(func, NULL);
3140 Py_DECREF(func);
3141 if (res == NULL)
3142 return -1;
3143 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003144}
3145
Guido van Rossumdc91b992001-08-08 22:26:22 +00003146SLOT0(slot_nb_invert, "__invert__")
3147SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3148SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3149SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3150SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3151SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003152
3153static int
3154slot_nb_coerce(PyObject **a, PyObject **b)
3155{
3156 static PyObject *coerce_str;
3157 PyObject *self = *a, *other = *b;
3158
3159 if (self->ob_type->tp_as_number != NULL &&
3160 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3161 PyObject *r;
3162 r = call_maybe(
3163 self, "__coerce__", &coerce_str, "(O)", other);
3164 if (r == NULL)
3165 return -1;
3166 if (r == Py_NotImplemented) {
3167 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003168 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003169 else {
3170 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3171 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003172 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003173 Py_DECREF(r);
3174 return -1;
3175 }
3176 *a = PyTuple_GET_ITEM(r, 0);
3177 Py_INCREF(*a);
3178 *b = PyTuple_GET_ITEM(r, 1);
3179 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003180 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003181 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003182 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003183 }
3184 if (other->ob_type->tp_as_number != NULL &&
3185 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3186 PyObject *r;
3187 r = call_maybe(
3188 other, "__coerce__", &coerce_str, "(O)", self);
3189 if (r == NULL)
3190 return -1;
3191 if (r == Py_NotImplemented) {
3192 Py_DECREF(r);
3193 return 1;
3194 }
3195 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3196 PyErr_SetString(PyExc_TypeError,
3197 "__coerce__ didn't return a 2-tuple");
3198 Py_DECREF(r);
3199 return -1;
3200 }
3201 *a = PyTuple_GET_ITEM(r, 1);
3202 Py_INCREF(*a);
3203 *b = PyTuple_GET_ITEM(r, 0);
3204 Py_INCREF(*b);
3205 Py_DECREF(r);
3206 return 0;
3207 }
3208 return 1;
3209}
3210
Guido van Rossumdc91b992001-08-08 22:26:22 +00003211SLOT0(slot_nb_int, "__int__")
3212SLOT0(slot_nb_long, "__long__")
3213SLOT0(slot_nb_float, "__float__")
3214SLOT0(slot_nb_oct, "__oct__")
3215SLOT0(slot_nb_hex, "__hex__")
3216SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3217SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3218SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3219SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3220SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3221SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3222SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3223SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3224SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3225SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3226SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3227SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3228 "__floordiv__", "__rfloordiv__")
3229SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3230SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3231SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003232
3233static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003234half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003235{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003236 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003237 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003238 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003239
Guido van Rossum60718732001-08-28 17:47:51 +00003240 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003241 if (func == NULL) {
3242 PyErr_Clear();
3243 }
3244 else {
3245 args = Py_BuildValue("(O)", other);
3246 if (args == NULL)
3247 res = NULL;
3248 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003249 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003250 Py_DECREF(args);
3251 }
3252 if (res != Py_NotImplemented) {
3253 if (res == NULL)
3254 return -2;
3255 c = PyInt_AsLong(res);
3256 Py_DECREF(res);
3257 if (c == -1 && PyErr_Occurred())
3258 return -2;
3259 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3260 }
3261 Py_DECREF(res);
3262 }
3263 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003264}
3265
Guido van Rossumab3b0342001-09-18 20:38:53 +00003266/* This slot is published for the benefit of try_3way_compare in object.c */
3267int
3268_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003269{
3270 int c;
3271
Guido van Rossumab3b0342001-09-18 20:38:53 +00003272 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003273 c = half_compare(self, other);
3274 if (c <= 1)
3275 return c;
3276 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003277 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003278 c = half_compare(other, self);
3279 if (c < -1)
3280 return -2;
3281 if (c <= 1)
3282 return -c;
3283 }
3284 return (void *)self < (void *)other ? -1 :
3285 (void *)self > (void *)other ? 1 : 0;
3286}
3287
3288static PyObject *
3289slot_tp_repr(PyObject *self)
3290{
3291 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003292 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003293
Guido van Rossum60718732001-08-28 17:47:51 +00003294 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003295 if (func != NULL) {
3296 res = PyEval_CallObject(func, NULL);
3297 Py_DECREF(func);
3298 return res;
3299 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003300 PyErr_Clear();
3301 return PyString_FromFormat("<%s object at %p>",
3302 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003303}
3304
3305static PyObject *
3306slot_tp_str(PyObject *self)
3307{
3308 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003309 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003310
Guido van Rossum60718732001-08-28 17:47:51 +00003311 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003312 if (func != NULL) {
3313 res = PyEval_CallObject(func, NULL);
3314 Py_DECREF(func);
3315 return res;
3316 }
3317 else {
3318 PyErr_Clear();
3319 return slot_tp_repr(self);
3320 }
3321}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003322
3323static long
3324slot_tp_hash(PyObject *self)
3325{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003326 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003327 static PyObject *hash_str, *eq_str, *cmp_str;
3328
Tim Peters6d6c1a32001-08-02 04:15:00 +00003329 long h;
3330
Guido van Rossum60718732001-08-28 17:47:51 +00003331 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003332
3333 if (func != NULL) {
3334 res = PyEval_CallObject(func, NULL);
3335 Py_DECREF(func);
3336 if (res == NULL)
3337 return -1;
3338 h = PyInt_AsLong(res);
3339 }
3340 else {
3341 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003342 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003343 if (func == NULL) {
3344 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003345 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003346 }
3347 if (func != NULL) {
3348 Py_DECREF(func);
3349 PyErr_SetString(PyExc_TypeError, "unhashable type");
3350 return -1;
3351 }
3352 PyErr_Clear();
3353 h = _Py_HashPointer((void *)self);
3354 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003355 if (h == -1 && !PyErr_Occurred())
3356 h = -2;
3357 return h;
3358}
3359
3360static PyObject *
3361slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3362{
Guido van Rossum60718732001-08-28 17:47:51 +00003363 static PyObject *call_str;
3364 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365 PyObject *res;
3366
3367 if (meth == NULL)
3368 return NULL;
3369 res = PyObject_Call(meth, args, kwds);
3370 Py_DECREF(meth);
3371 return res;
3372}
3373
Tim Peters6d6c1a32001-08-02 04:15:00 +00003374static PyObject *
3375slot_tp_getattro(PyObject *self, PyObject *name)
3376{
3377 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003378 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003379 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003380
Guido van Rossum8e248182001-08-12 05:17:56 +00003381 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003382 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003383 if (getattr_str == NULL)
3384 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003385 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003386 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003387 if (getattr == NULL) {
3388 /* Avoid further slowdowns */
3389 if (tp->tp_getattro == slot_tp_getattro)
3390 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003391 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003392 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393 return PyObject_CallFunction(getattr, "OO", self, name);
3394}
3395
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003396static PyObject *
3397slot_tp_getattr_hook(PyObject *self, PyObject *name)
3398{
3399 PyTypeObject *tp = self->ob_type;
3400 PyObject *getattr, *getattribute, *res;
3401 static PyObject *getattribute_str = NULL;
3402 static PyObject *getattr_str = NULL;
3403
3404 if (getattr_str == NULL) {
3405 getattr_str = PyString_InternFromString("__getattr__");
3406 if (getattr_str == NULL)
3407 return NULL;
3408 }
3409 if (getattribute_str == NULL) {
3410 getattribute_str =
3411 PyString_InternFromString("__getattribute__");
3412 if (getattribute_str == NULL)
3413 return NULL;
3414 }
3415 getattr = _PyType_Lookup(tp, getattr_str);
3416 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003417 if (getattribute != NULL &&
3418 getattribute->ob_type == &PyWrapperDescr_Type &&
3419 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3420 PyObject_GenericGetAttr)
3421 getattribute = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003422 if (getattr == NULL && getattribute == NULL) {
3423 /* Avoid further slowdowns */
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003424 /* XXX This is questionable: it means that a class that
3425 isn't born with __getattr__ or __getattribute__ cannot
3426 acquire them in later life. But it's a relatively big
3427 speedup, so I'm keeping it in for now. If this is
3428 removed, you can also remove the "def __getattr__" from
3429 class C (marked with another XXX comment) in dynamics()
3430 in Lib/test/test_descr.py. */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003431 if (tp->tp_getattro == slot_tp_getattr_hook)
3432 tp->tp_getattro = PyObject_GenericGetAttr;
3433 return PyObject_GenericGetAttr(self, name);
3434 }
3435 if (getattribute == NULL)
3436 res = PyObject_GenericGetAttr(self, name);
3437 else
3438 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003439 if (getattr != NULL &&
3440 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003441 PyErr_Clear();
3442 res = PyObject_CallFunction(getattr, "OO", self, name);
3443 }
3444 return res;
3445}
3446
Tim Peters6d6c1a32001-08-02 04:15:00 +00003447static int
3448slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3449{
3450 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003451 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003452
3453 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003454 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003455 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003456 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003457 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003458 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003459 if (res == NULL)
3460 return -1;
3461 Py_DECREF(res);
3462 return 0;
3463}
3464
3465/* Map rich comparison operators to their __xx__ namesakes */
3466static char *name_op[] = {
3467 "__lt__",
3468 "__le__",
3469 "__eq__",
3470 "__ne__",
3471 "__gt__",
3472 "__ge__",
3473};
3474
3475static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003476half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003477{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003478 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003479 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480
Guido van Rossum60718732001-08-28 17:47:51 +00003481 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003482 if (func == NULL) {
3483 PyErr_Clear();
3484 Py_INCREF(Py_NotImplemented);
3485 return Py_NotImplemented;
3486 }
3487 args = Py_BuildValue("(O)", other);
3488 if (args == NULL)
3489 res = NULL;
3490 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003491 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003492 Py_DECREF(args);
3493 }
3494 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003495 return res;
3496}
3497
Guido van Rossumb8f63662001-08-15 23:57:02 +00003498/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3499static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3500
3501static PyObject *
3502slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3503{
3504 PyObject *res;
3505
3506 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3507 res = half_richcompare(self, other, op);
3508 if (res != Py_NotImplemented)
3509 return res;
3510 Py_DECREF(res);
3511 }
3512 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3513 res = half_richcompare(other, self, swapped_op[op]);
3514 if (res != Py_NotImplemented) {
3515 return res;
3516 }
3517 Py_DECREF(res);
3518 }
3519 Py_INCREF(Py_NotImplemented);
3520 return Py_NotImplemented;
3521}
3522
3523static PyObject *
3524slot_tp_iter(PyObject *self)
3525{
3526 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003527 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003528
Guido van Rossum60718732001-08-28 17:47:51 +00003529 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003530 if (func != NULL) {
3531 res = PyObject_CallObject(func, NULL);
3532 Py_DECREF(func);
3533 return res;
3534 }
3535 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003536 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003537 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003538 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003539 return NULL;
3540 }
3541 Py_DECREF(func);
3542 return PySeqIter_New(self);
3543}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003544
3545static PyObject *
3546slot_tp_iternext(PyObject *self)
3547{
Guido van Rossum2730b132001-08-28 18:22:14 +00003548 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003549 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003550}
3551
Guido van Rossum1a493502001-08-17 16:47:50 +00003552static PyObject *
3553slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3554{
3555 PyTypeObject *tp = self->ob_type;
3556 PyObject *get;
3557 static PyObject *get_str = NULL;
3558
3559 if (get_str == NULL) {
3560 get_str = PyString_InternFromString("__get__");
3561 if (get_str == NULL)
3562 return NULL;
3563 }
3564 get = _PyType_Lookup(tp, get_str);
3565 if (get == NULL) {
3566 /* Avoid further slowdowns */
3567 if (tp->tp_descr_get == slot_tp_descr_get)
3568 tp->tp_descr_get = NULL;
3569 Py_INCREF(self);
3570 return self;
3571 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003572 if (obj == NULL)
3573 obj = Py_None;
3574 if (type == NULL)
3575 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003576 return PyObject_CallFunction(get, "OOO", self, obj, type);
3577}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003578
3579static int
3580slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3581{
Guido van Rossum2c252392001-08-24 10:13:31 +00003582 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003583 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003584
3585 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003586 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003587 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003588 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003589 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003590 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003591 if (res == NULL)
3592 return -1;
3593 Py_DECREF(res);
3594 return 0;
3595}
3596
3597static int
3598slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3599{
Guido van Rossum60718732001-08-28 17:47:51 +00003600 static PyObject *init_str;
3601 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602 PyObject *res;
3603
3604 if (meth == NULL)
3605 return -1;
3606 res = PyObject_Call(meth, args, kwds);
3607 Py_DECREF(meth);
3608 if (res == NULL)
3609 return -1;
3610 Py_DECREF(res);
3611 return 0;
3612}
3613
3614static PyObject *
3615slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3616{
3617 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3618 PyObject *newargs, *x;
3619 int i, n;
3620
3621 if (func == NULL)
3622 return NULL;
3623 assert(PyTuple_Check(args));
3624 n = PyTuple_GET_SIZE(args);
3625 newargs = PyTuple_New(n+1);
3626 if (newargs == NULL)
3627 return NULL;
3628 Py_INCREF(type);
3629 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3630 for (i = 0; i < n; i++) {
3631 x = PyTuple_GET_ITEM(args, i);
3632 Py_INCREF(x);
3633 PyTuple_SET_ITEM(newargs, i+1, x);
3634 }
3635 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003636 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637 Py_DECREF(func);
3638 return x;
3639}
3640
Guido van Rossumf040ede2001-08-07 16:40:56 +00003641/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003642 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003643 The dict argument is the dictionary argument passed to type_new(),
3644 which is the local namespace of the class statement, in other
3645 words, it contains the methods. For each special method (like
3646 __repr__) defined in the dictionary, the corresponding function
3647 slot in the type object (like tp_repr) is set to a special function
3648 whose name is 'slot_' followed by the slot name and whose signature
3649 is whatever is required for that slot. These slot functions look
3650 up the corresponding method in the type's dictionary and call it.
3651 The slot functions have to take care of the various peculiarities
3652 of the mapping between slots and special methods, such as mapping
3653 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3654 etc.) or mapping multiple slots to a single method (sq_item,
3655 mp_subscript <--> __getitem__). */
3656
Tim Peters6d6c1a32001-08-02 04:15:00 +00003657static void
3658override_slots(PyTypeObject *type, PyObject *dict)
3659{
3660 PySequenceMethods *sq = type->tp_as_sequence;
3661 PyMappingMethods *mp = type->tp_as_mapping;
3662 PyNumberMethods *nb = type->tp_as_number;
3663
Guido van Rossumdc91b992001-08-08 22:26:22 +00003664#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003665 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003666 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003667 }
3668
Guido van Rossumdc91b992001-08-08 22:26:22 +00003669#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003670 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003671 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003672 }
3673
Guido van Rossumdc91b992001-08-08 22:26:22 +00003674#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003675 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003676 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003677 }
3678
Guido van Rossumdc91b992001-08-08 22:26:22 +00003679#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003680 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003681 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682 }
3683
Guido van Rossumdc91b992001-08-08 22:26:22 +00003684 SQSLOT("__len__", sq_length, slot_sq_length);
3685 SQSLOT("__add__", sq_concat, slot_sq_concat);
3686 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3687 SQSLOT("__getitem__", sq_item, slot_sq_item);
3688 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3689 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3690 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3691 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3692 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3693 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3694 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3695 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003696
Guido van Rossumdc91b992001-08-08 22:26:22 +00003697 MPSLOT("__len__", mp_length, slot_mp_length);
3698 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3699 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3700 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003701
Guido van Rossumdc91b992001-08-08 22:26:22 +00003702 NBSLOT("__add__", nb_add, slot_nb_add);
3703 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3704 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3705 NBSLOT("__div__", nb_divide, slot_nb_divide);
3706 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3707 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3708 NBSLOT("__pow__", nb_power, slot_nb_power);
3709 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3710 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3711 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3712 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3713 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3714 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3715 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3716 NBSLOT("__and__", nb_and, slot_nb_and);
3717 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3718 NBSLOT("__or__", nb_or, slot_nb_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003719 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003720 NBSLOT("__int__", nb_int, slot_nb_int);
3721 NBSLOT("__long__", nb_long, slot_nb_long);
3722 NBSLOT("__float__", nb_float, slot_nb_float);
3723 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3724 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3725 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3726 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3727 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3728 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3729 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3730 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3731 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3732 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3733 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3734 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3735 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3736 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3737 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3738 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3739 slot_nb_inplace_floor_divide);
3740 NBSLOT("__itruediv__", nb_inplace_true_divide,
3741 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003742
Guido van Rossum8e248182001-08-12 05:17:56 +00003743 if (dict == NULL ||
3744 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003745 PyDict_GetItemString(dict, "__repr__"))
3746 type->tp_print = NULL;
3747
Guido van Rossumab3b0342001-09-18 20:38:53 +00003748 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003749 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3750 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3751 TPSLOT("__call__", tp_call, slot_tp_call);
3752 TPSLOT("__str__", tp_str, slot_tp_str);
Guido van Rossum867a8d22001-09-21 19:29:08 +00003753 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003754 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003755 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3756 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3757 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3758 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3759 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3760 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3761 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3762 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3763 TPSLOT("next", tp_iternext, slot_tp_iternext);
3764 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3765 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3766 TPSLOT("__init__", tp_init, slot_tp_init);
3767 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003768}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003769
3770
3771/* Cooperative 'super' */
3772
3773typedef struct {
3774 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003775 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003776 PyObject *obj;
3777} superobject;
3778
Guido van Rossum6f799372001-09-20 20:46:19 +00003779static PyMemberDef super_members[] = {
3780 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3781 "the class invoking super()"},
3782 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3783 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003784 {0}
3785};
3786
Guido van Rossum705f0f52001-08-24 16:47:00 +00003787static void
3788super_dealloc(PyObject *self)
3789{
3790 superobject *su = (superobject *)self;
3791
Guido van Rossum048eb752001-10-02 21:24:57 +00003792 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003793 Py_XDECREF(su->obj);
3794 Py_XDECREF(su->type);
3795 self->ob_type->tp_free(self);
3796}
3797
3798static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003799super_repr(PyObject *self)
3800{
3801 superobject *su = (superobject *)self;
3802
3803 if (su->obj)
3804 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003805 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003806 su->type ? su->type->tp_name : "NULL",
3807 su->obj->ob_type->tp_name);
3808 else
3809 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003810 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003811 su->type ? su->type->tp_name : "NULL");
3812}
3813
3814static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003815super_getattro(PyObject *self, PyObject *name)
3816{
3817 superobject *su = (superobject *)self;
3818
3819 if (su->obj != NULL) {
3820 PyObject *mro, *res, *tmp;
3821 descrgetfunc f;
3822 int i, n;
3823
Guido van Rossume705ef12001-08-29 15:47:06 +00003824 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003825 if (mro == NULL)
3826 n = 0;
3827 else {
3828 assert(PyTuple_Check(mro));
3829 n = PyTuple_GET_SIZE(mro);
3830 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003831 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003832 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003833 break;
3834 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003835 if (i >= n && PyType_Check(su->obj)) {
3836 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003837 if (mro == NULL)
3838 n = 0;
3839 else {
3840 assert(PyTuple_Check(mro));
3841 n = PyTuple_GET_SIZE(mro);
3842 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003843 for (i = 0; i < n; i++) {
3844 if ((PyObject *)(su->type) ==
3845 PyTuple_GET_ITEM(mro, i))
3846 break;
3847 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003848 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003849 i++;
3850 res = NULL;
3851 for (; i < n; i++) {
3852 tmp = PyTuple_GET_ITEM(mro, i);
3853 assert(PyType_Check(tmp));
3854 res = PyDict_GetItem(
3855 ((PyTypeObject *)tmp)->tp_defined, name);
3856 if (res != NULL) {
3857 Py_INCREF(res);
3858 f = res->ob_type->tp_descr_get;
3859 if (f != NULL) {
3860 tmp = f(res, su->obj, res);
3861 Py_DECREF(res);
3862 res = tmp;
3863 }
3864 return res;
3865 }
3866 }
3867 }
3868 return PyObject_GenericGetAttr(self, name);
3869}
3870
3871static PyObject *
3872super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3873{
3874 superobject *su = (superobject *)self;
3875 superobject *new;
3876
3877 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3878 /* Not binding to an object, or already bound */
3879 Py_INCREF(self);
3880 return self;
3881 }
3882 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3883 if (new == NULL)
3884 return NULL;
3885 Py_INCREF(su->type);
3886 Py_INCREF(obj);
3887 new->type = su->type;
3888 new->obj = obj;
3889 return (PyObject *)new;
3890}
3891
3892static int
3893super_init(PyObject *self, PyObject *args, PyObject *kwds)
3894{
3895 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003896 PyTypeObject *type;
3897 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003898
3899 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3900 return -1;
3901 if (obj == Py_None)
3902 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003903 if (obj != NULL &&
3904 !PyType_IsSubtype(obj->ob_type, type) &&
3905 !(PyType_Check(obj) &&
3906 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003907 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003908 "super(type, obj): "
3909 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003910 return -1;
3911 }
3912 Py_INCREF(type);
3913 Py_XINCREF(obj);
3914 su->type = type;
3915 su->obj = obj;
3916 return 0;
3917}
3918
3919static char super_doc[] =
3920"super(type) -> unbound super object\n"
3921"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003922"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003923"Typical use to call a cooperative superclass method:\n"
3924"class C(B):\n"
3925" def meth(self, arg):\n"
3926" super(C, self).meth(arg)";
3927
Guido van Rossum048eb752001-10-02 21:24:57 +00003928static int
3929super_traverse(PyObject *self, visitproc visit, void *arg)
3930{
3931 superobject *su = (superobject *)self;
3932 int err;
3933
3934#define VISIT(SLOT) \
3935 if (SLOT) { \
3936 err = visit((PyObject *)(SLOT), arg); \
3937 if (err) \
3938 return err; \
3939 }
3940
3941 VISIT(su->obj);
3942 VISIT(su->type);
3943
3944#undef VISIT
3945
3946 return 0;
3947}
3948
Guido van Rossum705f0f52001-08-24 16:47:00 +00003949PyTypeObject PySuper_Type = {
3950 PyObject_HEAD_INIT(&PyType_Type)
3951 0, /* ob_size */
3952 "super", /* tp_name */
3953 sizeof(superobject), /* tp_basicsize */
3954 0, /* tp_itemsize */
3955 /* methods */
3956 super_dealloc, /* tp_dealloc */
3957 0, /* tp_print */
3958 0, /* tp_getattr */
3959 0, /* tp_setattr */
3960 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003961 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003962 0, /* tp_as_number */
3963 0, /* tp_as_sequence */
3964 0, /* tp_as_mapping */
3965 0, /* tp_hash */
3966 0, /* tp_call */
3967 0, /* tp_str */
3968 super_getattro, /* tp_getattro */
3969 0, /* tp_setattro */
3970 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00003971 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3972 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003973 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00003974 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003975 0, /* tp_clear */
3976 0, /* tp_richcompare */
3977 0, /* tp_weaklistoffset */
3978 0, /* tp_iter */
3979 0, /* tp_iternext */
3980 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003981 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003982 0, /* tp_getset */
3983 0, /* tp_base */
3984 0, /* tp_dict */
3985 super_descr_get, /* tp_descr_get */
3986 0, /* tp_descr_set */
3987 0, /* tp_dictoffset */
3988 super_init, /* tp_init */
3989 PyType_GenericAlloc, /* tp_alloc */
3990 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00003991 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003992};