blob: 7fb6c8a2485f27765e5de1c14d5c63e67ceafa61 [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{
169 int size;
170 void *mem;
171 PyObject *obj;
172
173 /* Inline PyObject_New() so we can zero the memory */
174 size = _PyObject_VAR_SIZE(type, nitems);
175 mem = PyObject_MALLOC(size);
176 if (mem == NULL)
177 return PyErr_NoMemory();
178 memset(mem, '\0', size);
179 if (PyType_IS_GC(type))
180 obj = PyObject_FROM_GC(mem);
181 else
182 obj = (PyObject *)mem;
183 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
184 Py_INCREF(type);
185 if (type->tp_itemsize == 0)
186 PyObject_INIT(obj, type);
187 else
188 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
189 if (PyType_IS_GC(type))
190 PyObject_GC_Init(obj);
191 return obj;
192}
193
194PyObject *
195PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
196{
197 return type->tp_alloc(type, 0);
198}
199
200/* Helper for subtyping */
201
202static void
203subtype_dealloc(PyObject *self)
204{
205 int dictoffset = self->ob_type->tp_dictoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000206 int weaklistoffset = self->ob_type->tp_weaklistoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000207 PyTypeObject *type, *base;
208 destructor f;
209
210 /* This exists so we can DECREF self->ob_type */
211
212 /* Find the nearest base with a different tp_dealloc */
213 type = self->ob_type;
214 base = type->tp_base;
215 while ((f = base->tp_dealloc) == subtype_dealloc) {
216 base = base->tp_base;
217 assert(base);
218 }
219
220 /* If we added a dict, DECREF it */
221 if (dictoffset && !base->tp_dictoffset) {
222 PyObject **dictptr = (PyObject **) ((char *)self + dictoffset);
223 PyObject *dict = *dictptr;
224 if (dict != NULL) {
225 Py_DECREF(dict);
226 *dictptr = NULL;
227 }
228 }
229
Guido van Rossum9676b222001-08-17 20:32:36 +0000230 /* If we added weaklist, we clear it */
231 if (weaklistoffset && !base->tp_weaklistoffset)
232 PyObject_ClearWeakRefs(self);
233
Tim Peters6d6c1a32001-08-02 04:15:00 +0000234 /* Finalize GC if the base doesn't do GC and we do */
235 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
236 PyObject_GC_Fini(self);
237
238 /* Call the base tp_dealloc() */
239 assert(f);
240 f(self);
241
242 /* Can't reference self beyond this point */
243 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
244 Py_DECREF(type);
245 }
246}
247
248staticforward void override_slots(PyTypeObject *type, PyObject *dict);
249staticforward PyTypeObject *solid_base(PyTypeObject *type);
250
251typedef struct {
252 PyTypeObject type;
253 PyNumberMethods as_number;
254 PySequenceMethods as_sequence;
255 PyMappingMethods as_mapping;
256 PyBufferProcs as_buffer;
257 PyObject *name, *slots;
258 struct memberlist members[1];
259} etype;
260
261/* type test with subclassing support */
262
263int
264PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
265{
266 PyObject *mro;
267
268 mro = a->tp_mro;
269 if (mro != NULL) {
270 /* Deal with multiple inheritance without recursion
271 by walking the MRO tuple */
272 int i, n;
273 assert(PyTuple_Check(mro));
274 n = PyTuple_GET_SIZE(mro);
275 for (i = 0; i < n; i++) {
276 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
277 return 1;
278 }
279 return 0;
280 }
281 else {
282 /* a is not completely initilized yet; follow tp_base */
283 do {
284 if (a == b)
285 return 1;
286 a = a->tp_base;
287 } while (a != NULL);
288 return b == &PyBaseObject_Type;
289 }
290}
291
Guido van Rossum60718732001-08-28 17:47:51 +0000292/* Internal routine to do a method lookup in the type
293 without looking in the instance dictionary
294 (so we can't use PyObject_GetAttr) but still binding
295 it to the instance. The arguments are the object,
296 the method name as a C string, and the address of a
297 static variable used to cache the interned Python string. */
298
299static PyObject *
300lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
301{
302 PyObject *res;
303
304 if (*attrobj == NULL) {
305 *attrobj = PyString_InternFromString(attrstr);
306 if (*attrobj == NULL)
307 return NULL;
308 }
309 res = _PyType_Lookup(self->ob_type, *attrobj);
310 if (res == NULL)
311 PyErr_SetObject(PyExc_AttributeError, *attrobj);
312 else {
313 descrgetfunc f;
314 if ((f = res->ob_type->tp_descr_get) == NULL)
315 Py_INCREF(res);
316 else
317 res = f(res, self, (PyObject *)(self->ob_type));
318 }
319 return res;
320}
321
Tim Peters6d6c1a32001-08-02 04:15:00 +0000322/* Method resolution order algorithm from "Putting Metaclasses to Work"
323 by Forman and Danforth (Addison-Wesley 1999). */
324
325static int
326conservative_merge(PyObject *left, PyObject *right)
327{
328 int left_size;
329 int right_size;
330 int i, j, r, ok;
331 PyObject *temp, *rr;
332
333 assert(PyList_Check(left));
334 assert(PyList_Check(right));
335
336 again:
337 left_size = PyList_GET_SIZE(left);
338 right_size = PyList_GET_SIZE(right);
339 for (i = 0; i < left_size; i++) {
340 for (j = 0; j < right_size; j++) {
341 if (PyList_GET_ITEM(left, i) ==
342 PyList_GET_ITEM(right, j)) {
343 /* found a merge point */
344 temp = PyList_New(0);
345 if (temp == NULL)
346 return -1;
347 for (r = 0; r < j; r++) {
348 rr = PyList_GET_ITEM(right, r);
349 ok = PySequence_Contains(left, rr);
350 if (ok < 0) {
351 Py_DECREF(temp);
352 return -1;
353 }
354 if (!ok) {
355 ok = PyList_Append(temp, rr);
356 if (ok < 0) {
357 Py_DECREF(temp);
358 return -1;
359 }
360 }
361 }
362 ok = PyList_SetSlice(left, i, i, temp);
363 Py_DECREF(temp);
364 if (ok < 0)
365 return -1;
366 ok = PyList_SetSlice(right, 0, j+1, NULL);
367 if (ok < 0)
368 return -1;
369 goto again;
370 }
371 }
372 }
373 return PyList_SetSlice(left, left_size, left_size, right);
374}
375
376static int
377serious_order_disagreements(PyObject *left, PyObject *right)
378{
379 return 0; /* XXX later -- for now, we cheat: "don't do that" */
380}
381
382static PyObject *
383mro_implementation(PyTypeObject *type)
384{
385 int i, n, ok;
386 PyObject *bases, *result;
387
388 bases = type->tp_bases;
389 n = PyTuple_GET_SIZE(bases);
390 result = Py_BuildValue("[O]", (PyObject *)type);
391 if (result == NULL)
392 return NULL;
393 for (i = 0; i < n; i++) {
394 PyTypeObject *base =
395 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
396 PyObject *parentMRO = PySequence_List(base->tp_mro);
397 if (parentMRO == NULL) {
398 Py_DECREF(result);
399 return NULL;
400 }
401 if (serious_order_disagreements(result, parentMRO)) {
402 Py_DECREF(result);
403 return NULL;
404 }
405 ok = conservative_merge(result, parentMRO);
406 Py_DECREF(parentMRO);
407 if (ok < 0) {
408 Py_DECREF(result);
409 return NULL;
410 }
411 }
412 return result;
413}
414
415static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000416mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000417{
418 PyTypeObject *type = (PyTypeObject *)self;
419
Tim Peters6d6c1a32001-08-02 04:15:00 +0000420 return mro_implementation(type);
421}
422
423static int
424mro_internal(PyTypeObject *type)
425{
426 PyObject *mro, *result, *tuple;
427
428 if (type->ob_type == &PyType_Type) {
429 result = mro_implementation(type);
430 }
431 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000432 static PyObject *mro_str;
433 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000434 if (mro == NULL)
435 return -1;
436 result = PyObject_CallObject(mro, NULL);
437 Py_DECREF(mro);
438 }
439 if (result == NULL)
440 return -1;
441 tuple = PySequence_Tuple(result);
442 Py_DECREF(result);
443 type->tp_mro = tuple;
444 return 0;
445}
446
447
448/* Calculate the best base amongst multiple base classes.
449 This is the first one that's on the path to the "solid base". */
450
451static PyTypeObject *
452best_base(PyObject *bases)
453{
454 int i, n;
455 PyTypeObject *base, *winner, *candidate, *base_i;
456
457 assert(PyTuple_Check(bases));
458 n = PyTuple_GET_SIZE(bases);
459 assert(n > 0);
460 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
461 winner = &PyBaseObject_Type;
462 for (i = 0; i < n; i++) {
463 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
464 if (!PyType_Check((PyObject *)base_i)) {
465 PyErr_SetString(
466 PyExc_TypeError,
467 "bases must be types");
468 return NULL;
469 }
470 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000471 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000472 return NULL;
473 }
474 candidate = solid_base(base_i);
475 if (PyType_IsSubtype(winner, candidate))
476 ;
477 else if (PyType_IsSubtype(candidate, winner)) {
478 winner = candidate;
479 base = base_i;
480 }
481 else {
482 PyErr_SetString(
483 PyExc_TypeError,
484 "multiple bases have "
485 "instance lay-out conflict");
486 return NULL;
487 }
488 }
489 assert(base != NULL);
490 return base;
491}
492
493static int
494extra_ivars(PyTypeObject *type, PyTypeObject *base)
495{
Guido van Rossum9676b222001-08-17 20:32:36 +0000496 size_t t_size = PyType_BASICSIZE(type);
497 size_t b_size = PyType_BASICSIZE(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000498
Guido van Rossum9676b222001-08-17 20:32:36 +0000499 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000500 if (type->tp_itemsize || base->tp_itemsize) {
501 /* If itemsize is involved, stricter rules */
502 return t_size != b_size ||
503 type->tp_itemsize != base->tp_itemsize;
504 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000505 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
506 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
507 t_size -= sizeof(PyObject *);
508 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
509 type->tp_dictoffset + sizeof(PyObject *) == t_size)
510 t_size -= sizeof(PyObject *);
511
512 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000513}
514
515static PyTypeObject *
516solid_base(PyTypeObject *type)
517{
518 PyTypeObject *base;
519
520 if (type->tp_base)
521 base = solid_base(type->tp_base);
522 else
523 base = &PyBaseObject_Type;
524 if (extra_ivars(type, base))
525 return type;
526 else
527 return base;
528}
529
530staticforward void object_dealloc(PyObject *);
531staticforward int object_init(PyObject *, PyObject *, PyObject *);
532
533static PyObject *
534type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
535{
536 PyObject *name, *bases, *dict;
537 static char *kwlist[] = {"name", "bases", "dict", 0};
538 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000539 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000540 etype *et;
541 struct memberlist *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000542 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000543
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000544 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000545 if (metatype == &PyType_Type &&
546 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
547 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000548 PyObject *x = PyTuple_GET_ITEM(args, 0);
549 Py_INCREF(x->ob_type);
550 return (PyObject *) x->ob_type;
551 }
552
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000553 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000554 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
555 &name,
556 &PyTuple_Type, &bases,
557 &PyDict_Type, &dict))
558 return NULL;
559
560 /* Determine the proper metatype to deal with this,
561 and check for metatype conflicts while we're at it.
562 Note that if some other metatype wins to contract,
563 it's possible that its instances are not types. */
564 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000565 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000566 for (i = 0; i < nbases; i++) {
567 tmp = PyTuple_GET_ITEM(bases, i);
568 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000569 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000570 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000571 if (PyType_IsSubtype(tmptype, winner)) {
572 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000573 continue;
574 }
575 PyErr_SetString(PyExc_TypeError,
576 "metatype conflict among bases");
577 return NULL;
578 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000579 if (winner != metatype) {
580 if (winner->tp_new != type_new) /* Pass it to the winner */
581 return winner->tp_new(winner, args, kwds);
582 metatype = winner;
583 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000584
585 /* Adjust for empty tuple bases */
586 if (nbases == 0) {
587 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
588 if (bases == NULL)
589 return NULL;
590 nbases = 1;
591 }
592 else
593 Py_INCREF(bases);
594
595 /* XXX From here until type is allocated, "return NULL" leaks bases! */
596
597 /* Calculate best base, and check that all bases are type objects */
598 base = best_base(bases);
599 if (base == NULL)
600 return NULL;
601 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
602 PyErr_Format(PyExc_TypeError,
603 "type '%.100s' is not an acceptable base type",
604 base->tp_name);
605 return NULL;
606 }
607
Guido van Rossum1a493502001-08-17 16:47:50 +0000608 /* Should this be a dynamic class (i.e. modifiable __dict__)?
609 Look in two places for a variable named __dynamic__:
610 1) in the class dict
611 2) in the module dict (globals)
612 The first variable that is an int >= 0 is used.
613 Otherwise, a default is calculated from the base classes:
614 if any base class is dynamic, this class is dynamic; otherwise
615 it is static. */
616 dynamic = -1; /* Not yet determined */
617 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000618 tmp = PyDict_GetItemString(dict, "__dynamic__");
619 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000620 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000621 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000622 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000623 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000624 if (dynamic < 0) {
625 /* Look in the module globals */
626 tmp = PyEval_GetGlobals();
627 if (tmp != NULL) {
628 tmp = PyDict_GetItemString(tmp, "__dynamic__");
629 if (tmp != NULL) {
630 dynamic = PyInt_AsLong(tmp);
631 if (dynamic < 0)
632 PyErr_Clear();
633 }
634 }
635 }
636 if (dynamic < 0) {
637 /* Make a new class dynamic if any of its bases is
638 dynamic. This is not always the same as inheriting
639 the __dynamic__ class attribute! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640 dynamic = 0;
641 for (i = 0; i < nbases; i++) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000642 tmptype = (PyTypeObject *)
643 PyTuple_GET_ITEM(bases, i);
644 if (tmptype->tp_flags &
645 Py_TPFLAGS_DYNAMICTYPE) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000646 dynamic = 1;
647 break;
648 }
649 }
650 }
651
652 /* Check for a __slots__ sequence variable in dict, and count it */
653 slots = PyDict_GetItemString(dict, "__slots__");
654 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000655 add_dict = 0;
656 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000657 if (slots != NULL) {
658 /* Make it into a tuple */
659 if (PyString_Check(slots))
660 slots = Py_BuildValue("(O)", slots);
661 else
662 slots = PySequence_Tuple(slots);
663 if (slots == NULL)
664 return NULL;
665 nslots = PyTuple_GET_SIZE(slots);
666 for (i = 0; i < nslots; i++) {
667 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
668 PyErr_SetString(PyExc_TypeError,
669 "__slots__ must be a sequence of strings");
670 Py_DECREF(slots);
671 return NULL;
672 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000673 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674 }
675 }
676 if (slots == NULL && base->tp_dictoffset == 0 &&
677 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000678 base->tp_setattro == NULL)) {
679 nslots++;
680 add_dict++;
681 }
682 if (slots == NULL && base->tp_weaklistoffset == 0) {
683 nslots++;
684 add_weak++;
685 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000686
687 /* XXX From here until type is safely allocated,
688 "return NULL" may leak slots! */
689
690 /* Allocate the type object */
691 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
692 if (type == NULL)
693 return NULL;
694
695 /* Keep name and slots alive in the extended type object */
696 et = (etype *)type;
697 Py_INCREF(name);
698 et->name = name;
699 et->slots = slots;
700
Guido van Rossumdc91b992001-08-08 22:26:22 +0000701 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000702 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
703 Py_TPFLAGS_BASETYPE;
704 if (dynamic)
705 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000706
707 /* It's a new-style number unless it specifically inherits any
708 old-style numeric behavior */
709 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
710 (base->tp_as_number == NULL))
711 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
712
713 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000714 type->tp_as_number = &et->as_number;
715 type->tp_as_sequence = &et->as_sequence;
716 type->tp_as_mapping = &et->as_mapping;
717 type->tp_as_buffer = &et->as_buffer;
718 type->tp_name = PyString_AS_STRING(name);
719
720 /* Set tp_base and tp_bases */
721 type->tp_bases = bases;
722 Py_INCREF(base);
723 type->tp_base = base;
724
725 /* Initialize tp_defined from passed-in dict */
726 type->tp_defined = dict = PyDict_Copy(dict);
727 if (dict == NULL) {
728 Py_DECREF(type);
729 return NULL;
730 }
731
Guido van Rossumc3542212001-08-16 09:18:56 +0000732 /* Set __module__ in the dict */
733 if (PyDict_GetItemString(dict, "__module__") == NULL) {
734 tmp = PyEval_GetGlobals();
735 if (tmp != NULL) {
736 tmp = PyDict_GetItemString(tmp, "__name__");
737 if (tmp != NULL) {
738 if (PyDict_SetItemString(dict, "__module__",
739 tmp) < 0)
740 return NULL;
741 }
742 }
743 }
744
Tim Peters6d6c1a32001-08-02 04:15:00 +0000745 /* Special-case __new__: if it's a plain function,
746 make it a static function */
747 tmp = PyDict_GetItemString(dict, "__new__");
748 if (tmp != NULL && PyFunction_Check(tmp)) {
749 tmp = PyStaticMethod_New(tmp);
750 if (tmp == NULL) {
751 Py_DECREF(type);
752 return NULL;
753 }
754 PyDict_SetItemString(dict, "__new__", tmp);
755 Py_DECREF(tmp);
756 }
757
758 /* Add descriptors for custom slots from __slots__, or for __dict__ */
759 mp = et->members;
760 slotoffset = PyType_BASICSIZE(base);
761 if (slots != NULL) {
762 for (i = 0; i < nslots; i++, mp++) {
763 mp->name = PyString_AS_STRING(
764 PyTuple_GET_ITEM(slots, i));
765 mp->type = T_OBJECT;
766 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000767 if (base->tp_weaklistoffset == 0 &&
768 strcmp(mp->name, "__weakref__") == 0)
769 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000770 slotoffset += sizeof(PyObject *);
771 }
772 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000773 else {
774 if (add_dict) {
775 type->tp_dictoffset = slotoffset;
776 mp->name = "__dict__";
777 mp->type = T_OBJECT;
778 mp->offset = slotoffset;
779 mp->readonly = 1;
780 mp++;
781 slotoffset += sizeof(PyObject *);
782 }
783 if (add_weak) {
784 type->tp_weaklistoffset = slotoffset;
785 mp->name = "__weakref__";
786 mp->type = T_OBJECT;
787 mp->offset = slotoffset;
788 mp->readonly = 1;
789 mp++;
790 slotoffset += sizeof(PyObject *);
791 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000792 }
793 type->tp_basicsize = slotoffset;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000794 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000795
796 /* Special case some slots */
797 if (type->tp_dictoffset != 0 || nslots > 0) {
798 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
799 type->tp_getattro = PyObject_GenericGetAttr;
800 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
801 type->tp_setattro = PyObject_GenericSetAttr;
802 }
803 type->tp_dealloc = subtype_dealloc;
804
805 /* Always override allocation strategy to use regular heap */
806 type->tp_alloc = PyType_GenericAlloc;
807 type->tp_free = _PyObject_Del;
808
809 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000810 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000811 Py_DECREF(type);
812 return NULL;
813 }
814
815 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +0000816 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
817 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000818
Tim Peters6d6c1a32001-08-02 04:15:00 +0000819 return (PyObject *)type;
820}
821
822/* Internal API to look for a name through the MRO.
823 This returns a borrowed reference, and doesn't set an exception! */
824PyObject *
825_PyType_Lookup(PyTypeObject *type, PyObject *name)
826{
827 int i, n;
828 PyObject *mro, *res, *dict;
829
830 /* For static types, look in tp_dict */
831 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
832 dict = type->tp_dict;
833 assert(dict && PyDict_Check(dict));
834 return PyDict_GetItem(dict, name);
835 }
836
837 /* For dynamic types, look in tp_defined of types in MRO */
838 mro = type->tp_mro;
839 assert(PyTuple_Check(mro));
840 n = PyTuple_GET_SIZE(mro);
841 for (i = 0; i < n; i++) {
842 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
843 assert(PyType_Check(type));
844 dict = type->tp_defined;
845 assert(dict && PyDict_Check(dict));
846 res = PyDict_GetItem(dict, name);
847 if (res != NULL)
848 return res;
849 }
850 return NULL;
851}
852
853/* This is similar to PyObject_GenericGetAttr(),
854 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
855static PyObject *
856type_getattro(PyTypeObject *type, PyObject *name)
857{
858 PyTypeObject *metatype = type->ob_type;
859 PyObject *descr, *res;
860 descrgetfunc f;
861
862 /* Initialize this type (we'll assume the metatype is initialized) */
863 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000864 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000865 return NULL;
866 }
867
868 /* Get a descriptor from the metatype */
869 descr = _PyType_Lookup(metatype, name);
870 f = NULL;
871 if (descr != NULL) {
872 f = descr->ob_type->tp_descr_get;
873 if (f != NULL && PyDescr_IsData(descr))
874 return f(descr,
875 (PyObject *)type, (PyObject *)metatype);
876 }
877
878 /* Look in tp_defined of this type and its bases */
879 res = _PyType_Lookup(type, name);
880 if (res != NULL) {
881 f = res->ob_type->tp_descr_get;
882 if (f != NULL)
883 return f(res, (PyObject *)NULL, (PyObject *)type);
884 Py_INCREF(res);
885 return res;
886 }
887
888 /* Use the descriptor from the metatype */
889 if (f != NULL) {
890 res = f(descr, (PyObject *)type, (PyObject *)metatype);
891 return res;
892 }
893 if (descr != NULL) {
894 Py_INCREF(descr);
895 return descr;
896 }
897
898 /* Give up */
899 PyErr_Format(PyExc_AttributeError,
900 "type object '%.50s' has no attribute '%.400s'",
901 type->tp_name, PyString_AS_STRING(name));
902 return NULL;
903}
904
905static int
906type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
907{
908 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
909 return PyObject_GenericSetAttr((PyObject *)type, name, value);
910 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
911 return -1;
912}
913
914static void
915type_dealloc(PyTypeObject *type)
916{
917 etype *et;
918
919 /* Assert this is a heap-allocated type object */
920 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
921 et = (etype *)type;
922 Py_XDECREF(type->tp_base);
923 Py_XDECREF(type->tp_dict);
924 Py_XDECREF(type->tp_bases);
925 Py_XDECREF(type->tp_mro);
926 Py_XDECREF(type->tp_defined);
927 /* XXX more? */
928 Py_XDECREF(et->name);
929 Py_XDECREF(et->slots);
930 type->ob_type->tp_free((PyObject *)type);
931}
932
933static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000934 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000935 "mro() -> list\nreturn a type's method resolution order"},
936 {0}
937};
938
939static char type_doc[] =
940"type(object) -> the object's type\n"
941"type(name, bases, dict) -> a new type";
942
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000943PyTypeObject PyType_Type = {
944 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000945 0, /* ob_size */
946 "type", /* tp_name */
947 sizeof(etype), /* tp_basicsize */
948 sizeof(struct memberlist), /* tp_itemsize */
949 (destructor)type_dealloc, /* tp_dealloc */
950 0, /* tp_print */
951 0, /* tp_getattr */
952 0, /* tp_setattr */
953 type_compare, /* tp_compare */
954 (reprfunc)type_repr, /* tp_repr */
955 0, /* tp_as_number */
956 0, /* tp_as_sequence */
957 0, /* tp_as_mapping */
958 (hashfunc)_Py_HashPointer, /* tp_hash */
959 (ternaryfunc)type_call, /* tp_call */
960 0, /* tp_str */
961 (getattrofunc)type_getattro, /* tp_getattro */
962 (setattrofunc)type_setattro, /* tp_setattro */
963 0, /* tp_as_buffer */
964 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
965 type_doc, /* tp_doc */
966 0, /* tp_traverse */
967 0, /* tp_clear */
968 0, /* tp_richcompare */
969 0, /* tp_weaklistoffset */
970 0, /* tp_iter */
971 0, /* tp_iternext */
972 type_methods, /* tp_methods */
973 type_members, /* tp_members */
974 type_getsets, /* tp_getset */
975 0, /* tp_base */
976 0, /* tp_dict */
977 0, /* tp_descr_get */
978 0, /* tp_descr_set */
979 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
980 0, /* tp_init */
981 0, /* tp_alloc */
982 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000983};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000984
985
986/* The base type of all types (eventually)... except itself. */
987
988static int
989object_init(PyObject *self, PyObject *args, PyObject *kwds)
990{
991 return 0;
992}
993
994static void
995object_dealloc(PyObject *self)
996{
997 self->ob_type->tp_free(self);
998}
999
Guido van Rossum8e248182001-08-12 05:17:56 +00001000static PyObject *
1001object_repr(PyObject *self)
1002{
Guido van Rossum76e69632001-08-16 18:52:43 +00001003 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001004 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001005
Guido van Rossum76e69632001-08-16 18:52:43 +00001006 type = self->ob_type;
1007 mod = type_module(type, NULL);
1008 if (mod == NULL)
1009 PyErr_Clear();
1010 else if (!PyString_Check(mod)) {
1011 Py_DECREF(mod);
1012 mod = NULL;
1013 }
1014 name = type_name(type, NULL);
1015 if (name == NULL)
1016 return NULL;
1017 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Barry Warsaw7ce36942001-08-24 18:34:26 +00001018 rtn = PyString_FromFormat("<%s.%s instance at %p>",
1019 PyString_AS_STRING(mod),
1020 PyString_AS_STRING(name),
1021 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001022 else
Barry Warsaw7ce36942001-08-24 18:34:26 +00001023 rtn = PyString_FromFormat("<%s instance at %p>",
1024 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001025 Py_XDECREF(mod);
1026 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001027 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001028}
1029
Guido van Rossumb8f63662001-08-15 23:57:02 +00001030static PyObject *
1031object_str(PyObject *self)
1032{
1033 unaryfunc f;
1034
1035 f = self->ob_type->tp_repr;
1036 if (f == NULL)
1037 f = object_repr;
1038 return f(self);
1039}
1040
Guido van Rossum8e248182001-08-12 05:17:56 +00001041static long
1042object_hash(PyObject *self)
1043{
1044 return _Py_HashPointer(self);
1045}
Guido van Rossum8e248182001-08-12 05:17:56 +00001046
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047static void
1048object_free(PyObject *self)
1049{
1050 PyObject_Del(self);
1051}
1052
1053static struct memberlist object_members[] = {
1054 {"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
1055 {0}
1056};
1057
1058PyTypeObject PyBaseObject_Type = {
1059 PyObject_HEAD_INIT(&PyType_Type)
1060 0, /* ob_size */
1061 "object", /* tp_name */
1062 sizeof(PyObject), /* tp_basicsize */
1063 0, /* tp_itemsize */
1064 (destructor)object_dealloc, /* tp_dealloc */
1065 0, /* tp_print */
1066 0, /* tp_getattr */
1067 0, /* tp_setattr */
1068 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001069 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001070 0, /* tp_as_number */
1071 0, /* tp_as_sequence */
1072 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001073 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001074 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001075 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001076 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001077 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001078 0, /* tp_as_buffer */
1079 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1080 "The most base type", /* tp_doc */
1081 0, /* tp_traverse */
1082 0, /* tp_clear */
1083 0, /* tp_richcompare */
1084 0, /* tp_weaklistoffset */
1085 0, /* tp_iter */
1086 0, /* tp_iternext */
1087 0, /* tp_methods */
1088 object_members, /* tp_members */
1089 0, /* tp_getset */
1090 0, /* tp_base */
1091 0, /* tp_dict */
1092 0, /* tp_descr_get */
1093 0, /* tp_descr_set */
1094 0, /* tp_dictoffset */
1095 object_init, /* tp_init */
1096 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001097 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001098 object_free, /* tp_free */
1099};
1100
1101
1102/* Initialize the __dict__ in a type object */
1103
1104static int
1105add_methods(PyTypeObject *type, PyMethodDef *meth)
1106{
1107 PyObject *dict = type->tp_defined;
1108
1109 for (; meth->ml_name != NULL; meth++) {
1110 PyObject *descr;
1111 if (PyDict_GetItemString(dict, meth->ml_name))
1112 continue;
1113 descr = PyDescr_NewMethod(type, meth);
1114 if (descr == NULL)
1115 return -1;
1116 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1117 return -1;
1118 Py_DECREF(descr);
1119 }
1120 return 0;
1121}
1122
1123static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00001124add_members(PyTypeObject *type, struct memberlist *memb)
1125{
1126 PyObject *dict = type->tp_defined;
1127
1128 for (; memb->name != NULL; memb++) {
1129 PyObject *descr;
1130 if (PyDict_GetItemString(dict, memb->name))
1131 continue;
1132 descr = PyDescr_NewMember(type, memb);
1133 if (descr == NULL)
1134 return -1;
1135 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1136 return -1;
1137 Py_DECREF(descr);
1138 }
1139 return 0;
1140}
1141
1142static int
1143add_getset(PyTypeObject *type, struct getsetlist *gsp)
1144{
1145 PyObject *dict = type->tp_defined;
1146
1147 for (; gsp->name != NULL; gsp++) {
1148 PyObject *descr;
1149 if (PyDict_GetItemString(dict, gsp->name))
1150 continue;
1151 descr = PyDescr_NewGetSet(type, gsp);
1152
1153 if (descr == NULL)
1154 return -1;
1155 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1156 return -1;
1157 Py_DECREF(descr);
1158 }
1159 return 0;
1160}
1161
Guido van Rossum13d52f02001-08-10 21:24:08 +00001162static void
1163inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001164{
1165 int oldsize, newsize;
1166
Guido van Rossum13d52f02001-08-10 21:24:08 +00001167 /* Special flag magic */
1168 if (!type->tp_as_buffer && base->tp_as_buffer) {
1169 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1170 type->tp_flags |=
1171 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1172 }
1173 if (!type->tp_as_sequence && base->tp_as_sequence) {
1174 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1175 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1176 }
1177 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1178 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1179 if ((!type->tp_as_number && base->tp_as_number) ||
1180 (!type->tp_as_sequence && base->tp_as_sequence)) {
1181 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1182 if (!type->tp_as_number && !type->tp_as_sequence) {
1183 type->tp_flags |= base->tp_flags &
1184 Py_TPFLAGS_HAVE_INPLACEOPS;
1185 }
1186 }
1187 /* Wow */
1188 }
1189 if (!type->tp_as_number && base->tp_as_number) {
1190 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1191 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1192 }
1193
1194 /* Copying basicsize is connected to the GC flags */
1195 oldsize = PyType_BASICSIZE(base);
1196 newsize = type->tp_basicsize ? PyType_BASICSIZE(type) : oldsize;
1197 if (!(type->tp_flags & Py_TPFLAGS_GC) &&
1198 (base->tp_flags & Py_TPFLAGS_GC) &&
1199 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1200 (!type->tp_traverse && !type->tp_clear)) {
1201 type->tp_flags |= Py_TPFLAGS_GC;
1202 if (type->tp_traverse == NULL)
1203 type->tp_traverse = base->tp_traverse;
1204 if (type->tp_clear == NULL)
1205 type->tp_clear = base->tp_clear;
1206 }
1207 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1208 if (base != &PyBaseObject_Type ||
1209 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1210 if (type->tp_new == NULL)
1211 type->tp_new = base->tp_new;
1212 }
1213 }
1214 PyType_SET_BASICSIZE(type, newsize);
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001215
1216 /* Copy other non-function slots */
1217
1218#undef COPYVAL
1219#define COPYVAL(SLOT) \
1220 if (type->SLOT == 0) type->SLOT = base->SLOT
1221
1222 COPYVAL(tp_itemsize);
1223 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1224 COPYVAL(tp_weaklistoffset);
1225 }
1226 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1227 COPYVAL(tp_dictoffset);
1228 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001229}
1230
1231static void
1232inherit_slots(PyTypeObject *type, PyTypeObject *base)
1233{
1234 PyTypeObject *basebase;
1235
1236#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237#undef COPYSLOT
1238#undef COPYNUM
1239#undef COPYSEQ
1240#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001241
1242#define SLOTDEFINED(SLOT) \
1243 (base->SLOT != 0 && \
1244 (basebase == NULL || base->SLOT != basebase->SLOT))
1245
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001247 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001248
1249#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1250#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1251#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1252
Guido van Rossum13d52f02001-08-10 21:24:08 +00001253 /* This won't inherit indirect slots (from tp_as_number etc.)
1254 if type doesn't provide the space. */
1255
1256 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1257 basebase = base->tp_base;
1258 if (basebase->tp_as_number == NULL)
1259 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001260 COPYNUM(nb_add);
1261 COPYNUM(nb_subtract);
1262 COPYNUM(nb_multiply);
1263 COPYNUM(nb_divide);
1264 COPYNUM(nb_remainder);
1265 COPYNUM(nb_divmod);
1266 COPYNUM(nb_power);
1267 COPYNUM(nb_negative);
1268 COPYNUM(nb_positive);
1269 COPYNUM(nb_absolute);
1270 COPYNUM(nb_nonzero);
1271 COPYNUM(nb_invert);
1272 COPYNUM(nb_lshift);
1273 COPYNUM(nb_rshift);
1274 COPYNUM(nb_and);
1275 COPYNUM(nb_xor);
1276 COPYNUM(nb_or);
1277 COPYNUM(nb_coerce);
1278 COPYNUM(nb_int);
1279 COPYNUM(nb_long);
1280 COPYNUM(nb_float);
1281 COPYNUM(nb_oct);
1282 COPYNUM(nb_hex);
1283 COPYNUM(nb_inplace_add);
1284 COPYNUM(nb_inplace_subtract);
1285 COPYNUM(nb_inplace_multiply);
1286 COPYNUM(nb_inplace_divide);
1287 COPYNUM(nb_inplace_remainder);
1288 COPYNUM(nb_inplace_power);
1289 COPYNUM(nb_inplace_lshift);
1290 COPYNUM(nb_inplace_rshift);
1291 COPYNUM(nb_inplace_and);
1292 COPYNUM(nb_inplace_xor);
1293 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001294 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1295 COPYNUM(nb_true_divide);
1296 COPYNUM(nb_floor_divide);
1297 COPYNUM(nb_inplace_true_divide);
1298 COPYNUM(nb_inplace_floor_divide);
1299 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001300 }
1301
Guido van Rossum13d52f02001-08-10 21:24:08 +00001302 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1303 basebase = base->tp_base;
1304 if (basebase->tp_as_sequence == NULL)
1305 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 COPYSEQ(sq_length);
1307 COPYSEQ(sq_concat);
1308 COPYSEQ(sq_repeat);
1309 COPYSEQ(sq_item);
1310 COPYSEQ(sq_slice);
1311 COPYSEQ(sq_ass_item);
1312 COPYSEQ(sq_ass_slice);
1313 COPYSEQ(sq_contains);
1314 COPYSEQ(sq_inplace_concat);
1315 COPYSEQ(sq_inplace_repeat);
1316 }
1317
Guido van Rossum13d52f02001-08-10 21:24:08 +00001318 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1319 basebase = base->tp_base;
1320 if (basebase->tp_as_mapping == NULL)
1321 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322 COPYMAP(mp_length);
1323 COPYMAP(mp_subscript);
1324 COPYMAP(mp_ass_subscript);
1325 }
1326
Guido van Rossum13d52f02001-08-10 21:24:08 +00001327 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001328
Tim Peters6d6c1a32001-08-02 04:15:00 +00001329 COPYSLOT(tp_dealloc);
1330 COPYSLOT(tp_print);
1331 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1332 type->tp_getattr = base->tp_getattr;
1333 type->tp_getattro = base->tp_getattro;
1334 }
1335 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1336 type->tp_setattr = base->tp_setattr;
1337 type->tp_setattro = base->tp_setattro;
1338 }
1339 /* tp_compare see tp_richcompare */
1340 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001341 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001342 COPYSLOT(tp_call);
1343 COPYSLOT(tp_str);
1344 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001345 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001346 if (type->tp_compare == NULL &&
1347 type->tp_richcompare == NULL &&
1348 type->tp_hash == NULL)
1349 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001350 type->tp_compare = base->tp_compare;
1351 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001352 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001353 }
1354 }
1355 else {
1356 COPYSLOT(tp_compare);
1357 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001358 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1359 COPYSLOT(tp_iter);
1360 COPYSLOT(tp_iternext);
1361 }
1362 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1363 COPYSLOT(tp_descr_get);
1364 COPYSLOT(tp_descr_set);
1365 COPYSLOT(tp_dictoffset);
1366 COPYSLOT(tp_init);
1367 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001368 COPYSLOT(tp_free);
1369 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001370}
1371
Guido van Rossum13d52f02001-08-10 21:24:08 +00001372staticforward int add_operators(PyTypeObject *);
1373
Tim Peters6d6c1a32001-08-02 04:15:00 +00001374int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001375PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001376{
1377 PyObject *dict, *bases, *x;
1378 PyTypeObject *base;
1379 int i, n;
1380
Guido van Rossumd614f972001-08-10 17:39:49 +00001381 if (type->tp_flags & Py_TPFLAGS_READY) {
1382 assert(type->tp_dict != NULL);
1383 return 0;
1384 }
1385 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1386 assert(type->tp_dict == NULL);
1387
1388 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001389
1390 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1391 base = type->tp_base;
1392 if (base == NULL && type != &PyBaseObject_Type)
1393 base = type->tp_base = &PyBaseObject_Type;
1394
1395 /* Initialize tp_bases */
1396 bases = type->tp_bases;
1397 if (bases == NULL) {
1398 if (base == NULL)
1399 bases = PyTuple_New(0);
1400 else
1401 bases = Py_BuildValue("(O)", base);
1402 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001403 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001404 type->tp_bases = bases;
1405 }
1406
1407 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001408 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001409 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001410 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001411 }
1412
1413 /* Initialize tp_defined */
1414 dict = type->tp_defined;
1415 if (dict == NULL) {
1416 dict = PyDict_New();
1417 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001418 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001419 type->tp_defined = dict;
1420 }
1421
1422 /* Add type-specific descriptors to tp_defined */
1423 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001424 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001425 if (type->tp_methods != NULL) {
1426 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001427 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001428 }
1429 if (type->tp_members != NULL) {
1430 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001431 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001432 }
1433 if (type->tp_getset != NULL) {
1434 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001435 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001436 }
1437
1438 /* Temporarily make tp_dict the same object as tp_defined.
1439 (This is needed to call mro(), and can stay this way for
1440 dynamic types). */
1441 Py_INCREF(type->tp_defined);
1442 type->tp_dict = type->tp_defined;
1443
1444 /* Calculate method resolution order */
1445 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001446 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001447 }
1448
Guido van Rossum13d52f02001-08-10 21:24:08 +00001449 /* Inherit special flags from dominant base */
1450 if (type->tp_base != NULL)
1451 inherit_special(type, type->tp_base);
1452
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001454 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001455 /* For a dynamic type, all slots are overridden */
1456 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001457 }
1458 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001459 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001460 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001461 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001462 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001464 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001465 bases = type->tp_mro;
1466 assert(bases != NULL);
1467 assert(PyTuple_Check(bases));
1468 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001469 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1471 assert(PyType_Check(base));
1472 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001473 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001474 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001475 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476 }
1477 }
1478
Guido van Rossum13d52f02001-08-10 21:24:08 +00001479 /* Some more special stuff */
1480 base = type->tp_base;
1481 if (base != NULL) {
1482 if (type->tp_as_number == NULL)
1483 type->tp_as_number = base->tp_as_number;
1484 if (type->tp_as_sequence == NULL)
1485 type->tp_as_sequence = base->tp_as_sequence;
1486 if (type->tp_as_mapping == NULL)
1487 type->tp_as_mapping = base->tp_as_mapping;
1488 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001489
Guido van Rossum13d52f02001-08-10 21:24:08 +00001490 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001491 assert(type->tp_dict != NULL);
1492 type->tp_flags =
1493 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001494 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001495
1496 error:
1497 type->tp_flags &= ~Py_TPFLAGS_READYING;
1498 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001499}
1500
1501
1502/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1503
1504/* There's a wrapper *function* for each distinct function typedef used
1505 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1506 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1507 Most tables have only one entry; the tables for binary operators have two
1508 entries, one regular and one with reversed arguments. */
1509
1510static PyObject *
1511wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1512{
1513 inquiry func = (inquiry)wrapped;
1514 int res;
1515
1516 if (!PyArg_ParseTuple(args, ""))
1517 return NULL;
1518 res = (*func)(self);
1519 if (res == -1 && PyErr_Occurred())
1520 return NULL;
1521 return PyInt_FromLong((long)res);
1522}
1523
1524static struct wrapperbase tab_len[] = {
1525 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1526 {0}
1527};
1528
1529static PyObject *
1530wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1531{
1532 binaryfunc func = (binaryfunc)wrapped;
1533 PyObject *other;
1534
1535 if (!PyArg_ParseTuple(args, "O", &other))
1536 return NULL;
1537 return (*func)(self, other);
1538}
1539
1540static PyObject *
1541wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1542{
1543 binaryfunc func = (binaryfunc)wrapped;
1544 PyObject *other;
1545
1546 if (!PyArg_ParseTuple(args, "O", &other))
1547 return NULL;
1548 return (*func)(other, self);
1549}
1550
1551#undef BINARY
1552#define BINARY(NAME, OP) \
1553static struct wrapperbase tab_##NAME[] = { \
1554 {"__" #NAME "__", \
1555 (wrapperfunc)wrap_binaryfunc, \
1556 "x.__" #NAME "__(y) <==> " #OP}, \
1557 {"__r" #NAME "__", \
1558 (wrapperfunc)wrap_binaryfunc_r, \
1559 "y.__r" #NAME "__(x) <==> " #OP}, \
1560 {0} \
1561}
1562
1563BINARY(add, "x+y");
1564BINARY(sub, "x-y");
1565BINARY(mul, "x*y");
1566BINARY(div, "x/y");
1567BINARY(mod, "x%y");
1568BINARY(divmod, "divmod(x,y)");
1569BINARY(lshift, "x<<y");
1570BINARY(rshift, "x>>y");
1571BINARY(and, "x&y");
1572BINARY(xor, "x^y");
1573BINARY(or, "x|y");
1574
1575static PyObject *
1576wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1577{
1578 ternaryfunc func = (ternaryfunc)wrapped;
1579 PyObject *other;
1580 PyObject *third = Py_None;
1581
1582 /* Note: This wrapper only works for __pow__() */
1583
1584 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1585 return NULL;
1586 return (*func)(self, other, third);
1587}
1588
1589#undef TERNARY
1590#define TERNARY(NAME, OP) \
1591static struct wrapperbase tab_##NAME[] = { \
1592 {"__" #NAME "__", \
1593 (wrapperfunc)wrap_ternaryfunc, \
1594 "x.__" #NAME "__(y, z) <==> " #OP}, \
1595 {"__r" #NAME "__", \
1596 (wrapperfunc)wrap_ternaryfunc, \
1597 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1598 {0} \
1599}
1600
1601TERNARY(pow, "(x**y) % z");
1602
1603#undef UNARY
1604#define UNARY(NAME, OP) \
1605static struct wrapperbase tab_##NAME[] = { \
1606 {"__" #NAME "__", \
1607 (wrapperfunc)wrap_unaryfunc, \
1608 "x.__" #NAME "__() <==> " #OP}, \
1609 {0} \
1610}
1611
1612static PyObject *
1613wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1614{
1615 unaryfunc func = (unaryfunc)wrapped;
1616
1617 if (!PyArg_ParseTuple(args, ""))
1618 return NULL;
1619 return (*func)(self);
1620}
1621
1622UNARY(neg, "-x");
1623UNARY(pos, "+x");
1624UNARY(abs, "abs(x)");
1625UNARY(nonzero, "x != 0");
1626UNARY(invert, "~x");
1627UNARY(int, "int(x)");
1628UNARY(long, "long(x)");
1629UNARY(float, "float(x)");
1630UNARY(oct, "oct(x)");
1631UNARY(hex, "hex(x)");
1632
1633#undef IBINARY
1634#define IBINARY(NAME, OP) \
1635static struct wrapperbase tab_##NAME[] = { \
1636 {"__" #NAME "__", \
1637 (wrapperfunc)wrap_binaryfunc, \
1638 "x.__" #NAME "__(y) <==> " #OP}, \
1639 {0} \
1640}
1641
1642IBINARY(iadd, "x+=y");
1643IBINARY(isub, "x-=y");
1644IBINARY(imul, "x*=y");
1645IBINARY(idiv, "x/=y");
1646IBINARY(imod, "x%=y");
1647IBINARY(ilshift, "x<<=y");
1648IBINARY(irshift, "x>>=y");
1649IBINARY(iand, "x&=y");
1650IBINARY(ixor, "x^=y");
1651IBINARY(ior, "x|=y");
1652
1653#undef ITERNARY
1654#define ITERNARY(NAME, OP) \
1655static struct wrapperbase tab_##NAME[] = { \
1656 {"__" #NAME "__", \
1657 (wrapperfunc)wrap_ternaryfunc, \
1658 "x.__" #NAME "__(y) <==> " #OP}, \
1659 {0} \
1660}
1661
1662ITERNARY(ipow, "x = (x**y) % z");
1663
1664static struct wrapperbase tab_getitem[] = {
1665 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1666 "x.__getitem__(y) <==> x[y]"},
1667 {0}
1668};
1669
1670static PyObject *
1671wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1672{
1673 intargfunc func = (intargfunc)wrapped;
1674 int i;
1675
1676 if (!PyArg_ParseTuple(args, "i", &i))
1677 return NULL;
1678 return (*func)(self, i);
1679}
1680
1681static struct wrapperbase tab_mul_int[] = {
1682 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1683 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1684 {0}
1685};
1686
1687static struct wrapperbase tab_concat[] = {
1688 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1689 {0}
1690};
1691
1692static struct wrapperbase tab_imul_int[] = {
1693 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1694 {0}
1695};
1696
Guido van Rossum5d815f32001-08-17 21:57:47 +00001697static int
1698getindex(PyObject *self, PyObject *arg)
1699{
1700 int i;
1701
1702 i = PyInt_AsLong(arg);
1703 if (i == -1 && PyErr_Occurred())
1704 return -1;
1705 if (i < 0) {
1706 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
1707 if (sq && sq->sq_length) {
1708 int n = (*sq->sq_length)(self);
1709 if (n < 0)
1710 return -1;
1711 i += n;
1712 }
1713 }
1714 return i;
1715}
1716
1717static PyObject *
1718wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
1719{
1720 intargfunc func = (intargfunc)wrapped;
1721 PyObject *arg;
1722 int i;
1723
1724 if (!PyArg_ParseTuple(args, "O", &arg))
1725 return NULL;
1726 i = getindex(self, arg);
1727 if (i == -1 && PyErr_Occurred())
1728 return NULL;
1729 return (*func)(self, i);
1730}
1731
Tim Peters6d6c1a32001-08-02 04:15:00 +00001732static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001733 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001734 "x.__getitem__(i) <==> x[i]"},
1735 {0}
1736};
1737
1738static PyObject *
1739wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1740{
1741 intintargfunc func = (intintargfunc)wrapped;
1742 int i, j;
1743
1744 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1745 return NULL;
1746 return (*func)(self, i, j);
1747}
1748
1749static struct wrapperbase tab_getslice[] = {
1750 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1751 "x.__getslice__(i, j) <==> x[i:j]"},
1752 {0}
1753};
1754
1755static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001756wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001757{
1758 intobjargproc func = (intobjargproc)wrapped;
1759 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001760 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001761
Guido van Rossum5d815f32001-08-17 21:57:47 +00001762 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
1763 return NULL;
1764 i = getindex(self, arg);
1765 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766 return NULL;
1767 res = (*func)(self, i, value);
1768 if (res == -1 && PyErr_Occurred())
1769 return NULL;
1770 Py_INCREF(Py_None);
1771 return Py_None;
1772}
1773
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001774static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001775wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001776{
1777 intobjargproc func = (intobjargproc)wrapped;
1778 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001779 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001780
Guido van Rossum5d815f32001-08-17 21:57:47 +00001781 if (!PyArg_ParseTuple(args, "O", &arg))
1782 return NULL;
1783 i = getindex(self, arg);
1784 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001785 return NULL;
1786 res = (*func)(self, i, NULL);
1787 if (res == -1 && PyErr_Occurred())
1788 return NULL;
1789 Py_INCREF(Py_None);
1790 return Py_None;
1791}
1792
Tim Peters6d6c1a32001-08-02 04:15:00 +00001793static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001794 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00001796 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001797 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798 {0}
1799};
1800
1801static PyObject *
1802wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1803{
1804 intintobjargproc func = (intintobjargproc)wrapped;
1805 int i, j, res;
1806 PyObject *value;
1807
1808 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1809 return NULL;
1810 res = (*func)(self, i, j, value);
1811 if (res == -1 && PyErr_Occurred())
1812 return NULL;
1813 Py_INCREF(Py_None);
1814 return Py_None;
1815}
1816
1817static struct wrapperbase tab_setslice[] = {
1818 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1819 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1820 {0}
1821};
1822
1823/* XXX objobjproc is a misnomer; should be objargpred */
1824static PyObject *
1825wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1826{
1827 objobjproc func = (objobjproc)wrapped;
1828 int res;
1829 PyObject *value;
1830
1831 if (!PyArg_ParseTuple(args, "O", &value))
1832 return NULL;
1833 res = (*func)(self, value);
1834 if (res == -1 && PyErr_Occurred())
1835 return NULL;
1836 return PyInt_FromLong((long)res);
1837}
1838
1839static struct wrapperbase tab_contains[] = {
1840 {"__contains__", (wrapperfunc)wrap_objobjproc,
1841 "x.__contains__(y) <==> y in x"},
1842 {0}
1843};
1844
1845static PyObject *
1846wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1847{
1848 objobjargproc func = (objobjargproc)wrapped;
1849 int res;
1850 PyObject *key, *value;
1851
1852 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1853 return NULL;
1854 res = (*func)(self, key, value);
1855 if (res == -1 && PyErr_Occurred())
1856 return NULL;
1857 Py_INCREF(Py_None);
1858 return Py_None;
1859}
1860
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001861static PyObject *
1862wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1863{
1864 objobjargproc func = (objobjargproc)wrapped;
1865 int res;
1866 PyObject *key;
1867
1868 if (!PyArg_ParseTuple(args, "O", &key))
1869 return NULL;
1870 res = (*func)(self, key, NULL);
1871 if (res == -1 && PyErr_Occurred())
1872 return NULL;
1873 Py_INCREF(Py_None);
1874 return Py_None;
1875}
1876
Tim Peters6d6c1a32001-08-02 04:15:00 +00001877static struct wrapperbase tab_setitem[] = {
1878 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1879 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001880 {"__delitem__", (wrapperfunc)wrap_delitem,
1881 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882 {0}
1883};
1884
1885static PyObject *
1886wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1887{
1888 cmpfunc func = (cmpfunc)wrapped;
1889 int res;
1890 PyObject *other;
1891
1892 if (!PyArg_ParseTuple(args, "O", &other))
1893 return NULL;
1894 res = (*func)(self, other);
1895 if (PyErr_Occurred())
1896 return NULL;
1897 return PyInt_FromLong((long)res);
1898}
1899
1900static struct wrapperbase tab_cmp[] = {
1901 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1902 "x.__cmp__(y) <==> cmp(x,y)"},
1903 {0}
1904};
1905
1906static struct wrapperbase tab_repr[] = {
1907 {"__repr__", (wrapperfunc)wrap_unaryfunc,
1908 "x.__repr__() <==> repr(x)"},
1909 {0}
1910};
1911
1912static struct wrapperbase tab_getattr[] = {
1913 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
1914 "x.__getattr__('name') <==> x.name"},
1915 {0}
1916};
1917
1918static PyObject *
1919wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
1920{
1921 setattrofunc func = (setattrofunc)wrapped;
1922 int res;
1923 PyObject *name, *value;
1924
1925 if (!PyArg_ParseTuple(args, "OO", &name, &value))
1926 return NULL;
1927 res = (*func)(self, name, value);
1928 if (res < 0)
1929 return NULL;
1930 Py_INCREF(Py_None);
1931 return Py_None;
1932}
1933
1934static PyObject *
1935wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
1936{
1937 setattrofunc func = (setattrofunc)wrapped;
1938 int res;
1939 PyObject *name;
1940
1941 if (!PyArg_ParseTuple(args, "O", &name))
1942 return NULL;
1943 res = (*func)(self, name, NULL);
1944 if (res < 0)
1945 return NULL;
1946 Py_INCREF(Py_None);
1947 return Py_None;
1948}
1949
1950static struct wrapperbase tab_setattr[] = {
1951 {"__setattr__", (wrapperfunc)wrap_setattr,
1952 "x.__setattr__('name', value) <==> x.name = value"},
1953 {"__delattr__", (wrapperfunc)wrap_delattr,
1954 "x.__delattr__('name') <==> del x.name"},
1955 {0}
1956};
1957
1958static PyObject *
1959wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
1960{
1961 hashfunc func = (hashfunc)wrapped;
1962 long res;
1963
1964 if (!PyArg_ParseTuple(args, ""))
1965 return NULL;
1966 res = (*func)(self);
1967 if (res == -1 && PyErr_Occurred())
1968 return NULL;
1969 return PyInt_FromLong(res);
1970}
1971
1972static struct wrapperbase tab_hash[] = {
1973 {"__hash__", (wrapperfunc)wrap_hashfunc,
1974 "x.__hash__() <==> hash(x)"},
1975 {0}
1976};
1977
1978static PyObject *
1979wrap_call(PyObject *self, PyObject *args, void *wrapped)
1980{
1981 ternaryfunc func = (ternaryfunc)wrapped;
1982
1983 /* XXX What about keyword arguments? */
1984 return (*func)(self, args, NULL);
1985}
1986
1987static struct wrapperbase tab_call[] = {
1988 {"__call__", (wrapperfunc)wrap_call,
1989 "x.__call__(...) <==> x(...)"},
1990 {0}
1991};
1992
1993static struct wrapperbase tab_str[] = {
1994 {"__str__", (wrapperfunc)wrap_unaryfunc,
1995 "x.__str__() <==> str(x)"},
1996 {0}
1997};
1998
1999static PyObject *
2000wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2001{
2002 richcmpfunc func = (richcmpfunc)wrapped;
2003 PyObject *other;
2004
2005 if (!PyArg_ParseTuple(args, "O", &other))
2006 return NULL;
2007 return (*func)(self, other, op);
2008}
2009
2010#undef RICHCMP_WRAPPER
2011#define RICHCMP_WRAPPER(NAME, OP) \
2012static PyObject * \
2013richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2014{ \
2015 return wrap_richcmpfunc(self, args, wrapped, OP); \
2016}
2017
Jack Jansen8e938b42001-08-08 15:29:49 +00002018RICHCMP_WRAPPER(lt, Py_LT)
2019RICHCMP_WRAPPER(le, Py_LE)
2020RICHCMP_WRAPPER(eq, Py_EQ)
2021RICHCMP_WRAPPER(ne, Py_NE)
2022RICHCMP_WRAPPER(gt, Py_GT)
2023RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002024
2025#undef RICHCMP_ENTRY
2026#define RICHCMP_ENTRY(NAME, EXPR) \
2027 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2028 "x.__" #NAME "__(y) <==> " EXPR}
2029
2030static struct wrapperbase tab_richcmp[] = {
2031 RICHCMP_ENTRY(lt, "x<y"),
2032 RICHCMP_ENTRY(le, "x<=y"),
2033 RICHCMP_ENTRY(eq, "x==y"),
2034 RICHCMP_ENTRY(ne, "x!=y"),
2035 RICHCMP_ENTRY(gt, "x>y"),
2036 RICHCMP_ENTRY(ge, "x>=y"),
2037 {0}
2038};
2039
2040static struct wrapperbase tab_iter[] = {
2041 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2042 {0}
2043};
2044
2045static PyObject *
2046wrap_next(PyObject *self, PyObject *args, void *wrapped)
2047{
2048 unaryfunc func = (unaryfunc)wrapped;
2049 PyObject *res;
2050
2051 if (!PyArg_ParseTuple(args, ""))
2052 return NULL;
2053 res = (*func)(self);
2054 if (res == NULL && !PyErr_Occurred())
2055 PyErr_SetNone(PyExc_StopIteration);
2056 return res;
2057}
2058
2059static struct wrapperbase tab_next[] = {
2060 {"next", (wrapperfunc)wrap_next,
2061 "x.next() -> the next value, or raise StopIteration"},
2062 {0}
2063};
2064
2065static PyObject *
2066wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2067{
2068 descrgetfunc func = (descrgetfunc)wrapped;
2069 PyObject *obj;
2070 PyObject *type = NULL;
2071
2072 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2073 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002074 return (*func)(self, obj, type);
2075}
2076
2077static struct wrapperbase tab_descr_get[] = {
2078 {"__get__", (wrapperfunc)wrap_descr_get,
2079 "descr.__get__(obj, type) -> value"},
2080 {0}
2081};
2082
2083static PyObject *
2084wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2085{
2086 descrsetfunc func = (descrsetfunc)wrapped;
2087 PyObject *obj, *value;
2088 int ret;
2089
2090 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2091 return NULL;
2092 ret = (*func)(self, obj, value);
2093 if (ret < 0)
2094 return NULL;
2095 Py_INCREF(Py_None);
2096 return Py_None;
2097}
2098
2099static struct wrapperbase tab_descr_set[] = {
2100 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2101 "descr.__set__(obj, value)"},
2102 {0}
2103};
2104
2105static PyObject *
2106wrap_init(PyObject *self, PyObject *args, void *wrapped)
2107{
2108 initproc func = (initproc)wrapped;
2109
2110 /* XXX What about keyword arguments? */
2111 if (func(self, args, NULL) < 0)
2112 return NULL;
2113 Py_INCREF(Py_None);
2114 return Py_None;
2115}
2116
2117static struct wrapperbase tab_init[] = {
2118 {"__init__", (wrapperfunc)wrap_init,
2119 "x.__init__(...) initializes x; "
2120 "see x.__type__.__doc__ for signature"},
2121 {0}
2122};
2123
2124static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002125tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126{
Barry Warsaw60f01882001-08-22 19:24:42 +00002127 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002128 PyObject *arg0, *res;
2129
2130 if (self == NULL || !PyType_Check(self))
2131 Py_FatalError("__new__() called with non-type 'self'");
2132 type = (PyTypeObject *)self;
2133 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002134 PyErr_Format(PyExc_TypeError,
2135 "%s.__new__(): not enough arguments",
2136 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002137 return NULL;
2138 }
2139 arg0 = PyTuple_GET_ITEM(args, 0);
2140 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002141 PyErr_Format(PyExc_TypeError,
2142 "%s.__new__(X): X is not a type object (%s)",
2143 type->tp_name,
2144 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002145 return NULL;
2146 }
2147 subtype = (PyTypeObject *)arg0;
2148 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002149 PyErr_Format(PyExc_TypeError,
2150 "%s.__new__(%s): %s is not a subtype of %s",
2151 type->tp_name,
2152 subtype->tp_name,
2153 subtype->tp_name,
2154 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002155 return NULL;
2156 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002157
2158 /* Check that the use doesn't do something silly and unsafe like
2159 object.__new__(dictionary). To do this, we check that the
2160 most derived base that's not a heap type is this type. */
2161 staticbase = subtype;
2162 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2163 staticbase = staticbase->tp_base;
2164 if (staticbase != type) {
2165 PyErr_Format(PyExc_TypeError,
2166 "%s.__new__(%s) is not safe, use %s.__new__()",
2167 type->tp_name,
2168 subtype->tp_name,
2169 staticbase == NULL ? "?" : staticbase->tp_name);
2170 return NULL;
2171 }
2172
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002173 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2174 if (args == NULL)
2175 return NULL;
2176 res = type->tp_new(subtype, args, kwds);
2177 Py_DECREF(args);
2178 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002179}
2180
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002181static struct PyMethodDef tp_new_methoddef[] = {
2182 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2183 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002184 {0}
2185};
2186
2187static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002188add_tp_new_wrapper(PyTypeObject *type)
2189{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002190 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002191
Guido van Rossumf040ede2001-08-07 16:40:56 +00002192 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2193 return 0;
2194 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002195 if (func == NULL)
2196 return -1;
2197 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2198}
2199
Guido van Rossum13d52f02001-08-10 21:24:08 +00002200static int
2201add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2202{
2203 PyObject *dict = type->tp_defined;
2204
2205 for (; wraps->name != NULL; wraps++) {
2206 PyObject *descr;
2207 if (PyDict_GetItemString(dict, wraps->name))
2208 continue;
2209 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2210 if (descr == NULL)
2211 return -1;
2212 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2213 return -1;
2214 Py_DECREF(descr);
2215 }
2216 return 0;
2217}
2218
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002219/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002220 dictionary with method descriptors for function slots. For each
2221 function slot (like tp_repr) that's defined in the type, one or
2222 more corresponding descriptors are added in the type's tp_defined
2223 dictionary under the appropriate name (like __repr__). Some
2224 function slots cause more than one descriptor to be added (for
2225 example, the nb_add slot adds both __add__ and __radd__
2226 descriptors) and some function slots compete for the same
2227 descriptor (for example both sq_item and mp_subscript generate a
2228 __getitem__ descriptor). This only adds new descriptors and
2229 doesn't overwrite entries in tp_defined that were previously
2230 defined. The descriptors contain a reference to the C function
2231 they must call, so that it's safe if they are copied into a
2232 subtype's __dict__ and the subtype has a different C function in
2233 its slot -- calling the method defined by the descriptor will call
2234 the C function that was used to create it, rather than the C
2235 function present in the slot when it is called. (This is important
2236 because a subtype may have a C function in the slot that calls the
2237 method from the dictionary, and we want to avoid infinite recursion
2238 here.) */
2239
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002240static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241add_operators(PyTypeObject *type)
2242{
2243 PySequenceMethods *sq;
2244 PyMappingMethods *mp;
2245 PyNumberMethods *nb;
2246
2247#undef ADD
2248#define ADD(SLOT, TABLE) \
2249 if (SLOT) { \
2250 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2251 return -1; \
2252 }
2253
2254 if ((sq = type->tp_as_sequence) != NULL) {
2255 ADD(sq->sq_length, tab_len);
2256 ADD(sq->sq_concat, tab_concat);
2257 ADD(sq->sq_repeat, tab_mul_int);
2258 ADD(sq->sq_item, tab_getitem_int);
2259 ADD(sq->sq_slice, tab_getslice);
2260 ADD(sq->sq_ass_item, tab_setitem_int);
2261 ADD(sq->sq_ass_slice, tab_setslice);
2262 ADD(sq->sq_contains, tab_contains);
2263 ADD(sq->sq_inplace_concat, tab_iadd);
2264 ADD(sq->sq_inplace_repeat, tab_imul_int);
2265 }
2266
2267 if ((mp = type->tp_as_mapping) != NULL) {
2268 if (sq->sq_length == NULL)
2269 ADD(mp->mp_length, tab_len);
2270 ADD(mp->mp_subscript, tab_getitem);
2271 ADD(mp->mp_ass_subscript, tab_setitem);
2272 }
2273
2274 /* We don't support "old-style numbers" because their binary
2275 operators require that both arguments have the same type;
2276 the wrappers here only work for new-style numbers. */
2277 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2278 (nb = type->tp_as_number) != NULL) {
2279 ADD(nb->nb_add, tab_add);
2280 ADD(nb->nb_subtract, tab_sub);
2281 ADD(nb->nb_multiply, tab_mul);
2282 ADD(nb->nb_divide, tab_div);
2283 ADD(nb->nb_remainder, tab_mod);
2284 ADD(nb->nb_divmod, tab_divmod);
2285 ADD(nb->nb_power, tab_pow);
2286 ADD(nb->nb_negative, tab_neg);
2287 ADD(nb->nb_positive, tab_pos);
2288 ADD(nb->nb_absolute, tab_abs);
2289 ADD(nb->nb_nonzero, tab_nonzero);
2290 ADD(nb->nb_invert, tab_invert);
2291 ADD(nb->nb_lshift, tab_lshift);
2292 ADD(nb->nb_rshift, tab_rshift);
2293 ADD(nb->nb_and, tab_and);
2294 ADD(nb->nb_xor, tab_xor);
2295 ADD(nb->nb_or, tab_or);
2296 /* We don't support coerce() -- see above comment */
2297 ADD(nb->nb_int, tab_int);
2298 ADD(nb->nb_long, tab_long);
2299 ADD(nb->nb_float, tab_float);
2300 ADD(nb->nb_oct, tab_oct);
2301 ADD(nb->nb_hex, tab_hex);
2302 ADD(nb->nb_inplace_add, tab_iadd);
2303 ADD(nb->nb_inplace_subtract, tab_isub);
2304 ADD(nb->nb_inplace_multiply, tab_imul);
2305 ADD(nb->nb_inplace_divide, tab_idiv);
2306 ADD(nb->nb_inplace_remainder, tab_imod);
2307 ADD(nb->nb_inplace_power, tab_ipow);
2308 ADD(nb->nb_inplace_lshift, tab_ilshift);
2309 ADD(nb->nb_inplace_rshift, tab_irshift);
2310 ADD(nb->nb_inplace_and, tab_iand);
2311 ADD(nb->nb_inplace_xor, tab_ixor);
2312 ADD(nb->nb_inplace_or, tab_ior);
2313 }
2314
2315 ADD(type->tp_getattro, tab_getattr);
2316 ADD(type->tp_setattro, tab_setattr);
2317 ADD(type->tp_compare, tab_cmp);
2318 ADD(type->tp_repr, tab_repr);
2319 ADD(type->tp_hash, tab_hash);
2320 ADD(type->tp_call, tab_call);
2321 ADD(type->tp_str, tab_str);
2322 ADD(type->tp_richcompare, tab_richcmp);
2323 ADD(type->tp_iter, tab_iter);
2324 ADD(type->tp_iternext, tab_next);
2325 ADD(type->tp_descr_get, tab_descr_get);
2326 ADD(type->tp_descr_set, tab_descr_set);
2327 ADD(type->tp_init, tab_init);
2328
Guido van Rossumf040ede2001-08-07 16:40:56 +00002329 if (type->tp_new != NULL) {
2330 if (add_tp_new_wrapper(type) < 0)
2331 return -1;
2332 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002333
2334 return 0;
2335}
2336
Guido van Rossumf040ede2001-08-07 16:40:56 +00002337/* Slot wrappers that call the corresponding __foo__ slot. See comments
2338 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002339
Guido van Rossumdc91b992001-08-08 22:26:22 +00002340#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002342FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002343{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002344 return PyObject_CallMethod(self, OPSTR, ""); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002345}
2346
Guido van Rossumdc91b992001-08-08 22:26:22 +00002347#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002348static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002349FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002351 return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002352}
2353
Guido van Rossumdc91b992001-08-08 22:26:22 +00002354
2355#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002356static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002357FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002358{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002359 if (self->ob_type->tp_as_number != NULL && \
2360 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2361 PyObject *r; \
2362 r = PyObject_CallMethod( \
2363 self, OPSTR, "O", other); \
2364 if (r != Py_NotImplemented || \
2365 other->ob_type == self->ob_type) \
2366 return r; \
2367 Py_DECREF(r); \
2368 } \
2369 if (other->ob_type->tp_as_number != NULL && \
2370 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2371 return PyObject_CallMethod( \
2372 other, ROPSTR, "O", self); \
2373 } \
2374 Py_INCREF(Py_NotImplemented); \
2375 return Py_NotImplemented; \
2376}
2377
2378#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2379 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2380
2381#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2382static PyObject * \
2383FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2384{ \
2385 return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002386}
2387
2388static int
2389slot_sq_length(PyObject *self)
2390{
2391 PyObject *res = PyObject_CallMethod(self, "__len__", "");
2392
2393 if (res == NULL)
2394 return -1;
2395 return (int)PyInt_AsLong(res);
2396}
2397
Guido van Rossumdc91b992001-08-08 22:26:22 +00002398SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2399SLOT1(slot_sq_repeat, "__mul__", int, "i")
2400SLOT1(slot_sq_item, "__getitem__", int, "i")
2401SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002402
2403static int
2404slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2405{
2406 PyObject *res;
2407
2408 if (value == NULL)
2409 res = PyObject_CallMethod(self, "__delitem__", "i", index);
2410 else
2411 res = PyObject_CallMethod(self, "__setitem__",
2412 "iO", index, value);
2413 if (res == NULL)
2414 return -1;
2415 Py_DECREF(res);
2416 return 0;
2417}
2418
2419static int
2420slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2421{
2422 PyObject *res;
2423
2424 if (value == NULL)
2425 res = PyObject_CallMethod(self, "__delslice__", "ii", i, j);
2426 else
2427 res = PyObject_CallMethod(self, "__setslice__",
2428 "iiO", i, j, value);
2429 if (res == NULL)
2430 return -1;
2431 Py_DECREF(res);
2432 return 0;
2433}
2434
2435static int
2436slot_sq_contains(PyObject *self, PyObject *value)
2437{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002438 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002439 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002440
Guido van Rossum60718732001-08-28 17:47:51 +00002441 func = lookup_method(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002442
2443 if (func != NULL) {
2444 args = Py_BuildValue("(O)", value);
2445 if (args == NULL)
2446 res = NULL;
2447 else {
2448 res = PyEval_CallObject(func, args);
2449 Py_DECREF(args);
2450 }
2451 Py_DECREF(func);
2452 if (res == NULL)
2453 return -1;
2454 return PyObject_IsTrue(res);
2455 }
2456 else {
2457 PyErr_Clear();
2458 return _PySequence_IterContains(self, value);
2459 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002460}
2461
Guido van Rossumdc91b992001-08-08 22:26:22 +00002462SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2463SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002464
2465#define slot_mp_length slot_sq_length
2466
Guido van Rossumdc91b992001-08-08 22:26:22 +00002467SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002468
2469static int
2470slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2471{
2472 PyObject *res;
2473
2474 if (value == NULL)
2475 res = PyObject_CallMethod(self, "__delitem__", "O", key);
2476 else
2477 res = PyObject_CallMethod(self, "__setitem__",
2478 "OO", key, value);
2479 if (res == NULL)
2480 return -1;
2481 Py_DECREF(res);
2482 return 0;
2483}
2484
Guido van Rossumdc91b992001-08-08 22:26:22 +00002485SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2486SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2487SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2488SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2489SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2490SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2491
2492staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2493
2494SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2495 nb_power, "__pow__", "__rpow__")
2496
2497static PyObject *
2498slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2499{
2500 if (modulus == Py_None)
2501 return slot_nb_power_binary(self, other);
2502 /* Three-arg power doesn't use __rpow__ */
2503 return PyObject_CallMethod(self, "__pow__", "OO", other, modulus);
2504}
2505
2506SLOT0(slot_nb_negative, "__neg__")
2507SLOT0(slot_nb_positive, "__pos__")
2508SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002509
2510static int
2511slot_nb_nonzero(PyObject *self)
2512{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002513 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002514 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002515
Guido van Rossum60718732001-08-28 17:47:51 +00002516 func = lookup_method(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002517 if (func == NULL) {
2518 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002519 func = lookup_method(self, "__len__", &len_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002520 }
2521
2522 if (func != NULL) {
2523 res = PyEval_CallObject(func, NULL);
2524 Py_DECREF(func);
2525 if (res == NULL)
2526 return -1;
2527 return PyObject_IsTrue(res);
2528 }
2529 else {
2530 PyErr_Clear();
2531 return 1;
2532 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002533}
2534
Guido van Rossumdc91b992001-08-08 22:26:22 +00002535SLOT0(slot_nb_invert, "__invert__")
2536SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2537SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2538SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2539SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2540SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002541/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002542SLOT0(slot_nb_int, "__int__")
2543SLOT0(slot_nb_long, "__long__")
2544SLOT0(slot_nb_float, "__float__")
2545SLOT0(slot_nb_oct, "__oct__")
2546SLOT0(slot_nb_hex, "__hex__")
2547SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2548SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2549SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2550SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2551SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2552SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2553SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2554SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2555SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2556SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2557SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2558SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2559 "__floordiv__", "__rfloordiv__")
2560SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2561SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2562SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002563
2564static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002565half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002566{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002567 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002568 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002569 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002570
Guido van Rossum60718732001-08-28 17:47:51 +00002571 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002572 if (func == NULL) {
2573 PyErr_Clear();
2574 }
2575 else {
2576 args = Py_BuildValue("(O)", other);
2577 if (args == NULL)
2578 res = NULL;
2579 else {
2580 res = PyObject_CallObject(func, args);
2581 Py_DECREF(args);
2582 }
2583 if (res != Py_NotImplemented) {
2584 if (res == NULL)
2585 return -2;
2586 c = PyInt_AsLong(res);
2587 Py_DECREF(res);
2588 if (c == -1 && PyErr_Occurred())
2589 return -2;
2590 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2591 }
2592 Py_DECREF(res);
2593 }
2594 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002595}
2596
Guido van Rossumb8f63662001-08-15 23:57:02 +00002597static int
2598slot_tp_compare(PyObject *self, PyObject *other)
2599{
2600 int c;
2601
2602 if (self->ob_type->tp_compare == slot_tp_compare) {
2603 c = half_compare(self, other);
2604 if (c <= 1)
2605 return c;
2606 }
2607 if (other->ob_type->tp_compare == slot_tp_compare) {
2608 c = half_compare(other, self);
2609 if (c < -1)
2610 return -2;
2611 if (c <= 1)
2612 return -c;
2613 }
2614 return (void *)self < (void *)other ? -1 :
2615 (void *)self > (void *)other ? 1 : 0;
2616}
2617
2618static PyObject *
2619slot_tp_repr(PyObject *self)
2620{
2621 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002622 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002623
Guido van Rossum60718732001-08-28 17:47:51 +00002624 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002625 if (func != NULL) {
2626 res = PyEval_CallObject(func, NULL);
2627 Py_DECREF(func);
2628 return res;
2629 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00002630 PyErr_Clear();
2631 return PyString_FromFormat("<%s object at %p>",
2632 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002633}
2634
2635static PyObject *
2636slot_tp_str(PyObject *self)
2637{
2638 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002639 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002640
Guido van Rossum60718732001-08-28 17:47:51 +00002641 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002642 if (func != NULL) {
2643 res = PyEval_CallObject(func, NULL);
2644 Py_DECREF(func);
2645 return res;
2646 }
2647 else {
2648 PyErr_Clear();
2649 return slot_tp_repr(self);
2650 }
2651}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002652
2653static long
2654slot_tp_hash(PyObject *self)
2655{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002656 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002657 static PyObject *hash_str, *eq_str, *cmp_str;
2658
Tim Peters6d6c1a32001-08-02 04:15:00 +00002659 long h;
2660
Guido van Rossum60718732001-08-28 17:47:51 +00002661 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002662
2663 if (func != NULL) {
2664 res = PyEval_CallObject(func, NULL);
2665 Py_DECREF(func);
2666 if (res == NULL)
2667 return -1;
2668 h = PyInt_AsLong(res);
2669 }
2670 else {
2671 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002672 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002673 if (func == NULL) {
2674 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002675 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002676 }
2677 if (func != NULL) {
2678 Py_DECREF(func);
2679 PyErr_SetString(PyExc_TypeError, "unhashable type");
2680 return -1;
2681 }
2682 PyErr_Clear();
2683 h = _Py_HashPointer((void *)self);
2684 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002685 if (h == -1 && !PyErr_Occurred())
2686 h = -2;
2687 return h;
2688}
2689
2690static PyObject *
2691slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2692{
Guido van Rossum60718732001-08-28 17:47:51 +00002693 static PyObject *call_str;
2694 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002695 PyObject *res;
2696
2697 if (meth == NULL)
2698 return NULL;
2699 res = PyObject_Call(meth, args, kwds);
2700 Py_DECREF(meth);
2701 return res;
2702}
2703
Tim Peters6d6c1a32001-08-02 04:15:00 +00002704static PyObject *
2705slot_tp_getattro(PyObject *self, PyObject *name)
2706{
2707 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002708 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002709 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002710
Guido van Rossum8e248182001-08-12 05:17:56 +00002711 if (getattr_str == NULL) {
2712 getattr_str = PyString_InternFromString("__getattr__");
2713 if (getattr_str == NULL)
2714 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002715 }
Guido van Rossum8e248182001-08-12 05:17:56 +00002716 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00002717 if (getattr == NULL) {
2718 /* Avoid further slowdowns */
2719 if (tp->tp_getattro == slot_tp_getattro)
2720 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002721 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00002722 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723 return PyObject_CallFunction(getattr, "OO", self, name);
2724}
2725
2726static int
2727slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2728{
2729 PyObject *res;
2730
2731 if (value == NULL)
2732 res = PyObject_CallMethod(self, "__delattr__", "O", name);
2733 else
2734 res = PyObject_CallMethod(self, "__setattr__",
2735 "OO", name, value);
2736 if (res == NULL)
2737 return -1;
2738 Py_DECREF(res);
2739 return 0;
2740}
2741
2742/* Map rich comparison operators to their __xx__ namesakes */
2743static char *name_op[] = {
2744 "__lt__",
2745 "__le__",
2746 "__eq__",
2747 "__ne__",
2748 "__gt__",
2749 "__ge__",
2750};
2751
2752static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00002753half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002754{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002755 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002756 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757
Guido van Rossum60718732001-08-28 17:47:51 +00002758 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002759 if (func == NULL) {
2760 PyErr_Clear();
2761 Py_INCREF(Py_NotImplemented);
2762 return Py_NotImplemented;
2763 }
2764 args = Py_BuildValue("(O)", other);
2765 if (args == NULL)
2766 res = NULL;
2767 else {
2768 res = PyObject_CallObject(func, args);
2769 Py_DECREF(args);
2770 }
2771 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772 return res;
2773}
2774
Guido van Rossumb8f63662001-08-15 23:57:02 +00002775/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
2776static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
2777
2778static PyObject *
2779slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2780{
2781 PyObject *res;
2782
2783 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
2784 res = half_richcompare(self, other, op);
2785 if (res != Py_NotImplemented)
2786 return res;
2787 Py_DECREF(res);
2788 }
2789 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
2790 res = half_richcompare(other, self, swapped_op[op]);
2791 if (res != Py_NotImplemented) {
2792 return res;
2793 }
2794 Py_DECREF(res);
2795 }
2796 Py_INCREF(Py_NotImplemented);
2797 return Py_NotImplemented;
2798}
2799
2800static PyObject *
2801slot_tp_iter(PyObject *self)
2802{
2803 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002804 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002805
Guido van Rossum60718732001-08-28 17:47:51 +00002806 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002807 if (func != NULL) {
2808 res = PyObject_CallObject(func, NULL);
2809 Py_DECREF(func);
2810 return res;
2811 }
2812 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002813 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002814 if (func == NULL) {
2815 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
2816 return NULL;
2817 }
2818 Py_DECREF(func);
2819 return PySeqIter_New(self);
2820}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002821
2822static PyObject *
2823slot_tp_iternext(PyObject *self)
2824{
2825 return PyObject_CallMethod(self, "next", "");
2826}
2827
Guido van Rossum1a493502001-08-17 16:47:50 +00002828static PyObject *
2829slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
2830{
2831 PyTypeObject *tp = self->ob_type;
2832 PyObject *get;
2833 static PyObject *get_str = NULL;
2834
2835 if (get_str == NULL) {
2836 get_str = PyString_InternFromString("__get__");
2837 if (get_str == NULL)
2838 return NULL;
2839 }
2840 get = _PyType_Lookup(tp, get_str);
2841 if (get == NULL) {
2842 /* Avoid further slowdowns */
2843 if (tp->tp_descr_get == slot_tp_descr_get)
2844 tp->tp_descr_get = NULL;
2845 Py_INCREF(self);
2846 return self;
2847 }
Guido van Rossum2c252392001-08-24 10:13:31 +00002848 if (obj == NULL)
2849 obj = Py_None;
2850 if (type == NULL)
2851 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00002852 return PyObject_CallFunction(get, "OOO", self, obj, type);
2853}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002854
2855static int
2856slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2857{
Guido van Rossum2c252392001-08-24 10:13:31 +00002858 PyObject *res;
2859
2860 if (value == NULL)
2861 res = PyObject_CallMethod(self, "__del__", "O", target);
2862 else
2863 res = PyObject_CallMethod(self, "__set__",
2864 "OO", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002865 if (res == NULL)
2866 return -1;
2867 Py_DECREF(res);
2868 return 0;
2869}
2870
2871static int
2872slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2873{
Guido van Rossum60718732001-08-28 17:47:51 +00002874 static PyObject *init_str;
2875 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002876 PyObject *res;
2877
2878 if (meth == NULL)
2879 return -1;
2880 res = PyObject_Call(meth, args, kwds);
2881 Py_DECREF(meth);
2882 if (res == NULL)
2883 return -1;
2884 Py_DECREF(res);
2885 return 0;
2886}
2887
2888static PyObject *
2889slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2890{
2891 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
2892 PyObject *newargs, *x;
2893 int i, n;
2894
2895 if (func == NULL)
2896 return NULL;
2897 assert(PyTuple_Check(args));
2898 n = PyTuple_GET_SIZE(args);
2899 newargs = PyTuple_New(n+1);
2900 if (newargs == NULL)
2901 return NULL;
2902 Py_INCREF(type);
2903 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
2904 for (i = 0; i < n; i++) {
2905 x = PyTuple_GET_ITEM(args, i);
2906 Py_INCREF(x);
2907 PyTuple_SET_ITEM(newargs, i+1, x);
2908 }
2909 x = PyObject_Call(func, newargs, kwds);
2910 Py_DECREF(func);
2911 return x;
2912}
2913
Guido van Rossumf040ede2001-08-07 16:40:56 +00002914/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002915 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00002916 The dict argument is the dictionary argument passed to type_new(),
2917 which is the local namespace of the class statement, in other
2918 words, it contains the methods. For each special method (like
2919 __repr__) defined in the dictionary, the corresponding function
2920 slot in the type object (like tp_repr) is set to a special function
2921 whose name is 'slot_' followed by the slot name and whose signature
2922 is whatever is required for that slot. These slot functions look
2923 up the corresponding method in the type's dictionary and call it.
2924 The slot functions have to take care of the various peculiarities
2925 of the mapping between slots and special methods, such as mapping
2926 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
2927 etc.) or mapping multiple slots to a single method (sq_item,
2928 mp_subscript <--> __getitem__). */
2929
Tim Peters6d6c1a32001-08-02 04:15:00 +00002930static void
2931override_slots(PyTypeObject *type, PyObject *dict)
2932{
2933 PySequenceMethods *sq = type->tp_as_sequence;
2934 PyMappingMethods *mp = type->tp_as_mapping;
2935 PyNumberMethods *nb = type->tp_as_number;
2936
Guido van Rossumdc91b992001-08-08 22:26:22 +00002937#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00002938 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002939 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002940 }
2941
Guido van Rossumdc91b992001-08-08 22:26:22 +00002942#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00002943 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002944 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002945 }
2946
Guido van Rossumdc91b992001-08-08 22:26:22 +00002947#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00002948 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002949 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002950 }
2951
Guido van Rossumdc91b992001-08-08 22:26:22 +00002952#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00002953 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002954 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002955 }
2956
Guido van Rossumdc91b992001-08-08 22:26:22 +00002957 SQSLOT("__len__", sq_length, slot_sq_length);
2958 SQSLOT("__add__", sq_concat, slot_sq_concat);
2959 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
2960 SQSLOT("__getitem__", sq_item, slot_sq_item);
2961 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
2962 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
2963 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
2964 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
2965 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
2966 SQSLOT("__contains__", sq_contains, slot_sq_contains);
2967 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
2968 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002969
Guido van Rossumdc91b992001-08-08 22:26:22 +00002970 MPSLOT("__len__", mp_length, slot_mp_length);
2971 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
2972 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
2973 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974
Guido van Rossumdc91b992001-08-08 22:26:22 +00002975 NBSLOT("__add__", nb_add, slot_nb_add);
2976 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
2977 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
2978 NBSLOT("__div__", nb_divide, slot_nb_divide);
2979 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
2980 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
2981 NBSLOT("__pow__", nb_power, slot_nb_power);
2982 NBSLOT("__neg__", nb_negative, slot_nb_negative);
2983 NBSLOT("__pos__", nb_positive, slot_nb_positive);
2984 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
2985 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
2986 NBSLOT("__invert__", nb_invert, slot_nb_invert);
2987 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
2988 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
2989 NBSLOT("__and__", nb_and, slot_nb_and);
2990 NBSLOT("__xor__", nb_xor, slot_nb_xor);
2991 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002992 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002993 NBSLOT("__int__", nb_int, slot_nb_int);
2994 NBSLOT("__long__", nb_long, slot_nb_long);
2995 NBSLOT("__float__", nb_float, slot_nb_float);
2996 NBSLOT("__oct__", nb_oct, slot_nb_oct);
2997 NBSLOT("__hex__", nb_hex, slot_nb_hex);
2998 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
2999 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3000 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3001 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3002 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3003 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3004 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3005 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3006 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3007 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3008 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3009 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3010 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3011 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3012 slot_nb_inplace_floor_divide);
3013 NBSLOT("__itruediv__", nb_inplace_true_divide,
3014 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015
Guido van Rossum8e248182001-08-12 05:17:56 +00003016 if (dict == NULL ||
3017 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003018 PyDict_GetItemString(dict, "__repr__"))
3019 type->tp_print = NULL;
3020
Guido van Rossumdc91b992001-08-08 22:26:22 +00003021 TPSLOT("__cmp__", tp_compare, slot_tp_compare);
3022 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3023 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3024 TPSLOT("__call__", tp_call, slot_tp_call);
3025 TPSLOT("__str__", tp_str, slot_tp_str);
3026 TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
3027 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3028 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3029 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3030 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3031 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3032 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3033 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3034 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3035 TPSLOT("next", tp_iternext, slot_tp_iternext);
3036 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3037 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3038 TPSLOT("__init__", tp_init, slot_tp_init);
3039 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003041
3042
3043/* Cooperative 'super' */
3044
3045typedef struct {
3046 PyObject_HEAD
3047 PyObject *type;
3048 PyObject *obj;
3049} superobject;
3050
3051static void
3052super_dealloc(PyObject *self)
3053{
3054 superobject *su = (superobject *)self;
3055
3056 Py_XDECREF(su->obj);
3057 Py_XDECREF(su->type);
3058 self->ob_type->tp_free(self);
3059}
3060
3061static PyObject *
3062super_getattro(PyObject *self, PyObject *name)
3063{
3064 superobject *su = (superobject *)self;
3065
3066 if (su->obj != NULL) {
3067 PyObject *mro, *res, *tmp;
3068 descrgetfunc f;
3069 int i, n;
3070
3071 mro = ((PyTypeObject *)(su->obj->ob_type))->tp_mro;
3072 assert(mro != NULL && PyTuple_Check(mro));
3073 n = PyTuple_GET_SIZE(mro);
3074 for (i = 0; i < n; i++) {
3075 if (su->type == PyTuple_GET_ITEM(mro, i))
3076 break;
3077 }
3078 assert(i < n);
3079 i++;
3080 res = NULL;
3081 for (; i < n; i++) {
3082 tmp = PyTuple_GET_ITEM(mro, i);
3083 assert(PyType_Check(tmp));
3084 res = PyDict_GetItem(
3085 ((PyTypeObject *)tmp)->tp_defined, name);
3086 if (res != NULL) {
3087 Py_INCREF(res);
3088 f = res->ob_type->tp_descr_get;
3089 if (f != NULL) {
3090 tmp = f(res, su->obj, res);
3091 Py_DECREF(res);
3092 res = tmp;
3093 }
3094 return res;
3095 }
3096 }
3097 }
3098 return PyObject_GenericGetAttr(self, name);
3099}
3100
3101static PyObject *
3102super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3103{
3104 superobject *su = (superobject *)self;
3105 superobject *new;
3106
3107 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3108 /* Not binding to an object, or already bound */
3109 Py_INCREF(self);
3110 return self;
3111 }
3112 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3113 if (new == NULL)
3114 return NULL;
3115 Py_INCREF(su->type);
3116 Py_INCREF(obj);
3117 new->type = su->type;
3118 new->obj = obj;
3119 return (PyObject *)new;
3120}
3121
3122static int
3123super_init(PyObject *self, PyObject *args, PyObject *kwds)
3124{
3125 superobject *su = (superobject *)self;
3126 PyObject *type, *obj = NULL;
3127
3128 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3129 return -1;
3130 if (obj == Py_None)
3131 obj = NULL;
3132 if (obj != NULL && !PyType_IsSubtype(obj->ob_type,
3133 (PyTypeObject *)type)) {
3134 PyErr_SetString(PyExc_TypeError,
3135 "super(type, obj) requires isinstance(obj, type)");
3136 return -1;
3137 }
3138 Py_INCREF(type);
3139 Py_XINCREF(obj);
3140 su->type = type;
3141 su->obj = obj;
3142 return 0;
3143}
3144
3145static char super_doc[] =
3146"super(type) -> unbound super object\n"
3147"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
3148"Typical use to call a cooperative superclass method:\n"
3149"class C(B):\n"
3150" def meth(self, arg):\n"
3151" super(C, self).meth(arg)";
3152
3153PyTypeObject PySuper_Type = {
3154 PyObject_HEAD_INIT(&PyType_Type)
3155 0, /* ob_size */
3156 "super", /* tp_name */
3157 sizeof(superobject), /* tp_basicsize */
3158 0, /* tp_itemsize */
3159 /* methods */
3160 super_dealloc, /* tp_dealloc */
3161 0, /* tp_print */
3162 0, /* tp_getattr */
3163 0, /* tp_setattr */
3164 0, /* tp_compare */
3165 0, /* tp_repr */
3166 0, /* tp_as_number */
3167 0, /* tp_as_sequence */
3168 0, /* tp_as_mapping */
3169 0, /* tp_hash */
3170 0, /* tp_call */
3171 0, /* tp_str */
3172 super_getattro, /* tp_getattro */
3173 0, /* tp_setattro */
3174 0, /* tp_as_buffer */
3175 Py_TPFLAGS_DEFAULT, /* tp_flags */
3176 super_doc, /* tp_doc */
3177 0, /* tp_traverse */
3178 0, /* tp_clear */
3179 0, /* tp_richcompare */
3180 0, /* tp_weaklistoffset */
3181 0, /* tp_iter */
3182 0, /* tp_iternext */
3183 0, /* tp_methods */
3184 0, /* tp_members */
3185 0, /* tp_getset */
3186 0, /* tp_base */
3187 0, /* tp_dict */
3188 super_descr_get, /* tp_descr_get */
3189 0, /* tp_descr_set */
3190 0, /* tp_dictoffset */
3191 super_init, /* tp_init */
3192 PyType_GenericAlloc, /* tp_alloc */
3193 PyType_GenericNew, /* tp_new */
3194 _PyObject_Del, /* tp_free */
3195};