blob: 5cc4161dea228d664e78cc971b4553ad765e7f1a [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
292/* Method resolution order algorithm from "Putting Metaclasses to Work"
293 by Forman and Danforth (Addison-Wesley 1999). */
294
295static int
296conservative_merge(PyObject *left, PyObject *right)
297{
298 int left_size;
299 int right_size;
300 int i, j, r, ok;
301 PyObject *temp, *rr;
302
303 assert(PyList_Check(left));
304 assert(PyList_Check(right));
305
306 again:
307 left_size = PyList_GET_SIZE(left);
308 right_size = PyList_GET_SIZE(right);
309 for (i = 0; i < left_size; i++) {
310 for (j = 0; j < right_size; j++) {
311 if (PyList_GET_ITEM(left, i) ==
312 PyList_GET_ITEM(right, j)) {
313 /* found a merge point */
314 temp = PyList_New(0);
315 if (temp == NULL)
316 return -1;
317 for (r = 0; r < j; r++) {
318 rr = PyList_GET_ITEM(right, r);
319 ok = PySequence_Contains(left, rr);
320 if (ok < 0) {
321 Py_DECREF(temp);
322 return -1;
323 }
324 if (!ok) {
325 ok = PyList_Append(temp, rr);
326 if (ok < 0) {
327 Py_DECREF(temp);
328 return -1;
329 }
330 }
331 }
332 ok = PyList_SetSlice(left, i, i, temp);
333 Py_DECREF(temp);
334 if (ok < 0)
335 return -1;
336 ok = PyList_SetSlice(right, 0, j+1, NULL);
337 if (ok < 0)
338 return -1;
339 goto again;
340 }
341 }
342 }
343 return PyList_SetSlice(left, left_size, left_size, right);
344}
345
346static int
347serious_order_disagreements(PyObject *left, PyObject *right)
348{
349 return 0; /* XXX later -- for now, we cheat: "don't do that" */
350}
351
352static PyObject *
353mro_implementation(PyTypeObject *type)
354{
355 int i, n, ok;
356 PyObject *bases, *result;
357
358 bases = type->tp_bases;
359 n = PyTuple_GET_SIZE(bases);
360 result = Py_BuildValue("[O]", (PyObject *)type);
361 if (result == NULL)
362 return NULL;
363 for (i = 0; i < n; i++) {
364 PyTypeObject *base =
365 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
366 PyObject *parentMRO = PySequence_List(base->tp_mro);
367 if (parentMRO == NULL) {
368 Py_DECREF(result);
369 return NULL;
370 }
371 if (serious_order_disagreements(result, parentMRO)) {
372 Py_DECREF(result);
373 return NULL;
374 }
375 ok = conservative_merge(result, parentMRO);
376 Py_DECREF(parentMRO);
377 if (ok < 0) {
378 Py_DECREF(result);
379 return NULL;
380 }
381 }
382 return result;
383}
384
385static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000386mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000387{
388 PyTypeObject *type = (PyTypeObject *)self;
389
Tim Peters6d6c1a32001-08-02 04:15:00 +0000390 return mro_implementation(type);
391}
392
393static int
394mro_internal(PyTypeObject *type)
395{
396 PyObject *mro, *result, *tuple;
397
398 if (type->ob_type == &PyType_Type) {
399 result = mro_implementation(type);
400 }
401 else {
402 mro = PyObject_GetAttrString((PyObject *)type, "mro");
403 if (mro == NULL)
404 return -1;
405 result = PyObject_CallObject(mro, NULL);
406 Py_DECREF(mro);
407 }
408 if (result == NULL)
409 return -1;
410 tuple = PySequence_Tuple(result);
411 Py_DECREF(result);
412 type->tp_mro = tuple;
413 return 0;
414}
415
416
417/* Calculate the best base amongst multiple base classes.
418 This is the first one that's on the path to the "solid base". */
419
420static PyTypeObject *
421best_base(PyObject *bases)
422{
423 int i, n;
424 PyTypeObject *base, *winner, *candidate, *base_i;
425
426 assert(PyTuple_Check(bases));
427 n = PyTuple_GET_SIZE(bases);
428 assert(n > 0);
429 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
430 winner = &PyBaseObject_Type;
431 for (i = 0; i < n; i++) {
432 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
433 if (!PyType_Check((PyObject *)base_i)) {
434 PyErr_SetString(
435 PyExc_TypeError,
436 "bases must be types");
437 return NULL;
438 }
439 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000440 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000441 return NULL;
442 }
443 candidate = solid_base(base_i);
444 if (PyType_IsSubtype(winner, candidate))
445 ;
446 else if (PyType_IsSubtype(candidate, winner)) {
447 winner = candidate;
448 base = base_i;
449 }
450 else {
451 PyErr_SetString(
452 PyExc_TypeError,
453 "multiple bases have "
454 "instance lay-out conflict");
455 return NULL;
456 }
457 }
458 assert(base != NULL);
459 return base;
460}
461
462static int
463extra_ivars(PyTypeObject *type, PyTypeObject *base)
464{
Guido van Rossum9676b222001-08-17 20:32:36 +0000465 size_t t_size = PyType_BASICSIZE(type);
466 size_t b_size = PyType_BASICSIZE(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000467
Guido van Rossum9676b222001-08-17 20:32:36 +0000468 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000469 if (type->tp_itemsize || base->tp_itemsize) {
470 /* If itemsize is involved, stricter rules */
471 return t_size != b_size ||
472 type->tp_itemsize != base->tp_itemsize;
473 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000474 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
475 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
476 t_size -= sizeof(PyObject *);
477 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
478 type->tp_dictoffset + sizeof(PyObject *) == t_size)
479 t_size -= sizeof(PyObject *);
480
481 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000482}
483
484static PyTypeObject *
485solid_base(PyTypeObject *type)
486{
487 PyTypeObject *base;
488
489 if (type->tp_base)
490 base = solid_base(type->tp_base);
491 else
492 base = &PyBaseObject_Type;
493 if (extra_ivars(type, base))
494 return type;
495 else
496 return base;
497}
498
499staticforward void object_dealloc(PyObject *);
500staticforward int object_init(PyObject *, PyObject *, PyObject *);
501
502static PyObject *
503type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
504{
505 PyObject *name, *bases, *dict;
506 static char *kwlist[] = {"name", "bases", "dict", 0};
507 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000508 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000509 etype *et;
510 struct memberlist *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000511 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000512
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000513 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000514 if (metatype == &PyType_Type &&
515 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
516 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000517 PyObject *x = PyTuple_GET_ITEM(args, 0);
518 Py_INCREF(x->ob_type);
519 return (PyObject *) x->ob_type;
520 }
521
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000522 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000523 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
524 &name,
525 &PyTuple_Type, &bases,
526 &PyDict_Type, &dict))
527 return NULL;
528
529 /* Determine the proper metatype to deal with this,
530 and check for metatype conflicts while we're at it.
531 Note that if some other metatype wins to contract,
532 it's possible that its instances are not types. */
533 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000534 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000535 for (i = 0; i < nbases; i++) {
536 tmp = PyTuple_GET_ITEM(bases, i);
537 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000538 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000539 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000540 if (PyType_IsSubtype(tmptype, winner)) {
541 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000542 continue;
543 }
544 PyErr_SetString(PyExc_TypeError,
545 "metatype conflict among bases");
546 return NULL;
547 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000548 if (winner != metatype) {
549 if (winner->tp_new != type_new) /* Pass it to the winner */
550 return winner->tp_new(winner, args, kwds);
551 metatype = winner;
552 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000553
554 /* Adjust for empty tuple bases */
555 if (nbases == 0) {
556 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
557 if (bases == NULL)
558 return NULL;
559 nbases = 1;
560 }
561 else
562 Py_INCREF(bases);
563
564 /* XXX From here until type is allocated, "return NULL" leaks bases! */
565
566 /* Calculate best base, and check that all bases are type objects */
567 base = best_base(bases);
568 if (base == NULL)
569 return NULL;
570 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
571 PyErr_Format(PyExc_TypeError,
572 "type '%.100s' is not an acceptable base type",
573 base->tp_name);
574 return NULL;
575 }
576
Guido van Rossum1a493502001-08-17 16:47:50 +0000577 /* Should this be a dynamic class (i.e. modifiable __dict__)?
578 Look in two places for a variable named __dynamic__:
579 1) in the class dict
580 2) in the module dict (globals)
581 The first variable that is an int >= 0 is used.
582 Otherwise, a default is calculated from the base classes:
583 if any base class is dynamic, this class is dynamic; otherwise
584 it is static. */
585 dynamic = -1; /* Not yet determined */
586 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587 tmp = PyDict_GetItemString(dict, "__dynamic__");
588 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000589 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000590 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000591 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000592 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000593 if (dynamic < 0) {
594 /* Look in the module globals */
595 tmp = PyEval_GetGlobals();
596 if (tmp != NULL) {
597 tmp = PyDict_GetItemString(tmp, "__dynamic__");
598 if (tmp != NULL) {
599 dynamic = PyInt_AsLong(tmp);
600 if (dynamic < 0)
601 PyErr_Clear();
602 }
603 }
604 }
605 if (dynamic < 0) {
606 /* Make a new class dynamic if any of its bases is
607 dynamic. This is not always the same as inheriting
608 the __dynamic__ class attribute! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000609 dynamic = 0;
610 for (i = 0; i < nbases; i++) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000611 tmptype = (PyTypeObject *)
612 PyTuple_GET_ITEM(bases, i);
613 if (tmptype->tp_flags &
614 Py_TPFLAGS_DYNAMICTYPE) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000615 dynamic = 1;
616 break;
617 }
618 }
619 }
620
621 /* Check for a __slots__ sequence variable in dict, and count it */
622 slots = PyDict_GetItemString(dict, "__slots__");
623 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000624 add_dict = 0;
625 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000626 if (slots != NULL) {
627 /* Make it into a tuple */
628 if (PyString_Check(slots))
629 slots = Py_BuildValue("(O)", slots);
630 else
631 slots = PySequence_Tuple(slots);
632 if (slots == NULL)
633 return NULL;
634 nslots = PyTuple_GET_SIZE(slots);
635 for (i = 0; i < nslots; i++) {
636 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
637 PyErr_SetString(PyExc_TypeError,
638 "__slots__ must be a sequence of strings");
639 Py_DECREF(slots);
640 return NULL;
641 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000642 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000643 }
644 }
645 if (slots == NULL && base->tp_dictoffset == 0 &&
646 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000647 base->tp_setattro == NULL)) {
648 nslots++;
649 add_dict++;
650 }
651 if (slots == NULL && base->tp_weaklistoffset == 0) {
652 nslots++;
653 add_weak++;
654 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000655
656 /* XXX From here until type is safely allocated,
657 "return NULL" may leak slots! */
658
659 /* Allocate the type object */
660 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
661 if (type == NULL)
662 return NULL;
663
664 /* Keep name and slots alive in the extended type object */
665 et = (etype *)type;
666 Py_INCREF(name);
667 et->name = name;
668 et->slots = slots;
669
Guido van Rossumdc91b992001-08-08 22:26:22 +0000670 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000671 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
672 Py_TPFLAGS_BASETYPE;
673 if (dynamic)
674 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000675
676 /* It's a new-style number unless it specifically inherits any
677 old-style numeric behavior */
678 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
679 (base->tp_as_number == NULL))
680 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
681
682 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000683 type->tp_as_number = &et->as_number;
684 type->tp_as_sequence = &et->as_sequence;
685 type->tp_as_mapping = &et->as_mapping;
686 type->tp_as_buffer = &et->as_buffer;
687 type->tp_name = PyString_AS_STRING(name);
688
689 /* Set tp_base and tp_bases */
690 type->tp_bases = bases;
691 Py_INCREF(base);
692 type->tp_base = base;
693
694 /* Initialize tp_defined from passed-in dict */
695 type->tp_defined = dict = PyDict_Copy(dict);
696 if (dict == NULL) {
697 Py_DECREF(type);
698 return NULL;
699 }
700
Guido van Rossumc3542212001-08-16 09:18:56 +0000701 /* Set __module__ in the dict */
702 if (PyDict_GetItemString(dict, "__module__") == NULL) {
703 tmp = PyEval_GetGlobals();
704 if (tmp != NULL) {
705 tmp = PyDict_GetItemString(tmp, "__name__");
706 if (tmp != NULL) {
707 if (PyDict_SetItemString(dict, "__module__",
708 tmp) < 0)
709 return NULL;
710 }
711 }
712 }
713
Tim Peters6d6c1a32001-08-02 04:15:00 +0000714 /* Special-case __new__: if it's a plain function,
715 make it a static function */
716 tmp = PyDict_GetItemString(dict, "__new__");
717 if (tmp != NULL && PyFunction_Check(tmp)) {
718 tmp = PyStaticMethod_New(tmp);
719 if (tmp == NULL) {
720 Py_DECREF(type);
721 return NULL;
722 }
723 PyDict_SetItemString(dict, "__new__", tmp);
724 Py_DECREF(tmp);
725 }
726
727 /* Add descriptors for custom slots from __slots__, or for __dict__ */
728 mp = et->members;
729 slotoffset = PyType_BASICSIZE(base);
730 if (slots != NULL) {
731 for (i = 0; i < nslots; i++, mp++) {
732 mp->name = PyString_AS_STRING(
733 PyTuple_GET_ITEM(slots, i));
734 mp->type = T_OBJECT;
735 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000736 if (base->tp_weaklistoffset == 0 &&
737 strcmp(mp->name, "__weakref__") == 0)
738 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000739 slotoffset += sizeof(PyObject *);
740 }
741 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000742 else {
743 if (add_dict) {
744 type->tp_dictoffset = slotoffset;
745 mp->name = "__dict__";
746 mp->type = T_OBJECT;
747 mp->offset = slotoffset;
748 mp->readonly = 1;
749 mp++;
750 slotoffset += sizeof(PyObject *);
751 }
752 if (add_weak) {
753 type->tp_weaklistoffset = slotoffset;
754 mp->name = "__weakref__";
755 mp->type = T_OBJECT;
756 mp->offset = slotoffset;
757 mp->readonly = 1;
758 mp++;
759 slotoffset += sizeof(PyObject *);
760 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000761 }
762 type->tp_basicsize = slotoffset;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000763 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000764
765 /* Special case some slots */
766 if (type->tp_dictoffset != 0 || nslots > 0) {
767 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
768 type->tp_getattro = PyObject_GenericGetAttr;
769 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
770 type->tp_setattro = PyObject_GenericSetAttr;
771 }
772 type->tp_dealloc = subtype_dealloc;
773
774 /* Always override allocation strategy to use regular heap */
775 type->tp_alloc = PyType_GenericAlloc;
776 type->tp_free = _PyObject_Del;
777
778 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000779 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000780 Py_DECREF(type);
781 return NULL;
782 }
783
784 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +0000785 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
786 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +0000787
Tim Peters6d6c1a32001-08-02 04:15:00 +0000788 return (PyObject *)type;
789}
790
791/* Internal API to look for a name through the MRO.
792 This returns a borrowed reference, and doesn't set an exception! */
793PyObject *
794_PyType_Lookup(PyTypeObject *type, PyObject *name)
795{
796 int i, n;
797 PyObject *mro, *res, *dict;
798
799 /* For static types, look in tp_dict */
800 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
801 dict = type->tp_dict;
802 assert(dict && PyDict_Check(dict));
803 return PyDict_GetItem(dict, name);
804 }
805
806 /* For dynamic types, look in tp_defined of types in MRO */
807 mro = type->tp_mro;
808 assert(PyTuple_Check(mro));
809 n = PyTuple_GET_SIZE(mro);
810 for (i = 0; i < n; i++) {
811 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
812 assert(PyType_Check(type));
813 dict = type->tp_defined;
814 assert(dict && PyDict_Check(dict));
815 res = PyDict_GetItem(dict, name);
816 if (res != NULL)
817 return res;
818 }
819 return NULL;
820}
821
822/* This is similar to PyObject_GenericGetAttr(),
823 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
824static PyObject *
825type_getattro(PyTypeObject *type, PyObject *name)
826{
827 PyTypeObject *metatype = type->ob_type;
828 PyObject *descr, *res;
829 descrgetfunc f;
830
831 /* Initialize this type (we'll assume the metatype is initialized) */
832 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000833 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834 return NULL;
835 }
836
837 /* Get a descriptor from the metatype */
838 descr = _PyType_Lookup(metatype, name);
839 f = NULL;
840 if (descr != NULL) {
841 f = descr->ob_type->tp_descr_get;
842 if (f != NULL && PyDescr_IsData(descr))
843 return f(descr,
844 (PyObject *)type, (PyObject *)metatype);
845 }
846
847 /* Look in tp_defined of this type and its bases */
848 res = _PyType_Lookup(type, name);
849 if (res != NULL) {
850 f = res->ob_type->tp_descr_get;
851 if (f != NULL)
852 return f(res, (PyObject *)NULL, (PyObject *)type);
853 Py_INCREF(res);
854 return res;
855 }
856
857 /* Use the descriptor from the metatype */
858 if (f != NULL) {
859 res = f(descr, (PyObject *)type, (PyObject *)metatype);
860 return res;
861 }
862 if (descr != NULL) {
863 Py_INCREF(descr);
864 return descr;
865 }
866
867 /* Give up */
868 PyErr_Format(PyExc_AttributeError,
869 "type object '%.50s' has no attribute '%.400s'",
870 type->tp_name, PyString_AS_STRING(name));
871 return NULL;
872}
873
874static int
875type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
876{
877 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
878 return PyObject_GenericSetAttr((PyObject *)type, name, value);
879 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
880 return -1;
881}
882
883static void
884type_dealloc(PyTypeObject *type)
885{
886 etype *et;
887
888 /* Assert this is a heap-allocated type object */
889 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
890 et = (etype *)type;
891 Py_XDECREF(type->tp_base);
892 Py_XDECREF(type->tp_dict);
893 Py_XDECREF(type->tp_bases);
894 Py_XDECREF(type->tp_mro);
895 Py_XDECREF(type->tp_defined);
896 /* XXX more? */
897 Py_XDECREF(et->name);
898 Py_XDECREF(et->slots);
899 type->ob_type->tp_free((PyObject *)type);
900}
901
902static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000903 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000904 "mro() -> list\nreturn a type's method resolution order"},
905 {0}
906};
907
908static char type_doc[] =
909"type(object) -> the object's type\n"
910"type(name, bases, dict) -> a new type";
911
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000912PyTypeObject PyType_Type = {
913 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000914 0, /* ob_size */
915 "type", /* tp_name */
916 sizeof(etype), /* tp_basicsize */
917 sizeof(struct memberlist), /* tp_itemsize */
918 (destructor)type_dealloc, /* tp_dealloc */
919 0, /* tp_print */
920 0, /* tp_getattr */
921 0, /* tp_setattr */
922 type_compare, /* tp_compare */
923 (reprfunc)type_repr, /* tp_repr */
924 0, /* tp_as_number */
925 0, /* tp_as_sequence */
926 0, /* tp_as_mapping */
927 (hashfunc)_Py_HashPointer, /* tp_hash */
928 (ternaryfunc)type_call, /* tp_call */
929 0, /* tp_str */
930 (getattrofunc)type_getattro, /* tp_getattro */
931 (setattrofunc)type_setattro, /* tp_setattro */
932 0, /* tp_as_buffer */
933 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
934 type_doc, /* tp_doc */
935 0, /* tp_traverse */
936 0, /* tp_clear */
937 0, /* tp_richcompare */
938 0, /* tp_weaklistoffset */
939 0, /* tp_iter */
940 0, /* tp_iternext */
941 type_methods, /* tp_methods */
942 type_members, /* tp_members */
943 type_getsets, /* tp_getset */
944 0, /* tp_base */
945 0, /* tp_dict */
946 0, /* tp_descr_get */
947 0, /* tp_descr_set */
948 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
949 0, /* tp_init */
950 0, /* tp_alloc */
951 type_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000952};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000953
954
955/* The base type of all types (eventually)... except itself. */
956
957static int
958object_init(PyObject *self, PyObject *args, PyObject *kwds)
959{
960 return 0;
961}
962
963static void
964object_dealloc(PyObject *self)
965{
966 self->ob_type->tp_free(self);
967}
968
Guido van Rossum8e248182001-08-12 05:17:56 +0000969static PyObject *
970object_repr(PyObject *self)
971{
Guido van Rossum76e69632001-08-16 18:52:43 +0000972 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000973 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +0000974
Guido van Rossum76e69632001-08-16 18:52:43 +0000975 type = self->ob_type;
976 mod = type_module(type, NULL);
977 if (mod == NULL)
978 PyErr_Clear();
979 else if (!PyString_Check(mod)) {
980 Py_DECREF(mod);
981 mod = NULL;
982 }
983 name = type_name(type, NULL);
984 if (name == NULL)
985 return NULL;
986 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Barry Warsaw7ce36942001-08-24 18:34:26 +0000987 rtn = PyString_FromFormat("<%s.%s instance at %p>",
988 PyString_AS_STRING(mod),
989 PyString_AS_STRING(name),
990 self);
Guido van Rossum76e69632001-08-16 18:52:43 +0000991 else
Barry Warsaw7ce36942001-08-24 18:34:26 +0000992 rtn = PyString_FromFormat("<%s instance at %p>",
993 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +0000994 Py_XDECREF(mod);
995 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000996 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +0000997}
998
Guido van Rossumb8f63662001-08-15 23:57:02 +0000999static PyObject *
1000object_str(PyObject *self)
1001{
1002 unaryfunc f;
1003
1004 f = self->ob_type->tp_repr;
1005 if (f == NULL)
1006 f = object_repr;
1007 return f(self);
1008}
1009
Guido van Rossum8e248182001-08-12 05:17:56 +00001010static long
1011object_hash(PyObject *self)
1012{
1013 return _Py_HashPointer(self);
1014}
Guido van Rossum8e248182001-08-12 05:17:56 +00001015
Tim Peters6d6c1a32001-08-02 04:15:00 +00001016static void
1017object_free(PyObject *self)
1018{
1019 PyObject_Del(self);
1020}
1021
1022static struct memberlist object_members[] = {
1023 {"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
1024 {0}
1025};
1026
1027PyTypeObject PyBaseObject_Type = {
1028 PyObject_HEAD_INIT(&PyType_Type)
1029 0, /* ob_size */
1030 "object", /* tp_name */
1031 sizeof(PyObject), /* tp_basicsize */
1032 0, /* tp_itemsize */
1033 (destructor)object_dealloc, /* tp_dealloc */
1034 0, /* tp_print */
1035 0, /* tp_getattr */
1036 0, /* tp_setattr */
1037 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001038 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039 0, /* tp_as_number */
1040 0, /* tp_as_sequence */
1041 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001042 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001043 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001044 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001045 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001046 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047 0, /* tp_as_buffer */
1048 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1049 "The most base type", /* tp_doc */
1050 0, /* tp_traverse */
1051 0, /* tp_clear */
1052 0, /* tp_richcompare */
1053 0, /* tp_weaklistoffset */
1054 0, /* tp_iter */
1055 0, /* tp_iternext */
1056 0, /* tp_methods */
1057 object_members, /* tp_members */
1058 0, /* tp_getset */
1059 0, /* tp_base */
1060 0, /* tp_dict */
1061 0, /* tp_descr_get */
1062 0, /* tp_descr_set */
1063 0, /* tp_dictoffset */
1064 object_init, /* tp_init */
1065 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001066 PyType_GenericNew, /* tp_new */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001067 object_free, /* tp_free */
1068};
1069
1070
1071/* Initialize the __dict__ in a type object */
1072
1073static int
1074add_methods(PyTypeObject *type, PyMethodDef *meth)
1075{
1076 PyObject *dict = type->tp_defined;
1077
1078 for (; meth->ml_name != NULL; meth++) {
1079 PyObject *descr;
1080 if (PyDict_GetItemString(dict, meth->ml_name))
1081 continue;
1082 descr = PyDescr_NewMethod(type, meth);
1083 if (descr == NULL)
1084 return -1;
1085 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1086 return -1;
1087 Py_DECREF(descr);
1088 }
1089 return 0;
1090}
1091
1092static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093add_members(PyTypeObject *type, struct memberlist *memb)
1094{
1095 PyObject *dict = type->tp_defined;
1096
1097 for (; memb->name != NULL; memb++) {
1098 PyObject *descr;
1099 if (PyDict_GetItemString(dict, memb->name))
1100 continue;
1101 descr = PyDescr_NewMember(type, memb);
1102 if (descr == NULL)
1103 return -1;
1104 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1105 return -1;
1106 Py_DECREF(descr);
1107 }
1108 return 0;
1109}
1110
1111static int
1112add_getset(PyTypeObject *type, struct getsetlist *gsp)
1113{
1114 PyObject *dict = type->tp_defined;
1115
1116 for (; gsp->name != NULL; gsp++) {
1117 PyObject *descr;
1118 if (PyDict_GetItemString(dict, gsp->name))
1119 continue;
1120 descr = PyDescr_NewGetSet(type, gsp);
1121
1122 if (descr == NULL)
1123 return -1;
1124 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1125 return -1;
1126 Py_DECREF(descr);
1127 }
1128 return 0;
1129}
1130
Guido van Rossum13d52f02001-08-10 21:24:08 +00001131static void
1132inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001133{
1134 int oldsize, newsize;
1135
Guido van Rossum13d52f02001-08-10 21:24:08 +00001136 /* Special flag magic */
1137 if (!type->tp_as_buffer && base->tp_as_buffer) {
1138 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1139 type->tp_flags |=
1140 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1141 }
1142 if (!type->tp_as_sequence && base->tp_as_sequence) {
1143 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1144 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1145 }
1146 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1147 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1148 if ((!type->tp_as_number && base->tp_as_number) ||
1149 (!type->tp_as_sequence && base->tp_as_sequence)) {
1150 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1151 if (!type->tp_as_number && !type->tp_as_sequence) {
1152 type->tp_flags |= base->tp_flags &
1153 Py_TPFLAGS_HAVE_INPLACEOPS;
1154 }
1155 }
1156 /* Wow */
1157 }
1158 if (!type->tp_as_number && base->tp_as_number) {
1159 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1160 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1161 }
1162
1163 /* Copying basicsize is connected to the GC flags */
1164 oldsize = PyType_BASICSIZE(base);
1165 newsize = type->tp_basicsize ? PyType_BASICSIZE(type) : oldsize;
1166 if (!(type->tp_flags & Py_TPFLAGS_GC) &&
1167 (base->tp_flags & Py_TPFLAGS_GC) &&
1168 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1169 (!type->tp_traverse && !type->tp_clear)) {
1170 type->tp_flags |= Py_TPFLAGS_GC;
1171 if (type->tp_traverse == NULL)
1172 type->tp_traverse = base->tp_traverse;
1173 if (type->tp_clear == NULL)
1174 type->tp_clear = base->tp_clear;
1175 }
1176 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1177 if (base != &PyBaseObject_Type ||
1178 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1179 if (type->tp_new == NULL)
1180 type->tp_new = base->tp_new;
1181 }
1182 }
1183 PyType_SET_BASICSIZE(type, newsize);
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001184
1185 /* Copy other non-function slots */
1186
1187#undef COPYVAL
1188#define COPYVAL(SLOT) \
1189 if (type->SLOT == 0) type->SLOT = base->SLOT
1190
1191 COPYVAL(tp_itemsize);
1192 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1193 COPYVAL(tp_weaklistoffset);
1194 }
1195 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1196 COPYVAL(tp_dictoffset);
1197 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001198}
1199
1200static void
1201inherit_slots(PyTypeObject *type, PyTypeObject *base)
1202{
1203 PyTypeObject *basebase;
1204
1205#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001206#undef COPYSLOT
1207#undef COPYNUM
1208#undef COPYSEQ
1209#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001210
1211#define SLOTDEFINED(SLOT) \
1212 (base->SLOT != 0 && \
1213 (basebase == NULL || base->SLOT != basebase->SLOT))
1214
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001216 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001217
1218#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1219#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1220#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1221
Guido van Rossum13d52f02001-08-10 21:24:08 +00001222 /* This won't inherit indirect slots (from tp_as_number etc.)
1223 if type doesn't provide the space. */
1224
1225 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1226 basebase = base->tp_base;
1227 if (basebase->tp_as_number == NULL)
1228 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001229 COPYNUM(nb_add);
1230 COPYNUM(nb_subtract);
1231 COPYNUM(nb_multiply);
1232 COPYNUM(nb_divide);
1233 COPYNUM(nb_remainder);
1234 COPYNUM(nb_divmod);
1235 COPYNUM(nb_power);
1236 COPYNUM(nb_negative);
1237 COPYNUM(nb_positive);
1238 COPYNUM(nb_absolute);
1239 COPYNUM(nb_nonzero);
1240 COPYNUM(nb_invert);
1241 COPYNUM(nb_lshift);
1242 COPYNUM(nb_rshift);
1243 COPYNUM(nb_and);
1244 COPYNUM(nb_xor);
1245 COPYNUM(nb_or);
1246 COPYNUM(nb_coerce);
1247 COPYNUM(nb_int);
1248 COPYNUM(nb_long);
1249 COPYNUM(nb_float);
1250 COPYNUM(nb_oct);
1251 COPYNUM(nb_hex);
1252 COPYNUM(nb_inplace_add);
1253 COPYNUM(nb_inplace_subtract);
1254 COPYNUM(nb_inplace_multiply);
1255 COPYNUM(nb_inplace_divide);
1256 COPYNUM(nb_inplace_remainder);
1257 COPYNUM(nb_inplace_power);
1258 COPYNUM(nb_inplace_lshift);
1259 COPYNUM(nb_inplace_rshift);
1260 COPYNUM(nb_inplace_and);
1261 COPYNUM(nb_inplace_xor);
1262 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001263 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1264 COPYNUM(nb_true_divide);
1265 COPYNUM(nb_floor_divide);
1266 COPYNUM(nb_inplace_true_divide);
1267 COPYNUM(nb_inplace_floor_divide);
1268 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001269 }
1270
Guido van Rossum13d52f02001-08-10 21:24:08 +00001271 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1272 basebase = base->tp_base;
1273 if (basebase->tp_as_sequence == NULL)
1274 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 COPYSEQ(sq_length);
1276 COPYSEQ(sq_concat);
1277 COPYSEQ(sq_repeat);
1278 COPYSEQ(sq_item);
1279 COPYSEQ(sq_slice);
1280 COPYSEQ(sq_ass_item);
1281 COPYSEQ(sq_ass_slice);
1282 COPYSEQ(sq_contains);
1283 COPYSEQ(sq_inplace_concat);
1284 COPYSEQ(sq_inplace_repeat);
1285 }
1286
Guido van Rossum13d52f02001-08-10 21:24:08 +00001287 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1288 basebase = base->tp_base;
1289 if (basebase->tp_as_mapping == NULL)
1290 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291 COPYMAP(mp_length);
1292 COPYMAP(mp_subscript);
1293 COPYMAP(mp_ass_subscript);
1294 }
1295
Guido van Rossum13d52f02001-08-10 21:24:08 +00001296 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297
Tim Peters6d6c1a32001-08-02 04:15:00 +00001298 COPYSLOT(tp_dealloc);
1299 COPYSLOT(tp_print);
1300 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1301 type->tp_getattr = base->tp_getattr;
1302 type->tp_getattro = base->tp_getattro;
1303 }
1304 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1305 type->tp_setattr = base->tp_setattr;
1306 type->tp_setattro = base->tp_setattro;
1307 }
1308 /* tp_compare see tp_richcompare */
1309 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001310 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311 COPYSLOT(tp_call);
1312 COPYSLOT(tp_str);
1313 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001315 if (type->tp_compare == NULL &&
1316 type->tp_richcompare == NULL &&
1317 type->tp_hash == NULL)
1318 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001319 type->tp_compare = base->tp_compare;
1320 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001321 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322 }
1323 }
1324 else {
1325 COPYSLOT(tp_compare);
1326 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1328 COPYSLOT(tp_iter);
1329 COPYSLOT(tp_iternext);
1330 }
1331 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1332 COPYSLOT(tp_descr_get);
1333 COPYSLOT(tp_descr_set);
1334 COPYSLOT(tp_dictoffset);
1335 COPYSLOT(tp_init);
1336 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001337 COPYSLOT(tp_free);
1338 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339}
1340
Guido van Rossum13d52f02001-08-10 21:24:08 +00001341staticforward int add_operators(PyTypeObject *);
1342
Tim Peters6d6c1a32001-08-02 04:15:00 +00001343int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001344PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001345{
1346 PyObject *dict, *bases, *x;
1347 PyTypeObject *base;
1348 int i, n;
1349
Guido van Rossumd614f972001-08-10 17:39:49 +00001350 if (type->tp_flags & Py_TPFLAGS_READY) {
1351 assert(type->tp_dict != NULL);
1352 return 0;
1353 }
1354 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1355 assert(type->tp_dict == NULL);
1356
1357 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001358
1359 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1360 base = type->tp_base;
1361 if (base == NULL && type != &PyBaseObject_Type)
1362 base = type->tp_base = &PyBaseObject_Type;
1363
1364 /* Initialize tp_bases */
1365 bases = type->tp_bases;
1366 if (bases == NULL) {
1367 if (base == NULL)
1368 bases = PyTuple_New(0);
1369 else
1370 bases = Py_BuildValue("(O)", base);
1371 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001372 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373 type->tp_bases = bases;
1374 }
1375
1376 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001377 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001378 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001379 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001380 }
1381
1382 /* Initialize tp_defined */
1383 dict = type->tp_defined;
1384 if (dict == NULL) {
1385 dict = PyDict_New();
1386 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001387 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001388 type->tp_defined = dict;
1389 }
1390
1391 /* Add type-specific descriptors to tp_defined */
1392 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001393 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001394 if (type->tp_methods != NULL) {
1395 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001396 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001397 }
1398 if (type->tp_members != NULL) {
1399 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001400 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001401 }
1402 if (type->tp_getset != NULL) {
1403 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001404 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001405 }
1406
1407 /* Temporarily make tp_dict the same object as tp_defined.
1408 (This is needed to call mro(), and can stay this way for
1409 dynamic types). */
1410 Py_INCREF(type->tp_defined);
1411 type->tp_dict = type->tp_defined;
1412
1413 /* Calculate method resolution order */
1414 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001415 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001416 }
1417
Guido van Rossum13d52f02001-08-10 21:24:08 +00001418 /* Inherit special flags from dominant base */
1419 if (type->tp_base != NULL)
1420 inherit_special(type, type->tp_base);
1421
Tim Peters6d6c1a32001-08-02 04:15:00 +00001422 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001423 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001424 /* For a dynamic type, all slots are overridden */
1425 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001426 }
1427 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001428 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001429 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001430 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001431 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001432 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001433 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001434 bases = type->tp_mro;
1435 assert(bases != NULL);
1436 assert(PyTuple_Check(bases));
1437 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001438 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001439 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1440 assert(PyType_Check(base));
1441 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001442 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001443 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001444 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001445 }
1446 }
1447
Guido van Rossum13d52f02001-08-10 21:24:08 +00001448 /* Some more special stuff */
1449 base = type->tp_base;
1450 if (base != NULL) {
1451 if (type->tp_as_number == NULL)
1452 type->tp_as_number = base->tp_as_number;
1453 if (type->tp_as_sequence == NULL)
1454 type->tp_as_sequence = base->tp_as_sequence;
1455 if (type->tp_as_mapping == NULL)
1456 type->tp_as_mapping = base->tp_as_mapping;
1457 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458
Guido van Rossum13d52f02001-08-10 21:24:08 +00001459 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001460 assert(type->tp_dict != NULL);
1461 type->tp_flags =
1462 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001464
1465 error:
1466 type->tp_flags &= ~Py_TPFLAGS_READYING;
1467 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468}
1469
1470
1471/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1472
1473/* There's a wrapper *function* for each distinct function typedef used
1474 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1475 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1476 Most tables have only one entry; the tables for binary operators have two
1477 entries, one regular and one with reversed arguments. */
1478
1479static PyObject *
1480wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1481{
1482 inquiry func = (inquiry)wrapped;
1483 int res;
1484
1485 if (!PyArg_ParseTuple(args, ""))
1486 return NULL;
1487 res = (*func)(self);
1488 if (res == -1 && PyErr_Occurred())
1489 return NULL;
1490 return PyInt_FromLong((long)res);
1491}
1492
1493static struct wrapperbase tab_len[] = {
1494 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1495 {0}
1496};
1497
1498static PyObject *
1499wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1500{
1501 binaryfunc func = (binaryfunc)wrapped;
1502 PyObject *other;
1503
1504 if (!PyArg_ParseTuple(args, "O", &other))
1505 return NULL;
1506 return (*func)(self, other);
1507}
1508
1509static PyObject *
1510wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1511{
1512 binaryfunc func = (binaryfunc)wrapped;
1513 PyObject *other;
1514
1515 if (!PyArg_ParseTuple(args, "O", &other))
1516 return NULL;
1517 return (*func)(other, self);
1518}
1519
1520#undef BINARY
1521#define BINARY(NAME, OP) \
1522static struct wrapperbase tab_##NAME[] = { \
1523 {"__" #NAME "__", \
1524 (wrapperfunc)wrap_binaryfunc, \
1525 "x.__" #NAME "__(y) <==> " #OP}, \
1526 {"__r" #NAME "__", \
1527 (wrapperfunc)wrap_binaryfunc_r, \
1528 "y.__r" #NAME "__(x) <==> " #OP}, \
1529 {0} \
1530}
1531
1532BINARY(add, "x+y");
1533BINARY(sub, "x-y");
1534BINARY(mul, "x*y");
1535BINARY(div, "x/y");
1536BINARY(mod, "x%y");
1537BINARY(divmod, "divmod(x,y)");
1538BINARY(lshift, "x<<y");
1539BINARY(rshift, "x>>y");
1540BINARY(and, "x&y");
1541BINARY(xor, "x^y");
1542BINARY(or, "x|y");
1543
1544static PyObject *
1545wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1546{
1547 ternaryfunc func = (ternaryfunc)wrapped;
1548 PyObject *other;
1549 PyObject *third = Py_None;
1550
1551 /* Note: This wrapper only works for __pow__() */
1552
1553 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1554 return NULL;
1555 return (*func)(self, other, third);
1556}
1557
1558#undef TERNARY
1559#define TERNARY(NAME, OP) \
1560static struct wrapperbase tab_##NAME[] = { \
1561 {"__" #NAME "__", \
1562 (wrapperfunc)wrap_ternaryfunc, \
1563 "x.__" #NAME "__(y, z) <==> " #OP}, \
1564 {"__r" #NAME "__", \
1565 (wrapperfunc)wrap_ternaryfunc, \
1566 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1567 {0} \
1568}
1569
1570TERNARY(pow, "(x**y) % z");
1571
1572#undef UNARY
1573#define UNARY(NAME, OP) \
1574static struct wrapperbase tab_##NAME[] = { \
1575 {"__" #NAME "__", \
1576 (wrapperfunc)wrap_unaryfunc, \
1577 "x.__" #NAME "__() <==> " #OP}, \
1578 {0} \
1579}
1580
1581static PyObject *
1582wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1583{
1584 unaryfunc func = (unaryfunc)wrapped;
1585
1586 if (!PyArg_ParseTuple(args, ""))
1587 return NULL;
1588 return (*func)(self);
1589}
1590
1591UNARY(neg, "-x");
1592UNARY(pos, "+x");
1593UNARY(abs, "abs(x)");
1594UNARY(nonzero, "x != 0");
1595UNARY(invert, "~x");
1596UNARY(int, "int(x)");
1597UNARY(long, "long(x)");
1598UNARY(float, "float(x)");
1599UNARY(oct, "oct(x)");
1600UNARY(hex, "hex(x)");
1601
1602#undef IBINARY
1603#define IBINARY(NAME, OP) \
1604static struct wrapperbase tab_##NAME[] = { \
1605 {"__" #NAME "__", \
1606 (wrapperfunc)wrap_binaryfunc, \
1607 "x.__" #NAME "__(y) <==> " #OP}, \
1608 {0} \
1609}
1610
1611IBINARY(iadd, "x+=y");
1612IBINARY(isub, "x-=y");
1613IBINARY(imul, "x*=y");
1614IBINARY(idiv, "x/=y");
1615IBINARY(imod, "x%=y");
1616IBINARY(ilshift, "x<<=y");
1617IBINARY(irshift, "x>>=y");
1618IBINARY(iand, "x&=y");
1619IBINARY(ixor, "x^=y");
1620IBINARY(ior, "x|=y");
1621
1622#undef ITERNARY
1623#define ITERNARY(NAME, OP) \
1624static struct wrapperbase tab_##NAME[] = { \
1625 {"__" #NAME "__", \
1626 (wrapperfunc)wrap_ternaryfunc, \
1627 "x.__" #NAME "__(y) <==> " #OP}, \
1628 {0} \
1629}
1630
1631ITERNARY(ipow, "x = (x**y) % z");
1632
1633static struct wrapperbase tab_getitem[] = {
1634 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
1635 "x.__getitem__(y) <==> x[y]"},
1636 {0}
1637};
1638
1639static PyObject *
1640wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1641{
1642 intargfunc func = (intargfunc)wrapped;
1643 int i;
1644
1645 if (!PyArg_ParseTuple(args, "i", &i))
1646 return NULL;
1647 return (*func)(self, i);
1648}
1649
1650static struct wrapperbase tab_mul_int[] = {
1651 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1652 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1653 {0}
1654};
1655
1656static struct wrapperbase tab_concat[] = {
1657 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1658 {0}
1659};
1660
1661static struct wrapperbase tab_imul_int[] = {
1662 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1663 {0}
1664};
1665
Guido van Rossum5d815f32001-08-17 21:57:47 +00001666static int
1667getindex(PyObject *self, PyObject *arg)
1668{
1669 int i;
1670
1671 i = PyInt_AsLong(arg);
1672 if (i == -1 && PyErr_Occurred())
1673 return -1;
1674 if (i < 0) {
1675 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
1676 if (sq && sq->sq_length) {
1677 int n = (*sq->sq_length)(self);
1678 if (n < 0)
1679 return -1;
1680 i += n;
1681 }
1682 }
1683 return i;
1684}
1685
1686static PyObject *
1687wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
1688{
1689 intargfunc func = (intargfunc)wrapped;
1690 PyObject *arg;
1691 int i;
1692
1693 if (!PyArg_ParseTuple(args, "O", &arg))
1694 return NULL;
1695 i = getindex(self, arg);
1696 if (i == -1 && PyErr_Occurred())
1697 return NULL;
1698 return (*func)(self, i);
1699}
1700
Tim Peters6d6c1a32001-08-02 04:15:00 +00001701static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001702 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001703 "x.__getitem__(i) <==> x[i]"},
1704 {0}
1705};
1706
1707static PyObject *
1708wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1709{
1710 intintargfunc func = (intintargfunc)wrapped;
1711 int i, j;
1712
1713 if (!PyArg_ParseTuple(args, "ii", &i, &j))
1714 return NULL;
1715 return (*func)(self, i, j);
1716}
1717
1718static struct wrapperbase tab_getslice[] = {
1719 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
1720 "x.__getslice__(i, j) <==> x[i:j]"},
1721 {0}
1722};
1723
1724static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001725wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726{
1727 intobjargproc func = (intobjargproc)wrapped;
1728 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001729 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001730
Guido van Rossum5d815f32001-08-17 21:57:47 +00001731 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
1732 return NULL;
1733 i = getindex(self, arg);
1734 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00001735 return NULL;
1736 res = (*func)(self, i, value);
1737 if (res == -1 && PyErr_Occurred())
1738 return NULL;
1739 Py_INCREF(Py_None);
1740 return Py_None;
1741}
1742
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001743static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00001744wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001745{
1746 intobjargproc func = (intobjargproc)wrapped;
1747 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00001748 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001749
Guido van Rossum5d815f32001-08-17 21:57:47 +00001750 if (!PyArg_ParseTuple(args, "O", &arg))
1751 return NULL;
1752 i = getindex(self, arg);
1753 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001754 return NULL;
1755 res = (*func)(self, i, NULL);
1756 if (res == -1 && PyErr_Occurred())
1757 return NULL;
1758 Py_INCREF(Py_None);
1759 return Py_None;
1760}
1761
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00001763 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00001765 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001766 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001767 {0}
1768};
1769
1770static PyObject *
1771wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1772{
1773 intintobjargproc func = (intintobjargproc)wrapped;
1774 int i, j, res;
1775 PyObject *value;
1776
1777 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1778 return NULL;
1779 res = (*func)(self, i, j, value);
1780 if (res == -1 && PyErr_Occurred())
1781 return NULL;
1782 Py_INCREF(Py_None);
1783 return Py_None;
1784}
1785
1786static struct wrapperbase tab_setslice[] = {
1787 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1788 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1789 {0}
1790};
1791
1792/* XXX objobjproc is a misnomer; should be objargpred */
1793static PyObject *
1794wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1795{
1796 objobjproc func = (objobjproc)wrapped;
1797 int res;
1798 PyObject *value;
1799
1800 if (!PyArg_ParseTuple(args, "O", &value))
1801 return NULL;
1802 res = (*func)(self, value);
1803 if (res == -1 && PyErr_Occurred())
1804 return NULL;
1805 return PyInt_FromLong((long)res);
1806}
1807
1808static struct wrapperbase tab_contains[] = {
1809 {"__contains__", (wrapperfunc)wrap_objobjproc,
1810 "x.__contains__(y) <==> y in x"},
1811 {0}
1812};
1813
1814static PyObject *
1815wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1816{
1817 objobjargproc func = (objobjargproc)wrapped;
1818 int res;
1819 PyObject *key, *value;
1820
1821 if (!PyArg_ParseTuple(args, "OO", &key, &value))
1822 return NULL;
1823 res = (*func)(self, key, value);
1824 if (res == -1 && PyErr_Occurred())
1825 return NULL;
1826 Py_INCREF(Py_None);
1827 return Py_None;
1828}
1829
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001830static PyObject *
1831wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1832{
1833 objobjargproc func = (objobjargproc)wrapped;
1834 int res;
1835 PyObject *key;
1836
1837 if (!PyArg_ParseTuple(args, "O", &key))
1838 return NULL;
1839 res = (*func)(self, key, NULL);
1840 if (res == -1 && PyErr_Occurred())
1841 return NULL;
1842 Py_INCREF(Py_None);
1843 return Py_None;
1844}
1845
Tim Peters6d6c1a32001-08-02 04:15:00 +00001846static struct wrapperbase tab_setitem[] = {
1847 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
1848 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00001849 {"__delitem__", (wrapperfunc)wrap_delitem,
1850 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851 {0}
1852};
1853
1854static PyObject *
1855wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1856{
1857 cmpfunc func = (cmpfunc)wrapped;
1858 int res;
1859 PyObject *other;
1860
1861 if (!PyArg_ParseTuple(args, "O", &other))
1862 return NULL;
1863 res = (*func)(self, other);
1864 if (PyErr_Occurred())
1865 return NULL;
1866 return PyInt_FromLong((long)res);
1867}
1868
1869static struct wrapperbase tab_cmp[] = {
1870 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
1871 "x.__cmp__(y) <==> cmp(x,y)"},
1872 {0}
1873};
1874
1875static struct wrapperbase tab_repr[] = {
1876 {"__repr__", (wrapperfunc)wrap_unaryfunc,
1877 "x.__repr__() <==> repr(x)"},
1878 {0}
1879};
1880
1881static struct wrapperbase tab_getattr[] = {
1882 {"__getattr__", (wrapperfunc)wrap_binaryfunc,
1883 "x.__getattr__('name') <==> x.name"},
1884 {0}
1885};
1886
1887static PyObject *
1888wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
1889{
1890 setattrofunc func = (setattrofunc)wrapped;
1891 int res;
1892 PyObject *name, *value;
1893
1894 if (!PyArg_ParseTuple(args, "OO", &name, &value))
1895 return NULL;
1896 res = (*func)(self, name, value);
1897 if (res < 0)
1898 return NULL;
1899 Py_INCREF(Py_None);
1900 return Py_None;
1901}
1902
1903static PyObject *
1904wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
1905{
1906 setattrofunc func = (setattrofunc)wrapped;
1907 int res;
1908 PyObject *name;
1909
1910 if (!PyArg_ParseTuple(args, "O", &name))
1911 return NULL;
1912 res = (*func)(self, name, NULL);
1913 if (res < 0)
1914 return NULL;
1915 Py_INCREF(Py_None);
1916 return Py_None;
1917}
1918
1919static struct wrapperbase tab_setattr[] = {
1920 {"__setattr__", (wrapperfunc)wrap_setattr,
1921 "x.__setattr__('name', value) <==> x.name = value"},
1922 {"__delattr__", (wrapperfunc)wrap_delattr,
1923 "x.__delattr__('name') <==> del x.name"},
1924 {0}
1925};
1926
1927static PyObject *
1928wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
1929{
1930 hashfunc func = (hashfunc)wrapped;
1931 long res;
1932
1933 if (!PyArg_ParseTuple(args, ""))
1934 return NULL;
1935 res = (*func)(self);
1936 if (res == -1 && PyErr_Occurred())
1937 return NULL;
1938 return PyInt_FromLong(res);
1939}
1940
1941static struct wrapperbase tab_hash[] = {
1942 {"__hash__", (wrapperfunc)wrap_hashfunc,
1943 "x.__hash__() <==> hash(x)"},
1944 {0}
1945};
1946
1947static PyObject *
1948wrap_call(PyObject *self, PyObject *args, void *wrapped)
1949{
1950 ternaryfunc func = (ternaryfunc)wrapped;
1951
1952 /* XXX What about keyword arguments? */
1953 return (*func)(self, args, NULL);
1954}
1955
1956static struct wrapperbase tab_call[] = {
1957 {"__call__", (wrapperfunc)wrap_call,
1958 "x.__call__(...) <==> x(...)"},
1959 {0}
1960};
1961
1962static struct wrapperbase tab_str[] = {
1963 {"__str__", (wrapperfunc)wrap_unaryfunc,
1964 "x.__str__() <==> str(x)"},
1965 {0}
1966};
1967
1968static PyObject *
1969wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
1970{
1971 richcmpfunc func = (richcmpfunc)wrapped;
1972 PyObject *other;
1973
1974 if (!PyArg_ParseTuple(args, "O", &other))
1975 return NULL;
1976 return (*func)(self, other, op);
1977}
1978
1979#undef RICHCMP_WRAPPER
1980#define RICHCMP_WRAPPER(NAME, OP) \
1981static PyObject * \
1982richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
1983{ \
1984 return wrap_richcmpfunc(self, args, wrapped, OP); \
1985}
1986
Jack Jansen8e938b42001-08-08 15:29:49 +00001987RICHCMP_WRAPPER(lt, Py_LT)
1988RICHCMP_WRAPPER(le, Py_LE)
1989RICHCMP_WRAPPER(eq, Py_EQ)
1990RICHCMP_WRAPPER(ne, Py_NE)
1991RICHCMP_WRAPPER(gt, Py_GT)
1992RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001993
1994#undef RICHCMP_ENTRY
1995#define RICHCMP_ENTRY(NAME, EXPR) \
1996 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
1997 "x.__" #NAME "__(y) <==> " EXPR}
1998
1999static struct wrapperbase tab_richcmp[] = {
2000 RICHCMP_ENTRY(lt, "x<y"),
2001 RICHCMP_ENTRY(le, "x<=y"),
2002 RICHCMP_ENTRY(eq, "x==y"),
2003 RICHCMP_ENTRY(ne, "x!=y"),
2004 RICHCMP_ENTRY(gt, "x>y"),
2005 RICHCMP_ENTRY(ge, "x>=y"),
2006 {0}
2007};
2008
2009static struct wrapperbase tab_iter[] = {
2010 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2011 {0}
2012};
2013
2014static PyObject *
2015wrap_next(PyObject *self, PyObject *args, void *wrapped)
2016{
2017 unaryfunc func = (unaryfunc)wrapped;
2018 PyObject *res;
2019
2020 if (!PyArg_ParseTuple(args, ""))
2021 return NULL;
2022 res = (*func)(self);
2023 if (res == NULL && !PyErr_Occurred())
2024 PyErr_SetNone(PyExc_StopIteration);
2025 return res;
2026}
2027
2028static struct wrapperbase tab_next[] = {
2029 {"next", (wrapperfunc)wrap_next,
2030 "x.next() -> the next value, or raise StopIteration"},
2031 {0}
2032};
2033
2034static PyObject *
2035wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2036{
2037 descrgetfunc func = (descrgetfunc)wrapped;
2038 PyObject *obj;
2039 PyObject *type = NULL;
2040
2041 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2042 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043 return (*func)(self, obj, type);
2044}
2045
2046static struct wrapperbase tab_descr_get[] = {
2047 {"__get__", (wrapperfunc)wrap_descr_get,
2048 "descr.__get__(obj, type) -> value"},
2049 {0}
2050};
2051
2052static PyObject *
2053wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2054{
2055 descrsetfunc func = (descrsetfunc)wrapped;
2056 PyObject *obj, *value;
2057 int ret;
2058
2059 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2060 return NULL;
2061 ret = (*func)(self, obj, value);
2062 if (ret < 0)
2063 return NULL;
2064 Py_INCREF(Py_None);
2065 return Py_None;
2066}
2067
2068static struct wrapperbase tab_descr_set[] = {
2069 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2070 "descr.__set__(obj, value)"},
2071 {0}
2072};
2073
2074static PyObject *
2075wrap_init(PyObject *self, PyObject *args, void *wrapped)
2076{
2077 initproc func = (initproc)wrapped;
2078
2079 /* XXX What about keyword arguments? */
2080 if (func(self, args, NULL) < 0)
2081 return NULL;
2082 Py_INCREF(Py_None);
2083 return Py_None;
2084}
2085
2086static struct wrapperbase tab_init[] = {
2087 {"__init__", (wrapperfunc)wrap_init,
2088 "x.__init__(...) initializes x; "
2089 "see x.__type__.__doc__ for signature"},
2090 {0}
2091};
2092
2093static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002094tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002095{
Barry Warsaw60f01882001-08-22 19:24:42 +00002096 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002097 PyObject *arg0, *res;
2098
2099 if (self == NULL || !PyType_Check(self))
2100 Py_FatalError("__new__() called with non-type 'self'");
2101 type = (PyTypeObject *)self;
2102 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002103 PyErr_Format(PyExc_TypeError,
2104 "%s.__new__(): not enough arguments",
2105 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002106 return NULL;
2107 }
2108 arg0 = PyTuple_GET_ITEM(args, 0);
2109 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002110 PyErr_Format(PyExc_TypeError,
2111 "%s.__new__(X): X is not a type object (%s)",
2112 type->tp_name,
2113 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002114 return NULL;
2115 }
2116 subtype = (PyTypeObject *)arg0;
2117 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002118 PyErr_Format(PyExc_TypeError,
2119 "%s.__new__(%s): %s is not a subtype of %s",
2120 type->tp_name,
2121 subtype->tp_name,
2122 subtype->tp_name,
2123 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002124 return NULL;
2125 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002126
2127 /* Check that the use doesn't do something silly and unsafe like
2128 object.__new__(dictionary). To do this, we check that the
2129 most derived base that's not a heap type is this type. */
2130 staticbase = subtype;
2131 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2132 staticbase = staticbase->tp_base;
2133 if (staticbase != type) {
2134 PyErr_Format(PyExc_TypeError,
2135 "%s.__new__(%s) is not safe, use %s.__new__()",
2136 type->tp_name,
2137 subtype->tp_name,
2138 staticbase == NULL ? "?" : staticbase->tp_name);
2139 return NULL;
2140 }
2141
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002142 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2143 if (args == NULL)
2144 return NULL;
2145 res = type->tp_new(subtype, args, kwds);
2146 Py_DECREF(args);
2147 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002148}
2149
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002150static struct PyMethodDef tp_new_methoddef[] = {
2151 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2152 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002153 {0}
2154};
2155
2156static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002157add_tp_new_wrapper(PyTypeObject *type)
2158{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002159 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002160
Guido van Rossumf040ede2001-08-07 16:40:56 +00002161 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2162 return 0;
2163 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002164 if (func == NULL)
2165 return -1;
2166 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2167}
2168
Guido van Rossum13d52f02001-08-10 21:24:08 +00002169static int
2170add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2171{
2172 PyObject *dict = type->tp_defined;
2173
2174 for (; wraps->name != NULL; wraps++) {
2175 PyObject *descr;
2176 if (PyDict_GetItemString(dict, wraps->name))
2177 continue;
2178 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2179 if (descr == NULL)
2180 return -1;
2181 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2182 return -1;
2183 Py_DECREF(descr);
2184 }
2185 return 0;
2186}
2187
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002188/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002189 dictionary with method descriptors for function slots. For each
2190 function slot (like tp_repr) that's defined in the type, one or
2191 more corresponding descriptors are added in the type's tp_defined
2192 dictionary under the appropriate name (like __repr__). Some
2193 function slots cause more than one descriptor to be added (for
2194 example, the nb_add slot adds both __add__ and __radd__
2195 descriptors) and some function slots compete for the same
2196 descriptor (for example both sq_item and mp_subscript generate a
2197 __getitem__ descriptor). This only adds new descriptors and
2198 doesn't overwrite entries in tp_defined that were previously
2199 defined. The descriptors contain a reference to the C function
2200 they must call, so that it's safe if they are copied into a
2201 subtype's __dict__ and the subtype has a different C function in
2202 its slot -- calling the method defined by the descriptor will call
2203 the C function that was used to create it, rather than the C
2204 function present in the slot when it is called. (This is important
2205 because a subtype may have a C function in the slot that calls the
2206 method from the dictionary, and we want to avoid infinite recursion
2207 here.) */
2208
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002209static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002210add_operators(PyTypeObject *type)
2211{
2212 PySequenceMethods *sq;
2213 PyMappingMethods *mp;
2214 PyNumberMethods *nb;
2215
2216#undef ADD
2217#define ADD(SLOT, TABLE) \
2218 if (SLOT) { \
2219 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2220 return -1; \
2221 }
2222
2223 if ((sq = type->tp_as_sequence) != NULL) {
2224 ADD(sq->sq_length, tab_len);
2225 ADD(sq->sq_concat, tab_concat);
2226 ADD(sq->sq_repeat, tab_mul_int);
2227 ADD(sq->sq_item, tab_getitem_int);
2228 ADD(sq->sq_slice, tab_getslice);
2229 ADD(sq->sq_ass_item, tab_setitem_int);
2230 ADD(sq->sq_ass_slice, tab_setslice);
2231 ADD(sq->sq_contains, tab_contains);
2232 ADD(sq->sq_inplace_concat, tab_iadd);
2233 ADD(sq->sq_inplace_repeat, tab_imul_int);
2234 }
2235
2236 if ((mp = type->tp_as_mapping) != NULL) {
2237 if (sq->sq_length == NULL)
2238 ADD(mp->mp_length, tab_len);
2239 ADD(mp->mp_subscript, tab_getitem);
2240 ADD(mp->mp_ass_subscript, tab_setitem);
2241 }
2242
2243 /* We don't support "old-style numbers" because their binary
2244 operators require that both arguments have the same type;
2245 the wrappers here only work for new-style numbers. */
2246 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2247 (nb = type->tp_as_number) != NULL) {
2248 ADD(nb->nb_add, tab_add);
2249 ADD(nb->nb_subtract, tab_sub);
2250 ADD(nb->nb_multiply, tab_mul);
2251 ADD(nb->nb_divide, tab_div);
2252 ADD(nb->nb_remainder, tab_mod);
2253 ADD(nb->nb_divmod, tab_divmod);
2254 ADD(nb->nb_power, tab_pow);
2255 ADD(nb->nb_negative, tab_neg);
2256 ADD(nb->nb_positive, tab_pos);
2257 ADD(nb->nb_absolute, tab_abs);
2258 ADD(nb->nb_nonzero, tab_nonzero);
2259 ADD(nb->nb_invert, tab_invert);
2260 ADD(nb->nb_lshift, tab_lshift);
2261 ADD(nb->nb_rshift, tab_rshift);
2262 ADD(nb->nb_and, tab_and);
2263 ADD(nb->nb_xor, tab_xor);
2264 ADD(nb->nb_or, tab_or);
2265 /* We don't support coerce() -- see above comment */
2266 ADD(nb->nb_int, tab_int);
2267 ADD(nb->nb_long, tab_long);
2268 ADD(nb->nb_float, tab_float);
2269 ADD(nb->nb_oct, tab_oct);
2270 ADD(nb->nb_hex, tab_hex);
2271 ADD(nb->nb_inplace_add, tab_iadd);
2272 ADD(nb->nb_inplace_subtract, tab_isub);
2273 ADD(nb->nb_inplace_multiply, tab_imul);
2274 ADD(nb->nb_inplace_divide, tab_idiv);
2275 ADD(nb->nb_inplace_remainder, tab_imod);
2276 ADD(nb->nb_inplace_power, tab_ipow);
2277 ADD(nb->nb_inplace_lshift, tab_ilshift);
2278 ADD(nb->nb_inplace_rshift, tab_irshift);
2279 ADD(nb->nb_inplace_and, tab_iand);
2280 ADD(nb->nb_inplace_xor, tab_ixor);
2281 ADD(nb->nb_inplace_or, tab_ior);
2282 }
2283
2284 ADD(type->tp_getattro, tab_getattr);
2285 ADD(type->tp_setattro, tab_setattr);
2286 ADD(type->tp_compare, tab_cmp);
2287 ADD(type->tp_repr, tab_repr);
2288 ADD(type->tp_hash, tab_hash);
2289 ADD(type->tp_call, tab_call);
2290 ADD(type->tp_str, tab_str);
2291 ADD(type->tp_richcompare, tab_richcmp);
2292 ADD(type->tp_iter, tab_iter);
2293 ADD(type->tp_iternext, tab_next);
2294 ADD(type->tp_descr_get, tab_descr_get);
2295 ADD(type->tp_descr_set, tab_descr_set);
2296 ADD(type->tp_init, tab_init);
2297
Guido van Rossumf040ede2001-08-07 16:40:56 +00002298 if (type->tp_new != NULL) {
2299 if (add_tp_new_wrapper(type) < 0)
2300 return -1;
2301 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002302
2303 return 0;
2304}
2305
Guido van Rossumf040ede2001-08-07 16:40:56 +00002306/* Slot wrappers that call the corresponding __foo__ slot. See comments
2307 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002308
Guido van Rossumdc91b992001-08-08 22:26:22 +00002309#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002310static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002311FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002312{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002313 return PyObject_CallMethod(self, OPSTR, ""); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002314}
2315
Guido van Rossumdc91b992001-08-08 22:26:22 +00002316#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002317static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002318FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002319{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002320 return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002321}
2322
Guido van Rossumdc91b992001-08-08 22:26:22 +00002323
2324#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002325static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002326FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002327{ \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002328 if (self->ob_type->tp_as_number != NULL && \
2329 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2330 PyObject *r; \
2331 r = PyObject_CallMethod( \
2332 self, OPSTR, "O", other); \
2333 if (r != Py_NotImplemented || \
2334 other->ob_type == self->ob_type) \
2335 return r; \
2336 Py_DECREF(r); \
2337 } \
2338 if (other->ob_type->tp_as_number != NULL && \
2339 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2340 return PyObject_CallMethod( \
2341 other, ROPSTR, "O", self); \
2342 } \
2343 Py_INCREF(Py_NotImplemented); \
2344 return Py_NotImplemented; \
2345}
2346
2347#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2348 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2349
2350#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2351static PyObject * \
2352FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2353{ \
2354 return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002355}
2356
2357static int
2358slot_sq_length(PyObject *self)
2359{
2360 PyObject *res = PyObject_CallMethod(self, "__len__", "");
2361
2362 if (res == NULL)
2363 return -1;
2364 return (int)PyInt_AsLong(res);
2365}
2366
Guido van Rossumdc91b992001-08-08 22:26:22 +00002367SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2368SLOT1(slot_sq_repeat, "__mul__", int, "i")
2369SLOT1(slot_sq_item, "__getitem__", int, "i")
2370SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002371
2372static int
2373slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2374{
2375 PyObject *res;
2376
2377 if (value == NULL)
2378 res = PyObject_CallMethod(self, "__delitem__", "i", index);
2379 else
2380 res = PyObject_CallMethod(self, "__setitem__",
2381 "iO", index, value);
2382 if (res == NULL)
2383 return -1;
2384 Py_DECREF(res);
2385 return 0;
2386}
2387
2388static int
2389slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2390{
2391 PyObject *res;
2392
2393 if (value == NULL)
2394 res = PyObject_CallMethod(self, "__delslice__", "ii", i, j);
2395 else
2396 res = PyObject_CallMethod(self, "__setslice__",
2397 "iiO", i, j, value);
2398 if (res == NULL)
2399 return -1;
2400 Py_DECREF(res);
2401 return 0;
2402}
2403
2404static int
2405slot_sq_contains(PyObject *self, PyObject *value)
2406{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002407 PyObject *func, *res, *args;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002408
Guido van Rossumb8f63662001-08-15 23:57:02 +00002409 func = PyObject_GetAttrString(self, "__contains__");
2410
2411 if (func != NULL) {
2412 args = Py_BuildValue("(O)", value);
2413 if (args == NULL)
2414 res = NULL;
2415 else {
2416 res = PyEval_CallObject(func, args);
2417 Py_DECREF(args);
2418 }
2419 Py_DECREF(func);
2420 if (res == NULL)
2421 return -1;
2422 return PyObject_IsTrue(res);
2423 }
2424 else {
2425 PyErr_Clear();
2426 return _PySequence_IterContains(self, value);
2427 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002428}
2429
Guido van Rossumdc91b992001-08-08 22:26:22 +00002430SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2431SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002432
2433#define slot_mp_length slot_sq_length
2434
Guido van Rossumdc91b992001-08-08 22:26:22 +00002435SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002436
2437static int
2438slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2439{
2440 PyObject *res;
2441
2442 if (value == NULL)
2443 res = PyObject_CallMethod(self, "__delitem__", "O", key);
2444 else
2445 res = PyObject_CallMethod(self, "__setitem__",
2446 "OO", key, value);
2447 if (res == NULL)
2448 return -1;
2449 Py_DECREF(res);
2450 return 0;
2451}
2452
Guido van Rossumdc91b992001-08-08 22:26:22 +00002453SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2454SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2455SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2456SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2457SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2458SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2459
2460staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2461
2462SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2463 nb_power, "__pow__", "__rpow__")
2464
2465static PyObject *
2466slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2467{
2468 if (modulus == Py_None)
2469 return slot_nb_power_binary(self, other);
2470 /* Three-arg power doesn't use __rpow__ */
2471 return PyObject_CallMethod(self, "__pow__", "OO", other, modulus);
2472}
2473
2474SLOT0(slot_nb_negative, "__neg__")
2475SLOT0(slot_nb_positive, "__pos__")
2476SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002477
2478static int
2479slot_nb_nonzero(PyObject *self)
2480{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002481 PyObject *func, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002482
Guido van Rossumb8f63662001-08-15 23:57:02 +00002483 func = PyObject_GetAttrString(self, "__nonzero__");
2484 if (func == NULL) {
2485 PyErr_Clear();
2486 func = PyObject_GetAttrString(self, "__len__");
2487 }
2488
2489 if (func != NULL) {
2490 res = PyEval_CallObject(func, NULL);
2491 Py_DECREF(func);
2492 if (res == NULL)
2493 return -1;
2494 return PyObject_IsTrue(res);
2495 }
2496 else {
2497 PyErr_Clear();
2498 return 1;
2499 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002500}
2501
Guido van Rossumdc91b992001-08-08 22:26:22 +00002502SLOT0(slot_nb_invert, "__invert__")
2503SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2504SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2505SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2506SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2507SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002508/* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002509SLOT0(slot_nb_int, "__int__")
2510SLOT0(slot_nb_long, "__long__")
2511SLOT0(slot_nb_float, "__float__")
2512SLOT0(slot_nb_oct, "__oct__")
2513SLOT0(slot_nb_hex, "__hex__")
2514SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2515SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2516SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2517SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2518SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2519SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2520SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2521SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2522SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2523SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2524SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2525SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2526 "__floordiv__", "__rfloordiv__")
2527SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2528SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2529SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002530
2531static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002532half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002533{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002534 PyObject *func, *args, *res;
2535 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002536
Guido van Rossumb8f63662001-08-15 23:57:02 +00002537 func = PyObject_GetAttrString(self, "__cmp__");
2538 if (func == NULL) {
2539 PyErr_Clear();
2540 }
2541 else {
2542 args = Py_BuildValue("(O)", other);
2543 if (args == NULL)
2544 res = NULL;
2545 else {
2546 res = PyObject_CallObject(func, args);
2547 Py_DECREF(args);
2548 }
2549 if (res != Py_NotImplemented) {
2550 if (res == NULL)
2551 return -2;
2552 c = PyInt_AsLong(res);
2553 Py_DECREF(res);
2554 if (c == -1 && PyErr_Occurred())
2555 return -2;
2556 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2557 }
2558 Py_DECREF(res);
2559 }
2560 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561}
2562
Guido van Rossumb8f63662001-08-15 23:57:02 +00002563static int
2564slot_tp_compare(PyObject *self, PyObject *other)
2565{
2566 int c;
2567
2568 if (self->ob_type->tp_compare == slot_tp_compare) {
2569 c = half_compare(self, other);
2570 if (c <= 1)
2571 return c;
2572 }
2573 if (other->ob_type->tp_compare == slot_tp_compare) {
2574 c = half_compare(other, self);
2575 if (c < -1)
2576 return -2;
2577 if (c <= 1)
2578 return -c;
2579 }
2580 return (void *)self < (void *)other ? -1 :
2581 (void *)self > (void *)other ? 1 : 0;
2582}
2583
2584static PyObject *
2585slot_tp_repr(PyObject *self)
2586{
2587 PyObject *func, *res;
2588
2589 func = PyObject_GetAttrString(self, "__repr__");
2590 if (func != NULL) {
2591 res = PyEval_CallObject(func, NULL);
2592 Py_DECREF(func);
2593 return res;
2594 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00002595 PyErr_Clear();
2596 return PyString_FromFormat("<%s object at %p>",
2597 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002598}
2599
2600static PyObject *
2601slot_tp_str(PyObject *self)
2602{
2603 PyObject *func, *res;
2604
2605 func = PyObject_GetAttrString(self, "__str__");
2606 if (func != NULL) {
2607 res = PyEval_CallObject(func, NULL);
2608 Py_DECREF(func);
2609 return res;
2610 }
2611 else {
2612 PyErr_Clear();
2613 return slot_tp_repr(self);
2614 }
2615}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616
2617static long
2618slot_tp_hash(PyObject *self)
2619{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002620 PyObject *func, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002621 long h;
2622
Guido van Rossumb8f63662001-08-15 23:57:02 +00002623 func = PyObject_GetAttrString(self, "__hash__");
2624
2625 if (func != NULL) {
2626 res = PyEval_CallObject(func, NULL);
2627 Py_DECREF(func);
2628 if (res == NULL)
2629 return -1;
2630 h = PyInt_AsLong(res);
2631 }
2632 else {
2633 PyErr_Clear();
2634 func = PyObject_GetAttrString(self, "__eq__");
2635 if (func == NULL) {
2636 PyErr_Clear();
2637 func = PyObject_GetAttrString(self, "__cmp__");
2638 }
2639 if (func != NULL) {
2640 Py_DECREF(func);
2641 PyErr_SetString(PyExc_TypeError, "unhashable type");
2642 return -1;
2643 }
2644 PyErr_Clear();
2645 h = _Py_HashPointer((void *)self);
2646 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002647 if (h == -1 && !PyErr_Occurred())
2648 h = -2;
2649 return h;
2650}
2651
2652static PyObject *
2653slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2654{
2655 PyObject *meth = PyObject_GetAttrString(self, "__call__");
2656 PyObject *res;
2657
2658 if (meth == NULL)
2659 return NULL;
2660 res = PyObject_Call(meth, args, kwds);
2661 Py_DECREF(meth);
2662 return res;
2663}
2664
Tim Peters6d6c1a32001-08-02 04:15:00 +00002665static PyObject *
2666slot_tp_getattro(PyObject *self, PyObject *name)
2667{
2668 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002669 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002670 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002671
Guido van Rossum8e248182001-08-12 05:17:56 +00002672 if (getattr_str == NULL) {
2673 getattr_str = PyString_InternFromString("__getattr__");
2674 if (getattr_str == NULL)
2675 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002676 }
Guido van Rossum8e248182001-08-12 05:17:56 +00002677 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00002678 if (getattr == NULL) {
2679 /* Avoid further slowdowns */
2680 if (tp->tp_getattro == slot_tp_getattro)
2681 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00002682 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00002683 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002684 return PyObject_CallFunction(getattr, "OO", self, name);
2685}
2686
2687static int
2688slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2689{
2690 PyObject *res;
2691
2692 if (value == NULL)
2693 res = PyObject_CallMethod(self, "__delattr__", "O", name);
2694 else
2695 res = PyObject_CallMethod(self, "__setattr__",
2696 "OO", name, value);
2697 if (res == NULL)
2698 return -1;
2699 Py_DECREF(res);
2700 return 0;
2701}
2702
2703/* Map rich comparison operators to their __xx__ namesakes */
2704static char *name_op[] = {
2705 "__lt__",
2706 "__le__",
2707 "__eq__",
2708 "__ne__",
2709 "__gt__",
2710 "__ge__",
2711};
2712
2713static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00002714half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002715{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002716 PyObject *func, *args, *res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717
Guido van Rossumb8f63662001-08-15 23:57:02 +00002718 func = PyObject_GetAttrString(self, name_op[op]);
2719 if (func == NULL) {
2720 PyErr_Clear();
2721 Py_INCREF(Py_NotImplemented);
2722 return Py_NotImplemented;
2723 }
2724 args = Py_BuildValue("(O)", other);
2725 if (args == NULL)
2726 res = NULL;
2727 else {
2728 res = PyObject_CallObject(func, args);
2729 Py_DECREF(args);
2730 }
2731 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002732 return res;
2733}
2734
Guido van Rossumb8f63662001-08-15 23:57:02 +00002735/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
2736static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
2737
2738static PyObject *
2739slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2740{
2741 PyObject *res;
2742
2743 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
2744 res = half_richcompare(self, other, op);
2745 if (res != Py_NotImplemented)
2746 return res;
2747 Py_DECREF(res);
2748 }
2749 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
2750 res = half_richcompare(other, self, swapped_op[op]);
2751 if (res != Py_NotImplemented) {
2752 return res;
2753 }
2754 Py_DECREF(res);
2755 }
2756 Py_INCREF(Py_NotImplemented);
2757 return Py_NotImplemented;
2758}
2759
2760static PyObject *
2761slot_tp_iter(PyObject *self)
2762{
2763 PyObject *func, *res;
2764
2765 func = PyObject_GetAttrString(self, "__iter__");
2766 if (func != NULL) {
2767 res = PyObject_CallObject(func, NULL);
2768 Py_DECREF(func);
2769 return res;
2770 }
2771 PyErr_Clear();
2772 func = PyObject_GetAttrString(self, "__getitem__");
2773 if (func == NULL) {
2774 PyErr_SetString(PyExc_TypeError, "iter() of non-sequence");
2775 return NULL;
2776 }
2777 Py_DECREF(func);
2778 return PySeqIter_New(self);
2779}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780
2781static PyObject *
2782slot_tp_iternext(PyObject *self)
2783{
2784 return PyObject_CallMethod(self, "next", "");
2785}
2786
Guido van Rossum1a493502001-08-17 16:47:50 +00002787static PyObject *
2788slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
2789{
2790 PyTypeObject *tp = self->ob_type;
2791 PyObject *get;
2792 static PyObject *get_str = NULL;
2793
2794 if (get_str == NULL) {
2795 get_str = PyString_InternFromString("__get__");
2796 if (get_str == NULL)
2797 return NULL;
2798 }
2799 get = _PyType_Lookup(tp, get_str);
2800 if (get == NULL) {
2801 /* Avoid further slowdowns */
2802 if (tp->tp_descr_get == slot_tp_descr_get)
2803 tp->tp_descr_get = NULL;
2804 Py_INCREF(self);
2805 return self;
2806 }
Guido van Rossum2c252392001-08-24 10:13:31 +00002807 if (obj == NULL)
2808 obj = Py_None;
2809 if (type == NULL)
2810 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00002811 return PyObject_CallFunction(get, "OOO", self, obj, type);
2812}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002813
2814static int
2815slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2816{
Guido van Rossum2c252392001-08-24 10:13:31 +00002817 PyObject *res;
2818
2819 if (value == NULL)
2820 res = PyObject_CallMethod(self, "__del__", "O", target);
2821 else
2822 res = PyObject_CallMethod(self, "__set__",
2823 "OO", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002824 if (res == NULL)
2825 return -1;
2826 Py_DECREF(res);
2827 return 0;
2828}
2829
2830static int
2831slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2832{
2833 PyObject *meth = PyObject_GetAttrString(self, "__init__");
2834 PyObject *res;
2835
2836 if (meth == NULL)
2837 return -1;
2838 res = PyObject_Call(meth, args, kwds);
2839 Py_DECREF(meth);
2840 if (res == NULL)
2841 return -1;
2842 Py_DECREF(res);
2843 return 0;
2844}
2845
2846static PyObject *
2847slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2848{
2849 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
2850 PyObject *newargs, *x;
2851 int i, n;
2852
2853 if (func == NULL)
2854 return NULL;
2855 assert(PyTuple_Check(args));
2856 n = PyTuple_GET_SIZE(args);
2857 newargs = PyTuple_New(n+1);
2858 if (newargs == NULL)
2859 return NULL;
2860 Py_INCREF(type);
2861 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
2862 for (i = 0; i < n; i++) {
2863 x = PyTuple_GET_ITEM(args, i);
2864 Py_INCREF(x);
2865 PyTuple_SET_ITEM(newargs, i+1, x);
2866 }
2867 x = PyObject_Call(func, newargs, kwds);
2868 Py_DECREF(func);
2869 return x;
2870}
2871
Guido van Rossumf040ede2001-08-07 16:40:56 +00002872/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002873 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00002874 The dict argument is the dictionary argument passed to type_new(),
2875 which is the local namespace of the class statement, in other
2876 words, it contains the methods. For each special method (like
2877 __repr__) defined in the dictionary, the corresponding function
2878 slot in the type object (like tp_repr) is set to a special function
2879 whose name is 'slot_' followed by the slot name and whose signature
2880 is whatever is required for that slot. These slot functions look
2881 up the corresponding method in the type's dictionary and call it.
2882 The slot functions have to take care of the various peculiarities
2883 of the mapping between slots and special methods, such as mapping
2884 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
2885 etc.) or mapping multiple slots to a single method (sq_item,
2886 mp_subscript <--> __getitem__). */
2887
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888static void
2889override_slots(PyTypeObject *type, PyObject *dict)
2890{
2891 PySequenceMethods *sq = type->tp_as_sequence;
2892 PyMappingMethods *mp = type->tp_as_mapping;
2893 PyNumberMethods *nb = type->tp_as_number;
2894
Guido van Rossumdc91b992001-08-08 22:26:22 +00002895#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00002896 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002897 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002898 }
2899
Guido van Rossumdc91b992001-08-08 22:26:22 +00002900#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00002901 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002902 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002903 }
2904
Guido van Rossumdc91b992001-08-08 22:26:22 +00002905#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00002906 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002907 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002908 }
2909
Guido van Rossumdc91b992001-08-08 22:26:22 +00002910#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00002911 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002912 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002913 }
2914
Guido van Rossumdc91b992001-08-08 22:26:22 +00002915 SQSLOT("__len__", sq_length, slot_sq_length);
2916 SQSLOT("__add__", sq_concat, slot_sq_concat);
2917 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
2918 SQSLOT("__getitem__", sq_item, slot_sq_item);
2919 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
2920 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
2921 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
2922 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
2923 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
2924 SQSLOT("__contains__", sq_contains, slot_sq_contains);
2925 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
2926 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927
Guido van Rossumdc91b992001-08-08 22:26:22 +00002928 MPSLOT("__len__", mp_length, slot_mp_length);
2929 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
2930 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
2931 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002932
Guido van Rossumdc91b992001-08-08 22:26:22 +00002933 NBSLOT("__add__", nb_add, slot_nb_add);
2934 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
2935 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
2936 NBSLOT("__div__", nb_divide, slot_nb_divide);
2937 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
2938 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
2939 NBSLOT("__pow__", nb_power, slot_nb_power);
2940 NBSLOT("__neg__", nb_negative, slot_nb_negative);
2941 NBSLOT("__pos__", nb_positive, slot_nb_positive);
2942 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
2943 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
2944 NBSLOT("__invert__", nb_invert, slot_nb_invert);
2945 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
2946 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
2947 NBSLOT("__and__", nb_and, slot_nb_and);
2948 NBSLOT("__xor__", nb_xor, slot_nb_xor);
2949 NBSLOT("__or__", nb_or, slot_nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002950 /* Not coerce() */
Guido van Rossumdc91b992001-08-08 22:26:22 +00002951 NBSLOT("__int__", nb_int, slot_nb_int);
2952 NBSLOT("__long__", nb_long, slot_nb_long);
2953 NBSLOT("__float__", nb_float, slot_nb_float);
2954 NBSLOT("__oct__", nb_oct, slot_nb_oct);
2955 NBSLOT("__hex__", nb_hex, slot_nb_hex);
2956 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
2957 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
2958 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
2959 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
2960 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
2961 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
2962 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
2963 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
2964 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
2965 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
2966 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
2967 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
2968 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
2969 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
2970 slot_nb_inplace_floor_divide);
2971 NBSLOT("__itruediv__", nb_inplace_true_divide,
2972 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002973
Guido van Rossum8e248182001-08-12 05:17:56 +00002974 if (dict == NULL ||
2975 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00002976 PyDict_GetItemString(dict, "__repr__"))
2977 type->tp_print = NULL;
2978
Guido van Rossumdc91b992001-08-08 22:26:22 +00002979 TPSLOT("__cmp__", tp_compare, slot_tp_compare);
2980 TPSLOT("__repr__", tp_repr, slot_tp_repr);
2981 TPSLOT("__hash__", tp_hash, slot_tp_hash);
2982 TPSLOT("__call__", tp_call, slot_tp_call);
2983 TPSLOT("__str__", tp_str, slot_tp_str);
2984 TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
2985 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
2986 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
2987 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
2988 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
2989 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
2990 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
2991 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
2992 TPSLOT("__iter__", tp_iter, slot_tp_iter);
2993 TPSLOT("next", tp_iternext, slot_tp_iternext);
2994 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
2995 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
2996 TPSLOT("__init__", tp_init, slot_tp_init);
2997 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002998}
Guido van Rossum705f0f52001-08-24 16:47:00 +00002999
3000
3001/* Cooperative 'super' */
3002
3003typedef struct {
3004 PyObject_HEAD
3005 PyObject *type;
3006 PyObject *obj;
3007} superobject;
3008
3009static void
3010super_dealloc(PyObject *self)
3011{
3012 superobject *su = (superobject *)self;
3013
3014 Py_XDECREF(su->obj);
3015 Py_XDECREF(su->type);
3016 self->ob_type->tp_free(self);
3017}
3018
3019static PyObject *
3020super_getattro(PyObject *self, PyObject *name)
3021{
3022 superobject *su = (superobject *)self;
3023
3024 if (su->obj != NULL) {
3025 PyObject *mro, *res, *tmp;
3026 descrgetfunc f;
3027 int i, n;
3028
3029 mro = ((PyTypeObject *)(su->obj->ob_type))->tp_mro;
3030 assert(mro != NULL && PyTuple_Check(mro));
3031 n = PyTuple_GET_SIZE(mro);
3032 for (i = 0; i < n; i++) {
3033 if (su->type == PyTuple_GET_ITEM(mro, i))
3034 break;
3035 }
3036 assert(i < n);
3037 i++;
3038 res = NULL;
3039 for (; i < n; i++) {
3040 tmp = PyTuple_GET_ITEM(mro, i);
3041 assert(PyType_Check(tmp));
3042 res = PyDict_GetItem(
3043 ((PyTypeObject *)tmp)->tp_defined, name);
3044 if (res != NULL) {
3045 Py_INCREF(res);
3046 f = res->ob_type->tp_descr_get;
3047 if (f != NULL) {
3048 tmp = f(res, su->obj, res);
3049 Py_DECREF(res);
3050 res = tmp;
3051 }
3052 return res;
3053 }
3054 }
3055 }
3056 return PyObject_GenericGetAttr(self, name);
3057}
3058
3059static PyObject *
3060super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3061{
3062 superobject *su = (superobject *)self;
3063 superobject *new;
3064
3065 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3066 /* Not binding to an object, or already bound */
3067 Py_INCREF(self);
3068 return self;
3069 }
3070 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3071 if (new == NULL)
3072 return NULL;
3073 Py_INCREF(su->type);
3074 Py_INCREF(obj);
3075 new->type = su->type;
3076 new->obj = obj;
3077 return (PyObject *)new;
3078}
3079
3080static int
3081super_init(PyObject *self, PyObject *args, PyObject *kwds)
3082{
3083 superobject *su = (superobject *)self;
3084 PyObject *type, *obj = NULL;
3085
3086 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3087 return -1;
3088 if (obj == Py_None)
3089 obj = NULL;
3090 if (obj != NULL && !PyType_IsSubtype(obj->ob_type,
3091 (PyTypeObject *)type)) {
3092 PyErr_SetString(PyExc_TypeError,
3093 "super(type, obj) requires isinstance(obj, type)");
3094 return -1;
3095 }
3096 Py_INCREF(type);
3097 Py_XINCREF(obj);
3098 su->type = type;
3099 su->obj = obj;
3100 return 0;
3101}
3102
3103static char super_doc[] =
3104"super(type) -> unbound super object\n"
3105"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
3106"Typical use to call a cooperative superclass method:\n"
3107"class C(B):\n"
3108" def meth(self, arg):\n"
3109" super(C, self).meth(arg)";
3110
3111PyTypeObject PySuper_Type = {
3112 PyObject_HEAD_INIT(&PyType_Type)
3113 0, /* ob_size */
3114 "super", /* tp_name */
3115 sizeof(superobject), /* tp_basicsize */
3116 0, /* tp_itemsize */
3117 /* methods */
3118 super_dealloc, /* tp_dealloc */
3119 0, /* tp_print */
3120 0, /* tp_getattr */
3121 0, /* tp_setattr */
3122 0, /* tp_compare */
3123 0, /* tp_repr */
3124 0, /* tp_as_number */
3125 0, /* tp_as_sequence */
3126 0, /* tp_as_mapping */
3127 0, /* tp_hash */
3128 0, /* tp_call */
3129 0, /* tp_str */
3130 super_getattro, /* tp_getattro */
3131 0, /* tp_setattro */
3132 0, /* tp_as_buffer */
3133 Py_TPFLAGS_DEFAULT, /* tp_flags */
3134 super_doc, /* tp_doc */
3135 0, /* tp_traverse */
3136 0, /* tp_clear */
3137 0, /* tp_richcompare */
3138 0, /* tp_weaklistoffset */
3139 0, /* tp_iter */
3140 0, /* tp_iternext */
3141 0, /* tp_methods */
3142 0, /* tp_members */
3143 0, /* tp_getset */
3144 0, /* tp_base */
3145 0, /* tp_dict */
3146 super_descr_get, /* tp_descr_get */
3147 0, /* tp_descr_set */
3148 0, /* tp_dictoffset */
3149 super_init, /* tp_init */
3150 PyType_GenericAlloc, /* tp_alloc */
3151 PyType_GenericNew, /* tp_new */
3152 _PyObject_Del, /* tp_free */
3153};