blob: 027a568dec971f3810659fc3ad474f82b68155ee [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Type object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum6f799372001-09-20 20:46:19 +00007static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00008 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
9 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
10 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
11 {"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
17 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
18 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
25 char *s;
26
27 s = strrchr(type->tp_name, '.');
28 if (s == NULL)
29 s = type->tp_name;
30 else
31 s++;
32 return PyString_FromString(s);
33}
34
35static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000036type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000037{
Guido van Rossumc3542212001-08-16 09:18:56 +000038 PyObject *mod;
39 char *s;
40
41 s = strrchr(type->tp_name, '.');
42 if (s != NULL)
43 return PyString_FromStringAndSize(type->tp_name,
44 (int)(s - type->tp_name));
45 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
46 return PyString_FromString("__builtin__");
47 mod = PyDict_GetItemString(type->tp_defined, "__module__");
48 if (mod != NULL && PyString_Check(mod)) {
49 Py_INCREF(mod);
50 return mod;
51 }
52 PyErr_SetString(PyExc_AttributeError, "__module__");
53 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000054}
55
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
Guido van Rossum32d34c82001-09-20 21:45:26 +000094PyGetSetDef 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;
Guido van Rossum6f799372001-09-20 20:46:19 +0000266 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000267} 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
Guido van Rossum32d34c82001-09-20 21:45:26 +0000662PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000663 {"__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;
Guido van Rossum6f799372001-09-20 20:46:19 +0000675 PyMemberDef *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000676 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000678 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000679 if (metatype == &PyType_Type &&
680 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
681 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000682 PyObject *x = PyTuple_GET_ITEM(args, 0);
683 Py_INCREF(x->ob_type);
684 return (PyObject *) x->ob_type;
685 }
686
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000687 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
689 &name,
690 &PyTuple_Type, &bases,
691 &PyDict_Type, &dict))
692 return NULL;
693
694 /* Determine the proper metatype to deal with this,
695 and check for metatype conflicts while we're at it.
696 Note that if some other metatype wins to contract,
697 it's possible that its instances are not types. */
698 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000699 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700 for (i = 0; i < nbases; i++) {
701 tmp = PyTuple_GET_ITEM(bases, i);
702 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000703 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000704 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000705 if (PyType_IsSubtype(tmptype, winner)) {
706 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000707 continue;
708 }
709 PyErr_SetString(PyExc_TypeError,
710 "metatype conflict among bases");
711 return NULL;
712 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000713 if (winner != metatype) {
714 if (winner->tp_new != type_new) /* Pass it to the winner */
715 return winner->tp_new(winner, args, kwds);
716 metatype = winner;
717 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718
719 /* Adjust for empty tuple bases */
720 if (nbases == 0) {
721 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
722 if (bases == NULL)
723 return NULL;
724 nbases = 1;
725 }
726 else
727 Py_INCREF(bases);
728
729 /* XXX From here until type is allocated, "return NULL" leaks bases! */
730
731 /* Calculate best base, and check that all bases are type objects */
732 base = best_base(bases);
733 if (base == NULL)
734 return NULL;
735 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
736 PyErr_Format(PyExc_TypeError,
737 "type '%.100s' is not an acceptable base type",
738 base->tp_name);
739 return NULL;
740 }
741
Guido van Rossum1a493502001-08-17 16:47:50 +0000742 /* Should this be a dynamic class (i.e. modifiable __dict__)?
743 Look in two places for a variable named __dynamic__:
744 1) in the class dict
745 2) in the module dict (globals)
746 The first variable that is an int >= 0 is used.
747 Otherwise, a default is calculated from the base classes:
748 if any base class is dynamic, this class is dynamic; otherwise
749 it is static. */
750 dynamic = -1; /* Not yet determined */
751 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000752 tmp = PyDict_GetItemString(dict, "__dynamic__");
753 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000754 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000755 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000756 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000757 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000758 if (dynamic < 0) {
759 /* Look in the module globals */
760 tmp = PyEval_GetGlobals();
761 if (tmp != NULL) {
762 tmp = PyDict_GetItemString(tmp, "__dynamic__");
763 if (tmp != NULL) {
764 dynamic = PyInt_AsLong(tmp);
765 if (dynamic < 0)
766 PyErr_Clear();
767 }
768 }
769 }
770 if (dynamic < 0) {
771 /* Make a new class dynamic if any of its bases is
772 dynamic. This is not always the same as inheriting
773 the __dynamic__ class attribute! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000774 dynamic = 0;
775 for (i = 0; i < nbases; i++) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000776 tmptype = (PyTypeObject *)
777 PyTuple_GET_ITEM(bases, i);
778 if (tmptype->tp_flags &
779 Py_TPFLAGS_DYNAMICTYPE) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000780 dynamic = 1;
781 break;
782 }
783 }
784 }
785
786 /* Check for a __slots__ sequence variable in dict, and count it */
787 slots = PyDict_GetItemString(dict, "__slots__");
788 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000789 add_dict = 0;
790 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000791 if (slots != NULL) {
792 /* Make it into a tuple */
793 if (PyString_Check(slots))
794 slots = Py_BuildValue("(O)", slots);
795 else
796 slots = PySequence_Tuple(slots);
797 if (slots == NULL)
798 return NULL;
799 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000800 if (nslots > 0 && base->tp_itemsize != 0) {
801 PyErr_Format(PyExc_TypeError,
802 "nonempty __slots__ "
803 "not supported for subtype of '%s'",
804 base->tp_name);
805 return NULL;
806 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000807 for (i = 0; i < nslots; i++) {
808 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
809 PyErr_SetString(PyExc_TypeError,
810 "__slots__ must be a sequence of strings");
811 Py_DECREF(slots);
812 return NULL;
813 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000814 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000815 }
816 }
817 if (slots == NULL && base->tp_dictoffset == 0 &&
818 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000819 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000820 add_dict++;
821 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000822 if (slots == NULL && base->tp_weaklistoffset == 0 &&
823 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000824 nslots++;
825 add_weak++;
826 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000827
828 /* XXX From here until type is safely allocated,
829 "return NULL" may leak slots! */
830
831 /* Allocate the type object */
832 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
833 if (type == NULL)
834 return NULL;
835
836 /* Keep name and slots alive in the extended type object */
837 et = (etype *)type;
838 Py_INCREF(name);
839 et->name = name;
840 et->slots = slots;
841
Guido van Rossumdc91b992001-08-08 22:26:22 +0000842 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000843 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
844 Py_TPFLAGS_BASETYPE;
845 if (dynamic)
846 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000847
848 /* It's a new-style number unless it specifically inherits any
849 old-style numeric behavior */
850 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
851 (base->tp_as_number == NULL))
852 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
853
854 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000855 type->tp_as_number = &et->as_number;
856 type->tp_as_sequence = &et->as_sequence;
857 type->tp_as_mapping = &et->as_mapping;
858 type->tp_as_buffer = &et->as_buffer;
859 type->tp_name = PyString_AS_STRING(name);
860
861 /* Set tp_base and tp_bases */
862 type->tp_bases = bases;
863 Py_INCREF(base);
864 type->tp_base = base;
865
866 /* Initialize tp_defined from passed-in dict */
867 type->tp_defined = dict = PyDict_Copy(dict);
868 if (dict == NULL) {
869 Py_DECREF(type);
870 return NULL;
871 }
872
Guido van Rossumc3542212001-08-16 09:18:56 +0000873 /* Set __module__ in the dict */
874 if (PyDict_GetItemString(dict, "__module__") == NULL) {
875 tmp = PyEval_GetGlobals();
876 if (tmp != NULL) {
877 tmp = PyDict_GetItemString(tmp, "__name__");
878 if (tmp != NULL) {
879 if (PyDict_SetItemString(dict, "__module__",
880 tmp) < 0)
881 return NULL;
882 }
883 }
884 }
885
Tim Peters6d6c1a32001-08-02 04:15:00 +0000886 /* Special-case __new__: if it's a plain function,
887 make it a static function */
888 tmp = PyDict_GetItemString(dict, "__new__");
889 if (tmp != NULL && PyFunction_Check(tmp)) {
890 tmp = PyStaticMethod_New(tmp);
891 if (tmp == NULL) {
892 Py_DECREF(type);
893 return NULL;
894 }
895 PyDict_SetItemString(dict, "__new__", tmp);
896 Py_DECREF(tmp);
897 }
898
899 /* Add descriptors for custom slots from __slots__, or for __dict__ */
900 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000901 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000902 if (slots != NULL) {
903 for (i = 0; i < nslots; i++, mp++) {
904 mp->name = PyString_AS_STRING(
905 PyTuple_GET_ITEM(slots, i));
906 mp->type = T_OBJECT;
907 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000908 if (base->tp_weaklistoffset == 0 &&
909 strcmp(mp->name, "__weakref__") == 0)
910 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000911 slotoffset += sizeof(PyObject *);
912 }
913 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000914 else {
915 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000916 if (base->tp_itemsize)
Tim Peters017cb2c2001-08-30 20:07:55 +0000917 type->tp_dictoffset = -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000918 else
919 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000920 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000921 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000922 }
923 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000924 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000925 type->tp_weaklistoffset = slotoffset;
926 mp->name = "__weakref__";
927 mp->type = T_OBJECT;
928 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000929 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000930 mp++;
931 slotoffset += sizeof(PyObject *);
932 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000933 }
934 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000935 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000936 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000937
938 /* Special case some slots */
939 if (type->tp_dictoffset != 0 || nslots > 0) {
940 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
941 type->tp_getattro = PyObject_GenericGetAttr;
942 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
943 type->tp_setattro = PyObject_GenericSetAttr;
944 }
945 type->tp_dealloc = subtype_dealloc;
946
947 /* Always override allocation strategy to use regular heap */
948 type->tp_alloc = PyType_GenericAlloc;
949 type->tp_free = _PyObject_Del;
950
951 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000952 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000953 Py_DECREF(type);
954 return NULL;
955 }
956
957 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +0000958 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
959 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000960
Tim Peters6d6c1a32001-08-02 04:15:00 +0000961 return (PyObject *)type;
962}
963
964/* Internal API to look for a name through the MRO.
965 This returns a borrowed reference, and doesn't set an exception! */
966PyObject *
967_PyType_Lookup(PyTypeObject *type, PyObject *name)
968{
969 int i, n;
970 PyObject *mro, *res, *dict;
971
972 /* For static types, look in tp_dict */
973 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
974 dict = type->tp_dict;
975 assert(dict && PyDict_Check(dict));
976 return PyDict_GetItem(dict, name);
977 }
978
979 /* For dynamic types, look in tp_defined of types in MRO */
980 mro = type->tp_mro;
981 assert(PyTuple_Check(mro));
982 n = PyTuple_GET_SIZE(mro);
983 for (i = 0; i < n; i++) {
984 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
985 assert(PyType_Check(type));
986 dict = type->tp_defined;
987 assert(dict && PyDict_Check(dict));
988 res = PyDict_GetItem(dict, name);
989 if (res != NULL)
990 return res;
991 }
992 return NULL;
993}
994
995/* This is similar to PyObject_GenericGetAttr(),
996 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
997static PyObject *
998type_getattro(PyTypeObject *type, PyObject *name)
999{
1000 PyTypeObject *metatype = type->ob_type;
1001 PyObject *descr, *res;
1002 descrgetfunc f;
1003
1004 /* Initialize this type (we'll assume the metatype is initialized) */
1005 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001006 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007 return NULL;
1008 }
1009
1010 /* Get a descriptor from the metatype */
1011 descr = _PyType_Lookup(metatype, name);
1012 f = NULL;
1013 if (descr != NULL) {
1014 f = descr->ob_type->tp_descr_get;
1015 if (f != NULL && PyDescr_IsData(descr))
1016 return f(descr,
1017 (PyObject *)type, (PyObject *)metatype);
1018 }
1019
1020 /* Look in tp_defined of this type and its bases */
1021 res = _PyType_Lookup(type, name);
1022 if (res != NULL) {
1023 f = res->ob_type->tp_descr_get;
1024 if (f != NULL)
1025 return f(res, (PyObject *)NULL, (PyObject *)type);
1026 Py_INCREF(res);
1027 return res;
1028 }
1029
1030 /* Use the descriptor from the metatype */
1031 if (f != NULL) {
1032 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1033 return res;
1034 }
1035 if (descr != NULL) {
1036 Py_INCREF(descr);
1037 return descr;
1038 }
1039
1040 /* Give up */
1041 PyErr_Format(PyExc_AttributeError,
1042 "type object '%.50s' has no attribute '%.400s'",
1043 type->tp_name, PyString_AS_STRING(name));
1044 return NULL;
1045}
1046
1047static int
1048type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1049{
1050 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
1051 return PyObject_GenericSetAttr((PyObject *)type, name, value);
1052 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
1053 return -1;
1054}
1055
1056static void
1057type_dealloc(PyTypeObject *type)
1058{
1059 etype *et;
1060
1061 /* Assert this is a heap-allocated type object */
1062 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
1063 et = (etype *)type;
1064 Py_XDECREF(type->tp_base);
1065 Py_XDECREF(type->tp_dict);
1066 Py_XDECREF(type->tp_bases);
1067 Py_XDECREF(type->tp_mro);
1068 Py_XDECREF(type->tp_defined);
1069 /* XXX more? */
1070 Py_XDECREF(et->name);
1071 Py_XDECREF(et->slots);
1072 type->ob_type->tp_free((PyObject *)type);
1073}
1074
1075static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001076 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001077 "mro() -> list\nreturn a type's method resolution order"},
1078 {0}
1079};
1080
1081static char type_doc[] =
1082"type(object) -> the object's type\n"
1083"type(name, bases, dict) -> a new type";
1084
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001085PyTypeObject PyType_Type = {
1086 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087 0, /* ob_size */
1088 "type", /* tp_name */
1089 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001090 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091 (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__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001160 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001161 PyString_AS_STRING(mod),
1162 PyString_AS_STRING(name),
1163 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001164 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001165 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001166 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
Guido van Rossum6f799372001-09-20 20:46:19 +00001195static PyMemberDef object_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196 {"__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
Guido van Rossum6f799372001-09-20 20:46:19 +00001266add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001267{
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
Guido van Rossum32d34c82001-09-20 21:45:26 +00001285add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286{
1287 PyObject *dict = type->tp_defined;
1288
1289 for (; gsp->name != NULL; gsp++) {
1290 PyObject *descr;
1291 if (PyDict_GetItemString(dict, gsp->name))
1292 continue;
1293 descr = PyDescr_NewGetSet(type, gsp);
1294
1295 if (descr == NULL)
1296 return -1;
1297 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1298 return -1;
1299 Py_DECREF(descr);
1300 }
1301 return 0;
1302}
1303
Guido van Rossum13d52f02001-08-10 21:24:08 +00001304static void
1305inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306{
1307 int oldsize, newsize;
1308
Guido van Rossum13d52f02001-08-10 21:24:08 +00001309 /* Special flag magic */
1310 if (!type->tp_as_buffer && base->tp_as_buffer) {
1311 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1312 type->tp_flags |=
1313 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1314 }
1315 if (!type->tp_as_sequence && base->tp_as_sequence) {
1316 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1317 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1318 }
1319 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1320 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1321 if ((!type->tp_as_number && base->tp_as_number) ||
1322 (!type->tp_as_sequence && base->tp_as_sequence)) {
1323 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1324 if (!type->tp_as_number && !type->tp_as_sequence) {
1325 type->tp_flags |= base->tp_flags &
1326 Py_TPFLAGS_HAVE_INPLACEOPS;
1327 }
1328 }
1329 /* Wow */
1330 }
1331 if (!type->tp_as_number && base->tp_as_number) {
1332 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1333 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1334 }
1335
1336 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001337 oldsize = base->tp_basicsize;
1338 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1339 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1340 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001341 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1342 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001343 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001344 if (type->tp_traverse == NULL)
1345 type->tp_traverse = base->tp_traverse;
1346 if (type->tp_clear == NULL)
1347 type->tp_clear = base->tp_clear;
1348 }
1349 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1350 if (base != &PyBaseObject_Type ||
1351 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1352 if (type->tp_new == NULL)
1353 type->tp_new = base->tp_new;
1354 }
1355 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001356 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001357
1358 /* Copy other non-function slots */
1359
1360#undef COPYVAL
1361#define COPYVAL(SLOT) \
1362 if (type->SLOT == 0) type->SLOT = base->SLOT
1363
1364 COPYVAL(tp_itemsize);
1365 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1366 COPYVAL(tp_weaklistoffset);
1367 }
1368 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1369 COPYVAL(tp_dictoffset);
1370 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001371}
1372
1373static void
1374inherit_slots(PyTypeObject *type, PyTypeObject *base)
1375{
1376 PyTypeObject *basebase;
1377
1378#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001379#undef COPYSLOT
1380#undef COPYNUM
1381#undef COPYSEQ
1382#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001383
1384#define SLOTDEFINED(SLOT) \
1385 (base->SLOT != 0 && \
1386 (basebase == NULL || base->SLOT != basebase->SLOT))
1387
Tim Peters6d6c1a32001-08-02 04:15:00 +00001388#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001389 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001390
1391#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1392#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1393#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1394
Guido van Rossum13d52f02001-08-10 21:24:08 +00001395 /* This won't inherit indirect slots (from tp_as_number etc.)
1396 if type doesn't provide the space. */
1397
1398 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1399 basebase = base->tp_base;
1400 if (basebase->tp_as_number == NULL)
1401 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402 COPYNUM(nb_add);
1403 COPYNUM(nb_subtract);
1404 COPYNUM(nb_multiply);
1405 COPYNUM(nb_divide);
1406 COPYNUM(nb_remainder);
1407 COPYNUM(nb_divmod);
1408 COPYNUM(nb_power);
1409 COPYNUM(nb_negative);
1410 COPYNUM(nb_positive);
1411 COPYNUM(nb_absolute);
1412 COPYNUM(nb_nonzero);
1413 COPYNUM(nb_invert);
1414 COPYNUM(nb_lshift);
1415 COPYNUM(nb_rshift);
1416 COPYNUM(nb_and);
1417 COPYNUM(nb_xor);
1418 COPYNUM(nb_or);
1419 COPYNUM(nb_coerce);
1420 COPYNUM(nb_int);
1421 COPYNUM(nb_long);
1422 COPYNUM(nb_float);
1423 COPYNUM(nb_oct);
1424 COPYNUM(nb_hex);
1425 COPYNUM(nb_inplace_add);
1426 COPYNUM(nb_inplace_subtract);
1427 COPYNUM(nb_inplace_multiply);
1428 COPYNUM(nb_inplace_divide);
1429 COPYNUM(nb_inplace_remainder);
1430 COPYNUM(nb_inplace_power);
1431 COPYNUM(nb_inplace_lshift);
1432 COPYNUM(nb_inplace_rshift);
1433 COPYNUM(nb_inplace_and);
1434 COPYNUM(nb_inplace_xor);
1435 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001436 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1437 COPYNUM(nb_true_divide);
1438 COPYNUM(nb_floor_divide);
1439 COPYNUM(nb_inplace_true_divide);
1440 COPYNUM(nb_inplace_floor_divide);
1441 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001442 }
1443
Guido van Rossum13d52f02001-08-10 21:24:08 +00001444 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1445 basebase = base->tp_base;
1446 if (basebase->tp_as_sequence == NULL)
1447 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001448 COPYSEQ(sq_length);
1449 COPYSEQ(sq_concat);
1450 COPYSEQ(sq_repeat);
1451 COPYSEQ(sq_item);
1452 COPYSEQ(sq_slice);
1453 COPYSEQ(sq_ass_item);
1454 COPYSEQ(sq_ass_slice);
1455 COPYSEQ(sq_contains);
1456 COPYSEQ(sq_inplace_concat);
1457 COPYSEQ(sq_inplace_repeat);
1458 }
1459
Guido van Rossum13d52f02001-08-10 21:24:08 +00001460 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1461 basebase = base->tp_base;
1462 if (basebase->tp_as_mapping == NULL)
1463 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001464 COPYMAP(mp_length);
1465 COPYMAP(mp_subscript);
1466 COPYMAP(mp_ass_subscript);
1467 }
1468
Guido van Rossum13d52f02001-08-10 21:24:08 +00001469 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470
Tim Peters6d6c1a32001-08-02 04:15:00 +00001471 COPYSLOT(tp_dealloc);
1472 COPYSLOT(tp_print);
1473 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1474 type->tp_getattr = base->tp_getattr;
1475 type->tp_getattro = base->tp_getattro;
1476 }
1477 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1478 type->tp_setattr = base->tp_setattr;
1479 type->tp_setattro = base->tp_setattro;
1480 }
1481 /* tp_compare see tp_richcompare */
1482 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001483 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484 COPYSLOT(tp_call);
1485 COPYSLOT(tp_str);
1486 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001487 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001488 if (type->tp_compare == NULL &&
1489 type->tp_richcompare == NULL &&
1490 type->tp_hash == NULL)
1491 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001492 type->tp_compare = base->tp_compare;
1493 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001494 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001495 }
1496 }
1497 else {
1498 COPYSLOT(tp_compare);
1499 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001500 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1501 COPYSLOT(tp_iter);
1502 COPYSLOT(tp_iternext);
1503 }
1504 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1505 COPYSLOT(tp_descr_get);
1506 COPYSLOT(tp_descr_set);
1507 COPYSLOT(tp_dictoffset);
1508 COPYSLOT(tp_init);
1509 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001510 COPYSLOT(tp_free);
1511 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001512}
1513
Guido van Rossum13d52f02001-08-10 21:24:08 +00001514staticforward int add_operators(PyTypeObject *);
1515
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001517PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001518{
1519 PyObject *dict, *bases, *x;
1520 PyTypeObject *base;
1521 int i, n;
1522
Guido van Rossumd614f972001-08-10 17:39:49 +00001523 if (type->tp_flags & Py_TPFLAGS_READY) {
1524 assert(type->tp_dict != NULL);
1525 return 0;
1526 }
1527 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1528 assert(type->tp_dict == NULL);
1529
1530 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531
1532 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1533 base = type->tp_base;
1534 if (base == NULL && type != &PyBaseObject_Type)
1535 base = type->tp_base = &PyBaseObject_Type;
1536
1537 /* Initialize tp_bases */
1538 bases = type->tp_bases;
1539 if (bases == NULL) {
1540 if (base == NULL)
1541 bases = PyTuple_New(0);
1542 else
1543 bases = Py_BuildValue("(O)", base);
1544 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001545 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001546 type->tp_bases = bases;
1547 }
1548
1549 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001550 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001551 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001552 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553 }
1554
1555 /* Initialize tp_defined */
1556 dict = type->tp_defined;
1557 if (dict == NULL) {
1558 dict = PyDict_New();
1559 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001560 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001561 type->tp_defined = dict;
1562 }
1563
1564 /* Add type-specific descriptors to tp_defined */
1565 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001566 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567 if (type->tp_methods != NULL) {
1568 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001569 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001570 }
1571 if (type->tp_members != NULL) {
1572 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001573 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574 }
1575 if (type->tp_getset != NULL) {
1576 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001577 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001578 }
1579
1580 /* Temporarily make tp_dict the same object as tp_defined.
1581 (This is needed to call mro(), and can stay this way for
1582 dynamic types). */
1583 Py_INCREF(type->tp_defined);
1584 type->tp_dict = type->tp_defined;
1585
1586 /* Calculate method resolution order */
1587 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001588 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589 }
1590
Guido van Rossum13d52f02001-08-10 21:24:08 +00001591 /* Inherit special flags from dominant base */
1592 if (type->tp_base != NULL)
1593 inherit_special(type, type->tp_base);
1594
Tim Peters6d6c1a32001-08-02 04:15:00 +00001595 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001596 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001597 /* For a dynamic type, all slots are overridden */
1598 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001599 }
1600 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001601 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001602 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001604 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001605 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001606 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001607 bases = type->tp_mro;
1608 assert(bases != NULL);
1609 assert(PyTuple_Check(bases));
1610 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001611 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001612 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1613 assert(PyType_Check(base));
1614 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001615 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001616 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001617 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001618 }
1619 }
1620
Guido van Rossum13d52f02001-08-10 21:24:08 +00001621 /* Some more special stuff */
1622 base = type->tp_base;
1623 if (base != NULL) {
1624 if (type->tp_as_number == NULL)
1625 type->tp_as_number = base->tp_as_number;
1626 if (type->tp_as_sequence == NULL)
1627 type->tp_as_sequence = base->tp_as_sequence;
1628 if (type->tp_as_mapping == NULL)
1629 type->tp_as_mapping = base->tp_as_mapping;
1630 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631
Guido van Rossum13d52f02001-08-10 21:24:08 +00001632 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001633 assert(type->tp_dict != NULL);
1634 type->tp_flags =
1635 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001636 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001637
1638 error:
1639 type->tp_flags &= ~Py_TPFLAGS_READYING;
1640 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001641}
1642
1643
1644/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1645
1646/* There's a wrapper *function* for each distinct function typedef used
1647 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1648 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1649 Most tables have only one entry; the tables for binary operators have two
1650 entries, one regular and one with reversed arguments. */
1651
1652static PyObject *
1653wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1654{
1655 inquiry func = (inquiry)wrapped;
1656 int res;
1657
1658 if (!PyArg_ParseTuple(args, ""))
1659 return NULL;
1660 res = (*func)(self);
1661 if (res == -1 && PyErr_Occurred())
1662 return NULL;
1663 return PyInt_FromLong((long)res);
1664}
1665
1666static struct wrapperbase tab_len[] = {
1667 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1668 {0}
1669};
1670
1671static PyObject *
1672wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1673{
1674 binaryfunc func = (binaryfunc)wrapped;
1675 PyObject *other;
1676
1677 if (!PyArg_ParseTuple(args, "O", &other))
1678 return NULL;
1679 return (*func)(self, other);
1680}
1681
1682static PyObject *
1683wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1684{
1685 binaryfunc func = (binaryfunc)wrapped;
1686 PyObject *other;
1687
1688 if (!PyArg_ParseTuple(args, "O", &other))
1689 return NULL;
1690 return (*func)(other, self);
1691}
1692
1693#undef BINARY
1694#define BINARY(NAME, OP) \
1695static struct wrapperbase tab_##NAME[] = { \
1696 {"__" #NAME "__", \
1697 (wrapperfunc)wrap_binaryfunc, \
1698 "x.__" #NAME "__(y) <==> " #OP}, \
1699 {"__r" #NAME "__", \
1700 (wrapperfunc)wrap_binaryfunc_r, \
1701 "y.__r" #NAME "__(x) <==> " #OP}, \
1702 {0} \
1703}
1704
1705BINARY(add, "x+y");
1706BINARY(sub, "x-y");
1707BINARY(mul, "x*y");
1708BINARY(div, "x/y");
1709BINARY(mod, "x%y");
1710BINARY(divmod, "divmod(x,y)");
1711BINARY(lshift, "x<<y");
1712BINARY(rshift, "x>>y");
1713BINARY(and, "x&y");
1714BINARY(xor, "x^y");
1715BINARY(or, "x|y");
1716
1717static PyObject *
1718wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1719{
1720 ternaryfunc func = (ternaryfunc)wrapped;
1721 PyObject *other;
1722 PyObject *third = Py_None;
1723
1724 /* Note: This wrapper only works for __pow__() */
1725
1726 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1727 return NULL;
1728 return (*func)(self, other, third);
1729}
1730
1731#undef TERNARY
1732#define TERNARY(NAME, OP) \
1733static struct wrapperbase tab_##NAME[] = { \
1734 {"__" #NAME "__", \
1735 (wrapperfunc)wrap_ternaryfunc, \
1736 "x.__" #NAME "__(y, z) <==> " #OP}, \
1737 {"__r" #NAME "__", \
1738 (wrapperfunc)wrap_ternaryfunc, \
1739 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1740 {0} \
1741}
1742
1743TERNARY(pow, "(x**y) % z");
1744
1745#undef UNARY
1746#define UNARY(NAME, OP) \
1747static struct wrapperbase tab_##NAME[] = { \
1748 {"__" #NAME "__", \
1749 (wrapperfunc)wrap_unaryfunc, \
1750 "x.__" #NAME "__() <==> " #OP}, \
1751 {0} \
1752}
1753
1754static PyObject *
1755wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1756{
1757 unaryfunc func = (unaryfunc)wrapped;
1758
1759 if (!PyArg_ParseTuple(args, ""))
1760 return NULL;
1761 return (*func)(self);
1762}
1763
1764UNARY(neg, "-x");
1765UNARY(pos, "+x");
1766UNARY(abs, "abs(x)");
1767UNARY(nonzero, "x != 0");
1768UNARY(invert, "~x");
1769UNARY(int, "int(x)");
1770UNARY(long, "long(x)");
1771UNARY(float, "float(x)");
1772UNARY(oct, "oct(x)");
1773UNARY(hex, "hex(x)");
1774
1775#undef IBINARY
1776#define IBINARY(NAME, OP) \
1777static struct wrapperbase tab_##NAME[] = { \
1778 {"__" #NAME "__", \
1779 (wrapperfunc)wrap_binaryfunc, \
1780 "x.__" #NAME "__(y) <==> " #OP}, \
1781 {0} \
1782}
1783
1784IBINARY(iadd, "x+=y");
1785IBINARY(isub, "x-=y");
1786IBINARY(imul, "x*=y");
1787IBINARY(idiv, "x/=y");
1788IBINARY(imod, "x%=y");
1789IBINARY(ilshift, "x<<=y");
1790IBINARY(irshift, "x>>=y");
1791IBINARY(iand, "x&=y");
1792IBINARY(ixor, "x^=y");
1793IBINARY(ior, "x|=y");
1794
1795#undef ITERNARY
1796#define ITERNARY(NAME, OP) \
1797static struct wrapperbase tab_##NAME[] = { \
1798 {"__" #NAME "__", \
1799 (wrapperfunc)wrap_ternaryfunc, \
1800 "x.__" #NAME "__(y) <==> " #OP}, \
1801 {0} \
1802}
1803
1804ITERNARY(ipow, "x = (x**y) % z");
1805
1806static struct wrapperbase tab_getitem[] = {
1807 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1808 "x.__getitem__(y) <==> x[y]"},
1809 {0}
1810};
1811
1812static PyObject *
1813wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1814{
1815 intargfunc func = (intargfunc)wrapped;
1816 int i;
1817
1818 if (!PyArg_ParseTuple(args, "i", &i))
1819 return NULL;
1820 return (*func)(self, i);
1821}
1822
1823static struct wrapperbase tab_mul_int[] = {
1824 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1825 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1826 {0}
1827};
1828
1829static struct wrapperbase tab_concat[] = {
1830 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1831 {0}
1832};
1833
1834static struct wrapperbase tab_imul_int[] = {
1835 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1836 {0}
1837};
1838
Guido van Rossum5d815f32001-08-17 21:57:47 +00001839static int
1840getindex(PyObject *self, PyObject *arg)
1841{
1842 int i;
1843
1844 i = PyInt_AsLong(arg);
1845 if (i == -1 && PyErr_Occurred())
1846 return -1;
1847 if (i < 0) {
1848 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
1849 if (sq && sq->sq_length) {
1850 int n = (*sq->sq_length)(self);
1851 if (n < 0)
1852 return -1;
1853 i += n;
1854 }
1855 }
1856 return i;
1857}
1858
1859static PyObject *
1860wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
1861{
1862 intargfunc func = (intargfunc)wrapped;
1863 PyObject *arg;
1864 int i;
1865
1866 if (!PyArg_ParseTuple(args, "O", &arg))
1867 return NULL;
1868 i = getindex(self, arg);
1869 if (i == -1 && PyErr_Occurred())
1870 return NULL;
1871 return (*func)(self, i);
1872}
1873
Tim Peters6d6c1a32001-08-02 04:15:00 +00001874static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001875 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001876 "x.__getitem__(i) <==> x[i]"},
1877 {0}
1878};
1879
1880static PyObject *
1881wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1882{
1883 intintargfunc func = (intintargfunc)wrapped;
1884 int i, j;
1885
1886 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1887 return NULL;
1888 return (*func)(self, i, j);
1889}
1890
1891static struct wrapperbase tab_getslice[] = {
1892 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1893 "x.__getslice__(i, j) <==> x[i:j]"},
1894 {0}
1895};
1896
1897static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001898wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001899{
1900 intobjargproc func = (intobjargproc)wrapped;
1901 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001902 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001903
Guido van Rossum5d815f32001-08-17 21:57:47 +00001904 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
1905 return NULL;
1906 i = getindex(self, arg);
1907 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00001908 return NULL;
1909 res = (*func)(self, i, value);
1910 if (res == -1 && PyErr_Occurred())
1911 return NULL;
1912 Py_INCREF(Py_None);
1913 return Py_None;
1914}
1915
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001916static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001917wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001918{
1919 intobjargproc func = (intobjargproc)wrapped;
1920 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001921 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001922
Guido van Rossum5d815f32001-08-17 21:57:47 +00001923 if (!PyArg_ParseTuple(args, "O", &arg))
1924 return NULL;
1925 i = getindex(self, arg);
1926 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001927 return NULL;
1928 res = (*func)(self, i, NULL);
1929 if (res == -1 && PyErr_Occurred())
1930 return NULL;
1931 Py_INCREF(Py_None);
1932 return Py_None;
1933}
1934
Tim Peters6d6c1a32001-08-02 04:15:00 +00001935static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001936 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001937 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00001938 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001939 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940 {0}
1941};
1942
1943static PyObject *
1944wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1945{
1946 intintobjargproc func = (intintobjargproc)wrapped;
1947 int i, j, res;
1948 PyObject *value;
1949
1950 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1951 return NULL;
1952 res = (*func)(self, i, j, value);
1953 if (res == -1 && PyErr_Occurred())
1954 return NULL;
1955 Py_INCREF(Py_None);
1956 return Py_None;
1957}
1958
1959static struct wrapperbase tab_setslice[] = {
1960 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1961 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1962 {0}
1963};
1964
1965/* XXX objobjproc is a misnomer; should be objargpred */
1966static PyObject *
1967wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1968{
1969 objobjproc func = (objobjproc)wrapped;
1970 int res;
1971 PyObject *value;
1972
1973 if (!PyArg_ParseTuple(args, "O", &value))
1974 return NULL;
1975 res = (*func)(self, value);
1976 if (res == -1 && PyErr_Occurred())
1977 return NULL;
1978 return PyInt_FromLong((long)res);
1979}
1980
1981static struct wrapperbase tab_contains[] = {
1982 {"__contains__", (wrapperfunc)wrap_objobjproc,
1983 "x.__contains__(y) <==> y in x"},
1984 {0}
1985};
1986
1987static PyObject *
1988wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1989{
1990 objobjargproc func = (objobjargproc)wrapped;
1991 int res;
1992 PyObject *key, *value;
1993
1994 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1995 return NULL;
1996 res = (*func)(self, key, value);
1997 if (res == -1 && PyErr_Occurred())
1998 return NULL;
1999 Py_INCREF(Py_None);
2000 return Py_None;
2001}
2002
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002003static PyObject *
2004wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2005{
2006 objobjargproc func = (objobjargproc)wrapped;
2007 int res;
2008 PyObject *key;
2009
2010 if (!PyArg_ParseTuple(args, "O", &key))
2011 return NULL;
2012 res = (*func)(self, key, NULL);
2013 if (res == -1 && PyErr_Occurred())
2014 return NULL;
2015 Py_INCREF(Py_None);
2016 return Py_None;
2017}
2018
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019static struct wrapperbase tab_setitem[] = {
2020 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2021 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002022 {"__delitem__", (wrapperfunc)wrap_delitem,
2023 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002024 {0}
2025};
2026
2027static PyObject *
2028wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2029{
2030 cmpfunc func = (cmpfunc)wrapped;
2031 int res;
2032 PyObject *other;
2033
2034 if (!PyArg_ParseTuple(args, "O", &other))
2035 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002036 if (other->ob_type->tp_compare != func &&
2037 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002038 PyErr_Format(
2039 PyExc_TypeError,
2040 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2041 self->ob_type->tp_name,
2042 self->ob_type->tp_name,
2043 other->ob_type->tp_name);
2044 return NULL;
2045 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046 res = (*func)(self, other);
2047 if (PyErr_Occurred())
2048 return NULL;
2049 return PyInt_FromLong((long)res);
2050}
2051
2052static struct wrapperbase tab_cmp[] = {
2053 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2054 "x.__cmp__(y) <==> cmp(x,y)"},
2055 {0}
2056};
2057
2058static struct wrapperbase tab_repr[] = {
2059 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2060 "x.__repr__() <==> repr(x)"},
2061 {0}
2062};
2063
2064static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002065 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2066 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067 {0}
2068};
2069
2070static PyObject *
2071wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2072{
2073 setattrofunc func = (setattrofunc)wrapped;
2074 int res;
2075 PyObject *name, *value;
2076
2077 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2078 return NULL;
2079 res = (*func)(self, name, value);
2080 if (res < 0)
2081 return NULL;
2082 Py_INCREF(Py_None);
2083 return Py_None;
2084}
2085
2086static PyObject *
2087wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2088{
2089 setattrofunc func = (setattrofunc)wrapped;
2090 int res;
2091 PyObject *name;
2092
2093 if (!PyArg_ParseTuple(args, "O", &name))
2094 return NULL;
2095 res = (*func)(self, name, NULL);
2096 if (res < 0)
2097 return NULL;
2098 Py_INCREF(Py_None);
2099 return Py_None;
2100}
2101
2102static struct wrapperbase tab_setattr[] = {
2103 {"__setattr__", (wrapperfunc)wrap_setattr,
2104 "x.__setattr__('name', value) <==> x.name = value"},
2105 {"__delattr__", (wrapperfunc)wrap_delattr,
2106 "x.__delattr__('name') <==> del x.name"},
2107 {0}
2108};
2109
2110static PyObject *
2111wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2112{
2113 hashfunc func = (hashfunc)wrapped;
2114 long res;
2115
2116 if (!PyArg_ParseTuple(args, ""))
2117 return NULL;
2118 res = (*func)(self);
2119 if (res == -1 && PyErr_Occurred())
2120 return NULL;
2121 return PyInt_FromLong(res);
2122}
2123
2124static struct wrapperbase tab_hash[] = {
2125 {"__hash__", (wrapperfunc)wrap_hashfunc,
2126 "x.__hash__() <==> hash(x)"},
2127 {0}
2128};
2129
2130static PyObject *
2131wrap_call(PyObject *self, PyObject *args, void *wrapped)
2132{
2133 ternaryfunc func = (ternaryfunc)wrapped;
2134
2135 /* XXX What about keyword arguments? */
2136 return (*func)(self, args, NULL);
2137}
2138
2139static struct wrapperbase tab_call[] = {
2140 {"__call__", (wrapperfunc)wrap_call,
2141 "x.__call__(...) <==> x(...)"},
2142 {0}
2143};
2144
2145static struct wrapperbase tab_str[] = {
2146 {"__str__", (wrapperfunc)wrap_unaryfunc,
2147 "x.__str__() <==> str(x)"},
2148 {0}
2149};
2150
2151static PyObject *
2152wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2153{
2154 richcmpfunc func = (richcmpfunc)wrapped;
2155 PyObject *other;
2156
2157 if (!PyArg_ParseTuple(args, "O", &other))
2158 return NULL;
2159 return (*func)(self, other, op);
2160}
2161
2162#undef RICHCMP_WRAPPER
2163#define RICHCMP_WRAPPER(NAME, OP) \
2164static PyObject * \
2165richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2166{ \
2167 return wrap_richcmpfunc(self, args, wrapped, OP); \
2168}
2169
Jack Jansen8e938b42001-08-08 15:29:49 +00002170RICHCMP_WRAPPER(lt, Py_LT)
2171RICHCMP_WRAPPER(le, Py_LE)
2172RICHCMP_WRAPPER(eq, Py_EQ)
2173RICHCMP_WRAPPER(ne, Py_NE)
2174RICHCMP_WRAPPER(gt, Py_GT)
2175RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176
2177#undef RICHCMP_ENTRY
2178#define RICHCMP_ENTRY(NAME, EXPR) \
2179 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2180 "x.__" #NAME "__(y) <==> " EXPR}
2181
2182static struct wrapperbase tab_richcmp[] = {
2183 RICHCMP_ENTRY(lt, "x<y"),
2184 RICHCMP_ENTRY(le, "x<=y"),
2185 RICHCMP_ENTRY(eq, "x==y"),
2186 RICHCMP_ENTRY(ne, "x!=y"),
2187 RICHCMP_ENTRY(gt, "x>y"),
2188 RICHCMP_ENTRY(ge, "x>=y"),
2189 {0}
2190};
2191
2192static struct wrapperbase tab_iter[] = {
2193 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2194 {0}
2195};
2196
2197static PyObject *
2198wrap_next(PyObject *self, PyObject *args, void *wrapped)
2199{
2200 unaryfunc func = (unaryfunc)wrapped;
2201 PyObject *res;
2202
2203 if (!PyArg_ParseTuple(args, ""))
2204 return NULL;
2205 res = (*func)(self);
2206 if (res == NULL && !PyErr_Occurred())
2207 PyErr_SetNone(PyExc_StopIteration);
2208 return res;
2209}
2210
2211static struct wrapperbase tab_next[] = {
2212 {"next", (wrapperfunc)wrap_next,
2213 "x.next() -> the next value, or raise StopIteration"},
2214 {0}
2215};
2216
2217static PyObject *
2218wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2219{
2220 descrgetfunc func = (descrgetfunc)wrapped;
2221 PyObject *obj;
2222 PyObject *type = NULL;
2223
2224 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2225 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002226 return (*func)(self, obj, type);
2227}
2228
2229static struct wrapperbase tab_descr_get[] = {
2230 {"__get__", (wrapperfunc)wrap_descr_get,
2231 "descr.__get__(obj, type) -> value"},
2232 {0}
2233};
2234
2235static PyObject *
2236wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2237{
2238 descrsetfunc func = (descrsetfunc)wrapped;
2239 PyObject *obj, *value;
2240 int ret;
2241
2242 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2243 return NULL;
2244 ret = (*func)(self, obj, value);
2245 if (ret < 0)
2246 return NULL;
2247 Py_INCREF(Py_None);
2248 return Py_None;
2249}
2250
2251static struct wrapperbase tab_descr_set[] = {
2252 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2253 "descr.__set__(obj, value)"},
2254 {0}
2255};
2256
2257static PyObject *
2258wrap_init(PyObject *self, PyObject *args, void *wrapped)
2259{
2260 initproc func = (initproc)wrapped;
2261
2262 /* XXX What about keyword arguments? */
2263 if (func(self, args, NULL) < 0)
2264 return NULL;
2265 Py_INCREF(Py_None);
2266 return Py_None;
2267}
2268
2269static struct wrapperbase tab_init[] = {
2270 {"__init__", (wrapperfunc)wrap_init,
2271 "x.__init__(...) initializes x; "
2272 "see x.__type__.__doc__ for signature"},
2273 {0}
2274};
2275
2276static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002277tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002278{
Barry Warsaw60f01882001-08-22 19:24:42 +00002279 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002280 PyObject *arg0, *res;
2281
2282 if (self == NULL || !PyType_Check(self))
2283 Py_FatalError("__new__() called with non-type 'self'");
2284 type = (PyTypeObject *)self;
2285 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002286 PyErr_Format(PyExc_TypeError,
2287 "%s.__new__(): not enough arguments",
2288 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002289 return NULL;
2290 }
2291 arg0 = PyTuple_GET_ITEM(args, 0);
2292 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002293 PyErr_Format(PyExc_TypeError,
2294 "%s.__new__(X): X is not a type object (%s)",
2295 type->tp_name,
2296 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002297 return NULL;
2298 }
2299 subtype = (PyTypeObject *)arg0;
2300 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002301 PyErr_Format(PyExc_TypeError,
2302 "%s.__new__(%s): %s is not a subtype of %s",
2303 type->tp_name,
2304 subtype->tp_name,
2305 subtype->tp_name,
2306 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002307 return NULL;
2308 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002309
2310 /* Check that the use doesn't do something silly and unsafe like
2311 object.__new__(dictionary). To do this, we check that the
2312 most derived base that's not a heap type is this type. */
2313 staticbase = subtype;
2314 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2315 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002316 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002317 PyErr_Format(PyExc_TypeError,
2318 "%s.__new__(%s) is not safe, use %s.__new__()",
2319 type->tp_name,
2320 subtype->tp_name,
2321 staticbase == NULL ? "?" : staticbase->tp_name);
2322 return NULL;
2323 }
2324
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002325 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2326 if (args == NULL)
2327 return NULL;
2328 res = type->tp_new(subtype, args, kwds);
2329 Py_DECREF(args);
2330 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002331}
2332
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002333static struct PyMethodDef tp_new_methoddef[] = {
2334 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2335 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002336 {0}
2337};
2338
2339static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002340add_tp_new_wrapper(PyTypeObject *type)
2341{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002342 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002343
Guido van Rossumf040ede2001-08-07 16:40:56 +00002344 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2345 return 0;
2346 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002347 if (func == NULL)
2348 return -1;
2349 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2350}
2351
Guido van Rossum13d52f02001-08-10 21:24:08 +00002352static int
2353add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2354{
2355 PyObject *dict = type->tp_defined;
2356
2357 for (; wraps->name != NULL; wraps++) {
2358 PyObject *descr;
2359 if (PyDict_GetItemString(dict, wraps->name))
2360 continue;
2361 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2362 if (descr == NULL)
2363 return -1;
2364 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2365 return -1;
2366 Py_DECREF(descr);
2367 }
2368 return 0;
2369}
2370
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002371/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002372 dictionary with method descriptors for function slots. For each
2373 function slot (like tp_repr) that's defined in the type, one or
2374 more corresponding descriptors are added in the type's tp_defined
2375 dictionary under the appropriate name (like __repr__). Some
2376 function slots cause more than one descriptor to be added (for
2377 example, the nb_add slot adds both __add__ and __radd__
2378 descriptors) and some function slots compete for the same
2379 descriptor (for example both sq_item and mp_subscript generate a
2380 __getitem__ descriptor). This only adds new descriptors and
2381 doesn't overwrite entries in tp_defined that were previously
2382 defined. The descriptors contain a reference to the C function
2383 they must call, so that it's safe if they are copied into a
2384 subtype's __dict__ and the subtype has a different C function in
2385 its slot -- calling the method defined by the descriptor will call
2386 the C function that was used to create it, rather than the C
2387 function present in the slot when it is called. (This is important
2388 because a subtype may have a C function in the slot that calls the
2389 method from the dictionary, and we want to avoid infinite recursion
2390 here.) */
2391
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002392static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002393add_operators(PyTypeObject *type)
2394{
2395 PySequenceMethods *sq;
2396 PyMappingMethods *mp;
2397 PyNumberMethods *nb;
2398
2399#undef ADD
2400#define ADD(SLOT, TABLE) \
2401 if (SLOT) { \
2402 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2403 return -1; \
2404 }
2405
2406 if ((sq = type->tp_as_sequence) != NULL) {
2407 ADD(sq->sq_length, tab_len);
2408 ADD(sq->sq_concat, tab_concat);
2409 ADD(sq->sq_repeat, tab_mul_int);
2410 ADD(sq->sq_item, tab_getitem_int);
2411 ADD(sq->sq_slice, tab_getslice);
2412 ADD(sq->sq_ass_item, tab_setitem_int);
2413 ADD(sq->sq_ass_slice, tab_setslice);
2414 ADD(sq->sq_contains, tab_contains);
2415 ADD(sq->sq_inplace_concat, tab_iadd);
2416 ADD(sq->sq_inplace_repeat, tab_imul_int);
2417 }
2418
2419 if ((mp = type->tp_as_mapping) != NULL) {
2420 if (sq->sq_length == NULL)
2421 ADD(mp->mp_length, tab_len);
2422 ADD(mp->mp_subscript, tab_getitem);
2423 ADD(mp->mp_ass_subscript, tab_setitem);
2424 }
2425
2426 /* We don't support "old-style numbers" because their binary
2427 operators require that both arguments have the same type;
2428 the wrappers here only work for new-style numbers. */
2429 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2430 (nb = type->tp_as_number) != NULL) {
2431 ADD(nb->nb_add, tab_add);
2432 ADD(nb->nb_subtract, tab_sub);
2433 ADD(nb->nb_multiply, tab_mul);
2434 ADD(nb->nb_divide, tab_div);
2435 ADD(nb->nb_remainder, tab_mod);
2436 ADD(nb->nb_divmod, tab_divmod);
2437 ADD(nb->nb_power, tab_pow);
2438 ADD(nb->nb_negative, tab_neg);
2439 ADD(nb->nb_positive, tab_pos);
2440 ADD(nb->nb_absolute, tab_abs);
2441 ADD(nb->nb_nonzero, tab_nonzero);
2442 ADD(nb->nb_invert, tab_invert);
2443 ADD(nb->nb_lshift, tab_lshift);
2444 ADD(nb->nb_rshift, tab_rshift);
2445 ADD(nb->nb_and, tab_and);
2446 ADD(nb->nb_xor, tab_xor);
2447 ADD(nb->nb_or, tab_or);
2448 /* We don't support coerce() -- see above comment */
2449 ADD(nb->nb_int, tab_int);
2450 ADD(nb->nb_long, tab_long);
2451 ADD(nb->nb_float, tab_float);
2452 ADD(nb->nb_oct, tab_oct);
2453 ADD(nb->nb_hex, tab_hex);
2454 ADD(nb->nb_inplace_add, tab_iadd);
2455 ADD(nb->nb_inplace_subtract, tab_isub);
2456 ADD(nb->nb_inplace_multiply, tab_imul);
2457 ADD(nb->nb_inplace_divide, tab_idiv);
2458 ADD(nb->nb_inplace_remainder, tab_imod);
2459 ADD(nb->nb_inplace_power, tab_ipow);
2460 ADD(nb->nb_inplace_lshift, tab_ilshift);
2461 ADD(nb->nb_inplace_rshift, tab_irshift);
2462 ADD(nb->nb_inplace_and, tab_iand);
2463 ADD(nb->nb_inplace_xor, tab_ixor);
2464 ADD(nb->nb_inplace_or, tab_ior);
2465 }
2466
2467 ADD(type->tp_getattro, tab_getattr);
2468 ADD(type->tp_setattro, tab_setattr);
2469 ADD(type->tp_compare, tab_cmp);
2470 ADD(type->tp_repr, tab_repr);
2471 ADD(type->tp_hash, tab_hash);
2472 ADD(type->tp_call, tab_call);
2473 ADD(type->tp_str, tab_str);
2474 ADD(type->tp_richcompare, tab_richcmp);
2475 ADD(type->tp_iter, tab_iter);
2476 ADD(type->tp_iternext, tab_next);
2477 ADD(type->tp_descr_get, tab_descr_get);
2478 ADD(type->tp_descr_set, tab_descr_set);
2479 ADD(type->tp_init, tab_init);
2480
Guido van Rossumf040ede2001-08-07 16:40:56 +00002481 if (type->tp_new != NULL) {
2482 if (add_tp_new_wrapper(type) < 0)
2483 return -1;
2484 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002485
2486 return 0;
2487}
2488
Guido van Rossumf040ede2001-08-07 16:40:56 +00002489/* Slot wrappers that call the corresponding __foo__ slot. See comments
2490 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002491
Guido van Rossumdc91b992001-08-08 22:26:22 +00002492#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002493static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002494FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002495{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002496 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002497 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002498}
2499
Guido van Rossumdc91b992001-08-08 22:26:22 +00002500#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002501static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002502FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002503{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002504 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002505 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002506}
2507
Guido van Rossumdc91b992001-08-08 22:26:22 +00002508
2509#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002510static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002511FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002512{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002513 static PyObject *cache_str, *rcache_str; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002514 if (self->ob_type->tp_as_number != NULL && \
2515 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2516 PyObject *r; \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002517 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002518 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002519 if (r != Py_NotImplemented || \
2520 other->ob_type == self->ob_type) \
2521 return r; \
2522 Py_DECREF(r); \
2523 } \
2524 if (other->ob_type->tp_as_number != NULL && \
2525 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002526 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002527 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002528 } \
2529 Py_INCREF(Py_NotImplemented); \
2530 return Py_NotImplemented; \
2531}
2532
2533#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2534 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2535
2536#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2537static PyObject * \
2538FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2539{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002540 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002541 return call_method(self, OPSTR, &cache_str, \
2542 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002543}
2544
2545static int
2546slot_sq_length(PyObject *self)
2547{
Guido van Rossum2730b132001-08-28 18:22:14 +00002548 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002549 PyObject *res = call_method(self, "__len__", &len_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002550
2551 if (res == NULL)
2552 return -1;
2553 return (int)PyInt_AsLong(res);
2554}
2555
Guido van Rossumdc91b992001-08-08 22:26:22 +00002556SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2557SLOT1(slot_sq_repeat, "__mul__", int, "i")
2558SLOT1(slot_sq_item, "__getitem__", int, "i")
2559SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002560
2561static int
2562slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2563{
2564 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002565 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002566
2567 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002568 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002569 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002570 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002571 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002572 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002573 if (res == NULL)
2574 return -1;
2575 Py_DECREF(res);
2576 return 0;
2577}
2578
2579static int
2580slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2581{
2582 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002583 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002584
2585 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002586 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002587 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002588 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002589 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002590 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002591 if (res == NULL)
2592 return -1;
2593 Py_DECREF(res);
2594 return 0;
2595}
2596
2597static int
2598slot_sq_contains(PyObject *self, PyObject *value)
2599{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002600 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002601 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002602
Guido van Rossum60718732001-08-28 17:47:51 +00002603 func = lookup_method(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002604
2605 if (func != NULL) {
2606 args = Py_BuildValue("(O)", value);
2607 if (args == NULL)
2608 res = NULL;
2609 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002610 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002611 Py_DECREF(args);
2612 }
2613 Py_DECREF(func);
2614 if (res == NULL)
2615 return -1;
2616 return PyObject_IsTrue(res);
2617 }
2618 else {
2619 PyErr_Clear();
Tim Peters16a77ad2001-09-08 04:00:12 +00002620 return _PySequence_IterSearch(self, value,
2621 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002622 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002623}
2624
Guido van Rossumdc91b992001-08-08 22:26:22 +00002625SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2626SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002627
2628#define slot_mp_length slot_sq_length
2629
Guido van Rossumdc91b992001-08-08 22:26:22 +00002630SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002631
2632static int
2633slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2634{
2635 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002636 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002637
2638 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002639 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002640 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002641 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002642 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002643 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002644 if (res == NULL)
2645 return -1;
2646 Py_DECREF(res);
2647 return 0;
2648}
2649
Guido van Rossumdc91b992001-08-08 22:26:22 +00002650SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2651SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2652SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2653SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2654SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2655SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2656
2657staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2658
2659SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2660 nb_power, "__pow__", "__rpow__")
2661
2662static PyObject *
2663slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2664{
Guido van Rossum2730b132001-08-28 18:22:14 +00002665 static PyObject *pow_str;
2666
Guido van Rossumdc91b992001-08-08 22:26:22 +00002667 if (modulus == Py_None)
2668 return slot_nb_power_binary(self, other);
2669 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002670 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002671 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002672}
2673
2674SLOT0(slot_nb_negative, "__neg__")
2675SLOT0(slot_nb_positive, "__pos__")
2676SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002677
2678static int
2679slot_nb_nonzero(PyObject *self)
2680{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002681 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002682 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002683
Guido van Rossum60718732001-08-28 17:47:51 +00002684 func = lookup_method(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002685 if (func == NULL) {
2686 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002687 func = lookup_method(self, "__len__", &len_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002688 }
2689
2690 if (func != NULL) {
Guido van Rossum717ce002001-09-14 16:58:08 +00002691 res = PyObject_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002692 Py_DECREF(func);
2693 if (res == NULL)
2694 return -1;
2695 return PyObject_IsTrue(res);
2696 }
2697 else {
2698 PyErr_Clear();
2699 return 1;
2700 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002701}
2702
Guido van Rossumdc91b992001-08-08 22:26:22 +00002703SLOT0(slot_nb_invert, "__invert__")
2704SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2705SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2706SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2707SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2708SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002709/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002710SLOT0(slot_nb_int, "__int__")
2711SLOT0(slot_nb_long, "__long__")
2712SLOT0(slot_nb_float, "__float__")
2713SLOT0(slot_nb_oct, "__oct__")
2714SLOT0(slot_nb_hex, "__hex__")
2715SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2716SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2717SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2718SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2719SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2720SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2721SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2722SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2723SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2724SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2725SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2726SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2727 "__floordiv__", "__rfloordiv__")
2728SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2729SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2730SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731
2732static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002733half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002734{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002735 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002736 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002737 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002738
Guido van Rossum60718732001-08-28 17:47:51 +00002739 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002740 if (func == NULL) {
2741 PyErr_Clear();
2742 }
2743 else {
2744 args = Py_BuildValue("(O)", other);
2745 if (args == NULL)
2746 res = NULL;
2747 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002748 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002749 Py_DECREF(args);
2750 }
2751 if (res != Py_NotImplemented) {
2752 if (res == NULL)
2753 return -2;
2754 c = PyInt_AsLong(res);
2755 Py_DECREF(res);
2756 if (c == -1 && PyErr_Occurred())
2757 return -2;
2758 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2759 }
2760 Py_DECREF(res);
2761 }
2762 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002763}
2764
Guido van Rossumab3b0342001-09-18 20:38:53 +00002765/* This slot is published for the benefit of try_3way_compare in object.c */
2766int
2767_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00002768{
2769 int c;
2770
Guido van Rossumab3b0342001-09-18 20:38:53 +00002771 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002772 c = half_compare(self, other);
2773 if (c <= 1)
2774 return c;
2775 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00002776 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002777 c = half_compare(other, self);
2778 if (c < -1)
2779 return -2;
2780 if (c <= 1)
2781 return -c;
2782 }
2783 return (void *)self < (void *)other ? -1 :
2784 (void *)self > (void *)other ? 1 : 0;
2785}
2786
2787static PyObject *
2788slot_tp_repr(PyObject *self)
2789{
2790 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002791 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002792
Guido van Rossum60718732001-08-28 17:47:51 +00002793 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002794 if (func != NULL) {
2795 res = PyEval_CallObject(func, NULL);
2796 Py_DECREF(func);
2797 return res;
2798 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00002799 PyErr_Clear();
2800 return PyString_FromFormat("<%s object at %p>",
2801 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002802}
2803
2804static PyObject *
2805slot_tp_str(PyObject *self)
2806{
2807 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002808 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002809
Guido van Rossum60718732001-08-28 17:47:51 +00002810 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002811 if (func != NULL) {
2812 res = PyEval_CallObject(func, NULL);
2813 Py_DECREF(func);
2814 return res;
2815 }
2816 else {
2817 PyErr_Clear();
2818 return slot_tp_repr(self);
2819 }
2820}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002821
2822static long
2823slot_tp_hash(PyObject *self)
2824{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002825 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002826 static PyObject *hash_str, *eq_str, *cmp_str;
2827
Tim Peters6d6c1a32001-08-02 04:15:00 +00002828 long h;
2829
Guido van Rossum60718732001-08-28 17:47:51 +00002830 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002831
2832 if (func != NULL) {
2833 res = PyEval_CallObject(func, NULL);
2834 Py_DECREF(func);
2835 if (res == NULL)
2836 return -1;
2837 h = PyInt_AsLong(res);
2838 }
2839 else {
2840 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002841 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002842 if (func == NULL) {
2843 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002844 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002845 }
2846 if (func != NULL) {
2847 Py_DECREF(func);
2848 PyErr_SetString(PyExc_TypeError, "unhashable type");
2849 return -1;
2850 }
2851 PyErr_Clear();
2852 h = _Py_HashPointer((void *)self);
2853 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002854 if (h == -1 && !PyErr_Occurred())
2855 h = -2;
2856 return h;
2857}
2858
2859static PyObject *
2860slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2861{
Guido van Rossum60718732001-08-28 17:47:51 +00002862 static PyObject *call_str;
2863 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002864 PyObject *res;
2865
2866 if (meth == NULL)
2867 return NULL;
2868 res = PyObject_Call(meth, args, kwds);
2869 Py_DECREF(meth);
2870 return res;
2871}
2872
Tim Peters6d6c1a32001-08-02 04:15:00 +00002873static PyObject *
2874slot_tp_getattro(PyObject *self, PyObject *name)
2875{
2876 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002877 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002878 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002879
Guido van Rossum8e248182001-08-12 05:17:56 +00002880 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002881 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00002882 if (getattr_str == NULL)
2883 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002884 }
Guido van Rossum8e248182001-08-12 05:17:56 +00002885 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00002886 if (getattr == NULL) {
2887 /* Avoid further slowdowns */
2888 if (tp->tp_getattro == slot_tp_getattro)
2889 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002890 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00002891 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002892 return PyObject_CallFunction(getattr, "OO", self, name);
2893}
2894
Guido van Rossum19c1cd52001-09-21 21:24:49 +00002895static PyObject *
2896slot_tp_getattr_hook(PyObject *self, PyObject *name)
2897{
2898 PyTypeObject *tp = self->ob_type;
2899 PyObject *getattr, *getattribute, *res;
2900 static PyObject *getattribute_str = NULL;
2901 static PyObject *getattr_str = NULL;
2902
2903 if (getattr_str == NULL) {
2904 getattr_str = PyString_InternFromString("__getattr__");
2905 if (getattr_str == NULL)
2906 return NULL;
2907 }
2908 if (getattribute_str == NULL) {
2909 getattribute_str =
2910 PyString_InternFromString("__getattribute__");
2911 if (getattribute_str == NULL)
2912 return NULL;
2913 }
2914 getattr = _PyType_Lookup(tp, getattr_str);
2915 getattribute = _PyType_Lookup(tp, getattribute_str);
2916 if (getattr == NULL && getattribute == NULL) {
2917 /* Avoid further slowdowns */
2918 if (tp->tp_getattro == slot_tp_getattr_hook)
2919 tp->tp_getattro = PyObject_GenericGetAttr;
2920 return PyObject_GenericGetAttr(self, name);
2921 }
2922 if (getattribute == NULL)
2923 res = PyObject_GenericGetAttr(self, name);
2924 else
2925 res = PyObject_CallFunction(getattribute, "OO", self, name);
2926 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
2927 PyErr_Clear();
2928 res = PyObject_CallFunction(getattr, "OO", self, name);
2929 }
2930 return res;
2931}
2932
Tim Peters6d6c1a32001-08-02 04:15:00 +00002933static int
2934slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2935{
2936 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002937 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002938
2939 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002940 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002941 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002942 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002943 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002944 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002945 if (res == NULL)
2946 return -1;
2947 Py_DECREF(res);
2948 return 0;
2949}
2950
2951/* Map rich comparison operators to their __xx__ namesakes */
2952static char *name_op[] = {
2953 "__lt__",
2954 "__le__",
2955 "__eq__",
2956 "__ne__",
2957 "__gt__",
2958 "__ge__",
2959};
2960
2961static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00002962half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002963{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002964 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002965 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00002966
Guido van Rossum60718732001-08-28 17:47:51 +00002967 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002968 if (func == NULL) {
2969 PyErr_Clear();
2970 Py_INCREF(Py_NotImplemented);
2971 return Py_NotImplemented;
2972 }
2973 args = Py_BuildValue("(O)", other);
2974 if (args == NULL)
2975 res = NULL;
2976 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002977 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002978 Py_DECREF(args);
2979 }
2980 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002981 return res;
2982}
2983
Guido van Rossumb8f63662001-08-15 23:57:02 +00002984/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
2985static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
2986
2987static PyObject *
2988slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2989{
2990 PyObject *res;
2991
2992 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
2993 res = half_richcompare(self, other, op);
2994 if (res != Py_NotImplemented)
2995 return res;
2996 Py_DECREF(res);
2997 }
2998 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
2999 res = half_richcompare(other, self, swapped_op[op]);
3000 if (res != Py_NotImplemented) {
3001 return res;
3002 }
3003 Py_DECREF(res);
3004 }
3005 Py_INCREF(Py_NotImplemented);
3006 return Py_NotImplemented;
3007}
3008
3009static PyObject *
3010slot_tp_iter(PyObject *self)
3011{
3012 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003013 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003014
Guido van Rossum60718732001-08-28 17:47:51 +00003015 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003016 if (func != NULL) {
3017 res = PyObject_CallObject(func, NULL);
3018 Py_DECREF(func);
3019 return res;
3020 }
3021 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003022 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003023 if (func == NULL) {
3024 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
3025 return NULL;
3026 }
3027 Py_DECREF(func);
3028 return PySeqIter_New(self);
3029}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030
3031static PyObject *
3032slot_tp_iternext(PyObject *self)
3033{
Guido van Rossum2730b132001-08-28 18:22:14 +00003034 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003035 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003036}
3037
Guido van Rossum1a493502001-08-17 16:47:50 +00003038static PyObject *
3039slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3040{
3041 PyTypeObject *tp = self->ob_type;
3042 PyObject *get;
3043 static PyObject *get_str = NULL;
3044
3045 if (get_str == NULL) {
3046 get_str = PyString_InternFromString("__get__");
3047 if (get_str == NULL)
3048 return NULL;
3049 }
3050 get = _PyType_Lookup(tp, get_str);
3051 if (get == NULL) {
3052 /* Avoid further slowdowns */
3053 if (tp->tp_descr_get == slot_tp_descr_get)
3054 tp->tp_descr_get = NULL;
3055 Py_INCREF(self);
3056 return self;
3057 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003058 if (obj == NULL)
3059 obj = Py_None;
3060 if (type == NULL)
3061 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003062 return PyObject_CallFunction(get, "OOO", self, obj, type);
3063}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003064
3065static int
3066slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3067{
Guido van Rossum2c252392001-08-24 10:13:31 +00003068 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003069 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003070
3071 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003072 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003073 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003074 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003075 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003076 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003077 if (res == NULL)
3078 return -1;
3079 Py_DECREF(res);
3080 return 0;
3081}
3082
3083static int
3084slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3085{
Guido van Rossum60718732001-08-28 17:47:51 +00003086 static PyObject *init_str;
3087 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003088 PyObject *res;
3089
3090 if (meth == NULL)
3091 return -1;
3092 res = PyObject_Call(meth, args, kwds);
3093 Py_DECREF(meth);
3094 if (res == NULL)
3095 return -1;
3096 Py_DECREF(res);
3097 return 0;
3098}
3099
3100static PyObject *
3101slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3102{
3103 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3104 PyObject *newargs, *x;
3105 int i, n;
3106
3107 if (func == NULL)
3108 return NULL;
3109 assert(PyTuple_Check(args));
3110 n = PyTuple_GET_SIZE(args);
3111 newargs = PyTuple_New(n+1);
3112 if (newargs == NULL)
3113 return NULL;
3114 Py_INCREF(type);
3115 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3116 for (i = 0; i < n; i++) {
3117 x = PyTuple_GET_ITEM(args, i);
3118 Py_INCREF(x);
3119 PyTuple_SET_ITEM(newargs, i+1, x);
3120 }
3121 x = PyObject_Call(func, newargs, kwds);
3122 Py_DECREF(func);
3123 return x;
3124}
3125
Guido van Rossumf040ede2001-08-07 16:40:56 +00003126/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003127 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003128 The dict argument is the dictionary argument passed to type_new(),
3129 which is the local namespace of the class statement, in other
3130 words, it contains the methods. For each special method (like
3131 __repr__) defined in the dictionary, the corresponding function
3132 slot in the type object (like tp_repr) is set to a special function
3133 whose name is 'slot_' followed by the slot name and whose signature
3134 is whatever is required for that slot. These slot functions look
3135 up the corresponding method in the type's dictionary and call it.
3136 The slot functions have to take care of the various peculiarities
3137 of the mapping between slots and special methods, such as mapping
3138 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3139 etc.) or mapping multiple slots to a single method (sq_item,
3140 mp_subscript <--> __getitem__). */
3141
Tim Peters6d6c1a32001-08-02 04:15:00 +00003142static void
3143override_slots(PyTypeObject *type, PyObject *dict)
3144{
3145 PySequenceMethods *sq = type->tp_as_sequence;
3146 PyMappingMethods *mp = type->tp_as_mapping;
3147 PyNumberMethods *nb = type->tp_as_number;
3148
Guido van Rossumdc91b992001-08-08 22:26:22 +00003149#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003150 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003151 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152 }
3153
Guido van Rossumdc91b992001-08-08 22:26:22 +00003154#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003155 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003156 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003157 }
3158
Guido van Rossumdc91b992001-08-08 22:26:22 +00003159#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003160 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003161 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003162 }
3163
Guido van Rossumdc91b992001-08-08 22:26:22 +00003164#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003165 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003166 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003167 }
3168
Guido van Rossumdc91b992001-08-08 22:26:22 +00003169 SQSLOT("__len__", sq_length, slot_sq_length);
3170 SQSLOT("__add__", sq_concat, slot_sq_concat);
3171 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3172 SQSLOT("__getitem__", sq_item, slot_sq_item);
3173 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3174 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3175 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3176 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3177 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3178 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3179 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3180 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181
Guido van Rossumdc91b992001-08-08 22:26:22 +00003182 MPSLOT("__len__", mp_length, slot_mp_length);
3183 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3184 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3185 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003186
Guido van Rossumdc91b992001-08-08 22:26:22 +00003187 NBSLOT("__add__", nb_add, slot_nb_add);
3188 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3189 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3190 NBSLOT("__div__", nb_divide, slot_nb_divide);
3191 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3192 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3193 NBSLOT("__pow__", nb_power, slot_nb_power);
3194 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3195 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3196 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3197 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3198 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3199 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3200 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3201 NBSLOT("__and__", nb_and, slot_nb_and);
3202 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3203 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003204 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00003205 NBSLOT("__int__", nb_int, slot_nb_int);
3206 NBSLOT("__long__", nb_long, slot_nb_long);
3207 NBSLOT("__float__", nb_float, slot_nb_float);
3208 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3209 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3210 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3211 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3212 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3213 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3214 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3215 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3216 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3217 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3218 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3219 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3220 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3221 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3222 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3223 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3224 slot_nb_inplace_floor_divide);
3225 NBSLOT("__itruediv__", nb_inplace_true_divide,
3226 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003227
Guido van Rossum8e248182001-08-12 05:17:56 +00003228 if (dict == NULL ||
3229 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003230 PyDict_GetItemString(dict, "__repr__"))
3231 type->tp_print = NULL;
3232
Guido van Rossumab3b0342001-09-18 20:38:53 +00003233 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003234 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3235 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3236 TPSLOT("__call__", tp_call, slot_tp_call);
3237 TPSLOT("__str__", tp_str, slot_tp_str);
Guido van Rossum867a8d22001-09-21 19:29:08 +00003238 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003239 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003240 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3241 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3242 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3243 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3244 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3245 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3246 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3247 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3248 TPSLOT("next", tp_iternext, slot_tp_iternext);
3249 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3250 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3251 TPSLOT("__init__", tp_init, slot_tp_init);
3252 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003253}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003254
3255
3256/* Cooperative 'super' */
3257
3258typedef struct {
3259 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003260 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003261 PyObject *obj;
3262} superobject;
3263
Guido van Rossum6f799372001-09-20 20:46:19 +00003264static PyMemberDef super_members[] = {
3265 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3266 "the class invoking super()"},
3267 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3268 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003269 {0}
3270};
3271
Guido van Rossum705f0f52001-08-24 16:47:00 +00003272static void
3273super_dealloc(PyObject *self)
3274{
3275 superobject *su = (superobject *)self;
3276
3277 Py_XDECREF(su->obj);
3278 Py_XDECREF(su->type);
3279 self->ob_type->tp_free(self);
3280}
3281
3282static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003283super_repr(PyObject *self)
3284{
3285 superobject *su = (superobject *)self;
3286
3287 if (su->obj)
3288 return PyString_FromFormat(
3289 "<super: <type '%s'>, <%s object>>",
3290 su->type ? su->type->tp_name : "NULL",
3291 su->obj->ob_type->tp_name);
3292 else
3293 return PyString_FromFormat(
3294 "<super: <type '%s'>, NULL>",
3295 su->type ? su->type->tp_name : "NULL");
3296}
3297
3298static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003299super_getattro(PyObject *self, PyObject *name)
3300{
3301 superobject *su = (superobject *)self;
3302
3303 if (su->obj != NULL) {
3304 PyObject *mro, *res, *tmp;
3305 descrgetfunc f;
3306 int i, n;
3307
Guido van Rossume705ef12001-08-29 15:47:06 +00003308 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003309 if (mro == NULL)
3310 n = 0;
3311 else {
3312 assert(PyTuple_Check(mro));
3313 n = PyTuple_GET_SIZE(mro);
3314 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003315 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003316 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003317 break;
3318 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003319 if (i >= n && PyType_Check(su->obj)) {
3320 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003321 if (mro == NULL)
3322 n = 0;
3323 else {
3324 assert(PyTuple_Check(mro));
3325 n = PyTuple_GET_SIZE(mro);
3326 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003327 for (i = 0; i < n; i++) {
3328 if ((PyObject *)(su->type) ==
3329 PyTuple_GET_ITEM(mro, i))
3330 break;
3331 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003332 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003333 i++;
3334 res = NULL;
3335 for (; i < n; i++) {
3336 tmp = PyTuple_GET_ITEM(mro, i);
3337 assert(PyType_Check(tmp));
3338 res = PyDict_GetItem(
3339 ((PyTypeObject *)tmp)->tp_defined, name);
3340 if (res != NULL) {
3341 Py_INCREF(res);
3342 f = res->ob_type->tp_descr_get;
3343 if (f != NULL) {
3344 tmp = f(res, su->obj, res);
3345 Py_DECREF(res);
3346 res = tmp;
3347 }
3348 return res;
3349 }
3350 }
3351 }
3352 return PyObject_GenericGetAttr(self, name);
3353}
3354
3355static PyObject *
3356super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3357{
3358 superobject *su = (superobject *)self;
3359 superobject *new;
3360
3361 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3362 /* Not binding to an object, or already bound */
3363 Py_INCREF(self);
3364 return self;
3365 }
3366 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3367 if (new == NULL)
3368 return NULL;
3369 Py_INCREF(su->type);
3370 Py_INCREF(obj);
3371 new->type = su->type;
3372 new->obj = obj;
3373 return (PyObject *)new;
3374}
3375
3376static int
3377super_init(PyObject *self, PyObject *args, PyObject *kwds)
3378{
3379 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003380 PyTypeObject *type;
3381 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003382
3383 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3384 return -1;
3385 if (obj == Py_None)
3386 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003387 if (obj != NULL &&
3388 !PyType_IsSubtype(obj->ob_type, type) &&
3389 !(PyType_Check(obj) &&
3390 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003391 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003392 "super(type, obj): "
3393 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003394 return -1;
3395 }
3396 Py_INCREF(type);
3397 Py_XINCREF(obj);
3398 su->type = type;
3399 su->obj = obj;
3400 return 0;
3401}
3402
3403static char super_doc[] =
3404"super(type) -> unbound super object\n"
3405"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003406"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003407"Typical use to call a cooperative superclass method:\n"
3408"class C(B):\n"
3409" def meth(self, arg):\n"
3410" super(C, self).meth(arg)";
3411
3412PyTypeObject PySuper_Type = {
3413 PyObject_HEAD_INIT(&PyType_Type)
3414 0, /* ob_size */
3415 "super", /* tp_name */
3416 sizeof(superobject), /* tp_basicsize */
3417 0, /* tp_itemsize */
3418 /* methods */
3419 super_dealloc, /* tp_dealloc */
3420 0, /* tp_print */
3421 0, /* tp_getattr */
3422 0, /* tp_setattr */
3423 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003424 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003425 0, /* tp_as_number */
3426 0, /* tp_as_sequence */
3427 0, /* tp_as_mapping */
3428 0, /* tp_hash */
3429 0, /* tp_call */
3430 0, /* tp_str */
3431 super_getattro, /* tp_getattro */
3432 0, /* tp_setattro */
3433 0, /* tp_as_buffer */
Guido van Rossum31bcff82001-08-30 04:37:15 +00003434 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003435 super_doc, /* tp_doc */
3436 0, /* tp_traverse */
3437 0, /* tp_clear */
3438 0, /* tp_richcompare */
3439 0, /* tp_weaklistoffset */
3440 0, /* tp_iter */
3441 0, /* tp_iternext */
3442 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003443 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003444 0, /* tp_getset */
3445 0, /* tp_base */
3446 0, /* tp_dict */
3447 super_descr_get, /* tp_descr_get */
3448 0, /* tp_descr_set */
3449 0, /* tp_dictoffset */
3450 super_init, /* tp_init */
3451 PyType_GenericAlloc, /* tp_alloc */
3452 PyType_GenericNew, /* tp_new */
3453 _PyObject_Del, /* tp_free */
3454};