blob: 34a20e14c00aa7e8fea0bdaae856094ae9634839 [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 *
1982wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1983{
1984 binaryfunc func = (binaryfunc)wrapped;
1985 PyObject *other;
1986
1987 if (!PyArg_ParseTuple(args, "O", &other))
1988 return NULL;
1989 return (*func)(other, self);
1990}
1991
1992#undef BINARY
1993#define BINARY(NAME, OP) \
1994static struct wrapperbase tab_##NAME[] = { \
1995 {"__" #NAME "__", \
1996 (wrapperfunc)wrap_binaryfunc, \
1997 "x.__" #NAME "__(y) <==> " #OP}, \
1998 {"__r" #NAME "__", \
1999 (wrapperfunc)wrap_binaryfunc_r, \
2000 "y.__r" #NAME "__(x) <==> " #OP}, \
2001 {0} \
2002}
2003
2004BINARY(add, "x+y");
2005BINARY(sub, "x-y");
2006BINARY(mul, "x*y");
2007BINARY(div, "x/y");
2008BINARY(mod, "x%y");
2009BINARY(divmod, "divmod(x,y)");
2010BINARY(lshift, "x<<y");
2011BINARY(rshift, "x>>y");
2012BINARY(and, "x&y");
2013BINARY(xor, "x^y");
2014BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002015
2016static PyObject *
2017wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2018{
2019 coercion func = (coercion)wrapped;
2020 PyObject *other, *res;
2021 int ok;
2022
2023 if (!PyArg_ParseTuple(args, "O", &other))
2024 return NULL;
2025 ok = func(&self, &other);
2026 if (ok < 0)
2027 return NULL;
2028 if (ok > 0) {
2029 Py_INCREF(Py_NotImplemented);
2030 return Py_NotImplemented;
2031 }
2032 res = PyTuple_New(2);
2033 if (res == NULL) {
2034 Py_DECREF(self);
2035 Py_DECREF(other);
2036 return NULL;
2037 }
2038 PyTuple_SET_ITEM(res, 0, self);
2039 PyTuple_SET_ITEM(res, 1, other);
2040 return res;
2041}
2042
2043static struct wrapperbase tab_coerce[] = {
2044 {"__coerce__", (wrapperfunc)wrap_coercefunc,
2045 "x.__coerce__(y) <==> coerce(x, y)"},
2046 {0}
2047};
2048
Guido van Rossum874f15a2001-09-25 21:16:33 +00002049BINARY(floordiv, "x//y");
2050BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051
2052static PyObject *
2053wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2054{
2055 ternaryfunc func = (ternaryfunc)wrapped;
2056 PyObject *other;
2057 PyObject *third = Py_None;
2058
2059 /* Note: This wrapper only works for __pow__() */
2060
2061 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2062 return NULL;
2063 return (*func)(self, other, third);
2064}
2065
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002066static PyObject *
2067wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2068{
2069 ternaryfunc func = (ternaryfunc)wrapped;
2070 PyObject *other;
2071 PyObject *third = Py_None;
2072
2073 /* Note: This wrapper only works for __pow__() */
2074
2075 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2076 return NULL;
2077 return (*func)(other, self, third);
2078}
2079
Tim Peters6d6c1a32001-08-02 04:15:00 +00002080#undef TERNARY
2081#define TERNARY(NAME, OP) \
2082static struct wrapperbase tab_##NAME[] = { \
2083 {"__" #NAME "__", \
2084 (wrapperfunc)wrap_ternaryfunc, \
2085 "x.__" #NAME "__(y, z) <==> " #OP}, \
2086 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002087 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002088 "y.__r" #NAME "__(x, z) <==> " #OP}, \
2089 {0} \
2090}
2091
2092TERNARY(pow, "(x**y) % z");
2093
2094#undef UNARY
2095#define UNARY(NAME, OP) \
2096static struct wrapperbase tab_##NAME[] = { \
2097 {"__" #NAME "__", \
2098 (wrapperfunc)wrap_unaryfunc, \
2099 "x.__" #NAME "__() <==> " #OP}, \
2100 {0} \
2101}
2102
2103static PyObject *
2104wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2105{
2106 unaryfunc func = (unaryfunc)wrapped;
2107
2108 if (!PyArg_ParseTuple(args, ""))
2109 return NULL;
2110 return (*func)(self);
2111}
2112
2113UNARY(neg, "-x");
2114UNARY(pos, "+x");
2115UNARY(abs, "abs(x)");
2116UNARY(nonzero, "x != 0");
2117UNARY(invert, "~x");
2118UNARY(int, "int(x)");
2119UNARY(long, "long(x)");
2120UNARY(float, "float(x)");
2121UNARY(oct, "oct(x)");
2122UNARY(hex, "hex(x)");
2123
2124#undef IBINARY
2125#define IBINARY(NAME, OP) \
2126static struct wrapperbase tab_##NAME[] = { \
2127 {"__" #NAME "__", \
2128 (wrapperfunc)wrap_binaryfunc, \
2129 "x.__" #NAME "__(y) <==> " #OP}, \
2130 {0} \
2131}
2132
2133IBINARY(iadd, "x+=y");
2134IBINARY(isub, "x-=y");
2135IBINARY(imul, "x*=y");
2136IBINARY(idiv, "x/=y");
2137IBINARY(imod, "x%=y");
2138IBINARY(ilshift, "x<<=y");
2139IBINARY(irshift, "x>>=y");
2140IBINARY(iand, "x&=y");
2141IBINARY(ixor, "x^=y");
2142IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002143IBINARY(ifloordiv, "x//=y");
2144IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002145
2146#undef ITERNARY
2147#define ITERNARY(NAME, OP) \
2148static struct wrapperbase tab_##NAME[] = { \
2149 {"__" #NAME "__", \
2150 (wrapperfunc)wrap_ternaryfunc, \
2151 "x.__" #NAME "__(y) <==> " #OP}, \
2152 {0} \
2153}
2154
2155ITERNARY(ipow, "x = (x**y) % z");
2156
2157static struct wrapperbase tab_getitem[] = {
2158 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2159 "x.__getitem__(y) <==> x[y]"},
2160 {0}
2161};
2162
2163static PyObject *
2164wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2165{
2166 intargfunc func = (intargfunc)wrapped;
2167 int i;
2168
2169 if (!PyArg_ParseTuple(args, "i", &i))
2170 return NULL;
2171 return (*func)(self, i);
2172}
2173
2174static struct wrapperbase tab_mul_int[] = {
2175 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2176 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2177 {0}
2178};
2179
2180static struct wrapperbase tab_concat[] = {
2181 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2182 {0}
2183};
2184
2185static struct wrapperbase tab_imul_int[] = {
2186 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2187 {0}
2188};
2189
Guido van Rossum5d815f32001-08-17 21:57:47 +00002190static int
2191getindex(PyObject *self, PyObject *arg)
2192{
2193 int i;
2194
2195 i = PyInt_AsLong(arg);
2196 if (i == -1 && PyErr_Occurred())
2197 return -1;
2198 if (i < 0) {
2199 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2200 if (sq && sq->sq_length) {
2201 int n = (*sq->sq_length)(self);
2202 if (n < 0)
2203 return -1;
2204 i += n;
2205 }
2206 }
2207 return i;
2208}
2209
2210static PyObject *
2211wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2212{
2213 intargfunc func = (intargfunc)wrapped;
2214 PyObject *arg;
2215 int i;
2216
Guido van Rossumf4593e02001-10-03 12:09:30 +00002217 if (PyTuple_GET_SIZE(args) == 1) {
2218 arg = PyTuple_GET_ITEM(args, 0);
2219 i = getindex(self, arg);
2220 if (i == -1 && PyErr_Occurred())
2221 return NULL;
2222 return (*func)(self, i);
2223 }
2224 PyArg_ParseTuple(args, "O", &arg);
2225 assert(PyErr_Occurred());
2226 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002227}
2228
Tim Peters6d6c1a32001-08-02 04:15:00 +00002229static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002230 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002231 "x.__getitem__(i) <==> x[i]"},
2232 {0}
2233};
2234
2235static PyObject *
2236wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2237{
2238 intintargfunc func = (intintargfunc)wrapped;
2239 int i, j;
2240
2241 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2242 return NULL;
2243 return (*func)(self, i, j);
2244}
2245
2246static struct wrapperbase tab_getslice[] = {
2247 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2248 "x.__getslice__(i, j) <==> x[i:j]"},
2249 {0}
2250};
2251
2252static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002253wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002254{
2255 intobjargproc func = (intobjargproc)wrapped;
2256 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002257 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002258
Guido van Rossum5d815f32001-08-17 21:57:47 +00002259 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2260 return NULL;
2261 i = getindex(self, arg);
2262 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002263 return NULL;
2264 res = (*func)(self, i, value);
2265 if (res == -1 && PyErr_Occurred())
2266 return NULL;
2267 Py_INCREF(Py_None);
2268 return Py_None;
2269}
2270
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002271static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002272wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002273{
2274 intobjargproc func = (intobjargproc)wrapped;
2275 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002276 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002277
Guido van Rossum5d815f32001-08-17 21:57:47 +00002278 if (!PyArg_ParseTuple(args, "O", &arg))
2279 return NULL;
2280 i = getindex(self, arg);
2281 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002282 return NULL;
2283 res = (*func)(self, i, NULL);
2284 if (res == -1 && PyErr_Occurred())
2285 return NULL;
2286 Py_INCREF(Py_None);
2287 return Py_None;
2288}
2289
Tim Peters6d6c1a32001-08-02 04:15:00 +00002290static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002291 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002292 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002293 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002294 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295 {0}
2296};
2297
2298static PyObject *
2299wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2300{
2301 intintobjargproc func = (intintobjargproc)wrapped;
2302 int i, j, res;
2303 PyObject *value;
2304
2305 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2306 return NULL;
2307 res = (*func)(self, i, j, value);
2308 if (res == -1 && PyErr_Occurred())
2309 return NULL;
2310 Py_INCREF(Py_None);
2311 return Py_None;
2312}
2313
2314static struct wrapperbase tab_setslice[] = {
2315 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2316 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
2317 {0}
2318};
2319
2320/* XXX objobjproc is a misnomer; should be objargpred */
2321static PyObject *
2322wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2323{
2324 objobjproc func = (objobjproc)wrapped;
2325 int res;
2326 PyObject *value;
2327
2328 if (!PyArg_ParseTuple(args, "O", &value))
2329 return NULL;
2330 res = (*func)(self, value);
2331 if (res == -1 && PyErr_Occurred())
2332 return NULL;
2333 return PyInt_FromLong((long)res);
2334}
2335
2336static struct wrapperbase tab_contains[] = {
2337 {"__contains__", (wrapperfunc)wrap_objobjproc,
2338 "x.__contains__(y) <==> y in x"},
2339 {0}
2340};
2341
2342static PyObject *
2343wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2344{
2345 objobjargproc func = (objobjargproc)wrapped;
2346 int res;
2347 PyObject *key, *value;
2348
2349 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2350 return NULL;
2351 res = (*func)(self, key, value);
2352 if (res == -1 && PyErr_Occurred())
2353 return NULL;
2354 Py_INCREF(Py_None);
2355 return Py_None;
2356}
2357
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002358static PyObject *
2359wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2360{
2361 objobjargproc func = (objobjargproc)wrapped;
2362 int res;
2363 PyObject *key;
2364
2365 if (!PyArg_ParseTuple(args, "O", &key))
2366 return NULL;
2367 res = (*func)(self, key, NULL);
2368 if (res == -1 && PyErr_Occurred())
2369 return NULL;
2370 Py_INCREF(Py_None);
2371 return Py_None;
2372}
2373
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374static struct wrapperbase tab_setitem[] = {
2375 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2376 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002377 {"__delitem__", (wrapperfunc)wrap_delitem,
2378 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002379 {0}
2380};
2381
2382static PyObject *
2383wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2384{
2385 cmpfunc func = (cmpfunc)wrapped;
2386 int res;
2387 PyObject *other;
2388
2389 if (!PyArg_ParseTuple(args, "O", &other))
2390 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002391 if (other->ob_type->tp_compare != func &&
2392 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002393 PyErr_Format(
2394 PyExc_TypeError,
2395 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2396 self->ob_type->tp_name,
2397 self->ob_type->tp_name,
2398 other->ob_type->tp_name);
2399 return NULL;
2400 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002401 res = (*func)(self, other);
2402 if (PyErr_Occurred())
2403 return NULL;
2404 return PyInt_FromLong((long)res);
2405}
2406
2407static struct wrapperbase tab_cmp[] = {
2408 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2409 "x.__cmp__(y) <==> cmp(x,y)"},
2410 {0}
2411};
2412
2413static struct wrapperbase tab_repr[] = {
2414 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2415 "x.__repr__() <==> repr(x)"},
2416 {0}
2417};
2418
2419static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002420 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2421 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002422 {0}
2423};
2424
2425static PyObject *
2426wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2427{
2428 setattrofunc func = (setattrofunc)wrapped;
2429 int res;
2430 PyObject *name, *value;
2431
2432 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2433 return NULL;
2434 res = (*func)(self, name, value);
2435 if (res < 0)
2436 return NULL;
2437 Py_INCREF(Py_None);
2438 return Py_None;
2439}
2440
2441static PyObject *
2442wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2443{
2444 setattrofunc func = (setattrofunc)wrapped;
2445 int res;
2446 PyObject *name;
2447
2448 if (!PyArg_ParseTuple(args, "O", &name))
2449 return NULL;
2450 res = (*func)(self, name, NULL);
2451 if (res < 0)
2452 return NULL;
2453 Py_INCREF(Py_None);
2454 return Py_None;
2455}
2456
2457static struct wrapperbase tab_setattr[] = {
2458 {"__setattr__", (wrapperfunc)wrap_setattr,
2459 "x.__setattr__('name', value) <==> x.name = value"},
2460 {"__delattr__", (wrapperfunc)wrap_delattr,
2461 "x.__delattr__('name') <==> del x.name"},
2462 {0}
2463};
2464
2465static PyObject *
2466wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2467{
2468 hashfunc func = (hashfunc)wrapped;
2469 long res;
2470
2471 if (!PyArg_ParseTuple(args, ""))
2472 return NULL;
2473 res = (*func)(self);
2474 if (res == -1 && PyErr_Occurred())
2475 return NULL;
2476 return PyInt_FromLong(res);
2477}
2478
2479static struct wrapperbase tab_hash[] = {
2480 {"__hash__", (wrapperfunc)wrap_hashfunc,
2481 "x.__hash__() <==> hash(x)"},
2482 {0}
2483};
2484
2485static PyObject *
2486wrap_call(PyObject *self, PyObject *args, void *wrapped)
2487{
2488 ternaryfunc func = (ternaryfunc)wrapped;
2489
2490 /* XXX What about keyword arguments? */
2491 return (*func)(self, args, NULL);
2492}
2493
2494static struct wrapperbase tab_call[] = {
2495 {"__call__", (wrapperfunc)wrap_call,
2496 "x.__call__(...) <==> x(...)"},
2497 {0}
2498};
2499
2500static struct wrapperbase tab_str[] = {
2501 {"__str__", (wrapperfunc)wrap_unaryfunc,
2502 "x.__str__() <==> str(x)"},
2503 {0}
2504};
2505
2506static PyObject *
2507wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2508{
2509 richcmpfunc func = (richcmpfunc)wrapped;
2510 PyObject *other;
2511
2512 if (!PyArg_ParseTuple(args, "O", &other))
2513 return NULL;
2514 return (*func)(self, other, op);
2515}
2516
2517#undef RICHCMP_WRAPPER
2518#define RICHCMP_WRAPPER(NAME, OP) \
2519static PyObject * \
2520richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2521{ \
2522 return wrap_richcmpfunc(self, args, wrapped, OP); \
2523}
2524
Jack Jansen8e938b42001-08-08 15:29:49 +00002525RICHCMP_WRAPPER(lt, Py_LT)
2526RICHCMP_WRAPPER(le, Py_LE)
2527RICHCMP_WRAPPER(eq, Py_EQ)
2528RICHCMP_WRAPPER(ne, Py_NE)
2529RICHCMP_WRAPPER(gt, Py_GT)
2530RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002531
2532#undef RICHCMP_ENTRY
2533#define RICHCMP_ENTRY(NAME, EXPR) \
2534 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2535 "x.__" #NAME "__(y) <==> " EXPR}
2536
2537static struct wrapperbase tab_richcmp[] = {
2538 RICHCMP_ENTRY(lt, "x<y"),
2539 RICHCMP_ENTRY(le, "x<=y"),
2540 RICHCMP_ENTRY(eq, "x==y"),
2541 RICHCMP_ENTRY(ne, "x!=y"),
2542 RICHCMP_ENTRY(gt, "x>y"),
2543 RICHCMP_ENTRY(ge, "x>=y"),
2544 {0}
2545};
2546
2547static struct wrapperbase tab_iter[] = {
2548 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2549 {0}
2550};
2551
2552static PyObject *
2553wrap_next(PyObject *self, PyObject *args, void *wrapped)
2554{
2555 unaryfunc func = (unaryfunc)wrapped;
2556 PyObject *res;
2557
2558 if (!PyArg_ParseTuple(args, ""))
2559 return NULL;
2560 res = (*func)(self);
2561 if (res == NULL && !PyErr_Occurred())
2562 PyErr_SetNone(PyExc_StopIteration);
2563 return res;
2564}
2565
2566static struct wrapperbase tab_next[] = {
2567 {"next", (wrapperfunc)wrap_next,
2568 "x.next() -> the next value, or raise StopIteration"},
2569 {0}
2570};
2571
2572static PyObject *
2573wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2574{
2575 descrgetfunc func = (descrgetfunc)wrapped;
2576 PyObject *obj;
2577 PyObject *type = NULL;
2578
2579 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2580 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002581 return (*func)(self, obj, type);
2582}
2583
2584static struct wrapperbase tab_descr_get[] = {
2585 {"__get__", (wrapperfunc)wrap_descr_get,
2586 "descr.__get__(obj, type) -> value"},
2587 {0}
2588};
2589
2590static PyObject *
2591wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2592{
2593 descrsetfunc func = (descrsetfunc)wrapped;
2594 PyObject *obj, *value;
2595 int ret;
2596
2597 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2598 return NULL;
2599 ret = (*func)(self, obj, value);
2600 if (ret < 0)
2601 return NULL;
2602 Py_INCREF(Py_None);
2603 return Py_None;
2604}
2605
2606static struct wrapperbase tab_descr_set[] = {
2607 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2608 "descr.__set__(obj, value)"},
2609 {0}
2610};
2611
2612static PyObject *
2613wrap_init(PyObject *self, PyObject *args, void *wrapped)
2614{
2615 initproc func = (initproc)wrapped;
2616
2617 /* XXX What about keyword arguments? */
2618 if (func(self, args, NULL) < 0)
2619 return NULL;
2620 Py_INCREF(Py_None);
2621 return Py_None;
2622}
2623
2624static struct wrapperbase tab_init[] = {
2625 {"__init__", (wrapperfunc)wrap_init,
2626 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002627 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002628 {0}
2629};
2630
2631static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002632tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002633{
Barry Warsaw60f01882001-08-22 19:24:42 +00002634 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002635 PyObject *arg0, *res;
2636
2637 if (self == NULL || !PyType_Check(self))
2638 Py_FatalError("__new__() called with non-type 'self'");
2639 type = (PyTypeObject *)self;
2640 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002641 PyErr_Format(PyExc_TypeError,
2642 "%s.__new__(): not enough arguments",
2643 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002644 return NULL;
2645 }
2646 arg0 = PyTuple_GET_ITEM(args, 0);
2647 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002648 PyErr_Format(PyExc_TypeError,
2649 "%s.__new__(X): X is not a type object (%s)",
2650 type->tp_name,
2651 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002652 return NULL;
2653 }
2654 subtype = (PyTypeObject *)arg0;
2655 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002656 PyErr_Format(PyExc_TypeError,
2657 "%s.__new__(%s): %s is not a subtype of %s",
2658 type->tp_name,
2659 subtype->tp_name,
2660 subtype->tp_name,
2661 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002662 return NULL;
2663 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002664
2665 /* Check that the use doesn't do something silly and unsafe like
2666 object.__new__(dictionary). To do this, we check that the
2667 most derived base that's not a heap type is this type. */
2668 staticbase = subtype;
2669 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2670 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002671 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002672 PyErr_Format(PyExc_TypeError,
2673 "%s.__new__(%s) is not safe, use %s.__new__()",
2674 type->tp_name,
2675 subtype->tp_name,
2676 staticbase == NULL ? "?" : staticbase->tp_name);
2677 return NULL;
2678 }
2679
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002680 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2681 if (args == NULL)
2682 return NULL;
2683 res = type->tp_new(subtype, args, kwds);
2684 Py_DECREF(args);
2685 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002686}
2687
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002688static struct PyMethodDef tp_new_methoddef[] = {
2689 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2690 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002691 {0}
2692};
2693
2694static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002695add_tp_new_wrapper(PyTypeObject *type)
2696{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002697 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002698
Guido van Rossumf040ede2001-08-07 16:40:56 +00002699 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2700 return 0;
2701 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002702 if (func == NULL)
2703 return -1;
2704 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2705}
2706
Guido van Rossum13d52f02001-08-10 21:24:08 +00002707static int
2708add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2709{
2710 PyObject *dict = type->tp_defined;
2711
2712 for (; wraps->name != NULL; wraps++) {
2713 PyObject *descr;
2714 if (PyDict_GetItemString(dict, wraps->name))
2715 continue;
2716 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2717 if (descr == NULL)
2718 return -1;
2719 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2720 return -1;
2721 Py_DECREF(descr);
2722 }
2723 return 0;
2724}
2725
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002726/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002727 dictionary with method descriptors for function slots. For each
2728 function slot (like tp_repr) that's defined in the type, one or
2729 more corresponding descriptors are added in the type's tp_defined
2730 dictionary under the appropriate name (like __repr__). Some
2731 function slots cause more than one descriptor to be added (for
2732 example, the nb_add slot adds both __add__ and __radd__
2733 descriptors) and some function slots compete for the same
2734 descriptor (for example both sq_item and mp_subscript generate a
2735 __getitem__ descriptor). This only adds new descriptors and
2736 doesn't overwrite entries in tp_defined that were previously
2737 defined. The descriptors contain a reference to the C function
2738 they must call, so that it's safe if they are copied into a
2739 subtype's __dict__ and the subtype has a different C function in
2740 its slot -- calling the method defined by the descriptor will call
2741 the C function that was used to create it, rather than the C
2742 function present in the slot when it is called. (This is important
2743 because a subtype may have a C function in the slot that calls the
2744 method from the dictionary, and we want to avoid infinite recursion
2745 here.) */
2746
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002747static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748add_operators(PyTypeObject *type)
2749{
2750 PySequenceMethods *sq;
2751 PyMappingMethods *mp;
2752 PyNumberMethods *nb;
2753
2754#undef ADD
2755#define ADD(SLOT, TABLE) \
2756 if (SLOT) { \
2757 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2758 return -1; \
2759 }
2760
2761 if ((sq = type->tp_as_sequence) != NULL) {
2762 ADD(sq->sq_length, tab_len);
2763 ADD(sq->sq_concat, tab_concat);
2764 ADD(sq->sq_repeat, tab_mul_int);
2765 ADD(sq->sq_item, tab_getitem_int);
2766 ADD(sq->sq_slice, tab_getslice);
2767 ADD(sq->sq_ass_item, tab_setitem_int);
2768 ADD(sq->sq_ass_slice, tab_setslice);
2769 ADD(sq->sq_contains, tab_contains);
2770 ADD(sq->sq_inplace_concat, tab_iadd);
2771 ADD(sq->sq_inplace_repeat, tab_imul_int);
2772 }
2773
2774 if ((mp = type->tp_as_mapping) != NULL) {
2775 if (sq->sq_length == NULL)
2776 ADD(mp->mp_length, tab_len);
2777 ADD(mp->mp_subscript, tab_getitem);
2778 ADD(mp->mp_ass_subscript, tab_setitem);
2779 }
2780
2781 /* We don't support "old-style numbers" because their binary
2782 operators require that both arguments have the same type;
2783 the wrappers here only work for new-style numbers. */
2784 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2785 (nb = type->tp_as_number) != NULL) {
2786 ADD(nb->nb_add, tab_add);
2787 ADD(nb->nb_subtract, tab_sub);
2788 ADD(nb->nb_multiply, tab_mul);
2789 ADD(nb->nb_divide, tab_div);
2790 ADD(nb->nb_remainder, tab_mod);
2791 ADD(nb->nb_divmod, tab_divmod);
2792 ADD(nb->nb_power, tab_pow);
2793 ADD(nb->nb_negative, tab_neg);
2794 ADD(nb->nb_positive, tab_pos);
2795 ADD(nb->nb_absolute, tab_abs);
2796 ADD(nb->nb_nonzero, tab_nonzero);
2797 ADD(nb->nb_invert, tab_invert);
2798 ADD(nb->nb_lshift, tab_lshift);
2799 ADD(nb->nb_rshift, tab_rshift);
2800 ADD(nb->nb_and, tab_and);
2801 ADD(nb->nb_xor, tab_xor);
2802 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002803 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002804 ADD(nb->nb_int, tab_int);
2805 ADD(nb->nb_long, tab_long);
2806 ADD(nb->nb_float, tab_float);
2807 ADD(nb->nb_oct, tab_oct);
2808 ADD(nb->nb_hex, tab_hex);
2809 ADD(nb->nb_inplace_add, tab_iadd);
2810 ADD(nb->nb_inplace_subtract, tab_isub);
2811 ADD(nb->nb_inplace_multiply, tab_imul);
2812 ADD(nb->nb_inplace_divide, tab_idiv);
2813 ADD(nb->nb_inplace_remainder, tab_imod);
2814 ADD(nb->nb_inplace_power, tab_ipow);
2815 ADD(nb->nb_inplace_lshift, tab_ilshift);
2816 ADD(nb->nb_inplace_rshift, tab_irshift);
2817 ADD(nb->nb_inplace_and, tab_iand);
2818 ADD(nb->nb_inplace_xor, tab_ixor);
2819 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum874f15a2001-09-25 21:16:33 +00002820 if (type->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2821 ADD(nb->nb_floor_divide, tab_floordiv);
2822 ADD(nb->nb_true_divide, tab_truediv);
2823 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2824 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2825 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002826 }
2827
2828 ADD(type->tp_getattro, tab_getattr);
2829 ADD(type->tp_setattro, tab_setattr);
2830 ADD(type->tp_compare, tab_cmp);
2831 ADD(type->tp_repr, tab_repr);
2832 ADD(type->tp_hash, tab_hash);
2833 ADD(type->tp_call, tab_call);
2834 ADD(type->tp_str, tab_str);
2835 ADD(type->tp_richcompare, tab_richcmp);
2836 ADD(type->tp_iter, tab_iter);
2837 ADD(type->tp_iternext, tab_next);
2838 ADD(type->tp_descr_get, tab_descr_get);
2839 ADD(type->tp_descr_set, tab_descr_set);
2840 ADD(type->tp_init, tab_init);
2841
Guido van Rossumf040ede2001-08-07 16:40:56 +00002842 if (type->tp_new != NULL) {
2843 if (add_tp_new_wrapper(type) < 0)
2844 return -1;
2845 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002846
2847 return 0;
2848}
2849
Guido van Rossumf040ede2001-08-07 16:40:56 +00002850/* Slot wrappers that call the corresponding __foo__ slot. See comments
2851 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002852
Guido van Rossumdc91b992001-08-08 22:26:22 +00002853#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002854static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002855FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002856{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002857 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002858 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002859}
2860
Guido van Rossumdc91b992001-08-08 22:26:22 +00002861#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002862static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002863FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002864{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002865 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002866 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002867}
2868
Guido van Rossumdc91b992001-08-08 22:26:22 +00002869
2870#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002871static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002872FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002873{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002874 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002875 int do_other = self->ob_type != other->ob_type && \
2876 other->ob_type->tp_as_number != NULL && \
2877 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002878 if (self->ob_type->tp_as_number != NULL && \
2879 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2880 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002881 if (do_other && \
2882 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2883 r = call_maybe( \
2884 other, ROPSTR, &rcache_str, "(O)", self); \
2885 if (r != Py_NotImplemented) \
2886 return r; \
2887 Py_DECREF(r); \
2888 do_other = 0; \
2889 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002890 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002891 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002892 if (r != Py_NotImplemented || \
2893 other->ob_type == self->ob_type) \
2894 return r; \
2895 Py_DECREF(r); \
2896 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002897 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002898 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002899 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002900 } \
2901 Py_INCREF(Py_NotImplemented); \
2902 return Py_NotImplemented; \
2903}
2904
2905#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2906 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2907
2908#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2909static PyObject * \
2910FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2911{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002912 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002913 return call_method(self, OPSTR, &cache_str, \
2914 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002915}
2916
2917static int
2918slot_sq_length(PyObject *self)
2919{
Guido van Rossum2730b132001-08-28 18:22:14 +00002920 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002921 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002922 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002923
2924 if (res == NULL)
2925 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002926 len = (int)PyInt_AsLong(res);
2927 Py_DECREF(res);
2928 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002929}
2930
Guido van Rossumdc91b992001-08-08 22:26:22 +00002931SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2932SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002933
2934/* Super-optimized version of slot_sq_item.
2935 Other slots could do the same... */
2936static PyObject *
2937slot_sq_item(PyObject *self, int i)
2938{
2939 static PyObject *getitem_str;
2940 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2941 descrgetfunc f;
2942
2943 if (getitem_str == NULL) {
2944 getitem_str = PyString_InternFromString("__getitem__");
2945 if (getitem_str == NULL)
2946 return NULL;
2947 }
2948 func = _PyType_Lookup(self->ob_type, getitem_str);
2949 if (func != NULL) {
2950 if (func->ob_type == &PyWrapperDescr_Type) {
2951 PyWrapperDescrObject *wrapper =
2952 (PyWrapperDescrObject *)func;
2953 if (wrapper->d_base->wrapper == wrap_sq_item) {
2954 intargfunc f;
2955 f = (intargfunc)(wrapper->d_wrapped);
2956 return f(self, i);
2957 }
2958 }
2959 if ((f = func->ob_type->tp_descr_get) == NULL)
2960 Py_INCREF(func);
2961 else
2962 func = f(func, self, (PyObject *)(self->ob_type));
2963 ival = PyInt_FromLong(i);
2964 if (ival != NULL) {
2965 args = PyTuple_New(1);
2966 if (args != NULL) {
2967 PyTuple_SET_ITEM(args, 0, ival);
2968 retval = PyObject_Call(func, args, NULL);
2969 Py_XDECREF(args);
2970 Py_XDECREF(func);
2971 return retval;
2972 }
2973 }
2974 }
2975 else {
2976 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2977 }
2978 Py_XDECREF(args);
2979 Py_XDECREF(ival);
2980 Py_XDECREF(func);
2981 return NULL;
2982}
2983
Guido van Rossumdc91b992001-08-08 22:26:22 +00002984SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002985
2986static int
2987slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2988{
2989 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002990 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002991
2992 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002993 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002994 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002996 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002997 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002998 if (res == NULL)
2999 return -1;
3000 Py_DECREF(res);
3001 return 0;
3002}
3003
3004static int
3005slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3006{
3007 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003008 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003009
3010 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003011 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003012 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003013 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003014 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003015 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003016 if (res == NULL)
3017 return -1;
3018 Py_DECREF(res);
3019 return 0;
3020}
3021
3022static int
3023slot_sq_contains(PyObject *self, PyObject *value)
3024{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003025 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003026 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003027
Guido van Rossum55f20992001-10-01 17:18:22 +00003028 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003029
3030 if (func != NULL) {
3031 args = Py_BuildValue("(O)", value);
3032 if (args == NULL)
3033 res = NULL;
3034 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003035 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003036 Py_DECREF(args);
3037 }
3038 Py_DECREF(func);
3039 if (res == NULL)
3040 return -1;
3041 return PyObject_IsTrue(res);
3042 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003043 else if (PyErr_Occurred())
3044 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003045 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003046 return _PySequence_IterSearch(self, value,
3047 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003048 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003049}
3050
Guido van Rossumdc91b992001-08-08 22:26:22 +00003051SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3052SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003053
3054#define slot_mp_length slot_sq_length
3055
Guido van Rossumdc91b992001-08-08 22:26:22 +00003056SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003057
3058static int
3059slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3060{
3061 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003062 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003063
3064 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003065 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003066 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003068 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003069 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003070 if (res == NULL)
3071 return -1;
3072 Py_DECREF(res);
3073 return 0;
3074}
3075
Guido van Rossumdc91b992001-08-08 22:26:22 +00003076SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3077SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3078SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3079SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3080SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3081SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3082
3083staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3084
3085SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3086 nb_power, "__pow__", "__rpow__")
3087
3088static PyObject *
3089slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3090{
Guido van Rossum2730b132001-08-28 18:22:14 +00003091 static PyObject *pow_str;
3092
Guido van Rossumdc91b992001-08-08 22:26:22 +00003093 if (modulus == Py_None)
3094 return slot_nb_power_binary(self, other);
3095 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003096 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003097 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003098}
3099
3100SLOT0(slot_nb_negative, "__neg__")
3101SLOT0(slot_nb_positive, "__pos__")
3102SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103
3104static int
3105slot_nb_nonzero(PyObject *self)
3106{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003107 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003108 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109
Guido van Rossum55f20992001-10-01 17:18:22 +00003110 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003111 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003112 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003113 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003114 func = lookup_maybe(self, "__len__", &len_str);
3115 if (func == NULL) {
3116 if (PyErr_Occurred())
3117 return -1;
3118 else
3119 return 1;
3120 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003121 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003122 res = PyObject_CallObject(func, NULL);
3123 Py_DECREF(func);
3124 if (res == NULL)
3125 return -1;
3126 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003127}
3128
Guido van Rossumdc91b992001-08-08 22:26:22 +00003129SLOT0(slot_nb_invert, "__invert__")
3130SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3131SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3132SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3133SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3134SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003135
3136static int
3137slot_nb_coerce(PyObject **a, PyObject **b)
3138{
3139 static PyObject *coerce_str;
3140 PyObject *self = *a, *other = *b;
3141
3142 if (self->ob_type->tp_as_number != NULL &&
3143 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3144 PyObject *r;
3145 r = call_maybe(
3146 self, "__coerce__", &coerce_str, "(O)", other);
3147 if (r == NULL)
3148 return -1;
3149 if (r == Py_NotImplemented) {
3150 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003151 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003152 else {
3153 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3154 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003155 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003156 Py_DECREF(r);
3157 return -1;
3158 }
3159 *a = PyTuple_GET_ITEM(r, 0);
3160 Py_INCREF(*a);
3161 *b = PyTuple_GET_ITEM(r, 1);
3162 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003163 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003164 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003165 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003166 }
3167 if (other->ob_type->tp_as_number != NULL &&
3168 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3169 PyObject *r;
3170 r = call_maybe(
3171 other, "__coerce__", &coerce_str, "(O)", self);
3172 if (r == NULL)
3173 return -1;
3174 if (r == Py_NotImplemented) {
3175 Py_DECREF(r);
3176 return 1;
3177 }
3178 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3179 PyErr_SetString(PyExc_TypeError,
3180 "__coerce__ didn't return a 2-tuple");
3181 Py_DECREF(r);
3182 return -1;
3183 }
3184 *a = PyTuple_GET_ITEM(r, 1);
3185 Py_INCREF(*a);
3186 *b = PyTuple_GET_ITEM(r, 0);
3187 Py_INCREF(*b);
3188 Py_DECREF(r);
3189 return 0;
3190 }
3191 return 1;
3192}
3193
Guido van Rossumdc91b992001-08-08 22:26:22 +00003194SLOT0(slot_nb_int, "__int__")
3195SLOT0(slot_nb_long, "__long__")
3196SLOT0(slot_nb_float, "__float__")
3197SLOT0(slot_nb_oct, "__oct__")
3198SLOT0(slot_nb_hex, "__hex__")
3199SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3200SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3201SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3202SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3203SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3204SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3205SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3206SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3207SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3208SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3209SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3210SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3211 "__floordiv__", "__rfloordiv__")
3212SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3213SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3214SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003215
3216static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003217half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003219 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003220 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003221 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003222
Guido van Rossum60718732001-08-28 17:47:51 +00003223 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003224 if (func == NULL) {
3225 PyErr_Clear();
3226 }
3227 else {
3228 args = Py_BuildValue("(O)", other);
3229 if (args == NULL)
3230 res = NULL;
3231 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003232 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003233 Py_DECREF(args);
3234 }
3235 if (res != Py_NotImplemented) {
3236 if (res == NULL)
3237 return -2;
3238 c = PyInt_AsLong(res);
3239 Py_DECREF(res);
3240 if (c == -1 && PyErr_Occurred())
3241 return -2;
3242 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3243 }
3244 Py_DECREF(res);
3245 }
3246 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003247}
3248
Guido van Rossumab3b0342001-09-18 20:38:53 +00003249/* This slot is published for the benefit of try_3way_compare in object.c */
3250int
3251_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003252{
3253 int c;
3254
Guido van Rossumab3b0342001-09-18 20:38:53 +00003255 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003256 c = half_compare(self, other);
3257 if (c <= 1)
3258 return c;
3259 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003260 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003261 c = half_compare(other, self);
3262 if (c < -1)
3263 return -2;
3264 if (c <= 1)
3265 return -c;
3266 }
3267 return (void *)self < (void *)other ? -1 :
3268 (void *)self > (void *)other ? 1 : 0;
3269}
3270
3271static PyObject *
3272slot_tp_repr(PyObject *self)
3273{
3274 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003275 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003276
Guido van Rossum60718732001-08-28 17:47:51 +00003277 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003278 if (func != NULL) {
3279 res = PyEval_CallObject(func, NULL);
3280 Py_DECREF(func);
3281 return res;
3282 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003283 PyErr_Clear();
3284 return PyString_FromFormat("<%s object at %p>",
3285 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003286}
3287
3288static PyObject *
3289slot_tp_str(PyObject *self)
3290{
3291 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003292 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003293
Guido van Rossum60718732001-08-28 17:47:51 +00003294 func = lookup_method(self, "__str__", &str_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 }
3300 else {
3301 PyErr_Clear();
3302 return slot_tp_repr(self);
3303 }
3304}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003305
3306static long
3307slot_tp_hash(PyObject *self)
3308{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003309 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003310 static PyObject *hash_str, *eq_str, *cmp_str;
3311
Tim Peters6d6c1a32001-08-02 04:15:00 +00003312 long h;
3313
Guido van Rossum60718732001-08-28 17:47:51 +00003314 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003315
3316 if (func != NULL) {
3317 res = PyEval_CallObject(func, NULL);
3318 Py_DECREF(func);
3319 if (res == NULL)
3320 return -1;
3321 h = PyInt_AsLong(res);
3322 }
3323 else {
3324 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003325 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003326 if (func == NULL) {
3327 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003328 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003329 }
3330 if (func != NULL) {
3331 Py_DECREF(func);
3332 PyErr_SetString(PyExc_TypeError, "unhashable type");
3333 return -1;
3334 }
3335 PyErr_Clear();
3336 h = _Py_HashPointer((void *)self);
3337 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003338 if (h == -1 && !PyErr_Occurred())
3339 h = -2;
3340 return h;
3341}
3342
3343static PyObject *
3344slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3345{
Guido van Rossum60718732001-08-28 17:47:51 +00003346 static PyObject *call_str;
3347 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003348 PyObject *res;
3349
3350 if (meth == NULL)
3351 return NULL;
3352 res = PyObject_Call(meth, args, kwds);
3353 Py_DECREF(meth);
3354 return res;
3355}
3356
Tim Peters6d6c1a32001-08-02 04:15:00 +00003357static PyObject *
3358slot_tp_getattro(PyObject *self, PyObject *name)
3359{
3360 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003361 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003362 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003363
Guido van Rossum8e248182001-08-12 05:17:56 +00003364 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003365 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003366 if (getattr_str == NULL)
3367 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003368 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003369 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003370 if (getattr == NULL) {
3371 /* Avoid further slowdowns */
3372 if (tp->tp_getattro == slot_tp_getattro)
3373 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003374 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003375 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003376 return PyObject_CallFunction(getattr, "OO", self, name);
3377}
3378
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003379static PyObject *
3380slot_tp_getattr_hook(PyObject *self, PyObject *name)
3381{
3382 PyTypeObject *tp = self->ob_type;
3383 PyObject *getattr, *getattribute, *res;
3384 static PyObject *getattribute_str = NULL;
3385 static PyObject *getattr_str = NULL;
3386
3387 if (getattr_str == NULL) {
3388 getattr_str = PyString_InternFromString("__getattr__");
3389 if (getattr_str == NULL)
3390 return NULL;
3391 }
3392 if (getattribute_str == NULL) {
3393 getattribute_str =
3394 PyString_InternFromString("__getattribute__");
3395 if (getattribute_str == NULL)
3396 return NULL;
3397 }
3398 getattr = _PyType_Lookup(tp, getattr_str);
3399 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003400 if (getattribute != NULL &&
3401 getattribute->ob_type == &PyWrapperDescr_Type &&
3402 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3403 PyObject_GenericGetAttr)
3404 getattribute = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003405 if (getattr == NULL && getattribute == NULL) {
3406 /* Avoid further slowdowns */
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003407 /* XXX This is questionable: it means that a class that
3408 isn't born with __getattr__ or __getattribute__ cannot
3409 acquire them in later life. But it's a relatively big
3410 speedup, so I'm keeping it in for now. If this is
3411 removed, you can also remove the "def __getattr__" from
3412 class C (marked with another XXX comment) in dynamics()
3413 in Lib/test/test_descr.py. */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003414 if (tp->tp_getattro == slot_tp_getattr_hook)
3415 tp->tp_getattro = PyObject_GenericGetAttr;
3416 return PyObject_GenericGetAttr(self, name);
3417 }
3418 if (getattribute == NULL)
3419 res = PyObject_GenericGetAttr(self, name);
3420 else
3421 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003422 if (getattr != NULL &&
3423 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003424 PyErr_Clear();
3425 res = PyObject_CallFunction(getattr, "OO", self, name);
3426 }
3427 return res;
3428}
3429
Tim Peters6d6c1a32001-08-02 04:15:00 +00003430static int
3431slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3432{
3433 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003434 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003435
3436 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003437 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003438 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003439 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003440 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003441 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003442 if (res == NULL)
3443 return -1;
3444 Py_DECREF(res);
3445 return 0;
3446}
3447
3448/* Map rich comparison operators to their __xx__ namesakes */
3449static char *name_op[] = {
3450 "__lt__",
3451 "__le__",
3452 "__eq__",
3453 "__ne__",
3454 "__gt__",
3455 "__ge__",
3456};
3457
3458static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003459half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003460{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003461 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003462 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003463
Guido van Rossum60718732001-08-28 17:47:51 +00003464 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003465 if (func == NULL) {
3466 PyErr_Clear();
3467 Py_INCREF(Py_NotImplemented);
3468 return Py_NotImplemented;
3469 }
3470 args = Py_BuildValue("(O)", other);
3471 if (args == NULL)
3472 res = NULL;
3473 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003474 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003475 Py_DECREF(args);
3476 }
3477 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003478 return res;
3479}
3480
Guido van Rossumb8f63662001-08-15 23:57:02 +00003481/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3482static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3483
3484static PyObject *
3485slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3486{
3487 PyObject *res;
3488
3489 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3490 res = half_richcompare(self, other, op);
3491 if (res != Py_NotImplemented)
3492 return res;
3493 Py_DECREF(res);
3494 }
3495 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3496 res = half_richcompare(other, self, swapped_op[op]);
3497 if (res != Py_NotImplemented) {
3498 return res;
3499 }
3500 Py_DECREF(res);
3501 }
3502 Py_INCREF(Py_NotImplemented);
3503 return Py_NotImplemented;
3504}
3505
3506static PyObject *
3507slot_tp_iter(PyObject *self)
3508{
3509 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003510 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003511
Guido van Rossum60718732001-08-28 17:47:51 +00003512 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003513 if (func != NULL) {
3514 res = PyObject_CallObject(func, NULL);
3515 Py_DECREF(func);
3516 return res;
3517 }
3518 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003519 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003520 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003521 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003522 return NULL;
3523 }
3524 Py_DECREF(func);
3525 return PySeqIter_New(self);
3526}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527
3528static PyObject *
3529slot_tp_iternext(PyObject *self)
3530{
Guido van Rossum2730b132001-08-28 18:22:14 +00003531 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003532 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003533}
3534
Guido van Rossum1a493502001-08-17 16:47:50 +00003535static PyObject *
3536slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3537{
3538 PyTypeObject *tp = self->ob_type;
3539 PyObject *get;
3540 static PyObject *get_str = NULL;
3541
3542 if (get_str == NULL) {
3543 get_str = PyString_InternFromString("__get__");
3544 if (get_str == NULL)
3545 return NULL;
3546 }
3547 get = _PyType_Lookup(tp, get_str);
3548 if (get == NULL) {
3549 /* Avoid further slowdowns */
3550 if (tp->tp_descr_get == slot_tp_descr_get)
3551 tp->tp_descr_get = NULL;
3552 Py_INCREF(self);
3553 return self;
3554 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003555 if (obj == NULL)
3556 obj = Py_None;
3557 if (type == NULL)
3558 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003559 return PyObject_CallFunction(get, "OOO", self, obj, type);
3560}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003561
3562static int
3563slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3564{
Guido van Rossum2c252392001-08-24 10:13:31 +00003565 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003566 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003567
3568 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003569 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003570 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003571 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003572 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003573 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003574 if (res == NULL)
3575 return -1;
3576 Py_DECREF(res);
3577 return 0;
3578}
3579
3580static int
3581slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3582{
Guido van Rossum60718732001-08-28 17:47:51 +00003583 static PyObject *init_str;
3584 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585 PyObject *res;
3586
3587 if (meth == NULL)
3588 return -1;
3589 res = PyObject_Call(meth, args, kwds);
3590 Py_DECREF(meth);
3591 if (res == NULL)
3592 return -1;
3593 Py_DECREF(res);
3594 return 0;
3595}
3596
3597static PyObject *
3598slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3599{
3600 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3601 PyObject *newargs, *x;
3602 int i, n;
3603
3604 if (func == NULL)
3605 return NULL;
3606 assert(PyTuple_Check(args));
3607 n = PyTuple_GET_SIZE(args);
3608 newargs = PyTuple_New(n+1);
3609 if (newargs == NULL)
3610 return NULL;
3611 Py_INCREF(type);
3612 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3613 for (i = 0; i < n; i++) {
3614 x = PyTuple_GET_ITEM(args, i);
3615 Py_INCREF(x);
3616 PyTuple_SET_ITEM(newargs, i+1, x);
3617 }
3618 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003619 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003620 Py_DECREF(func);
3621 return x;
3622}
3623
Guido van Rossumf040ede2001-08-07 16:40:56 +00003624/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003625 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003626 The dict argument is the dictionary argument passed to type_new(),
3627 which is the local namespace of the class statement, in other
3628 words, it contains the methods. For each special method (like
3629 __repr__) defined in the dictionary, the corresponding function
3630 slot in the type object (like tp_repr) is set to a special function
3631 whose name is 'slot_' followed by the slot name and whose signature
3632 is whatever is required for that slot. These slot functions look
3633 up the corresponding method in the type's dictionary and call it.
3634 The slot functions have to take care of the various peculiarities
3635 of the mapping between slots and special methods, such as mapping
3636 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3637 etc.) or mapping multiple slots to a single method (sq_item,
3638 mp_subscript <--> __getitem__). */
3639
Tim Peters6d6c1a32001-08-02 04:15:00 +00003640static void
3641override_slots(PyTypeObject *type, PyObject *dict)
3642{
3643 PySequenceMethods *sq = type->tp_as_sequence;
3644 PyMappingMethods *mp = type->tp_as_mapping;
3645 PyNumberMethods *nb = type->tp_as_number;
3646
Guido van Rossumdc91b992001-08-08 22:26:22 +00003647#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003648 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003649 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003650 }
3651
Guido van Rossumdc91b992001-08-08 22:26:22 +00003652#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003653 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003654 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003655 }
3656
Guido van Rossumdc91b992001-08-08 22:26:22 +00003657#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003658 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003659 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003660 }
3661
Guido van Rossumdc91b992001-08-08 22:26:22 +00003662#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003663 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003664 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003665 }
3666
Guido van Rossumdc91b992001-08-08 22:26:22 +00003667 SQSLOT("__len__", sq_length, slot_sq_length);
3668 SQSLOT("__add__", sq_concat, slot_sq_concat);
3669 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3670 SQSLOT("__getitem__", sq_item, slot_sq_item);
3671 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3672 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3673 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3674 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3675 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3676 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3677 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3678 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003679
Guido van Rossumdc91b992001-08-08 22:26:22 +00003680 MPSLOT("__len__", mp_length, slot_mp_length);
3681 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3682 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3683 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003684
Guido van Rossumdc91b992001-08-08 22:26:22 +00003685 NBSLOT("__add__", nb_add, slot_nb_add);
3686 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3687 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3688 NBSLOT("__div__", nb_divide, slot_nb_divide);
3689 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3690 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3691 NBSLOT("__pow__", nb_power, slot_nb_power);
3692 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3693 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3694 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3695 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3696 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3697 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3698 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3699 NBSLOT("__and__", nb_and, slot_nb_and);
3700 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3701 NBSLOT("__or__", nb_or, slot_nb_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003702 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003703 NBSLOT("__int__", nb_int, slot_nb_int);
3704 NBSLOT("__long__", nb_long, slot_nb_long);
3705 NBSLOT("__float__", nb_float, slot_nb_float);
3706 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3707 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3708 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3709 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3710 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3711 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3712 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3713 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3714 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3715 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3716 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3717 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3718 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3719 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3720 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3721 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3722 slot_nb_inplace_floor_divide);
3723 NBSLOT("__itruediv__", nb_inplace_true_divide,
3724 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725
Guido van Rossum8e248182001-08-12 05:17:56 +00003726 if (dict == NULL ||
3727 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003728 PyDict_GetItemString(dict, "__repr__"))
3729 type->tp_print = NULL;
3730
Guido van Rossumab3b0342001-09-18 20:38:53 +00003731 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003732 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3733 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3734 TPSLOT("__call__", tp_call, slot_tp_call);
3735 TPSLOT("__str__", tp_str, slot_tp_str);
Guido van Rossum867a8d22001-09-21 19:29:08 +00003736 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003737 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003738 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3739 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3740 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3741 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3742 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3743 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3744 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3745 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3746 TPSLOT("next", tp_iternext, slot_tp_iternext);
3747 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3748 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3749 TPSLOT("__init__", tp_init, slot_tp_init);
3750 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003751}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003752
3753
3754/* Cooperative 'super' */
3755
3756typedef struct {
3757 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003758 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003759 PyObject *obj;
3760} superobject;
3761
Guido van Rossum6f799372001-09-20 20:46:19 +00003762static PyMemberDef super_members[] = {
3763 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3764 "the class invoking super()"},
3765 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3766 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003767 {0}
3768};
3769
Guido van Rossum705f0f52001-08-24 16:47:00 +00003770static void
3771super_dealloc(PyObject *self)
3772{
3773 superobject *su = (superobject *)self;
3774
Guido van Rossum048eb752001-10-02 21:24:57 +00003775 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003776 Py_XDECREF(su->obj);
3777 Py_XDECREF(su->type);
3778 self->ob_type->tp_free(self);
3779}
3780
3781static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003782super_repr(PyObject *self)
3783{
3784 superobject *su = (superobject *)self;
3785
3786 if (su->obj)
3787 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003788 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003789 su->type ? su->type->tp_name : "NULL",
3790 su->obj->ob_type->tp_name);
3791 else
3792 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003793 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003794 su->type ? su->type->tp_name : "NULL");
3795}
3796
3797static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003798super_getattro(PyObject *self, PyObject *name)
3799{
3800 superobject *su = (superobject *)self;
3801
3802 if (su->obj != NULL) {
3803 PyObject *mro, *res, *tmp;
3804 descrgetfunc f;
3805 int i, n;
3806
Guido van Rossume705ef12001-08-29 15:47:06 +00003807 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003808 if (mro == NULL)
3809 n = 0;
3810 else {
3811 assert(PyTuple_Check(mro));
3812 n = PyTuple_GET_SIZE(mro);
3813 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003814 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003815 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003816 break;
3817 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003818 if (i >= n && PyType_Check(su->obj)) {
3819 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003820 if (mro == NULL)
3821 n = 0;
3822 else {
3823 assert(PyTuple_Check(mro));
3824 n = PyTuple_GET_SIZE(mro);
3825 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003826 for (i = 0; i < n; i++) {
3827 if ((PyObject *)(su->type) ==
3828 PyTuple_GET_ITEM(mro, i))
3829 break;
3830 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003831 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003832 i++;
3833 res = NULL;
3834 for (; i < n; i++) {
3835 tmp = PyTuple_GET_ITEM(mro, i);
3836 assert(PyType_Check(tmp));
3837 res = PyDict_GetItem(
3838 ((PyTypeObject *)tmp)->tp_defined, name);
3839 if (res != NULL) {
3840 Py_INCREF(res);
3841 f = res->ob_type->tp_descr_get;
3842 if (f != NULL) {
3843 tmp = f(res, su->obj, res);
3844 Py_DECREF(res);
3845 res = tmp;
3846 }
3847 return res;
3848 }
3849 }
3850 }
3851 return PyObject_GenericGetAttr(self, name);
3852}
3853
3854static PyObject *
3855super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3856{
3857 superobject *su = (superobject *)self;
3858 superobject *new;
3859
3860 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3861 /* Not binding to an object, or already bound */
3862 Py_INCREF(self);
3863 return self;
3864 }
3865 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3866 if (new == NULL)
3867 return NULL;
3868 Py_INCREF(su->type);
3869 Py_INCREF(obj);
3870 new->type = su->type;
3871 new->obj = obj;
3872 return (PyObject *)new;
3873}
3874
3875static int
3876super_init(PyObject *self, PyObject *args, PyObject *kwds)
3877{
3878 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003879 PyTypeObject *type;
3880 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003881
3882 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3883 return -1;
3884 if (obj == Py_None)
3885 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003886 if (obj != NULL &&
3887 !PyType_IsSubtype(obj->ob_type, type) &&
3888 !(PyType_Check(obj) &&
3889 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003890 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003891 "super(type, obj): "
3892 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003893 return -1;
3894 }
3895 Py_INCREF(type);
3896 Py_XINCREF(obj);
3897 su->type = type;
3898 su->obj = obj;
3899 return 0;
3900}
3901
3902static char super_doc[] =
3903"super(type) -> unbound super object\n"
3904"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003905"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003906"Typical use to call a cooperative superclass method:\n"
3907"class C(B):\n"
3908" def meth(self, arg):\n"
3909" super(C, self).meth(arg)";
3910
Guido van Rossum048eb752001-10-02 21:24:57 +00003911static int
3912super_traverse(PyObject *self, visitproc visit, void *arg)
3913{
3914 superobject *su = (superobject *)self;
3915 int err;
3916
3917#define VISIT(SLOT) \
3918 if (SLOT) { \
3919 err = visit((PyObject *)(SLOT), arg); \
3920 if (err) \
3921 return err; \
3922 }
3923
3924 VISIT(su->obj);
3925 VISIT(su->type);
3926
3927#undef VISIT
3928
3929 return 0;
3930}
3931
Guido van Rossum705f0f52001-08-24 16:47:00 +00003932PyTypeObject PySuper_Type = {
3933 PyObject_HEAD_INIT(&PyType_Type)
3934 0, /* ob_size */
3935 "super", /* tp_name */
3936 sizeof(superobject), /* tp_basicsize */
3937 0, /* tp_itemsize */
3938 /* methods */
3939 super_dealloc, /* tp_dealloc */
3940 0, /* tp_print */
3941 0, /* tp_getattr */
3942 0, /* tp_setattr */
3943 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003944 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003945 0, /* tp_as_number */
3946 0, /* tp_as_sequence */
3947 0, /* tp_as_mapping */
3948 0, /* tp_hash */
3949 0, /* tp_call */
3950 0, /* tp_str */
3951 super_getattro, /* tp_getattro */
3952 0, /* tp_setattro */
3953 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00003954 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3955 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003956 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00003957 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003958 0, /* tp_clear */
3959 0, /* tp_richcompare */
3960 0, /* tp_weaklistoffset */
3961 0, /* tp_iter */
3962 0, /* tp_iternext */
3963 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003964 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003965 0, /* tp_getset */
3966 0, /* tp_base */
3967 0, /* tp_dict */
3968 super_descr_get, /* tp_descr_get */
3969 0, /* tp_descr_set */
3970 0, /* tp_dictoffset */
3971 super_init, /* tp_init */
3972 PyType_GenericAlloc, /* tp_alloc */
3973 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00003974 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003975};