blob: 877a3bd870587ac555c76543e388cee7337b2738 [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 Rossum5c294fb2001-09-25 03:43:42 +00001195static PyObject *
1196object_get_class(PyObject *self, void *closure)
1197{
1198 Py_INCREF(self->ob_type);
1199 return (PyObject *)(self->ob_type);
1200}
1201
1202static int
1203equiv_structs(PyTypeObject *a, PyTypeObject *b)
1204{
1205 return a == b ||
1206 (a != NULL &&
1207 b != NULL &&
1208 a->tp_basicsize == b->tp_basicsize &&
1209 a->tp_itemsize == b->tp_itemsize &&
1210 a->tp_dictoffset == b->tp_dictoffset &&
1211 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1212 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1213 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1214}
1215
1216static int
1217same_slots_added(PyTypeObject *a, PyTypeObject *b)
1218{
1219 PyTypeObject *base = a->tp_base;
1220 int size;
1221
1222 if (base != b->tp_base)
1223 return 0;
1224 if (equiv_structs(a, base) && equiv_structs(b, base))
1225 return 1;
1226 size = base->tp_basicsize;
1227 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1228 size += sizeof(PyObject *);
1229 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1230 size += sizeof(PyObject *);
1231 return size == a->tp_basicsize && size == b->tp_basicsize;
1232}
1233
1234static int
1235object_set_class(PyObject *self, PyObject *value, void *closure)
1236{
1237 PyTypeObject *old = self->ob_type;
1238 PyTypeObject *new, *newbase, *oldbase;
1239
1240 if (!PyType_Check(value)) {
1241 PyErr_Format(PyExc_TypeError,
1242 "__class__ must be set to new-style class, not '%s' object",
1243 value->ob_type->tp_name);
1244 return -1;
1245 }
1246 new = (PyTypeObject *)value;
1247 newbase = new;
1248 oldbase = old;
1249 while (equiv_structs(newbase, newbase->tp_base))
1250 newbase = newbase->tp_base;
1251 while (equiv_structs(oldbase, oldbase->tp_base))
1252 oldbase = oldbase->tp_base;
1253 if (newbase != oldbase &&
1254 (newbase->tp_base != oldbase->tp_base ||
1255 !same_slots_added(newbase, oldbase))) {
1256 PyErr_Format(PyExc_TypeError,
1257 "__class__ assignment: "
1258 "'%s' object layout differs from '%s'",
1259 new->tp_name,
1260 old->tp_name);
1261 return -1;
1262 }
1263 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1264 Py_INCREF(new);
1265 }
1266 self->ob_type = new;
1267 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1268 Py_DECREF(old);
1269 }
1270 return 0;
1271}
1272
1273static PyGetSetDef object_getsets[] = {
1274 {"__class__", object_get_class, object_set_class,
1275 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001276 {0}
1277};
1278
1279PyTypeObject PyBaseObject_Type = {
1280 PyObject_HEAD_INIT(&PyType_Type)
1281 0, /* ob_size */
1282 "object", /* tp_name */
1283 sizeof(PyObject), /* tp_basicsize */
1284 0, /* tp_itemsize */
1285 (destructor)object_dealloc, /* tp_dealloc */
1286 0, /* tp_print */
1287 0, /* tp_getattr */
1288 0, /* tp_setattr */
1289 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001290 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291 0, /* tp_as_number */
1292 0, /* tp_as_sequence */
1293 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001294 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001295 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001296 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001298 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299 0, /* tp_as_buffer */
1300 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1301 "The most base type", /* tp_doc */
1302 0, /* tp_traverse */
1303 0, /* tp_clear */
1304 0, /* tp_richcompare */
1305 0, /* tp_weaklistoffset */
1306 0, /* tp_iter */
1307 0, /* tp_iternext */
1308 0, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001309 0, /* tp_members */
1310 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311 0, /* tp_base */
1312 0, /* tp_dict */
1313 0, /* tp_descr_get */
1314 0, /* tp_descr_set */
1315 0, /* tp_dictoffset */
1316 object_init, /* tp_init */
1317 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001318 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001319 object_free, /* tp_free */
1320};
1321
1322
1323/* Initialize the __dict__ in a type object */
1324
1325static int
1326add_methods(PyTypeObject *type, PyMethodDef *meth)
1327{
1328 PyObject *dict = type->tp_defined;
1329
1330 for (; meth->ml_name != NULL; meth++) {
1331 PyObject *descr;
1332 if (PyDict_GetItemString(dict, meth->ml_name))
1333 continue;
1334 descr = PyDescr_NewMethod(type, meth);
1335 if (descr == NULL)
1336 return -1;
1337 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1338 return -1;
1339 Py_DECREF(descr);
1340 }
1341 return 0;
1342}
1343
1344static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001345add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001346{
1347 PyObject *dict = type->tp_defined;
1348
1349 for (; memb->name != NULL; memb++) {
1350 PyObject *descr;
1351 if (PyDict_GetItemString(dict, memb->name))
1352 continue;
1353 descr = PyDescr_NewMember(type, memb);
1354 if (descr == NULL)
1355 return -1;
1356 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1357 return -1;
1358 Py_DECREF(descr);
1359 }
1360 return 0;
1361}
1362
1363static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001364add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001365{
1366 PyObject *dict = type->tp_defined;
1367
1368 for (; gsp->name != NULL; gsp++) {
1369 PyObject *descr;
1370 if (PyDict_GetItemString(dict, gsp->name))
1371 continue;
1372 descr = PyDescr_NewGetSet(type, gsp);
1373
1374 if (descr == NULL)
1375 return -1;
1376 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1377 return -1;
1378 Py_DECREF(descr);
1379 }
1380 return 0;
1381}
1382
Guido van Rossum13d52f02001-08-10 21:24:08 +00001383static void
1384inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385{
1386 int oldsize, newsize;
1387
Guido van Rossum13d52f02001-08-10 21:24:08 +00001388 /* Special flag magic */
1389 if (!type->tp_as_buffer && base->tp_as_buffer) {
1390 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1391 type->tp_flags |=
1392 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1393 }
1394 if (!type->tp_as_sequence && base->tp_as_sequence) {
1395 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1396 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1397 }
1398 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1399 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1400 if ((!type->tp_as_number && base->tp_as_number) ||
1401 (!type->tp_as_sequence && base->tp_as_sequence)) {
1402 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1403 if (!type->tp_as_number && !type->tp_as_sequence) {
1404 type->tp_flags |= base->tp_flags &
1405 Py_TPFLAGS_HAVE_INPLACEOPS;
1406 }
1407 }
1408 /* Wow */
1409 }
1410 if (!type->tp_as_number && base->tp_as_number) {
1411 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1412 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1413 }
1414
1415 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001416 oldsize = base->tp_basicsize;
1417 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1418 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1419 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001420 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1421 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001422 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001423 if (type->tp_traverse == NULL)
1424 type->tp_traverse = base->tp_traverse;
1425 if (type->tp_clear == NULL)
1426 type->tp_clear = base->tp_clear;
1427 }
1428 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1429 if (base != &PyBaseObject_Type ||
1430 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1431 if (type->tp_new == NULL)
1432 type->tp_new = base->tp_new;
1433 }
1434 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001435 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001436
1437 /* Copy other non-function slots */
1438
1439#undef COPYVAL
1440#define COPYVAL(SLOT) \
1441 if (type->SLOT == 0) type->SLOT = base->SLOT
1442
1443 COPYVAL(tp_itemsize);
1444 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1445 COPYVAL(tp_weaklistoffset);
1446 }
1447 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1448 COPYVAL(tp_dictoffset);
1449 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001450}
1451
1452static void
1453inherit_slots(PyTypeObject *type, PyTypeObject *base)
1454{
1455 PyTypeObject *basebase;
1456
1457#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458#undef COPYSLOT
1459#undef COPYNUM
1460#undef COPYSEQ
1461#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001462
1463#define SLOTDEFINED(SLOT) \
1464 (base->SLOT != 0 && \
1465 (basebase == NULL || base->SLOT != basebase->SLOT))
1466
Tim Peters6d6c1a32001-08-02 04:15:00 +00001467#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001468 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001469
1470#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1471#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1472#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1473
Guido van Rossum13d52f02001-08-10 21:24:08 +00001474 /* This won't inherit indirect slots (from tp_as_number etc.)
1475 if type doesn't provide the space. */
1476
1477 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1478 basebase = base->tp_base;
1479 if (basebase->tp_as_number == NULL)
1480 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001481 COPYNUM(nb_add);
1482 COPYNUM(nb_subtract);
1483 COPYNUM(nb_multiply);
1484 COPYNUM(nb_divide);
1485 COPYNUM(nb_remainder);
1486 COPYNUM(nb_divmod);
1487 COPYNUM(nb_power);
1488 COPYNUM(nb_negative);
1489 COPYNUM(nb_positive);
1490 COPYNUM(nb_absolute);
1491 COPYNUM(nb_nonzero);
1492 COPYNUM(nb_invert);
1493 COPYNUM(nb_lshift);
1494 COPYNUM(nb_rshift);
1495 COPYNUM(nb_and);
1496 COPYNUM(nb_xor);
1497 COPYNUM(nb_or);
1498 COPYNUM(nb_coerce);
1499 COPYNUM(nb_int);
1500 COPYNUM(nb_long);
1501 COPYNUM(nb_float);
1502 COPYNUM(nb_oct);
1503 COPYNUM(nb_hex);
1504 COPYNUM(nb_inplace_add);
1505 COPYNUM(nb_inplace_subtract);
1506 COPYNUM(nb_inplace_multiply);
1507 COPYNUM(nb_inplace_divide);
1508 COPYNUM(nb_inplace_remainder);
1509 COPYNUM(nb_inplace_power);
1510 COPYNUM(nb_inplace_lshift);
1511 COPYNUM(nb_inplace_rshift);
1512 COPYNUM(nb_inplace_and);
1513 COPYNUM(nb_inplace_xor);
1514 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001515 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1516 COPYNUM(nb_true_divide);
1517 COPYNUM(nb_floor_divide);
1518 COPYNUM(nb_inplace_true_divide);
1519 COPYNUM(nb_inplace_floor_divide);
1520 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001521 }
1522
Guido van Rossum13d52f02001-08-10 21:24:08 +00001523 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1524 basebase = base->tp_base;
1525 if (basebase->tp_as_sequence == NULL)
1526 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527 COPYSEQ(sq_length);
1528 COPYSEQ(sq_concat);
1529 COPYSEQ(sq_repeat);
1530 COPYSEQ(sq_item);
1531 COPYSEQ(sq_slice);
1532 COPYSEQ(sq_ass_item);
1533 COPYSEQ(sq_ass_slice);
1534 COPYSEQ(sq_contains);
1535 COPYSEQ(sq_inplace_concat);
1536 COPYSEQ(sq_inplace_repeat);
1537 }
1538
Guido van Rossum13d52f02001-08-10 21:24:08 +00001539 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1540 basebase = base->tp_base;
1541 if (basebase->tp_as_mapping == NULL)
1542 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001543 COPYMAP(mp_length);
1544 COPYMAP(mp_subscript);
1545 COPYMAP(mp_ass_subscript);
1546 }
1547
Guido van Rossum13d52f02001-08-10 21:24:08 +00001548 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001549
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550 COPYSLOT(tp_dealloc);
1551 COPYSLOT(tp_print);
1552 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1553 type->tp_getattr = base->tp_getattr;
1554 type->tp_getattro = base->tp_getattro;
1555 }
1556 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1557 type->tp_setattr = base->tp_setattr;
1558 type->tp_setattro = base->tp_setattro;
1559 }
1560 /* tp_compare see tp_richcompare */
1561 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001562 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001563 COPYSLOT(tp_call);
1564 COPYSLOT(tp_str);
1565 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001566 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001567 if (type->tp_compare == NULL &&
1568 type->tp_richcompare == NULL &&
1569 type->tp_hash == NULL)
1570 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571 type->tp_compare = base->tp_compare;
1572 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001573 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574 }
1575 }
1576 else {
1577 COPYSLOT(tp_compare);
1578 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001579 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1580 COPYSLOT(tp_iter);
1581 COPYSLOT(tp_iternext);
1582 }
1583 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1584 COPYSLOT(tp_descr_get);
1585 COPYSLOT(tp_descr_set);
1586 COPYSLOT(tp_dictoffset);
1587 COPYSLOT(tp_init);
1588 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589 COPYSLOT(tp_free);
1590 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001591}
1592
Guido van Rossum13d52f02001-08-10 21:24:08 +00001593staticforward int add_operators(PyTypeObject *);
1594
Tim Peters6d6c1a32001-08-02 04:15:00 +00001595int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001596PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001597{
1598 PyObject *dict, *bases, *x;
1599 PyTypeObject *base;
1600 int i, n;
1601
Guido van Rossumd614f972001-08-10 17:39:49 +00001602 if (type->tp_flags & Py_TPFLAGS_READY) {
1603 assert(type->tp_dict != NULL);
1604 return 0;
1605 }
1606 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1607 assert(type->tp_dict == NULL);
1608
1609 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001610
1611 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1612 base = type->tp_base;
1613 if (base == NULL && type != &PyBaseObject_Type)
1614 base = type->tp_base = &PyBaseObject_Type;
1615
1616 /* Initialize tp_bases */
1617 bases = type->tp_bases;
1618 if (bases == NULL) {
1619 if (base == NULL)
1620 bases = PyTuple_New(0);
1621 else
1622 bases = Py_BuildValue("(O)", base);
1623 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001624 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625 type->tp_bases = bases;
1626 }
1627
1628 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001629 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001630 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001631 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001632 }
1633
1634 /* Initialize tp_defined */
1635 dict = type->tp_defined;
1636 if (dict == NULL) {
1637 dict = PyDict_New();
1638 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001639 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001640 type->tp_defined = dict;
1641 }
1642
1643 /* Add type-specific descriptors to tp_defined */
1644 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001645 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001646 if (type->tp_methods != NULL) {
1647 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001648 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001649 }
1650 if (type->tp_members != NULL) {
1651 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001652 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653 }
1654 if (type->tp_getset != NULL) {
1655 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001656 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657 }
1658
1659 /* Temporarily make tp_dict the same object as tp_defined.
1660 (This is needed to call mro(), and can stay this way for
1661 dynamic types). */
1662 Py_INCREF(type->tp_defined);
1663 type->tp_dict = type->tp_defined;
1664
1665 /* Calculate method resolution order */
1666 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001667 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668 }
1669
Guido van Rossum13d52f02001-08-10 21:24:08 +00001670 /* Inherit special flags from dominant base */
1671 if (type->tp_base != NULL)
1672 inherit_special(type, type->tp_base);
1673
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001675 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001676 /* For a dynamic type, all slots are overridden */
1677 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001678 }
1679 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001680 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001681 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001682 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001683 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001685 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686 bases = type->tp_mro;
1687 assert(bases != NULL);
1688 assert(PyTuple_Check(bases));
1689 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001690 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1692 assert(PyType_Check(base));
1693 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001694 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001695 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001696 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001697 }
1698 }
1699
Guido van Rossum13d52f02001-08-10 21:24:08 +00001700 /* Some more special stuff */
1701 base = type->tp_base;
1702 if (base != NULL) {
1703 if (type->tp_as_number == NULL)
1704 type->tp_as_number = base->tp_as_number;
1705 if (type->tp_as_sequence == NULL)
1706 type->tp_as_sequence = base->tp_as_sequence;
1707 if (type->tp_as_mapping == NULL)
1708 type->tp_as_mapping = base->tp_as_mapping;
1709 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001710
Guido van Rossum13d52f02001-08-10 21:24:08 +00001711 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001712 assert(type->tp_dict != NULL);
1713 type->tp_flags =
1714 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001716
1717 error:
1718 type->tp_flags &= ~Py_TPFLAGS_READYING;
1719 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001720}
1721
1722
1723/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1724
1725/* There's a wrapper *function* for each distinct function typedef used
1726 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1727 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1728 Most tables have only one entry; the tables for binary operators have two
1729 entries, one regular and one with reversed arguments. */
1730
1731static PyObject *
1732wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1733{
1734 inquiry func = (inquiry)wrapped;
1735 int res;
1736
1737 if (!PyArg_ParseTuple(args, ""))
1738 return NULL;
1739 res = (*func)(self);
1740 if (res == -1 && PyErr_Occurred())
1741 return NULL;
1742 return PyInt_FromLong((long)res);
1743}
1744
1745static struct wrapperbase tab_len[] = {
1746 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1747 {0}
1748};
1749
1750static PyObject *
1751wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1752{
1753 binaryfunc func = (binaryfunc)wrapped;
1754 PyObject *other;
1755
1756 if (!PyArg_ParseTuple(args, "O", &other))
1757 return NULL;
1758 return (*func)(self, other);
1759}
1760
1761static PyObject *
1762wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1763{
1764 binaryfunc func = (binaryfunc)wrapped;
1765 PyObject *other;
1766
1767 if (!PyArg_ParseTuple(args, "O", &other))
1768 return NULL;
1769 return (*func)(other, self);
1770}
1771
1772#undef BINARY
1773#define BINARY(NAME, OP) \
1774static struct wrapperbase tab_##NAME[] = { \
1775 {"__" #NAME "__", \
1776 (wrapperfunc)wrap_binaryfunc, \
1777 "x.__" #NAME "__(y) <==> " #OP}, \
1778 {"__r" #NAME "__", \
1779 (wrapperfunc)wrap_binaryfunc_r, \
1780 "y.__r" #NAME "__(x) <==> " #OP}, \
1781 {0} \
1782}
1783
1784BINARY(add, "x+y");
1785BINARY(sub, "x-y");
1786BINARY(mul, "x*y");
1787BINARY(div, "x/y");
1788BINARY(mod, "x%y");
1789BINARY(divmod, "divmod(x,y)");
1790BINARY(lshift, "x<<y");
1791BINARY(rshift, "x>>y");
1792BINARY(and, "x&y");
1793BINARY(xor, "x^y");
1794BINARY(or, "x|y");
1795
1796static PyObject *
1797wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1798{
1799 ternaryfunc func = (ternaryfunc)wrapped;
1800 PyObject *other;
1801 PyObject *third = Py_None;
1802
1803 /* Note: This wrapper only works for __pow__() */
1804
1805 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1806 return NULL;
1807 return (*func)(self, other, third);
1808}
1809
1810#undef TERNARY
1811#define TERNARY(NAME, OP) \
1812static struct wrapperbase tab_##NAME[] = { \
1813 {"__" #NAME "__", \
1814 (wrapperfunc)wrap_ternaryfunc, \
1815 "x.__" #NAME "__(y, z) <==> " #OP}, \
1816 {"__r" #NAME "__", \
1817 (wrapperfunc)wrap_ternaryfunc, \
1818 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1819 {0} \
1820}
1821
1822TERNARY(pow, "(x**y) % z");
1823
1824#undef UNARY
1825#define UNARY(NAME, OP) \
1826static struct wrapperbase tab_##NAME[] = { \
1827 {"__" #NAME "__", \
1828 (wrapperfunc)wrap_unaryfunc, \
1829 "x.__" #NAME "__() <==> " #OP}, \
1830 {0} \
1831}
1832
1833static PyObject *
1834wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1835{
1836 unaryfunc func = (unaryfunc)wrapped;
1837
1838 if (!PyArg_ParseTuple(args, ""))
1839 return NULL;
1840 return (*func)(self);
1841}
1842
1843UNARY(neg, "-x");
1844UNARY(pos, "+x");
1845UNARY(abs, "abs(x)");
1846UNARY(nonzero, "x != 0");
1847UNARY(invert, "~x");
1848UNARY(int, "int(x)");
1849UNARY(long, "long(x)");
1850UNARY(float, "float(x)");
1851UNARY(oct, "oct(x)");
1852UNARY(hex, "hex(x)");
1853
1854#undef IBINARY
1855#define IBINARY(NAME, OP) \
1856static struct wrapperbase tab_##NAME[] = { \
1857 {"__" #NAME "__", \
1858 (wrapperfunc)wrap_binaryfunc, \
1859 "x.__" #NAME "__(y) <==> " #OP}, \
1860 {0} \
1861}
1862
1863IBINARY(iadd, "x+=y");
1864IBINARY(isub, "x-=y");
1865IBINARY(imul, "x*=y");
1866IBINARY(idiv, "x/=y");
1867IBINARY(imod, "x%=y");
1868IBINARY(ilshift, "x<<=y");
1869IBINARY(irshift, "x>>=y");
1870IBINARY(iand, "x&=y");
1871IBINARY(ixor, "x^=y");
1872IBINARY(ior, "x|=y");
1873
1874#undef ITERNARY
1875#define ITERNARY(NAME, OP) \
1876static struct wrapperbase tab_##NAME[] = { \
1877 {"__" #NAME "__", \
1878 (wrapperfunc)wrap_ternaryfunc, \
1879 "x.__" #NAME "__(y) <==> " #OP}, \
1880 {0} \
1881}
1882
1883ITERNARY(ipow, "x = (x**y) % z");
1884
1885static struct wrapperbase tab_getitem[] = {
1886 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1887 "x.__getitem__(y) <==> x[y]"},
1888 {0}
1889};
1890
1891static PyObject *
1892wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1893{
1894 intargfunc func = (intargfunc)wrapped;
1895 int i;
1896
1897 if (!PyArg_ParseTuple(args, "i", &i))
1898 return NULL;
1899 return (*func)(self, i);
1900}
1901
1902static struct wrapperbase tab_mul_int[] = {
1903 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1904 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1905 {0}
1906};
1907
1908static struct wrapperbase tab_concat[] = {
1909 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1910 {0}
1911};
1912
1913static struct wrapperbase tab_imul_int[] = {
1914 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1915 {0}
1916};
1917
Guido van Rossum5d815f32001-08-17 21:57:47 +00001918static int
1919getindex(PyObject *self, PyObject *arg)
1920{
1921 int i;
1922
1923 i = PyInt_AsLong(arg);
1924 if (i == -1 && PyErr_Occurred())
1925 return -1;
1926 if (i < 0) {
1927 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
1928 if (sq && sq->sq_length) {
1929 int n = (*sq->sq_length)(self);
1930 if (n < 0)
1931 return -1;
1932 i += n;
1933 }
1934 }
1935 return i;
1936}
1937
1938static PyObject *
1939wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
1940{
1941 intargfunc func = (intargfunc)wrapped;
1942 PyObject *arg;
1943 int i;
1944
1945 if (!PyArg_ParseTuple(args, "O", &arg))
1946 return NULL;
1947 i = getindex(self, arg);
1948 if (i == -1 && PyErr_Occurred())
1949 return NULL;
1950 return (*func)(self, i);
1951}
1952
Tim Peters6d6c1a32001-08-02 04:15:00 +00001953static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001954 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001955 "x.__getitem__(i) <==> x[i]"},
1956 {0}
1957};
1958
1959static PyObject *
1960wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1961{
1962 intintargfunc func = (intintargfunc)wrapped;
1963 int i, j;
1964
1965 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1966 return NULL;
1967 return (*func)(self, i, j);
1968}
1969
1970static struct wrapperbase tab_getslice[] = {
1971 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1972 "x.__getslice__(i, j) <==> x[i:j]"},
1973 {0}
1974};
1975
1976static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001977wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001978{
1979 intobjargproc func = (intobjargproc)wrapped;
1980 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001981 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001982
Guido van Rossum5d815f32001-08-17 21:57:47 +00001983 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
1984 return NULL;
1985 i = getindex(self, arg);
1986 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987 return NULL;
1988 res = (*func)(self, i, value);
1989 if (res == -1 && PyErr_Occurred())
1990 return NULL;
1991 Py_INCREF(Py_None);
1992 return Py_None;
1993}
1994
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001995static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001996wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001997{
1998 intobjargproc func = (intobjargproc)wrapped;
1999 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002000 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002001
Guido van Rossum5d815f32001-08-17 21:57:47 +00002002 if (!PyArg_ParseTuple(args, "O", &arg))
2003 return NULL;
2004 i = getindex(self, arg);
2005 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002006 return NULL;
2007 res = (*func)(self, i, NULL);
2008 if (res == -1 && PyErr_Occurred())
2009 return NULL;
2010 Py_INCREF(Py_None);
2011 return Py_None;
2012}
2013
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002015 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002017 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002018 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019 {0}
2020};
2021
2022static PyObject *
2023wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2024{
2025 intintobjargproc func = (intintobjargproc)wrapped;
2026 int i, j, res;
2027 PyObject *value;
2028
2029 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2030 return NULL;
2031 res = (*func)(self, i, j, value);
2032 if (res == -1 && PyErr_Occurred())
2033 return NULL;
2034 Py_INCREF(Py_None);
2035 return Py_None;
2036}
2037
2038static struct wrapperbase tab_setslice[] = {
2039 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2040 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
2041 {0}
2042};
2043
2044/* XXX objobjproc is a misnomer; should be objargpred */
2045static PyObject *
2046wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2047{
2048 objobjproc func = (objobjproc)wrapped;
2049 int res;
2050 PyObject *value;
2051
2052 if (!PyArg_ParseTuple(args, "O", &value))
2053 return NULL;
2054 res = (*func)(self, value);
2055 if (res == -1 && PyErr_Occurred())
2056 return NULL;
2057 return PyInt_FromLong((long)res);
2058}
2059
2060static struct wrapperbase tab_contains[] = {
2061 {"__contains__", (wrapperfunc)wrap_objobjproc,
2062 "x.__contains__(y) <==> y in x"},
2063 {0}
2064};
2065
2066static PyObject *
2067wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2068{
2069 objobjargproc func = (objobjargproc)wrapped;
2070 int res;
2071 PyObject *key, *value;
2072
2073 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2074 return NULL;
2075 res = (*func)(self, key, value);
2076 if (res == -1 && PyErr_Occurred())
2077 return NULL;
2078 Py_INCREF(Py_None);
2079 return Py_None;
2080}
2081
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002082static PyObject *
2083wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2084{
2085 objobjargproc func = (objobjargproc)wrapped;
2086 int res;
2087 PyObject *key;
2088
2089 if (!PyArg_ParseTuple(args, "O", &key))
2090 return NULL;
2091 res = (*func)(self, key, NULL);
2092 if (res == -1 && PyErr_Occurred())
2093 return NULL;
2094 Py_INCREF(Py_None);
2095 return Py_None;
2096}
2097
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098static struct wrapperbase tab_setitem[] = {
2099 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2100 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002101 {"__delitem__", (wrapperfunc)wrap_delitem,
2102 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002103 {0}
2104};
2105
2106static PyObject *
2107wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2108{
2109 cmpfunc func = (cmpfunc)wrapped;
2110 int res;
2111 PyObject *other;
2112
2113 if (!PyArg_ParseTuple(args, "O", &other))
2114 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002115 if (other->ob_type->tp_compare != func &&
2116 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002117 PyErr_Format(
2118 PyExc_TypeError,
2119 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2120 self->ob_type->tp_name,
2121 self->ob_type->tp_name,
2122 other->ob_type->tp_name);
2123 return NULL;
2124 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002125 res = (*func)(self, other);
2126 if (PyErr_Occurred())
2127 return NULL;
2128 return PyInt_FromLong((long)res);
2129}
2130
2131static struct wrapperbase tab_cmp[] = {
2132 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2133 "x.__cmp__(y) <==> cmp(x,y)"},
2134 {0}
2135};
2136
2137static struct wrapperbase tab_repr[] = {
2138 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2139 "x.__repr__() <==> repr(x)"},
2140 {0}
2141};
2142
2143static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002144 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2145 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002146 {0}
2147};
2148
2149static PyObject *
2150wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2151{
2152 setattrofunc func = (setattrofunc)wrapped;
2153 int res;
2154 PyObject *name, *value;
2155
2156 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2157 return NULL;
2158 res = (*func)(self, name, value);
2159 if (res < 0)
2160 return NULL;
2161 Py_INCREF(Py_None);
2162 return Py_None;
2163}
2164
2165static PyObject *
2166wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2167{
2168 setattrofunc func = (setattrofunc)wrapped;
2169 int res;
2170 PyObject *name;
2171
2172 if (!PyArg_ParseTuple(args, "O", &name))
2173 return NULL;
2174 res = (*func)(self, name, NULL);
2175 if (res < 0)
2176 return NULL;
2177 Py_INCREF(Py_None);
2178 return Py_None;
2179}
2180
2181static struct wrapperbase tab_setattr[] = {
2182 {"__setattr__", (wrapperfunc)wrap_setattr,
2183 "x.__setattr__('name', value) <==> x.name = value"},
2184 {"__delattr__", (wrapperfunc)wrap_delattr,
2185 "x.__delattr__('name') <==> del x.name"},
2186 {0}
2187};
2188
2189static PyObject *
2190wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2191{
2192 hashfunc func = (hashfunc)wrapped;
2193 long res;
2194
2195 if (!PyArg_ParseTuple(args, ""))
2196 return NULL;
2197 res = (*func)(self);
2198 if (res == -1 && PyErr_Occurred())
2199 return NULL;
2200 return PyInt_FromLong(res);
2201}
2202
2203static struct wrapperbase tab_hash[] = {
2204 {"__hash__", (wrapperfunc)wrap_hashfunc,
2205 "x.__hash__() <==> hash(x)"},
2206 {0}
2207};
2208
2209static PyObject *
2210wrap_call(PyObject *self, PyObject *args, void *wrapped)
2211{
2212 ternaryfunc func = (ternaryfunc)wrapped;
2213
2214 /* XXX What about keyword arguments? */
2215 return (*func)(self, args, NULL);
2216}
2217
2218static struct wrapperbase tab_call[] = {
2219 {"__call__", (wrapperfunc)wrap_call,
2220 "x.__call__(...) <==> x(...)"},
2221 {0}
2222};
2223
2224static struct wrapperbase tab_str[] = {
2225 {"__str__", (wrapperfunc)wrap_unaryfunc,
2226 "x.__str__() <==> str(x)"},
2227 {0}
2228};
2229
2230static PyObject *
2231wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2232{
2233 richcmpfunc func = (richcmpfunc)wrapped;
2234 PyObject *other;
2235
2236 if (!PyArg_ParseTuple(args, "O", &other))
2237 return NULL;
2238 return (*func)(self, other, op);
2239}
2240
2241#undef RICHCMP_WRAPPER
2242#define RICHCMP_WRAPPER(NAME, OP) \
2243static PyObject * \
2244richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2245{ \
2246 return wrap_richcmpfunc(self, args, wrapped, OP); \
2247}
2248
Jack Jansen8e938b42001-08-08 15:29:49 +00002249RICHCMP_WRAPPER(lt, Py_LT)
2250RICHCMP_WRAPPER(le, Py_LE)
2251RICHCMP_WRAPPER(eq, Py_EQ)
2252RICHCMP_WRAPPER(ne, Py_NE)
2253RICHCMP_WRAPPER(gt, Py_GT)
2254RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002255
2256#undef RICHCMP_ENTRY
2257#define RICHCMP_ENTRY(NAME, EXPR) \
2258 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2259 "x.__" #NAME "__(y) <==> " EXPR}
2260
2261static struct wrapperbase tab_richcmp[] = {
2262 RICHCMP_ENTRY(lt, "x<y"),
2263 RICHCMP_ENTRY(le, "x<=y"),
2264 RICHCMP_ENTRY(eq, "x==y"),
2265 RICHCMP_ENTRY(ne, "x!=y"),
2266 RICHCMP_ENTRY(gt, "x>y"),
2267 RICHCMP_ENTRY(ge, "x>=y"),
2268 {0}
2269};
2270
2271static struct wrapperbase tab_iter[] = {
2272 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2273 {0}
2274};
2275
2276static PyObject *
2277wrap_next(PyObject *self, PyObject *args, void *wrapped)
2278{
2279 unaryfunc func = (unaryfunc)wrapped;
2280 PyObject *res;
2281
2282 if (!PyArg_ParseTuple(args, ""))
2283 return NULL;
2284 res = (*func)(self);
2285 if (res == NULL && !PyErr_Occurred())
2286 PyErr_SetNone(PyExc_StopIteration);
2287 return res;
2288}
2289
2290static struct wrapperbase tab_next[] = {
2291 {"next", (wrapperfunc)wrap_next,
2292 "x.next() -> the next value, or raise StopIteration"},
2293 {0}
2294};
2295
2296static PyObject *
2297wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2298{
2299 descrgetfunc func = (descrgetfunc)wrapped;
2300 PyObject *obj;
2301 PyObject *type = NULL;
2302
2303 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2304 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002305 return (*func)(self, obj, type);
2306}
2307
2308static struct wrapperbase tab_descr_get[] = {
2309 {"__get__", (wrapperfunc)wrap_descr_get,
2310 "descr.__get__(obj, type) -> value"},
2311 {0}
2312};
2313
2314static PyObject *
2315wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2316{
2317 descrsetfunc func = (descrsetfunc)wrapped;
2318 PyObject *obj, *value;
2319 int ret;
2320
2321 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2322 return NULL;
2323 ret = (*func)(self, obj, value);
2324 if (ret < 0)
2325 return NULL;
2326 Py_INCREF(Py_None);
2327 return Py_None;
2328}
2329
2330static struct wrapperbase tab_descr_set[] = {
2331 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2332 "descr.__set__(obj, value)"},
2333 {0}
2334};
2335
2336static PyObject *
2337wrap_init(PyObject *self, PyObject *args, void *wrapped)
2338{
2339 initproc func = (initproc)wrapped;
2340
2341 /* XXX What about keyword arguments? */
2342 if (func(self, args, NULL) < 0)
2343 return NULL;
2344 Py_INCREF(Py_None);
2345 return Py_None;
2346}
2347
2348static struct wrapperbase tab_init[] = {
2349 {"__init__", (wrapperfunc)wrap_init,
2350 "x.__init__(...) initializes x; "
2351 "see x.__type__.__doc__ for signature"},
2352 {0}
2353};
2354
2355static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002356tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002357{
Barry Warsaw60f01882001-08-22 19:24:42 +00002358 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002359 PyObject *arg0, *res;
2360
2361 if (self == NULL || !PyType_Check(self))
2362 Py_FatalError("__new__() called with non-type 'self'");
2363 type = (PyTypeObject *)self;
2364 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002365 PyErr_Format(PyExc_TypeError,
2366 "%s.__new__(): not enough arguments",
2367 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002368 return NULL;
2369 }
2370 arg0 = PyTuple_GET_ITEM(args, 0);
2371 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002372 PyErr_Format(PyExc_TypeError,
2373 "%s.__new__(X): X is not a type object (%s)",
2374 type->tp_name,
2375 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002376 return NULL;
2377 }
2378 subtype = (PyTypeObject *)arg0;
2379 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002380 PyErr_Format(PyExc_TypeError,
2381 "%s.__new__(%s): %s is not a subtype of %s",
2382 type->tp_name,
2383 subtype->tp_name,
2384 subtype->tp_name,
2385 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002386 return NULL;
2387 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002388
2389 /* Check that the use doesn't do something silly and unsafe like
2390 object.__new__(dictionary). To do this, we check that the
2391 most derived base that's not a heap type is this type. */
2392 staticbase = subtype;
2393 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2394 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002395 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002396 PyErr_Format(PyExc_TypeError,
2397 "%s.__new__(%s) is not safe, use %s.__new__()",
2398 type->tp_name,
2399 subtype->tp_name,
2400 staticbase == NULL ? "?" : staticbase->tp_name);
2401 return NULL;
2402 }
2403
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002404 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2405 if (args == NULL)
2406 return NULL;
2407 res = type->tp_new(subtype, args, kwds);
2408 Py_DECREF(args);
2409 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002410}
2411
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002412static struct PyMethodDef tp_new_methoddef[] = {
2413 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2414 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002415 {0}
2416};
2417
2418static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002419add_tp_new_wrapper(PyTypeObject *type)
2420{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002421 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002422
Guido van Rossumf040ede2001-08-07 16:40:56 +00002423 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2424 return 0;
2425 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002426 if (func == NULL)
2427 return -1;
2428 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2429}
2430
Guido van Rossum13d52f02001-08-10 21:24:08 +00002431static int
2432add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2433{
2434 PyObject *dict = type->tp_defined;
2435
2436 for (; wraps->name != NULL; wraps++) {
2437 PyObject *descr;
2438 if (PyDict_GetItemString(dict, wraps->name))
2439 continue;
2440 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2441 if (descr == NULL)
2442 return -1;
2443 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2444 return -1;
2445 Py_DECREF(descr);
2446 }
2447 return 0;
2448}
2449
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002450/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002451 dictionary with method descriptors for function slots. For each
2452 function slot (like tp_repr) that's defined in the type, one or
2453 more corresponding descriptors are added in the type's tp_defined
2454 dictionary under the appropriate name (like __repr__). Some
2455 function slots cause more than one descriptor to be added (for
2456 example, the nb_add slot adds both __add__ and __radd__
2457 descriptors) and some function slots compete for the same
2458 descriptor (for example both sq_item and mp_subscript generate a
2459 __getitem__ descriptor). This only adds new descriptors and
2460 doesn't overwrite entries in tp_defined that were previously
2461 defined. The descriptors contain a reference to the C function
2462 they must call, so that it's safe if they are copied into a
2463 subtype's __dict__ and the subtype has a different C function in
2464 its slot -- calling the method defined by the descriptor will call
2465 the C function that was used to create it, rather than the C
2466 function present in the slot when it is called. (This is important
2467 because a subtype may have a C function in the slot that calls the
2468 method from the dictionary, and we want to avoid infinite recursion
2469 here.) */
2470
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002471static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002472add_operators(PyTypeObject *type)
2473{
2474 PySequenceMethods *sq;
2475 PyMappingMethods *mp;
2476 PyNumberMethods *nb;
2477
2478#undef ADD
2479#define ADD(SLOT, TABLE) \
2480 if (SLOT) { \
2481 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2482 return -1; \
2483 }
2484
2485 if ((sq = type->tp_as_sequence) != NULL) {
2486 ADD(sq->sq_length, tab_len);
2487 ADD(sq->sq_concat, tab_concat);
2488 ADD(sq->sq_repeat, tab_mul_int);
2489 ADD(sq->sq_item, tab_getitem_int);
2490 ADD(sq->sq_slice, tab_getslice);
2491 ADD(sq->sq_ass_item, tab_setitem_int);
2492 ADD(sq->sq_ass_slice, tab_setslice);
2493 ADD(sq->sq_contains, tab_contains);
2494 ADD(sq->sq_inplace_concat, tab_iadd);
2495 ADD(sq->sq_inplace_repeat, tab_imul_int);
2496 }
2497
2498 if ((mp = type->tp_as_mapping) != NULL) {
2499 if (sq->sq_length == NULL)
2500 ADD(mp->mp_length, tab_len);
2501 ADD(mp->mp_subscript, tab_getitem);
2502 ADD(mp->mp_ass_subscript, tab_setitem);
2503 }
2504
2505 /* We don't support "old-style numbers" because their binary
2506 operators require that both arguments have the same type;
2507 the wrappers here only work for new-style numbers. */
2508 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2509 (nb = type->tp_as_number) != NULL) {
2510 ADD(nb->nb_add, tab_add);
2511 ADD(nb->nb_subtract, tab_sub);
2512 ADD(nb->nb_multiply, tab_mul);
2513 ADD(nb->nb_divide, tab_div);
2514 ADD(nb->nb_remainder, tab_mod);
2515 ADD(nb->nb_divmod, tab_divmod);
2516 ADD(nb->nb_power, tab_pow);
2517 ADD(nb->nb_negative, tab_neg);
2518 ADD(nb->nb_positive, tab_pos);
2519 ADD(nb->nb_absolute, tab_abs);
2520 ADD(nb->nb_nonzero, tab_nonzero);
2521 ADD(nb->nb_invert, tab_invert);
2522 ADD(nb->nb_lshift, tab_lshift);
2523 ADD(nb->nb_rshift, tab_rshift);
2524 ADD(nb->nb_and, tab_and);
2525 ADD(nb->nb_xor, tab_xor);
2526 ADD(nb->nb_or, tab_or);
2527 /* We don't support coerce() -- see above comment */
2528 ADD(nb->nb_int, tab_int);
2529 ADD(nb->nb_long, tab_long);
2530 ADD(nb->nb_float, tab_float);
2531 ADD(nb->nb_oct, tab_oct);
2532 ADD(nb->nb_hex, tab_hex);
2533 ADD(nb->nb_inplace_add, tab_iadd);
2534 ADD(nb->nb_inplace_subtract, tab_isub);
2535 ADD(nb->nb_inplace_multiply, tab_imul);
2536 ADD(nb->nb_inplace_divide, tab_idiv);
2537 ADD(nb->nb_inplace_remainder, tab_imod);
2538 ADD(nb->nb_inplace_power, tab_ipow);
2539 ADD(nb->nb_inplace_lshift, tab_ilshift);
2540 ADD(nb->nb_inplace_rshift, tab_irshift);
2541 ADD(nb->nb_inplace_and, tab_iand);
2542 ADD(nb->nb_inplace_xor, tab_ixor);
2543 ADD(nb->nb_inplace_or, tab_ior);
2544 }
2545
2546 ADD(type->tp_getattro, tab_getattr);
2547 ADD(type->tp_setattro, tab_setattr);
2548 ADD(type->tp_compare, tab_cmp);
2549 ADD(type->tp_repr, tab_repr);
2550 ADD(type->tp_hash, tab_hash);
2551 ADD(type->tp_call, tab_call);
2552 ADD(type->tp_str, tab_str);
2553 ADD(type->tp_richcompare, tab_richcmp);
2554 ADD(type->tp_iter, tab_iter);
2555 ADD(type->tp_iternext, tab_next);
2556 ADD(type->tp_descr_get, tab_descr_get);
2557 ADD(type->tp_descr_set, tab_descr_set);
2558 ADD(type->tp_init, tab_init);
2559
Guido van Rossumf040ede2001-08-07 16:40:56 +00002560 if (type->tp_new != NULL) {
2561 if (add_tp_new_wrapper(type) < 0)
2562 return -1;
2563 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002564
2565 return 0;
2566}
2567
Guido van Rossumf040ede2001-08-07 16:40:56 +00002568/* Slot wrappers that call the corresponding __foo__ slot. See comments
2569 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002570
Guido van Rossumdc91b992001-08-08 22:26:22 +00002571#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002572static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002573FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002574{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002575 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002576 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002577}
2578
Guido van Rossumdc91b992001-08-08 22:26:22 +00002579#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002580static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002581FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002582{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002583 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002584 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002585}
2586
Guido van Rossumdc91b992001-08-08 22:26:22 +00002587
2588#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002590FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002591{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002592 static PyObject *cache_str, *rcache_str; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002593 if (self->ob_type->tp_as_number != NULL && \
2594 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2595 PyObject *r; \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002596 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002597 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002598 if (r != Py_NotImplemented || \
2599 other->ob_type == self->ob_type) \
2600 return r; \
2601 Py_DECREF(r); \
2602 } \
2603 if (other->ob_type->tp_as_number != NULL && \
2604 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002605 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002606 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002607 } \
2608 Py_INCREF(Py_NotImplemented); \
2609 return Py_NotImplemented; \
2610}
2611
2612#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2613 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2614
2615#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2616static PyObject * \
2617FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2618{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002619 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002620 return call_method(self, OPSTR, &cache_str, \
2621 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002622}
2623
2624static int
2625slot_sq_length(PyObject *self)
2626{
Guido van Rossum2730b132001-08-28 18:22:14 +00002627 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002628 PyObject *res = call_method(self, "__len__", &len_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002629
2630 if (res == NULL)
2631 return -1;
2632 return (int)PyInt_AsLong(res);
2633}
2634
Guido van Rossumdc91b992001-08-08 22:26:22 +00002635SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2636SLOT1(slot_sq_repeat, "__mul__", int, "i")
2637SLOT1(slot_sq_item, "__getitem__", int, "i")
2638SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002639
2640static int
2641slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2642{
2643 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002644 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002645
2646 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002647 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002648 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002649 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002650 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002651 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002652 if (res == NULL)
2653 return -1;
2654 Py_DECREF(res);
2655 return 0;
2656}
2657
2658static int
2659slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2660{
2661 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002662 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002663
2664 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002665 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002666 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002668 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002669 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002670 if (res == NULL)
2671 return -1;
2672 Py_DECREF(res);
2673 return 0;
2674}
2675
2676static int
2677slot_sq_contains(PyObject *self, PyObject *value)
2678{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002679 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002680 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002681
Guido van Rossum60718732001-08-28 17:47:51 +00002682 func = lookup_method(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002683
2684 if (func != NULL) {
2685 args = Py_BuildValue("(O)", value);
2686 if (args == NULL)
2687 res = NULL;
2688 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002689 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002690 Py_DECREF(args);
2691 }
2692 Py_DECREF(func);
2693 if (res == NULL)
2694 return -1;
2695 return PyObject_IsTrue(res);
2696 }
2697 else {
2698 PyErr_Clear();
Tim Peters16a77ad2001-09-08 04:00:12 +00002699 return _PySequence_IterSearch(self, value,
2700 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002701 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002702}
2703
Guido van Rossumdc91b992001-08-08 22:26:22 +00002704SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2705SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002706
2707#define slot_mp_length slot_sq_length
2708
Guido van Rossumdc91b992001-08-08 22:26:22 +00002709SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002710
2711static int
2712slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2713{
2714 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002715 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716
2717 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002718 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002719 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002720 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002721 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002722 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723 if (res == NULL)
2724 return -1;
2725 Py_DECREF(res);
2726 return 0;
2727}
2728
Guido van Rossumdc91b992001-08-08 22:26:22 +00002729SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2730SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2731SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2732SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2733SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2734SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2735
2736staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2737
2738SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2739 nb_power, "__pow__", "__rpow__")
2740
2741static PyObject *
2742slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2743{
Guido van Rossum2730b132001-08-28 18:22:14 +00002744 static PyObject *pow_str;
2745
Guido van Rossumdc91b992001-08-08 22:26:22 +00002746 if (modulus == Py_None)
2747 return slot_nb_power_binary(self, other);
2748 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002749 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002750 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002751}
2752
2753SLOT0(slot_nb_negative, "__neg__")
2754SLOT0(slot_nb_positive, "__pos__")
2755SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002756
2757static int
2758slot_nb_nonzero(PyObject *self)
2759{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002760 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002761 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002762
Guido van Rossum60718732001-08-28 17:47:51 +00002763 func = lookup_method(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002764 if (func == NULL) {
2765 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002766 func = lookup_method(self, "__len__", &len_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002767 }
2768
2769 if (func != NULL) {
Guido van Rossum717ce002001-09-14 16:58:08 +00002770 res = PyObject_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002771 Py_DECREF(func);
2772 if (res == NULL)
2773 return -1;
2774 return PyObject_IsTrue(res);
2775 }
2776 else {
2777 PyErr_Clear();
2778 return 1;
2779 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780}
2781
Guido van Rossumdc91b992001-08-08 22:26:22 +00002782SLOT0(slot_nb_invert, "__invert__")
2783SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2784SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2785SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2786SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2787SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002789SLOT0(slot_nb_int, "__int__")
2790SLOT0(slot_nb_long, "__long__")
2791SLOT0(slot_nb_float, "__float__")
2792SLOT0(slot_nb_oct, "__oct__")
2793SLOT0(slot_nb_hex, "__hex__")
2794SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2795SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2796SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2797SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2798SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2799SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2800SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2801SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2802SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2803SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2804SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2805SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2806 "__floordiv__", "__rfloordiv__")
2807SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2808SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2809SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810
2811static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002812half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002813{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002814 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002815 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002816 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817
Guido van Rossum60718732001-08-28 17:47:51 +00002818 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002819 if (func == NULL) {
2820 PyErr_Clear();
2821 }
2822 else {
2823 args = Py_BuildValue("(O)", other);
2824 if (args == NULL)
2825 res = NULL;
2826 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002827 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002828 Py_DECREF(args);
2829 }
2830 if (res != Py_NotImplemented) {
2831 if (res == NULL)
2832 return -2;
2833 c = PyInt_AsLong(res);
2834 Py_DECREF(res);
2835 if (c == -1 && PyErr_Occurred())
2836 return -2;
2837 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2838 }
2839 Py_DECREF(res);
2840 }
2841 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002842}
2843
Guido van Rossumab3b0342001-09-18 20:38:53 +00002844/* This slot is published for the benefit of try_3way_compare in object.c */
2845int
2846_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00002847{
2848 int c;
2849
Guido van Rossumab3b0342001-09-18 20:38:53 +00002850 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002851 c = half_compare(self, other);
2852 if (c <= 1)
2853 return c;
2854 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00002855 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002856 c = half_compare(other, self);
2857 if (c < -1)
2858 return -2;
2859 if (c <= 1)
2860 return -c;
2861 }
2862 return (void *)self < (void *)other ? -1 :
2863 (void *)self > (void *)other ? 1 : 0;
2864}
2865
2866static PyObject *
2867slot_tp_repr(PyObject *self)
2868{
2869 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002870 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002871
Guido van Rossum60718732001-08-28 17:47:51 +00002872 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002873 if (func != NULL) {
2874 res = PyEval_CallObject(func, NULL);
2875 Py_DECREF(func);
2876 return res;
2877 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00002878 PyErr_Clear();
2879 return PyString_FromFormat("<%s object at %p>",
2880 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002881}
2882
2883static PyObject *
2884slot_tp_str(PyObject *self)
2885{
2886 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002887 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002888
Guido van Rossum60718732001-08-28 17:47:51 +00002889 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002890 if (func != NULL) {
2891 res = PyEval_CallObject(func, NULL);
2892 Py_DECREF(func);
2893 return res;
2894 }
2895 else {
2896 PyErr_Clear();
2897 return slot_tp_repr(self);
2898 }
2899}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900
2901static long
2902slot_tp_hash(PyObject *self)
2903{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002904 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002905 static PyObject *hash_str, *eq_str, *cmp_str;
2906
Tim Peters6d6c1a32001-08-02 04:15:00 +00002907 long h;
2908
Guido van Rossum60718732001-08-28 17:47:51 +00002909 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002910
2911 if (func != NULL) {
2912 res = PyEval_CallObject(func, NULL);
2913 Py_DECREF(func);
2914 if (res == NULL)
2915 return -1;
2916 h = PyInt_AsLong(res);
2917 }
2918 else {
2919 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002920 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002921 if (func == NULL) {
2922 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002923 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002924 }
2925 if (func != NULL) {
2926 Py_DECREF(func);
2927 PyErr_SetString(PyExc_TypeError, "unhashable type");
2928 return -1;
2929 }
2930 PyErr_Clear();
2931 h = _Py_HashPointer((void *)self);
2932 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002933 if (h == -1 && !PyErr_Occurred())
2934 h = -2;
2935 return h;
2936}
2937
2938static PyObject *
2939slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2940{
Guido van Rossum60718732001-08-28 17:47:51 +00002941 static PyObject *call_str;
2942 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002943 PyObject *res;
2944
2945 if (meth == NULL)
2946 return NULL;
2947 res = PyObject_Call(meth, args, kwds);
2948 Py_DECREF(meth);
2949 return res;
2950}
2951
Tim Peters6d6c1a32001-08-02 04:15:00 +00002952static PyObject *
2953slot_tp_getattro(PyObject *self, PyObject *name)
2954{
2955 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002957 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002958
Guido van Rossum8e248182001-08-12 05:17:56 +00002959 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002960 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00002961 if (getattr_str == NULL)
2962 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002963 }
Guido van Rossum8e248182001-08-12 05:17:56 +00002964 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00002965 if (getattr == NULL) {
2966 /* Avoid further slowdowns */
2967 if (tp->tp_getattro == slot_tp_getattro)
2968 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002969 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00002970 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002971 return PyObject_CallFunction(getattr, "OO", self, name);
2972}
2973
Guido van Rossum19c1cd52001-09-21 21:24:49 +00002974static PyObject *
2975slot_tp_getattr_hook(PyObject *self, PyObject *name)
2976{
2977 PyTypeObject *tp = self->ob_type;
2978 PyObject *getattr, *getattribute, *res;
2979 static PyObject *getattribute_str = NULL;
2980 static PyObject *getattr_str = NULL;
2981
2982 if (getattr_str == NULL) {
2983 getattr_str = PyString_InternFromString("__getattr__");
2984 if (getattr_str == NULL)
2985 return NULL;
2986 }
2987 if (getattribute_str == NULL) {
2988 getattribute_str =
2989 PyString_InternFromString("__getattribute__");
2990 if (getattribute_str == NULL)
2991 return NULL;
2992 }
2993 getattr = _PyType_Lookup(tp, getattr_str);
2994 getattribute = _PyType_Lookup(tp, getattribute_str);
2995 if (getattr == NULL && getattribute == NULL) {
2996 /* Avoid further slowdowns */
2997 if (tp->tp_getattro == slot_tp_getattr_hook)
2998 tp->tp_getattro = PyObject_GenericGetAttr;
2999 return PyObject_GenericGetAttr(self, name);
3000 }
3001 if (getattribute == NULL)
3002 res = PyObject_GenericGetAttr(self, name);
3003 else
3004 res = PyObject_CallFunction(getattribute, "OO", self, name);
3005 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
3006 PyErr_Clear();
3007 res = PyObject_CallFunction(getattr, "OO", self, name);
3008 }
3009 return res;
3010}
3011
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012static int
3013slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3014{
3015 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003016 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003017
3018 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003019 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003020 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003021 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003022 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003023 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003024 if (res == NULL)
3025 return -1;
3026 Py_DECREF(res);
3027 return 0;
3028}
3029
3030/* Map rich comparison operators to their __xx__ namesakes */
3031static char *name_op[] = {
3032 "__lt__",
3033 "__le__",
3034 "__eq__",
3035 "__ne__",
3036 "__gt__",
3037 "__ge__",
3038};
3039
3040static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003041half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003043 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003044 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045
Guido van Rossum60718732001-08-28 17:47:51 +00003046 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003047 if (func == NULL) {
3048 PyErr_Clear();
3049 Py_INCREF(Py_NotImplemented);
3050 return Py_NotImplemented;
3051 }
3052 args = Py_BuildValue("(O)", other);
3053 if (args == NULL)
3054 res = NULL;
3055 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003056 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003057 Py_DECREF(args);
3058 }
3059 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003060 return res;
3061}
3062
Guido van Rossumb8f63662001-08-15 23:57:02 +00003063/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3064static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3065
3066static PyObject *
3067slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3068{
3069 PyObject *res;
3070
3071 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3072 res = half_richcompare(self, other, op);
3073 if (res != Py_NotImplemented)
3074 return res;
3075 Py_DECREF(res);
3076 }
3077 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3078 res = half_richcompare(other, self, swapped_op[op]);
3079 if (res != Py_NotImplemented) {
3080 return res;
3081 }
3082 Py_DECREF(res);
3083 }
3084 Py_INCREF(Py_NotImplemented);
3085 return Py_NotImplemented;
3086}
3087
3088static PyObject *
3089slot_tp_iter(PyObject *self)
3090{
3091 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003092 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003093
Guido van Rossum60718732001-08-28 17:47:51 +00003094 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003095 if (func != NULL) {
3096 res = PyObject_CallObject(func, NULL);
3097 Py_DECREF(func);
3098 return res;
3099 }
3100 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003101 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003102 if (func == NULL) {
3103 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
3104 return NULL;
3105 }
3106 Py_DECREF(func);
3107 return PySeqIter_New(self);
3108}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109
3110static PyObject *
3111slot_tp_iternext(PyObject *self)
3112{
Guido van Rossum2730b132001-08-28 18:22:14 +00003113 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003114 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115}
3116
Guido van Rossum1a493502001-08-17 16:47:50 +00003117static PyObject *
3118slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3119{
3120 PyTypeObject *tp = self->ob_type;
3121 PyObject *get;
3122 static PyObject *get_str = NULL;
3123
3124 if (get_str == NULL) {
3125 get_str = PyString_InternFromString("__get__");
3126 if (get_str == NULL)
3127 return NULL;
3128 }
3129 get = _PyType_Lookup(tp, get_str);
3130 if (get == NULL) {
3131 /* Avoid further slowdowns */
3132 if (tp->tp_descr_get == slot_tp_descr_get)
3133 tp->tp_descr_get = NULL;
3134 Py_INCREF(self);
3135 return self;
3136 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003137 if (obj == NULL)
3138 obj = Py_None;
3139 if (type == NULL)
3140 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003141 return PyObject_CallFunction(get, "OOO", self, obj, type);
3142}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003143
3144static int
3145slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3146{
Guido van Rossum2c252392001-08-24 10:13:31 +00003147 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003148 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003149
3150 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003151 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003152 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003153 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003154 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003155 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003156 if (res == NULL)
3157 return -1;
3158 Py_DECREF(res);
3159 return 0;
3160}
3161
3162static int
3163slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3164{
Guido van Rossum60718732001-08-28 17:47:51 +00003165 static PyObject *init_str;
3166 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003167 PyObject *res;
3168
3169 if (meth == NULL)
3170 return -1;
3171 res = PyObject_Call(meth, args, kwds);
3172 Py_DECREF(meth);
3173 if (res == NULL)
3174 return -1;
3175 Py_DECREF(res);
3176 return 0;
3177}
3178
3179static PyObject *
3180slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3181{
3182 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3183 PyObject *newargs, *x;
3184 int i, n;
3185
3186 if (func == NULL)
3187 return NULL;
3188 assert(PyTuple_Check(args));
3189 n = PyTuple_GET_SIZE(args);
3190 newargs = PyTuple_New(n+1);
3191 if (newargs == NULL)
3192 return NULL;
3193 Py_INCREF(type);
3194 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3195 for (i = 0; i < n; i++) {
3196 x = PyTuple_GET_ITEM(args, i);
3197 Py_INCREF(x);
3198 PyTuple_SET_ITEM(newargs, i+1, x);
3199 }
3200 x = PyObject_Call(func, newargs, kwds);
3201 Py_DECREF(func);
3202 return x;
3203}
3204
Guido van Rossumf040ede2001-08-07 16:40:56 +00003205/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003206 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003207 The dict argument is the dictionary argument passed to type_new(),
3208 which is the local namespace of the class statement, in other
3209 words, it contains the methods. For each special method (like
3210 __repr__) defined in the dictionary, the corresponding function
3211 slot in the type object (like tp_repr) is set to a special function
3212 whose name is 'slot_' followed by the slot name and whose signature
3213 is whatever is required for that slot. These slot functions look
3214 up the corresponding method in the type's dictionary and call it.
3215 The slot functions have to take care of the various peculiarities
3216 of the mapping between slots and special methods, such as mapping
3217 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3218 etc.) or mapping multiple slots to a single method (sq_item,
3219 mp_subscript <--> __getitem__). */
3220
Tim Peters6d6c1a32001-08-02 04:15:00 +00003221static void
3222override_slots(PyTypeObject *type, PyObject *dict)
3223{
3224 PySequenceMethods *sq = type->tp_as_sequence;
3225 PyMappingMethods *mp = type->tp_as_mapping;
3226 PyNumberMethods *nb = type->tp_as_number;
3227
Guido van Rossumdc91b992001-08-08 22:26:22 +00003228#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003229 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003230 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003231 }
3232
Guido van Rossumdc91b992001-08-08 22:26:22 +00003233#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003234 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003235 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003236 }
3237
Guido van Rossumdc91b992001-08-08 22:26:22 +00003238#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003239 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003240 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003241 }
3242
Guido van Rossumdc91b992001-08-08 22:26:22 +00003243#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003244 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003245 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003246 }
3247
Guido van Rossumdc91b992001-08-08 22:26:22 +00003248 SQSLOT("__len__", sq_length, slot_sq_length);
3249 SQSLOT("__add__", sq_concat, slot_sq_concat);
3250 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3251 SQSLOT("__getitem__", sq_item, slot_sq_item);
3252 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3253 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3254 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3255 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3256 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3257 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3258 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3259 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003260
Guido van Rossumdc91b992001-08-08 22:26:22 +00003261 MPSLOT("__len__", mp_length, slot_mp_length);
3262 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3263 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3264 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003265
Guido van Rossumdc91b992001-08-08 22:26:22 +00003266 NBSLOT("__add__", nb_add, slot_nb_add);
3267 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3268 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3269 NBSLOT("__div__", nb_divide, slot_nb_divide);
3270 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3271 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3272 NBSLOT("__pow__", nb_power, slot_nb_power);
3273 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3274 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3275 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3276 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3277 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3278 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3279 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3280 NBSLOT("__and__", nb_and, slot_nb_and);
3281 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3282 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003283 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00003284 NBSLOT("__int__", nb_int, slot_nb_int);
3285 NBSLOT("__long__", nb_long, slot_nb_long);
3286 NBSLOT("__float__", nb_float, slot_nb_float);
3287 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3288 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3289 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3290 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3291 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3292 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3293 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3294 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3295 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3296 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3297 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3298 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3299 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3300 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3301 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3302 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3303 slot_nb_inplace_floor_divide);
3304 NBSLOT("__itruediv__", nb_inplace_true_divide,
3305 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003306
Guido van Rossum8e248182001-08-12 05:17:56 +00003307 if (dict == NULL ||
3308 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003309 PyDict_GetItemString(dict, "__repr__"))
3310 type->tp_print = NULL;
3311
Guido van Rossumab3b0342001-09-18 20:38:53 +00003312 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003313 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3314 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3315 TPSLOT("__call__", tp_call, slot_tp_call);
3316 TPSLOT("__str__", tp_str, slot_tp_str);
Guido van Rossum867a8d22001-09-21 19:29:08 +00003317 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003318 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003319 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3320 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3321 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3322 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3323 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3324 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3325 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3326 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3327 TPSLOT("next", tp_iternext, slot_tp_iternext);
3328 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3329 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3330 TPSLOT("__init__", tp_init, slot_tp_init);
3331 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003332}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003333
3334
3335/* Cooperative 'super' */
3336
3337typedef struct {
3338 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003339 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003340 PyObject *obj;
3341} superobject;
3342
Guido van Rossum6f799372001-09-20 20:46:19 +00003343static PyMemberDef super_members[] = {
3344 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3345 "the class invoking super()"},
3346 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3347 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003348 {0}
3349};
3350
Guido van Rossum705f0f52001-08-24 16:47:00 +00003351static void
3352super_dealloc(PyObject *self)
3353{
3354 superobject *su = (superobject *)self;
3355
3356 Py_XDECREF(su->obj);
3357 Py_XDECREF(su->type);
3358 self->ob_type->tp_free(self);
3359}
3360
3361static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003362super_repr(PyObject *self)
3363{
3364 superobject *su = (superobject *)self;
3365
3366 if (su->obj)
3367 return PyString_FromFormat(
3368 "<super: <type '%s'>, <%s object>>",
3369 su->type ? su->type->tp_name : "NULL",
3370 su->obj->ob_type->tp_name);
3371 else
3372 return PyString_FromFormat(
3373 "<super: <type '%s'>, NULL>",
3374 su->type ? su->type->tp_name : "NULL");
3375}
3376
3377static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003378super_getattro(PyObject *self, PyObject *name)
3379{
3380 superobject *su = (superobject *)self;
3381
3382 if (su->obj != NULL) {
3383 PyObject *mro, *res, *tmp;
3384 descrgetfunc f;
3385 int i, n;
3386
Guido van Rossume705ef12001-08-29 15:47:06 +00003387 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003388 if (mro == NULL)
3389 n = 0;
3390 else {
3391 assert(PyTuple_Check(mro));
3392 n = PyTuple_GET_SIZE(mro);
3393 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003394 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003395 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003396 break;
3397 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003398 if (i >= n && PyType_Check(su->obj)) {
3399 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003400 if (mro == NULL)
3401 n = 0;
3402 else {
3403 assert(PyTuple_Check(mro));
3404 n = PyTuple_GET_SIZE(mro);
3405 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003406 for (i = 0; i < n; i++) {
3407 if ((PyObject *)(su->type) ==
3408 PyTuple_GET_ITEM(mro, i))
3409 break;
3410 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003411 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003412 i++;
3413 res = NULL;
3414 for (; i < n; i++) {
3415 tmp = PyTuple_GET_ITEM(mro, i);
3416 assert(PyType_Check(tmp));
3417 res = PyDict_GetItem(
3418 ((PyTypeObject *)tmp)->tp_defined, name);
3419 if (res != NULL) {
3420 Py_INCREF(res);
3421 f = res->ob_type->tp_descr_get;
3422 if (f != NULL) {
3423 tmp = f(res, su->obj, res);
3424 Py_DECREF(res);
3425 res = tmp;
3426 }
3427 return res;
3428 }
3429 }
3430 }
3431 return PyObject_GenericGetAttr(self, name);
3432}
3433
3434static PyObject *
3435super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3436{
3437 superobject *su = (superobject *)self;
3438 superobject *new;
3439
3440 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3441 /* Not binding to an object, or already bound */
3442 Py_INCREF(self);
3443 return self;
3444 }
3445 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3446 if (new == NULL)
3447 return NULL;
3448 Py_INCREF(su->type);
3449 Py_INCREF(obj);
3450 new->type = su->type;
3451 new->obj = obj;
3452 return (PyObject *)new;
3453}
3454
3455static int
3456super_init(PyObject *self, PyObject *args, PyObject *kwds)
3457{
3458 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003459 PyTypeObject *type;
3460 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003461
3462 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3463 return -1;
3464 if (obj == Py_None)
3465 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003466 if (obj != NULL &&
3467 !PyType_IsSubtype(obj->ob_type, type) &&
3468 !(PyType_Check(obj) &&
3469 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003470 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003471 "super(type, obj): "
3472 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003473 return -1;
3474 }
3475 Py_INCREF(type);
3476 Py_XINCREF(obj);
3477 su->type = type;
3478 su->obj = obj;
3479 return 0;
3480}
3481
3482static char super_doc[] =
3483"super(type) -> unbound super object\n"
3484"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003485"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003486"Typical use to call a cooperative superclass method:\n"
3487"class C(B):\n"
3488" def meth(self, arg):\n"
3489" super(C, self).meth(arg)";
3490
3491PyTypeObject PySuper_Type = {
3492 PyObject_HEAD_INIT(&PyType_Type)
3493 0, /* ob_size */
3494 "super", /* tp_name */
3495 sizeof(superobject), /* tp_basicsize */
3496 0, /* tp_itemsize */
3497 /* methods */
3498 super_dealloc, /* tp_dealloc */
3499 0, /* tp_print */
3500 0, /* tp_getattr */
3501 0, /* tp_setattr */
3502 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003503 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003504 0, /* tp_as_number */
3505 0, /* tp_as_sequence */
3506 0, /* tp_as_mapping */
3507 0, /* tp_hash */
3508 0, /* tp_call */
3509 0, /* tp_str */
3510 super_getattro, /* tp_getattro */
3511 0, /* tp_setattro */
3512 0, /* tp_as_buffer */
Guido van Rossum31bcff82001-08-30 04:37:15 +00003513 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003514 super_doc, /* tp_doc */
3515 0, /* tp_traverse */
3516 0, /* tp_clear */
3517 0, /* tp_richcompare */
3518 0, /* tp_weaklistoffset */
3519 0, /* tp_iter */
3520 0, /* tp_iternext */
3521 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003522 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003523 0, /* tp_getset */
3524 0, /* tp_base */
3525 0, /* tp_dict */
3526 super_descr_get, /* tp_descr_get */
3527 0, /* tp_descr_set */
3528 0, /* tp_dictoffset */
3529 super_init, /* tp_init */
3530 PyType_GenericAlloc, /* tp_alloc */
3531 PyType_GenericNew, /* tp_new */
3532 _PyObject_Del, /* tp_free */
3533};