blob: f15b096580bf8faf66014530f0b48c08784a6c4a [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
Guido van Rossum9478d072001-09-07 18:52:13 +0000276 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
277 return b == a || b == &PyBaseObject_Type;
278
Tim Peters6d6c1a32001-08-02 04:15:00 +0000279 mro = a->tp_mro;
280 if (mro != NULL) {
281 /* Deal with multiple inheritance without recursion
282 by walking the MRO tuple */
283 int i, n;
284 assert(PyTuple_Check(mro));
285 n = PyTuple_GET_SIZE(mro);
286 for (i = 0; i < n; i++) {
287 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
288 return 1;
289 }
290 return 0;
291 }
292 else {
293 /* a is not completely initilized yet; follow tp_base */
294 do {
295 if (a == b)
296 return 1;
297 a = a->tp_base;
298 } while (a != NULL);
299 return b == &PyBaseObject_Type;
300 }
301}
302
Guido van Rossum60718732001-08-28 17:47:51 +0000303/* Internal routine to do a method lookup in the type
304 without looking in the instance dictionary
305 (so we can't use PyObject_GetAttr) but still binding
306 it to the instance. The arguments are the object,
307 the method name as a C string, and the address of a
308 static variable used to cache the interned Python string. */
309
310static PyObject *
311lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
312{
313 PyObject *res;
314
315 if (*attrobj == NULL) {
316 *attrobj = PyString_InternFromString(attrstr);
317 if (*attrobj == NULL)
318 return NULL;
319 }
320 res = _PyType_Lookup(self->ob_type, *attrobj);
321 if (res == NULL)
322 PyErr_SetObject(PyExc_AttributeError, *attrobj);
323 else {
324 descrgetfunc f;
325 if ((f = res->ob_type->tp_descr_get) == NULL)
326 Py_INCREF(res);
327 else
328 res = f(res, self, (PyObject *)(self->ob_type));
329 }
330 return res;
331}
332
Guido van Rossum2730b132001-08-28 18:22:14 +0000333/* A variation of PyObject_CallMethod that uses lookup_method()
334 instead of PyObject_GetAttrString(). This uses the same convention
335 as lookup_method to cache the interned name string object. */
336
337PyObject *
338call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
339{
340 va_list va;
341 PyObject *args, *func = 0, *retval;
342 PyObject *dummy_str = NULL;
343 va_start(va, format);
344
345 func = lookup_method(o, name, &dummy_str);
346 Py_XDECREF(dummy_str);
347 if (func == NULL) {
348 va_end(va);
349 PyErr_SetString(PyExc_AttributeError, name);
350 return 0;
351 }
352
353 if (format && *format)
354 args = Py_VaBuildValue(format, va);
355 else
356 args = PyTuple_New(0);
357
358 va_end(va);
359
360 if (!args)
361 return NULL;
362
363 if (!PyTuple_Check(args)) {
364 PyObject *a;
365
366 a = PyTuple_New(1);
367 if (a == NULL)
368 return NULL;
369 if (PyTuple_SetItem(a, 0, args) < 0)
370 return NULL;
371 args = a;
372 }
373
374 retval = PyObject_CallObject(func, args);
375
376 Py_DECREF(args);
377 Py_DECREF(func);
378
379 return retval;
380}
381
Tim Peters6d6c1a32001-08-02 04:15:00 +0000382/* Method resolution order algorithm from "Putting Metaclasses to Work"
383 by Forman and Danforth (Addison-Wesley 1999). */
384
385static int
386conservative_merge(PyObject *left, PyObject *right)
387{
388 int left_size;
389 int right_size;
390 int i, j, r, ok;
391 PyObject *temp, *rr;
392
393 assert(PyList_Check(left));
394 assert(PyList_Check(right));
395
396 again:
397 left_size = PyList_GET_SIZE(left);
398 right_size = PyList_GET_SIZE(right);
399 for (i = 0; i < left_size; i++) {
400 for (j = 0; j < right_size; j++) {
401 if (PyList_GET_ITEM(left, i) ==
402 PyList_GET_ITEM(right, j)) {
403 /* found a merge point */
404 temp = PyList_New(0);
405 if (temp == NULL)
406 return -1;
407 for (r = 0; r < j; r++) {
408 rr = PyList_GET_ITEM(right, r);
409 ok = PySequence_Contains(left, rr);
410 if (ok < 0) {
411 Py_DECREF(temp);
412 return -1;
413 }
414 if (!ok) {
415 ok = PyList_Append(temp, rr);
416 if (ok < 0) {
417 Py_DECREF(temp);
418 return -1;
419 }
420 }
421 }
422 ok = PyList_SetSlice(left, i, i, temp);
423 Py_DECREF(temp);
424 if (ok < 0)
425 return -1;
426 ok = PyList_SetSlice(right, 0, j+1, NULL);
427 if (ok < 0)
428 return -1;
429 goto again;
430 }
431 }
432 }
433 return PyList_SetSlice(left, left_size, left_size, right);
434}
435
436static int
437serious_order_disagreements(PyObject *left, PyObject *right)
438{
439 return 0; /* XXX later -- for now, we cheat: "don't do that" */
440}
441
442static PyObject *
443mro_implementation(PyTypeObject *type)
444{
445 int i, n, ok;
446 PyObject *bases, *result;
447
448 bases = type->tp_bases;
449 n = PyTuple_GET_SIZE(bases);
450 result = Py_BuildValue("[O]", (PyObject *)type);
451 if (result == NULL)
452 return NULL;
453 for (i = 0; i < n; i++) {
454 PyTypeObject *base =
455 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
456 PyObject *parentMRO = PySequence_List(base->tp_mro);
457 if (parentMRO == NULL) {
458 Py_DECREF(result);
459 return NULL;
460 }
461 if (serious_order_disagreements(result, parentMRO)) {
462 Py_DECREF(result);
463 return NULL;
464 }
465 ok = conservative_merge(result, parentMRO);
466 Py_DECREF(parentMRO);
467 if (ok < 0) {
468 Py_DECREF(result);
469 return NULL;
470 }
471 }
472 return result;
473}
474
475static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000476mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000477{
478 PyTypeObject *type = (PyTypeObject *)self;
479
Tim Peters6d6c1a32001-08-02 04:15:00 +0000480 return mro_implementation(type);
481}
482
483static int
484mro_internal(PyTypeObject *type)
485{
486 PyObject *mro, *result, *tuple;
487
488 if (type->ob_type == &PyType_Type) {
489 result = mro_implementation(type);
490 }
491 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000492 static PyObject *mro_str;
493 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000494 if (mro == NULL)
495 return -1;
496 result = PyObject_CallObject(mro, NULL);
497 Py_DECREF(mro);
498 }
499 if (result == NULL)
500 return -1;
501 tuple = PySequence_Tuple(result);
502 Py_DECREF(result);
503 type->tp_mro = tuple;
504 return 0;
505}
506
507
508/* Calculate the best base amongst multiple base classes.
509 This is the first one that's on the path to the "solid base". */
510
511static PyTypeObject *
512best_base(PyObject *bases)
513{
514 int i, n;
515 PyTypeObject *base, *winner, *candidate, *base_i;
516
517 assert(PyTuple_Check(bases));
518 n = PyTuple_GET_SIZE(bases);
519 assert(n > 0);
520 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
521 winner = &PyBaseObject_Type;
522 for (i = 0; i < n; i++) {
523 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
524 if (!PyType_Check((PyObject *)base_i)) {
525 PyErr_SetString(
526 PyExc_TypeError,
527 "bases must be types");
528 return NULL;
529 }
530 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000531 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000532 return NULL;
533 }
534 candidate = solid_base(base_i);
535 if (PyType_IsSubtype(winner, candidate))
536 ;
537 else if (PyType_IsSubtype(candidate, winner)) {
538 winner = candidate;
539 base = base_i;
540 }
541 else {
542 PyErr_SetString(
543 PyExc_TypeError,
544 "multiple bases have "
545 "instance lay-out conflict");
546 return NULL;
547 }
548 }
549 assert(base != NULL);
550 return base;
551}
552
553static int
554extra_ivars(PyTypeObject *type, PyTypeObject *base)
555{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000556 size_t t_size = type->tp_basicsize;
557 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000558
Guido van Rossum9676b222001-08-17 20:32:36 +0000559 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000560 if (type->tp_itemsize || base->tp_itemsize) {
561 /* If itemsize is involved, stricter rules */
562 return t_size != b_size ||
563 type->tp_itemsize != base->tp_itemsize;
564 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000565 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
566 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
567 t_size -= sizeof(PyObject *);
568 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
569 type->tp_dictoffset + sizeof(PyObject *) == t_size)
570 t_size -= sizeof(PyObject *);
571
572 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000573}
574
575static PyTypeObject *
576solid_base(PyTypeObject *type)
577{
578 PyTypeObject *base;
579
580 if (type->tp_base)
581 base = solid_base(type->tp_base);
582 else
583 base = &PyBaseObject_Type;
584 if (extra_ivars(type, base))
585 return type;
586 else
587 return base;
588}
589
590staticforward void object_dealloc(PyObject *);
591staticforward int object_init(PyObject *, PyObject *, PyObject *);
592
593static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000594subtype_dict(PyObject *obj, void *context)
595{
596 PyObject **dictptr = _PyObject_GetDictPtr(obj);
597 PyObject *dict;
598
599 if (dictptr == NULL) {
600 PyErr_SetString(PyExc_AttributeError,
601 "This object has no __dict__");
602 return NULL;
603 }
604 dict = *dictptr;
605 if (dict == NULL) {
606 Py_INCREF(Py_None);
607 return Py_None;
608 }
609 else {
610 Py_INCREF(dict);
611 return dict;
612 }
613}
614
615struct getsetlist subtype_getsets[] = {
616 {"__dict__", subtype_dict, NULL, NULL},
617 {0},
618};
619
620static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000621type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
622{
623 PyObject *name, *bases, *dict;
624 static char *kwlist[] = {"name", "bases", "dict", 0};
625 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000626 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000627 etype *et;
628 struct memberlist *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000629 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000630
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000631 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000632 if (metatype == &PyType_Type &&
633 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
634 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000635 PyObject *x = PyTuple_GET_ITEM(args, 0);
636 Py_INCREF(x->ob_type);
637 return (PyObject *) x->ob_type;
638 }
639
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000640 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000641 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
642 &name,
643 &PyTuple_Type, &bases,
644 &PyDict_Type, &dict))
645 return NULL;
646
647 /* Determine the proper metatype to deal with this,
648 and check for metatype conflicts while we're at it.
649 Note that if some other metatype wins to contract,
650 it's possible that its instances are not types. */
651 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000652 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000653 for (i = 0; i < nbases; i++) {
654 tmp = PyTuple_GET_ITEM(bases, i);
655 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000656 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000657 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000658 if (PyType_IsSubtype(tmptype, winner)) {
659 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000660 continue;
661 }
662 PyErr_SetString(PyExc_TypeError,
663 "metatype conflict among bases");
664 return NULL;
665 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000666 if (winner != metatype) {
667 if (winner->tp_new != type_new) /* Pass it to the winner */
668 return winner->tp_new(winner, args, kwds);
669 metatype = winner;
670 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000671
672 /* Adjust for empty tuple bases */
673 if (nbases == 0) {
674 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
675 if (bases == NULL)
676 return NULL;
677 nbases = 1;
678 }
679 else
680 Py_INCREF(bases);
681
682 /* XXX From here until type is allocated, "return NULL" leaks bases! */
683
684 /* Calculate best base, and check that all bases are type objects */
685 base = best_base(bases);
686 if (base == NULL)
687 return NULL;
688 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
689 PyErr_Format(PyExc_TypeError,
690 "type '%.100s' is not an acceptable base type",
691 base->tp_name);
692 return NULL;
693 }
694
Guido van Rossum1a493502001-08-17 16:47:50 +0000695 /* Should this be a dynamic class (i.e. modifiable __dict__)?
696 Look in two places for a variable named __dynamic__:
697 1) in the class dict
698 2) in the module dict (globals)
699 The first variable that is an int >= 0 is used.
700 Otherwise, a default is calculated from the base classes:
701 if any base class is dynamic, this class is dynamic; otherwise
702 it is static. */
703 dynamic = -1; /* Not yet determined */
704 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000705 tmp = PyDict_GetItemString(dict, "__dynamic__");
706 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000707 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000708 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000709 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000710 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000711 if (dynamic < 0) {
712 /* Look in the module globals */
713 tmp = PyEval_GetGlobals();
714 if (tmp != NULL) {
715 tmp = PyDict_GetItemString(tmp, "__dynamic__");
716 if (tmp != NULL) {
717 dynamic = PyInt_AsLong(tmp);
718 if (dynamic < 0)
719 PyErr_Clear();
720 }
721 }
722 }
723 if (dynamic < 0) {
724 /* Make a new class dynamic if any of its bases is
725 dynamic. This is not always the same as inheriting
726 the __dynamic__ class attribute! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000727 dynamic = 0;
728 for (i = 0; i < nbases; i++) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000729 tmptype = (PyTypeObject *)
730 PyTuple_GET_ITEM(bases, i);
731 if (tmptype->tp_flags &
732 Py_TPFLAGS_DYNAMICTYPE) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000733 dynamic = 1;
734 break;
735 }
736 }
737 }
738
739 /* Check for a __slots__ sequence variable in dict, and count it */
740 slots = PyDict_GetItemString(dict, "__slots__");
741 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000742 add_dict = 0;
743 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000744 if (slots != NULL) {
745 /* Make it into a tuple */
746 if (PyString_Check(slots))
747 slots = Py_BuildValue("(O)", slots);
748 else
749 slots = PySequence_Tuple(slots);
750 if (slots == NULL)
751 return NULL;
752 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000753 if (nslots > 0 && base->tp_itemsize != 0) {
754 PyErr_Format(PyExc_TypeError,
755 "nonempty __slots__ "
756 "not supported for subtype of '%s'",
757 base->tp_name);
758 return NULL;
759 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000760 for (i = 0; i < nslots; i++) {
761 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
762 PyErr_SetString(PyExc_TypeError,
763 "__slots__ must be a sequence of strings");
764 Py_DECREF(slots);
765 return NULL;
766 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000767 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000768 }
769 }
770 if (slots == NULL && base->tp_dictoffset == 0 &&
771 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000772 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000773 add_dict++;
774 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000775 if (slots == NULL && base->tp_weaklistoffset == 0 &&
776 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000777 nslots++;
778 add_weak++;
779 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000780
781 /* XXX From here until type is safely allocated,
782 "return NULL" may leak slots! */
783
784 /* Allocate the type object */
785 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
786 if (type == NULL)
787 return NULL;
788
789 /* Keep name and slots alive in the extended type object */
790 et = (etype *)type;
791 Py_INCREF(name);
792 et->name = name;
793 et->slots = slots;
794
Guido van Rossumdc91b992001-08-08 22:26:22 +0000795 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000796 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
797 Py_TPFLAGS_BASETYPE;
798 if (dynamic)
799 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000800
801 /* It's a new-style number unless it specifically inherits any
802 old-style numeric behavior */
803 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
804 (base->tp_as_number == NULL))
805 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
806
807 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000808 type->tp_as_number = &et->as_number;
809 type->tp_as_sequence = &et->as_sequence;
810 type->tp_as_mapping = &et->as_mapping;
811 type->tp_as_buffer = &et->as_buffer;
812 type->tp_name = PyString_AS_STRING(name);
813
814 /* Set tp_base and tp_bases */
815 type->tp_bases = bases;
816 Py_INCREF(base);
817 type->tp_base = base;
818
819 /* Initialize tp_defined from passed-in dict */
820 type->tp_defined = dict = PyDict_Copy(dict);
821 if (dict == NULL) {
822 Py_DECREF(type);
823 return NULL;
824 }
825
Guido van Rossumc3542212001-08-16 09:18:56 +0000826 /* Set __module__ in the dict */
827 if (PyDict_GetItemString(dict, "__module__") == NULL) {
828 tmp = PyEval_GetGlobals();
829 if (tmp != NULL) {
830 tmp = PyDict_GetItemString(tmp, "__name__");
831 if (tmp != NULL) {
832 if (PyDict_SetItemString(dict, "__module__",
833 tmp) < 0)
834 return NULL;
835 }
836 }
837 }
838
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839 /* Special-case __new__: if it's a plain function,
840 make it a static function */
841 tmp = PyDict_GetItemString(dict, "__new__");
842 if (tmp != NULL && PyFunction_Check(tmp)) {
843 tmp = PyStaticMethod_New(tmp);
844 if (tmp == NULL) {
845 Py_DECREF(type);
846 return NULL;
847 }
848 PyDict_SetItemString(dict, "__new__", tmp);
849 Py_DECREF(tmp);
850 }
851
852 /* Add descriptors for custom slots from __slots__, or for __dict__ */
853 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000854 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000855 if (slots != NULL) {
856 for (i = 0; i < nslots; i++, mp++) {
857 mp->name = PyString_AS_STRING(
858 PyTuple_GET_ITEM(slots, i));
859 mp->type = T_OBJECT;
860 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000861 if (base->tp_weaklistoffset == 0 &&
862 strcmp(mp->name, "__weakref__") == 0)
863 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000864 slotoffset += sizeof(PyObject *);
865 }
866 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000867 else {
868 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000869 if (base->tp_itemsize)
Tim Peters017cb2c2001-08-30 20:07:55 +0000870 type->tp_dictoffset = -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000871 else
872 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000873 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000874 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000875 }
876 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000877 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000878 type->tp_weaklistoffset = slotoffset;
879 mp->name = "__weakref__";
880 mp->type = T_OBJECT;
881 mp->offset = slotoffset;
882 mp->readonly = 1;
883 mp++;
884 slotoffset += sizeof(PyObject *);
885 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000886 }
887 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000888 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000889 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000890
891 /* Special case some slots */
892 if (type->tp_dictoffset != 0 || nslots > 0) {
893 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
894 type->tp_getattro = PyObject_GenericGetAttr;
895 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
896 type->tp_setattro = PyObject_GenericSetAttr;
897 }
898 type->tp_dealloc = subtype_dealloc;
899
900 /* Always override allocation strategy to use regular heap */
901 type->tp_alloc = PyType_GenericAlloc;
902 type->tp_free = _PyObject_Del;
903
904 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000905 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000906 Py_DECREF(type);
907 return NULL;
908 }
909
910 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +0000911 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
912 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000913
Tim Peters6d6c1a32001-08-02 04:15:00 +0000914 return (PyObject *)type;
915}
916
917/* Internal API to look for a name through the MRO.
918 This returns a borrowed reference, and doesn't set an exception! */
919PyObject *
920_PyType_Lookup(PyTypeObject *type, PyObject *name)
921{
922 int i, n;
923 PyObject *mro, *res, *dict;
924
925 /* For static types, look in tp_dict */
926 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
927 dict = type->tp_dict;
928 assert(dict && PyDict_Check(dict));
929 return PyDict_GetItem(dict, name);
930 }
931
932 /* For dynamic types, look in tp_defined of types in MRO */
933 mro = type->tp_mro;
934 assert(PyTuple_Check(mro));
935 n = PyTuple_GET_SIZE(mro);
936 for (i = 0; i < n; i++) {
937 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
938 assert(PyType_Check(type));
939 dict = type->tp_defined;
940 assert(dict && PyDict_Check(dict));
941 res = PyDict_GetItem(dict, name);
942 if (res != NULL)
943 return res;
944 }
945 return NULL;
946}
947
948/* This is similar to PyObject_GenericGetAttr(),
949 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
950static PyObject *
951type_getattro(PyTypeObject *type, PyObject *name)
952{
953 PyTypeObject *metatype = type->ob_type;
954 PyObject *descr, *res;
955 descrgetfunc f;
956
957 /* Initialize this type (we'll assume the metatype is initialized) */
958 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000959 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000960 return NULL;
961 }
962
963 /* Get a descriptor from the metatype */
964 descr = _PyType_Lookup(metatype, name);
965 f = NULL;
966 if (descr != NULL) {
967 f = descr->ob_type->tp_descr_get;
968 if (f != NULL && PyDescr_IsData(descr))
969 return f(descr,
970 (PyObject *)type, (PyObject *)metatype);
971 }
972
973 /* Look in tp_defined of this type and its bases */
974 res = _PyType_Lookup(type, name);
975 if (res != NULL) {
976 f = res->ob_type->tp_descr_get;
977 if (f != NULL)
978 return f(res, (PyObject *)NULL, (PyObject *)type);
979 Py_INCREF(res);
980 return res;
981 }
982
983 /* Use the descriptor from the metatype */
984 if (f != NULL) {
985 res = f(descr, (PyObject *)type, (PyObject *)metatype);
986 return res;
987 }
988 if (descr != NULL) {
989 Py_INCREF(descr);
990 return descr;
991 }
992
993 /* Give up */
994 PyErr_Format(PyExc_AttributeError,
995 "type object '%.50s' has no attribute '%.400s'",
996 type->tp_name, PyString_AS_STRING(name));
997 return NULL;
998}
999
1000static int
1001type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1002{
1003 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
1004 return PyObject_GenericSetAttr((PyObject *)type, name, value);
1005 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
1006 return -1;
1007}
1008
1009static void
1010type_dealloc(PyTypeObject *type)
1011{
1012 etype *et;
1013
1014 /* Assert this is a heap-allocated type object */
1015 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
1016 et = (etype *)type;
1017 Py_XDECREF(type->tp_base);
1018 Py_XDECREF(type->tp_dict);
1019 Py_XDECREF(type->tp_bases);
1020 Py_XDECREF(type->tp_mro);
1021 Py_XDECREF(type->tp_defined);
1022 /* XXX more? */
1023 Py_XDECREF(et->name);
1024 Py_XDECREF(et->slots);
1025 type->ob_type->tp_free((PyObject *)type);
1026}
1027
1028static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001029 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001030 "mro() -> list\nreturn a type's method resolution order"},
1031 {0}
1032};
1033
1034static char type_doc[] =
1035"type(object) -> the object's type\n"
1036"type(name, bases, dict) -> a new type";
1037
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001038PyTypeObject PyType_Type = {
1039 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001040 0, /* ob_size */
1041 "type", /* tp_name */
1042 sizeof(etype), /* tp_basicsize */
1043 sizeof(struct memberlist), /* tp_itemsize */
1044 (destructor)type_dealloc, /* tp_dealloc */
1045 0, /* tp_print */
1046 0, /* tp_getattr */
1047 0, /* tp_setattr */
1048 type_compare, /* tp_compare */
1049 (reprfunc)type_repr, /* tp_repr */
1050 0, /* tp_as_number */
1051 0, /* tp_as_sequence */
1052 0, /* tp_as_mapping */
1053 (hashfunc)_Py_HashPointer, /* tp_hash */
1054 (ternaryfunc)type_call, /* tp_call */
1055 0, /* tp_str */
1056 (getattrofunc)type_getattro, /* tp_getattro */
1057 (setattrofunc)type_setattro, /* tp_setattro */
1058 0, /* tp_as_buffer */
1059 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1060 type_doc, /* tp_doc */
1061 0, /* tp_traverse */
1062 0, /* tp_clear */
1063 0, /* tp_richcompare */
1064 0, /* tp_weaklistoffset */
1065 0, /* tp_iter */
1066 0, /* tp_iternext */
1067 type_methods, /* tp_methods */
1068 type_members, /* tp_members */
1069 type_getsets, /* tp_getset */
1070 0, /* tp_base */
1071 0, /* tp_dict */
1072 0, /* tp_descr_get */
1073 0, /* tp_descr_set */
1074 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1075 0, /* tp_init */
1076 0, /* tp_alloc */
1077 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001078};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079
1080
1081/* The base type of all types (eventually)... except itself. */
1082
1083static int
1084object_init(PyObject *self, PyObject *args, PyObject *kwds)
1085{
1086 return 0;
1087}
1088
1089static void
1090object_dealloc(PyObject *self)
1091{
1092 self->ob_type->tp_free(self);
1093}
1094
Guido van Rossum8e248182001-08-12 05:17:56 +00001095static PyObject *
1096object_repr(PyObject *self)
1097{
Guido van Rossum76e69632001-08-16 18:52:43 +00001098 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001099 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001100
Guido van Rossum76e69632001-08-16 18:52:43 +00001101 type = self->ob_type;
1102 mod = type_module(type, NULL);
1103 if (mod == NULL)
1104 PyErr_Clear();
1105 else if (!PyString_Check(mod)) {
1106 Py_DECREF(mod);
1107 mod = NULL;
1108 }
1109 name = type_name(type, NULL);
1110 if (name == NULL)
1111 return NULL;
1112 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Barry Warsaw7ce36942001-08-24 18:34:26 +00001113 rtn = PyString_FromFormat("<%s.%s instance at %p>",
1114 PyString_AS_STRING(mod),
1115 PyString_AS_STRING(name),
1116 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001117 else
Barry Warsaw7ce36942001-08-24 18:34:26 +00001118 rtn = PyString_FromFormat("<%s instance at %p>",
1119 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001120 Py_XDECREF(mod);
1121 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001122 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001123}
1124
Guido van Rossumb8f63662001-08-15 23:57:02 +00001125static PyObject *
1126object_str(PyObject *self)
1127{
1128 unaryfunc f;
1129
1130 f = self->ob_type->tp_repr;
1131 if (f == NULL)
1132 f = object_repr;
1133 return f(self);
1134}
1135
Guido van Rossum8e248182001-08-12 05:17:56 +00001136static long
1137object_hash(PyObject *self)
1138{
1139 return _Py_HashPointer(self);
1140}
Guido van Rossum8e248182001-08-12 05:17:56 +00001141
Tim Peters6d6c1a32001-08-02 04:15:00 +00001142static void
1143object_free(PyObject *self)
1144{
1145 PyObject_Del(self);
1146}
1147
1148static struct memberlist object_members[] = {
1149 {"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
1150 {0}
1151};
1152
1153PyTypeObject PyBaseObject_Type = {
1154 PyObject_HEAD_INIT(&PyType_Type)
1155 0, /* ob_size */
1156 "object", /* tp_name */
1157 sizeof(PyObject), /* tp_basicsize */
1158 0, /* tp_itemsize */
1159 (destructor)object_dealloc, /* tp_dealloc */
1160 0, /* tp_print */
1161 0, /* tp_getattr */
1162 0, /* tp_setattr */
1163 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001164 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165 0, /* tp_as_number */
1166 0, /* tp_as_sequence */
1167 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001168 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001169 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001170 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001172 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173 0, /* tp_as_buffer */
1174 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1175 "The most base type", /* tp_doc */
1176 0, /* tp_traverse */
1177 0, /* tp_clear */
1178 0, /* tp_richcompare */
1179 0, /* tp_weaklistoffset */
1180 0, /* tp_iter */
1181 0, /* tp_iternext */
1182 0, /* tp_methods */
1183 object_members, /* tp_members */
1184 0, /* tp_getset */
1185 0, /* tp_base */
1186 0, /* tp_dict */
1187 0, /* tp_descr_get */
1188 0, /* tp_descr_set */
1189 0, /* tp_dictoffset */
1190 object_init, /* tp_init */
1191 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001192 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001193 object_free, /* tp_free */
1194};
1195
1196
1197/* Initialize the __dict__ in a type object */
1198
1199static int
1200add_methods(PyTypeObject *type, PyMethodDef *meth)
1201{
1202 PyObject *dict = type->tp_defined;
1203
1204 for (; meth->ml_name != NULL; meth++) {
1205 PyObject *descr;
1206 if (PyDict_GetItemString(dict, meth->ml_name))
1207 continue;
1208 descr = PyDescr_NewMethod(type, meth);
1209 if (descr == NULL)
1210 return -1;
1211 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1212 return -1;
1213 Py_DECREF(descr);
1214 }
1215 return 0;
1216}
1217
1218static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00001219add_members(PyTypeObject *type, struct memberlist *memb)
1220{
1221 PyObject *dict = type->tp_defined;
1222
1223 for (; memb->name != NULL; memb++) {
1224 PyObject *descr;
1225 if (PyDict_GetItemString(dict, memb->name))
1226 continue;
1227 descr = PyDescr_NewMember(type, memb);
1228 if (descr == NULL)
1229 return -1;
1230 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1231 return -1;
1232 Py_DECREF(descr);
1233 }
1234 return 0;
1235}
1236
1237static int
1238add_getset(PyTypeObject *type, struct getsetlist *gsp)
1239{
1240 PyObject *dict = type->tp_defined;
1241
1242 for (; gsp->name != NULL; gsp++) {
1243 PyObject *descr;
1244 if (PyDict_GetItemString(dict, gsp->name))
1245 continue;
1246 descr = PyDescr_NewGetSet(type, gsp);
1247
1248 if (descr == NULL)
1249 return -1;
1250 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1251 return -1;
1252 Py_DECREF(descr);
1253 }
1254 return 0;
1255}
1256
Guido van Rossum13d52f02001-08-10 21:24:08 +00001257static void
1258inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001259{
1260 int oldsize, newsize;
1261
Guido van Rossum13d52f02001-08-10 21:24:08 +00001262 /* Special flag magic */
1263 if (!type->tp_as_buffer && base->tp_as_buffer) {
1264 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1265 type->tp_flags |=
1266 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1267 }
1268 if (!type->tp_as_sequence && base->tp_as_sequence) {
1269 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1270 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1271 }
1272 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1273 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1274 if ((!type->tp_as_number && base->tp_as_number) ||
1275 (!type->tp_as_sequence && base->tp_as_sequence)) {
1276 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1277 if (!type->tp_as_number && !type->tp_as_sequence) {
1278 type->tp_flags |= base->tp_flags &
1279 Py_TPFLAGS_HAVE_INPLACEOPS;
1280 }
1281 }
1282 /* Wow */
1283 }
1284 if (!type->tp_as_number && base->tp_as_number) {
1285 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1286 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1287 }
1288
1289 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001290 oldsize = base->tp_basicsize;
1291 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1292 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1293 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001294 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1295 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001296 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001297 if (type->tp_traverse == NULL)
1298 type->tp_traverse = base->tp_traverse;
1299 if (type->tp_clear == NULL)
1300 type->tp_clear = base->tp_clear;
1301 }
1302 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1303 if (base != &PyBaseObject_Type ||
1304 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1305 if (type->tp_new == NULL)
1306 type->tp_new = base->tp_new;
1307 }
1308 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001309 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001310
1311 /* Copy other non-function slots */
1312
1313#undef COPYVAL
1314#define COPYVAL(SLOT) \
1315 if (type->SLOT == 0) type->SLOT = base->SLOT
1316
1317 COPYVAL(tp_itemsize);
1318 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1319 COPYVAL(tp_weaklistoffset);
1320 }
1321 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1322 COPYVAL(tp_dictoffset);
1323 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001324}
1325
1326static void
1327inherit_slots(PyTypeObject *type, PyTypeObject *base)
1328{
1329 PyTypeObject *basebase;
1330
1331#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332#undef COPYSLOT
1333#undef COPYNUM
1334#undef COPYSEQ
1335#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001336
1337#define SLOTDEFINED(SLOT) \
1338 (base->SLOT != 0 && \
1339 (basebase == NULL || base->SLOT != basebase->SLOT))
1340
Tim Peters6d6c1a32001-08-02 04:15:00 +00001341#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001342 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001343
1344#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1345#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1346#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1347
Guido van Rossum13d52f02001-08-10 21:24:08 +00001348 /* This won't inherit indirect slots (from tp_as_number etc.)
1349 if type doesn't provide the space. */
1350
1351 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1352 basebase = base->tp_base;
1353 if (basebase->tp_as_number == NULL)
1354 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355 COPYNUM(nb_add);
1356 COPYNUM(nb_subtract);
1357 COPYNUM(nb_multiply);
1358 COPYNUM(nb_divide);
1359 COPYNUM(nb_remainder);
1360 COPYNUM(nb_divmod);
1361 COPYNUM(nb_power);
1362 COPYNUM(nb_negative);
1363 COPYNUM(nb_positive);
1364 COPYNUM(nb_absolute);
1365 COPYNUM(nb_nonzero);
1366 COPYNUM(nb_invert);
1367 COPYNUM(nb_lshift);
1368 COPYNUM(nb_rshift);
1369 COPYNUM(nb_and);
1370 COPYNUM(nb_xor);
1371 COPYNUM(nb_or);
1372 COPYNUM(nb_coerce);
1373 COPYNUM(nb_int);
1374 COPYNUM(nb_long);
1375 COPYNUM(nb_float);
1376 COPYNUM(nb_oct);
1377 COPYNUM(nb_hex);
1378 COPYNUM(nb_inplace_add);
1379 COPYNUM(nb_inplace_subtract);
1380 COPYNUM(nb_inplace_multiply);
1381 COPYNUM(nb_inplace_divide);
1382 COPYNUM(nb_inplace_remainder);
1383 COPYNUM(nb_inplace_power);
1384 COPYNUM(nb_inplace_lshift);
1385 COPYNUM(nb_inplace_rshift);
1386 COPYNUM(nb_inplace_and);
1387 COPYNUM(nb_inplace_xor);
1388 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001389 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1390 COPYNUM(nb_true_divide);
1391 COPYNUM(nb_floor_divide);
1392 COPYNUM(nb_inplace_true_divide);
1393 COPYNUM(nb_inplace_floor_divide);
1394 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001395 }
1396
Guido van Rossum13d52f02001-08-10 21:24:08 +00001397 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1398 basebase = base->tp_base;
1399 if (basebase->tp_as_sequence == NULL)
1400 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001401 COPYSEQ(sq_length);
1402 COPYSEQ(sq_concat);
1403 COPYSEQ(sq_repeat);
1404 COPYSEQ(sq_item);
1405 COPYSEQ(sq_slice);
1406 COPYSEQ(sq_ass_item);
1407 COPYSEQ(sq_ass_slice);
1408 COPYSEQ(sq_contains);
1409 COPYSEQ(sq_inplace_concat);
1410 COPYSEQ(sq_inplace_repeat);
1411 }
1412
Guido van Rossum13d52f02001-08-10 21:24:08 +00001413 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1414 basebase = base->tp_base;
1415 if (basebase->tp_as_mapping == NULL)
1416 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001417 COPYMAP(mp_length);
1418 COPYMAP(mp_subscript);
1419 COPYMAP(mp_ass_subscript);
1420 }
1421
Guido van Rossum13d52f02001-08-10 21:24:08 +00001422 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001423
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424 COPYSLOT(tp_dealloc);
1425 COPYSLOT(tp_print);
1426 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1427 type->tp_getattr = base->tp_getattr;
1428 type->tp_getattro = base->tp_getattro;
1429 }
1430 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1431 type->tp_setattr = base->tp_setattr;
1432 type->tp_setattro = base->tp_setattro;
1433 }
1434 /* tp_compare see tp_richcompare */
1435 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001436 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001437 COPYSLOT(tp_call);
1438 COPYSLOT(tp_str);
1439 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001441 if (type->tp_compare == NULL &&
1442 type->tp_richcompare == NULL &&
1443 type->tp_hash == NULL)
1444 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001445 type->tp_compare = base->tp_compare;
1446 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001447 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001448 }
1449 }
1450 else {
1451 COPYSLOT(tp_compare);
1452 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1454 COPYSLOT(tp_iter);
1455 COPYSLOT(tp_iternext);
1456 }
1457 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1458 COPYSLOT(tp_descr_get);
1459 COPYSLOT(tp_descr_set);
1460 COPYSLOT(tp_dictoffset);
1461 COPYSLOT(tp_init);
1462 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463 COPYSLOT(tp_free);
1464 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001465}
1466
Guido van Rossum13d52f02001-08-10 21:24:08 +00001467staticforward int add_operators(PyTypeObject *);
1468
Tim Peters6d6c1a32001-08-02 04:15:00 +00001469int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001470PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001471{
1472 PyObject *dict, *bases, *x;
1473 PyTypeObject *base;
1474 int i, n;
1475
Guido van Rossumd614f972001-08-10 17:39:49 +00001476 if (type->tp_flags & Py_TPFLAGS_READY) {
1477 assert(type->tp_dict != NULL);
1478 return 0;
1479 }
1480 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1481 assert(type->tp_dict == NULL);
1482
1483 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484
1485 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1486 base = type->tp_base;
1487 if (base == NULL && type != &PyBaseObject_Type)
1488 base = type->tp_base = &PyBaseObject_Type;
1489
1490 /* Initialize tp_bases */
1491 bases = type->tp_bases;
1492 if (bases == NULL) {
1493 if (base == NULL)
1494 bases = PyTuple_New(0);
1495 else
1496 bases = Py_BuildValue("(O)", base);
1497 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001498 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001499 type->tp_bases = bases;
1500 }
1501
1502 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001503 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001504 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001505 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001506 }
1507
1508 /* Initialize tp_defined */
1509 dict = type->tp_defined;
1510 if (dict == NULL) {
1511 dict = PyDict_New();
1512 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001513 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001514 type->tp_defined = dict;
1515 }
1516
1517 /* Add type-specific descriptors to tp_defined */
1518 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001519 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001520 if (type->tp_methods != NULL) {
1521 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001522 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523 }
1524 if (type->tp_members != NULL) {
1525 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001526 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527 }
1528 if (type->tp_getset != NULL) {
1529 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001530 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531 }
1532
1533 /* Temporarily make tp_dict the same object as tp_defined.
1534 (This is needed to call mro(), and can stay this way for
1535 dynamic types). */
1536 Py_INCREF(type->tp_defined);
1537 type->tp_dict = type->tp_defined;
1538
1539 /* Calculate method resolution order */
1540 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001541 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001542 }
1543
Guido van Rossum13d52f02001-08-10 21:24:08 +00001544 /* Inherit special flags from dominant base */
1545 if (type->tp_base != NULL)
1546 inherit_special(type, type->tp_base);
1547
Tim Peters6d6c1a32001-08-02 04:15:00 +00001548 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001549 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001550 /* For a dynamic type, all slots are overridden */
1551 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001552 }
1553 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001555 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001557 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001558 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001559 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560 bases = type->tp_mro;
1561 assert(bases != NULL);
1562 assert(PyTuple_Check(bases));
1563 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001564 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001565 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1566 assert(PyType_Check(base));
1567 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001568 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001569 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001570 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571 }
1572 }
1573
Guido van Rossum13d52f02001-08-10 21:24:08 +00001574 /* Some more special stuff */
1575 base = type->tp_base;
1576 if (base != NULL) {
1577 if (type->tp_as_number == NULL)
1578 type->tp_as_number = base->tp_as_number;
1579 if (type->tp_as_sequence == NULL)
1580 type->tp_as_sequence = base->tp_as_sequence;
1581 if (type->tp_as_mapping == NULL)
1582 type->tp_as_mapping = base->tp_as_mapping;
1583 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001584
Guido van Rossum13d52f02001-08-10 21:24:08 +00001585 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001586 assert(type->tp_dict != NULL);
1587 type->tp_flags =
1588 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001590
1591 error:
1592 type->tp_flags &= ~Py_TPFLAGS_READYING;
1593 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001594}
1595
1596
1597/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1598
1599/* There's a wrapper *function* for each distinct function typedef used
1600 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1601 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1602 Most tables have only one entry; the tables for binary operators have two
1603 entries, one regular and one with reversed arguments. */
1604
1605static PyObject *
1606wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1607{
1608 inquiry func = (inquiry)wrapped;
1609 int res;
1610
1611 if (!PyArg_ParseTuple(args, ""))
1612 return NULL;
1613 res = (*func)(self);
1614 if (res == -1 && PyErr_Occurred())
1615 return NULL;
1616 return PyInt_FromLong((long)res);
1617}
1618
1619static struct wrapperbase tab_len[] = {
1620 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1621 {0}
1622};
1623
1624static PyObject *
1625wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1626{
1627 binaryfunc func = (binaryfunc)wrapped;
1628 PyObject *other;
1629
1630 if (!PyArg_ParseTuple(args, "O", &other))
1631 return NULL;
1632 return (*func)(self, other);
1633}
1634
1635static PyObject *
1636wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1637{
1638 binaryfunc func = (binaryfunc)wrapped;
1639 PyObject *other;
1640
1641 if (!PyArg_ParseTuple(args, "O", &other))
1642 return NULL;
1643 return (*func)(other, self);
1644}
1645
1646#undef BINARY
1647#define BINARY(NAME, OP) \
1648static struct wrapperbase tab_##NAME[] = { \
1649 {"__" #NAME "__", \
1650 (wrapperfunc)wrap_binaryfunc, \
1651 "x.__" #NAME "__(y) <==> " #OP}, \
1652 {"__r" #NAME "__", \
1653 (wrapperfunc)wrap_binaryfunc_r, \
1654 "y.__r" #NAME "__(x) <==> " #OP}, \
1655 {0} \
1656}
1657
1658BINARY(add, "x+y");
1659BINARY(sub, "x-y");
1660BINARY(mul, "x*y");
1661BINARY(div, "x/y");
1662BINARY(mod, "x%y");
1663BINARY(divmod, "divmod(x,y)");
1664BINARY(lshift, "x<<y");
1665BINARY(rshift, "x>>y");
1666BINARY(and, "x&y");
1667BINARY(xor, "x^y");
1668BINARY(or, "x|y");
1669
1670static PyObject *
1671wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1672{
1673 ternaryfunc func = (ternaryfunc)wrapped;
1674 PyObject *other;
1675 PyObject *third = Py_None;
1676
1677 /* Note: This wrapper only works for __pow__() */
1678
1679 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1680 return NULL;
1681 return (*func)(self, other, third);
1682}
1683
1684#undef TERNARY
1685#define TERNARY(NAME, OP) \
1686static struct wrapperbase tab_##NAME[] = { \
1687 {"__" #NAME "__", \
1688 (wrapperfunc)wrap_ternaryfunc, \
1689 "x.__" #NAME "__(y, z) <==> " #OP}, \
1690 {"__r" #NAME "__", \
1691 (wrapperfunc)wrap_ternaryfunc, \
1692 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1693 {0} \
1694}
1695
1696TERNARY(pow, "(x**y) % z");
1697
1698#undef UNARY
1699#define UNARY(NAME, OP) \
1700static struct wrapperbase tab_##NAME[] = { \
1701 {"__" #NAME "__", \
1702 (wrapperfunc)wrap_unaryfunc, \
1703 "x.__" #NAME "__() <==> " #OP}, \
1704 {0} \
1705}
1706
1707static PyObject *
1708wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1709{
1710 unaryfunc func = (unaryfunc)wrapped;
1711
1712 if (!PyArg_ParseTuple(args, ""))
1713 return NULL;
1714 return (*func)(self);
1715}
1716
1717UNARY(neg, "-x");
1718UNARY(pos, "+x");
1719UNARY(abs, "abs(x)");
1720UNARY(nonzero, "x != 0");
1721UNARY(invert, "~x");
1722UNARY(int, "int(x)");
1723UNARY(long, "long(x)");
1724UNARY(float, "float(x)");
1725UNARY(oct, "oct(x)");
1726UNARY(hex, "hex(x)");
1727
1728#undef IBINARY
1729#define IBINARY(NAME, OP) \
1730static struct wrapperbase tab_##NAME[] = { \
1731 {"__" #NAME "__", \
1732 (wrapperfunc)wrap_binaryfunc, \
1733 "x.__" #NAME "__(y) <==> " #OP}, \
1734 {0} \
1735}
1736
1737IBINARY(iadd, "x+=y");
1738IBINARY(isub, "x-=y");
1739IBINARY(imul, "x*=y");
1740IBINARY(idiv, "x/=y");
1741IBINARY(imod, "x%=y");
1742IBINARY(ilshift, "x<<=y");
1743IBINARY(irshift, "x>>=y");
1744IBINARY(iand, "x&=y");
1745IBINARY(ixor, "x^=y");
1746IBINARY(ior, "x|=y");
1747
1748#undef ITERNARY
1749#define ITERNARY(NAME, OP) \
1750static struct wrapperbase tab_##NAME[] = { \
1751 {"__" #NAME "__", \
1752 (wrapperfunc)wrap_ternaryfunc, \
1753 "x.__" #NAME "__(y) <==> " #OP}, \
1754 {0} \
1755}
1756
1757ITERNARY(ipow, "x = (x**y) % z");
1758
1759static struct wrapperbase tab_getitem[] = {
1760 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1761 "x.__getitem__(y) <==> x[y]"},
1762 {0}
1763};
1764
1765static PyObject *
1766wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1767{
1768 intargfunc func = (intargfunc)wrapped;
1769 int i;
1770
1771 if (!PyArg_ParseTuple(args, "i", &i))
1772 return NULL;
1773 return (*func)(self, i);
1774}
1775
1776static struct wrapperbase tab_mul_int[] = {
1777 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1778 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1779 {0}
1780};
1781
1782static struct wrapperbase tab_concat[] = {
1783 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1784 {0}
1785};
1786
1787static struct wrapperbase tab_imul_int[] = {
1788 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1789 {0}
1790};
1791
Guido van Rossum5d815f32001-08-17 21:57:47 +00001792static int
1793getindex(PyObject *self, PyObject *arg)
1794{
1795 int i;
1796
1797 i = PyInt_AsLong(arg);
1798 if (i == -1 && PyErr_Occurred())
1799 return -1;
1800 if (i < 0) {
1801 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
1802 if (sq && sq->sq_length) {
1803 int n = (*sq->sq_length)(self);
1804 if (n < 0)
1805 return -1;
1806 i += n;
1807 }
1808 }
1809 return i;
1810}
1811
1812static PyObject *
1813wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
1814{
1815 intargfunc func = (intargfunc)wrapped;
1816 PyObject *arg;
1817 int i;
1818
1819 if (!PyArg_ParseTuple(args, "O", &arg))
1820 return NULL;
1821 i = getindex(self, arg);
1822 if (i == -1 && PyErr_Occurred())
1823 return NULL;
1824 return (*func)(self, i);
1825}
1826
Tim Peters6d6c1a32001-08-02 04:15:00 +00001827static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001828 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001829 "x.__getitem__(i) <==> x[i]"},
1830 {0}
1831};
1832
1833static PyObject *
1834wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1835{
1836 intintargfunc func = (intintargfunc)wrapped;
1837 int i, j;
1838
1839 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1840 return NULL;
1841 return (*func)(self, i, j);
1842}
1843
1844static struct wrapperbase tab_getslice[] = {
1845 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1846 "x.__getslice__(i, j) <==> x[i:j]"},
1847 {0}
1848};
1849
1850static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001851wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001852{
1853 intobjargproc func = (intobjargproc)wrapped;
1854 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001855 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001856
Guido van Rossum5d815f32001-08-17 21:57:47 +00001857 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
1858 return NULL;
1859 i = getindex(self, arg);
1860 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00001861 return NULL;
1862 res = (*func)(self, i, value);
1863 if (res == -1 && PyErr_Occurred())
1864 return NULL;
1865 Py_INCREF(Py_None);
1866 return Py_None;
1867}
1868
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001869static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001870wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001871{
1872 intobjargproc func = (intobjargproc)wrapped;
1873 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001874 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001875
Guido van Rossum5d815f32001-08-17 21:57:47 +00001876 if (!PyArg_ParseTuple(args, "O", &arg))
1877 return NULL;
1878 i = getindex(self, arg);
1879 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001880 return NULL;
1881 res = (*func)(self, i, NULL);
1882 if (res == -1 && PyErr_Occurred())
1883 return NULL;
1884 Py_INCREF(Py_None);
1885 return Py_None;
1886}
1887
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001889 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001890 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00001891 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001892 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001893 {0}
1894};
1895
1896static PyObject *
1897wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1898{
1899 intintobjargproc func = (intintobjargproc)wrapped;
1900 int i, j, res;
1901 PyObject *value;
1902
1903 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1904 return NULL;
1905 res = (*func)(self, i, j, value);
1906 if (res == -1 && PyErr_Occurred())
1907 return NULL;
1908 Py_INCREF(Py_None);
1909 return Py_None;
1910}
1911
1912static struct wrapperbase tab_setslice[] = {
1913 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1914 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1915 {0}
1916};
1917
1918/* XXX objobjproc is a misnomer; should be objargpred */
1919static PyObject *
1920wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1921{
1922 objobjproc func = (objobjproc)wrapped;
1923 int res;
1924 PyObject *value;
1925
1926 if (!PyArg_ParseTuple(args, "O", &value))
1927 return NULL;
1928 res = (*func)(self, value);
1929 if (res == -1 && PyErr_Occurred())
1930 return NULL;
1931 return PyInt_FromLong((long)res);
1932}
1933
1934static struct wrapperbase tab_contains[] = {
1935 {"__contains__", (wrapperfunc)wrap_objobjproc,
1936 "x.__contains__(y) <==> y in x"},
1937 {0}
1938};
1939
1940static PyObject *
1941wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1942{
1943 objobjargproc func = (objobjargproc)wrapped;
1944 int res;
1945 PyObject *key, *value;
1946
1947 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1948 return NULL;
1949 res = (*func)(self, key, value);
1950 if (res == -1 && PyErr_Occurred())
1951 return NULL;
1952 Py_INCREF(Py_None);
1953 return Py_None;
1954}
1955
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001956static PyObject *
1957wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1958{
1959 objobjargproc func = (objobjargproc)wrapped;
1960 int res;
1961 PyObject *key;
1962
1963 if (!PyArg_ParseTuple(args, "O", &key))
1964 return NULL;
1965 res = (*func)(self, key, NULL);
1966 if (res == -1 && PyErr_Occurred())
1967 return NULL;
1968 Py_INCREF(Py_None);
1969 return Py_None;
1970}
1971
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972static struct wrapperbase tab_setitem[] = {
1973 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1974 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001975 {"__delitem__", (wrapperfunc)wrap_delitem,
1976 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001977 {0}
1978};
1979
1980static PyObject *
1981wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1982{
1983 cmpfunc func = (cmpfunc)wrapped;
1984 int res;
1985 PyObject *other;
1986
1987 if (!PyArg_ParseTuple(args, "O", &other))
1988 return NULL;
1989 res = (*func)(self, other);
1990 if (PyErr_Occurred())
1991 return NULL;
1992 return PyInt_FromLong((long)res);
1993}
1994
1995static struct wrapperbase tab_cmp[] = {
1996 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1997 "x.__cmp__(y) <==> cmp(x,y)"},
1998 {0}
1999};
2000
2001static struct wrapperbase tab_repr[] = {
2002 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2003 "x.__repr__() <==> repr(x)"},
2004 {0}
2005};
2006
2007static struct wrapperbase tab_getattr[] = {
2008 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
2009 "x.__getattr__('name') <==> x.name"},
2010 {0}
2011};
2012
2013static PyObject *
2014wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2015{
2016 setattrofunc func = (setattrofunc)wrapped;
2017 int res;
2018 PyObject *name, *value;
2019
2020 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2021 return NULL;
2022 res = (*func)(self, name, value);
2023 if (res < 0)
2024 return NULL;
2025 Py_INCREF(Py_None);
2026 return Py_None;
2027}
2028
2029static PyObject *
2030wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2031{
2032 setattrofunc func = (setattrofunc)wrapped;
2033 int res;
2034 PyObject *name;
2035
2036 if (!PyArg_ParseTuple(args, "O", &name))
2037 return NULL;
2038 res = (*func)(self, name, NULL);
2039 if (res < 0)
2040 return NULL;
2041 Py_INCREF(Py_None);
2042 return Py_None;
2043}
2044
2045static struct wrapperbase tab_setattr[] = {
2046 {"__setattr__", (wrapperfunc)wrap_setattr,
2047 "x.__setattr__('name', value) <==> x.name = value"},
2048 {"__delattr__", (wrapperfunc)wrap_delattr,
2049 "x.__delattr__('name') <==> del x.name"},
2050 {0}
2051};
2052
2053static PyObject *
2054wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2055{
2056 hashfunc func = (hashfunc)wrapped;
2057 long res;
2058
2059 if (!PyArg_ParseTuple(args, ""))
2060 return NULL;
2061 res = (*func)(self);
2062 if (res == -1 && PyErr_Occurred())
2063 return NULL;
2064 return PyInt_FromLong(res);
2065}
2066
2067static struct wrapperbase tab_hash[] = {
2068 {"__hash__", (wrapperfunc)wrap_hashfunc,
2069 "x.__hash__() <==> hash(x)"},
2070 {0}
2071};
2072
2073static PyObject *
2074wrap_call(PyObject *self, PyObject *args, void *wrapped)
2075{
2076 ternaryfunc func = (ternaryfunc)wrapped;
2077
2078 /* XXX What about keyword arguments? */
2079 return (*func)(self, args, NULL);
2080}
2081
2082static struct wrapperbase tab_call[] = {
2083 {"__call__", (wrapperfunc)wrap_call,
2084 "x.__call__(...) <==> x(...)"},
2085 {0}
2086};
2087
2088static struct wrapperbase tab_str[] = {
2089 {"__str__", (wrapperfunc)wrap_unaryfunc,
2090 "x.__str__() <==> str(x)"},
2091 {0}
2092};
2093
2094static PyObject *
2095wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2096{
2097 richcmpfunc func = (richcmpfunc)wrapped;
2098 PyObject *other;
2099
2100 if (!PyArg_ParseTuple(args, "O", &other))
2101 return NULL;
2102 return (*func)(self, other, op);
2103}
2104
2105#undef RICHCMP_WRAPPER
2106#define RICHCMP_WRAPPER(NAME, OP) \
2107static PyObject * \
2108richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2109{ \
2110 return wrap_richcmpfunc(self, args, wrapped, OP); \
2111}
2112
Jack Jansen8e938b42001-08-08 15:29:49 +00002113RICHCMP_WRAPPER(lt, Py_LT)
2114RICHCMP_WRAPPER(le, Py_LE)
2115RICHCMP_WRAPPER(eq, Py_EQ)
2116RICHCMP_WRAPPER(ne, Py_NE)
2117RICHCMP_WRAPPER(gt, Py_GT)
2118RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002119
2120#undef RICHCMP_ENTRY
2121#define RICHCMP_ENTRY(NAME, EXPR) \
2122 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2123 "x.__" #NAME "__(y) <==> " EXPR}
2124
2125static struct wrapperbase tab_richcmp[] = {
2126 RICHCMP_ENTRY(lt, "x<y"),
2127 RICHCMP_ENTRY(le, "x<=y"),
2128 RICHCMP_ENTRY(eq, "x==y"),
2129 RICHCMP_ENTRY(ne, "x!=y"),
2130 RICHCMP_ENTRY(gt, "x>y"),
2131 RICHCMP_ENTRY(ge, "x>=y"),
2132 {0}
2133};
2134
2135static struct wrapperbase tab_iter[] = {
2136 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2137 {0}
2138};
2139
2140static PyObject *
2141wrap_next(PyObject *self, PyObject *args, void *wrapped)
2142{
2143 unaryfunc func = (unaryfunc)wrapped;
2144 PyObject *res;
2145
2146 if (!PyArg_ParseTuple(args, ""))
2147 return NULL;
2148 res = (*func)(self);
2149 if (res == NULL && !PyErr_Occurred())
2150 PyErr_SetNone(PyExc_StopIteration);
2151 return res;
2152}
2153
2154static struct wrapperbase tab_next[] = {
2155 {"next", (wrapperfunc)wrap_next,
2156 "x.next() -> the next value, or raise StopIteration"},
2157 {0}
2158};
2159
2160static PyObject *
2161wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2162{
2163 descrgetfunc func = (descrgetfunc)wrapped;
2164 PyObject *obj;
2165 PyObject *type = NULL;
2166
2167 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2168 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002169 return (*func)(self, obj, type);
2170}
2171
2172static struct wrapperbase tab_descr_get[] = {
2173 {"__get__", (wrapperfunc)wrap_descr_get,
2174 "descr.__get__(obj, type) -> value"},
2175 {0}
2176};
2177
2178static PyObject *
2179wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2180{
2181 descrsetfunc func = (descrsetfunc)wrapped;
2182 PyObject *obj, *value;
2183 int ret;
2184
2185 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2186 return NULL;
2187 ret = (*func)(self, obj, value);
2188 if (ret < 0)
2189 return NULL;
2190 Py_INCREF(Py_None);
2191 return Py_None;
2192}
2193
2194static struct wrapperbase tab_descr_set[] = {
2195 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2196 "descr.__set__(obj, value)"},
2197 {0}
2198};
2199
2200static PyObject *
2201wrap_init(PyObject *self, PyObject *args, void *wrapped)
2202{
2203 initproc func = (initproc)wrapped;
2204
2205 /* XXX What about keyword arguments? */
2206 if (func(self, args, NULL) < 0)
2207 return NULL;
2208 Py_INCREF(Py_None);
2209 return Py_None;
2210}
2211
2212static struct wrapperbase tab_init[] = {
2213 {"__init__", (wrapperfunc)wrap_init,
2214 "x.__init__(...) initializes x; "
2215 "see x.__type__.__doc__ for signature"},
2216 {0}
2217};
2218
2219static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002220tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002221{
Barry Warsaw60f01882001-08-22 19:24:42 +00002222 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002223 PyObject *arg0, *res;
2224
2225 if (self == NULL || !PyType_Check(self))
2226 Py_FatalError("__new__() called with non-type 'self'");
2227 type = (PyTypeObject *)self;
2228 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002229 PyErr_Format(PyExc_TypeError,
2230 "%s.__new__(): not enough arguments",
2231 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002232 return NULL;
2233 }
2234 arg0 = PyTuple_GET_ITEM(args, 0);
2235 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002236 PyErr_Format(PyExc_TypeError,
2237 "%s.__new__(X): X is not a type object (%s)",
2238 type->tp_name,
2239 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002240 return NULL;
2241 }
2242 subtype = (PyTypeObject *)arg0;
2243 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002244 PyErr_Format(PyExc_TypeError,
2245 "%s.__new__(%s): %s is not a subtype of %s",
2246 type->tp_name,
2247 subtype->tp_name,
2248 subtype->tp_name,
2249 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002250 return NULL;
2251 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002252
2253 /* Check that the use doesn't do something silly and unsafe like
2254 object.__new__(dictionary). To do this, we check that the
2255 most derived base that's not a heap type is this type. */
2256 staticbase = subtype;
2257 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2258 staticbase = staticbase->tp_base;
2259 if (staticbase != type) {
2260 PyErr_Format(PyExc_TypeError,
2261 "%s.__new__(%s) is not safe, use %s.__new__()",
2262 type->tp_name,
2263 subtype->tp_name,
2264 staticbase == NULL ? "?" : staticbase->tp_name);
2265 return NULL;
2266 }
2267
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002268 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2269 if (args == NULL)
2270 return NULL;
2271 res = type->tp_new(subtype, args, kwds);
2272 Py_DECREF(args);
2273 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002274}
2275
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002276static struct PyMethodDef tp_new_methoddef[] = {
2277 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2278 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002279 {0}
2280};
2281
2282static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002283add_tp_new_wrapper(PyTypeObject *type)
2284{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002285 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002286
Guido van Rossumf040ede2001-08-07 16:40:56 +00002287 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2288 return 0;
2289 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002290 if (func == NULL)
2291 return -1;
2292 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2293}
2294
Guido van Rossum13d52f02001-08-10 21:24:08 +00002295static int
2296add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2297{
2298 PyObject *dict = type->tp_defined;
2299
2300 for (; wraps->name != NULL; wraps++) {
2301 PyObject *descr;
2302 if (PyDict_GetItemString(dict, wraps->name))
2303 continue;
2304 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2305 if (descr == NULL)
2306 return -1;
2307 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2308 return -1;
2309 Py_DECREF(descr);
2310 }
2311 return 0;
2312}
2313
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002314/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002315 dictionary with method descriptors for function slots. For each
2316 function slot (like tp_repr) that's defined in the type, one or
2317 more corresponding descriptors are added in the type's tp_defined
2318 dictionary under the appropriate name (like __repr__). Some
2319 function slots cause more than one descriptor to be added (for
2320 example, the nb_add slot adds both __add__ and __radd__
2321 descriptors) and some function slots compete for the same
2322 descriptor (for example both sq_item and mp_subscript generate a
2323 __getitem__ descriptor). This only adds new descriptors and
2324 doesn't overwrite entries in tp_defined that were previously
2325 defined. The descriptors contain a reference to the C function
2326 they must call, so that it's safe if they are copied into a
2327 subtype's __dict__ and the subtype has a different C function in
2328 its slot -- calling the method defined by the descriptor will call
2329 the C function that was used to create it, rather than the C
2330 function present in the slot when it is called. (This is important
2331 because a subtype may have a C function in the slot that calls the
2332 method from the dictionary, and we want to avoid infinite recursion
2333 here.) */
2334
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002335static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002336add_operators(PyTypeObject *type)
2337{
2338 PySequenceMethods *sq;
2339 PyMappingMethods *mp;
2340 PyNumberMethods *nb;
2341
2342#undef ADD
2343#define ADD(SLOT, TABLE) \
2344 if (SLOT) { \
2345 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2346 return -1; \
2347 }
2348
2349 if ((sq = type->tp_as_sequence) != NULL) {
2350 ADD(sq->sq_length, tab_len);
2351 ADD(sq->sq_concat, tab_concat);
2352 ADD(sq->sq_repeat, tab_mul_int);
2353 ADD(sq->sq_item, tab_getitem_int);
2354 ADD(sq->sq_slice, tab_getslice);
2355 ADD(sq->sq_ass_item, tab_setitem_int);
2356 ADD(sq->sq_ass_slice, tab_setslice);
2357 ADD(sq->sq_contains, tab_contains);
2358 ADD(sq->sq_inplace_concat, tab_iadd);
2359 ADD(sq->sq_inplace_repeat, tab_imul_int);
2360 }
2361
2362 if ((mp = type->tp_as_mapping) != NULL) {
2363 if (sq->sq_length == NULL)
2364 ADD(mp->mp_length, tab_len);
2365 ADD(mp->mp_subscript, tab_getitem);
2366 ADD(mp->mp_ass_subscript, tab_setitem);
2367 }
2368
2369 /* We don't support "old-style numbers" because their binary
2370 operators require that both arguments have the same type;
2371 the wrappers here only work for new-style numbers. */
2372 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2373 (nb = type->tp_as_number) != NULL) {
2374 ADD(nb->nb_add, tab_add);
2375 ADD(nb->nb_subtract, tab_sub);
2376 ADD(nb->nb_multiply, tab_mul);
2377 ADD(nb->nb_divide, tab_div);
2378 ADD(nb->nb_remainder, tab_mod);
2379 ADD(nb->nb_divmod, tab_divmod);
2380 ADD(nb->nb_power, tab_pow);
2381 ADD(nb->nb_negative, tab_neg);
2382 ADD(nb->nb_positive, tab_pos);
2383 ADD(nb->nb_absolute, tab_abs);
2384 ADD(nb->nb_nonzero, tab_nonzero);
2385 ADD(nb->nb_invert, tab_invert);
2386 ADD(nb->nb_lshift, tab_lshift);
2387 ADD(nb->nb_rshift, tab_rshift);
2388 ADD(nb->nb_and, tab_and);
2389 ADD(nb->nb_xor, tab_xor);
2390 ADD(nb->nb_or, tab_or);
2391 /* We don't support coerce() -- see above comment */
2392 ADD(nb->nb_int, tab_int);
2393 ADD(nb->nb_long, tab_long);
2394 ADD(nb->nb_float, tab_float);
2395 ADD(nb->nb_oct, tab_oct);
2396 ADD(nb->nb_hex, tab_hex);
2397 ADD(nb->nb_inplace_add, tab_iadd);
2398 ADD(nb->nb_inplace_subtract, tab_isub);
2399 ADD(nb->nb_inplace_multiply, tab_imul);
2400 ADD(nb->nb_inplace_divide, tab_idiv);
2401 ADD(nb->nb_inplace_remainder, tab_imod);
2402 ADD(nb->nb_inplace_power, tab_ipow);
2403 ADD(nb->nb_inplace_lshift, tab_ilshift);
2404 ADD(nb->nb_inplace_rshift, tab_irshift);
2405 ADD(nb->nb_inplace_and, tab_iand);
2406 ADD(nb->nb_inplace_xor, tab_ixor);
2407 ADD(nb->nb_inplace_or, tab_ior);
2408 }
2409
2410 ADD(type->tp_getattro, tab_getattr);
2411 ADD(type->tp_setattro, tab_setattr);
2412 ADD(type->tp_compare, tab_cmp);
2413 ADD(type->tp_repr, tab_repr);
2414 ADD(type->tp_hash, tab_hash);
2415 ADD(type->tp_call, tab_call);
2416 ADD(type->tp_str, tab_str);
2417 ADD(type->tp_richcompare, tab_richcmp);
2418 ADD(type->tp_iter, tab_iter);
2419 ADD(type->tp_iternext, tab_next);
2420 ADD(type->tp_descr_get, tab_descr_get);
2421 ADD(type->tp_descr_set, tab_descr_set);
2422 ADD(type->tp_init, tab_init);
2423
Guido van Rossumf040ede2001-08-07 16:40:56 +00002424 if (type->tp_new != NULL) {
2425 if (add_tp_new_wrapper(type) < 0)
2426 return -1;
2427 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002428
2429 return 0;
2430}
2431
Guido van Rossumf040ede2001-08-07 16:40:56 +00002432/* Slot wrappers that call the corresponding __foo__ slot. See comments
2433 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002434
Guido van Rossumdc91b992001-08-08 22:26:22 +00002435#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002436static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002437FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002439 static PyObject *cache_str; \
Guido van Rossum2730b132001-08-28 18:22:14 +00002440 return call_method(self, OPSTR, &cache_str, ""); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002441}
2442
Guido van Rossumdc91b992001-08-08 22:26:22 +00002443#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002444static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002445FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002446{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002447 static PyObject *cache_str; \
2448 return call_method(self, OPSTR, &cache_str, ARGCODES, arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449}
2450
Guido van Rossumdc91b992001-08-08 22:26:22 +00002451
2452#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002453static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002454FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002455{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002456 static PyObject *cache_str, *rcache_str; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002457 if (self->ob_type->tp_as_number != NULL && \
2458 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2459 PyObject *r; \
Guido van Rossum2730b132001-08-28 18:22:14 +00002460 r = call_method( \
2461 self, OPSTR, &cache_str, "O", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002462 if (r != Py_NotImplemented || \
2463 other->ob_type == self->ob_type) \
2464 return r; \
2465 Py_DECREF(r); \
2466 } \
2467 if (other->ob_type->tp_as_number != NULL && \
2468 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossum2730b132001-08-28 18:22:14 +00002469 return call_method( \
2470 other, ROPSTR, &rcache_str, "O", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002471 } \
2472 Py_INCREF(Py_NotImplemented); \
2473 return Py_NotImplemented; \
2474}
2475
2476#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2477 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2478
2479#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2480static PyObject * \
2481FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2482{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002483 static PyObject *cache_str; \
2484 return call_method(self, OPSTR, &cache_str, ARGCODES, arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002485}
2486
2487static int
2488slot_sq_length(PyObject *self)
2489{
Guido van Rossum2730b132001-08-28 18:22:14 +00002490 static PyObject *len_str;
2491 PyObject *res = call_method(self, "__len__", &len_str, "");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002492
2493 if (res == NULL)
2494 return -1;
2495 return (int)PyInt_AsLong(res);
2496}
2497
Guido van Rossumdc91b992001-08-08 22:26:22 +00002498SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2499SLOT1(slot_sq_repeat, "__mul__", int, "i")
2500SLOT1(slot_sq_item, "__getitem__", int, "i")
2501SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002502
2503static int
2504slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2505{
2506 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002507 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002508
2509 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002510 res = call_method(self, "__delitem__", &delitem_str,
2511 "i", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002512 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002513 res = call_method(self, "__setitem__", &setitem_str,
2514 "iO", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002515 if (res == NULL)
2516 return -1;
2517 Py_DECREF(res);
2518 return 0;
2519}
2520
2521static int
2522slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2523{
2524 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002525 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002526
2527 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002528 res = call_method(self, "__delslice__", &delslice_str,
2529 "ii", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002530 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002531 res = call_method(self, "__setslice__", &setslice_str,
2532 "iiO", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002533 if (res == NULL)
2534 return -1;
2535 Py_DECREF(res);
2536 return 0;
2537}
2538
2539static int
2540slot_sq_contains(PyObject *self, PyObject *value)
2541{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002542 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002543 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002544
Guido van Rossum60718732001-08-28 17:47:51 +00002545 func = lookup_method(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002546
2547 if (func != NULL) {
2548 args = Py_BuildValue("(O)", value);
2549 if (args == NULL)
2550 res = NULL;
2551 else {
2552 res = PyEval_CallObject(func, args);
2553 Py_DECREF(args);
2554 }
2555 Py_DECREF(func);
2556 if (res == NULL)
2557 return -1;
2558 return PyObject_IsTrue(res);
2559 }
2560 else {
2561 PyErr_Clear();
2562 return _PySequence_IterContains(self, value);
2563 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002564}
2565
Guido van Rossumdc91b992001-08-08 22:26:22 +00002566SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2567SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002568
2569#define slot_mp_length slot_sq_length
2570
Guido van Rossumdc91b992001-08-08 22:26:22 +00002571SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002572
2573static int
2574slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2575{
2576 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002577 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002578
2579 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002580 res = call_method(self, "__delitem__", &delitem_str,
2581 "O", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002582 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002583 res = call_method(self, "__setitem__", &setitem_str,
2584 "OO", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002585 if (res == NULL)
2586 return -1;
2587 Py_DECREF(res);
2588 return 0;
2589}
2590
Guido van Rossumdc91b992001-08-08 22:26:22 +00002591SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2592SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2593SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2594SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2595SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2596SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2597
2598staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2599
2600SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2601 nb_power, "__pow__", "__rpow__")
2602
2603static PyObject *
2604slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2605{
Guido van Rossum2730b132001-08-28 18:22:14 +00002606 static PyObject *pow_str;
2607
Guido van Rossumdc91b992001-08-08 22:26:22 +00002608 if (modulus == Py_None)
2609 return slot_nb_power_binary(self, other);
2610 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002611 return call_method(self, "__pow__", &pow_str,
2612 "OO", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002613}
2614
2615SLOT0(slot_nb_negative, "__neg__")
2616SLOT0(slot_nb_positive, "__pos__")
2617SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002618
2619static int
2620slot_nb_nonzero(PyObject *self)
2621{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002622 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002623 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002624
Guido van Rossum60718732001-08-28 17:47:51 +00002625 func = lookup_method(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002626 if (func == NULL) {
2627 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002628 func = lookup_method(self, "__len__", &len_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002629 }
2630
2631 if (func != NULL) {
2632 res = PyEval_CallObject(func, NULL);
2633 Py_DECREF(func);
2634 if (res == NULL)
2635 return -1;
2636 return PyObject_IsTrue(res);
2637 }
2638 else {
2639 PyErr_Clear();
2640 return 1;
2641 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002642}
2643
Guido van Rossumdc91b992001-08-08 22:26:22 +00002644SLOT0(slot_nb_invert, "__invert__")
2645SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2646SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2647SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2648SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2649SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002650/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002651SLOT0(slot_nb_int, "__int__")
2652SLOT0(slot_nb_long, "__long__")
2653SLOT0(slot_nb_float, "__float__")
2654SLOT0(slot_nb_oct, "__oct__")
2655SLOT0(slot_nb_hex, "__hex__")
2656SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2657SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2658SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2659SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2660SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2661SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2662SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2663SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2664SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2665SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2666SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2667SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2668 "__floordiv__", "__rfloordiv__")
2669SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2670SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2671SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002672
2673static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002674half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002675{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002676 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002677 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002678 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002679
Guido van Rossum60718732001-08-28 17:47:51 +00002680 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002681 if (func == NULL) {
2682 PyErr_Clear();
2683 }
2684 else {
2685 args = Py_BuildValue("(O)", other);
2686 if (args == NULL)
2687 res = NULL;
2688 else {
2689 res = PyObject_CallObject(func, args);
2690 Py_DECREF(args);
2691 }
2692 if (res != Py_NotImplemented) {
2693 if (res == NULL)
2694 return -2;
2695 c = PyInt_AsLong(res);
2696 Py_DECREF(res);
2697 if (c == -1 && PyErr_Occurred())
2698 return -2;
2699 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2700 }
2701 Py_DECREF(res);
2702 }
2703 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002704}
2705
Guido van Rossumb8f63662001-08-15 23:57:02 +00002706static int
2707slot_tp_compare(PyObject *self, PyObject *other)
2708{
2709 int c;
2710
2711 if (self->ob_type->tp_compare == slot_tp_compare) {
2712 c = half_compare(self, other);
2713 if (c <= 1)
2714 return c;
2715 }
2716 if (other->ob_type->tp_compare == slot_tp_compare) {
2717 c = half_compare(other, self);
2718 if (c < -1)
2719 return -2;
2720 if (c <= 1)
2721 return -c;
2722 }
2723 return (void *)self < (void *)other ? -1 :
2724 (void *)self > (void *)other ? 1 : 0;
2725}
2726
2727static PyObject *
2728slot_tp_repr(PyObject *self)
2729{
2730 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002731 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002732
Guido van Rossum60718732001-08-28 17:47:51 +00002733 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002734 if (func != NULL) {
2735 res = PyEval_CallObject(func, NULL);
2736 Py_DECREF(func);
2737 return res;
2738 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00002739 PyErr_Clear();
2740 return PyString_FromFormat("<%s object at %p>",
2741 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002742}
2743
2744static PyObject *
2745slot_tp_str(PyObject *self)
2746{
2747 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002748 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002749
Guido van Rossum60718732001-08-28 17:47:51 +00002750 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002751 if (func != NULL) {
2752 res = PyEval_CallObject(func, NULL);
2753 Py_DECREF(func);
2754 return res;
2755 }
2756 else {
2757 PyErr_Clear();
2758 return slot_tp_repr(self);
2759 }
2760}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002761
2762static long
2763slot_tp_hash(PyObject *self)
2764{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002765 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002766 static PyObject *hash_str, *eq_str, *cmp_str;
2767
Tim Peters6d6c1a32001-08-02 04:15:00 +00002768 long h;
2769
Guido van Rossum60718732001-08-28 17:47:51 +00002770 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002771
2772 if (func != NULL) {
2773 res = PyEval_CallObject(func, NULL);
2774 Py_DECREF(func);
2775 if (res == NULL)
2776 return -1;
2777 h = PyInt_AsLong(res);
2778 }
2779 else {
2780 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002781 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002782 if (func == NULL) {
2783 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002784 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002785 }
2786 if (func != NULL) {
2787 Py_DECREF(func);
2788 PyErr_SetString(PyExc_TypeError, "unhashable type");
2789 return -1;
2790 }
2791 PyErr_Clear();
2792 h = _Py_HashPointer((void *)self);
2793 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794 if (h == -1 && !PyErr_Occurred())
2795 h = -2;
2796 return h;
2797}
2798
2799static PyObject *
2800slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2801{
Guido van Rossum60718732001-08-28 17:47:51 +00002802 static PyObject *call_str;
2803 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002804 PyObject *res;
2805
2806 if (meth == NULL)
2807 return NULL;
2808 res = PyObject_Call(meth, args, kwds);
2809 Py_DECREF(meth);
2810 return res;
2811}
2812
Tim Peters6d6c1a32001-08-02 04:15:00 +00002813static PyObject *
2814slot_tp_getattro(PyObject *self, PyObject *name)
2815{
2816 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002818 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002819
Guido van Rossum8e248182001-08-12 05:17:56 +00002820 if (getattr_str == NULL) {
2821 getattr_str = PyString_InternFromString("__getattr__");
2822 if (getattr_str == NULL)
2823 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002824 }
Guido van Rossum8e248182001-08-12 05:17:56 +00002825 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00002826 if (getattr == NULL) {
2827 /* Avoid further slowdowns */
2828 if (tp->tp_getattro == slot_tp_getattro)
2829 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002830 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00002831 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002832 return PyObject_CallFunction(getattr, "OO", self, name);
2833}
2834
2835static int
2836slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2837{
2838 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002839 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002840
2841 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002842 res = call_method(self, "__delattr__", &delattr_str,
2843 "O", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002844 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002845 res = call_method(self, "__setattr__", &setattr_str,
2846 "OO", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002847 if (res == NULL)
2848 return -1;
2849 Py_DECREF(res);
2850 return 0;
2851}
2852
2853/* Map rich comparison operators to their __xx__ namesakes */
2854static char *name_op[] = {
2855 "__lt__",
2856 "__le__",
2857 "__eq__",
2858 "__ne__",
2859 "__gt__",
2860 "__ge__",
2861};
2862
2863static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00002864half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002865{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002866 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002867 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00002868
Guido van Rossum60718732001-08-28 17:47:51 +00002869 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002870 if (func == NULL) {
2871 PyErr_Clear();
2872 Py_INCREF(Py_NotImplemented);
2873 return Py_NotImplemented;
2874 }
2875 args = Py_BuildValue("(O)", other);
2876 if (args == NULL)
2877 res = NULL;
2878 else {
2879 res = PyObject_CallObject(func, args);
2880 Py_DECREF(args);
2881 }
2882 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002883 return res;
2884}
2885
Guido van Rossumb8f63662001-08-15 23:57:02 +00002886/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
2887static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
2888
2889static PyObject *
2890slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2891{
2892 PyObject *res;
2893
2894 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
2895 res = half_richcompare(self, other, op);
2896 if (res != Py_NotImplemented)
2897 return res;
2898 Py_DECREF(res);
2899 }
2900 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
2901 res = half_richcompare(other, self, swapped_op[op]);
2902 if (res != Py_NotImplemented) {
2903 return res;
2904 }
2905 Py_DECREF(res);
2906 }
2907 Py_INCREF(Py_NotImplemented);
2908 return Py_NotImplemented;
2909}
2910
2911static PyObject *
2912slot_tp_iter(PyObject *self)
2913{
2914 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002915 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002916
Guido van Rossum60718732001-08-28 17:47:51 +00002917 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002918 if (func != NULL) {
2919 res = PyObject_CallObject(func, NULL);
2920 Py_DECREF(func);
2921 return res;
2922 }
2923 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002924 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002925 if (func == NULL) {
2926 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
2927 return NULL;
2928 }
2929 Py_DECREF(func);
2930 return PySeqIter_New(self);
2931}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002932
2933static PyObject *
2934slot_tp_iternext(PyObject *self)
2935{
Guido van Rossum2730b132001-08-28 18:22:14 +00002936 static PyObject *next_str;
2937 return call_method(self, "next", &next_str, "");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002938}
2939
Guido van Rossum1a493502001-08-17 16:47:50 +00002940static PyObject *
2941slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
2942{
2943 PyTypeObject *tp = self->ob_type;
2944 PyObject *get;
2945 static PyObject *get_str = NULL;
2946
2947 if (get_str == NULL) {
2948 get_str = PyString_InternFromString("__get__");
2949 if (get_str == NULL)
2950 return NULL;
2951 }
2952 get = _PyType_Lookup(tp, get_str);
2953 if (get == NULL) {
2954 /* Avoid further slowdowns */
2955 if (tp->tp_descr_get == slot_tp_descr_get)
2956 tp->tp_descr_get = NULL;
2957 Py_INCREF(self);
2958 return self;
2959 }
Guido van Rossum2c252392001-08-24 10:13:31 +00002960 if (obj == NULL)
2961 obj = Py_None;
2962 if (type == NULL)
2963 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00002964 return PyObject_CallFunction(get, "OOO", self, obj, type);
2965}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002966
2967static int
2968slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2969{
Guido van Rossum2c252392001-08-24 10:13:31 +00002970 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002971 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00002972
2973 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002974 res = call_method(self, "__del__", &del_str,
2975 "O", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00002976 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002977 res = call_method(self, "__set__", &set_str,
2978 "OO", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002979 if (res == NULL)
2980 return -1;
2981 Py_DECREF(res);
2982 return 0;
2983}
2984
2985static int
2986slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2987{
Guido van Rossum60718732001-08-28 17:47:51 +00002988 static PyObject *init_str;
2989 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002990 PyObject *res;
2991
2992 if (meth == NULL)
2993 return -1;
2994 res = PyObject_Call(meth, args, kwds);
2995 Py_DECREF(meth);
2996 if (res == NULL)
2997 return -1;
2998 Py_DECREF(res);
2999 return 0;
3000}
3001
3002static PyObject *
3003slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3004{
3005 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3006 PyObject *newargs, *x;
3007 int i, n;
3008
3009 if (func == NULL)
3010 return NULL;
3011 assert(PyTuple_Check(args));
3012 n = PyTuple_GET_SIZE(args);
3013 newargs = PyTuple_New(n+1);
3014 if (newargs == NULL)
3015 return NULL;
3016 Py_INCREF(type);
3017 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3018 for (i = 0; i < n; i++) {
3019 x = PyTuple_GET_ITEM(args, i);
3020 Py_INCREF(x);
3021 PyTuple_SET_ITEM(newargs, i+1, x);
3022 }
3023 x = PyObject_Call(func, newargs, kwds);
3024 Py_DECREF(func);
3025 return x;
3026}
3027
Guido van Rossumf040ede2001-08-07 16:40:56 +00003028/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003029 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003030 The dict argument is the dictionary argument passed to type_new(),
3031 which is the local namespace of the class statement, in other
3032 words, it contains the methods. For each special method (like
3033 __repr__) defined in the dictionary, the corresponding function
3034 slot in the type object (like tp_repr) is set to a special function
3035 whose name is 'slot_' followed by the slot name and whose signature
3036 is whatever is required for that slot. These slot functions look
3037 up the corresponding method in the type's dictionary and call it.
3038 The slot functions have to take care of the various peculiarities
3039 of the mapping between slots and special methods, such as mapping
3040 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3041 etc.) or mapping multiple slots to a single method (sq_item,
3042 mp_subscript <--> __getitem__). */
3043
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044static void
3045override_slots(PyTypeObject *type, PyObject *dict)
3046{
3047 PySequenceMethods *sq = type->tp_as_sequence;
3048 PyMappingMethods *mp = type->tp_as_mapping;
3049 PyNumberMethods *nb = type->tp_as_number;
3050
Guido van Rossumdc91b992001-08-08 22:26:22 +00003051#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003052 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003053 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054 }
3055
Guido van Rossumdc91b992001-08-08 22:26:22 +00003056#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003057 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003058 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003059 }
3060
Guido van Rossumdc91b992001-08-08 22:26:22 +00003061#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003062 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003063 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003064 }
3065
Guido van Rossumdc91b992001-08-08 22:26:22 +00003066#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003067 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003068 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069 }
3070
Guido van Rossumdc91b992001-08-08 22:26:22 +00003071 SQSLOT("__len__", sq_length, slot_sq_length);
3072 SQSLOT("__add__", sq_concat, slot_sq_concat);
3073 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3074 SQSLOT("__getitem__", sq_item, slot_sq_item);
3075 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3076 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3077 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3078 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3079 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3080 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3081 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3082 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003083
Guido van Rossumdc91b992001-08-08 22:26:22 +00003084 MPSLOT("__len__", mp_length, slot_mp_length);
3085 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3086 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3087 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003088
Guido van Rossumdc91b992001-08-08 22:26:22 +00003089 NBSLOT("__add__", nb_add, slot_nb_add);
3090 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3091 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3092 NBSLOT("__div__", nb_divide, slot_nb_divide);
3093 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3094 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3095 NBSLOT("__pow__", nb_power, slot_nb_power);
3096 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3097 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3098 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3099 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3100 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3101 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3102 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3103 NBSLOT("__and__", nb_and, slot_nb_and);
3104 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3105 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003106 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00003107 NBSLOT("__int__", nb_int, slot_nb_int);
3108 NBSLOT("__long__", nb_long, slot_nb_long);
3109 NBSLOT("__float__", nb_float, slot_nb_float);
3110 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3111 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3112 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3113 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3114 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3115 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3116 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3117 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3118 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3119 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3120 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3121 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3122 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3123 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3124 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3125 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3126 slot_nb_inplace_floor_divide);
3127 NBSLOT("__itruediv__", nb_inplace_true_divide,
3128 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003129
Guido van Rossum8e248182001-08-12 05:17:56 +00003130 if (dict == NULL ||
3131 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132 PyDict_GetItemString(dict, "__repr__"))
3133 type->tp_print = NULL;
3134
Guido van Rossumdc91b992001-08-08 22:26:22 +00003135 TPSLOT("__cmp__", tp_compare, slot_tp_compare);
3136 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3137 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3138 TPSLOT("__call__", tp_call, slot_tp_call);
3139 TPSLOT("__str__", tp_str, slot_tp_str);
3140 TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
3141 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3142 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3143 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3144 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3145 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3146 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3147 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3148 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3149 TPSLOT("next", tp_iternext, slot_tp_iternext);
3150 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3151 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3152 TPSLOT("__init__", tp_init, slot_tp_init);
3153 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003154}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003155
3156
3157/* Cooperative 'super' */
3158
3159typedef struct {
3160 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003161 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003162 PyObject *obj;
3163} superobject;
3164
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003165static struct memberlist super_members[] = {
3166 {"__type__", T_OBJECT, offsetof(superobject, type), READONLY},
3167 {"__obj__", T_OBJECT, offsetof(superobject, obj), READONLY},
3168 {0}
3169};
3170
Guido van Rossum705f0f52001-08-24 16:47:00 +00003171static void
3172super_dealloc(PyObject *self)
3173{
3174 superobject *su = (superobject *)self;
3175
3176 Py_XDECREF(su->obj);
3177 Py_XDECREF(su->type);
3178 self->ob_type->tp_free(self);
3179}
3180
3181static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003182super_repr(PyObject *self)
3183{
3184 superobject *su = (superobject *)self;
3185
3186 if (su->obj)
3187 return PyString_FromFormat(
3188 "<super: <type '%s'>, <%s object>>",
3189 su->type ? su->type->tp_name : "NULL",
3190 su->obj->ob_type->tp_name);
3191 else
3192 return PyString_FromFormat(
3193 "<super: <type '%s'>, NULL>",
3194 su->type ? su->type->tp_name : "NULL");
3195}
3196
3197static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003198super_getattro(PyObject *self, PyObject *name)
3199{
3200 superobject *su = (superobject *)self;
3201
3202 if (su->obj != NULL) {
3203 PyObject *mro, *res, *tmp;
3204 descrgetfunc f;
3205 int i, n;
3206
Guido van Rossume705ef12001-08-29 15:47:06 +00003207 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003208 if (mro == NULL)
3209 n = 0;
3210 else {
3211 assert(PyTuple_Check(mro));
3212 n = PyTuple_GET_SIZE(mro);
3213 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003214 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003215 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003216 break;
3217 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003218 if (i >= n && PyType_Check(su->obj)) {
3219 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003220 if (mro == NULL)
3221 n = 0;
3222 else {
3223 assert(PyTuple_Check(mro));
3224 n = PyTuple_GET_SIZE(mro);
3225 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003226 for (i = 0; i < n; i++) {
3227 if ((PyObject *)(su->type) ==
3228 PyTuple_GET_ITEM(mro, i))
3229 break;
3230 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003231 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003232 i++;
3233 res = NULL;
3234 for (; i < n; i++) {
3235 tmp = PyTuple_GET_ITEM(mro, i);
3236 assert(PyType_Check(tmp));
3237 res = PyDict_GetItem(
3238 ((PyTypeObject *)tmp)->tp_defined, name);
3239 if (res != NULL) {
3240 Py_INCREF(res);
3241 f = res->ob_type->tp_descr_get;
3242 if (f != NULL) {
3243 tmp = f(res, su->obj, res);
3244 Py_DECREF(res);
3245 res = tmp;
3246 }
3247 return res;
3248 }
3249 }
3250 }
3251 return PyObject_GenericGetAttr(self, name);
3252}
3253
3254static PyObject *
3255super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3256{
3257 superobject *su = (superobject *)self;
3258 superobject *new;
3259
3260 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3261 /* Not binding to an object, or already bound */
3262 Py_INCREF(self);
3263 return self;
3264 }
3265 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3266 if (new == NULL)
3267 return NULL;
3268 Py_INCREF(su->type);
3269 Py_INCREF(obj);
3270 new->type = su->type;
3271 new->obj = obj;
3272 return (PyObject *)new;
3273}
3274
3275static int
3276super_init(PyObject *self, PyObject *args, PyObject *kwds)
3277{
3278 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003279 PyTypeObject *type;
3280 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003281
3282 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3283 return -1;
3284 if (obj == Py_None)
3285 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003286 if (obj != NULL &&
3287 !PyType_IsSubtype(obj->ob_type, type) &&
3288 !(PyType_Check(obj) &&
3289 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003290 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003291 "super(type, obj): "
3292 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003293 return -1;
3294 }
3295 Py_INCREF(type);
3296 Py_XINCREF(obj);
3297 su->type = type;
3298 su->obj = obj;
3299 return 0;
3300}
3301
3302static char super_doc[] =
3303"super(type) -> unbound super object\n"
3304"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003305"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003306"Typical use to call a cooperative superclass method:\n"
3307"class C(B):\n"
3308" def meth(self, arg):\n"
3309" super(C, self).meth(arg)";
3310
3311PyTypeObject PySuper_Type = {
3312 PyObject_HEAD_INIT(&PyType_Type)
3313 0, /* ob_size */
3314 "super", /* tp_name */
3315 sizeof(superobject), /* tp_basicsize */
3316 0, /* tp_itemsize */
3317 /* methods */
3318 super_dealloc, /* tp_dealloc */
3319 0, /* tp_print */
3320 0, /* tp_getattr */
3321 0, /* tp_setattr */
3322 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003323 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003324 0, /* tp_as_number */
3325 0, /* tp_as_sequence */
3326 0, /* tp_as_mapping */
3327 0, /* tp_hash */
3328 0, /* tp_call */
3329 0, /* tp_str */
3330 super_getattro, /* tp_getattro */
3331 0, /* tp_setattro */
3332 0, /* tp_as_buffer */
Guido van Rossum31bcff82001-08-30 04:37:15 +00003333 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003334 super_doc, /* tp_doc */
3335 0, /* tp_traverse */
3336 0, /* tp_clear */
3337 0, /* tp_richcompare */
3338 0, /* tp_weaklistoffset */
3339 0, /* tp_iter */
3340 0, /* tp_iternext */
3341 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003342 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003343 0, /* tp_getset */
3344 0, /* tp_base */
3345 0, /* tp_dict */
3346 super_descr_get, /* tp_descr_get */
3347 0, /* tp_descr_set */
3348 0, /* tp_dictoffset */
3349 super_init, /* tp_init */
3350 PyType_GenericAlloc, /* tp_alloc */
3351 PyType_GenericNew, /* tp_new */
3352 _PyObject_Del, /* tp_free */
3353};