blob: 984b5829ba0f8bbde0eda061f72564bff689ec4a [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Type object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Tim Peters6d6c1a32001-08-02 04:15:00 +00007static struct memberlist type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00008 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
9 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
10 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
11 {"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
17 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
18 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
25 char *s;
26
27 s = strrchr(type->tp_name, '.');
28 if (s == NULL)
29 s = type->tp_name;
30 else
31 s++;
32 return PyString_FromString(s);
33}
34
35static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000036type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000037{
Guido van Rossumc3542212001-08-16 09:18:56 +000038 PyObject *mod;
39 char *s;
40
41 s = strrchr(type->tp_name, '.');
42 if (s != NULL)
43 return PyString_FromStringAndSize(type->tp_name,
44 (int)(s - type->tp_name));
45 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
46 return PyString_FromString("__builtin__");
47 mod = PyDict_GetItemString(type->tp_defined, "__module__");
48 if (mod != NULL && PyString_Check(mod)) {
49 Py_INCREF(mod);
50 return mod;
51 }
52 PyErr_SetString(PyExc_AttributeError, "__module__");
53 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000054}
55
56static PyObject *
57type_dict(PyTypeObject *type, void *context)
58{
59 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000060 Py_INCREF(Py_None);
61 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000062 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000063 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
64 Py_INCREF(type->tp_dict);
65 return type->tp_dict;
66 }
67 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000068}
69
Tim Peters6d6c1a32001-08-02 04:15:00 +000070static PyObject *
71type_defined(PyTypeObject *type, void *context)
72{
73 if (type->tp_defined == NULL) {
74 Py_INCREF(Py_None);
75 return Py_None;
76 }
77 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
78 Py_INCREF(type->tp_defined);
79 return type->tp_defined;
80 }
81 return PyDictProxy_New(type->tp_defined);
82}
83
84static PyObject *
85type_dynamic(PyTypeObject *type, void *context)
86{
87 PyObject *res;
88
89 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
90 Py_INCREF(res);
91 return res;
92}
93
94struct getsetlist type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000095 {"__name__", (getter)type_name, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000096 {"__module__", (getter)type_module, NULL, NULL},
97 {"__dict__", (getter)type_dict, NULL, NULL},
98 {"__defined__", (getter)type_defined, NULL, NULL},
99 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
100 {0}
101};
102
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000103static int
104type_compare(PyObject *v, PyObject *w)
105{
106 /* This is called with type objects only. So we
107 can just compare the addresses. */
108 Py_uintptr_t vv = (Py_uintptr_t)v;
109 Py_uintptr_t ww = (Py_uintptr_t)w;
110 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
111}
112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000114type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000115{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000116 PyObject *mod, *name, *rtn;
Guido van Rossumc3542212001-08-16 09:18:56 +0000117
118 mod = type_module(type, NULL);
119 if (mod == NULL)
120 PyErr_Clear();
121 else if (!PyString_Check(mod)) {
122 Py_DECREF(mod);
123 mod = NULL;
124 }
125 name = type_name(type, NULL);
126 if (name == NULL)
127 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000128
129 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
130 rtn = PyString_FromFormat("<type '%s.%s'>",
131 PyString_AS_STRING(mod),
132 PyString_AS_STRING(name));
133 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000134 else
Barry Warsaw7ce36942001-08-24 18:34:26 +0000135 rtn = PyString_FromFormat("<type '%s'>", type->tp_name);
136
Guido van Rossumc3542212001-08-16 09:18:56 +0000137 Py_XDECREF(mod);
138 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000139 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140}
141
Tim Peters6d6c1a32001-08-02 04:15:00 +0000142static PyObject *
143type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
144{
145 PyObject *obj;
146
147 if (type->tp_new == NULL) {
148 PyErr_Format(PyExc_TypeError,
149 "cannot create '%.100s' instances",
150 type->tp_name);
151 return NULL;
152 }
153
154 obj = type->tp_new(type, args, NULL);
155 if (obj != NULL) {
156 type = obj->ob_type;
157 if (type->tp_init != NULL &&
158 type->tp_init(obj, args, kwds) < 0) {
159 Py_DECREF(obj);
160 obj = NULL;
161 }
162 }
163 return obj;
164}
165
166PyObject *
167PyType_GenericAlloc(PyTypeObject *type, int nitems)
168{
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000169#define PTRSIZE (sizeof(PyObject *))
170
Tim Peters6d6c1a32001-08-02 04:15:00 +0000171 int size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000172 PyObject *obj;
173
174 /* Inline PyObject_New() so we can zero the memory */
175 size = _PyObject_VAR_SIZE(type, nitems);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000176 /* Round up size, if necessary, so we fully zero out __dict__ */
177 if (type->tp_itemsize % PTRSIZE != 0) {
178 size += PTRSIZE - 1;
179 size /= PTRSIZE;
180 size *= PTRSIZE;
181 }
Neil Schemenauerc806c882001-08-29 23:54:54 +0000182 if (PyType_IS_GC(type)) {
183 obj = _PyObject_GC_Malloc(type, nitems);
184 }
185 else {
186 obj = PyObject_MALLOC(size);
187 }
188 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000189 return PyErr_NoMemory();
Neil Schemenauerc806c882001-08-29 23:54:54 +0000190 memset(obj, '\0', size);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000191 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
192 Py_INCREF(type);
193 if (type->tp_itemsize == 0)
194 PyObject_INIT(obj, type);
195 else
196 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
197 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000198 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000199 return obj;
200}
201
202PyObject *
203PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
204{
205 return type->tp_alloc(type, 0);
206}
207
208/* Helper for subtyping */
209
210static void
211subtype_dealloc(PyObject *self)
212{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000213 PyTypeObject *type, *base;
214 destructor f;
215
216 /* This exists so we can DECREF self->ob_type */
217
218 /* Find the nearest base with a different tp_dealloc */
219 type = self->ob_type;
220 base = type->tp_base;
221 while ((f = base->tp_dealloc) == subtype_dealloc) {
222 base = base->tp_base;
223 assert(base);
224 }
225
226 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000227 if (type->tp_dictoffset && !base->tp_dictoffset) {
228 PyObject **dictptr = _PyObject_GetDictPtr(self);
229 if (dictptr != NULL) {
230 PyObject *dict = *dictptr;
231 if (dict != NULL) {
232 Py_DECREF(dict);
233 *dictptr = NULL;
234 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000235 }
236 }
237
Guido van Rossum9676b222001-08-17 20:32:36 +0000238 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000239 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000240 PyObject_ClearWeakRefs(self);
241
Tim Peters6d6c1a32001-08-02 04:15:00 +0000242 /* Finalize GC if the base doesn't do GC and we do */
243 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
244 PyObject_GC_Fini(self);
245
246 /* Call the base tp_dealloc() */
247 assert(f);
248 f(self);
249
250 /* Can't reference self beyond this point */
251 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
252 Py_DECREF(type);
253 }
254}
255
256staticforward void override_slots(PyTypeObject *type, PyObject *dict);
257staticforward PyTypeObject *solid_base(PyTypeObject *type);
258
259typedef struct {
260 PyTypeObject type;
261 PyNumberMethods as_number;
262 PySequenceMethods as_sequence;
263 PyMappingMethods as_mapping;
264 PyBufferProcs as_buffer;
265 PyObject *name, *slots;
266 struct memberlist members[1];
267} etype;
268
269/* type test with subclassing support */
270
271int
272PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
273{
274 PyObject *mro;
275
276 mro = a->tp_mro;
277 if (mro != NULL) {
278 /* Deal with multiple inheritance without recursion
279 by walking the MRO tuple */
280 int i, n;
281 assert(PyTuple_Check(mro));
282 n = PyTuple_GET_SIZE(mro);
283 for (i = 0; i < n; i++) {
284 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
285 return 1;
286 }
287 return 0;
288 }
289 else {
290 /* a is not completely initilized yet; follow tp_base */
291 do {
292 if (a == b)
293 return 1;
294 a = a->tp_base;
295 } while (a != NULL);
296 return b == &PyBaseObject_Type;
297 }
298}
299
Guido van Rossum60718732001-08-28 17:47:51 +0000300/* Internal routine to do a method lookup in the type
301 without looking in the instance dictionary
302 (so we can't use PyObject_GetAttr) but still binding
303 it to the instance. The arguments are the object,
304 the method name as a C string, and the address of a
305 static variable used to cache the interned Python string. */
306
307static PyObject *
308lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
309{
310 PyObject *res;
311
312 if (*attrobj == NULL) {
313 *attrobj = PyString_InternFromString(attrstr);
314 if (*attrobj == NULL)
315 return NULL;
316 }
317 res = _PyType_Lookup(self->ob_type, *attrobj);
318 if (res == NULL)
319 PyErr_SetObject(PyExc_AttributeError, *attrobj);
320 else {
321 descrgetfunc f;
322 if ((f = res->ob_type->tp_descr_get) == NULL)
323 Py_INCREF(res);
324 else
325 res = f(res, self, (PyObject *)(self->ob_type));
326 }
327 return res;
328}
329
Guido van Rossum2730b132001-08-28 18:22:14 +0000330/* A variation of PyObject_CallMethod that uses lookup_method()
331 instead of PyObject_GetAttrString(). This uses the same convention
332 as lookup_method to cache the interned name string object. */
333
334PyObject *
335call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
336{
337 va_list va;
338 PyObject *args, *func = 0, *retval;
339 PyObject *dummy_str = NULL;
340 va_start(va, format);
341
342 func = lookup_method(o, name, &dummy_str);
343 Py_XDECREF(dummy_str);
344 if (func == NULL) {
345 va_end(va);
346 PyErr_SetString(PyExc_AttributeError, name);
347 return 0;
348 }
349
350 if (format && *format)
351 args = Py_VaBuildValue(format, va);
352 else
353 args = PyTuple_New(0);
354
355 va_end(va);
356
357 if (!args)
358 return NULL;
359
360 if (!PyTuple_Check(args)) {
361 PyObject *a;
362
363 a = PyTuple_New(1);
364 if (a == NULL)
365 return NULL;
366 if (PyTuple_SetItem(a, 0, args) < 0)
367 return NULL;
368 args = a;
369 }
370
371 retval = PyObject_CallObject(func, args);
372
373 Py_DECREF(args);
374 Py_DECREF(func);
375
376 return retval;
377}
378
Tim Peters6d6c1a32001-08-02 04:15:00 +0000379/* Method resolution order algorithm from "Putting Metaclasses to Work"
380 by Forman and Danforth (Addison-Wesley 1999). */
381
382static int
383conservative_merge(PyObject *left, PyObject *right)
384{
385 int left_size;
386 int right_size;
387 int i, j, r, ok;
388 PyObject *temp, *rr;
389
390 assert(PyList_Check(left));
391 assert(PyList_Check(right));
392
393 again:
394 left_size = PyList_GET_SIZE(left);
395 right_size = PyList_GET_SIZE(right);
396 for (i = 0; i < left_size; i++) {
397 for (j = 0; j < right_size; j++) {
398 if (PyList_GET_ITEM(left, i) ==
399 PyList_GET_ITEM(right, j)) {
400 /* found a merge point */
401 temp = PyList_New(0);
402 if (temp == NULL)
403 return -1;
404 for (r = 0; r < j; r++) {
405 rr = PyList_GET_ITEM(right, r);
406 ok = PySequence_Contains(left, rr);
407 if (ok < 0) {
408 Py_DECREF(temp);
409 return -1;
410 }
411 if (!ok) {
412 ok = PyList_Append(temp, rr);
413 if (ok < 0) {
414 Py_DECREF(temp);
415 return -1;
416 }
417 }
418 }
419 ok = PyList_SetSlice(left, i, i, temp);
420 Py_DECREF(temp);
421 if (ok < 0)
422 return -1;
423 ok = PyList_SetSlice(right, 0, j+1, NULL);
424 if (ok < 0)
425 return -1;
426 goto again;
427 }
428 }
429 }
430 return PyList_SetSlice(left, left_size, left_size, right);
431}
432
433static int
434serious_order_disagreements(PyObject *left, PyObject *right)
435{
436 return 0; /* XXX later -- for now, we cheat: "don't do that" */
437}
438
439static PyObject *
440mro_implementation(PyTypeObject *type)
441{
442 int i, n, ok;
443 PyObject *bases, *result;
444
445 bases = type->tp_bases;
446 n = PyTuple_GET_SIZE(bases);
447 result = Py_BuildValue("[O]", (PyObject *)type);
448 if (result == NULL)
449 return NULL;
450 for (i = 0; i < n; i++) {
451 PyTypeObject *base =
452 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
453 PyObject *parentMRO = PySequence_List(base->tp_mro);
454 if (parentMRO == NULL) {
455 Py_DECREF(result);
456 return NULL;
457 }
458 if (serious_order_disagreements(result, parentMRO)) {
459 Py_DECREF(result);
460 return NULL;
461 }
462 ok = conservative_merge(result, parentMRO);
463 Py_DECREF(parentMRO);
464 if (ok < 0) {
465 Py_DECREF(result);
466 return NULL;
467 }
468 }
469 return result;
470}
471
472static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000473mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000474{
475 PyTypeObject *type = (PyTypeObject *)self;
476
Tim Peters6d6c1a32001-08-02 04:15:00 +0000477 return mro_implementation(type);
478}
479
480static int
481mro_internal(PyTypeObject *type)
482{
483 PyObject *mro, *result, *tuple;
484
485 if (type->ob_type == &PyType_Type) {
486 result = mro_implementation(type);
487 }
488 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000489 static PyObject *mro_str;
490 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000491 if (mro == NULL)
492 return -1;
493 result = PyObject_CallObject(mro, NULL);
494 Py_DECREF(mro);
495 }
496 if (result == NULL)
497 return -1;
498 tuple = PySequence_Tuple(result);
499 Py_DECREF(result);
500 type->tp_mro = tuple;
501 return 0;
502}
503
504
505/* Calculate the best base amongst multiple base classes.
506 This is the first one that's on the path to the "solid base". */
507
508static PyTypeObject *
509best_base(PyObject *bases)
510{
511 int i, n;
512 PyTypeObject *base, *winner, *candidate, *base_i;
513
514 assert(PyTuple_Check(bases));
515 n = PyTuple_GET_SIZE(bases);
516 assert(n > 0);
517 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
518 winner = &PyBaseObject_Type;
519 for (i = 0; i < n; i++) {
520 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
521 if (!PyType_Check((PyObject *)base_i)) {
522 PyErr_SetString(
523 PyExc_TypeError,
524 "bases must be types");
525 return NULL;
526 }
527 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000528 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000529 return NULL;
530 }
531 candidate = solid_base(base_i);
532 if (PyType_IsSubtype(winner, candidate))
533 ;
534 else if (PyType_IsSubtype(candidate, winner)) {
535 winner = candidate;
536 base = base_i;
537 }
538 else {
539 PyErr_SetString(
540 PyExc_TypeError,
541 "multiple bases have "
542 "instance lay-out conflict");
543 return NULL;
544 }
545 }
546 assert(base != NULL);
547 return base;
548}
549
550static int
551extra_ivars(PyTypeObject *type, PyTypeObject *base)
552{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000553 size_t t_size = type->tp_basicsize;
554 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000555
Guido van Rossum9676b222001-08-17 20:32:36 +0000556 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000557 if (type->tp_itemsize || base->tp_itemsize) {
558 /* If itemsize is involved, stricter rules */
559 return t_size != b_size ||
560 type->tp_itemsize != base->tp_itemsize;
561 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000562 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
563 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
564 t_size -= sizeof(PyObject *);
565 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
566 type->tp_dictoffset + sizeof(PyObject *) == t_size)
567 t_size -= sizeof(PyObject *);
568
569 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000570}
571
572static PyTypeObject *
573solid_base(PyTypeObject *type)
574{
575 PyTypeObject *base;
576
577 if (type->tp_base)
578 base = solid_base(type->tp_base);
579 else
580 base = &PyBaseObject_Type;
581 if (extra_ivars(type, base))
582 return type;
583 else
584 return base;
585}
586
587staticforward void object_dealloc(PyObject *);
588staticforward int object_init(PyObject *, PyObject *, PyObject *);
589
590static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000591subtype_dict(PyObject *obj, void *context)
592{
593 PyObject **dictptr = _PyObject_GetDictPtr(obj);
594 PyObject *dict;
595
596 if (dictptr == NULL) {
597 PyErr_SetString(PyExc_AttributeError,
598 "This object has no __dict__");
599 return NULL;
600 }
601 dict = *dictptr;
602 if (dict == NULL) {
603 Py_INCREF(Py_None);
604 return Py_None;
605 }
606 else {
607 Py_INCREF(dict);
608 return dict;
609 }
610}
611
612struct getsetlist subtype_getsets[] = {
613 {"__dict__", subtype_dict, NULL, NULL},
614 {0},
615};
616
617static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000618type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
619{
620 PyObject *name, *bases, *dict;
621 static char *kwlist[] = {"name", "bases", "dict", 0};
622 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000623 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000624 etype *et;
625 struct memberlist *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000626 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000627
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000628 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000629 if (metatype == &PyType_Type &&
630 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
631 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000632 PyObject *x = PyTuple_GET_ITEM(args, 0);
633 Py_INCREF(x->ob_type);
634 return (PyObject *) x->ob_type;
635 }
636
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000637 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
639 &name,
640 &PyTuple_Type, &bases,
641 &PyDict_Type, &dict))
642 return NULL;
643
644 /* Determine the proper metatype to deal with this,
645 and check for metatype conflicts while we're at it.
646 Note that if some other metatype wins to contract,
647 it's possible that its instances are not types. */
648 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000649 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000650 for (i = 0; i < nbases; i++) {
651 tmp = PyTuple_GET_ITEM(bases, i);
652 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000653 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000654 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000655 if (PyType_IsSubtype(tmptype, winner)) {
656 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000657 continue;
658 }
659 PyErr_SetString(PyExc_TypeError,
660 "metatype conflict among bases");
661 return NULL;
662 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000663 if (winner != metatype) {
664 if (winner->tp_new != type_new) /* Pass it to the winner */
665 return winner->tp_new(winner, args, kwds);
666 metatype = winner;
667 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000668
669 /* Adjust for empty tuple bases */
670 if (nbases == 0) {
671 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
672 if (bases == NULL)
673 return NULL;
674 nbases = 1;
675 }
676 else
677 Py_INCREF(bases);
678
679 /* XXX From here until type is allocated, "return NULL" leaks bases! */
680
681 /* Calculate best base, and check that all bases are type objects */
682 base = best_base(bases);
683 if (base == NULL)
684 return NULL;
685 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
686 PyErr_Format(PyExc_TypeError,
687 "type '%.100s' is not an acceptable base type",
688 base->tp_name);
689 return NULL;
690 }
691
Guido van Rossum1a493502001-08-17 16:47:50 +0000692 /* Should this be a dynamic class (i.e. modifiable __dict__)?
693 Look in two places for a variable named __dynamic__:
694 1) in the class dict
695 2) in the module dict (globals)
696 The first variable that is an int >= 0 is used.
697 Otherwise, a default is calculated from the base classes:
698 if any base class is dynamic, this class is dynamic; otherwise
699 it is static. */
700 dynamic = -1; /* Not yet determined */
701 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000702 tmp = PyDict_GetItemString(dict, "__dynamic__");
703 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000704 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000705 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000706 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000707 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000708 if (dynamic < 0) {
709 /* Look in the module globals */
710 tmp = PyEval_GetGlobals();
711 if (tmp != NULL) {
712 tmp = PyDict_GetItemString(tmp, "__dynamic__");
713 if (tmp != NULL) {
714 dynamic = PyInt_AsLong(tmp);
715 if (dynamic < 0)
716 PyErr_Clear();
717 }
718 }
719 }
720 if (dynamic < 0) {
721 /* Make a new class dynamic if any of its bases is
722 dynamic. This is not always the same as inheriting
723 the __dynamic__ class attribute! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000724 dynamic = 0;
725 for (i = 0; i < nbases; i++) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000726 tmptype = (PyTypeObject *)
727 PyTuple_GET_ITEM(bases, i);
728 if (tmptype->tp_flags &
729 Py_TPFLAGS_DYNAMICTYPE) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000730 dynamic = 1;
731 break;
732 }
733 }
734 }
735
736 /* Check for a __slots__ sequence variable in dict, and count it */
737 slots = PyDict_GetItemString(dict, "__slots__");
738 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000739 add_dict = 0;
740 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741 if (slots != NULL) {
742 /* Make it into a tuple */
743 if (PyString_Check(slots))
744 slots = Py_BuildValue("(O)", slots);
745 else
746 slots = PySequence_Tuple(slots);
747 if (slots == NULL)
748 return NULL;
749 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000750 if (nslots > 0 && base->tp_itemsize != 0) {
751 PyErr_Format(PyExc_TypeError,
752 "nonempty __slots__ "
753 "not supported for subtype of '%s'",
754 base->tp_name);
755 return NULL;
756 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000757 for (i = 0; i < nslots; i++) {
758 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
759 PyErr_SetString(PyExc_TypeError,
760 "__slots__ must be a sequence of strings");
761 Py_DECREF(slots);
762 return NULL;
763 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000764 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000765 }
766 }
767 if (slots == NULL && base->tp_dictoffset == 0 &&
768 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000769 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000770 add_dict++;
771 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000772 if (slots == NULL && base->tp_weaklistoffset == 0 &&
773 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000774 nslots++;
775 add_weak++;
776 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000777
778 /* XXX From here until type is safely allocated,
779 "return NULL" may leak slots! */
780
781 /* Allocate the type object */
782 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
783 if (type == NULL)
784 return NULL;
785
786 /* Keep name and slots alive in the extended type object */
787 et = (etype *)type;
788 Py_INCREF(name);
789 et->name = name;
790 et->slots = slots;
791
Guido van Rossumdc91b992001-08-08 22:26:22 +0000792 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000793 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
794 Py_TPFLAGS_BASETYPE;
795 if (dynamic)
796 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000797
798 /* It's a new-style number unless it specifically inherits any
799 old-style numeric behavior */
800 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
801 (base->tp_as_number == NULL))
802 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
803
804 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000805 type->tp_as_number = &et->as_number;
806 type->tp_as_sequence = &et->as_sequence;
807 type->tp_as_mapping = &et->as_mapping;
808 type->tp_as_buffer = &et->as_buffer;
809 type->tp_name = PyString_AS_STRING(name);
810
811 /* Set tp_base and tp_bases */
812 type->tp_bases = bases;
813 Py_INCREF(base);
814 type->tp_base = base;
815
816 /* Initialize tp_defined from passed-in dict */
817 type->tp_defined = dict = PyDict_Copy(dict);
818 if (dict == NULL) {
819 Py_DECREF(type);
820 return NULL;
821 }
822
Guido van Rossumc3542212001-08-16 09:18:56 +0000823 /* Set __module__ in the dict */
824 if (PyDict_GetItemString(dict, "__module__") == NULL) {
825 tmp = PyEval_GetGlobals();
826 if (tmp != NULL) {
827 tmp = PyDict_GetItemString(tmp, "__name__");
828 if (tmp != NULL) {
829 if (PyDict_SetItemString(dict, "__module__",
830 tmp) < 0)
831 return NULL;
832 }
833 }
834 }
835
Tim Peters6d6c1a32001-08-02 04:15:00 +0000836 /* Special-case __new__: if it's a plain function,
837 make it a static function */
838 tmp = PyDict_GetItemString(dict, "__new__");
839 if (tmp != NULL && PyFunction_Check(tmp)) {
840 tmp = PyStaticMethod_New(tmp);
841 if (tmp == NULL) {
842 Py_DECREF(type);
843 return NULL;
844 }
845 PyDict_SetItemString(dict, "__new__", tmp);
846 Py_DECREF(tmp);
847 }
848
849 /* Add descriptors for custom slots from __slots__, or for __dict__ */
850 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000851 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852 if (slots != NULL) {
853 for (i = 0; i < nslots; i++, mp++) {
854 mp->name = PyString_AS_STRING(
855 PyTuple_GET_ITEM(slots, i));
856 mp->type = T_OBJECT;
857 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000858 if (base->tp_weaklistoffset == 0 &&
859 strcmp(mp->name, "__weakref__") == 0)
860 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000861 slotoffset += sizeof(PyObject *);
862 }
863 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000864 else {
865 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000866 if (base->tp_itemsize)
867 type->tp_dictoffset = -sizeof(PyObject *);
868 else
869 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000870 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000871 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000872 }
873 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000874 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000875 type->tp_weaklistoffset = slotoffset;
876 mp->name = "__weakref__";
877 mp->type = T_OBJECT;
878 mp->offset = slotoffset;
879 mp->readonly = 1;
880 mp++;
881 slotoffset += sizeof(PyObject *);
882 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000883 }
884 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000885 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000886 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000887
888 /* Special case some slots */
889 if (type->tp_dictoffset != 0 || nslots > 0) {
890 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
891 type->tp_getattro = PyObject_GenericGetAttr;
892 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
893 type->tp_setattro = PyObject_GenericSetAttr;
894 }
895 type->tp_dealloc = subtype_dealloc;
896
897 /* Always override allocation strategy to use regular heap */
898 type->tp_alloc = PyType_GenericAlloc;
899 type->tp_free = _PyObject_Del;
900
901 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000902 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000903 Py_DECREF(type);
904 return NULL;
905 }
906
907 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +0000908 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
909 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000910
Tim Peters6d6c1a32001-08-02 04:15:00 +0000911 return (PyObject *)type;
912}
913
914/* Internal API to look for a name through the MRO.
915 This returns a borrowed reference, and doesn't set an exception! */
916PyObject *
917_PyType_Lookup(PyTypeObject *type, PyObject *name)
918{
919 int i, n;
920 PyObject *mro, *res, *dict;
921
922 /* For static types, look in tp_dict */
923 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
924 dict = type->tp_dict;
925 assert(dict && PyDict_Check(dict));
926 return PyDict_GetItem(dict, name);
927 }
928
929 /* For dynamic types, look in tp_defined of types in MRO */
930 mro = type->tp_mro;
931 assert(PyTuple_Check(mro));
932 n = PyTuple_GET_SIZE(mro);
933 for (i = 0; i < n; i++) {
934 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
935 assert(PyType_Check(type));
936 dict = type->tp_defined;
937 assert(dict && PyDict_Check(dict));
938 res = PyDict_GetItem(dict, name);
939 if (res != NULL)
940 return res;
941 }
942 return NULL;
943}
944
945/* This is similar to PyObject_GenericGetAttr(),
946 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
947static PyObject *
948type_getattro(PyTypeObject *type, PyObject *name)
949{
950 PyTypeObject *metatype = type->ob_type;
951 PyObject *descr, *res;
952 descrgetfunc f;
953
954 /* Initialize this type (we'll assume the metatype is initialized) */
955 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000956 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000957 return NULL;
958 }
959
960 /* Get a descriptor from the metatype */
961 descr = _PyType_Lookup(metatype, name);
962 f = NULL;
963 if (descr != NULL) {
964 f = descr->ob_type->tp_descr_get;
965 if (f != NULL && PyDescr_IsData(descr))
966 return f(descr,
967 (PyObject *)type, (PyObject *)metatype);
968 }
969
970 /* Look in tp_defined of this type and its bases */
971 res = _PyType_Lookup(type, name);
972 if (res != NULL) {
973 f = res->ob_type->tp_descr_get;
974 if (f != NULL)
975 return f(res, (PyObject *)NULL, (PyObject *)type);
976 Py_INCREF(res);
977 return res;
978 }
979
980 /* Use the descriptor from the metatype */
981 if (f != NULL) {
982 res = f(descr, (PyObject *)type, (PyObject *)metatype);
983 return res;
984 }
985 if (descr != NULL) {
986 Py_INCREF(descr);
987 return descr;
988 }
989
990 /* Give up */
991 PyErr_Format(PyExc_AttributeError,
992 "type object '%.50s' has no attribute '%.400s'",
993 type->tp_name, PyString_AS_STRING(name));
994 return NULL;
995}
996
997static int
998type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
999{
1000 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
1001 return PyObject_GenericSetAttr((PyObject *)type, name, value);
1002 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
1003 return -1;
1004}
1005
1006static void
1007type_dealloc(PyTypeObject *type)
1008{
1009 etype *et;
1010
1011 /* Assert this is a heap-allocated type object */
1012 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
1013 et = (etype *)type;
1014 Py_XDECREF(type->tp_base);
1015 Py_XDECREF(type->tp_dict);
1016 Py_XDECREF(type->tp_bases);
1017 Py_XDECREF(type->tp_mro);
1018 Py_XDECREF(type->tp_defined);
1019 /* XXX more? */
1020 Py_XDECREF(et->name);
1021 Py_XDECREF(et->slots);
1022 type->ob_type->tp_free((PyObject *)type);
1023}
1024
1025static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001026 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001027 "mro() -> list\nreturn a type's method resolution order"},
1028 {0}
1029};
1030
1031static char type_doc[] =
1032"type(object) -> the object's type\n"
1033"type(name, bases, dict) -> a new type";
1034
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001035PyTypeObject PyType_Type = {
1036 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001037 0, /* ob_size */
1038 "type", /* tp_name */
1039 sizeof(etype), /* tp_basicsize */
1040 sizeof(struct memberlist), /* tp_itemsize */
1041 (destructor)type_dealloc, /* tp_dealloc */
1042 0, /* tp_print */
1043 0, /* tp_getattr */
1044 0, /* tp_setattr */
1045 type_compare, /* tp_compare */
1046 (reprfunc)type_repr, /* tp_repr */
1047 0, /* tp_as_number */
1048 0, /* tp_as_sequence */
1049 0, /* tp_as_mapping */
1050 (hashfunc)_Py_HashPointer, /* tp_hash */
1051 (ternaryfunc)type_call, /* tp_call */
1052 0, /* tp_str */
1053 (getattrofunc)type_getattro, /* tp_getattro */
1054 (setattrofunc)type_setattro, /* tp_setattro */
1055 0, /* tp_as_buffer */
1056 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1057 type_doc, /* tp_doc */
1058 0, /* tp_traverse */
1059 0, /* tp_clear */
1060 0, /* tp_richcompare */
1061 0, /* tp_weaklistoffset */
1062 0, /* tp_iter */
1063 0, /* tp_iternext */
1064 type_methods, /* tp_methods */
1065 type_members, /* tp_members */
1066 type_getsets, /* tp_getset */
1067 0, /* tp_base */
1068 0, /* tp_dict */
1069 0, /* tp_descr_get */
1070 0, /* tp_descr_set */
1071 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1072 0, /* tp_init */
1073 0, /* tp_alloc */
1074 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001075};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001076
1077
1078/* The base type of all types (eventually)... except itself. */
1079
1080static int
1081object_init(PyObject *self, PyObject *args, PyObject *kwds)
1082{
1083 return 0;
1084}
1085
1086static void
1087object_dealloc(PyObject *self)
1088{
1089 self->ob_type->tp_free(self);
1090}
1091
Guido van Rossum8e248182001-08-12 05:17:56 +00001092static PyObject *
1093object_repr(PyObject *self)
1094{
Guido van Rossum76e69632001-08-16 18:52:43 +00001095 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001096 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001097
Guido van Rossum76e69632001-08-16 18:52:43 +00001098 type = self->ob_type;
1099 mod = type_module(type, NULL);
1100 if (mod == NULL)
1101 PyErr_Clear();
1102 else if (!PyString_Check(mod)) {
1103 Py_DECREF(mod);
1104 mod = NULL;
1105 }
1106 name = type_name(type, NULL);
1107 if (name == NULL)
1108 return NULL;
1109 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Barry Warsaw7ce36942001-08-24 18:34:26 +00001110 rtn = PyString_FromFormat("<%s.%s instance at %p>",
1111 PyString_AS_STRING(mod),
1112 PyString_AS_STRING(name),
1113 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001114 else
Barry Warsaw7ce36942001-08-24 18:34:26 +00001115 rtn = PyString_FromFormat("<%s instance at %p>",
1116 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001117 Py_XDECREF(mod);
1118 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001119 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001120}
1121
Guido van Rossumb8f63662001-08-15 23:57:02 +00001122static PyObject *
1123object_str(PyObject *self)
1124{
1125 unaryfunc f;
1126
1127 f = self->ob_type->tp_repr;
1128 if (f == NULL)
1129 f = object_repr;
1130 return f(self);
1131}
1132
Guido van Rossum8e248182001-08-12 05:17:56 +00001133static long
1134object_hash(PyObject *self)
1135{
1136 return _Py_HashPointer(self);
1137}
Guido van Rossum8e248182001-08-12 05:17:56 +00001138
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139static void
1140object_free(PyObject *self)
1141{
1142 PyObject_Del(self);
1143}
1144
1145static struct memberlist object_members[] = {
1146 {"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
1147 {0}
1148};
1149
1150PyTypeObject PyBaseObject_Type = {
1151 PyObject_HEAD_INIT(&PyType_Type)
1152 0, /* ob_size */
1153 "object", /* tp_name */
1154 sizeof(PyObject), /* tp_basicsize */
1155 0, /* tp_itemsize */
1156 (destructor)object_dealloc, /* tp_dealloc */
1157 0, /* tp_print */
1158 0, /* tp_getattr */
1159 0, /* tp_setattr */
1160 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001161 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001162 0, /* tp_as_number */
1163 0, /* tp_as_sequence */
1164 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001165 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001166 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001167 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001169 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001170 0, /* tp_as_buffer */
1171 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1172 "The most base type", /* tp_doc */
1173 0, /* tp_traverse */
1174 0, /* tp_clear */
1175 0, /* tp_richcompare */
1176 0, /* tp_weaklistoffset */
1177 0, /* tp_iter */
1178 0, /* tp_iternext */
1179 0, /* tp_methods */
1180 object_members, /* tp_members */
1181 0, /* tp_getset */
1182 0, /* tp_base */
1183 0, /* tp_dict */
1184 0, /* tp_descr_get */
1185 0, /* tp_descr_set */
1186 0, /* tp_dictoffset */
1187 object_init, /* tp_init */
1188 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001189 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001190 object_free, /* tp_free */
1191};
1192
1193
1194/* Initialize the __dict__ in a type object */
1195
1196static int
1197add_methods(PyTypeObject *type, PyMethodDef *meth)
1198{
1199 PyObject *dict = type->tp_defined;
1200
1201 for (; meth->ml_name != NULL; meth++) {
1202 PyObject *descr;
1203 if (PyDict_GetItemString(dict, meth->ml_name))
1204 continue;
1205 descr = PyDescr_NewMethod(type, meth);
1206 if (descr == NULL)
1207 return -1;
1208 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1209 return -1;
1210 Py_DECREF(descr);
1211 }
1212 return 0;
1213}
1214
1215static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216add_members(PyTypeObject *type, struct memberlist *memb)
1217{
1218 PyObject *dict = type->tp_defined;
1219
1220 for (; memb->name != NULL; memb++) {
1221 PyObject *descr;
1222 if (PyDict_GetItemString(dict, memb->name))
1223 continue;
1224 descr = PyDescr_NewMember(type, memb);
1225 if (descr == NULL)
1226 return -1;
1227 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1228 return -1;
1229 Py_DECREF(descr);
1230 }
1231 return 0;
1232}
1233
1234static int
1235add_getset(PyTypeObject *type, struct getsetlist *gsp)
1236{
1237 PyObject *dict = type->tp_defined;
1238
1239 for (; gsp->name != NULL; gsp++) {
1240 PyObject *descr;
1241 if (PyDict_GetItemString(dict, gsp->name))
1242 continue;
1243 descr = PyDescr_NewGetSet(type, gsp);
1244
1245 if (descr == NULL)
1246 return -1;
1247 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1248 return -1;
1249 Py_DECREF(descr);
1250 }
1251 return 0;
1252}
1253
Guido van Rossum13d52f02001-08-10 21:24:08 +00001254static void
1255inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001256{
1257 int oldsize, newsize;
1258
Guido van Rossum13d52f02001-08-10 21:24:08 +00001259 /* Special flag magic */
1260 if (!type->tp_as_buffer && base->tp_as_buffer) {
1261 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1262 type->tp_flags |=
1263 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1264 }
1265 if (!type->tp_as_sequence && base->tp_as_sequence) {
1266 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1267 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1268 }
1269 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1270 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1271 if ((!type->tp_as_number && base->tp_as_number) ||
1272 (!type->tp_as_sequence && base->tp_as_sequence)) {
1273 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1274 if (!type->tp_as_number && !type->tp_as_sequence) {
1275 type->tp_flags |= base->tp_flags &
1276 Py_TPFLAGS_HAVE_INPLACEOPS;
1277 }
1278 }
1279 /* Wow */
1280 }
1281 if (!type->tp_as_number && base->tp_as_number) {
1282 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1283 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1284 }
1285
1286 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001287 oldsize = base->tp_basicsize;
1288 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1289 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1290 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001291 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1292 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001293 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001294 if (type->tp_traverse == NULL)
1295 type->tp_traverse = base->tp_traverse;
1296 if (type->tp_clear == NULL)
1297 type->tp_clear = base->tp_clear;
1298 }
1299 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1300 if (base != &PyBaseObject_Type ||
1301 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1302 if (type->tp_new == NULL)
1303 type->tp_new = base->tp_new;
1304 }
1305 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001306 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001307
1308 /* Copy other non-function slots */
1309
1310#undef COPYVAL
1311#define COPYVAL(SLOT) \
1312 if (type->SLOT == 0) type->SLOT = base->SLOT
1313
1314 COPYVAL(tp_itemsize);
1315 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1316 COPYVAL(tp_weaklistoffset);
1317 }
1318 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1319 COPYVAL(tp_dictoffset);
1320 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001321}
1322
1323static void
1324inherit_slots(PyTypeObject *type, PyTypeObject *base)
1325{
1326 PyTypeObject *basebase;
1327
1328#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001329#undef COPYSLOT
1330#undef COPYNUM
1331#undef COPYSEQ
1332#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001333
1334#define SLOTDEFINED(SLOT) \
1335 (base->SLOT != 0 && \
1336 (basebase == NULL || base->SLOT != basebase->SLOT))
1337
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001339 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340
1341#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1342#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1343#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1344
Guido van Rossum13d52f02001-08-10 21:24:08 +00001345 /* This won't inherit indirect slots (from tp_as_number etc.)
1346 if type doesn't provide the space. */
1347
1348 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1349 basebase = base->tp_base;
1350 if (basebase->tp_as_number == NULL)
1351 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352 COPYNUM(nb_add);
1353 COPYNUM(nb_subtract);
1354 COPYNUM(nb_multiply);
1355 COPYNUM(nb_divide);
1356 COPYNUM(nb_remainder);
1357 COPYNUM(nb_divmod);
1358 COPYNUM(nb_power);
1359 COPYNUM(nb_negative);
1360 COPYNUM(nb_positive);
1361 COPYNUM(nb_absolute);
1362 COPYNUM(nb_nonzero);
1363 COPYNUM(nb_invert);
1364 COPYNUM(nb_lshift);
1365 COPYNUM(nb_rshift);
1366 COPYNUM(nb_and);
1367 COPYNUM(nb_xor);
1368 COPYNUM(nb_or);
1369 COPYNUM(nb_coerce);
1370 COPYNUM(nb_int);
1371 COPYNUM(nb_long);
1372 COPYNUM(nb_float);
1373 COPYNUM(nb_oct);
1374 COPYNUM(nb_hex);
1375 COPYNUM(nb_inplace_add);
1376 COPYNUM(nb_inplace_subtract);
1377 COPYNUM(nb_inplace_multiply);
1378 COPYNUM(nb_inplace_divide);
1379 COPYNUM(nb_inplace_remainder);
1380 COPYNUM(nb_inplace_power);
1381 COPYNUM(nb_inplace_lshift);
1382 COPYNUM(nb_inplace_rshift);
1383 COPYNUM(nb_inplace_and);
1384 COPYNUM(nb_inplace_xor);
1385 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001386 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1387 COPYNUM(nb_true_divide);
1388 COPYNUM(nb_floor_divide);
1389 COPYNUM(nb_inplace_true_divide);
1390 COPYNUM(nb_inplace_floor_divide);
1391 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001392 }
1393
Guido van Rossum13d52f02001-08-10 21:24:08 +00001394 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1395 basebase = base->tp_base;
1396 if (basebase->tp_as_sequence == NULL)
1397 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001398 COPYSEQ(sq_length);
1399 COPYSEQ(sq_concat);
1400 COPYSEQ(sq_repeat);
1401 COPYSEQ(sq_item);
1402 COPYSEQ(sq_slice);
1403 COPYSEQ(sq_ass_item);
1404 COPYSEQ(sq_ass_slice);
1405 COPYSEQ(sq_contains);
1406 COPYSEQ(sq_inplace_concat);
1407 COPYSEQ(sq_inplace_repeat);
1408 }
1409
Guido van Rossum13d52f02001-08-10 21:24:08 +00001410 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1411 basebase = base->tp_base;
1412 if (basebase->tp_as_mapping == NULL)
1413 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001414 COPYMAP(mp_length);
1415 COPYMAP(mp_subscript);
1416 COPYMAP(mp_ass_subscript);
1417 }
1418
Guido van Rossum13d52f02001-08-10 21:24:08 +00001419 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001420
Tim Peters6d6c1a32001-08-02 04:15:00 +00001421 COPYSLOT(tp_dealloc);
1422 COPYSLOT(tp_print);
1423 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1424 type->tp_getattr = base->tp_getattr;
1425 type->tp_getattro = base->tp_getattro;
1426 }
1427 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1428 type->tp_setattr = base->tp_setattr;
1429 type->tp_setattro = base->tp_setattro;
1430 }
1431 /* tp_compare see tp_richcompare */
1432 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001433 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001434 COPYSLOT(tp_call);
1435 COPYSLOT(tp_str);
1436 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001437 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001438 if (type->tp_compare == NULL &&
1439 type->tp_richcompare == NULL &&
1440 type->tp_hash == NULL)
1441 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001442 type->tp_compare = base->tp_compare;
1443 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001444 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001445 }
1446 }
1447 else {
1448 COPYSLOT(tp_compare);
1449 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001450 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1451 COPYSLOT(tp_iter);
1452 COPYSLOT(tp_iternext);
1453 }
1454 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1455 COPYSLOT(tp_descr_get);
1456 COPYSLOT(tp_descr_set);
1457 COPYSLOT(tp_dictoffset);
1458 COPYSLOT(tp_init);
1459 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001460 COPYSLOT(tp_free);
1461 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001462}
1463
Guido van Rossum13d52f02001-08-10 21:24:08 +00001464staticforward int add_operators(PyTypeObject *);
1465
Tim Peters6d6c1a32001-08-02 04:15:00 +00001466int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001467PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468{
1469 PyObject *dict, *bases, *x;
1470 PyTypeObject *base;
1471 int i, n;
1472
Guido van Rossumd614f972001-08-10 17:39:49 +00001473 if (type->tp_flags & Py_TPFLAGS_READY) {
1474 assert(type->tp_dict != NULL);
1475 return 0;
1476 }
1477 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1478 assert(type->tp_dict == NULL);
1479
1480 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001481
1482 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1483 base = type->tp_base;
1484 if (base == NULL && type != &PyBaseObject_Type)
1485 base = type->tp_base = &PyBaseObject_Type;
1486
1487 /* Initialize tp_bases */
1488 bases = type->tp_bases;
1489 if (bases == NULL) {
1490 if (base == NULL)
1491 bases = PyTuple_New(0);
1492 else
1493 bases = Py_BuildValue("(O)", base);
1494 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001495 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496 type->tp_bases = bases;
1497 }
1498
1499 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001500 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001501 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001502 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001503 }
1504
1505 /* Initialize tp_defined */
1506 dict = type->tp_defined;
1507 if (dict == NULL) {
1508 dict = PyDict_New();
1509 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001510 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001511 type->tp_defined = dict;
1512 }
1513
1514 /* Add type-specific descriptors to tp_defined */
1515 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001516 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517 if (type->tp_methods != NULL) {
1518 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001519 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001520 }
1521 if (type->tp_members != NULL) {
1522 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001523 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524 }
1525 if (type->tp_getset != NULL) {
1526 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001527 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001528 }
1529
1530 /* Temporarily make tp_dict the same object as tp_defined.
1531 (This is needed to call mro(), and can stay this way for
1532 dynamic types). */
1533 Py_INCREF(type->tp_defined);
1534 type->tp_dict = type->tp_defined;
1535
1536 /* Calculate method resolution order */
1537 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001538 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001539 }
1540
Guido van Rossum13d52f02001-08-10 21:24:08 +00001541 /* Inherit special flags from dominant base */
1542 if (type->tp_base != NULL)
1543 inherit_special(type, type->tp_base);
1544
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001546 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001547 /* For a dynamic type, all slots are overridden */
1548 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001549 }
1550 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001551 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001552 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001554 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001555 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001556 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001557 bases = type->tp_mro;
1558 assert(bases != NULL);
1559 assert(PyTuple_Check(bases));
1560 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001561 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001562 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1563 assert(PyType_Check(base));
1564 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001565 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001566 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001567 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001568 }
1569 }
1570
Guido van Rossum13d52f02001-08-10 21:24:08 +00001571 /* Some more special stuff */
1572 base = type->tp_base;
1573 if (base != NULL) {
1574 if (type->tp_as_number == NULL)
1575 type->tp_as_number = base->tp_as_number;
1576 if (type->tp_as_sequence == NULL)
1577 type->tp_as_sequence = base->tp_as_sequence;
1578 if (type->tp_as_mapping == NULL)
1579 type->tp_as_mapping = base->tp_as_mapping;
1580 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001581
Guido van Rossum13d52f02001-08-10 21:24:08 +00001582 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001583 assert(type->tp_dict != NULL);
1584 type->tp_flags =
1585 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001587
1588 error:
1589 type->tp_flags &= ~Py_TPFLAGS_READYING;
1590 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001591}
1592
1593
1594/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1595
1596/* There's a wrapper *function* for each distinct function typedef used
1597 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1598 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1599 Most tables have only one entry; the tables for binary operators have two
1600 entries, one regular and one with reversed arguments. */
1601
1602static PyObject *
1603wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1604{
1605 inquiry func = (inquiry)wrapped;
1606 int res;
1607
1608 if (!PyArg_ParseTuple(args, ""))
1609 return NULL;
1610 res = (*func)(self);
1611 if (res == -1 && PyErr_Occurred())
1612 return NULL;
1613 return PyInt_FromLong((long)res);
1614}
1615
1616static struct wrapperbase tab_len[] = {
1617 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1618 {0}
1619};
1620
1621static PyObject *
1622wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1623{
1624 binaryfunc func = (binaryfunc)wrapped;
1625 PyObject *other;
1626
1627 if (!PyArg_ParseTuple(args, "O", &other))
1628 return NULL;
1629 return (*func)(self, other);
1630}
1631
1632static PyObject *
1633wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1634{
1635 binaryfunc func = (binaryfunc)wrapped;
1636 PyObject *other;
1637
1638 if (!PyArg_ParseTuple(args, "O", &other))
1639 return NULL;
1640 return (*func)(other, self);
1641}
1642
1643#undef BINARY
1644#define BINARY(NAME, OP) \
1645static struct wrapperbase tab_##NAME[] = { \
1646 {"__" #NAME "__", \
1647 (wrapperfunc)wrap_binaryfunc, \
1648 "x.__" #NAME "__(y) <==> " #OP}, \
1649 {"__r" #NAME "__", \
1650 (wrapperfunc)wrap_binaryfunc_r, \
1651 "y.__r" #NAME "__(x) <==> " #OP}, \
1652 {0} \
1653}
1654
1655BINARY(add, "x+y");
1656BINARY(sub, "x-y");
1657BINARY(mul, "x*y");
1658BINARY(div, "x/y");
1659BINARY(mod, "x%y");
1660BINARY(divmod, "divmod(x,y)");
1661BINARY(lshift, "x<<y");
1662BINARY(rshift, "x>>y");
1663BINARY(and, "x&y");
1664BINARY(xor, "x^y");
1665BINARY(or, "x|y");
1666
1667static PyObject *
1668wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1669{
1670 ternaryfunc func = (ternaryfunc)wrapped;
1671 PyObject *other;
1672 PyObject *third = Py_None;
1673
1674 /* Note: This wrapper only works for __pow__() */
1675
1676 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1677 return NULL;
1678 return (*func)(self, other, third);
1679}
1680
1681#undef TERNARY
1682#define TERNARY(NAME, OP) \
1683static struct wrapperbase tab_##NAME[] = { \
1684 {"__" #NAME "__", \
1685 (wrapperfunc)wrap_ternaryfunc, \
1686 "x.__" #NAME "__(y, z) <==> " #OP}, \
1687 {"__r" #NAME "__", \
1688 (wrapperfunc)wrap_ternaryfunc, \
1689 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1690 {0} \
1691}
1692
1693TERNARY(pow, "(x**y) % z");
1694
1695#undef UNARY
1696#define UNARY(NAME, OP) \
1697static struct wrapperbase tab_##NAME[] = { \
1698 {"__" #NAME "__", \
1699 (wrapperfunc)wrap_unaryfunc, \
1700 "x.__" #NAME "__() <==> " #OP}, \
1701 {0} \
1702}
1703
1704static PyObject *
1705wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1706{
1707 unaryfunc func = (unaryfunc)wrapped;
1708
1709 if (!PyArg_ParseTuple(args, ""))
1710 return NULL;
1711 return (*func)(self);
1712}
1713
1714UNARY(neg, "-x");
1715UNARY(pos, "+x");
1716UNARY(abs, "abs(x)");
1717UNARY(nonzero, "x != 0");
1718UNARY(invert, "~x");
1719UNARY(int, "int(x)");
1720UNARY(long, "long(x)");
1721UNARY(float, "float(x)");
1722UNARY(oct, "oct(x)");
1723UNARY(hex, "hex(x)");
1724
1725#undef IBINARY
1726#define IBINARY(NAME, OP) \
1727static struct wrapperbase tab_##NAME[] = { \
1728 {"__" #NAME "__", \
1729 (wrapperfunc)wrap_binaryfunc, \
1730 "x.__" #NAME "__(y) <==> " #OP}, \
1731 {0} \
1732}
1733
1734IBINARY(iadd, "x+=y");
1735IBINARY(isub, "x-=y");
1736IBINARY(imul, "x*=y");
1737IBINARY(idiv, "x/=y");
1738IBINARY(imod, "x%=y");
1739IBINARY(ilshift, "x<<=y");
1740IBINARY(irshift, "x>>=y");
1741IBINARY(iand, "x&=y");
1742IBINARY(ixor, "x^=y");
1743IBINARY(ior, "x|=y");
1744
1745#undef ITERNARY
1746#define ITERNARY(NAME, OP) \
1747static struct wrapperbase tab_##NAME[] = { \
1748 {"__" #NAME "__", \
1749 (wrapperfunc)wrap_ternaryfunc, \
1750 "x.__" #NAME "__(y) <==> " #OP}, \
1751 {0} \
1752}
1753
1754ITERNARY(ipow, "x = (x**y) % z");
1755
1756static struct wrapperbase tab_getitem[] = {
1757 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1758 "x.__getitem__(y) <==> x[y]"},
1759 {0}
1760};
1761
1762static PyObject *
1763wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1764{
1765 intargfunc func = (intargfunc)wrapped;
1766 int i;
1767
1768 if (!PyArg_ParseTuple(args, "i", &i))
1769 return NULL;
1770 return (*func)(self, i);
1771}
1772
1773static struct wrapperbase tab_mul_int[] = {
1774 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1775 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1776 {0}
1777};
1778
1779static struct wrapperbase tab_concat[] = {
1780 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1781 {0}
1782};
1783
1784static struct wrapperbase tab_imul_int[] = {
1785 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1786 {0}
1787};
1788
Guido van Rossum5d815f32001-08-17 21:57:47 +00001789static int
1790getindex(PyObject *self, PyObject *arg)
1791{
1792 int i;
1793
1794 i = PyInt_AsLong(arg);
1795 if (i == -1 && PyErr_Occurred())
1796 return -1;
1797 if (i < 0) {
1798 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
1799 if (sq && sq->sq_length) {
1800 int n = (*sq->sq_length)(self);
1801 if (n < 0)
1802 return -1;
1803 i += n;
1804 }
1805 }
1806 return i;
1807}
1808
1809static PyObject *
1810wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
1811{
1812 intargfunc func = (intargfunc)wrapped;
1813 PyObject *arg;
1814 int i;
1815
1816 if (!PyArg_ParseTuple(args, "O", &arg))
1817 return NULL;
1818 i = getindex(self, arg);
1819 if (i == -1 && PyErr_Occurred())
1820 return NULL;
1821 return (*func)(self, i);
1822}
1823
Tim Peters6d6c1a32001-08-02 04:15:00 +00001824static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001825 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826 "x.__getitem__(i) <==> x[i]"},
1827 {0}
1828};
1829
1830static PyObject *
1831wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1832{
1833 intintargfunc func = (intintargfunc)wrapped;
1834 int i, j;
1835
1836 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1837 return NULL;
1838 return (*func)(self, i, j);
1839}
1840
1841static struct wrapperbase tab_getslice[] = {
1842 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1843 "x.__getslice__(i, j) <==> x[i:j]"},
1844 {0}
1845};
1846
1847static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001848wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001849{
1850 intobjargproc func = (intobjargproc)wrapped;
1851 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001852 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853
Guido van Rossum5d815f32001-08-17 21:57:47 +00001854 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
1855 return NULL;
1856 i = getindex(self, arg);
1857 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858 return NULL;
1859 res = (*func)(self, i, value);
1860 if (res == -1 && PyErr_Occurred())
1861 return NULL;
1862 Py_INCREF(Py_None);
1863 return Py_None;
1864}
1865
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001866static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001867wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001868{
1869 intobjargproc func = (intobjargproc)wrapped;
1870 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001871 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001872
Guido van Rossum5d815f32001-08-17 21:57:47 +00001873 if (!PyArg_ParseTuple(args, "O", &arg))
1874 return NULL;
1875 i = getindex(self, arg);
1876 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001877 return NULL;
1878 res = (*func)(self, i, NULL);
1879 if (res == -1 && PyErr_Occurred())
1880 return NULL;
1881 Py_INCREF(Py_None);
1882 return Py_None;
1883}
1884
Tim Peters6d6c1a32001-08-02 04:15:00 +00001885static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001886 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00001888 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001889 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001890 {0}
1891};
1892
1893static PyObject *
1894wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1895{
1896 intintobjargproc func = (intintobjargproc)wrapped;
1897 int i, j, res;
1898 PyObject *value;
1899
1900 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1901 return NULL;
1902 res = (*func)(self, i, j, value);
1903 if (res == -1 && PyErr_Occurred())
1904 return NULL;
1905 Py_INCREF(Py_None);
1906 return Py_None;
1907}
1908
1909static struct wrapperbase tab_setslice[] = {
1910 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1911 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1912 {0}
1913};
1914
1915/* XXX objobjproc is a misnomer; should be objargpred */
1916static PyObject *
1917wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1918{
1919 objobjproc func = (objobjproc)wrapped;
1920 int res;
1921 PyObject *value;
1922
1923 if (!PyArg_ParseTuple(args, "O", &value))
1924 return NULL;
1925 res = (*func)(self, value);
1926 if (res == -1 && PyErr_Occurred())
1927 return NULL;
1928 return PyInt_FromLong((long)res);
1929}
1930
1931static struct wrapperbase tab_contains[] = {
1932 {"__contains__", (wrapperfunc)wrap_objobjproc,
1933 "x.__contains__(y) <==> y in x"},
1934 {0}
1935};
1936
1937static PyObject *
1938wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1939{
1940 objobjargproc func = (objobjargproc)wrapped;
1941 int res;
1942 PyObject *key, *value;
1943
1944 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1945 return NULL;
1946 res = (*func)(self, key, value);
1947 if (res == -1 && PyErr_Occurred())
1948 return NULL;
1949 Py_INCREF(Py_None);
1950 return Py_None;
1951}
1952
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001953static PyObject *
1954wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1955{
1956 objobjargproc func = (objobjargproc)wrapped;
1957 int res;
1958 PyObject *key;
1959
1960 if (!PyArg_ParseTuple(args, "O", &key))
1961 return NULL;
1962 res = (*func)(self, key, NULL);
1963 if (res == -1 && PyErr_Occurred())
1964 return NULL;
1965 Py_INCREF(Py_None);
1966 return Py_None;
1967}
1968
Tim Peters6d6c1a32001-08-02 04:15:00 +00001969static struct wrapperbase tab_setitem[] = {
1970 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1971 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001972 {"__delitem__", (wrapperfunc)wrap_delitem,
1973 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001974 {0}
1975};
1976
1977static PyObject *
1978wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1979{
1980 cmpfunc func = (cmpfunc)wrapped;
1981 int res;
1982 PyObject *other;
1983
1984 if (!PyArg_ParseTuple(args, "O", &other))
1985 return NULL;
1986 res = (*func)(self, other);
1987 if (PyErr_Occurred())
1988 return NULL;
1989 return PyInt_FromLong((long)res);
1990}
1991
1992static struct wrapperbase tab_cmp[] = {
1993 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1994 "x.__cmp__(y) <==> cmp(x,y)"},
1995 {0}
1996};
1997
1998static struct wrapperbase tab_repr[] = {
1999 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2000 "x.__repr__() <==> repr(x)"},
2001 {0}
2002};
2003
2004static struct wrapperbase tab_getattr[] = {
2005 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
2006 "x.__getattr__('name') <==> x.name"},
2007 {0}
2008};
2009
2010static PyObject *
2011wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2012{
2013 setattrofunc func = (setattrofunc)wrapped;
2014 int res;
2015 PyObject *name, *value;
2016
2017 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2018 return NULL;
2019 res = (*func)(self, name, value);
2020 if (res < 0)
2021 return NULL;
2022 Py_INCREF(Py_None);
2023 return Py_None;
2024}
2025
2026static PyObject *
2027wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2028{
2029 setattrofunc func = (setattrofunc)wrapped;
2030 int res;
2031 PyObject *name;
2032
2033 if (!PyArg_ParseTuple(args, "O", &name))
2034 return NULL;
2035 res = (*func)(self, name, NULL);
2036 if (res < 0)
2037 return NULL;
2038 Py_INCREF(Py_None);
2039 return Py_None;
2040}
2041
2042static struct wrapperbase tab_setattr[] = {
2043 {"__setattr__", (wrapperfunc)wrap_setattr,
2044 "x.__setattr__('name', value) <==> x.name = value"},
2045 {"__delattr__", (wrapperfunc)wrap_delattr,
2046 "x.__delattr__('name') <==> del x.name"},
2047 {0}
2048};
2049
2050static PyObject *
2051wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2052{
2053 hashfunc func = (hashfunc)wrapped;
2054 long res;
2055
2056 if (!PyArg_ParseTuple(args, ""))
2057 return NULL;
2058 res = (*func)(self);
2059 if (res == -1 && PyErr_Occurred())
2060 return NULL;
2061 return PyInt_FromLong(res);
2062}
2063
2064static struct wrapperbase tab_hash[] = {
2065 {"__hash__", (wrapperfunc)wrap_hashfunc,
2066 "x.__hash__() <==> hash(x)"},
2067 {0}
2068};
2069
2070static PyObject *
2071wrap_call(PyObject *self, PyObject *args, void *wrapped)
2072{
2073 ternaryfunc func = (ternaryfunc)wrapped;
2074
2075 /* XXX What about keyword arguments? */
2076 return (*func)(self, args, NULL);
2077}
2078
2079static struct wrapperbase tab_call[] = {
2080 {"__call__", (wrapperfunc)wrap_call,
2081 "x.__call__(...) <==> x(...)"},
2082 {0}
2083};
2084
2085static struct wrapperbase tab_str[] = {
2086 {"__str__", (wrapperfunc)wrap_unaryfunc,
2087 "x.__str__() <==> str(x)"},
2088 {0}
2089};
2090
2091static PyObject *
2092wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2093{
2094 richcmpfunc func = (richcmpfunc)wrapped;
2095 PyObject *other;
2096
2097 if (!PyArg_ParseTuple(args, "O", &other))
2098 return NULL;
2099 return (*func)(self, other, op);
2100}
2101
2102#undef RICHCMP_WRAPPER
2103#define RICHCMP_WRAPPER(NAME, OP) \
2104static PyObject * \
2105richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2106{ \
2107 return wrap_richcmpfunc(self, args, wrapped, OP); \
2108}
2109
Jack Jansen8e938b42001-08-08 15:29:49 +00002110RICHCMP_WRAPPER(lt, Py_LT)
2111RICHCMP_WRAPPER(le, Py_LE)
2112RICHCMP_WRAPPER(eq, Py_EQ)
2113RICHCMP_WRAPPER(ne, Py_NE)
2114RICHCMP_WRAPPER(gt, Py_GT)
2115RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002116
2117#undef RICHCMP_ENTRY
2118#define RICHCMP_ENTRY(NAME, EXPR) \
2119 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2120 "x.__" #NAME "__(y) <==> " EXPR}
2121
2122static struct wrapperbase tab_richcmp[] = {
2123 RICHCMP_ENTRY(lt, "x<y"),
2124 RICHCMP_ENTRY(le, "x<=y"),
2125 RICHCMP_ENTRY(eq, "x==y"),
2126 RICHCMP_ENTRY(ne, "x!=y"),
2127 RICHCMP_ENTRY(gt, "x>y"),
2128 RICHCMP_ENTRY(ge, "x>=y"),
2129 {0}
2130};
2131
2132static struct wrapperbase tab_iter[] = {
2133 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2134 {0}
2135};
2136
2137static PyObject *
2138wrap_next(PyObject *self, PyObject *args, void *wrapped)
2139{
2140 unaryfunc func = (unaryfunc)wrapped;
2141 PyObject *res;
2142
2143 if (!PyArg_ParseTuple(args, ""))
2144 return NULL;
2145 res = (*func)(self);
2146 if (res == NULL && !PyErr_Occurred())
2147 PyErr_SetNone(PyExc_StopIteration);
2148 return res;
2149}
2150
2151static struct wrapperbase tab_next[] = {
2152 {"next", (wrapperfunc)wrap_next,
2153 "x.next() -> the next value, or raise StopIteration"},
2154 {0}
2155};
2156
2157static PyObject *
2158wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2159{
2160 descrgetfunc func = (descrgetfunc)wrapped;
2161 PyObject *obj;
2162 PyObject *type = NULL;
2163
2164 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2165 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166 return (*func)(self, obj, type);
2167}
2168
2169static struct wrapperbase tab_descr_get[] = {
2170 {"__get__", (wrapperfunc)wrap_descr_get,
2171 "descr.__get__(obj, type) -> value"},
2172 {0}
2173};
2174
2175static PyObject *
2176wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2177{
2178 descrsetfunc func = (descrsetfunc)wrapped;
2179 PyObject *obj, *value;
2180 int ret;
2181
2182 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2183 return NULL;
2184 ret = (*func)(self, obj, value);
2185 if (ret < 0)
2186 return NULL;
2187 Py_INCREF(Py_None);
2188 return Py_None;
2189}
2190
2191static struct wrapperbase tab_descr_set[] = {
2192 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2193 "descr.__set__(obj, value)"},
2194 {0}
2195};
2196
2197static PyObject *
2198wrap_init(PyObject *self, PyObject *args, void *wrapped)
2199{
2200 initproc func = (initproc)wrapped;
2201
2202 /* XXX What about keyword arguments? */
2203 if (func(self, args, NULL) < 0)
2204 return NULL;
2205 Py_INCREF(Py_None);
2206 return Py_None;
2207}
2208
2209static struct wrapperbase tab_init[] = {
2210 {"__init__", (wrapperfunc)wrap_init,
2211 "x.__init__(...) initializes x; "
2212 "see x.__type__.__doc__ for signature"},
2213 {0}
2214};
2215
2216static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002217tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002218{
Barry Warsaw60f01882001-08-22 19:24:42 +00002219 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002220 PyObject *arg0, *res;
2221
2222 if (self == NULL || !PyType_Check(self))
2223 Py_FatalError("__new__() called with non-type 'self'");
2224 type = (PyTypeObject *)self;
2225 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002226 PyErr_Format(PyExc_TypeError,
2227 "%s.__new__(): not enough arguments",
2228 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002229 return NULL;
2230 }
2231 arg0 = PyTuple_GET_ITEM(args, 0);
2232 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002233 PyErr_Format(PyExc_TypeError,
2234 "%s.__new__(X): X is not a type object (%s)",
2235 type->tp_name,
2236 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002237 return NULL;
2238 }
2239 subtype = (PyTypeObject *)arg0;
2240 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002241 PyErr_Format(PyExc_TypeError,
2242 "%s.__new__(%s): %s is not a subtype of %s",
2243 type->tp_name,
2244 subtype->tp_name,
2245 subtype->tp_name,
2246 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002247 return NULL;
2248 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002249
2250 /* Check that the use doesn't do something silly and unsafe like
2251 object.__new__(dictionary). To do this, we check that the
2252 most derived base that's not a heap type is this type. */
2253 staticbase = subtype;
2254 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2255 staticbase = staticbase->tp_base;
2256 if (staticbase != type) {
2257 PyErr_Format(PyExc_TypeError,
2258 "%s.__new__(%s) is not safe, use %s.__new__()",
2259 type->tp_name,
2260 subtype->tp_name,
2261 staticbase == NULL ? "?" : staticbase->tp_name);
2262 return NULL;
2263 }
2264
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002265 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2266 if (args == NULL)
2267 return NULL;
2268 res = type->tp_new(subtype, args, kwds);
2269 Py_DECREF(args);
2270 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271}
2272
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002273static struct PyMethodDef tp_new_methoddef[] = {
2274 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2275 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002276 {0}
2277};
2278
2279static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002280add_tp_new_wrapper(PyTypeObject *type)
2281{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002282 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002283
Guido van Rossumf040ede2001-08-07 16:40:56 +00002284 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2285 return 0;
2286 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002287 if (func == NULL)
2288 return -1;
2289 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2290}
2291
Guido van Rossum13d52f02001-08-10 21:24:08 +00002292static int
2293add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2294{
2295 PyObject *dict = type->tp_defined;
2296
2297 for (; wraps->name != NULL; wraps++) {
2298 PyObject *descr;
2299 if (PyDict_GetItemString(dict, wraps->name))
2300 continue;
2301 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2302 if (descr == NULL)
2303 return -1;
2304 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2305 return -1;
2306 Py_DECREF(descr);
2307 }
2308 return 0;
2309}
2310
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002311/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002312 dictionary with method descriptors for function slots. For each
2313 function slot (like tp_repr) that's defined in the type, one or
2314 more corresponding descriptors are added in the type's tp_defined
2315 dictionary under the appropriate name (like __repr__). Some
2316 function slots cause more than one descriptor to be added (for
2317 example, the nb_add slot adds both __add__ and __radd__
2318 descriptors) and some function slots compete for the same
2319 descriptor (for example both sq_item and mp_subscript generate a
2320 __getitem__ descriptor). This only adds new descriptors and
2321 doesn't overwrite entries in tp_defined that were previously
2322 defined. The descriptors contain a reference to the C function
2323 they must call, so that it's safe if they are copied into a
2324 subtype's __dict__ and the subtype has a different C function in
2325 its slot -- calling the method defined by the descriptor will call
2326 the C function that was used to create it, rather than the C
2327 function present in the slot when it is called. (This is important
2328 because a subtype may have a C function in the slot that calls the
2329 method from the dictionary, and we want to avoid infinite recursion
2330 here.) */
2331
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002332static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002333add_operators(PyTypeObject *type)
2334{
2335 PySequenceMethods *sq;
2336 PyMappingMethods *mp;
2337 PyNumberMethods *nb;
2338
2339#undef ADD
2340#define ADD(SLOT, TABLE) \
2341 if (SLOT) { \
2342 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2343 return -1; \
2344 }
2345
2346 if ((sq = type->tp_as_sequence) != NULL) {
2347 ADD(sq->sq_length, tab_len);
2348 ADD(sq->sq_concat, tab_concat);
2349 ADD(sq->sq_repeat, tab_mul_int);
2350 ADD(sq->sq_item, tab_getitem_int);
2351 ADD(sq->sq_slice, tab_getslice);
2352 ADD(sq->sq_ass_item, tab_setitem_int);
2353 ADD(sq->sq_ass_slice, tab_setslice);
2354 ADD(sq->sq_contains, tab_contains);
2355 ADD(sq->sq_inplace_concat, tab_iadd);
2356 ADD(sq->sq_inplace_repeat, tab_imul_int);
2357 }
2358
2359 if ((mp = type->tp_as_mapping) != NULL) {
2360 if (sq->sq_length == NULL)
2361 ADD(mp->mp_length, tab_len);
2362 ADD(mp->mp_subscript, tab_getitem);
2363 ADD(mp->mp_ass_subscript, tab_setitem);
2364 }
2365
2366 /* We don't support "old-style numbers" because their binary
2367 operators require that both arguments have the same type;
2368 the wrappers here only work for new-style numbers. */
2369 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2370 (nb = type->tp_as_number) != NULL) {
2371 ADD(nb->nb_add, tab_add);
2372 ADD(nb->nb_subtract, tab_sub);
2373 ADD(nb->nb_multiply, tab_mul);
2374 ADD(nb->nb_divide, tab_div);
2375 ADD(nb->nb_remainder, tab_mod);
2376 ADD(nb->nb_divmod, tab_divmod);
2377 ADD(nb->nb_power, tab_pow);
2378 ADD(nb->nb_negative, tab_neg);
2379 ADD(nb->nb_positive, tab_pos);
2380 ADD(nb->nb_absolute, tab_abs);
2381 ADD(nb->nb_nonzero, tab_nonzero);
2382 ADD(nb->nb_invert, tab_invert);
2383 ADD(nb->nb_lshift, tab_lshift);
2384 ADD(nb->nb_rshift, tab_rshift);
2385 ADD(nb->nb_and, tab_and);
2386 ADD(nb->nb_xor, tab_xor);
2387 ADD(nb->nb_or, tab_or);
2388 /* We don't support coerce() -- see above comment */
2389 ADD(nb->nb_int, tab_int);
2390 ADD(nb->nb_long, tab_long);
2391 ADD(nb->nb_float, tab_float);
2392 ADD(nb->nb_oct, tab_oct);
2393 ADD(nb->nb_hex, tab_hex);
2394 ADD(nb->nb_inplace_add, tab_iadd);
2395 ADD(nb->nb_inplace_subtract, tab_isub);
2396 ADD(nb->nb_inplace_multiply, tab_imul);
2397 ADD(nb->nb_inplace_divide, tab_idiv);
2398 ADD(nb->nb_inplace_remainder, tab_imod);
2399 ADD(nb->nb_inplace_power, tab_ipow);
2400 ADD(nb->nb_inplace_lshift, tab_ilshift);
2401 ADD(nb->nb_inplace_rshift, tab_irshift);
2402 ADD(nb->nb_inplace_and, tab_iand);
2403 ADD(nb->nb_inplace_xor, tab_ixor);
2404 ADD(nb->nb_inplace_or, tab_ior);
2405 }
2406
2407 ADD(type->tp_getattro, tab_getattr);
2408 ADD(type->tp_setattro, tab_setattr);
2409 ADD(type->tp_compare, tab_cmp);
2410 ADD(type->tp_repr, tab_repr);
2411 ADD(type->tp_hash, tab_hash);
2412 ADD(type->tp_call, tab_call);
2413 ADD(type->tp_str, tab_str);
2414 ADD(type->tp_richcompare, tab_richcmp);
2415 ADD(type->tp_iter, tab_iter);
2416 ADD(type->tp_iternext, tab_next);
2417 ADD(type->tp_descr_get, tab_descr_get);
2418 ADD(type->tp_descr_set, tab_descr_set);
2419 ADD(type->tp_init, tab_init);
2420
Guido van Rossumf040ede2001-08-07 16:40:56 +00002421 if (type->tp_new != NULL) {
2422 if (add_tp_new_wrapper(type) < 0)
2423 return -1;
2424 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002425
2426 return 0;
2427}
2428
Guido van Rossumf040ede2001-08-07 16:40:56 +00002429/* Slot wrappers that call the corresponding __foo__ slot. See comments
2430 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002431
Guido van Rossumdc91b992001-08-08 22:26:22 +00002432#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002433static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002434FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002436 static PyObject *cache_str; \
Guido van Rossum2730b132001-08-28 18:22:14 +00002437 return call_method(self, OPSTR, &cache_str, ""); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438}
2439
Guido van Rossumdc91b992001-08-08 22:26:22 +00002440#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002441static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002442FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002443{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002444 static PyObject *cache_str; \
2445 return call_method(self, OPSTR, &cache_str, ARGCODES, arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002446}
2447
Guido van Rossumdc91b992001-08-08 22:26:22 +00002448
2449#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002450static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002451FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002452{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002453 static PyObject *cache_str, *rcache_str; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002454 if (self->ob_type->tp_as_number != NULL && \
2455 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2456 PyObject *r; \
Guido van Rossum2730b132001-08-28 18:22:14 +00002457 r = call_method( \
2458 self, OPSTR, &cache_str, "O", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002459 if (r != Py_NotImplemented || \
2460 other->ob_type == self->ob_type) \
2461 return r; \
2462 Py_DECREF(r); \
2463 } \
2464 if (other->ob_type->tp_as_number != NULL && \
2465 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossum2730b132001-08-28 18:22:14 +00002466 return call_method( \
2467 other, ROPSTR, &rcache_str, "O", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002468 } \
2469 Py_INCREF(Py_NotImplemented); \
2470 return Py_NotImplemented; \
2471}
2472
2473#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2474 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2475
2476#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2477static PyObject * \
2478FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2479{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002480 static PyObject *cache_str; \
2481 return call_method(self, OPSTR, &cache_str, ARGCODES, arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002482}
2483
2484static int
2485slot_sq_length(PyObject *self)
2486{
Guido van Rossum2730b132001-08-28 18:22:14 +00002487 static PyObject *len_str;
2488 PyObject *res = call_method(self, "__len__", &len_str, "");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002489
2490 if (res == NULL)
2491 return -1;
2492 return (int)PyInt_AsLong(res);
2493}
2494
Guido van Rossumdc91b992001-08-08 22:26:22 +00002495SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2496SLOT1(slot_sq_repeat, "__mul__", int, "i")
2497SLOT1(slot_sq_item, "__getitem__", int, "i")
2498SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002499
2500static int
2501slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2502{
2503 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002504 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002505
2506 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002507 res = call_method(self, "__delitem__", &delitem_str,
2508 "i", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002509 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002510 res = call_method(self, "__setitem__", &setitem_str,
2511 "iO", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002512 if (res == NULL)
2513 return -1;
2514 Py_DECREF(res);
2515 return 0;
2516}
2517
2518static int
2519slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2520{
2521 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002522 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002523
2524 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002525 res = call_method(self, "__delslice__", &delslice_str,
2526 "ii", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002527 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002528 res = call_method(self, "__setslice__", &setslice_str,
2529 "iiO", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002530 if (res == NULL)
2531 return -1;
2532 Py_DECREF(res);
2533 return 0;
2534}
2535
2536static int
2537slot_sq_contains(PyObject *self, PyObject *value)
2538{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002539 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002540 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002541
Guido van Rossum60718732001-08-28 17:47:51 +00002542 func = lookup_method(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002543
2544 if (func != NULL) {
2545 args = Py_BuildValue("(O)", value);
2546 if (args == NULL)
2547 res = NULL;
2548 else {
2549 res = PyEval_CallObject(func, args);
2550 Py_DECREF(args);
2551 }
2552 Py_DECREF(func);
2553 if (res == NULL)
2554 return -1;
2555 return PyObject_IsTrue(res);
2556 }
2557 else {
2558 PyErr_Clear();
2559 return _PySequence_IterContains(self, value);
2560 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561}
2562
Guido van Rossumdc91b992001-08-08 22:26:22 +00002563SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2564SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002565
2566#define slot_mp_length slot_sq_length
2567
Guido van Rossumdc91b992001-08-08 22:26:22 +00002568SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002569
2570static int
2571slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2572{
2573 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002574 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002575
2576 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002577 res = call_method(self, "__delitem__", &delitem_str,
2578 "O", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002579 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002580 res = call_method(self, "__setitem__", &setitem_str,
2581 "OO", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002582 if (res == NULL)
2583 return -1;
2584 Py_DECREF(res);
2585 return 0;
2586}
2587
Guido van Rossumdc91b992001-08-08 22:26:22 +00002588SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2589SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2590SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2591SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2592SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2593SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2594
2595staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2596
2597SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2598 nb_power, "__pow__", "__rpow__")
2599
2600static PyObject *
2601slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2602{
Guido van Rossum2730b132001-08-28 18:22:14 +00002603 static PyObject *pow_str;
2604
Guido van Rossumdc91b992001-08-08 22:26:22 +00002605 if (modulus == Py_None)
2606 return slot_nb_power_binary(self, other);
2607 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002608 return call_method(self, "__pow__", &pow_str,
2609 "OO", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002610}
2611
2612SLOT0(slot_nb_negative, "__neg__")
2613SLOT0(slot_nb_positive, "__pos__")
2614SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002615
2616static int
2617slot_nb_nonzero(PyObject *self)
2618{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002619 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002620 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002621
Guido van Rossum60718732001-08-28 17:47:51 +00002622 func = lookup_method(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002623 if (func == NULL) {
2624 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002625 func = lookup_method(self, "__len__", &len_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002626 }
2627
2628 if (func != NULL) {
2629 res = PyEval_CallObject(func, NULL);
2630 Py_DECREF(func);
2631 if (res == NULL)
2632 return -1;
2633 return PyObject_IsTrue(res);
2634 }
2635 else {
2636 PyErr_Clear();
2637 return 1;
2638 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002639}
2640
Guido van Rossumdc91b992001-08-08 22:26:22 +00002641SLOT0(slot_nb_invert, "__invert__")
2642SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2643SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2644SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2645SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2646SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002647/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002648SLOT0(slot_nb_int, "__int__")
2649SLOT0(slot_nb_long, "__long__")
2650SLOT0(slot_nb_float, "__float__")
2651SLOT0(slot_nb_oct, "__oct__")
2652SLOT0(slot_nb_hex, "__hex__")
2653SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2654SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2655SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2656SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2657SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2658SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2659SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2660SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2661SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2662SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2663SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2664SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2665 "__floordiv__", "__rfloordiv__")
2666SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2667SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2668SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002669
2670static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002671half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002672{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002673 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002674 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002675 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002676
Guido van Rossum60718732001-08-28 17:47:51 +00002677 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002678 if (func == NULL) {
2679 PyErr_Clear();
2680 }
2681 else {
2682 args = Py_BuildValue("(O)", other);
2683 if (args == NULL)
2684 res = NULL;
2685 else {
2686 res = PyObject_CallObject(func, args);
2687 Py_DECREF(args);
2688 }
2689 if (res != Py_NotImplemented) {
2690 if (res == NULL)
2691 return -2;
2692 c = PyInt_AsLong(res);
2693 Py_DECREF(res);
2694 if (c == -1 && PyErr_Occurred())
2695 return -2;
2696 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2697 }
2698 Py_DECREF(res);
2699 }
2700 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002701}
2702
Guido van Rossumb8f63662001-08-15 23:57:02 +00002703static int
2704slot_tp_compare(PyObject *self, PyObject *other)
2705{
2706 int c;
2707
2708 if (self->ob_type->tp_compare == slot_tp_compare) {
2709 c = half_compare(self, other);
2710 if (c <= 1)
2711 return c;
2712 }
2713 if (other->ob_type->tp_compare == slot_tp_compare) {
2714 c = half_compare(other, self);
2715 if (c < -1)
2716 return -2;
2717 if (c <= 1)
2718 return -c;
2719 }
2720 return (void *)self < (void *)other ? -1 :
2721 (void *)self > (void *)other ? 1 : 0;
2722}
2723
2724static PyObject *
2725slot_tp_repr(PyObject *self)
2726{
2727 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002728 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002729
Guido van Rossum60718732001-08-28 17:47:51 +00002730 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002731 if (func != NULL) {
2732 res = PyEval_CallObject(func, NULL);
2733 Py_DECREF(func);
2734 return res;
2735 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00002736 PyErr_Clear();
2737 return PyString_FromFormat("<%s object at %p>",
2738 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002739}
2740
2741static PyObject *
2742slot_tp_str(PyObject *self)
2743{
2744 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002745 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002746
Guido van Rossum60718732001-08-28 17:47:51 +00002747 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002748 if (func != NULL) {
2749 res = PyEval_CallObject(func, NULL);
2750 Py_DECREF(func);
2751 return res;
2752 }
2753 else {
2754 PyErr_Clear();
2755 return slot_tp_repr(self);
2756 }
2757}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758
2759static long
2760slot_tp_hash(PyObject *self)
2761{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002762 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002763 static PyObject *hash_str, *eq_str, *cmp_str;
2764
Tim Peters6d6c1a32001-08-02 04:15:00 +00002765 long h;
2766
Guido van Rossum60718732001-08-28 17:47:51 +00002767 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002768
2769 if (func != NULL) {
2770 res = PyEval_CallObject(func, NULL);
2771 Py_DECREF(func);
2772 if (res == NULL)
2773 return -1;
2774 h = PyInt_AsLong(res);
2775 }
2776 else {
2777 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002778 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002779 if (func == NULL) {
2780 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002781 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002782 }
2783 if (func != NULL) {
2784 Py_DECREF(func);
2785 PyErr_SetString(PyExc_TypeError, "unhashable type");
2786 return -1;
2787 }
2788 PyErr_Clear();
2789 h = _Py_HashPointer((void *)self);
2790 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791 if (h == -1 && !PyErr_Occurred())
2792 h = -2;
2793 return h;
2794}
2795
2796static PyObject *
2797slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2798{
Guido van Rossum60718732001-08-28 17:47:51 +00002799 static PyObject *call_str;
2800 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801 PyObject *res;
2802
2803 if (meth == NULL)
2804 return NULL;
2805 res = PyObject_Call(meth, args, kwds);
2806 Py_DECREF(meth);
2807 return res;
2808}
2809
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810static PyObject *
2811slot_tp_getattro(PyObject *self, PyObject *name)
2812{
2813 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002814 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002815 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002816
Guido van Rossum8e248182001-08-12 05:17:56 +00002817 if (getattr_str == NULL) {
2818 getattr_str = PyString_InternFromString("__getattr__");
2819 if (getattr_str == NULL)
2820 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002821 }
Guido van Rossum8e248182001-08-12 05:17:56 +00002822 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00002823 if (getattr == NULL) {
2824 /* Avoid further slowdowns */
2825 if (tp->tp_getattro == slot_tp_getattro)
2826 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002827 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00002828 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002829 return PyObject_CallFunction(getattr, "OO", self, name);
2830}
2831
2832static int
2833slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2834{
2835 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002836 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002837
2838 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002839 res = call_method(self, "__delattr__", &delattr_str,
2840 "O", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002841 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002842 res = call_method(self, "__setattr__", &setattr_str,
2843 "OO", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002844 if (res == NULL)
2845 return -1;
2846 Py_DECREF(res);
2847 return 0;
2848}
2849
2850/* Map rich comparison operators to their __xx__ namesakes */
2851static char *name_op[] = {
2852 "__lt__",
2853 "__le__",
2854 "__eq__",
2855 "__ne__",
2856 "__gt__",
2857 "__ge__",
2858};
2859
2860static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00002861half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002862{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002863 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002864 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00002865
Guido van Rossum60718732001-08-28 17:47:51 +00002866 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002867 if (func == NULL) {
2868 PyErr_Clear();
2869 Py_INCREF(Py_NotImplemented);
2870 return Py_NotImplemented;
2871 }
2872 args = Py_BuildValue("(O)", other);
2873 if (args == NULL)
2874 res = NULL;
2875 else {
2876 res = PyObject_CallObject(func, args);
2877 Py_DECREF(args);
2878 }
2879 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002880 return res;
2881}
2882
Guido van Rossumb8f63662001-08-15 23:57:02 +00002883/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
2884static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
2885
2886static PyObject *
2887slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2888{
2889 PyObject *res;
2890
2891 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
2892 res = half_richcompare(self, other, op);
2893 if (res != Py_NotImplemented)
2894 return res;
2895 Py_DECREF(res);
2896 }
2897 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
2898 res = half_richcompare(other, self, swapped_op[op]);
2899 if (res != Py_NotImplemented) {
2900 return res;
2901 }
2902 Py_DECREF(res);
2903 }
2904 Py_INCREF(Py_NotImplemented);
2905 return Py_NotImplemented;
2906}
2907
2908static PyObject *
2909slot_tp_iter(PyObject *self)
2910{
2911 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002912 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002913
Guido van Rossum60718732001-08-28 17:47:51 +00002914 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002915 if (func != NULL) {
2916 res = PyObject_CallObject(func, NULL);
2917 Py_DECREF(func);
2918 return res;
2919 }
2920 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002921 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002922 if (func == NULL) {
2923 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
2924 return NULL;
2925 }
2926 Py_DECREF(func);
2927 return PySeqIter_New(self);
2928}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002929
2930static PyObject *
2931slot_tp_iternext(PyObject *self)
2932{
Guido van Rossum2730b132001-08-28 18:22:14 +00002933 static PyObject *next_str;
2934 return call_method(self, "next", &next_str, "");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002935}
2936
Guido van Rossum1a493502001-08-17 16:47:50 +00002937static PyObject *
2938slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
2939{
2940 PyTypeObject *tp = self->ob_type;
2941 PyObject *get;
2942 static PyObject *get_str = NULL;
2943
2944 if (get_str == NULL) {
2945 get_str = PyString_InternFromString("__get__");
2946 if (get_str == NULL)
2947 return NULL;
2948 }
2949 get = _PyType_Lookup(tp, get_str);
2950 if (get == NULL) {
2951 /* Avoid further slowdowns */
2952 if (tp->tp_descr_get == slot_tp_descr_get)
2953 tp->tp_descr_get = NULL;
2954 Py_INCREF(self);
2955 return self;
2956 }
Guido van Rossum2c252392001-08-24 10:13:31 +00002957 if (obj == NULL)
2958 obj = Py_None;
2959 if (type == NULL)
2960 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00002961 return PyObject_CallFunction(get, "OOO", self, obj, type);
2962}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002963
2964static int
2965slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2966{
Guido van Rossum2c252392001-08-24 10:13:31 +00002967 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002968 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00002969
2970 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002971 res = call_method(self, "__del__", &del_str,
2972 "O", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00002973 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002974 res = call_method(self, "__set__", &set_str,
2975 "OO", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002976 if (res == NULL)
2977 return -1;
2978 Py_DECREF(res);
2979 return 0;
2980}
2981
2982static int
2983slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2984{
Guido van Rossum60718732001-08-28 17:47:51 +00002985 static PyObject *init_str;
2986 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987 PyObject *res;
2988
2989 if (meth == NULL)
2990 return -1;
2991 res = PyObject_Call(meth, args, kwds);
2992 Py_DECREF(meth);
2993 if (res == NULL)
2994 return -1;
2995 Py_DECREF(res);
2996 return 0;
2997}
2998
2999static PyObject *
3000slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3001{
3002 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3003 PyObject *newargs, *x;
3004 int i, n;
3005
3006 if (func == NULL)
3007 return NULL;
3008 assert(PyTuple_Check(args));
3009 n = PyTuple_GET_SIZE(args);
3010 newargs = PyTuple_New(n+1);
3011 if (newargs == NULL)
3012 return NULL;
3013 Py_INCREF(type);
3014 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3015 for (i = 0; i < n; i++) {
3016 x = PyTuple_GET_ITEM(args, i);
3017 Py_INCREF(x);
3018 PyTuple_SET_ITEM(newargs, i+1, x);
3019 }
3020 x = PyObject_Call(func, newargs, kwds);
3021 Py_DECREF(func);
3022 return x;
3023}
3024
Guido van Rossumf040ede2001-08-07 16:40:56 +00003025/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003026 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003027 The dict argument is the dictionary argument passed to type_new(),
3028 which is the local namespace of the class statement, in other
3029 words, it contains the methods. For each special method (like
3030 __repr__) defined in the dictionary, the corresponding function
3031 slot in the type object (like tp_repr) is set to a special function
3032 whose name is 'slot_' followed by the slot name and whose signature
3033 is whatever is required for that slot. These slot functions look
3034 up the corresponding method in the type's dictionary and call it.
3035 The slot functions have to take care of the various peculiarities
3036 of the mapping between slots and special methods, such as mapping
3037 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3038 etc.) or mapping multiple slots to a single method (sq_item,
3039 mp_subscript <--> __getitem__). */
3040
Tim Peters6d6c1a32001-08-02 04:15:00 +00003041static void
3042override_slots(PyTypeObject *type, PyObject *dict)
3043{
3044 PySequenceMethods *sq = type->tp_as_sequence;
3045 PyMappingMethods *mp = type->tp_as_mapping;
3046 PyNumberMethods *nb = type->tp_as_number;
3047
Guido van Rossumdc91b992001-08-08 22:26:22 +00003048#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003049 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003050 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003051 }
3052
Guido van Rossumdc91b992001-08-08 22:26:22 +00003053#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003054 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003055 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003056 }
3057
Guido van Rossumdc91b992001-08-08 22:26:22 +00003058#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003059 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003060 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003061 }
3062
Guido van Rossumdc91b992001-08-08 22:26:22 +00003063#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003064 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003065 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003066 }
3067
Guido van Rossumdc91b992001-08-08 22:26:22 +00003068 SQSLOT("__len__", sq_length, slot_sq_length);
3069 SQSLOT("__add__", sq_concat, slot_sq_concat);
3070 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3071 SQSLOT("__getitem__", sq_item, slot_sq_item);
3072 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3073 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3074 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3075 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3076 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3077 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3078 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3079 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003080
Guido van Rossumdc91b992001-08-08 22:26:22 +00003081 MPSLOT("__len__", mp_length, slot_mp_length);
3082 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3083 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3084 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003085
Guido van Rossumdc91b992001-08-08 22:26:22 +00003086 NBSLOT("__add__", nb_add, slot_nb_add);
3087 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3088 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3089 NBSLOT("__div__", nb_divide, slot_nb_divide);
3090 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3091 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3092 NBSLOT("__pow__", nb_power, slot_nb_power);
3093 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3094 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3095 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3096 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3097 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3098 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3099 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3100 NBSLOT("__and__", nb_and, slot_nb_and);
3101 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3102 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00003104 NBSLOT("__int__", nb_int, slot_nb_int);
3105 NBSLOT("__long__", nb_long, slot_nb_long);
3106 NBSLOT("__float__", nb_float, slot_nb_float);
3107 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3108 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3109 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3110 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3111 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3112 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3113 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3114 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3115 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3116 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3117 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3118 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3119 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3120 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3121 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3122 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3123 slot_nb_inplace_floor_divide);
3124 NBSLOT("__itruediv__", nb_inplace_true_divide,
3125 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003126
Guido van Rossum8e248182001-08-12 05:17:56 +00003127 if (dict == NULL ||
3128 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003129 PyDict_GetItemString(dict, "__repr__"))
3130 type->tp_print = NULL;
3131
Guido van Rossumdc91b992001-08-08 22:26:22 +00003132 TPSLOT("__cmp__", tp_compare, slot_tp_compare);
3133 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3134 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3135 TPSLOT("__call__", tp_call, slot_tp_call);
3136 TPSLOT("__str__", tp_str, slot_tp_str);
3137 TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
3138 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3139 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3140 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3141 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3142 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3143 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3144 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3145 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3146 TPSLOT("next", tp_iternext, slot_tp_iternext);
3147 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3148 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3149 TPSLOT("__init__", tp_init, slot_tp_init);
3150 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003151}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003152
3153
3154/* Cooperative 'super' */
3155
3156typedef struct {
3157 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003158 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003159 PyObject *obj;
3160} superobject;
3161
3162static void
3163super_dealloc(PyObject *self)
3164{
3165 superobject *su = (superobject *)self;
3166
3167 Py_XDECREF(su->obj);
3168 Py_XDECREF(su->type);
3169 self->ob_type->tp_free(self);
3170}
3171
3172static PyObject *
3173super_getattro(PyObject *self, PyObject *name)
3174{
3175 superobject *su = (superobject *)self;
3176
3177 if (su->obj != NULL) {
3178 PyObject *mro, *res, *tmp;
3179 descrgetfunc f;
3180 int i, n;
3181
Guido van Rossume705ef12001-08-29 15:47:06 +00003182 mro = su->obj->ob_type->tp_mro;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003183 assert(mro != NULL && PyTuple_Check(mro));
3184 n = PyTuple_GET_SIZE(mro);
3185 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003186 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003187 break;
3188 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003189 if (i >= n && PyType_Check(su->obj)) {
3190 mro = ((PyTypeObject *)(su->obj))->tp_mro;
3191 assert(mro != NULL && PyTuple_Check(mro));
3192 n = PyTuple_GET_SIZE(mro);
3193 for (i = 0; i < n; i++) {
3194 if ((PyObject *)(su->type) ==
3195 PyTuple_GET_ITEM(mro, i))
3196 break;
3197 }
3198 if (i >= n) {
3199 PyErr_SetString(PyExc_TypeError,
3200 "bogus super object");
3201 return NULL;
3202 }
3203 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003204 i++;
3205 res = NULL;
3206 for (; i < n; i++) {
3207 tmp = PyTuple_GET_ITEM(mro, i);
3208 assert(PyType_Check(tmp));
3209 res = PyDict_GetItem(
3210 ((PyTypeObject *)tmp)->tp_defined, name);
3211 if (res != NULL) {
3212 Py_INCREF(res);
3213 f = res->ob_type->tp_descr_get;
3214 if (f != NULL) {
3215 tmp = f(res, su->obj, res);
3216 Py_DECREF(res);
3217 res = tmp;
3218 }
3219 return res;
3220 }
3221 }
3222 }
3223 return PyObject_GenericGetAttr(self, name);
3224}
3225
3226static PyObject *
3227super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3228{
3229 superobject *su = (superobject *)self;
3230 superobject *new;
3231
3232 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3233 /* Not binding to an object, or already bound */
3234 Py_INCREF(self);
3235 return self;
3236 }
3237 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3238 if (new == NULL)
3239 return NULL;
3240 Py_INCREF(su->type);
3241 Py_INCREF(obj);
3242 new->type = su->type;
3243 new->obj = obj;
3244 return (PyObject *)new;
3245}
3246
3247static int
3248super_init(PyObject *self, PyObject *args, PyObject *kwds)
3249{
3250 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003251 PyTypeObject *type;
3252 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003253
3254 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3255 return -1;
3256 if (obj == Py_None)
3257 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003258 if (obj != NULL &&
3259 !PyType_IsSubtype(obj->ob_type, type) &&
3260 !(PyType_Check(obj) &&
3261 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003262 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003263 "super(type, obj): "
3264 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003265 return -1;
3266 }
3267 Py_INCREF(type);
3268 Py_XINCREF(obj);
3269 su->type = type;
3270 su->obj = obj;
3271 return 0;
3272}
3273
3274static char super_doc[] =
3275"super(type) -> unbound super object\n"
3276"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003277"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003278"Typical use to call a cooperative superclass method:\n"
3279"class C(B):\n"
3280" def meth(self, arg):\n"
3281" super(C, self).meth(arg)";
3282
3283PyTypeObject PySuper_Type = {
3284 PyObject_HEAD_INIT(&PyType_Type)
3285 0, /* ob_size */
3286 "super", /* tp_name */
3287 sizeof(superobject), /* tp_basicsize */
3288 0, /* tp_itemsize */
3289 /* methods */
3290 super_dealloc, /* tp_dealloc */
3291 0, /* tp_print */
3292 0, /* tp_getattr */
3293 0, /* tp_setattr */
3294 0, /* tp_compare */
3295 0, /* tp_repr */
3296 0, /* tp_as_number */
3297 0, /* tp_as_sequence */
3298 0, /* tp_as_mapping */
3299 0, /* tp_hash */
3300 0, /* tp_call */
3301 0, /* tp_str */
3302 super_getattro, /* tp_getattro */
3303 0, /* tp_setattro */
3304 0, /* tp_as_buffer */
Guido van Rossum31bcff82001-08-30 04:37:15 +00003305 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003306 super_doc, /* tp_doc */
3307 0, /* tp_traverse */
3308 0, /* tp_clear */
3309 0, /* tp_richcompare */
3310 0, /* tp_weaklistoffset */
3311 0, /* tp_iter */
3312 0, /* tp_iternext */
3313 0, /* tp_methods */
3314 0, /* tp_members */
3315 0, /* tp_getset */
3316 0, /* tp_base */
3317 0, /* tp_dict */
3318 super_descr_get, /* tp_descr_get */
3319 0, /* tp_descr_set */
3320 0, /* tp_dictoffset */
3321 super_init, /* tp_init */
3322 PyType_GenericAlloc, /* tp_alloc */
3323 PyType_GenericNew, /* tp_new */
3324 _PyObject_Del, /* tp_free */
3325};