blob: 52fd7e9b731ecfce5ec0f2cfa023003585000460 [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;
929 mp->readonly = 1;
930 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;
2036 res = (*func)(self, other);
2037 if (PyErr_Occurred())
2038 return NULL;
2039 return PyInt_FromLong((long)res);
2040}
2041
2042static struct wrapperbase tab_cmp[] = {
2043 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2044 "x.__cmp__(y) <==> cmp(x,y)"},
2045 {0}
2046};
2047
2048static struct wrapperbase tab_repr[] = {
2049 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2050 "x.__repr__() <==> repr(x)"},
2051 {0}
2052};
2053
2054static struct wrapperbase tab_getattr[] = {
2055 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
2056 "x.__getattr__('name') <==> x.name"},
2057 {0}
2058};
2059
2060static PyObject *
2061wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2062{
2063 setattrofunc func = (setattrofunc)wrapped;
2064 int res;
2065 PyObject *name, *value;
2066
2067 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2068 return NULL;
2069 res = (*func)(self, name, value);
2070 if (res < 0)
2071 return NULL;
2072 Py_INCREF(Py_None);
2073 return Py_None;
2074}
2075
2076static PyObject *
2077wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2078{
2079 setattrofunc func = (setattrofunc)wrapped;
2080 int res;
2081 PyObject *name;
2082
2083 if (!PyArg_ParseTuple(args, "O", &name))
2084 return NULL;
2085 res = (*func)(self, name, NULL);
2086 if (res < 0)
2087 return NULL;
2088 Py_INCREF(Py_None);
2089 return Py_None;
2090}
2091
2092static struct wrapperbase tab_setattr[] = {
2093 {"__setattr__", (wrapperfunc)wrap_setattr,
2094 "x.__setattr__('name', value) <==> x.name = value"},
2095 {"__delattr__", (wrapperfunc)wrap_delattr,
2096 "x.__delattr__('name') <==> del x.name"},
2097 {0}
2098};
2099
2100static PyObject *
2101wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2102{
2103 hashfunc func = (hashfunc)wrapped;
2104 long res;
2105
2106 if (!PyArg_ParseTuple(args, ""))
2107 return NULL;
2108 res = (*func)(self);
2109 if (res == -1 && PyErr_Occurred())
2110 return NULL;
2111 return PyInt_FromLong(res);
2112}
2113
2114static struct wrapperbase tab_hash[] = {
2115 {"__hash__", (wrapperfunc)wrap_hashfunc,
2116 "x.__hash__() <==> hash(x)"},
2117 {0}
2118};
2119
2120static PyObject *
2121wrap_call(PyObject *self, PyObject *args, void *wrapped)
2122{
2123 ternaryfunc func = (ternaryfunc)wrapped;
2124
2125 /* XXX What about keyword arguments? */
2126 return (*func)(self, args, NULL);
2127}
2128
2129static struct wrapperbase tab_call[] = {
2130 {"__call__", (wrapperfunc)wrap_call,
2131 "x.__call__(...) <==> x(...)"},
2132 {0}
2133};
2134
2135static struct wrapperbase tab_str[] = {
2136 {"__str__", (wrapperfunc)wrap_unaryfunc,
2137 "x.__str__() <==> str(x)"},
2138 {0}
2139};
2140
2141static PyObject *
2142wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2143{
2144 richcmpfunc func = (richcmpfunc)wrapped;
2145 PyObject *other;
2146
2147 if (!PyArg_ParseTuple(args, "O", &other))
2148 return NULL;
2149 return (*func)(self, other, op);
2150}
2151
2152#undef RICHCMP_WRAPPER
2153#define RICHCMP_WRAPPER(NAME, OP) \
2154static PyObject * \
2155richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2156{ \
2157 return wrap_richcmpfunc(self, args, wrapped, OP); \
2158}
2159
Jack Jansen8e938b42001-08-08 15:29:49 +00002160RICHCMP_WRAPPER(lt, Py_LT)
2161RICHCMP_WRAPPER(le, Py_LE)
2162RICHCMP_WRAPPER(eq, Py_EQ)
2163RICHCMP_WRAPPER(ne, Py_NE)
2164RICHCMP_WRAPPER(gt, Py_GT)
2165RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166
2167#undef RICHCMP_ENTRY
2168#define RICHCMP_ENTRY(NAME, EXPR) \
2169 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2170 "x.__" #NAME "__(y) <==> " EXPR}
2171
2172static struct wrapperbase tab_richcmp[] = {
2173 RICHCMP_ENTRY(lt, "x<y"),
2174 RICHCMP_ENTRY(le, "x<=y"),
2175 RICHCMP_ENTRY(eq, "x==y"),
2176 RICHCMP_ENTRY(ne, "x!=y"),
2177 RICHCMP_ENTRY(gt, "x>y"),
2178 RICHCMP_ENTRY(ge, "x>=y"),
2179 {0}
2180};
2181
2182static struct wrapperbase tab_iter[] = {
2183 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2184 {0}
2185};
2186
2187static PyObject *
2188wrap_next(PyObject *self, PyObject *args, void *wrapped)
2189{
2190 unaryfunc func = (unaryfunc)wrapped;
2191 PyObject *res;
2192
2193 if (!PyArg_ParseTuple(args, ""))
2194 return NULL;
2195 res = (*func)(self);
2196 if (res == NULL && !PyErr_Occurred())
2197 PyErr_SetNone(PyExc_StopIteration);
2198 return res;
2199}
2200
2201static struct wrapperbase tab_next[] = {
2202 {"next", (wrapperfunc)wrap_next,
2203 "x.next() -> the next value, or raise StopIteration"},
2204 {0}
2205};
2206
2207static PyObject *
2208wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2209{
2210 descrgetfunc func = (descrgetfunc)wrapped;
2211 PyObject *obj;
2212 PyObject *type = NULL;
2213
2214 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2215 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002216 return (*func)(self, obj, type);
2217}
2218
2219static struct wrapperbase tab_descr_get[] = {
2220 {"__get__", (wrapperfunc)wrap_descr_get,
2221 "descr.__get__(obj, type) -> value"},
2222 {0}
2223};
2224
2225static PyObject *
2226wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2227{
2228 descrsetfunc func = (descrsetfunc)wrapped;
2229 PyObject *obj, *value;
2230 int ret;
2231
2232 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2233 return NULL;
2234 ret = (*func)(self, obj, value);
2235 if (ret < 0)
2236 return NULL;
2237 Py_INCREF(Py_None);
2238 return Py_None;
2239}
2240
2241static struct wrapperbase tab_descr_set[] = {
2242 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2243 "descr.__set__(obj, value)"},
2244 {0}
2245};
2246
2247static PyObject *
2248wrap_init(PyObject *self, PyObject *args, void *wrapped)
2249{
2250 initproc func = (initproc)wrapped;
2251
2252 /* XXX What about keyword arguments? */
2253 if (func(self, args, NULL) < 0)
2254 return NULL;
2255 Py_INCREF(Py_None);
2256 return Py_None;
2257}
2258
2259static struct wrapperbase tab_init[] = {
2260 {"__init__", (wrapperfunc)wrap_init,
2261 "x.__init__(...) initializes x; "
2262 "see x.__type__.__doc__ for signature"},
2263 {0}
2264};
2265
2266static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002267tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002268{
Barry Warsaw60f01882001-08-22 19:24:42 +00002269 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002270 PyObject *arg0, *res;
2271
2272 if (self == NULL || !PyType_Check(self))
2273 Py_FatalError("__new__() called with non-type 'self'");
2274 type = (PyTypeObject *)self;
2275 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002276 PyErr_Format(PyExc_TypeError,
2277 "%s.__new__(): not enough arguments",
2278 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002279 return NULL;
2280 }
2281 arg0 = PyTuple_GET_ITEM(args, 0);
2282 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002283 PyErr_Format(PyExc_TypeError,
2284 "%s.__new__(X): X is not a type object (%s)",
2285 type->tp_name,
2286 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002287 return NULL;
2288 }
2289 subtype = (PyTypeObject *)arg0;
2290 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002291 PyErr_Format(PyExc_TypeError,
2292 "%s.__new__(%s): %s is not a subtype of %s",
2293 type->tp_name,
2294 subtype->tp_name,
2295 subtype->tp_name,
2296 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002297 return NULL;
2298 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002299
2300 /* Check that the use doesn't do something silly and unsafe like
2301 object.__new__(dictionary). To do this, we check that the
2302 most derived base that's not a heap type is this type. */
2303 staticbase = subtype;
2304 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2305 staticbase = staticbase->tp_base;
2306 if (staticbase != type) {
2307 PyErr_Format(PyExc_TypeError,
2308 "%s.__new__(%s) is not safe, use %s.__new__()",
2309 type->tp_name,
2310 subtype->tp_name,
2311 staticbase == NULL ? "?" : staticbase->tp_name);
2312 return NULL;
2313 }
2314
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002315 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2316 if (args == NULL)
2317 return NULL;
2318 res = type->tp_new(subtype, args, kwds);
2319 Py_DECREF(args);
2320 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002321}
2322
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002323static struct PyMethodDef tp_new_methoddef[] = {
2324 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2325 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002326 {0}
2327};
2328
2329static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002330add_tp_new_wrapper(PyTypeObject *type)
2331{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002332 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002333
Guido van Rossumf040ede2001-08-07 16:40:56 +00002334 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2335 return 0;
2336 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002337 if (func == NULL)
2338 return -1;
2339 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2340}
2341
Guido van Rossum13d52f02001-08-10 21:24:08 +00002342static int
2343add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2344{
2345 PyObject *dict = type->tp_defined;
2346
2347 for (; wraps->name != NULL; wraps++) {
2348 PyObject *descr;
2349 if (PyDict_GetItemString(dict, wraps->name))
2350 continue;
2351 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2352 if (descr == NULL)
2353 return -1;
2354 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2355 return -1;
2356 Py_DECREF(descr);
2357 }
2358 return 0;
2359}
2360
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002361/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002362 dictionary with method descriptors for function slots. For each
2363 function slot (like tp_repr) that's defined in the type, one or
2364 more corresponding descriptors are added in the type's tp_defined
2365 dictionary under the appropriate name (like __repr__). Some
2366 function slots cause more than one descriptor to be added (for
2367 example, the nb_add slot adds both __add__ and __radd__
2368 descriptors) and some function slots compete for the same
2369 descriptor (for example both sq_item and mp_subscript generate a
2370 __getitem__ descriptor). This only adds new descriptors and
2371 doesn't overwrite entries in tp_defined that were previously
2372 defined. The descriptors contain a reference to the C function
2373 they must call, so that it's safe if they are copied into a
2374 subtype's __dict__ and the subtype has a different C function in
2375 its slot -- calling the method defined by the descriptor will call
2376 the C function that was used to create it, rather than the C
2377 function present in the slot when it is called. (This is important
2378 because a subtype may have a C function in the slot that calls the
2379 method from the dictionary, and we want to avoid infinite recursion
2380 here.) */
2381
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002382static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002383add_operators(PyTypeObject *type)
2384{
2385 PySequenceMethods *sq;
2386 PyMappingMethods *mp;
2387 PyNumberMethods *nb;
2388
2389#undef ADD
2390#define ADD(SLOT, TABLE) \
2391 if (SLOT) { \
2392 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2393 return -1; \
2394 }
2395
2396 if ((sq = type->tp_as_sequence) != NULL) {
2397 ADD(sq->sq_length, tab_len);
2398 ADD(sq->sq_concat, tab_concat);
2399 ADD(sq->sq_repeat, tab_mul_int);
2400 ADD(sq->sq_item, tab_getitem_int);
2401 ADD(sq->sq_slice, tab_getslice);
2402 ADD(sq->sq_ass_item, tab_setitem_int);
2403 ADD(sq->sq_ass_slice, tab_setslice);
2404 ADD(sq->sq_contains, tab_contains);
2405 ADD(sq->sq_inplace_concat, tab_iadd);
2406 ADD(sq->sq_inplace_repeat, tab_imul_int);
2407 }
2408
2409 if ((mp = type->tp_as_mapping) != NULL) {
2410 if (sq->sq_length == NULL)
2411 ADD(mp->mp_length, tab_len);
2412 ADD(mp->mp_subscript, tab_getitem);
2413 ADD(mp->mp_ass_subscript, tab_setitem);
2414 }
2415
2416 /* We don't support "old-style numbers" because their binary
2417 operators require that both arguments have the same type;
2418 the wrappers here only work for new-style numbers. */
2419 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2420 (nb = type->tp_as_number) != NULL) {
2421 ADD(nb->nb_add, tab_add);
2422 ADD(nb->nb_subtract, tab_sub);
2423 ADD(nb->nb_multiply, tab_mul);
2424 ADD(nb->nb_divide, tab_div);
2425 ADD(nb->nb_remainder, tab_mod);
2426 ADD(nb->nb_divmod, tab_divmod);
2427 ADD(nb->nb_power, tab_pow);
2428 ADD(nb->nb_negative, tab_neg);
2429 ADD(nb->nb_positive, tab_pos);
2430 ADD(nb->nb_absolute, tab_abs);
2431 ADD(nb->nb_nonzero, tab_nonzero);
2432 ADD(nb->nb_invert, tab_invert);
2433 ADD(nb->nb_lshift, tab_lshift);
2434 ADD(nb->nb_rshift, tab_rshift);
2435 ADD(nb->nb_and, tab_and);
2436 ADD(nb->nb_xor, tab_xor);
2437 ADD(nb->nb_or, tab_or);
2438 /* We don't support coerce() -- see above comment */
2439 ADD(nb->nb_int, tab_int);
2440 ADD(nb->nb_long, tab_long);
2441 ADD(nb->nb_float, tab_float);
2442 ADD(nb->nb_oct, tab_oct);
2443 ADD(nb->nb_hex, tab_hex);
2444 ADD(nb->nb_inplace_add, tab_iadd);
2445 ADD(nb->nb_inplace_subtract, tab_isub);
2446 ADD(nb->nb_inplace_multiply, tab_imul);
2447 ADD(nb->nb_inplace_divide, tab_idiv);
2448 ADD(nb->nb_inplace_remainder, tab_imod);
2449 ADD(nb->nb_inplace_power, tab_ipow);
2450 ADD(nb->nb_inplace_lshift, tab_ilshift);
2451 ADD(nb->nb_inplace_rshift, tab_irshift);
2452 ADD(nb->nb_inplace_and, tab_iand);
2453 ADD(nb->nb_inplace_xor, tab_ixor);
2454 ADD(nb->nb_inplace_or, tab_ior);
2455 }
2456
2457 ADD(type->tp_getattro, tab_getattr);
2458 ADD(type->tp_setattro, tab_setattr);
2459 ADD(type->tp_compare, tab_cmp);
2460 ADD(type->tp_repr, tab_repr);
2461 ADD(type->tp_hash, tab_hash);
2462 ADD(type->tp_call, tab_call);
2463 ADD(type->tp_str, tab_str);
2464 ADD(type->tp_richcompare, tab_richcmp);
2465 ADD(type->tp_iter, tab_iter);
2466 ADD(type->tp_iternext, tab_next);
2467 ADD(type->tp_descr_get, tab_descr_get);
2468 ADD(type->tp_descr_set, tab_descr_set);
2469 ADD(type->tp_init, tab_init);
2470
Guido van Rossumf040ede2001-08-07 16:40:56 +00002471 if (type->tp_new != NULL) {
2472 if (add_tp_new_wrapper(type) < 0)
2473 return -1;
2474 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002475
2476 return 0;
2477}
2478
Guido van Rossumf040ede2001-08-07 16:40:56 +00002479/* Slot wrappers that call the corresponding __foo__ slot. See comments
2480 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002481
Guido van Rossumdc91b992001-08-08 22:26:22 +00002482#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002483static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002484FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002485{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002486 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002487 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002488}
2489
Guido van Rossumdc91b992001-08-08 22:26:22 +00002490#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002491static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002492FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002493{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002494 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002495 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002496}
2497
Guido van Rossumdc91b992001-08-08 22:26:22 +00002498
2499#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002500static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002501FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002502{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002503 static PyObject *cache_str, *rcache_str; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002504 if (self->ob_type->tp_as_number != NULL && \
2505 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2506 PyObject *r; \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002507 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002508 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002509 if (r != Py_NotImplemented || \
2510 other->ob_type == self->ob_type) \
2511 return r; \
2512 Py_DECREF(r); \
2513 } \
2514 if (other->ob_type->tp_as_number != NULL && \
2515 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002516 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002517 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002518 } \
2519 Py_INCREF(Py_NotImplemented); \
2520 return Py_NotImplemented; \
2521}
2522
2523#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2524 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2525
2526#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2527static PyObject * \
2528FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2529{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002530 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002531 return call_method(self, OPSTR, &cache_str, \
2532 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002533}
2534
2535static int
2536slot_sq_length(PyObject *self)
2537{
Guido van Rossum2730b132001-08-28 18:22:14 +00002538 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002539 PyObject *res = call_method(self, "__len__", &len_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002540
2541 if (res == NULL)
2542 return -1;
2543 return (int)PyInt_AsLong(res);
2544}
2545
Guido van Rossumdc91b992001-08-08 22:26:22 +00002546SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2547SLOT1(slot_sq_repeat, "__mul__", int, "i")
2548SLOT1(slot_sq_item, "__getitem__", int, "i")
2549SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002550
2551static int
2552slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2553{
2554 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002555 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002556
2557 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002558 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002559 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002560 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002561 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002562 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002563 if (res == NULL)
2564 return -1;
2565 Py_DECREF(res);
2566 return 0;
2567}
2568
2569static int
2570slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2571{
2572 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002573 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002574
2575 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002576 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002577 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002578 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002579 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002580 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002581 if (res == NULL)
2582 return -1;
2583 Py_DECREF(res);
2584 return 0;
2585}
2586
2587static int
2588slot_sq_contains(PyObject *self, PyObject *value)
2589{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002590 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002591 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002592
Guido van Rossum60718732001-08-28 17:47:51 +00002593 func = lookup_method(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002594
2595 if (func != NULL) {
2596 args = Py_BuildValue("(O)", value);
2597 if (args == NULL)
2598 res = NULL;
2599 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002600 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002601 Py_DECREF(args);
2602 }
2603 Py_DECREF(func);
2604 if (res == NULL)
2605 return -1;
2606 return PyObject_IsTrue(res);
2607 }
2608 else {
2609 PyErr_Clear();
Tim Peters16a77ad2001-09-08 04:00:12 +00002610 return _PySequence_IterSearch(self, value,
2611 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002612 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002613}
2614
Guido van Rossumdc91b992001-08-08 22:26:22 +00002615SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2616SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002617
2618#define slot_mp_length slot_sq_length
2619
Guido van Rossumdc91b992001-08-08 22:26:22 +00002620SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002621
2622static int
2623slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2624{
2625 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002626 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002627
2628 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002629 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002630 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002631 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002632 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002633 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002634 if (res == NULL)
2635 return -1;
2636 Py_DECREF(res);
2637 return 0;
2638}
2639
Guido van Rossumdc91b992001-08-08 22:26:22 +00002640SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2641SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2642SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2643SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2644SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2645SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2646
2647staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2648
2649SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2650 nb_power, "__pow__", "__rpow__")
2651
2652static PyObject *
2653slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2654{
Guido van Rossum2730b132001-08-28 18:22:14 +00002655 static PyObject *pow_str;
2656
Guido van Rossumdc91b992001-08-08 22:26:22 +00002657 if (modulus == Py_None)
2658 return slot_nb_power_binary(self, other);
2659 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002660 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002661 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002662}
2663
2664SLOT0(slot_nb_negative, "__neg__")
2665SLOT0(slot_nb_positive, "__pos__")
2666SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667
2668static int
2669slot_nb_nonzero(PyObject *self)
2670{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002671 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002672 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002673
Guido van Rossum60718732001-08-28 17:47:51 +00002674 func = lookup_method(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002675 if (func == NULL) {
2676 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002677 func = lookup_method(self, "__len__", &len_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002678 }
2679
2680 if (func != NULL) {
Guido van Rossum717ce002001-09-14 16:58:08 +00002681 res = PyObject_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002682 Py_DECREF(func);
2683 if (res == NULL)
2684 return -1;
2685 return PyObject_IsTrue(res);
2686 }
2687 else {
2688 PyErr_Clear();
2689 return 1;
2690 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002691}
2692
Guido van Rossumdc91b992001-08-08 22:26:22 +00002693SLOT0(slot_nb_invert, "__invert__")
2694SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2695SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2696SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2697SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2698SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002699/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002700SLOT0(slot_nb_int, "__int__")
2701SLOT0(slot_nb_long, "__long__")
2702SLOT0(slot_nb_float, "__float__")
2703SLOT0(slot_nb_oct, "__oct__")
2704SLOT0(slot_nb_hex, "__hex__")
2705SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2706SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2707SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2708SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2709SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2710SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2711SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2712SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2713SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2714SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2715SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2716SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2717 "__floordiv__", "__rfloordiv__")
2718SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2719SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2720SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002721
2722static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002723half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002724{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002725 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002726 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002727 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728
Guido van Rossum60718732001-08-28 17:47:51 +00002729 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002730 if (func == NULL) {
2731 PyErr_Clear();
2732 }
2733 else {
2734 args = Py_BuildValue("(O)", other);
2735 if (args == NULL)
2736 res = NULL;
2737 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002738 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002739 Py_DECREF(args);
2740 }
2741 if (res != Py_NotImplemented) {
2742 if (res == NULL)
2743 return -2;
2744 c = PyInt_AsLong(res);
2745 Py_DECREF(res);
2746 if (c == -1 && PyErr_Occurred())
2747 return -2;
2748 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2749 }
2750 Py_DECREF(res);
2751 }
2752 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002753}
2754
Guido van Rossumb8f63662001-08-15 23:57:02 +00002755static int
2756slot_tp_compare(PyObject *self, PyObject *other)
2757{
2758 int c;
2759
2760 if (self->ob_type->tp_compare == slot_tp_compare) {
2761 c = half_compare(self, other);
2762 if (c <= 1)
2763 return c;
2764 }
2765 if (other->ob_type->tp_compare == slot_tp_compare) {
2766 c = half_compare(other, self);
2767 if (c < -1)
2768 return -2;
2769 if (c <= 1)
2770 return -c;
2771 }
2772 return (void *)self < (void *)other ? -1 :
2773 (void *)self > (void *)other ? 1 : 0;
2774}
2775
2776static PyObject *
2777slot_tp_repr(PyObject *self)
2778{
2779 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002780 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002781
Guido van Rossum60718732001-08-28 17:47:51 +00002782 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002783 if (func != NULL) {
2784 res = PyEval_CallObject(func, NULL);
2785 Py_DECREF(func);
2786 return res;
2787 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00002788 PyErr_Clear();
2789 return PyString_FromFormat("<%s object at %p>",
2790 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002791}
2792
2793static PyObject *
2794slot_tp_str(PyObject *self)
2795{
2796 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002797 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002798
Guido van Rossum60718732001-08-28 17:47:51 +00002799 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002800 if (func != NULL) {
2801 res = PyEval_CallObject(func, NULL);
2802 Py_DECREF(func);
2803 return res;
2804 }
2805 else {
2806 PyErr_Clear();
2807 return slot_tp_repr(self);
2808 }
2809}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810
2811static long
2812slot_tp_hash(PyObject *self)
2813{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002814 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002815 static PyObject *hash_str, *eq_str, *cmp_str;
2816
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817 long h;
2818
Guido van Rossum60718732001-08-28 17:47:51 +00002819 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002820
2821 if (func != NULL) {
2822 res = PyEval_CallObject(func, NULL);
2823 Py_DECREF(func);
2824 if (res == NULL)
2825 return -1;
2826 h = PyInt_AsLong(res);
2827 }
2828 else {
2829 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002830 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002831 if (func == NULL) {
2832 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002833 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002834 }
2835 if (func != NULL) {
2836 Py_DECREF(func);
2837 PyErr_SetString(PyExc_TypeError, "unhashable type");
2838 return -1;
2839 }
2840 PyErr_Clear();
2841 h = _Py_HashPointer((void *)self);
2842 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002843 if (h == -1 && !PyErr_Occurred())
2844 h = -2;
2845 return h;
2846}
2847
2848static PyObject *
2849slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2850{
Guido van Rossum60718732001-08-28 17:47:51 +00002851 static PyObject *call_str;
2852 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002853 PyObject *res;
2854
2855 if (meth == NULL)
2856 return NULL;
2857 res = PyObject_Call(meth, args, kwds);
2858 Py_DECREF(meth);
2859 return res;
2860}
2861
Tim Peters6d6c1a32001-08-02 04:15:00 +00002862static PyObject *
2863slot_tp_getattro(PyObject *self, PyObject *name)
2864{
2865 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002866 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002867 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002868
Guido van Rossum8e248182001-08-12 05:17:56 +00002869 if (getattr_str == NULL) {
2870 getattr_str = PyString_InternFromString("__getattr__");
2871 if (getattr_str == NULL)
2872 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002873 }
Guido van Rossum8e248182001-08-12 05:17:56 +00002874 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00002875 if (getattr == NULL) {
2876 /* Avoid further slowdowns */
2877 if (tp->tp_getattro == slot_tp_getattro)
2878 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002879 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00002880 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002881 return PyObject_CallFunction(getattr, "OO", self, name);
2882}
2883
2884static int
2885slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2886{
2887 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002888 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002889
2890 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002891 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002892 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002893 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002894 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002895 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002896 if (res == NULL)
2897 return -1;
2898 Py_DECREF(res);
2899 return 0;
2900}
2901
2902/* Map rich comparison operators to their __xx__ namesakes */
2903static char *name_op[] = {
2904 "__lt__",
2905 "__le__",
2906 "__eq__",
2907 "__ne__",
2908 "__gt__",
2909 "__ge__",
2910};
2911
2912static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00002913half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002914{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002915 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002916 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00002917
Guido van Rossum60718732001-08-28 17:47:51 +00002918 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002919 if (func == NULL) {
2920 PyErr_Clear();
2921 Py_INCREF(Py_NotImplemented);
2922 return Py_NotImplemented;
2923 }
2924 args = Py_BuildValue("(O)", other);
2925 if (args == NULL)
2926 res = NULL;
2927 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002928 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002929 Py_DECREF(args);
2930 }
2931 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002932 return res;
2933}
2934
Guido van Rossumb8f63662001-08-15 23:57:02 +00002935/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
2936static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
2937
2938static PyObject *
2939slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2940{
2941 PyObject *res;
2942
2943 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
2944 res = half_richcompare(self, other, op);
2945 if (res != Py_NotImplemented)
2946 return res;
2947 Py_DECREF(res);
2948 }
2949 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
2950 res = half_richcompare(other, self, swapped_op[op]);
2951 if (res != Py_NotImplemented) {
2952 return res;
2953 }
2954 Py_DECREF(res);
2955 }
2956 Py_INCREF(Py_NotImplemented);
2957 return Py_NotImplemented;
2958}
2959
2960static PyObject *
2961slot_tp_iter(PyObject *self)
2962{
2963 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002964 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002965
Guido van Rossum60718732001-08-28 17:47:51 +00002966 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002967 if (func != NULL) {
2968 res = PyObject_CallObject(func, NULL);
2969 Py_DECREF(func);
2970 return res;
2971 }
2972 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002973 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002974 if (func == NULL) {
2975 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
2976 return NULL;
2977 }
2978 Py_DECREF(func);
2979 return PySeqIter_New(self);
2980}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002981
2982static PyObject *
2983slot_tp_iternext(PyObject *self)
2984{
Guido van Rossum2730b132001-08-28 18:22:14 +00002985 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002986 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987}
2988
Guido van Rossum1a493502001-08-17 16:47:50 +00002989static PyObject *
2990slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
2991{
2992 PyTypeObject *tp = self->ob_type;
2993 PyObject *get;
2994 static PyObject *get_str = NULL;
2995
2996 if (get_str == NULL) {
2997 get_str = PyString_InternFromString("__get__");
2998 if (get_str == NULL)
2999 return NULL;
3000 }
3001 get = _PyType_Lookup(tp, get_str);
3002 if (get == NULL) {
3003 /* Avoid further slowdowns */
3004 if (tp->tp_descr_get == slot_tp_descr_get)
3005 tp->tp_descr_get = NULL;
3006 Py_INCREF(self);
3007 return self;
3008 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003009 if (obj == NULL)
3010 obj = Py_None;
3011 if (type == NULL)
3012 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003013 return PyObject_CallFunction(get, "OOO", self, obj, type);
3014}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015
3016static int
3017slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3018{
Guido van Rossum2c252392001-08-24 10:13:31 +00003019 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003020 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003021
3022 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003023 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003024 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003025 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003026 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003027 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003028 if (res == NULL)
3029 return -1;
3030 Py_DECREF(res);
3031 return 0;
3032}
3033
3034static int
3035slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3036{
Guido van Rossum60718732001-08-28 17:47:51 +00003037 static PyObject *init_str;
3038 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003039 PyObject *res;
3040
3041 if (meth == NULL)
3042 return -1;
3043 res = PyObject_Call(meth, args, kwds);
3044 Py_DECREF(meth);
3045 if (res == NULL)
3046 return -1;
3047 Py_DECREF(res);
3048 return 0;
3049}
3050
3051static PyObject *
3052slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3053{
3054 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3055 PyObject *newargs, *x;
3056 int i, n;
3057
3058 if (func == NULL)
3059 return NULL;
3060 assert(PyTuple_Check(args));
3061 n = PyTuple_GET_SIZE(args);
3062 newargs = PyTuple_New(n+1);
3063 if (newargs == NULL)
3064 return NULL;
3065 Py_INCREF(type);
3066 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3067 for (i = 0; i < n; i++) {
3068 x = PyTuple_GET_ITEM(args, i);
3069 Py_INCREF(x);
3070 PyTuple_SET_ITEM(newargs, i+1, x);
3071 }
3072 x = PyObject_Call(func, newargs, kwds);
3073 Py_DECREF(func);
3074 return x;
3075}
3076
Guido van Rossumf040ede2001-08-07 16:40:56 +00003077/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003078 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003079 The dict argument is the dictionary argument passed to type_new(),
3080 which is the local namespace of the class statement, in other
3081 words, it contains the methods. For each special method (like
3082 __repr__) defined in the dictionary, the corresponding function
3083 slot in the type object (like tp_repr) is set to a special function
3084 whose name is 'slot_' followed by the slot name and whose signature
3085 is whatever is required for that slot. These slot functions look
3086 up the corresponding method in the type's dictionary and call it.
3087 The slot functions have to take care of the various peculiarities
3088 of the mapping between slots and special methods, such as mapping
3089 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3090 etc.) or mapping multiple slots to a single method (sq_item,
3091 mp_subscript <--> __getitem__). */
3092
Tim Peters6d6c1a32001-08-02 04:15:00 +00003093static void
3094override_slots(PyTypeObject *type, PyObject *dict)
3095{
3096 PySequenceMethods *sq = type->tp_as_sequence;
3097 PyMappingMethods *mp = type->tp_as_mapping;
3098 PyNumberMethods *nb = type->tp_as_number;
3099
Guido van Rossumdc91b992001-08-08 22:26:22 +00003100#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003101 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003102 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103 }
3104
Guido van Rossumdc91b992001-08-08 22:26:22 +00003105#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003106 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003107 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003108 }
3109
Guido van Rossumdc91b992001-08-08 22:26:22 +00003110#define NBSLOT(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 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003113 }
3114
Guido van Rossumdc91b992001-08-08 22:26:22 +00003115#define TPSLOT(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 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118 }
3119
Guido van Rossumdc91b992001-08-08 22:26:22 +00003120 SQSLOT("__len__", sq_length, slot_sq_length);
3121 SQSLOT("__add__", sq_concat, slot_sq_concat);
3122 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3123 SQSLOT("__getitem__", sq_item, slot_sq_item);
3124 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3125 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3126 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3127 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3128 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3129 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3130 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3131 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132
Guido van Rossumdc91b992001-08-08 22:26:22 +00003133 MPSLOT("__len__", mp_length, slot_mp_length);
3134 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3135 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3136 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003137
Guido van Rossumdc91b992001-08-08 22:26:22 +00003138 NBSLOT("__add__", nb_add, slot_nb_add);
3139 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3140 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3141 NBSLOT("__div__", nb_divide, slot_nb_divide);
3142 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3143 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3144 NBSLOT("__pow__", nb_power, slot_nb_power);
3145 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3146 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3147 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3148 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3149 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3150 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3151 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3152 NBSLOT("__and__", nb_and, slot_nb_and);
3153 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3154 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003155 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00003156 NBSLOT("__int__", nb_int, slot_nb_int);
3157 NBSLOT("__long__", nb_long, slot_nb_long);
3158 NBSLOT("__float__", nb_float, slot_nb_float);
3159 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3160 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3161 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3162 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3163 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3164 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3165 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3166 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3167 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3168 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3169 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3170 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3171 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3172 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3173 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3174 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3175 slot_nb_inplace_floor_divide);
3176 NBSLOT("__itruediv__", nb_inplace_true_divide,
3177 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003178
Guido van Rossum8e248182001-08-12 05:17:56 +00003179 if (dict == NULL ||
3180 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181 PyDict_GetItemString(dict, "__repr__"))
3182 type->tp_print = NULL;
3183
Guido van Rossumdc91b992001-08-08 22:26:22 +00003184 TPSLOT("__cmp__", tp_compare, slot_tp_compare);
3185 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3186 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3187 TPSLOT("__call__", tp_call, slot_tp_call);
3188 TPSLOT("__str__", tp_str, slot_tp_str);
3189 TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
3190 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3191 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3192 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3193 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3194 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3195 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3196 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3197 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3198 TPSLOT("next", tp_iternext, slot_tp_iternext);
3199 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3200 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3201 TPSLOT("__init__", tp_init, slot_tp_init);
3202 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003203}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003204
3205
3206/* Cooperative 'super' */
3207
3208typedef struct {
3209 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003210 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003211 PyObject *obj;
3212} superobject;
3213
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003214static struct memberlist super_members[] = {
3215 {"__type__", T_OBJECT, offsetof(superobject, type), READONLY},
3216 {"__obj__", T_OBJECT, offsetof(superobject, obj), READONLY},
3217 {0}
3218};
3219
Guido van Rossum705f0f52001-08-24 16:47:00 +00003220static void
3221super_dealloc(PyObject *self)
3222{
3223 superobject *su = (superobject *)self;
3224
3225 Py_XDECREF(su->obj);
3226 Py_XDECREF(su->type);
3227 self->ob_type->tp_free(self);
3228}
3229
3230static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003231super_repr(PyObject *self)
3232{
3233 superobject *su = (superobject *)self;
3234
3235 if (su->obj)
3236 return PyString_FromFormat(
3237 "<super: <type '%s'>, <%s object>>",
3238 su->type ? su->type->tp_name : "NULL",
3239 su->obj->ob_type->tp_name);
3240 else
3241 return PyString_FromFormat(
3242 "<super: <type '%s'>, NULL>",
3243 su->type ? su->type->tp_name : "NULL");
3244}
3245
3246static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003247super_getattro(PyObject *self, PyObject *name)
3248{
3249 superobject *su = (superobject *)self;
3250
3251 if (su->obj != NULL) {
3252 PyObject *mro, *res, *tmp;
3253 descrgetfunc f;
3254 int i, n;
3255
Guido van Rossume705ef12001-08-29 15:47:06 +00003256 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003257 if (mro == NULL)
3258 n = 0;
3259 else {
3260 assert(PyTuple_Check(mro));
3261 n = PyTuple_GET_SIZE(mro);
3262 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003263 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003264 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003265 break;
3266 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003267 if (i >= n && PyType_Check(su->obj)) {
3268 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003269 if (mro == NULL)
3270 n = 0;
3271 else {
3272 assert(PyTuple_Check(mro));
3273 n = PyTuple_GET_SIZE(mro);
3274 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003275 for (i = 0; i < n; i++) {
3276 if ((PyObject *)(su->type) ==
3277 PyTuple_GET_ITEM(mro, i))
3278 break;
3279 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003280 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003281 i++;
3282 res = NULL;
3283 for (; i < n; i++) {
3284 tmp = PyTuple_GET_ITEM(mro, i);
3285 assert(PyType_Check(tmp));
3286 res = PyDict_GetItem(
3287 ((PyTypeObject *)tmp)->tp_defined, name);
3288 if (res != NULL) {
3289 Py_INCREF(res);
3290 f = res->ob_type->tp_descr_get;
3291 if (f != NULL) {
3292 tmp = f(res, su->obj, res);
3293 Py_DECREF(res);
3294 res = tmp;
3295 }
3296 return res;
3297 }
3298 }
3299 }
3300 return PyObject_GenericGetAttr(self, name);
3301}
3302
3303static PyObject *
3304super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3305{
3306 superobject *su = (superobject *)self;
3307 superobject *new;
3308
3309 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3310 /* Not binding to an object, or already bound */
3311 Py_INCREF(self);
3312 return self;
3313 }
3314 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3315 if (new == NULL)
3316 return NULL;
3317 Py_INCREF(su->type);
3318 Py_INCREF(obj);
3319 new->type = su->type;
3320 new->obj = obj;
3321 return (PyObject *)new;
3322}
3323
3324static int
3325super_init(PyObject *self, PyObject *args, PyObject *kwds)
3326{
3327 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003328 PyTypeObject *type;
3329 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003330
3331 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3332 return -1;
3333 if (obj == Py_None)
3334 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003335 if (obj != NULL &&
3336 !PyType_IsSubtype(obj->ob_type, type) &&
3337 !(PyType_Check(obj) &&
3338 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003339 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003340 "super(type, obj): "
3341 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003342 return -1;
3343 }
3344 Py_INCREF(type);
3345 Py_XINCREF(obj);
3346 su->type = type;
3347 su->obj = obj;
3348 return 0;
3349}
3350
3351static char super_doc[] =
3352"super(type) -> unbound super object\n"
3353"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003354"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003355"Typical use to call a cooperative superclass method:\n"
3356"class C(B):\n"
3357" def meth(self, arg):\n"
3358" super(C, self).meth(arg)";
3359
3360PyTypeObject PySuper_Type = {
3361 PyObject_HEAD_INIT(&PyType_Type)
3362 0, /* ob_size */
3363 "super", /* tp_name */
3364 sizeof(superobject), /* tp_basicsize */
3365 0, /* tp_itemsize */
3366 /* methods */
3367 super_dealloc, /* tp_dealloc */
3368 0, /* tp_print */
3369 0, /* tp_getattr */
3370 0, /* tp_setattr */
3371 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003372 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003373 0, /* tp_as_number */
3374 0, /* tp_as_sequence */
3375 0, /* tp_as_mapping */
3376 0, /* tp_hash */
3377 0, /* tp_call */
3378 0, /* tp_str */
3379 super_getattro, /* tp_getattro */
3380 0, /* tp_setattro */
3381 0, /* tp_as_buffer */
Guido van Rossum31bcff82001-08-30 04:37:15 +00003382 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003383 super_doc, /* tp_doc */
3384 0, /* tp_traverse */
3385 0, /* tp_clear */
3386 0, /* tp_richcompare */
3387 0, /* tp_weaklistoffset */
3388 0, /* tp_iter */
3389 0, /* tp_iternext */
3390 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003391 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003392 0, /* tp_getset */
3393 0, /* tp_base */
3394 0, /* tp_dict */
3395 super_descr_get, /* tp_descr_get */
3396 0, /* tp_descr_set */
3397 0, /* tp_dictoffset */
3398 super_init, /* tp_init */
3399 PyType_GenericAlloc, /* tp_alloc */
3400 PyType_GenericNew, /* tp_new */
3401 _PyObject_Del, /* tp_free */
3402};