blob: 26ddabe0c267f23647174a21943e5e0bc5669045 [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
Tim Peters6d6c1a32001-08-02 04:15:00 +00007static struct memberlist 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
56static PyObject *
57type_dict(PyTypeObject *type, void *context)
58{
59 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000060 Py_INCREF(Py_None);
61 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000062 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000063 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
64 Py_INCREF(type->tp_dict);
65 return type->tp_dict;
66 }
67 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000068}
69
Tim Peters6d6c1a32001-08-02 04:15:00 +000070static PyObject *
71type_defined(PyTypeObject *type, void *context)
72{
73 if (type->tp_defined == NULL) {
74 Py_INCREF(Py_None);
75 return Py_None;
76 }
77 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
78 Py_INCREF(type->tp_defined);
79 return type->tp_defined;
80 }
81 return PyDictProxy_New(type->tp_defined);
82}
83
84static PyObject *
85type_dynamic(PyTypeObject *type, void *context)
86{
87 PyObject *res;
88
89 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
90 Py_INCREF(res);
91 return res;
92}
93
94struct getsetlist type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000095 {"__name__", (getter)type_name, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000096 {"__module__", (getter)type_module, NULL, NULL},
97 {"__dict__", (getter)type_dict, NULL, NULL},
98 {"__defined__", (getter)type_defined, NULL, NULL},
99 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
100 {0}
101};
102
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000103static int
104type_compare(PyObject *v, PyObject *w)
105{
106 /* This is called with type objects only. So we
107 can just compare the addresses. */
108 Py_uintptr_t vv = (Py_uintptr_t)v;
109 Py_uintptr_t ww = (Py_uintptr_t)w;
110 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
111}
112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000114type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000115{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000116 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000117
118 mod = type_module(type, NULL);
119 if (mod == NULL)
120 PyErr_Clear();
121 else if (!PyString_Check(mod)) {
122 Py_DECREF(mod);
123 mod = NULL;
124 }
125 name = type_name(type, NULL);
126 if (name == NULL)
127 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000128
129 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
130 rtn = PyString_FromFormat("<type '%s.%s'>",
131 PyString_AS_STRING(mod),
132 PyString_AS_STRING(name));
133 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000134 else
Barry Warsaw7ce36942001-08-24 18:34:26 +0000135 rtn = PyString_FromFormat("<type '%s'>", type->tp_name);
136
Guido van Rossumc3542212001-08-16 09:18:56 +0000137 Py_XDECREF(mod);
138 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000139 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140}
141
Tim Peters6d6c1a32001-08-02 04:15:00 +0000142static PyObject *
143type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
144{
145 PyObject *obj;
146
147 if (type->tp_new == NULL) {
148 PyErr_Format(PyExc_TypeError,
149 "cannot create '%.100s' instances",
150 type->tp_name);
151 return NULL;
152 }
153
Tim Peters3f996e72001-09-13 19:18:27 +0000154 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000155 if (obj != NULL) {
156 type = obj->ob_type;
157 if (type->tp_init != NULL &&
158 type->tp_init(obj, args, kwds) < 0) {
159 Py_DECREF(obj);
160 obj = NULL;
161 }
162 }
163 return obj;
164}
165
166PyObject *
167PyType_GenericAlloc(PyTypeObject *type, int nitems)
168{
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000169#define PTRSIZE (sizeof(PyObject *))
170
Tim Peters6d6c1a32001-08-02 04:15:00 +0000171 int size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000172 PyObject *obj;
173
174 /* Inline PyObject_New() so we can zero the memory */
175 size = _PyObject_VAR_SIZE(type, nitems);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000176 /* Round up size, if necessary, so we fully zero out __dict__ */
177 if (type->tp_itemsize % PTRSIZE != 0) {
178 size += PTRSIZE - 1;
179 size /= PTRSIZE;
180 size *= PTRSIZE;
181 }
Neil Schemenauerc806c882001-08-29 23:54:54 +0000182 if (PyType_IS_GC(type)) {
183 obj = _PyObject_GC_Malloc(type, nitems);
184 }
185 else {
186 obj = PyObject_MALLOC(size);
187 }
188 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000189 return PyErr_NoMemory();
Neil Schemenauerc806c882001-08-29 23:54:54 +0000190 memset(obj, '\0', size);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000191 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
192 Py_INCREF(type);
193 if (type->tp_itemsize == 0)
194 PyObject_INIT(obj, type);
195 else
196 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
197 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000198 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000199 return obj;
200}
201
202PyObject *
203PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
204{
205 return type->tp_alloc(type, 0);
206}
207
208/* Helper for subtyping */
209
210static void
211subtype_dealloc(PyObject *self)
212{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000213 PyTypeObject *type, *base;
214 destructor f;
215
216 /* This exists so we can DECREF self->ob_type */
217
218 /* Find the nearest base with a different tp_dealloc */
219 type = self->ob_type;
220 base = type->tp_base;
221 while ((f = base->tp_dealloc) == subtype_dealloc) {
222 base = base->tp_base;
223 assert(base);
224 }
225
226 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000227 if (type->tp_dictoffset && !base->tp_dictoffset) {
228 PyObject **dictptr = _PyObject_GetDictPtr(self);
229 if (dictptr != NULL) {
230 PyObject *dict = *dictptr;
231 if (dict != NULL) {
232 Py_DECREF(dict);
233 *dictptr = NULL;
234 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000235 }
236 }
237
Guido van Rossum9676b222001-08-17 20:32:36 +0000238 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000239 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000240 PyObject_ClearWeakRefs(self);
241
Tim Peters6d6c1a32001-08-02 04:15:00 +0000242 /* Finalize GC if the base doesn't do GC and we do */
243 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
244 PyObject_GC_Fini(self);
245
246 /* Call the base tp_dealloc() */
247 assert(f);
248 f(self);
249
250 /* Can't reference self beyond this point */
251 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
252 Py_DECREF(type);
253 }
254}
255
256staticforward void override_slots(PyTypeObject *type, PyObject *dict);
257staticforward PyTypeObject *solid_base(PyTypeObject *type);
258
259typedef struct {
260 PyTypeObject type;
261 PyNumberMethods as_number;
262 PySequenceMethods as_sequence;
263 PyMappingMethods as_mapping;
264 PyBufferProcs as_buffer;
265 PyObject *name, *slots;
266 struct memberlist members[1];
267} etype;
268
269/* type test with subclassing support */
270
271int
272PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
273{
274 PyObject *mro;
275
Guido van Rossum9478d072001-09-07 18:52:13 +0000276 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
277 return b == a || b == &PyBaseObject_Type;
278
Tim Peters6d6c1a32001-08-02 04:15:00 +0000279 mro = a->tp_mro;
280 if (mro != NULL) {
281 /* Deal with multiple inheritance without recursion
282 by walking the MRO tuple */
283 int i, n;
284 assert(PyTuple_Check(mro));
285 n = PyTuple_GET_SIZE(mro);
286 for (i = 0; i < n; i++) {
287 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
288 return 1;
289 }
290 return 0;
291 }
292 else {
293 /* a is not completely initilized yet; follow tp_base */
294 do {
295 if (a == b)
296 return 1;
297 a = a->tp_base;
298 } while (a != NULL);
299 return b == &PyBaseObject_Type;
300 }
301}
302
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000303/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000304 without looking in the instance dictionary
305 (so we can't use PyObject_GetAttr) but still binding
306 it to the instance. The arguments are the object,
307 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000308 static variable used to cache the interned Python string.
309
310 Two variants:
311
312 - lookup_maybe() returns NULL without raising an exception
313 when the _PyType_Lookup() call fails;
314
315 - lookup_method() always raises an exception upon errors.
316*/
Guido van Rossum60718732001-08-28 17:47:51 +0000317
318static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000319lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000320{
321 PyObject *res;
322
323 if (*attrobj == NULL) {
324 *attrobj = PyString_InternFromString(attrstr);
325 if (*attrobj == NULL)
326 return NULL;
327 }
328 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000329 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000330 descrgetfunc f;
331 if ((f = res->ob_type->tp_descr_get) == NULL)
332 Py_INCREF(res);
333 else
334 res = f(res, self, (PyObject *)(self->ob_type));
335 }
336 return res;
337}
338
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000339static PyObject *
340lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
341{
342 PyObject *res = lookup_maybe(self, attrstr, attrobj);
343 if (res == NULL && !PyErr_Occurred())
344 PyErr_SetObject(PyExc_AttributeError, *attrobj);
345 return res;
346}
347
Guido van Rossum2730b132001-08-28 18:22:14 +0000348/* A variation of PyObject_CallMethod that uses lookup_method()
349 instead of PyObject_GetAttrString(). This uses the same convention
350 as lookup_method to cache the interned name string object. */
351
352PyObject *
353call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
354{
355 va_list va;
356 PyObject *args, *func = 0, *retval;
357 PyObject *dummy_str = NULL;
358 va_start(va, format);
359
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000360 func = lookup_maybe(o, name, &dummy_str);
361 if (func == NULL) {
362 va_end(va);
363 if (!PyErr_Occurred())
364 PyErr_SetObject(PyExc_AttributeError, dummy_str);
365 Py_XDECREF(dummy_str);
366 return NULL;
367 }
368 Py_DECREF(dummy_str);
369
370 if (format && *format)
371 args = Py_VaBuildValue(format, va);
372 else
373 args = PyTuple_New(0);
374
375 va_end(va);
376
377 if (args == NULL)
378 return NULL;
379
380 assert(PyTuple_Check(args));
381 retval = PyObject_Call(func, args, NULL);
382
383 Py_DECREF(args);
384 Py_DECREF(func);
385
386 return retval;
387}
388
389/* Clone of call_method() that returns NotImplemented when the lookup fails. */
390
391PyObject *
392call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
393{
394 va_list va;
395 PyObject *args, *func = 0, *retval;
396 PyObject *dummy_str = NULL;
397 va_start(va, format);
398
399 func = lookup_maybe(o, name, &dummy_str);
Guido van Rossum2730b132001-08-28 18:22:14 +0000400 Py_XDECREF(dummy_str);
401 if (func == NULL) {
402 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000403 if (!PyErr_Occurred()) {
404 Py_INCREF(Py_NotImplemented);
405 return Py_NotImplemented;
406 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000407 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000408 }
409
410 if (format && *format)
411 args = Py_VaBuildValue(format, va);
412 else
413 args = PyTuple_New(0);
414
415 va_end(va);
416
Guido van Rossum717ce002001-09-14 16:58:08 +0000417 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000418 return NULL;
419
Guido van Rossum717ce002001-09-14 16:58:08 +0000420 assert(PyTuple_Check(args));
421 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000422
423 Py_DECREF(args);
424 Py_DECREF(func);
425
426 return retval;
427}
428
Tim Peters6d6c1a32001-08-02 04:15:00 +0000429/* Method resolution order algorithm from "Putting Metaclasses to Work"
430 by Forman and Danforth (Addison-Wesley 1999). */
431
432static int
433conservative_merge(PyObject *left, PyObject *right)
434{
435 int left_size;
436 int right_size;
437 int i, j, r, ok;
438 PyObject *temp, *rr;
439
440 assert(PyList_Check(left));
441 assert(PyList_Check(right));
442
443 again:
444 left_size = PyList_GET_SIZE(left);
445 right_size = PyList_GET_SIZE(right);
446 for (i = 0; i < left_size; i++) {
447 for (j = 0; j < right_size; j++) {
448 if (PyList_GET_ITEM(left, i) ==
449 PyList_GET_ITEM(right, j)) {
450 /* found a merge point */
451 temp = PyList_New(0);
452 if (temp == NULL)
453 return -1;
454 for (r = 0; r < j; r++) {
455 rr = PyList_GET_ITEM(right, r);
456 ok = PySequence_Contains(left, rr);
457 if (ok < 0) {
458 Py_DECREF(temp);
459 return -1;
460 }
461 if (!ok) {
462 ok = PyList_Append(temp, rr);
463 if (ok < 0) {
464 Py_DECREF(temp);
465 return -1;
466 }
467 }
468 }
469 ok = PyList_SetSlice(left, i, i, temp);
470 Py_DECREF(temp);
471 if (ok < 0)
472 return -1;
473 ok = PyList_SetSlice(right, 0, j+1, NULL);
474 if (ok < 0)
475 return -1;
476 goto again;
477 }
478 }
479 }
480 return PyList_SetSlice(left, left_size, left_size, right);
481}
482
483static int
484serious_order_disagreements(PyObject *left, PyObject *right)
485{
486 return 0; /* XXX later -- for now, we cheat: "don't do that" */
487}
488
489static PyObject *
490mro_implementation(PyTypeObject *type)
491{
492 int i, n, ok;
493 PyObject *bases, *result;
494
495 bases = type->tp_bases;
496 n = PyTuple_GET_SIZE(bases);
497 result = Py_BuildValue("[O]", (PyObject *)type);
498 if (result == NULL)
499 return NULL;
500 for (i = 0; i < n; i++) {
501 PyTypeObject *base =
502 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
503 PyObject *parentMRO = PySequence_List(base->tp_mro);
504 if (parentMRO == NULL) {
505 Py_DECREF(result);
506 return NULL;
507 }
508 if (serious_order_disagreements(result, parentMRO)) {
509 Py_DECREF(result);
510 return NULL;
511 }
512 ok = conservative_merge(result, parentMRO);
513 Py_DECREF(parentMRO);
514 if (ok < 0) {
515 Py_DECREF(result);
516 return NULL;
517 }
518 }
519 return result;
520}
521
522static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000523mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000524{
525 PyTypeObject *type = (PyTypeObject *)self;
526
Tim Peters6d6c1a32001-08-02 04:15:00 +0000527 return mro_implementation(type);
528}
529
530static int
531mro_internal(PyTypeObject *type)
532{
533 PyObject *mro, *result, *tuple;
534
535 if (type->ob_type == &PyType_Type) {
536 result = mro_implementation(type);
537 }
538 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000539 static PyObject *mro_str;
540 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000541 if (mro == NULL)
542 return -1;
543 result = PyObject_CallObject(mro, NULL);
544 Py_DECREF(mro);
545 }
546 if (result == NULL)
547 return -1;
548 tuple = PySequence_Tuple(result);
549 Py_DECREF(result);
550 type->tp_mro = tuple;
551 return 0;
552}
553
554
555/* Calculate the best base amongst multiple base classes.
556 This is the first one that's on the path to the "solid base". */
557
558static PyTypeObject *
559best_base(PyObject *bases)
560{
561 int i, n;
562 PyTypeObject *base, *winner, *candidate, *base_i;
563
564 assert(PyTuple_Check(bases));
565 n = PyTuple_GET_SIZE(bases);
566 assert(n > 0);
567 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
568 winner = &PyBaseObject_Type;
569 for (i = 0; i < n; i++) {
570 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
571 if (!PyType_Check((PyObject *)base_i)) {
572 PyErr_SetString(
573 PyExc_TypeError,
574 "bases must be types");
575 return NULL;
576 }
577 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000578 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000579 return NULL;
580 }
581 candidate = solid_base(base_i);
582 if (PyType_IsSubtype(winner, candidate))
583 ;
584 else if (PyType_IsSubtype(candidate, winner)) {
585 winner = candidate;
586 base = base_i;
587 }
588 else {
589 PyErr_SetString(
590 PyExc_TypeError,
591 "multiple bases have "
592 "instance lay-out conflict");
593 return NULL;
594 }
595 }
596 assert(base != NULL);
597 return base;
598}
599
600static int
601extra_ivars(PyTypeObject *type, PyTypeObject *base)
602{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000603 size_t t_size = type->tp_basicsize;
604 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000605
Guido van Rossum9676b222001-08-17 20:32:36 +0000606 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000607 if (type->tp_itemsize || base->tp_itemsize) {
608 /* If itemsize is involved, stricter rules */
609 return t_size != b_size ||
610 type->tp_itemsize != base->tp_itemsize;
611 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000612 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
613 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
614 t_size -= sizeof(PyObject *);
615 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
616 type->tp_dictoffset + sizeof(PyObject *) == t_size)
617 t_size -= sizeof(PyObject *);
618
619 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000620}
621
622static PyTypeObject *
623solid_base(PyTypeObject *type)
624{
625 PyTypeObject *base;
626
627 if (type->tp_base)
628 base = solid_base(type->tp_base);
629 else
630 base = &PyBaseObject_Type;
631 if (extra_ivars(type, base))
632 return type;
633 else
634 return base;
635}
636
637staticforward void object_dealloc(PyObject *);
638staticforward int object_init(PyObject *, PyObject *, PyObject *);
639
640static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000641subtype_dict(PyObject *obj, void *context)
642{
643 PyObject **dictptr = _PyObject_GetDictPtr(obj);
644 PyObject *dict;
645
646 if (dictptr == NULL) {
647 PyErr_SetString(PyExc_AttributeError,
648 "This object has no __dict__");
649 return NULL;
650 }
651 dict = *dictptr;
652 if (dict == NULL) {
653 Py_INCREF(Py_None);
654 return Py_None;
655 }
656 else {
657 Py_INCREF(dict);
658 return dict;
659 }
660}
661
662struct getsetlist subtype_getsets[] = {
663 {"__dict__", subtype_dict, NULL, NULL},
664 {0},
665};
666
667static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000668type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
669{
670 PyObject *name, *bases, *dict;
671 static char *kwlist[] = {"name", "bases", "dict", 0};
672 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000673 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674 etype *et;
675 struct memberlist *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000676 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000678 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000679 if (metatype == &PyType_Type &&
680 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
681 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000682 PyObject *x = PyTuple_GET_ITEM(args, 0);
683 Py_INCREF(x->ob_type);
684 return (PyObject *) x->ob_type;
685 }
686
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000687 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
689 &name,
690 &PyTuple_Type, &bases,
691 &PyDict_Type, &dict))
692 return NULL;
693
694 /* Determine the proper metatype to deal with this,
695 and check for metatype conflicts while we're at it.
696 Note that if some other metatype wins to contract,
697 it's possible that its instances are not types. */
698 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000699 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700 for (i = 0; i < nbases; i++) {
701 tmp = PyTuple_GET_ITEM(bases, i);
702 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000703 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000704 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000705 if (PyType_IsSubtype(tmptype, winner)) {
706 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000707 continue;
708 }
709 PyErr_SetString(PyExc_TypeError,
710 "metatype conflict among bases");
711 return NULL;
712 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000713 if (winner != metatype) {
714 if (winner->tp_new != type_new) /* Pass it to the winner */
715 return winner->tp_new(winner, args, kwds);
716 metatype = winner;
717 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718
719 /* Adjust for empty tuple bases */
720 if (nbases == 0) {
721 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
722 if (bases == NULL)
723 return NULL;
724 nbases = 1;
725 }
726 else
727 Py_INCREF(bases);
728
729 /* XXX From here until type is allocated, "return NULL" leaks bases! */
730
731 /* Calculate best base, and check that all bases are type objects */
732 base = best_base(bases);
733 if (base == NULL)
734 return NULL;
735 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
736 PyErr_Format(PyExc_TypeError,
737 "type '%.100s' is not an acceptable base type",
738 base->tp_name);
739 return NULL;
740 }
741
Guido van Rossum1a493502001-08-17 16:47:50 +0000742 /* Should this be a dynamic class (i.e. modifiable __dict__)?
743 Look in two places for a variable named __dynamic__:
744 1) in the class dict
745 2) in the module dict (globals)
746 The first variable that is an int >= 0 is used.
747 Otherwise, a default is calculated from the base classes:
748 if any base class is dynamic, this class is dynamic; otherwise
749 it is static. */
750 dynamic = -1; /* Not yet determined */
751 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000752 tmp = PyDict_GetItemString(dict, "__dynamic__");
753 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000754 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000755 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000756 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000757 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000758 if (dynamic < 0) {
759 /* Look in the module globals */
760 tmp = PyEval_GetGlobals();
761 if (tmp != NULL) {
762 tmp = PyDict_GetItemString(tmp, "__dynamic__");
763 if (tmp != NULL) {
764 dynamic = PyInt_AsLong(tmp);
765 if (dynamic < 0)
766 PyErr_Clear();
767 }
768 }
769 }
770 if (dynamic < 0) {
771 /* Make a new class dynamic if any of its bases is
772 dynamic. This is not always the same as inheriting
773 the __dynamic__ class attribute! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000774 dynamic = 0;
775 for (i = 0; i < nbases; i++) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000776 tmptype = (PyTypeObject *)
777 PyTuple_GET_ITEM(bases, i);
778 if (tmptype->tp_flags &
779 Py_TPFLAGS_DYNAMICTYPE) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000780 dynamic = 1;
781 break;
782 }
783 }
784 }
785
786 /* Check for a __slots__ sequence variable in dict, and count it */
787 slots = PyDict_GetItemString(dict, "__slots__");
788 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000789 add_dict = 0;
790 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000791 if (slots != NULL) {
792 /* Make it into a tuple */
793 if (PyString_Check(slots))
794 slots = Py_BuildValue("(O)", slots);
795 else
796 slots = PySequence_Tuple(slots);
797 if (slots == NULL)
798 return NULL;
799 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000800 if (nslots > 0 && base->tp_itemsize != 0) {
801 PyErr_Format(PyExc_TypeError,
802 "nonempty __slots__ "
803 "not supported for subtype of '%s'",
804 base->tp_name);
805 return NULL;
806 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000807 for (i = 0; i < nslots; i++) {
808 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
809 PyErr_SetString(PyExc_TypeError,
810 "__slots__ must be a sequence of strings");
811 Py_DECREF(slots);
812 return NULL;
813 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000814 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000815 }
816 }
817 if (slots == NULL && base->tp_dictoffset == 0 &&
818 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000819 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000820 add_dict++;
821 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000822 if (slots == NULL && base->tp_weaklistoffset == 0 &&
823 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000824 nslots++;
825 add_weak++;
826 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000827
828 /* XXX From here until type is safely allocated,
829 "return NULL" may leak slots! */
830
831 /* Allocate the type object */
832 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
833 if (type == NULL)
834 return NULL;
835
836 /* Keep name and slots alive in the extended type object */
837 et = (etype *)type;
838 Py_INCREF(name);
839 et->name = name;
840 et->slots = slots;
841
Guido van Rossumdc91b992001-08-08 22:26:22 +0000842 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000843 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
844 Py_TPFLAGS_BASETYPE;
845 if (dynamic)
846 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000847
848 /* It's a new-style number unless it specifically inherits any
849 old-style numeric behavior */
850 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
851 (base->tp_as_number == NULL))
852 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
853
854 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000855 type->tp_as_number = &et->as_number;
856 type->tp_as_sequence = &et->as_sequence;
857 type->tp_as_mapping = &et->as_mapping;
858 type->tp_as_buffer = &et->as_buffer;
859 type->tp_name = PyString_AS_STRING(name);
860
861 /* Set tp_base and tp_bases */
862 type->tp_bases = bases;
863 Py_INCREF(base);
864 type->tp_base = base;
865
866 /* Initialize tp_defined from passed-in dict */
867 type->tp_defined = dict = PyDict_Copy(dict);
868 if (dict == NULL) {
869 Py_DECREF(type);
870 return NULL;
871 }
872
Guido van Rossumc3542212001-08-16 09:18:56 +0000873 /* Set __module__ in the dict */
874 if (PyDict_GetItemString(dict, "__module__") == NULL) {
875 tmp = PyEval_GetGlobals();
876 if (tmp != NULL) {
877 tmp = PyDict_GetItemString(tmp, "__name__");
878 if (tmp != NULL) {
879 if (PyDict_SetItemString(dict, "__module__",
880 tmp) < 0)
881 return NULL;
882 }
883 }
884 }
885
Tim Peters6d6c1a32001-08-02 04:15:00 +0000886 /* Special-case __new__: if it's a plain function,
887 make it a static function */
888 tmp = PyDict_GetItemString(dict, "__new__");
889 if (tmp != NULL && PyFunction_Check(tmp)) {
890 tmp = PyStaticMethod_New(tmp);
891 if (tmp == NULL) {
892 Py_DECREF(type);
893 return NULL;
894 }
895 PyDict_SetItemString(dict, "__new__", tmp);
896 Py_DECREF(tmp);
897 }
898
899 /* Add descriptors for custom slots from __slots__, or for __dict__ */
900 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000901 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000902 if (slots != NULL) {
903 for (i = 0; i < nslots; i++, mp++) {
904 mp->name = PyString_AS_STRING(
905 PyTuple_GET_ITEM(slots, i));
906 mp->type = T_OBJECT;
907 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000908 if (base->tp_weaklistoffset == 0 &&
909 strcmp(mp->name, "__weakref__") == 0)
910 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000911 slotoffset += sizeof(PyObject *);
912 }
913 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000914 else {
915 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000916 if (base->tp_itemsize)
Tim Peters017cb2c2001-08-30 20:07:55 +0000917 type->tp_dictoffset = -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000918 else
919 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000920 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000921 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000922 }
923 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000924 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000925 type->tp_weaklistoffset = slotoffset;
926 mp->name = "__weakref__";
927 mp->type = T_OBJECT;
928 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000929 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000930 mp++;
931 slotoffset += sizeof(PyObject *);
932 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000933 }
934 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000935 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000936 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000937
938 /* Special case some slots */
939 if (type->tp_dictoffset != 0 || nslots > 0) {
940 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
941 type->tp_getattro = PyObject_GenericGetAttr;
942 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
943 type->tp_setattro = PyObject_GenericSetAttr;
944 }
945 type->tp_dealloc = subtype_dealloc;
946
947 /* Always override allocation strategy to use regular heap */
948 type->tp_alloc = PyType_GenericAlloc;
949 type->tp_free = _PyObject_Del;
950
951 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000952 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000953 Py_DECREF(type);
954 return NULL;
955 }
956
957 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +0000958 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
959 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000960
Tim Peters6d6c1a32001-08-02 04:15:00 +0000961 return (PyObject *)type;
962}
963
964/* Internal API to look for a name through the MRO.
965 This returns a borrowed reference, and doesn't set an exception! */
966PyObject *
967_PyType_Lookup(PyTypeObject *type, PyObject *name)
968{
969 int i, n;
970 PyObject *mro, *res, *dict;
971
972 /* For static types, look in tp_dict */
973 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
974 dict = type->tp_dict;
975 assert(dict && PyDict_Check(dict));
976 return PyDict_GetItem(dict, name);
977 }
978
979 /* For dynamic types, look in tp_defined of types in MRO */
980 mro = type->tp_mro;
981 assert(PyTuple_Check(mro));
982 n = PyTuple_GET_SIZE(mro);
983 for (i = 0; i < n; i++) {
984 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
985 assert(PyType_Check(type));
986 dict = type->tp_defined;
987 assert(dict && PyDict_Check(dict));
988 res = PyDict_GetItem(dict, name);
989 if (res != NULL)
990 return res;
991 }
992 return NULL;
993}
994
995/* This is similar to PyObject_GenericGetAttr(),
996 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
997static PyObject *
998type_getattro(PyTypeObject *type, PyObject *name)
999{
1000 PyTypeObject *metatype = type->ob_type;
1001 PyObject *descr, *res;
1002 descrgetfunc f;
1003
1004 /* Initialize this type (we'll assume the metatype is initialized) */
1005 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001006 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007 return NULL;
1008 }
1009
1010 /* Get a descriptor from the metatype */
1011 descr = _PyType_Lookup(metatype, name);
1012 f = NULL;
1013 if (descr != NULL) {
1014 f = descr->ob_type->tp_descr_get;
1015 if (f != NULL && PyDescr_IsData(descr))
1016 return f(descr,
1017 (PyObject *)type, (PyObject *)metatype);
1018 }
1019
1020 /* Look in tp_defined of this type and its bases */
1021 res = _PyType_Lookup(type, name);
1022 if (res != NULL) {
1023 f = res->ob_type->tp_descr_get;
1024 if (f != NULL)
1025 return f(res, (PyObject *)NULL, (PyObject *)type);
1026 Py_INCREF(res);
1027 return res;
1028 }
1029
1030 /* Use the descriptor from the metatype */
1031 if (f != NULL) {
1032 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1033 return res;
1034 }
1035 if (descr != NULL) {
1036 Py_INCREF(descr);
1037 return descr;
1038 }
1039
1040 /* Give up */
1041 PyErr_Format(PyExc_AttributeError,
1042 "type object '%.50s' has no attribute '%.400s'",
1043 type->tp_name, PyString_AS_STRING(name));
1044 return NULL;
1045}
1046
1047static int
1048type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1049{
1050 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
1051 return PyObject_GenericSetAttr((PyObject *)type, name, value);
1052 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
1053 return -1;
1054}
1055
1056static void
1057type_dealloc(PyTypeObject *type)
1058{
1059 etype *et;
1060
1061 /* Assert this is a heap-allocated type object */
1062 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
1063 et = (etype *)type;
1064 Py_XDECREF(type->tp_base);
1065 Py_XDECREF(type->tp_dict);
1066 Py_XDECREF(type->tp_bases);
1067 Py_XDECREF(type->tp_mro);
1068 Py_XDECREF(type->tp_defined);
1069 /* XXX more? */
1070 Py_XDECREF(et->name);
1071 Py_XDECREF(et->slots);
1072 type->ob_type->tp_free((PyObject *)type);
1073}
1074
1075static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001076 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001077 "mro() -> list\nreturn a type's method resolution order"},
1078 {0}
1079};
1080
1081static char type_doc[] =
1082"type(object) -> the object's type\n"
1083"type(name, bases, dict) -> a new type";
1084
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001085PyTypeObject PyType_Type = {
1086 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087 0, /* ob_size */
1088 "type", /* tp_name */
1089 sizeof(etype), /* tp_basicsize */
1090 sizeof(struct memberlist), /* tp_itemsize */
1091 (destructor)type_dealloc, /* tp_dealloc */
1092 0, /* tp_print */
1093 0, /* tp_getattr */
1094 0, /* tp_setattr */
1095 type_compare, /* tp_compare */
1096 (reprfunc)type_repr, /* tp_repr */
1097 0, /* tp_as_number */
1098 0, /* tp_as_sequence */
1099 0, /* tp_as_mapping */
1100 (hashfunc)_Py_HashPointer, /* tp_hash */
1101 (ternaryfunc)type_call, /* tp_call */
1102 0, /* tp_str */
1103 (getattrofunc)type_getattro, /* tp_getattro */
1104 (setattrofunc)type_setattro, /* tp_setattro */
1105 0, /* tp_as_buffer */
1106 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1107 type_doc, /* tp_doc */
1108 0, /* tp_traverse */
1109 0, /* tp_clear */
1110 0, /* tp_richcompare */
1111 0, /* tp_weaklistoffset */
1112 0, /* tp_iter */
1113 0, /* tp_iternext */
1114 type_methods, /* tp_methods */
1115 type_members, /* tp_members */
1116 type_getsets, /* tp_getset */
1117 0, /* tp_base */
1118 0, /* tp_dict */
1119 0, /* tp_descr_get */
1120 0, /* tp_descr_set */
1121 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1122 0, /* tp_init */
1123 0, /* tp_alloc */
1124 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001125};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001126
1127
1128/* The base type of all types (eventually)... except itself. */
1129
1130static int
1131object_init(PyObject *self, PyObject *args, PyObject *kwds)
1132{
1133 return 0;
1134}
1135
1136static void
1137object_dealloc(PyObject *self)
1138{
1139 self->ob_type->tp_free(self);
1140}
1141
Guido van Rossum8e248182001-08-12 05:17:56 +00001142static PyObject *
1143object_repr(PyObject *self)
1144{
Guido van Rossum76e69632001-08-16 18:52:43 +00001145 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001146 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001147
Guido van Rossum76e69632001-08-16 18:52:43 +00001148 type = self->ob_type;
1149 mod = type_module(type, NULL);
1150 if (mod == NULL)
1151 PyErr_Clear();
1152 else if (!PyString_Check(mod)) {
1153 Py_DECREF(mod);
1154 mod = NULL;
1155 }
1156 name = type_name(type, NULL);
1157 if (name == NULL)
1158 return NULL;
1159 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Barry Warsaw7ce36942001-08-24 18:34:26 +00001160 rtn = PyString_FromFormat("<%s.%s instance at %p>",
1161 PyString_AS_STRING(mod),
1162 PyString_AS_STRING(name),
1163 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001164 else
Barry Warsaw7ce36942001-08-24 18:34:26 +00001165 rtn = PyString_FromFormat("<%s instance at %p>",
1166 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001167 Py_XDECREF(mod);
1168 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001169 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001170}
1171
Guido van Rossumb8f63662001-08-15 23:57:02 +00001172static PyObject *
1173object_str(PyObject *self)
1174{
1175 unaryfunc f;
1176
1177 f = self->ob_type->tp_repr;
1178 if (f == NULL)
1179 f = object_repr;
1180 return f(self);
1181}
1182
Guido van Rossum8e248182001-08-12 05:17:56 +00001183static long
1184object_hash(PyObject *self)
1185{
1186 return _Py_HashPointer(self);
1187}
Guido van Rossum8e248182001-08-12 05:17:56 +00001188
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189static void
1190object_free(PyObject *self)
1191{
1192 PyObject_Del(self);
1193}
1194
1195static struct memberlist object_members[] = {
1196 {"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
1197 {0}
1198};
1199
1200PyTypeObject PyBaseObject_Type = {
1201 PyObject_HEAD_INIT(&PyType_Type)
1202 0, /* ob_size */
1203 "object", /* tp_name */
1204 sizeof(PyObject), /* tp_basicsize */
1205 0, /* tp_itemsize */
1206 (destructor)object_dealloc, /* tp_dealloc */
1207 0, /* tp_print */
1208 0, /* tp_getattr */
1209 0, /* tp_setattr */
1210 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001211 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212 0, /* tp_as_number */
1213 0, /* tp_as_sequence */
1214 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001215 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001217 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001218 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001219 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001220 0, /* tp_as_buffer */
1221 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1222 "The most base type", /* tp_doc */
1223 0, /* tp_traverse */
1224 0, /* tp_clear */
1225 0, /* tp_richcompare */
1226 0, /* tp_weaklistoffset */
1227 0, /* tp_iter */
1228 0, /* tp_iternext */
1229 0, /* tp_methods */
1230 object_members, /* tp_members */
1231 0, /* tp_getset */
1232 0, /* tp_base */
1233 0, /* tp_dict */
1234 0, /* tp_descr_get */
1235 0, /* tp_descr_set */
1236 0, /* tp_dictoffset */
1237 object_init, /* tp_init */
1238 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001239 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001240 object_free, /* tp_free */
1241};
1242
1243
1244/* Initialize the __dict__ in a type object */
1245
1246static int
1247add_methods(PyTypeObject *type, PyMethodDef *meth)
1248{
1249 PyObject *dict = type->tp_defined;
1250
1251 for (; meth->ml_name != NULL; meth++) {
1252 PyObject *descr;
1253 if (PyDict_GetItemString(dict, meth->ml_name))
1254 continue;
1255 descr = PyDescr_NewMethod(type, meth);
1256 if (descr == NULL)
1257 return -1;
1258 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1259 return -1;
1260 Py_DECREF(descr);
1261 }
1262 return 0;
1263}
1264
1265static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00001266add_members(PyTypeObject *type, struct memberlist *memb)
1267{
1268 PyObject *dict = type->tp_defined;
1269
1270 for (; memb->name != NULL; memb++) {
1271 PyObject *descr;
1272 if (PyDict_GetItemString(dict, memb->name))
1273 continue;
1274 descr = PyDescr_NewMember(type, memb);
1275 if (descr == NULL)
1276 return -1;
1277 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1278 return -1;
1279 Py_DECREF(descr);
1280 }
1281 return 0;
1282}
1283
1284static int
1285add_getset(PyTypeObject *type, struct getsetlist *gsp)
1286{
1287 PyObject *dict = type->tp_defined;
1288
1289 for (; gsp->name != NULL; gsp++) {
1290 PyObject *descr;
1291 if (PyDict_GetItemString(dict, gsp->name))
1292 continue;
1293 descr = PyDescr_NewGetSet(type, gsp);
1294
1295 if (descr == NULL)
1296 return -1;
1297 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1298 return -1;
1299 Py_DECREF(descr);
1300 }
1301 return 0;
1302}
1303
Guido van Rossum13d52f02001-08-10 21:24:08 +00001304static void
1305inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306{
1307 int oldsize, newsize;
1308
Guido van Rossum13d52f02001-08-10 21:24:08 +00001309 /* Special flag magic */
1310 if (!type->tp_as_buffer && base->tp_as_buffer) {
1311 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1312 type->tp_flags |=
1313 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1314 }
1315 if (!type->tp_as_sequence && base->tp_as_sequence) {
1316 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1317 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1318 }
1319 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1320 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1321 if ((!type->tp_as_number && base->tp_as_number) ||
1322 (!type->tp_as_sequence && base->tp_as_sequence)) {
1323 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1324 if (!type->tp_as_number && !type->tp_as_sequence) {
1325 type->tp_flags |= base->tp_flags &
1326 Py_TPFLAGS_HAVE_INPLACEOPS;
1327 }
1328 }
1329 /* Wow */
1330 }
1331 if (!type->tp_as_number && base->tp_as_number) {
1332 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1333 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1334 }
1335
1336 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001337 oldsize = base->tp_basicsize;
1338 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1339 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1340 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001341 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1342 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001343 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001344 if (type->tp_traverse == NULL)
1345 type->tp_traverse = base->tp_traverse;
1346 if (type->tp_clear == NULL)
1347 type->tp_clear = base->tp_clear;
1348 }
1349 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1350 if (base != &PyBaseObject_Type ||
1351 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1352 if (type->tp_new == NULL)
1353 type->tp_new = base->tp_new;
1354 }
1355 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001356 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001357
1358 /* Copy other non-function slots */
1359
1360#undef COPYVAL
1361#define COPYVAL(SLOT) \
1362 if (type->SLOT == 0) type->SLOT = base->SLOT
1363
1364 COPYVAL(tp_itemsize);
1365 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1366 COPYVAL(tp_weaklistoffset);
1367 }
1368 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1369 COPYVAL(tp_dictoffset);
1370 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001371}
1372
1373static void
1374inherit_slots(PyTypeObject *type, PyTypeObject *base)
1375{
1376 PyTypeObject *basebase;
1377
1378#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001379#undef COPYSLOT
1380#undef COPYNUM
1381#undef COPYSEQ
1382#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001383
1384#define SLOTDEFINED(SLOT) \
1385 (base->SLOT != 0 && \
1386 (basebase == NULL || base->SLOT != basebase->SLOT))
1387
Tim Peters6d6c1a32001-08-02 04:15:00 +00001388#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001389 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001390
1391#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1392#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1393#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1394
Guido van Rossum13d52f02001-08-10 21:24:08 +00001395 /* This won't inherit indirect slots (from tp_as_number etc.)
1396 if type doesn't provide the space. */
1397
1398 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1399 basebase = base->tp_base;
1400 if (basebase->tp_as_number == NULL)
1401 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402 COPYNUM(nb_add);
1403 COPYNUM(nb_subtract);
1404 COPYNUM(nb_multiply);
1405 COPYNUM(nb_divide);
1406 COPYNUM(nb_remainder);
1407 COPYNUM(nb_divmod);
1408 COPYNUM(nb_power);
1409 COPYNUM(nb_negative);
1410 COPYNUM(nb_positive);
1411 COPYNUM(nb_absolute);
1412 COPYNUM(nb_nonzero);
1413 COPYNUM(nb_invert);
1414 COPYNUM(nb_lshift);
1415 COPYNUM(nb_rshift);
1416 COPYNUM(nb_and);
1417 COPYNUM(nb_xor);
1418 COPYNUM(nb_or);
1419 COPYNUM(nb_coerce);
1420 COPYNUM(nb_int);
1421 COPYNUM(nb_long);
1422 COPYNUM(nb_float);
1423 COPYNUM(nb_oct);
1424 COPYNUM(nb_hex);
1425 COPYNUM(nb_inplace_add);
1426 COPYNUM(nb_inplace_subtract);
1427 COPYNUM(nb_inplace_multiply);
1428 COPYNUM(nb_inplace_divide);
1429 COPYNUM(nb_inplace_remainder);
1430 COPYNUM(nb_inplace_power);
1431 COPYNUM(nb_inplace_lshift);
1432 COPYNUM(nb_inplace_rshift);
1433 COPYNUM(nb_inplace_and);
1434 COPYNUM(nb_inplace_xor);
1435 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001436 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1437 COPYNUM(nb_true_divide);
1438 COPYNUM(nb_floor_divide);
1439 COPYNUM(nb_inplace_true_divide);
1440 COPYNUM(nb_inplace_floor_divide);
1441 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001442 }
1443
Guido van Rossum13d52f02001-08-10 21:24:08 +00001444 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1445 basebase = base->tp_base;
1446 if (basebase->tp_as_sequence == NULL)
1447 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001448 COPYSEQ(sq_length);
1449 COPYSEQ(sq_concat);
1450 COPYSEQ(sq_repeat);
1451 COPYSEQ(sq_item);
1452 COPYSEQ(sq_slice);
1453 COPYSEQ(sq_ass_item);
1454 COPYSEQ(sq_ass_slice);
1455 COPYSEQ(sq_contains);
1456 COPYSEQ(sq_inplace_concat);
1457 COPYSEQ(sq_inplace_repeat);
1458 }
1459
Guido van Rossum13d52f02001-08-10 21:24:08 +00001460 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1461 basebase = base->tp_base;
1462 if (basebase->tp_as_mapping == NULL)
1463 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001464 COPYMAP(mp_length);
1465 COPYMAP(mp_subscript);
1466 COPYMAP(mp_ass_subscript);
1467 }
1468
Guido van Rossum13d52f02001-08-10 21:24:08 +00001469 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470
Tim Peters6d6c1a32001-08-02 04:15:00 +00001471 COPYSLOT(tp_dealloc);
1472 COPYSLOT(tp_print);
1473 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1474 type->tp_getattr = base->tp_getattr;
1475 type->tp_getattro = base->tp_getattro;
1476 }
1477 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1478 type->tp_setattr = base->tp_setattr;
1479 type->tp_setattro = base->tp_setattro;
1480 }
1481 /* tp_compare see tp_richcompare */
1482 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001483 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484 COPYSLOT(tp_call);
1485 COPYSLOT(tp_str);
1486 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001487 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001488 if (type->tp_compare == NULL &&
1489 type->tp_richcompare == NULL &&
1490 type->tp_hash == NULL)
1491 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001492 type->tp_compare = base->tp_compare;
1493 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001494 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001495 }
1496 }
1497 else {
1498 COPYSLOT(tp_compare);
1499 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001500 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1501 COPYSLOT(tp_iter);
1502 COPYSLOT(tp_iternext);
1503 }
1504 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1505 COPYSLOT(tp_descr_get);
1506 COPYSLOT(tp_descr_set);
1507 COPYSLOT(tp_dictoffset);
1508 COPYSLOT(tp_init);
1509 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001510 COPYSLOT(tp_free);
1511 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001512}
1513
Guido van Rossum13d52f02001-08-10 21:24:08 +00001514staticforward int add_operators(PyTypeObject *);
1515
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001517PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001518{
1519 PyObject *dict, *bases, *x;
1520 PyTypeObject *base;
1521 int i, n;
1522
Guido van Rossumd614f972001-08-10 17:39:49 +00001523 if (type->tp_flags & Py_TPFLAGS_READY) {
1524 assert(type->tp_dict != NULL);
1525 return 0;
1526 }
1527 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1528 assert(type->tp_dict == NULL);
1529
1530 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531
1532 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1533 base = type->tp_base;
1534 if (base == NULL && type != &PyBaseObject_Type)
1535 base = type->tp_base = &PyBaseObject_Type;
1536
1537 /* Initialize tp_bases */
1538 bases = type->tp_bases;
1539 if (bases == NULL) {
1540 if (base == NULL)
1541 bases = PyTuple_New(0);
1542 else
1543 bases = Py_BuildValue("(O)", base);
1544 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001545 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001546 type->tp_bases = bases;
1547 }
1548
1549 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001550 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001551 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001552 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553 }
1554
1555 /* Initialize tp_defined */
1556 dict = type->tp_defined;
1557 if (dict == NULL) {
1558 dict = PyDict_New();
1559 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001560 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001561 type->tp_defined = dict;
1562 }
1563
1564 /* Add type-specific descriptors to tp_defined */
1565 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001566 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567 if (type->tp_methods != NULL) {
1568 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001569 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001570 }
1571 if (type->tp_members != NULL) {
1572 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001573 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574 }
1575 if (type->tp_getset != NULL) {
1576 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001577 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001578 }
1579
1580 /* Temporarily make tp_dict the same object as tp_defined.
1581 (This is needed to call mro(), and can stay this way for
1582 dynamic types). */
1583 Py_INCREF(type->tp_defined);
1584 type->tp_dict = type->tp_defined;
1585
1586 /* Calculate method resolution order */
1587 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001588 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589 }
1590
Guido van Rossum13d52f02001-08-10 21:24:08 +00001591 /* Inherit special flags from dominant base */
1592 if (type->tp_base != NULL)
1593 inherit_special(type, type->tp_base);
1594
Tim Peters6d6c1a32001-08-02 04:15:00 +00001595 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001596 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001597 /* For a dynamic type, all slots are overridden */
1598 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001599 }
1600 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001601 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001602 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001604 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001605 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001606 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001607 bases = type->tp_mro;
1608 assert(bases != NULL);
1609 assert(PyTuple_Check(bases));
1610 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001611 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001612 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1613 assert(PyType_Check(base));
1614 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001615 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001616 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001617 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001618 }
1619 }
1620
Guido van Rossum13d52f02001-08-10 21:24:08 +00001621 /* Some more special stuff */
1622 base = type->tp_base;
1623 if (base != NULL) {
1624 if (type->tp_as_number == NULL)
1625 type->tp_as_number = base->tp_as_number;
1626 if (type->tp_as_sequence == NULL)
1627 type->tp_as_sequence = base->tp_as_sequence;
1628 if (type->tp_as_mapping == NULL)
1629 type->tp_as_mapping = base->tp_as_mapping;
1630 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631
Guido van Rossum13d52f02001-08-10 21:24:08 +00001632 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001633 assert(type->tp_dict != NULL);
1634 type->tp_flags =
1635 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001636 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001637
1638 error:
1639 type->tp_flags &= ~Py_TPFLAGS_READYING;
1640 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001641}
1642
1643
1644/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1645
1646/* There's a wrapper *function* for each distinct function typedef used
1647 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1648 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1649 Most tables have only one entry; the tables for binary operators have two
1650 entries, one regular and one with reversed arguments. */
1651
1652static PyObject *
1653wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1654{
1655 inquiry func = (inquiry)wrapped;
1656 int res;
1657
1658 if (!PyArg_ParseTuple(args, ""))
1659 return NULL;
1660 res = (*func)(self);
1661 if (res == -1 && PyErr_Occurred())
1662 return NULL;
1663 return PyInt_FromLong((long)res);
1664}
1665
1666static struct wrapperbase tab_len[] = {
1667 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1668 {0}
1669};
1670
1671static PyObject *
1672wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1673{
1674 binaryfunc func = (binaryfunc)wrapped;
1675 PyObject *other;
1676
1677 if (!PyArg_ParseTuple(args, "O", &other))
1678 return NULL;
1679 return (*func)(self, other);
1680}
1681
1682static PyObject *
1683wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1684{
1685 binaryfunc func = (binaryfunc)wrapped;
1686 PyObject *other;
1687
1688 if (!PyArg_ParseTuple(args, "O", &other))
1689 return NULL;
1690 return (*func)(other, self);
1691}
1692
1693#undef BINARY
1694#define BINARY(NAME, OP) \
1695static struct wrapperbase tab_##NAME[] = { \
1696 {"__" #NAME "__", \
1697 (wrapperfunc)wrap_binaryfunc, \
1698 "x.__" #NAME "__(y) <==> " #OP}, \
1699 {"__r" #NAME "__", \
1700 (wrapperfunc)wrap_binaryfunc_r, \
1701 "y.__r" #NAME "__(x) <==> " #OP}, \
1702 {0} \
1703}
1704
1705BINARY(add, "x+y");
1706BINARY(sub, "x-y");
1707BINARY(mul, "x*y");
1708BINARY(div, "x/y");
1709BINARY(mod, "x%y");
1710BINARY(divmod, "divmod(x,y)");
1711BINARY(lshift, "x<<y");
1712BINARY(rshift, "x>>y");
1713BINARY(and, "x&y");
1714BINARY(xor, "x^y");
1715BINARY(or, "x|y");
1716
1717static PyObject *
1718wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1719{
1720 ternaryfunc func = (ternaryfunc)wrapped;
1721 PyObject *other;
1722 PyObject *third = Py_None;
1723
1724 /* Note: This wrapper only works for __pow__() */
1725
1726 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1727 return NULL;
1728 return (*func)(self, other, third);
1729}
1730
1731#undef TERNARY
1732#define TERNARY(NAME, OP) \
1733static struct wrapperbase tab_##NAME[] = { \
1734 {"__" #NAME "__", \
1735 (wrapperfunc)wrap_ternaryfunc, \
1736 "x.__" #NAME "__(y, z) <==> " #OP}, \
1737 {"__r" #NAME "__", \
1738 (wrapperfunc)wrap_ternaryfunc, \
1739 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1740 {0} \
1741}
1742
1743TERNARY(pow, "(x**y) % z");
1744
1745#undef UNARY
1746#define UNARY(NAME, OP) \
1747static struct wrapperbase tab_##NAME[] = { \
1748 {"__" #NAME "__", \
1749 (wrapperfunc)wrap_unaryfunc, \
1750 "x.__" #NAME "__() <==> " #OP}, \
1751 {0} \
1752}
1753
1754static PyObject *
1755wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1756{
1757 unaryfunc func = (unaryfunc)wrapped;
1758
1759 if (!PyArg_ParseTuple(args, ""))
1760 return NULL;
1761 return (*func)(self);
1762}
1763
1764UNARY(neg, "-x");
1765UNARY(pos, "+x");
1766UNARY(abs, "abs(x)");
1767UNARY(nonzero, "x != 0");
1768UNARY(invert, "~x");
1769UNARY(int, "int(x)");
1770UNARY(long, "long(x)");
1771UNARY(float, "float(x)");
1772UNARY(oct, "oct(x)");
1773UNARY(hex, "hex(x)");
1774
1775#undef IBINARY
1776#define IBINARY(NAME, OP) \
1777static struct wrapperbase tab_##NAME[] = { \
1778 {"__" #NAME "__", \
1779 (wrapperfunc)wrap_binaryfunc, \
1780 "x.__" #NAME "__(y) <==> " #OP}, \
1781 {0} \
1782}
1783
1784IBINARY(iadd, "x+=y");
1785IBINARY(isub, "x-=y");
1786IBINARY(imul, "x*=y");
1787IBINARY(idiv, "x/=y");
1788IBINARY(imod, "x%=y");
1789IBINARY(ilshift, "x<<=y");
1790IBINARY(irshift, "x>>=y");
1791IBINARY(iand, "x&=y");
1792IBINARY(ixor, "x^=y");
1793IBINARY(ior, "x|=y");
1794
1795#undef ITERNARY
1796#define ITERNARY(NAME, OP) \
1797static struct wrapperbase tab_##NAME[] = { \
1798 {"__" #NAME "__", \
1799 (wrapperfunc)wrap_ternaryfunc, \
1800 "x.__" #NAME "__(y) <==> " #OP}, \
1801 {0} \
1802}
1803
1804ITERNARY(ipow, "x = (x**y) % z");
1805
1806static struct wrapperbase tab_getitem[] = {
1807 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1808 "x.__getitem__(y) <==> x[y]"},
1809 {0}
1810};
1811
1812static PyObject *
1813wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1814{
1815 intargfunc func = (intargfunc)wrapped;
1816 int i;
1817
1818 if (!PyArg_ParseTuple(args, "i", &i))
1819 return NULL;
1820 return (*func)(self, i);
1821}
1822
1823static struct wrapperbase tab_mul_int[] = {
1824 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1825 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1826 {0}
1827};
1828
1829static struct wrapperbase tab_concat[] = {
1830 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1831 {0}
1832};
1833
1834static struct wrapperbase tab_imul_int[] = {
1835 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1836 {0}
1837};
1838
Guido van Rossum5d815f32001-08-17 21:57:47 +00001839static int
1840getindex(PyObject *self, PyObject *arg)
1841{
1842 int i;
1843
1844 i = PyInt_AsLong(arg);
1845 if (i == -1 && PyErr_Occurred())
1846 return -1;
1847 if (i < 0) {
1848 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
1849 if (sq && sq->sq_length) {
1850 int n = (*sq->sq_length)(self);
1851 if (n < 0)
1852 return -1;
1853 i += n;
1854 }
1855 }
1856 return i;
1857}
1858
1859static PyObject *
1860wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
1861{
1862 intargfunc func = (intargfunc)wrapped;
1863 PyObject *arg;
1864 int i;
1865
1866 if (!PyArg_ParseTuple(args, "O", &arg))
1867 return NULL;
1868 i = getindex(self, arg);
1869 if (i == -1 && PyErr_Occurred())
1870 return NULL;
1871 return (*func)(self, i);
1872}
1873
Tim Peters6d6c1a32001-08-02 04:15:00 +00001874static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001875 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001876 "x.__getitem__(i) <==> x[i]"},
1877 {0}
1878};
1879
1880static PyObject *
1881wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1882{
1883 intintargfunc func = (intintargfunc)wrapped;
1884 int i, j;
1885
1886 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1887 return NULL;
1888 return (*func)(self, i, j);
1889}
1890
1891static struct wrapperbase tab_getslice[] = {
1892 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1893 "x.__getslice__(i, j) <==> x[i:j]"},
1894 {0}
1895};
1896
1897static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001898wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001899{
1900 intobjargproc func = (intobjargproc)wrapped;
1901 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001902 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001903
Guido van Rossum5d815f32001-08-17 21:57:47 +00001904 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
1905 return NULL;
1906 i = getindex(self, arg);
1907 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00001908 return NULL;
1909 res = (*func)(self, i, value);
1910 if (res == -1 && PyErr_Occurred())
1911 return NULL;
1912 Py_INCREF(Py_None);
1913 return Py_None;
1914}
1915
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001916static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001917wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001918{
1919 intobjargproc func = (intobjargproc)wrapped;
1920 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001921 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001922
Guido van Rossum5d815f32001-08-17 21:57:47 +00001923 if (!PyArg_ParseTuple(args, "O", &arg))
1924 return NULL;
1925 i = getindex(self, arg);
1926 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001927 return NULL;
1928 res = (*func)(self, i, NULL);
1929 if (res == -1 && PyErr_Occurred())
1930 return NULL;
1931 Py_INCREF(Py_None);
1932 return Py_None;
1933}
1934
Tim Peters6d6c1a32001-08-02 04:15:00 +00001935static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001936 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001937 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00001938 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001939 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940 {0}
1941};
1942
1943static PyObject *
1944wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1945{
1946 intintobjargproc func = (intintobjargproc)wrapped;
1947 int i, j, res;
1948 PyObject *value;
1949
1950 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1951 return NULL;
1952 res = (*func)(self, i, j, value);
1953 if (res == -1 && PyErr_Occurred())
1954 return NULL;
1955 Py_INCREF(Py_None);
1956 return Py_None;
1957}
1958
1959static struct wrapperbase tab_setslice[] = {
1960 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1961 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1962 {0}
1963};
1964
1965/* XXX objobjproc is a misnomer; should be objargpred */
1966static PyObject *
1967wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1968{
1969 objobjproc func = (objobjproc)wrapped;
1970 int res;
1971 PyObject *value;
1972
1973 if (!PyArg_ParseTuple(args, "O", &value))
1974 return NULL;
1975 res = (*func)(self, value);
1976 if (res == -1 && PyErr_Occurred())
1977 return NULL;
1978 return PyInt_FromLong((long)res);
1979}
1980
1981static struct wrapperbase tab_contains[] = {
1982 {"__contains__", (wrapperfunc)wrap_objobjproc,
1983 "x.__contains__(y) <==> y in x"},
1984 {0}
1985};
1986
1987static PyObject *
1988wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1989{
1990 objobjargproc func = (objobjargproc)wrapped;
1991 int res;
1992 PyObject *key, *value;
1993
1994 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1995 return NULL;
1996 res = (*func)(self, key, value);
1997 if (res == -1 && PyErr_Occurred())
1998 return NULL;
1999 Py_INCREF(Py_None);
2000 return Py_None;
2001}
2002
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002003static PyObject *
2004wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2005{
2006 objobjargproc func = (objobjargproc)wrapped;
2007 int res;
2008 PyObject *key;
2009
2010 if (!PyArg_ParseTuple(args, "O", &key))
2011 return NULL;
2012 res = (*func)(self, key, NULL);
2013 if (res == -1 && PyErr_Occurred())
2014 return NULL;
2015 Py_INCREF(Py_None);
2016 return Py_None;
2017}
2018
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019static struct wrapperbase tab_setitem[] = {
2020 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2021 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002022 {"__delitem__", (wrapperfunc)wrap_delitem,
2023 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002024 {0}
2025};
2026
2027static PyObject *
2028wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2029{
2030 cmpfunc func = (cmpfunc)wrapped;
2031 int res;
2032 PyObject *other;
2033
2034 if (!PyArg_ParseTuple(args, "O", &other))
2035 return NULL;
Guido van Rossumceccae52001-09-18 20:03:57 +00002036 if (!PyType_IsSubtype(other->ob_type, self->ob_type)) {
2037 PyErr_Format(
2038 PyExc_TypeError,
2039 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2040 self->ob_type->tp_name,
2041 self->ob_type->tp_name,
2042 other->ob_type->tp_name);
2043 return NULL;
2044 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045 res = (*func)(self, other);
2046 if (PyErr_Occurred())
2047 return NULL;
2048 return PyInt_FromLong((long)res);
2049}
2050
2051static struct wrapperbase tab_cmp[] = {
2052 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2053 "x.__cmp__(y) <==> cmp(x,y)"},
2054 {0}
2055};
2056
2057static struct wrapperbase tab_repr[] = {
2058 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2059 "x.__repr__() <==> repr(x)"},
2060 {0}
2061};
2062
2063static struct wrapperbase tab_getattr[] = {
2064 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
2065 "x.__getattr__('name') <==> x.name"},
2066 {0}
2067};
2068
2069static PyObject *
2070wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2071{
2072 setattrofunc func = (setattrofunc)wrapped;
2073 int res;
2074 PyObject *name, *value;
2075
2076 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2077 return NULL;
2078 res = (*func)(self, name, value);
2079 if (res < 0)
2080 return NULL;
2081 Py_INCREF(Py_None);
2082 return Py_None;
2083}
2084
2085static PyObject *
2086wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2087{
2088 setattrofunc func = (setattrofunc)wrapped;
2089 int res;
2090 PyObject *name;
2091
2092 if (!PyArg_ParseTuple(args, "O", &name))
2093 return NULL;
2094 res = (*func)(self, name, NULL);
2095 if (res < 0)
2096 return NULL;
2097 Py_INCREF(Py_None);
2098 return Py_None;
2099}
2100
2101static struct wrapperbase tab_setattr[] = {
2102 {"__setattr__", (wrapperfunc)wrap_setattr,
2103 "x.__setattr__('name', value) <==> x.name = value"},
2104 {"__delattr__", (wrapperfunc)wrap_delattr,
2105 "x.__delattr__('name') <==> del x.name"},
2106 {0}
2107};
2108
2109static PyObject *
2110wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2111{
2112 hashfunc func = (hashfunc)wrapped;
2113 long res;
2114
2115 if (!PyArg_ParseTuple(args, ""))
2116 return NULL;
2117 res = (*func)(self);
2118 if (res == -1 && PyErr_Occurred())
2119 return NULL;
2120 return PyInt_FromLong(res);
2121}
2122
2123static struct wrapperbase tab_hash[] = {
2124 {"__hash__", (wrapperfunc)wrap_hashfunc,
2125 "x.__hash__() <==> hash(x)"},
2126 {0}
2127};
2128
2129static PyObject *
2130wrap_call(PyObject *self, PyObject *args, void *wrapped)
2131{
2132 ternaryfunc func = (ternaryfunc)wrapped;
2133
2134 /* XXX What about keyword arguments? */
2135 return (*func)(self, args, NULL);
2136}
2137
2138static struct wrapperbase tab_call[] = {
2139 {"__call__", (wrapperfunc)wrap_call,
2140 "x.__call__(...) <==> x(...)"},
2141 {0}
2142};
2143
2144static struct wrapperbase tab_str[] = {
2145 {"__str__", (wrapperfunc)wrap_unaryfunc,
2146 "x.__str__() <==> str(x)"},
2147 {0}
2148};
2149
2150static PyObject *
2151wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2152{
2153 richcmpfunc func = (richcmpfunc)wrapped;
2154 PyObject *other;
2155
2156 if (!PyArg_ParseTuple(args, "O", &other))
2157 return NULL;
2158 return (*func)(self, other, op);
2159}
2160
2161#undef RICHCMP_WRAPPER
2162#define RICHCMP_WRAPPER(NAME, OP) \
2163static PyObject * \
2164richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2165{ \
2166 return wrap_richcmpfunc(self, args, wrapped, OP); \
2167}
2168
Jack Jansen8e938b42001-08-08 15:29:49 +00002169RICHCMP_WRAPPER(lt, Py_LT)
2170RICHCMP_WRAPPER(le, Py_LE)
2171RICHCMP_WRAPPER(eq, Py_EQ)
2172RICHCMP_WRAPPER(ne, Py_NE)
2173RICHCMP_WRAPPER(gt, Py_GT)
2174RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002175
2176#undef RICHCMP_ENTRY
2177#define RICHCMP_ENTRY(NAME, EXPR) \
2178 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2179 "x.__" #NAME "__(y) <==> " EXPR}
2180
2181static struct wrapperbase tab_richcmp[] = {
2182 RICHCMP_ENTRY(lt, "x<y"),
2183 RICHCMP_ENTRY(le, "x<=y"),
2184 RICHCMP_ENTRY(eq, "x==y"),
2185 RICHCMP_ENTRY(ne, "x!=y"),
2186 RICHCMP_ENTRY(gt, "x>y"),
2187 RICHCMP_ENTRY(ge, "x>=y"),
2188 {0}
2189};
2190
2191static struct wrapperbase tab_iter[] = {
2192 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2193 {0}
2194};
2195
2196static PyObject *
2197wrap_next(PyObject *self, PyObject *args, void *wrapped)
2198{
2199 unaryfunc func = (unaryfunc)wrapped;
2200 PyObject *res;
2201
2202 if (!PyArg_ParseTuple(args, ""))
2203 return NULL;
2204 res = (*func)(self);
2205 if (res == NULL && !PyErr_Occurred())
2206 PyErr_SetNone(PyExc_StopIteration);
2207 return res;
2208}
2209
2210static struct wrapperbase tab_next[] = {
2211 {"next", (wrapperfunc)wrap_next,
2212 "x.next() -> the next value, or raise StopIteration"},
2213 {0}
2214};
2215
2216static PyObject *
2217wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2218{
2219 descrgetfunc func = (descrgetfunc)wrapped;
2220 PyObject *obj;
2221 PyObject *type = NULL;
2222
2223 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2224 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002225 return (*func)(self, obj, type);
2226}
2227
2228static struct wrapperbase tab_descr_get[] = {
2229 {"__get__", (wrapperfunc)wrap_descr_get,
2230 "descr.__get__(obj, type) -> value"},
2231 {0}
2232};
2233
2234static PyObject *
2235wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2236{
2237 descrsetfunc func = (descrsetfunc)wrapped;
2238 PyObject *obj, *value;
2239 int ret;
2240
2241 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2242 return NULL;
2243 ret = (*func)(self, obj, value);
2244 if (ret < 0)
2245 return NULL;
2246 Py_INCREF(Py_None);
2247 return Py_None;
2248}
2249
2250static struct wrapperbase tab_descr_set[] = {
2251 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2252 "descr.__set__(obj, value)"},
2253 {0}
2254};
2255
2256static PyObject *
2257wrap_init(PyObject *self, PyObject *args, void *wrapped)
2258{
2259 initproc func = (initproc)wrapped;
2260
2261 /* XXX What about keyword arguments? */
2262 if (func(self, args, NULL) < 0)
2263 return NULL;
2264 Py_INCREF(Py_None);
2265 return Py_None;
2266}
2267
2268static struct wrapperbase tab_init[] = {
2269 {"__init__", (wrapperfunc)wrap_init,
2270 "x.__init__(...) initializes x; "
2271 "see x.__type__.__doc__ for signature"},
2272 {0}
2273};
2274
2275static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002276tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002277{
Barry Warsaw60f01882001-08-22 19:24:42 +00002278 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002279 PyObject *arg0, *res;
2280
2281 if (self == NULL || !PyType_Check(self))
2282 Py_FatalError("__new__() called with non-type 'self'");
2283 type = (PyTypeObject *)self;
2284 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002285 PyErr_Format(PyExc_TypeError,
2286 "%s.__new__(): not enough arguments",
2287 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002288 return NULL;
2289 }
2290 arg0 = PyTuple_GET_ITEM(args, 0);
2291 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002292 PyErr_Format(PyExc_TypeError,
2293 "%s.__new__(X): X is not a type object (%s)",
2294 type->tp_name,
2295 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002296 return NULL;
2297 }
2298 subtype = (PyTypeObject *)arg0;
2299 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002300 PyErr_Format(PyExc_TypeError,
2301 "%s.__new__(%s): %s is not a subtype of %s",
2302 type->tp_name,
2303 subtype->tp_name,
2304 subtype->tp_name,
2305 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002306 return NULL;
2307 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002308
2309 /* Check that the use doesn't do something silly and unsafe like
2310 object.__new__(dictionary). To do this, we check that the
2311 most derived base that's not a heap type is this type. */
2312 staticbase = subtype;
2313 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2314 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002315 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002316 PyErr_Format(PyExc_TypeError,
2317 "%s.__new__(%s) is not safe, use %s.__new__()",
2318 type->tp_name,
2319 subtype->tp_name,
2320 staticbase == NULL ? "?" : staticbase->tp_name);
2321 return NULL;
2322 }
2323
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002324 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2325 if (args == NULL)
2326 return NULL;
2327 res = type->tp_new(subtype, args, kwds);
2328 Py_DECREF(args);
2329 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002330}
2331
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002332static struct PyMethodDef tp_new_methoddef[] = {
2333 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2334 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002335 {0}
2336};
2337
2338static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002339add_tp_new_wrapper(PyTypeObject *type)
2340{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002341 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002342
Guido van Rossumf040ede2001-08-07 16:40:56 +00002343 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2344 return 0;
2345 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002346 if (func == NULL)
2347 return -1;
2348 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2349}
2350
Guido van Rossum13d52f02001-08-10 21:24:08 +00002351static int
2352add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2353{
2354 PyObject *dict = type->tp_defined;
2355
2356 for (; wraps->name != NULL; wraps++) {
2357 PyObject *descr;
2358 if (PyDict_GetItemString(dict, wraps->name))
2359 continue;
2360 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2361 if (descr == NULL)
2362 return -1;
2363 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2364 return -1;
2365 Py_DECREF(descr);
2366 }
2367 return 0;
2368}
2369
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002370/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002371 dictionary with method descriptors for function slots. For each
2372 function slot (like tp_repr) that's defined in the type, one or
2373 more corresponding descriptors are added in the type's tp_defined
2374 dictionary under the appropriate name (like __repr__). Some
2375 function slots cause more than one descriptor to be added (for
2376 example, the nb_add slot adds both __add__ and __radd__
2377 descriptors) and some function slots compete for the same
2378 descriptor (for example both sq_item and mp_subscript generate a
2379 __getitem__ descriptor). This only adds new descriptors and
2380 doesn't overwrite entries in tp_defined that were previously
2381 defined. The descriptors contain a reference to the C function
2382 they must call, so that it's safe if they are copied into a
2383 subtype's __dict__ and the subtype has a different C function in
2384 its slot -- calling the method defined by the descriptor will call
2385 the C function that was used to create it, rather than the C
2386 function present in the slot when it is called. (This is important
2387 because a subtype may have a C function in the slot that calls the
2388 method from the dictionary, and we want to avoid infinite recursion
2389 here.) */
2390
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002391static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002392add_operators(PyTypeObject *type)
2393{
2394 PySequenceMethods *sq;
2395 PyMappingMethods *mp;
2396 PyNumberMethods *nb;
2397
2398#undef ADD
2399#define ADD(SLOT, TABLE) \
2400 if (SLOT) { \
2401 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2402 return -1; \
2403 }
2404
2405 if ((sq = type->tp_as_sequence) != NULL) {
2406 ADD(sq->sq_length, tab_len);
2407 ADD(sq->sq_concat, tab_concat);
2408 ADD(sq->sq_repeat, tab_mul_int);
2409 ADD(sq->sq_item, tab_getitem_int);
2410 ADD(sq->sq_slice, tab_getslice);
2411 ADD(sq->sq_ass_item, tab_setitem_int);
2412 ADD(sq->sq_ass_slice, tab_setslice);
2413 ADD(sq->sq_contains, tab_contains);
2414 ADD(sq->sq_inplace_concat, tab_iadd);
2415 ADD(sq->sq_inplace_repeat, tab_imul_int);
2416 }
2417
2418 if ((mp = type->tp_as_mapping) != NULL) {
2419 if (sq->sq_length == NULL)
2420 ADD(mp->mp_length, tab_len);
2421 ADD(mp->mp_subscript, tab_getitem);
2422 ADD(mp->mp_ass_subscript, tab_setitem);
2423 }
2424
2425 /* We don't support "old-style numbers" because their binary
2426 operators require that both arguments have the same type;
2427 the wrappers here only work for new-style numbers. */
2428 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2429 (nb = type->tp_as_number) != NULL) {
2430 ADD(nb->nb_add, tab_add);
2431 ADD(nb->nb_subtract, tab_sub);
2432 ADD(nb->nb_multiply, tab_mul);
2433 ADD(nb->nb_divide, tab_div);
2434 ADD(nb->nb_remainder, tab_mod);
2435 ADD(nb->nb_divmod, tab_divmod);
2436 ADD(nb->nb_power, tab_pow);
2437 ADD(nb->nb_negative, tab_neg);
2438 ADD(nb->nb_positive, tab_pos);
2439 ADD(nb->nb_absolute, tab_abs);
2440 ADD(nb->nb_nonzero, tab_nonzero);
2441 ADD(nb->nb_invert, tab_invert);
2442 ADD(nb->nb_lshift, tab_lshift);
2443 ADD(nb->nb_rshift, tab_rshift);
2444 ADD(nb->nb_and, tab_and);
2445 ADD(nb->nb_xor, tab_xor);
2446 ADD(nb->nb_or, tab_or);
2447 /* We don't support coerce() -- see above comment */
2448 ADD(nb->nb_int, tab_int);
2449 ADD(nb->nb_long, tab_long);
2450 ADD(nb->nb_float, tab_float);
2451 ADD(nb->nb_oct, tab_oct);
2452 ADD(nb->nb_hex, tab_hex);
2453 ADD(nb->nb_inplace_add, tab_iadd);
2454 ADD(nb->nb_inplace_subtract, tab_isub);
2455 ADD(nb->nb_inplace_multiply, tab_imul);
2456 ADD(nb->nb_inplace_divide, tab_idiv);
2457 ADD(nb->nb_inplace_remainder, tab_imod);
2458 ADD(nb->nb_inplace_power, tab_ipow);
2459 ADD(nb->nb_inplace_lshift, tab_ilshift);
2460 ADD(nb->nb_inplace_rshift, tab_irshift);
2461 ADD(nb->nb_inplace_and, tab_iand);
2462 ADD(nb->nb_inplace_xor, tab_ixor);
2463 ADD(nb->nb_inplace_or, tab_ior);
2464 }
2465
2466 ADD(type->tp_getattro, tab_getattr);
2467 ADD(type->tp_setattro, tab_setattr);
2468 ADD(type->tp_compare, tab_cmp);
2469 ADD(type->tp_repr, tab_repr);
2470 ADD(type->tp_hash, tab_hash);
2471 ADD(type->tp_call, tab_call);
2472 ADD(type->tp_str, tab_str);
2473 ADD(type->tp_richcompare, tab_richcmp);
2474 ADD(type->tp_iter, tab_iter);
2475 ADD(type->tp_iternext, tab_next);
2476 ADD(type->tp_descr_get, tab_descr_get);
2477 ADD(type->tp_descr_set, tab_descr_set);
2478 ADD(type->tp_init, tab_init);
2479
Guido van Rossumf040ede2001-08-07 16:40:56 +00002480 if (type->tp_new != NULL) {
2481 if (add_tp_new_wrapper(type) < 0)
2482 return -1;
2483 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484
2485 return 0;
2486}
2487
Guido van Rossumf040ede2001-08-07 16:40:56 +00002488/* Slot wrappers that call the corresponding __foo__ slot. See comments
2489 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002490
Guido van Rossumdc91b992001-08-08 22:26:22 +00002491#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002492static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002493FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002494{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002495 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002496 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002497}
2498
Guido van Rossumdc91b992001-08-08 22:26:22 +00002499#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002500static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002501FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002502{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002503 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002504 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002505}
2506
Guido van Rossumdc91b992001-08-08 22:26:22 +00002507
2508#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002509static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002510FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002511{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002512 static PyObject *cache_str, *rcache_str; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002513 if (self->ob_type->tp_as_number != NULL && \
2514 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2515 PyObject *r; \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002516 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002517 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002518 if (r != Py_NotImplemented || \
2519 other->ob_type == self->ob_type) \
2520 return r; \
2521 Py_DECREF(r); \
2522 } \
2523 if (other->ob_type->tp_as_number != NULL && \
2524 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002525 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002526 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002527 } \
2528 Py_INCREF(Py_NotImplemented); \
2529 return Py_NotImplemented; \
2530}
2531
2532#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2533 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2534
2535#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2536static PyObject * \
2537FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2538{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002539 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002540 return call_method(self, OPSTR, &cache_str, \
2541 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002542}
2543
2544static int
2545slot_sq_length(PyObject *self)
2546{
Guido van Rossum2730b132001-08-28 18:22:14 +00002547 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002548 PyObject *res = call_method(self, "__len__", &len_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002549
2550 if (res == NULL)
2551 return -1;
2552 return (int)PyInt_AsLong(res);
2553}
2554
Guido van Rossumdc91b992001-08-08 22:26:22 +00002555SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2556SLOT1(slot_sq_repeat, "__mul__", int, "i")
2557SLOT1(slot_sq_item, "__getitem__", int, "i")
2558SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002559
2560static int
2561slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2562{
2563 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002564 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002565
2566 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002567 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002568 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002569 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002570 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002571 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002572 if (res == NULL)
2573 return -1;
2574 Py_DECREF(res);
2575 return 0;
2576}
2577
2578static int
2579slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2580{
2581 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002582 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002583
2584 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002585 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002586 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002587 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002588 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002589 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002590 if (res == NULL)
2591 return -1;
2592 Py_DECREF(res);
2593 return 0;
2594}
2595
2596static int
2597slot_sq_contains(PyObject *self, PyObject *value)
2598{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002599 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002600 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002601
Guido van Rossum60718732001-08-28 17:47:51 +00002602 func = lookup_method(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002603
2604 if (func != NULL) {
2605 args = Py_BuildValue("(O)", value);
2606 if (args == NULL)
2607 res = NULL;
2608 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002609 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002610 Py_DECREF(args);
2611 }
2612 Py_DECREF(func);
2613 if (res == NULL)
2614 return -1;
2615 return PyObject_IsTrue(res);
2616 }
2617 else {
2618 PyErr_Clear();
Tim Peters16a77ad2001-09-08 04:00:12 +00002619 return _PySequence_IterSearch(self, value,
2620 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002621 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002622}
2623
Guido van Rossumdc91b992001-08-08 22:26:22 +00002624SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2625SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002626
2627#define slot_mp_length slot_sq_length
2628
Guido van Rossumdc91b992001-08-08 22:26:22 +00002629SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002630
2631static int
2632slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2633{
2634 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002635 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002636
2637 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002638 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002639 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002640 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002641 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002642 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002643 if (res == NULL)
2644 return -1;
2645 Py_DECREF(res);
2646 return 0;
2647}
2648
Guido van Rossumdc91b992001-08-08 22:26:22 +00002649SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2650SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2651SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2652SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2653SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2654SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2655
2656staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2657
2658SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2659 nb_power, "__pow__", "__rpow__")
2660
2661static PyObject *
2662slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2663{
Guido van Rossum2730b132001-08-28 18:22:14 +00002664 static PyObject *pow_str;
2665
Guido van Rossumdc91b992001-08-08 22:26:22 +00002666 if (modulus == Py_None)
2667 return slot_nb_power_binary(self, other);
2668 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002669 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002670 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002671}
2672
2673SLOT0(slot_nb_negative, "__neg__")
2674SLOT0(slot_nb_positive, "__pos__")
2675SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002676
2677static int
2678slot_nb_nonzero(PyObject *self)
2679{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002680 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002681 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682
Guido van Rossum60718732001-08-28 17:47:51 +00002683 func = lookup_method(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002684 if (func == NULL) {
2685 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002686 func = lookup_method(self, "__len__", &len_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002687 }
2688
2689 if (func != NULL) {
Guido van Rossum717ce002001-09-14 16:58:08 +00002690 res = PyObject_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002691 Py_DECREF(func);
2692 if (res == NULL)
2693 return -1;
2694 return PyObject_IsTrue(res);
2695 }
2696 else {
2697 PyErr_Clear();
2698 return 1;
2699 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002700}
2701
Guido van Rossumdc91b992001-08-08 22:26:22 +00002702SLOT0(slot_nb_invert, "__invert__")
2703SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2704SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2705SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2706SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2707SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002708/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002709SLOT0(slot_nb_int, "__int__")
2710SLOT0(slot_nb_long, "__long__")
2711SLOT0(slot_nb_float, "__float__")
2712SLOT0(slot_nb_oct, "__oct__")
2713SLOT0(slot_nb_hex, "__hex__")
2714SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2715SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2716SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2717SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2718SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2719SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2720SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2721SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2722SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2723SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2724SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2725SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2726 "__floordiv__", "__rfloordiv__")
2727SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2728SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2729SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730
2731static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002732half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002733{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002734 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002735 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002736 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002737
Guido van Rossum60718732001-08-28 17:47:51 +00002738 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002739 if (func == NULL) {
2740 PyErr_Clear();
2741 }
2742 else {
2743 args = Py_BuildValue("(O)", other);
2744 if (args == NULL)
2745 res = NULL;
2746 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002747 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002748 Py_DECREF(args);
2749 }
2750 if (res != Py_NotImplemented) {
2751 if (res == NULL)
2752 return -2;
2753 c = PyInt_AsLong(res);
2754 Py_DECREF(res);
2755 if (c == -1 && PyErr_Occurred())
2756 return -2;
2757 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2758 }
2759 Py_DECREF(res);
2760 }
2761 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002762}
2763
Guido van Rossumab3b0342001-09-18 20:38:53 +00002764/* This slot is published for the benefit of try_3way_compare in object.c */
2765int
2766_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00002767{
2768 int c;
2769
Guido van Rossumab3b0342001-09-18 20:38:53 +00002770 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002771 c = half_compare(self, other);
2772 if (c <= 1)
2773 return c;
2774 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00002775 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002776 c = half_compare(other, self);
2777 if (c < -1)
2778 return -2;
2779 if (c <= 1)
2780 return -c;
2781 }
2782 return (void *)self < (void *)other ? -1 :
2783 (void *)self > (void *)other ? 1 : 0;
2784}
2785
2786static PyObject *
2787slot_tp_repr(PyObject *self)
2788{
2789 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002790 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002791
Guido van Rossum60718732001-08-28 17:47:51 +00002792 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002793 if (func != NULL) {
2794 res = PyEval_CallObject(func, NULL);
2795 Py_DECREF(func);
2796 return res;
2797 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00002798 PyErr_Clear();
2799 return PyString_FromFormat("<%s object at %p>",
2800 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002801}
2802
2803static PyObject *
2804slot_tp_str(PyObject *self)
2805{
2806 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002807 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002808
Guido van Rossum60718732001-08-28 17:47:51 +00002809 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002810 if (func != NULL) {
2811 res = PyEval_CallObject(func, NULL);
2812 Py_DECREF(func);
2813 return res;
2814 }
2815 else {
2816 PyErr_Clear();
2817 return slot_tp_repr(self);
2818 }
2819}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002820
2821static long
2822slot_tp_hash(PyObject *self)
2823{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002824 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002825 static PyObject *hash_str, *eq_str, *cmp_str;
2826
Tim Peters6d6c1a32001-08-02 04:15:00 +00002827 long h;
2828
Guido van Rossum60718732001-08-28 17:47:51 +00002829 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002830
2831 if (func != NULL) {
2832 res = PyEval_CallObject(func, NULL);
2833 Py_DECREF(func);
2834 if (res == NULL)
2835 return -1;
2836 h = PyInt_AsLong(res);
2837 }
2838 else {
2839 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002840 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002841 if (func == NULL) {
2842 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002843 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002844 }
2845 if (func != NULL) {
2846 Py_DECREF(func);
2847 PyErr_SetString(PyExc_TypeError, "unhashable type");
2848 return -1;
2849 }
2850 PyErr_Clear();
2851 h = _Py_HashPointer((void *)self);
2852 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002853 if (h == -1 && !PyErr_Occurred())
2854 h = -2;
2855 return h;
2856}
2857
2858static PyObject *
2859slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2860{
Guido van Rossum60718732001-08-28 17:47:51 +00002861 static PyObject *call_str;
2862 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002863 PyObject *res;
2864
2865 if (meth == NULL)
2866 return NULL;
2867 res = PyObject_Call(meth, args, kwds);
2868 Py_DECREF(meth);
2869 return res;
2870}
2871
Tim Peters6d6c1a32001-08-02 04:15:00 +00002872static PyObject *
2873slot_tp_getattro(PyObject *self, PyObject *name)
2874{
2875 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002876 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002877 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002878
Guido van Rossum8e248182001-08-12 05:17:56 +00002879 if (getattr_str == NULL) {
2880 getattr_str = PyString_InternFromString("__getattr__");
2881 if (getattr_str == NULL)
2882 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002883 }
Guido van Rossum8e248182001-08-12 05:17:56 +00002884 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00002885 if (getattr == NULL) {
2886 /* Avoid further slowdowns */
2887 if (tp->tp_getattro == slot_tp_getattro)
2888 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002889 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00002890 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002891 return PyObject_CallFunction(getattr, "OO", self, name);
2892}
2893
2894static int
2895slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2896{
2897 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002898 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002899
2900 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002901 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002902 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002903 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002904 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002905 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002906 if (res == NULL)
2907 return -1;
2908 Py_DECREF(res);
2909 return 0;
2910}
2911
2912/* Map rich comparison operators to their __xx__ namesakes */
2913static char *name_op[] = {
2914 "__lt__",
2915 "__le__",
2916 "__eq__",
2917 "__ne__",
2918 "__gt__",
2919 "__ge__",
2920};
2921
2922static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00002923half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002924{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002925 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002926 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927
Guido van Rossum60718732001-08-28 17:47:51 +00002928 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002929 if (func == NULL) {
2930 PyErr_Clear();
2931 Py_INCREF(Py_NotImplemented);
2932 return Py_NotImplemented;
2933 }
2934 args = Py_BuildValue("(O)", other);
2935 if (args == NULL)
2936 res = NULL;
2937 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002938 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002939 Py_DECREF(args);
2940 }
2941 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002942 return res;
2943}
2944
Guido van Rossumb8f63662001-08-15 23:57:02 +00002945/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
2946static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
2947
2948static PyObject *
2949slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2950{
2951 PyObject *res;
2952
2953 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
2954 res = half_richcompare(self, other, op);
2955 if (res != Py_NotImplemented)
2956 return res;
2957 Py_DECREF(res);
2958 }
2959 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
2960 res = half_richcompare(other, self, swapped_op[op]);
2961 if (res != Py_NotImplemented) {
2962 return res;
2963 }
2964 Py_DECREF(res);
2965 }
2966 Py_INCREF(Py_NotImplemented);
2967 return Py_NotImplemented;
2968}
2969
2970static PyObject *
2971slot_tp_iter(PyObject *self)
2972{
2973 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002974 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002975
Guido van Rossum60718732001-08-28 17:47:51 +00002976 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002977 if (func != NULL) {
2978 res = PyObject_CallObject(func, NULL);
2979 Py_DECREF(func);
2980 return res;
2981 }
2982 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002983 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002984 if (func == NULL) {
2985 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
2986 return NULL;
2987 }
2988 Py_DECREF(func);
2989 return PySeqIter_New(self);
2990}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002991
2992static PyObject *
2993slot_tp_iternext(PyObject *self)
2994{
Guido van Rossum2730b132001-08-28 18:22:14 +00002995 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002996 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002997}
2998
Guido van Rossum1a493502001-08-17 16:47:50 +00002999static PyObject *
3000slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3001{
3002 PyTypeObject *tp = self->ob_type;
3003 PyObject *get;
3004 static PyObject *get_str = NULL;
3005
3006 if (get_str == NULL) {
3007 get_str = PyString_InternFromString("__get__");
3008 if (get_str == NULL)
3009 return NULL;
3010 }
3011 get = _PyType_Lookup(tp, get_str);
3012 if (get == NULL) {
3013 /* Avoid further slowdowns */
3014 if (tp->tp_descr_get == slot_tp_descr_get)
3015 tp->tp_descr_get = NULL;
3016 Py_INCREF(self);
3017 return self;
3018 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003019 if (obj == NULL)
3020 obj = Py_None;
3021 if (type == NULL)
3022 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003023 return PyObject_CallFunction(get, "OOO", self, obj, type);
3024}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003025
3026static int
3027slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3028{
Guido van Rossum2c252392001-08-24 10:13:31 +00003029 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003030 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003031
3032 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003033 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003034 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003035 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003036 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003037 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003038 if (res == NULL)
3039 return -1;
3040 Py_DECREF(res);
3041 return 0;
3042}
3043
3044static int
3045slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3046{
Guido van Rossum60718732001-08-28 17:47:51 +00003047 static PyObject *init_str;
3048 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003049 PyObject *res;
3050
3051 if (meth == NULL)
3052 return -1;
3053 res = PyObject_Call(meth, args, kwds);
3054 Py_DECREF(meth);
3055 if (res == NULL)
3056 return -1;
3057 Py_DECREF(res);
3058 return 0;
3059}
3060
3061static PyObject *
3062slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3063{
3064 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3065 PyObject *newargs, *x;
3066 int i, n;
3067
3068 if (func == NULL)
3069 return NULL;
3070 assert(PyTuple_Check(args));
3071 n = PyTuple_GET_SIZE(args);
3072 newargs = PyTuple_New(n+1);
3073 if (newargs == NULL)
3074 return NULL;
3075 Py_INCREF(type);
3076 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3077 for (i = 0; i < n; i++) {
3078 x = PyTuple_GET_ITEM(args, i);
3079 Py_INCREF(x);
3080 PyTuple_SET_ITEM(newargs, i+1, x);
3081 }
3082 x = PyObject_Call(func, newargs, kwds);
3083 Py_DECREF(func);
3084 return x;
3085}
3086
Guido van Rossumf040ede2001-08-07 16:40:56 +00003087/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003088 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003089 The dict argument is the dictionary argument passed to type_new(),
3090 which is the local namespace of the class statement, in other
3091 words, it contains the methods. For each special method (like
3092 __repr__) defined in the dictionary, the corresponding function
3093 slot in the type object (like tp_repr) is set to a special function
3094 whose name is 'slot_' followed by the slot name and whose signature
3095 is whatever is required for that slot. These slot functions look
3096 up the corresponding method in the type's dictionary and call it.
3097 The slot functions have to take care of the various peculiarities
3098 of the mapping between slots and special methods, such as mapping
3099 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3100 etc.) or mapping multiple slots to a single method (sq_item,
3101 mp_subscript <--> __getitem__). */
3102
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103static void
3104override_slots(PyTypeObject *type, PyObject *dict)
3105{
3106 PySequenceMethods *sq = type->tp_as_sequence;
3107 PyMappingMethods *mp = type->tp_as_mapping;
3108 PyNumberMethods *nb = type->tp_as_number;
3109
Guido van Rossumdc91b992001-08-08 22:26:22 +00003110#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003111 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003112 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003113 }
3114
Guido van Rossumdc91b992001-08-08 22:26:22 +00003115#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003116 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003117 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118 }
3119
Guido van Rossumdc91b992001-08-08 22:26:22 +00003120#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003121 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003122 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003123 }
3124
Guido van Rossumdc91b992001-08-08 22:26:22 +00003125#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003126 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003127 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003128 }
3129
Guido van Rossumdc91b992001-08-08 22:26:22 +00003130 SQSLOT("__len__", sq_length, slot_sq_length);
3131 SQSLOT("__add__", sq_concat, slot_sq_concat);
3132 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3133 SQSLOT("__getitem__", sq_item, slot_sq_item);
3134 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3135 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3136 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3137 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3138 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3139 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3140 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3141 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003142
Guido van Rossumdc91b992001-08-08 22:26:22 +00003143 MPSLOT("__len__", mp_length, slot_mp_length);
3144 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3145 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3146 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003147
Guido van Rossumdc91b992001-08-08 22:26:22 +00003148 NBSLOT("__add__", nb_add, slot_nb_add);
3149 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3150 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3151 NBSLOT("__div__", nb_divide, slot_nb_divide);
3152 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3153 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3154 NBSLOT("__pow__", nb_power, slot_nb_power);
3155 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3156 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3157 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3158 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3159 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3160 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3161 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3162 NBSLOT("__and__", nb_and, slot_nb_and);
3163 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3164 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00003166 NBSLOT("__int__", nb_int, slot_nb_int);
3167 NBSLOT("__long__", nb_long, slot_nb_long);
3168 NBSLOT("__float__", nb_float, slot_nb_float);
3169 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3170 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3171 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3172 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3173 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3174 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3175 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3176 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3177 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3178 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3179 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3180 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3181 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3182 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3183 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3184 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3185 slot_nb_inplace_floor_divide);
3186 NBSLOT("__itruediv__", nb_inplace_true_divide,
3187 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188
Guido van Rossum8e248182001-08-12 05:17:56 +00003189 if (dict == NULL ||
3190 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003191 PyDict_GetItemString(dict, "__repr__"))
3192 type->tp_print = NULL;
3193
Guido van Rossumab3b0342001-09-18 20:38:53 +00003194 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003195 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3196 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3197 TPSLOT("__call__", tp_call, slot_tp_call);
3198 TPSLOT("__str__", tp_str, slot_tp_str);
3199 TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
3200 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3201 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3202 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3203 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3204 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3205 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3206 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3207 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3208 TPSLOT("next", tp_iternext, slot_tp_iternext);
3209 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3210 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3211 TPSLOT("__init__", tp_init, slot_tp_init);
3212 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003213}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003214
3215
3216/* Cooperative 'super' */
3217
3218typedef struct {
3219 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003220 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003221 PyObject *obj;
3222} superobject;
3223
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003224static struct memberlist super_members[] = {
3225 {"__type__", T_OBJECT, offsetof(superobject, type), READONLY},
3226 {"__obj__", T_OBJECT, offsetof(superobject, obj), READONLY},
3227 {0}
3228};
3229
Guido van Rossum705f0f52001-08-24 16:47:00 +00003230static void
3231super_dealloc(PyObject *self)
3232{
3233 superobject *su = (superobject *)self;
3234
3235 Py_XDECREF(su->obj);
3236 Py_XDECREF(su->type);
3237 self->ob_type->tp_free(self);
3238}
3239
3240static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003241super_repr(PyObject *self)
3242{
3243 superobject *su = (superobject *)self;
3244
3245 if (su->obj)
3246 return PyString_FromFormat(
3247 "<super: <type '%s'>, <%s object>>",
3248 su->type ? su->type->tp_name : "NULL",
3249 su->obj->ob_type->tp_name);
3250 else
3251 return PyString_FromFormat(
3252 "<super: <type '%s'>, NULL>",
3253 su->type ? su->type->tp_name : "NULL");
3254}
3255
3256static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003257super_getattro(PyObject *self, PyObject *name)
3258{
3259 superobject *su = (superobject *)self;
3260
3261 if (su->obj != NULL) {
3262 PyObject *mro, *res, *tmp;
3263 descrgetfunc f;
3264 int i, n;
3265
Guido van Rossume705ef12001-08-29 15:47:06 +00003266 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003267 if (mro == NULL)
3268 n = 0;
3269 else {
3270 assert(PyTuple_Check(mro));
3271 n = PyTuple_GET_SIZE(mro);
3272 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003273 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003274 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003275 break;
3276 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003277 if (i >= n && PyType_Check(su->obj)) {
3278 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003279 if (mro == NULL)
3280 n = 0;
3281 else {
3282 assert(PyTuple_Check(mro));
3283 n = PyTuple_GET_SIZE(mro);
3284 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003285 for (i = 0; i < n; i++) {
3286 if ((PyObject *)(su->type) ==
3287 PyTuple_GET_ITEM(mro, i))
3288 break;
3289 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003290 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003291 i++;
3292 res = NULL;
3293 for (; i < n; i++) {
3294 tmp = PyTuple_GET_ITEM(mro, i);
3295 assert(PyType_Check(tmp));
3296 res = PyDict_GetItem(
3297 ((PyTypeObject *)tmp)->tp_defined, name);
3298 if (res != NULL) {
3299 Py_INCREF(res);
3300 f = res->ob_type->tp_descr_get;
3301 if (f != NULL) {
3302 tmp = f(res, su->obj, res);
3303 Py_DECREF(res);
3304 res = tmp;
3305 }
3306 return res;
3307 }
3308 }
3309 }
3310 return PyObject_GenericGetAttr(self, name);
3311}
3312
3313static PyObject *
3314super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3315{
3316 superobject *su = (superobject *)self;
3317 superobject *new;
3318
3319 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3320 /* Not binding to an object, or already bound */
3321 Py_INCREF(self);
3322 return self;
3323 }
3324 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3325 if (new == NULL)
3326 return NULL;
3327 Py_INCREF(su->type);
3328 Py_INCREF(obj);
3329 new->type = su->type;
3330 new->obj = obj;
3331 return (PyObject *)new;
3332}
3333
3334static int
3335super_init(PyObject *self, PyObject *args, PyObject *kwds)
3336{
3337 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003338 PyTypeObject *type;
3339 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003340
3341 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3342 return -1;
3343 if (obj == Py_None)
3344 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003345 if (obj != NULL &&
3346 !PyType_IsSubtype(obj->ob_type, type) &&
3347 !(PyType_Check(obj) &&
3348 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003349 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003350 "super(type, obj): "
3351 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003352 return -1;
3353 }
3354 Py_INCREF(type);
3355 Py_XINCREF(obj);
3356 su->type = type;
3357 su->obj = obj;
3358 return 0;
3359}
3360
3361static char super_doc[] =
3362"super(type) -> unbound super object\n"
3363"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003364"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003365"Typical use to call a cooperative superclass method:\n"
3366"class C(B):\n"
3367" def meth(self, arg):\n"
3368" super(C, self).meth(arg)";
3369
3370PyTypeObject PySuper_Type = {
3371 PyObject_HEAD_INIT(&PyType_Type)
3372 0, /* ob_size */
3373 "super", /* tp_name */
3374 sizeof(superobject), /* tp_basicsize */
3375 0, /* tp_itemsize */
3376 /* methods */
3377 super_dealloc, /* tp_dealloc */
3378 0, /* tp_print */
3379 0, /* tp_getattr */
3380 0, /* tp_setattr */
3381 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003382 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003383 0, /* tp_as_number */
3384 0, /* tp_as_sequence */
3385 0, /* tp_as_mapping */
3386 0, /* tp_hash */
3387 0, /* tp_call */
3388 0, /* tp_str */
3389 super_getattro, /* tp_getattro */
3390 0, /* tp_setattro */
3391 0, /* tp_as_buffer */
Guido van Rossum31bcff82001-08-30 04:37:15 +00003392 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003393 super_doc, /* tp_doc */
3394 0, /* tp_traverse */
3395 0, /* tp_clear */
3396 0, /* tp_richcompare */
3397 0, /* tp_weaklistoffset */
3398 0, /* tp_iter */
3399 0, /* tp_iternext */
3400 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003401 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003402 0, /* tp_getset */
3403 0, /* tp_base */
3404 0, /* tp_dict */
3405 super_descr_get, /* tp_descr_get */
3406 0, /* tp_descr_set */
3407 0, /* tp_dictoffset */
3408 super_init, /* tp_init */
3409 PyType_GenericAlloc, /* tp_alloc */
3410 PyType_GenericNew, /* tp_new */
3411 _PyObject_Del, /* tp_free */
3412};