blob: 0342e71562c3e248f1adac804b0514c0228ad87d [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Type object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum6f799372001-09-20 20:46:19 +00007static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00008 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
9 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
10 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
11 {"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
17 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
18 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
25 char *s;
26
27 s = strrchr(type->tp_name, '.');
28 if (s == NULL)
29 s = type->tp_name;
30 else
31 s++;
32 return PyString_FromString(s);
33}
34
35static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000036type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000037{
Guido van Rossumc3542212001-08-16 09:18:56 +000038 PyObject *mod;
39 char *s;
40
41 s = strrchr(type->tp_name, '.');
42 if (s != NULL)
43 return PyString_FromStringAndSize(type->tp_name,
44 (int)(s - type->tp_name));
45 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
46 return PyString_FromString("__builtin__");
47 mod = PyDict_GetItemString(type->tp_defined, "__module__");
48 if (mod != NULL && PyString_Check(mod)) {
49 Py_INCREF(mod);
50 return mod;
51 }
52 PyErr_SetString(PyExc_AttributeError, "__module__");
53 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000054}
55
Guido van Rossum3926a632001-09-25 16:25:58 +000056static int
57type_set_module(PyTypeObject *type, PyObject *value, void *context)
58{
59 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ||
60 strrchr(type->tp_name, '.')) {
61 PyErr_Format(PyExc_TypeError,
62 "can't set %s.__module__", type->tp_name);
63 return -1;
64 }
65 if (!value) {
66 PyErr_Format(PyExc_TypeError,
67 "can't delete %s.__module__", type->tp_name);
68 return -1;
69 }
70 return PyDict_SetItemString(type->tp_dict, "__module__", value);
71}
72
Tim Peters6d6c1a32001-08-02 04:15:00 +000073static PyObject *
74type_dict(PyTypeObject *type, void *context)
75{
76 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077 Py_INCREF(Py_None);
78 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000079 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000080 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
81 Py_INCREF(type->tp_dict);
82 return type->tp_dict;
83 }
84 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000085}
86
Tim Peters6d6c1a32001-08-02 04:15:00 +000087static PyObject *
88type_defined(PyTypeObject *type, void *context)
89{
90 if (type->tp_defined == NULL) {
91 Py_INCREF(Py_None);
92 return Py_None;
93 }
94 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
95 Py_INCREF(type->tp_defined);
96 return type->tp_defined;
97 }
98 return PyDictProxy_New(type->tp_defined);
99}
100
101static PyObject *
102type_dynamic(PyTypeObject *type, void *context)
103{
104 PyObject *res;
105
106 res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
107 Py_INCREF(res);
108 return res;
109}
110
Guido van Rossum32d34c82001-09-20 21:45:26 +0000111PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000112 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000113 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000114 {"__dict__", (getter)type_dict, NULL, NULL},
115 {"__defined__", (getter)type_defined, NULL, NULL},
116 {"__dynamic__", (getter)type_dynamic, NULL, NULL},
117 {0}
118};
119
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000120static int
121type_compare(PyObject *v, PyObject *w)
122{
123 /* This is called with type objects only. So we
124 can just compare the addresses. */
125 Py_uintptr_t vv = (Py_uintptr_t)v;
126 Py_uintptr_t ww = (Py_uintptr_t)w;
127 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
128}
129
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000131type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000133 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000134 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000135
136 mod = type_module(type, NULL);
137 if (mod == NULL)
138 PyErr_Clear();
139 else if (!PyString_Check(mod)) {
140 Py_DECREF(mod);
141 mod = NULL;
142 }
143 name = type_name(type, NULL);
144 if (name == NULL)
145 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000146
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000147 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
148 kind = "class";
149 else
150 kind = "type";
151
Barry Warsaw7ce36942001-08-24 18:34:26 +0000152 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000153 rtn = PyString_FromFormat("<%s '%s.%s'>",
154 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000155 PyString_AS_STRING(mod),
156 PyString_AS_STRING(name));
157 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000158 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000159 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000160
Guido van Rossumc3542212001-08-16 09:18:56 +0000161 Py_XDECREF(mod);
162 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000163 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
Tim Peters6d6c1a32001-08-02 04:15:00 +0000166static PyObject *
167type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
168{
169 PyObject *obj;
170
171 if (type->tp_new == NULL) {
172 PyErr_Format(PyExc_TypeError,
173 "cannot create '%.100s' instances",
174 type->tp_name);
175 return NULL;
176 }
177
Tim Peters3f996e72001-09-13 19:18:27 +0000178 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 if (obj != NULL) {
180 type = obj->ob_type;
181 if (type->tp_init != NULL &&
182 type->tp_init(obj, args, kwds) < 0) {
183 Py_DECREF(obj);
184 obj = NULL;
185 }
186 }
187 return obj;
188}
189
190PyObject *
191PyType_GenericAlloc(PyTypeObject *type, int nitems)
192{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000193 PyObject *obj;
Tim Peters6d483d32001-10-06 21:27:34 +0000194 size_t size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000195
Tim Peters6d483d32001-10-06 21:27:34 +0000196 _PyObject_VAR_SIZE(size, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000197
198 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000199 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000200 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000201 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000202
Neil Schemenauerc806c882001-08-29 23:54:54 +0000203 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000204 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000205
Neil Schemenauerc806c882001-08-29 23:54:54 +0000206 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000207
Tim Peters6d6c1a32001-08-02 04:15:00 +0000208 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
209 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000210
Tim Peters6d6c1a32001-08-02 04:15:00 +0000211 if (type->tp_itemsize == 0)
212 PyObject_INIT(obj, type);
213 else
214 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000215
Tim Peters6d6c1a32001-08-02 04:15:00 +0000216 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000217 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000218 return obj;
219}
220
221PyObject *
222PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
223{
224 return type->tp_alloc(type, 0);
225}
226
Guido van Rossum9475a232001-10-05 20:51:39 +0000227/* Helpers for subtyping */
228
229static int
230subtype_traverse(PyObject *self, visitproc visit, void *arg)
231{
232 PyTypeObject *type, *base;
233 traverseproc f;
234 int err;
235
236 /* Find the nearest base with a different tp_traverse */
237 type = self->ob_type;
238 base = type->tp_base;
239 while ((f = base->tp_traverse) == subtype_traverse) {
240 base = base->tp_base;
241 assert(base);
242 }
243
244 if (type->tp_dictoffset != base->tp_dictoffset) {
245 PyObject **dictptr = _PyObject_GetDictPtr(self);
246 if (dictptr && *dictptr) {
247 err = visit(*dictptr, arg);
248 if (err)
249 return err;
250 }
251 }
252
253 if (f)
254 return f(self, visit, arg);
255 return 0;
256}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000257
258static void
259subtype_dealloc(PyObject *self)
260{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000261 PyTypeObject *type, *base;
262 destructor f;
263
264 /* This exists so we can DECREF self->ob_type */
265
266 /* Find the nearest base with a different tp_dealloc */
267 type = self->ob_type;
268 base = type->tp_base;
269 while ((f = base->tp_dealloc) == subtype_dealloc) {
270 base = base->tp_base;
271 assert(base);
272 }
273
274 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000275 if (type->tp_dictoffset && !base->tp_dictoffset) {
276 PyObject **dictptr = _PyObject_GetDictPtr(self);
277 if (dictptr != NULL) {
278 PyObject *dict = *dictptr;
279 if (dict != NULL) {
280 Py_DECREF(dict);
281 *dictptr = NULL;
282 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000283 }
284 }
285
Guido van Rossum9676b222001-08-17 20:32:36 +0000286 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000287 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000288 PyObject_ClearWeakRefs(self);
289
Tim Peters6d6c1a32001-08-02 04:15:00 +0000290 /* Finalize GC if the base doesn't do GC and we do */
291 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000292 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000293
294 /* Call the base tp_dealloc() */
295 assert(f);
296 f(self);
297
298 /* Can't reference self beyond this point */
299 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
300 Py_DECREF(type);
301 }
302}
303
304staticforward void override_slots(PyTypeObject *type, PyObject *dict);
305staticforward PyTypeObject *solid_base(PyTypeObject *type);
306
307typedef struct {
308 PyTypeObject type;
309 PyNumberMethods as_number;
310 PySequenceMethods as_sequence;
311 PyMappingMethods as_mapping;
312 PyBufferProcs as_buffer;
313 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000314 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000315} etype;
316
317/* type test with subclassing support */
318
319int
320PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
321{
322 PyObject *mro;
323
Guido van Rossum9478d072001-09-07 18:52:13 +0000324 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
325 return b == a || b == &PyBaseObject_Type;
326
Tim Peters6d6c1a32001-08-02 04:15:00 +0000327 mro = a->tp_mro;
328 if (mro != NULL) {
329 /* Deal with multiple inheritance without recursion
330 by walking the MRO tuple */
331 int i, n;
332 assert(PyTuple_Check(mro));
333 n = PyTuple_GET_SIZE(mro);
334 for (i = 0; i < n; i++) {
335 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
336 return 1;
337 }
338 return 0;
339 }
340 else {
341 /* a is not completely initilized yet; follow tp_base */
342 do {
343 if (a == b)
344 return 1;
345 a = a->tp_base;
346 } while (a != NULL);
347 return b == &PyBaseObject_Type;
348 }
349}
350
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000351/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000352 without looking in the instance dictionary
353 (so we can't use PyObject_GetAttr) but still binding
354 it to the instance. The arguments are the object,
355 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000356 static variable used to cache the interned Python string.
357
358 Two variants:
359
360 - lookup_maybe() returns NULL without raising an exception
361 when the _PyType_Lookup() call fails;
362
363 - lookup_method() always raises an exception upon errors.
364*/
Guido van Rossum60718732001-08-28 17:47:51 +0000365
366static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000367lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000368{
369 PyObject *res;
370
371 if (*attrobj == NULL) {
372 *attrobj = PyString_InternFromString(attrstr);
373 if (*attrobj == NULL)
374 return NULL;
375 }
376 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000377 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000378 descrgetfunc f;
379 if ((f = res->ob_type->tp_descr_get) == NULL)
380 Py_INCREF(res);
381 else
382 res = f(res, self, (PyObject *)(self->ob_type));
383 }
384 return res;
385}
386
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000387static PyObject *
388lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
389{
390 PyObject *res = lookup_maybe(self, attrstr, attrobj);
391 if (res == NULL && !PyErr_Occurred())
392 PyErr_SetObject(PyExc_AttributeError, *attrobj);
393 return res;
394}
395
Guido van Rossum2730b132001-08-28 18:22:14 +0000396/* A variation of PyObject_CallMethod that uses lookup_method()
397 instead of PyObject_GetAttrString(). This uses the same convention
398 as lookup_method to cache the interned name string object. */
399
400PyObject *
401call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
402{
403 va_list va;
404 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000405 va_start(va, format);
406
Guido van Rossumda21c012001-10-03 00:50:18 +0000407 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000408 if (func == NULL) {
409 va_end(va);
410 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000411 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000412 return NULL;
413 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000414
415 if (format && *format)
416 args = Py_VaBuildValue(format, va);
417 else
418 args = PyTuple_New(0);
419
420 va_end(va);
421
422 if (args == NULL)
423 return NULL;
424
425 assert(PyTuple_Check(args));
426 retval = PyObject_Call(func, args, NULL);
427
428 Py_DECREF(args);
429 Py_DECREF(func);
430
431 return retval;
432}
433
434/* Clone of call_method() that returns NotImplemented when the lookup fails. */
435
436PyObject *
437call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
438{
439 va_list va;
440 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000441 va_start(va, format);
442
Guido van Rossumda21c012001-10-03 00:50:18 +0000443 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000444 if (func == NULL) {
445 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000446 if (!PyErr_Occurred()) {
447 Py_INCREF(Py_NotImplemented);
448 return Py_NotImplemented;
449 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000450 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000451 }
452
453 if (format && *format)
454 args = Py_VaBuildValue(format, va);
455 else
456 args = PyTuple_New(0);
457
458 va_end(va);
459
Guido van Rossum717ce002001-09-14 16:58:08 +0000460 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000461 return NULL;
462
Guido van Rossum717ce002001-09-14 16:58:08 +0000463 assert(PyTuple_Check(args));
464 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000465
466 Py_DECREF(args);
467 Py_DECREF(func);
468
469 return retval;
470}
471
Tim Peters6d6c1a32001-08-02 04:15:00 +0000472/* Method resolution order algorithm from "Putting Metaclasses to Work"
473 by Forman and Danforth (Addison-Wesley 1999). */
474
475static int
476conservative_merge(PyObject *left, PyObject *right)
477{
478 int left_size;
479 int right_size;
480 int i, j, r, ok;
481 PyObject *temp, *rr;
482
483 assert(PyList_Check(left));
484 assert(PyList_Check(right));
485
486 again:
487 left_size = PyList_GET_SIZE(left);
488 right_size = PyList_GET_SIZE(right);
489 for (i = 0; i < left_size; i++) {
490 for (j = 0; j < right_size; j++) {
491 if (PyList_GET_ITEM(left, i) ==
492 PyList_GET_ITEM(right, j)) {
493 /* found a merge point */
494 temp = PyList_New(0);
495 if (temp == NULL)
496 return -1;
497 for (r = 0; r < j; r++) {
498 rr = PyList_GET_ITEM(right, r);
499 ok = PySequence_Contains(left, rr);
500 if (ok < 0) {
501 Py_DECREF(temp);
502 return -1;
503 }
504 if (!ok) {
505 ok = PyList_Append(temp, rr);
506 if (ok < 0) {
507 Py_DECREF(temp);
508 return -1;
509 }
510 }
511 }
512 ok = PyList_SetSlice(left, i, i, temp);
513 Py_DECREF(temp);
514 if (ok < 0)
515 return -1;
516 ok = PyList_SetSlice(right, 0, j+1, NULL);
517 if (ok < 0)
518 return -1;
519 goto again;
520 }
521 }
522 }
523 return PyList_SetSlice(left, left_size, left_size, right);
524}
525
526static int
527serious_order_disagreements(PyObject *left, PyObject *right)
528{
529 return 0; /* XXX later -- for now, we cheat: "don't do that" */
530}
531
532static PyObject *
533mro_implementation(PyTypeObject *type)
534{
535 int i, n, ok;
536 PyObject *bases, *result;
537
538 bases = type->tp_bases;
539 n = PyTuple_GET_SIZE(bases);
540 result = Py_BuildValue("[O]", (PyObject *)type);
541 if (result == NULL)
542 return NULL;
543 for (i = 0; i < n; i++) {
544 PyTypeObject *base =
545 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
546 PyObject *parentMRO = PySequence_List(base->tp_mro);
547 if (parentMRO == NULL) {
548 Py_DECREF(result);
549 return NULL;
550 }
551 if (serious_order_disagreements(result, parentMRO)) {
552 Py_DECREF(result);
553 return NULL;
554 }
555 ok = conservative_merge(result, parentMRO);
556 Py_DECREF(parentMRO);
557 if (ok < 0) {
558 Py_DECREF(result);
559 return NULL;
560 }
561 }
562 return result;
563}
564
565static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000566mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000567{
568 PyTypeObject *type = (PyTypeObject *)self;
569
Tim Peters6d6c1a32001-08-02 04:15:00 +0000570 return mro_implementation(type);
571}
572
573static int
574mro_internal(PyTypeObject *type)
575{
576 PyObject *mro, *result, *tuple;
577
578 if (type->ob_type == &PyType_Type) {
579 result = mro_implementation(type);
580 }
581 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000582 static PyObject *mro_str;
583 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000584 if (mro == NULL)
585 return -1;
586 result = PyObject_CallObject(mro, NULL);
587 Py_DECREF(mro);
588 }
589 if (result == NULL)
590 return -1;
591 tuple = PySequence_Tuple(result);
592 Py_DECREF(result);
593 type->tp_mro = tuple;
594 return 0;
595}
596
597
598/* Calculate the best base amongst multiple base classes.
599 This is the first one that's on the path to the "solid base". */
600
601static PyTypeObject *
602best_base(PyObject *bases)
603{
604 int i, n;
605 PyTypeObject *base, *winner, *candidate, *base_i;
606
607 assert(PyTuple_Check(bases));
608 n = PyTuple_GET_SIZE(bases);
609 assert(n > 0);
610 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
611 winner = &PyBaseObject_Type;
612 for (i = 0; i < n; i++) {
613 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
614 if (!PyType_Check((PyObject *)base_i)) {
615 PyErr_SetString(
616 PyExc_TypeError,
617 "bases must be types");
618 return NULL;
619 }
620 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000621 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000622 return NULL;
623 }
624 candidate = solid_base(base_i);
625 if (PyType_IsSubtype(winner, candidate))
626 ;
627 else if (PyType_IsSubtype(candidate, winner)) {
628 winner = candidate;
629 base = base_i;
630 }
631 else {
632 PyErr_SetString(
633 PyExc_TypeError,
634 "multiple bases have "
635 "instance lay-out conflict");
636 return NULL;
637 }
638 }
639 assert(base != NULL);
640 return base;
641}
642
643static int
644extra_ivars(PyTypeObject *type, PyTypeObject *base)
645{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000646 size_t t_size = type->tp_basicsize;
647 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000648
Guido van Rossum9676b222001-08-17 20:32:36 +0000649 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000650 if (type->tp_itemsize || base->tp_itemsize) {
651 /* If itemsize is involved, stricter rules */
652 return t_size != b_size ||
653 type->tp_itemsize != base->tp_itemsize;
654 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000655 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
656 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
657 t_size -= sizeof(PyObject *);
658 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
659 type->tp_dictoffset + sizeof(PyObject *) == t_size)
660 t_size -= sizeof(PyObject *);
661
662 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663}
664
665static PyTypeObject *
666solid_base(PyTypeObject *type)
667{
668 PyTypeObject *base;
669
670 if (type->tp_base)
671 base = solid_base(type->tp_base);
672 else
673 base = &PyBaseObject_Type;
674 if (extra_ivars(type, base))
675 return type;
676 else
677 return base;
678}
679
680staticforward void object_dealloc(PyObject *);
681staticforward int object_init(PyObject *, PyObject *, PyObject *);
682
683static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000684subtype_dict(PyObject *obj, void *context)
685{
686 PyObject **dictptr = _PyObject_GetDictPtr(obj);
687 PyObject *dict;
688
689 if (dictptr == NULL) {
690 PyErr_SetString(PyExc_AttributeError,
691 "This object has no __dict__");
692 return NULL;
693 }
694 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000695 if (dict == NULL)
696 *dictptr = dict = PyDict_New();
697 Py_XINCREF(dict);
698 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000699}
700
Guido van Rossum32d34c82001-09-20 21:45:26 +0000701PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000702 {"__dict__", subtype_dict, NULL, NULL},
703 {0},
704};
705
706static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000707type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
708{
709 PyObject *name, *bases, *dict;
710 static char *kwlist[] = {"name", "bases", "dict", 0};
711 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000712 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000713 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000714 PyMemberDef *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000715 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000716
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000717 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718 if (metatype == &PyType_Type &&
719 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
720 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000721 PyObject *x = PyTuple_GET_ITEM(args, 0);
722 Py_INCREF(x->ob_type);
723 return (PyObject *) x->ob_type;
724 }
725
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000726 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000727 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
728 &name,
729 &PyTuple_Type, &bases,
730 &PyDict_Type, &dict))
731 return NULL;
732
733 /* Determine the proper metatype to deal with this,
734 and check for metatype conflicts while we're at it.
735 Note that if some other metatype wins to contract,
736 it's possible that its instances are not types. */
737 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000738 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000739 for (i = 0; i < nbases; i++) {
740 tmp = PyTuple_GET_ITEM(bases, i);
741 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000742 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000743 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000744 if (PyType_IsSubtype(tmptype, winner)) {
745 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000746 continue;
747 }
748 PyErr_SetString(PyExc_TypeError,
749 "metatype conflict among bases");
750 return NULL;
751 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000752 if (winner != metatype) {
753 if (winner->tp_new != type_new) /* Pass it to the winner */
754 return winner->tp_new(winner, args, kwds);
755 metatype = winner;
756 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000757
758 /* Adjust for empty tuple bases */
759 if (nbases == 0) {
760 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
761 if (bases == NULL)
762 return NULL;
763 nbases = 1;
764 }
765 else
766 Py_INCREF(bases);
767
768 /* XXX From here until type is allocated, "return NULL" leaks bases! */
769
770 /* Calculate best base, and check that all bases are type objects */
771 base = best_base(bases);
772 if (base == NULL)
773 return NULL;
774 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
775 PyErr_Format(PyExc_TypeError,
776 "type '%.100s' is not an acceptable base type",
777 base->tp_name);
778 return NULL;
779 }
780
Guido van Rossum1a493502001-08-17 16:47:50 +0000781 /* Should this be a dynamic class (i.e. modifiable __dict__)?
782 Look in two places for a variable named __dynamic__:
783 1) in the class dict
784 2) in the module dict (globals)
785 The first variable that is an int >= 0 is used.
Guido van Rossum50fda3b2001-10-04 19:46:06 +0000786 Otherwise, the default is dynamic. */
Guido van Rossum1a493502001-08-17 16:47:50 +0000787 dynamic = -1; /* Not yet determined */
788 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000789 tmp = PyDict_GetItemString(dict, "__dynamic__");
790 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000791 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000792 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000793 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000794 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000795 if (dynamic < 0) {
796 /* Look in the module globals */
797 tmp = PyEval_GetGlobals();
798 if (tmp != NULL) {
799 tmp = PyDict_GetItemString(tmp, "__dynamic__");
800 if (tmp != NULL) {
801 dynamic = PyInt_AsLong(tmp);
802 if (dynamic < 0)
803 PyErr_Clear();
804 }
805 }
806 }
807 if (dynamic < 0) {
Guido van Rossum50fda3b2001-10-04 19:46:06 +0000808 /* Default to dynamic */
809 dynamic = 1;
810
Tim Peters6d6c1a32001-08-02 04:15:00 +0000811 }
812
813 /* Check for a __slots__ sequence variable in dict, and count it */
814 slots = PyDict_GetItemString(dict, "__slots__");
815 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000816 add_dict = 0;
817 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000818 if (slots != NULL) {
819 /* Make it into a tuple */
820 if (PyString_Check(slots))
821 slots = Py_BuildValue("(O)", slots);
822 else
823 slots = PySequence_Tuple(slots);
824 if (slots == NULL)
825 return NULL;
826 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000827 if (nslots > 0 && base->tp_itemsize != 0) {
828 PyErr_Format(PyExc_TypeError,
829 "nonempty __slots__ "
830 "not supported for subtype of '%s'",
831 base->tp_name);
832 return NULL;
833 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834 for (i = 0; i < nslots; i++) {
835 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
836 PyErr_SetString(PyExc_TypeError,
837 "__slots__ must be a sequence of strings");
838 Py_DECREF(slots);
839 return NULL;
840 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000841 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842 }
843 }
844 if (slots == NULL && base->tp_dictoffset == 0 &&
845 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000846 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000847 add_dict++;
848 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000849 if (slots == NULL && base->tp_weaklistoffset == 0 &&
850 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000851 nslots++;
852 add_weak++;
853 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000854
855 /* XXX From here until type is safely allocated,
856 "return NULL" may leak slots! */
857
858 /* Allocate the type object */
859 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
860 if (type == NULL)
861 return NULL;
862
863 /* Keep name and slots alive in the extended type object */
864 et = (etype *)type;
865 Py_INCREF(name);
866 et->name = name;
867 et->slots = slots;
868
Guido van Rossumdc91b992001-08-08 22:26:22 +0000869 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000870 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
871 Py_TPFLAGS_BASETYPE;
872 if (dynamic)
873 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000874 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
875 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000876
877 /* It's a new-style number unless it specifically inherits any
878 old-style numeric behavior */
879 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
880 (base->tp_as_number == NULL))
881 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
882
883 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000884 type->tp_as_number = &et->as_number;
885 type->tp_as_sequence = &et->as_sequence;
886 type->tp_as_mapping = &et->as_mapping;
887 type->tp_as_buffer = &et->as_buffer;
888 type->tp_name = PyString_AS_STRING(name);
889
890 /* Set tp_base and tp_bases */
891 type->tp_bases = bases;
892 Py_INCREF(base);
893 type->tp_base = base;
894
895 /* Initialize tp_defined from passed-in dict */
896 type->tp_defined = dict = PyDict_Copy(dict);
897 if (dict == NULL) {
898 Py_DECREF(type);
899 return NULL;
900 }
901
Guido van Rossumc3542212001-08-16 09:18:56 +0000902 /* Set __module__ in the dict */
903 if (PyDict_GetItemString(dict, "__module__") == NULL) {
904 tmp = PyEval_GetGlobals();
905 if (tmp != NULL) {
906 tmp = PyDict_GetItemString(tmp, "__name__");
907 if (tmp != NULL) {
908 if (PyDict_SetItemString(dict, "__module__",
909 tmp) < 0)
910 return NULL;
911 }
912 }
913 }
914
Tim Peters2f93e282001-10-04 05:27:00 +0000915 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
916 and is a string (tp_doc is a char* -- can't copy a general object
917 into it).
918 XXX What if it's a Unicode string? Don't know -- this ignores it.
919 */
920 {
921 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
922 if (doc != NULL && PyString_Check(doc)) {
923 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +0000924 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +0000925 if (type->tp_doc == NULL) {
926 Py_DECREF(type);
927 return NULL;
928 }
929 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
930 }
931 }
932
Tim Peters6d6c1a32001-08-02 04:15:00 +0000933 /* Special-case __new__: if it's a plain function,
934 make it a static function */
935 tmp = PyDict_GetItemString(dict, "__new__");
936 if (tmp != NULL && PyFunction_Check(tmp)) {
937 tmp = PyStaticMethod_New(tmp);
938 if (tmp == NULL) {
939 Py_DECREF(type);
940 return NULL;
941 }
942 PyDict_SetItemString(dict, "__new__", tmp);
943 Py_DECREF(tmp);
944 }
945
946 /* Add descriptors for custom slots from __slots__, or for __dict__ */
947 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000948 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000949 if (slots != NULL) {
950 for (i = 0; i < nslots; i++, mp++) {
951 mp->name = PyString_AS_STRING(
952 PyTuple_GET_ITEM(slots, i));
953 mp->type = T_OBJECT;
954 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000955 if (base->tp_weaklistoffset == 0 &&
956 strcmp(mp->name, "__weakref__") == 0)
957 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000958 slotoffset += sizeof(PyObject *);
959 }
960 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000961 else {
962 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000963 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +0000964 type->tp_dictoffset =
965 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000966 else
967 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000968 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000969 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000970 }
971 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000972 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000973 type->tp_weaklistoffset = slotoffset;
974 mp->name = "__weakref__";
975 mp->type = T_OBJECT;
976 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000977 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000978 mp++;
979 slotoffset += sizeof(PyObject *);
980 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000981 }
982 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000983 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000984 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985
986 /* Special case some slots */
987 if (type->tp_dictoffset != 0 || nslots > 0) {
988 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
989 type->tp_getattro = PyObject_GenericGetAttr;
990 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
991 type->tp_setattro = PyObject_GenericSetAttr;
992 }
993 type->tp_dealloc = subtype_dealloc;
994
Guido van Rossum9475a232001-10-05 20:51:39 +0000995 /* Enable GC unless there are really no instance variables possible */
996 if (!(type->tp_basicsize == sizeof(PyObject) &&
997 type->tp_itemsize == 0))
998 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
999
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000 /* Always override allocation strategy to use regular heap */
1001 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001002 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1003 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001004 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001005 type->tp_clear = base->tp_clear;
1006 }
1007 else
1008 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001009
1010 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001011 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001012 Py_DECREF(type);
1013 return NULL;
1014 }
1015
1016 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +00001017 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
1018 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001019
Tim Peters6d6c1a32001-08-02 04:15:00 +00001020 return (PyObject *)type;
1021}
1022
1023/* Internal API to look for a name through the MRO.
1024 This returns a borrowed reference, and doesn't set an exception! */
1025PyObject *
1026_PyType_Lookup(PyTypeObject *type, PyObject *name)
1027{
1028 int i, n;
1029 PyObject *mro, *res, *dict;
1030
1031 /* For static types, look in tp_dict */
1032 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
1033 dict = type->tp_dict;
1034 assert(dict && PyDict_Check(dict));
1035 return PyDict_GetItem(dict, name);
1036 }
1037
1038 /* For dynamic types, look in tp_defined of types in MRO */
1039 mro = type->tp_mro;
1040 assert(PyTuple_Check(mro));
1041 n = PyTuple_GET_SIZE(mro);
1042 for (i = 0; i < n; i++) {
1043 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
1044 assert(PyType_Check(type));
1045 dict = type->tp_defined;
1046 assert(dict && PyDict_Check(dict));
1047 res = PyDict_GetItem(dict, name);
1048 if (res != NULL)
1049 return res;
1050 }
1051 return NULL;
1052}
1053
1054/* This is similar to PyObject_GenericGetAttr(),
1055 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1056static PyObject *
1057type_getattro(PyTypeObject *type, PyObject *name)
1058{
1059 PyTypeObject *metatype = type->ob_type;
1060 PyObject *descr, *res;
1061 descrgetfunc f;
1062
1063 /* Initialize this type (we'll assume the metatype is initialized) */
1064 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001065 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066 return NULL;
1067 }
1068
1069 /* Get a descriptor from the metatype */
1070 descr = _PyType_Lookup(metatype, name);
1071 f = NULL;
1072 if (descr != NULL) {
1073 f = descr->ob_type->tp_descr_get;
1074 if (f != NULL && PyDescr_IsData(descr))
1075 return f(descr,
1076 (PyObject *)type, (PyObject *)metatype);
1077 }
1078
1079 /* Look in tp_defined of this type and its bases */
1080 res = _PyType_Lookup(type, name);
1081 if (res != NULL) {
1082 f = res->ob_type->tp_descr_get;
1083 if (f != NULL)
1084 return f(res, (PyObject *)NULL, (PyObject *)type);
1085 Py_INCREF(res);
1086 return res;
1087 }
1088
1089 /* Use the descriptor from the metatype */
1090 if (f != NULL) {
1091 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1092 return res;
1093 }
1094 if (descr != NULL) {
1095 Py_INCREF(descr);
1096 return descr;
1097 }
1098
1099 /* Give up */
1100 PyErr_Format(PyExc_AttributeError,
1101 "type object '%.50s' has no attribute '%.400s'",
1102 type->tp_name, PyString_AS_STRING(name));
1103 return NULL;
1104}
1105
1106static int
1107type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1108{
1109 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
1110 return PyObject_GenericSetAttr((PyObject *)type, name, value);
1111 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
1112 return -1;
1113}
1114
1115static void
1116type_dealloc(PyTypeObject *type)
1117{
1118 etype *et;
1119
1120 /* Assert this is a heap-allocated type object */
1121 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001122 _PyObject_GC_UNTRACK(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 et = (etype *)type;
1124 Py_XDECREF(type->tp_base);
1125 Py_XDECREF(type->tp_dict);
1126 Py_XDECREF(type->tp_bases);
1127 Py_XDECREF(type->tp_mro);
1128 Py_XDECREF(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001129 Py_XDECREF(et->name);
1130 Py_XDECREF(et->slots);
1131 type->ob_type->tp_free((PyObject *)type);
1132}
1133
1134static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001135 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001136 "mro() -> list\nreturn a type's method resolution order"},
1137 {0}
1138};
1139
1140static char type_doc[] =
1141"type(object) -> the object's type\n"
1142"type(name, bases, dict) -> a new type";
1143
Guido van Rossum048eb752001-10-02 21:24:57 +00001144static int
1145type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1146{
1147 etype *et;
1148 int err;
1149
1150 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1151 return 0;
1152
1153 et = (etype *)type;
1154
1155#define VISIT(SLOT) \
1156 if (SLOT) { \
1157 err = visit((PyObject *)(SLOT), arg); \
1158 if (err) \
1159 return err; \
1160 }
1161
1162 VISIT(type->tp_dict);
1163 VISIT(type->tp_defined);
1164 VISIT(type->tp_mro);
1165 VISIT(type->tp_bases);
1166 VISIT(type->tp_base);
1167 VISIT(et->slots);
1168
1169#undef VISIT
1170
1171 return 0;
1172}
1173
1174static int
1175type_clear(PyTypeObject *type)
1176{
1177 etype *et;
1178 PyObject *tmp;
1179
1180 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1181 return 0;
1182
1183 et = (etype *)type;
1184
1185#define CLEAR(SLOT) \
1186 if (SLOT) { \
1187 tmp = (PyObject *)(SLOT); \
1188 SLOT = NULL; \
1189 Py_DECREF(tmp); \
1190 }
1191
1192 CLEAR(type->tp_dict);
1193 CLEAR(type->tp_defined);
1194 CLEAR(type->tp_mro);
1195 CLEAR(type->tp_bases);
1196 CLEAR(type->tp_base);
1197 CLEAR(et->slots);
1198
Tim Peters2f93e282001-10-04 05:27:00 +00001199 if (type->tp_doc != NULL) {
1200 PyObject_FREE(type->tp_doc);
1201 type->tp_doc = NULL;
1202 }
1203
Guido van Rossum048eb752001-10-02 21:24:57 +00001204#undef CLEAR
1205
1206 return 0;
1207}
1208
1209static int
1210type_is_gc(PyTypeObject *type)
1211{
1212 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1213}
1214
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001215PyTypeObject PyType_Type = {
1216 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001217 0, /* ob_size */
1218 "type", /* tp_name */
1219 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001220 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221 (destructor)type_dealloc, /* tp_dealloc */
1222 0, /* tp_print */
1223 0, /* tp_getattr */
1224 0, /* tp_setattr */
1225 type_compare, /* tp_compare */
1226 (reprfunc)type_repr, /* tp_repr */
1227 0, /* tp_as_number */
1228 0, /* tp_as_sequence */
1229 0, /* tp_as_mapping */
1230 (hashfunc)_Py_HashPointer, /* tp_hash */
1231 (ternaryfunc)type_call, /* tp_call */
1232 0, /* tp_str */
1233 (getattrofunc)type_getattro, /* tp_getattro */
1234 (setattrofunc)type_setattro, /* tp_setattro */
1235 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001236 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1237 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001238 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001239 (traverseproc)type_traverse, /* tp_traverse */
1240 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001241 0, /* tp_richcompare */
1242 0, /* tp_weaklistoffset */
1243 0, /* tp_iter */
1244 0, /* tp_iternext */
1245 type_methods, /* tp_methods */
1246 type_members, /* tp_members */
1247 type_getsets, /* tp_getset */
1248 0, /* tp_base */
1249 0, /* tp_dict */
1250 0, /* tp_descr_get */
1251 0, /* tp_descr_set */
1252 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1253 0, /* tp_init */
1254 0, /* tp_alloc */
1255 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001256 _PyObject_GC_Del, /* tp_free */
1257 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001258};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001259
1260
1261/* The base type of all types (eventually)... except itself. */
1262
1263static int
1264object_init(PyObject *self, PyObject *args, PyObject *kwds)
1265{
1266 return 0;
1267}
1268
1269static void
1270object_dealloc(PyObject *self)
1271{
1272 self->ob_type->tp_free(self);
1273}
1274
Guido van Rossum8e248182001-08-12 05:17:56 +00001275static PyObject *
1276object_repr(PyObject *self)
1277{
Guido van Rossum76e69632001-08-16 18:52:43 +00001278 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001279 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001280
Guido van Rossum76e69632001-08-16 18:52:43 +00001281 type = self->ob_type;
1282 mod = type_module(type, NULL);
1283 if (mod == NULL)
1284 PyErr_Clear();
1285 else if (!PyString_Check(mod)) {
1286 Py_DECREF(mod);
1287 mod = NULL;
1288 }
1289 name = type_name(type, NULL);
1290 if (name == NULL)
1291 return NULL;
1292 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001293 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001294 PyString_AS_STRING(mod),
1295 PyString_AS_STRING(name),
1296 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001297 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001298 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001299 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001300 Py_XDECREF(mod);
1301 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001302 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001303}
1304
Guido van Rossumb8f63662001-08-15 23:57:02 +00001305static PyObject *
1306object_str(PyObject *self)
1307{
1308 unaryfunc f;
1309
1310 f = self->ob_type->tp_repr;
1311 if (f == NULL)
1312 f = object_repr;
1313 return f(self);
1314}
1315
Guido van Rossum8e248182001-08-12 05:17:56 +00001316static long
1317object_hash(PyObject *self)
1318{
1319 return _Py_HashPointer(self);
1320}
Guido van Rossum8e248182001-08-12 05:17:56 +00001321
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001322static PyObject *
1323object_get_class(PyObject *self, void *closure)
1324{
1325 Py_INCREF(self->ob_type);
1326 return (PyObject *)(self->ob_type);
1327}
1328
1329static int
1330equiv_structs(PyTypeObject *a, PyTypeObject *b)
1331{
1332 return a == b ||
1333 (a != NULL &&
1334 b != NULL &&
1335 a->tp_basicsize == b->tp_basicsize &&
1336 a->tp_itemsize == b->tp_itemsize &&
1337 a->tp_dictoffset == b->tp_dictoffset &&
1338 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1339 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1340 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1341}
1342
1343static int
1344same_slots_added(PyTypeObject *a, PyTypeObject *b)
1345{
1346 PyTypeObject *base = a->tp_base;
1347 int size;
1348
1349 if (base != b->tp_base)
1350 return 0;
1351 if (equiv_structs(a, base) && equiv_structs(b, base))
1352 return 1;
1353 size = base->tp_basicsize;
1354 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1355 size += sizeof(PyObject *);
1356 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1357 size += sizeof(PyObject *);
1358 return size == a->tp_basicsize && size == b->tp_basicsize;
1359}
1360
1361static int
1362object_set_class(PyObject *self, PyObject *value, void *closure)
1363{
1364 PyTypeObject *old = self->ob_type;
1365 PyTypeObject *new, *newbase, *oldbase;
1366
1367 if (!PyType_Check(value)) {
1368 PyErr_Format(PyExc_TypeError,
1369 "__class__ must be set to new-style class, not '%s' object",
1370 value->ob_type->tp_name);
1371 return -1;
1372 }
1373 new = (PyTypeObject *)value;
1374 newbase = new;
1375 oldbase = old;
1376 while (equiv_structs(newbase, newbase->tp_base))
1377 newbase = newbase->tp_base;
1378 while (equiv_structs(oldbase, oldbase->tp_base))
1379 oldbase = oldbase->tp_base;
1380 if (newbase != oldbase &&
1381 (newbase->tp_base != oldbase->tp_base ||
1382 !same_slots_added(newbase, oldbase))) {
1383 PyErr_Format(PyExc_TypeError,
1384 "__class__ assignment: "
1385 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001386 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001387 old->tp_name);
1388 return -1;
1389 }
1390 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1391 Py_INCREF(new);
1392 }
1393 self->ob_type = new;
1394 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1395 Py_DECREF(old);
1396 }
1397 return 0;
1398}
1399
1400static PyGetSetDef object_getsets[] = {
1401 {"__class__", object_get_class, object_set_class,
1402 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001403 {0}
1404};
1405
Guido van Rossum3926a632001-09-25 16:25:58 +00001406static PyObject *
1407object_reduce(PyObject *self, PyObject *args)
1408{
1409 /* Call copy_reg._reduce(self) */
1410 static PyObject *copy_reg_str;
1411 PyObject *copy_reg, *res;
1412
1413 if (!copy_reg_str) {
1414 copy_reg_str = PyString_InternFromString("copy_reg");
1415 if (copy_reg_str == NULL)
1416 return NULL;
1417 }
1418 copy_reg = PyImport_Import(copy_reg_str);
1419 if (!copy_reg)
1420 return NULL;
1421 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1422 Py_DECREF(copy_reg);
1423 return res;
1424}
1425
1426static PyMethodDef object_methods[] = {
1427 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1428 {0}
1429};
1430
Tim Peters6d6c1a32001-08-02 04:15:00 +00001431PyTypeObject PyBaseObject_Type = {
1432 PyObject_HEAD_INIT(&PyType_Type)
1433 0, /* ob_size */
1434 "object", /* tp_name */
1435 sizeof(PyObject), /* tp_basicsize */
1436 0, /* tp_itemsize */
1437 (destructor)object_dealloc, /* tp_dealloc */
1438 0, /* tp_print */
1439 0, /* tp_getattr */
1440 0, /* tp_setattr */
1441 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001442 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001443 0, /* tp_as_number */
1444 0, /* tp_as_sequence */
1445 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001446 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001447 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001448 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001449 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001450 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001451 0, /* tp_as_buffer */
1452 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1453 "The most base type", /* tp_doc */
1454 0, /* tp_traverse */
1455 0, /* tp_clear */
1456 0, /* tp_richcompare */
1457 0, /* tp_weaklistoffset */
1458 0, /* tp_iter */
1459 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001460 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001461 0, /* tp_members */
1462 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463 0, /* tp_base */
1464 0, /* tp_dict */
1465 0, /* tp_descr_get */
1466 0, /* tp_descr_set */
1467 0, /* tp_dictoffset */
1468 object_init, /* tp_init */
1469 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001470 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001471 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472};
1473
1474
1475/* Initialize the __dict__ in a type object */
1476
1477static int
1478add_methods(PyTypeObject *type, PyMethodDef *meth)
1479{
1480 PyObject *dict = type->tp_defined;
1481
1482 for (; meth->ml_name != NULL; meth++) {
1483 PyObject *descr;
1484 if (PyDict_GetItemString(dict, meth->ml_name))
1485 continue;
1486 descr = PyDescr_NewMethod(type, meth);
1487 if (descr == NULL)
1488 return -1;
1489 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1490 return -1;
1491 Py_DECREF(descr);
1492 }
1493 return 0;
1494}
1495
1496static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001497add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001498{
1499 PyObject *dict = type->tp_defined;
1500
1501 for (; memb->name != NULL; memb++) {
1502 PyObject *descr;
1503 if (PyDict_GetItemString(dict, memb->name))
1504 continue;
1505 descr = PyDescr_NewMember(type, memb);
1506 if (descr == NULL)
1507 return -1;
1508 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1509 return -1;
1510 Py_DECREF(descr);
1511 }
1512 return 0;
1513}
1514
1515static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001516add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517{
1518 PyObject *dict = type->tp_defined;
1519
1520 for (; gsp->name != NULL; gsp++) {
1521 PyObject *descr;
1522 if (PyDict_GetItemString(dict, gsp->name))
1523 continue;
1524 descr = PyDescr_NewGetSet(type, gsp);
1525
1526 if (descr == NULL)
1527 return -1;
1528 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1529 return -1;
1530 Py_DECREF(descr);
1531 }
1532 return 0;
1533}
1534
Guido van Rossum13d52f02001-08-10 21:24:08 +00001535static void
1536inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001537{
1538 int oldsize, newsize;
1539
Guido van Rossum13d52f02001-08-10 21:24:08 +00001540 /* Special flag magic */
1541 if (!type->tp_as_buffer && base->tp_as_buffer) {
1542 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1543 type->tp_flags |=
1544 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1545 }
1546 if (!type->tp_as_sequence && base->tp_as_sequence) {
1547 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1548 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1549 }
1550 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1551 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1552 if ((!type->tp_as_number && base->tp_as_number) ||
1553 (!type->tp_as_sequence && base->tp_as_sequence)) {
1554 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1555 if (!type->tp_as_number && !type->tp_as_sequence) {
1556 type->tp_flags |= base->tp_flags &
1557 Py_TPFLAGS_HAVE_INPLACEOPS;
1558 }
1559 }
1560 /* Wow */
1561 }
1562 if (!type->tp_as_number && base->tp_as_number) {
1563 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1564 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1565 }
1566
1567 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001568 oldsize = base->tp_basicsize;
1569 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1570 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1571 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001572 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1573 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001574 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001575 if (type->tp_traverse == NULL)
1576 type->tp_traverse = base->tp_traverse;
1577 if (type->tp_clear == NULL)
1578 type->tp_clear = base->tp_clear;
1579 }
1580 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1581 if (base != &PyBaseObject_Type ||
1582 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1583 if (type->tp_new == NULL)
1584 type->tp_new = base->tp_new;
1585 }
1586 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001587 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001588
1589 /* Copy other non-function slots */
1590
1591#undef COPYVAL
1592#define COPYVAL(SLOT) \
1593 if (type->SLOT == 0) type->SLOT = base->SLOT
1594
1595 COPYVAL(tp_itemsize);
1596 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1597 COPYVAL(tp_weaklistoffset);
1598 }
1599 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1600 COPYVAL(tp_dictoffset);
1601 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001602}
1603
1604static void
1605inherit_slots(PyTypeObject *type, PyTypeObject *base)
1606{
1607 PyTypeObject *basebase;
1608
1609#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001610#undef COPYSLOT
1611#undef COPYNUM
1612#undef COPYSEQ
1613#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001614
1615#define SLOTDEFINED(SLOT) \
1616 (base->SLOT != 0 && \
1617 (basebase == NULL || base->SLOT != basebase->SLOT))
1618
Tim Peters6d6c1a32001-08-02 04:15:00 +00001619#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001620 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001621
1622#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1623#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1624#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1625
Guido van Rossum13d52f02001-08-10 21:24:08 +00001626 /* This won't inherit indirect slots (from tp_as_number etc.)
1627 if type doesn't provide the space. */
1628
1629 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1630 basebase = base->tp_base;
1631 if (basebase->tp_as_number == NULL)
1632 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001633 COPYNUM(nb_add);
1634 COPYNUM(nb_subtract);
1635 COPYNUM(nb_multiply);
1636 COPYNUM(nb_divide);
1637 COPYNUM(nb_remainder);
1638 COPYNUM(nb_divmod);
1639 COPYNUM(nb_power);
1640 COPYNUM(nb_negative);
1641 COPYNUM(nb_positive);
1642 COPYNUM(nb_absolute);
1643 COPYNUM(nb_nonzero);
1644 COPYNUM(nb_invert);
1645 COPYNUM(nb_lshift);
1646 COPYNUM(nb_rshift);
1647 COPYNUM(nb_and);
1648 COPYNUM(nb_xor);
1649 COPYNUM(nb_or);
1650 COPYNUM(nb_coerce);
1651 COPYNUM(nb_int);
1652 COPYNUM(nb_long);
1653 COPYNUM(nb_float);
1654 COPYNUM(nb_oct);
1655 COPYNUM(nb_hex);
1656 COPYNUM(nb_inplace_add);
1657 COPYNUM(nb_inplace_subtract);
1658 COPYNUM(nb_inplace_multiply);
1659 COPYNUM(nb_inplace_divide);
1660 COPYNUM(nb_inplace_remainder);
1661 COPYNUM(nb_inplace_power);
1662 COPYNUM(nb_inplace_lshift);
1663 COPYNUM(nb_inplace_rshift);
1664 COPYNUM(nb_inplace_and);
1665 COPYNUM(nb_inplace_xor);
1666 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001667 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1668 COPYNUM(nb_true_divide);
1669 COPYNUM(nb_floor_divide);
1670 COPYNUM(nb_inplace_true_divide);
1671 COPYNUM(nb_inplace_floor_divide);
1672 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001673 }
1674
Guido van Rossum13d52f02001-08-10 21:24:08 +00001675 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1676 basebase = base->tp_base;
1677 if (basebase->tp_as_sequence == NULL)
1678 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679 COPYSEQ(sq_length);
1680 COPYSEQ(sq_concat);
1681 COPYSEQ(sq_repeat);
1682 COPYSEQ(sq_item);
1683 COPYSEQ(sq_slice);
1684 COPYSEQ(sq_ass_item);
1685 COPYSEQ(sq_ass_slice);
1686 COPYSEQ(sq_contains);
1687 COPYSEQ(sq_inplace_concat);
1688 COPYSEQ(sq_inplace_repeat);
1689 }
1690
Guido van Rossum13d52f02001-08-10 21:24:08 +00001691 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1692 basebase = base->tp_base;
1693 if (basebase->tp_as_mapping == NULL)
1694 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001695 COPYMAP(mp_length);
1696 COPYMAP(mp_subscript);
1697 COPYMAP(mp_ass_subscript);
1698 }
1699
Guido van Rossum13d52f02001-08-10 21:24:08 +00001700 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001701
Tim Peters6d6c1a32001-08-02 04:15:00 +00001702 COPYSLOT(tp_dealloc);
1703 COPYSLOT(tp_print);
1704 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1705 type->tp_getattr = base->tp_getattr;
1706 type->tp_getattro = base->tp_getattro;
1707 }
1708 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1709 type->tp_setattr = base->tp_setattr;
1710 type->tp_setattro = base->tp_setattro;
1711 }
1712 /* tp_compare see tp_richcompare */
1713 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001714 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715 COPYSLOT(tp_call);
1716 COPYSLOT(tp_str);
1717 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001718 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001719 if (type->tp_compare == NULL &&
1720 type->tp_richcompare == NULL &&
1721 type->tp_hash == NULL)
1722 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001723 type->tp_compare = base->tp_compare;
1724 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001725 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726 }
1727 }
1728 else {
1729 COPYSLOT(tp_compare);
1730 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001731 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1732 COPYSLOT(tp_iter);
1733 COPYSLOT(tp_iternext);
1734 }
1735 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1736 COPYSLOT(tp_descr_get);
1737 COPYSLOT(tp_descr_set);
1738 COPYSLOT(tp_dictoffset);
1739 COPYSLOT(tp_init);
1740 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001741 COPYSLOT(tp_free);
1742 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001743}
1744
Guido van Rossum13d52f02001-08-10 21:24:08 +00001745staticforward int add_operators(PyTypeObject *);
1746
Tim Peters6d6c1a32001-08-02 04:15:00 +00001747int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001748PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001749{
1750 PyObject *dict, *bases, *x;
1751 PyTypeObject *base;
1752 int i, n;
1753
Guido van Rossumd614f972001-08-10 17:39:49 +00001754 if (type->tp_flags & Py_TPFLAGS_READY) {
1755 assert(type->tp_dict != NULL);
1756 return 0;
1757 }
1758 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1759 assert(type->tp_dict == NULL);
1760
1761 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762
1763 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1764 base = type->tp_base;
1765 if (base == NULL && type != &PyBaseObject_Type)
1766 base = type->tp_base = &PyBaseObject_Type;
1767
1768 /* Initialize tp_bases */
1769 bases = type->tp_bases;
1770 if (bases == NULL) {
1771 if (base == NULL)
1772 bases = PyTuple_New(0);
1773 else
1774 bases = Py_BuildValue("(O)", base);
1775 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001776 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777 type->tp_bases = bases;
1778 }
1779
1780 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001781 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001782 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001783 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001784 }
1785
1786 /* Initialize tp_defined */
1787 dict = type->tp_defined;
1788 if (dict == NULL) {
1789 dict = PyDict_New();
1790 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001791 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001792 type->tp_defined = dict;
1793 }
1794
1795 /* Add type-specific descriptors to tp_defined */
1796 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001797 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798 if (type->tp_methods != NULL) {
1799 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001800 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001801 }
1802 if (type->tp_members != NULL) {
1803 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001804 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001805 }
1806 if (type->tp_getset != NULL) {
1807 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001808 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001809 }
1810
1811 /* Temporarily make tp_dict the same object as tp_defined.
1812 (This is needed to call mro(), and can stay this way for
1813 dynamic types). */
1814 Py_INCREF(type->tp_defined);
1815 type->tp_dict = type->tp_defined;
1816
1817 /* Calculate method resolution order */
1818 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001819 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001820 }
1821
Guido van Rossum13d52f02001-08-10 21:24:08 +00001822 /* Inherit special flags from dominant base */
1823 if (type->tp_base != NULL)
1824 inherit_special(type, type->tp_base);
1825
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001827 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001828 /* For a dynamic type, all slots are overridden */
1829 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001830 }
1831 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001832 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001833 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001835 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001837 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001838 bases = type->tp_mro;
1839 assert(bases != NULL);
1840 assert(PyTuple_Check(bases));
1841 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001842 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001843 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1844 assert(PyType_Check(base));
1845 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001846 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001847 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001848 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001849 }
1850 }
1851
Guido van Rossum13d52f02001-08-10 21:24:08 +00001852 /* Some more special stuff */
1853 base = type->tp_base;
1854 if (base != NULL) {
1855 if (type->tp_as_number == NULL)
1856 type->tp_as_number = base->tp_as_number;
1857 if (type->tp_as_sequence == NULL)
1858 type->tp_as_sequence = base->tp_as_sequence;
1859 if (type->tp_as_mapping == NULL)
1860 type->tp_as_mapping = base->tp_as_mapping;
1861 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001862
Guido van Rossum13d52f02001-08-10 21:24:08 +00001863 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001864 assert(type->tp_dict != NULL);
1865 type->tp_flags =
1866 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001868
1869 error:
1870 type->tp_flags &= ~Py_TPFLAGS_READYING;
1871 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001872}
1873
1874
1875/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1876
1877/* There's a wrapper *function* for each distinct function typedef used
1878 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1879 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1880 Most tables have only one entry; the tables for binary operators have two
1881 entries, one regular and one with reversed arguments. */
1882
1883static PyObject *
1884wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1885{
1886 inquiry func = (inquiry)wrapped;
1887 int res;
1888
1889 if (!PyArg_ParseTuple(args, ""))
1890 return NULL;
1891 res = (*func)(self);
1892 if (res == -1 && PyErr_Occurred())
1893 return NULL;
1894 return PyInt_FromLong((long)res);
1895}
1896
1897static struct wrapperbase tab_len[] = {
1898 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1899 {0}
1900};
1901
1902static PyObject *
1903wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1904{
1905 binaryfunc func = (binaryfunc)wrapped;
1906 PyObject *other;
1907
1908 if (!PyArg_ParseTuple(args, "O", &other))
1909 return NULL;
1910 return (*func)(self, other);
1911}
1912
1913static PyObject *
1914wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1915{
1916 binaryfunc func = (binaryfunc)wrapped;
1917 PyObject *other;
1918
1919 if (!PyArg_ParseTuple(args, "O", &other))
1920 return NULL;
1921 return (*func)(other, self);
1922}
1923
1924#undef BINARY
1925#define BINARY(NAME, OP) \
1926static struct wrapperbase tab_##NAME[] = { \
1927 {"__" #NAME "__", \
1928 (wrapperfunc)wrap_binaryfunc, \
1929 "x.__" #NAME "__(y) <==> " #OP}, \
1930 {"__r" #NAME "__", \
1931 (wrapperfunc)wrap_binaryfunc_r, \
1932 "y.__r" #NAME "__(x) <==> " #OP}, \
1933 {0} \
1934}
1935
1936BINARY(add, "x+y");
1937BINARY(sub, "x-y");
1938BINARY(mul, "x*y");
1939BINARY(div, "x/y");
1940BINARY(mod, "x%y");
1941BINARY(divmod, "divmod(x,y)");
1942BINARY(lshift, "x<<y");
1943BINARY(rshift, "x>>y");
1944BINARY(and, "x&y");
1945BINARY(xor, "x^y");
1946BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00001947
1948static PyObject *
1949wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
1950{
1951 coercion func = (coercion)wrapped;
1952 PyObject *other, *res;
1953 int ok;
1954
1955 if (!PyArg_ParseTuple(args, "O", &other))
1956 return NULL;
1957 ok = func(&self, &other);
1958 if (ok < 0)
1959 return NULL;
1960 if (ok > 0) {
1961 Py_INCREF(Py_NotImplemented);
1962 return Py_NotImplemented;
1963 }
1964 res = PyTuple_New(2);
1965 if (res == NULL) {
1966 Py_DECREF(self);
1967 Py_DECREF(other);
1968 return NULL;
1969 }
1970 PyTuple_SET_ITEM(res, 0, self);
1971 PyTuple_SET_ITEM(res, 1, other);
1972 return res;
1973}
1974
1975static struct wrapperbase tab_coerce[] = {
1976 {"__coerce__", (wrapperfunc)wrap_coercefunc,
1977 "x.__coerce__(y) <==> coerce(x, y)"},
1978 {0}
1979};
1980
Guido van Rossum874f15a2001-09-25 21:16:33 +00001981BINARY(floordiv, "x//y");
1982BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001983
1984static PyObject *
1985wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1986{
1987 ternaryfunc func = (ternaryfunc)wrapped;
1988 PyObject *other;
1989 PyObject *third = Py_None;
1990
1991 /* Note: This wrapper only works for __pow__() */
1992
1993 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1994 return NULL;
1995 return (*func)(self, other, third);
1996}
1997
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00001998static PyObject *
1999wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2000{
2001 ternaryfunc func = (ternaryfunc)wrapped;
2002 PyObject *other;
2003 PyObject *third = Py_None;
2004
2005 /* Note: This wrapper only works for __pow__() */
2006
2007 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2008 return NULL;
2009 return (*func)(other, self, third);
2010}
2011
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012#undef TERNARY
2013#define TERNARY(NAME, OP) \
2014static struct wrapperbase tab_##NAME[] = { \
2015 {"__" #NAME "__", \
2016 (wrapperfunc)wrap_ternaryfunc, \
2017 "x.__" #NAME "__(y, z) <==> " #OP}, \
2018 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002019 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020 "y.__r" #NAME "__(x, z) <==> " #OP}, \
2021 {0} \
2022}
2023
2024TERNARY(pow, "(x**y) % z");
2025
2026#undef UNARY
2027#define UNARY(NAME, OP) \
2028static struct wrapperbase tab_##NAME[] = { \
2029 {"__" #NAME "__", \
2030 (wrapperfunc)wrap_unaryfunc, \
2031 "x.__" #NAME "__() <==> " #OP}, \
2032 {0} \
2033}
2034
2035static PyObject *
2036wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2037{
2038 unaryfunc func = (unaryfunc)wrapped;
2039
2040 if (!PyArg_ParseTuple(args, ""))
2041 return NULL;
2042 return (*func)(self);
2043}
2044
2045UNARY(neg, "-x");
2046UNARY(pos, "+x");
2047UNARY(abs, "abs(x)");
2048UNARY(nonzero, "x != 0");
2049UNARY(invert, "~x");
2050UNARY(int, "int(x)");
2051UNARY(long, "long(x)");
2052UNARY(float, "float(x)");
2053UNARY(oct, "oct(x)");
2054UNARY(hex, "hex(x)");
2055
2056#undef IBINARY
2057#define IBINARY(NAME, OP) \
2058static struct wrapperbase tab_##NAME[] = { \
2059 {"__" #NAME "__", \
2060 (wrapperfunc)wrap_binaryfunc, \
2061 "x.__" #NAME "__(y) <==> " #OP}, \
2062 {0} \
2063}
2064
2065IBINARY(iadd, "x+=y");
2066IBINARY(isub, "x-=y");
2067IBINARY(imul, "x*=y");
2068IBINARY(idiv, "x/=y");
2069IBINARY(imod, "x%=y");
2070IBINARY(ilshift, "x<<=y");
2071IBINARY(irshift, "x>>=y");
2072IBINARY(iand, "x&=y");
2073IBINARY(ixor, "x^=y");
2074IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002075IBINARY(ifloordiv, "x//=y");
2076IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002077
2078#undef ITERNARY
2079#define ITERNARY(NAME, OP) \
2080static struct wrapperbase tab_##NAME[] = { \
2081 {"__" #NAME "__", \
2082 (wrapperfunc)wrap_ternaryfunc, \
2083 "x.__" #NAME "__(y) <==> " #OP}, \
2084 {0} \
2085}
2086
2087ITERNARY(ipow, "x = (x**y) % z");
2088
2089static struct wrapperbase tab_getitem[] = {
2090 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2091 "x.__getitem__(y) <==> x[y]"},
2092 {0}
2093};
2094
2095static PyObject *
2096wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2097{
2098 intargfunc func = (intargfunc)wrapped;
2099 int i;
2100
2101 if (!PyArg_ParseTuple(args, "i", &i))
2102 return NULL;
2103 return (*func)(self, i);
2104}
2105
2106static struct wrapperbase tab_mul_int[] = {
2107 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2108 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2109 {0}
2110};
2111
2112static struct wrapperbase tab_concat[] = {
2113 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2114 {0}
2115};
2116
2117static struct wrapperbase tab_imul_int[] = {
2118 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2119 {0}
2120};
2121
Guido van Rossum5d815f32001-08-17 21:57:47 +00002122static int
2123getindex(PyObject *self, PyObject *arg)
2124{
2125 int i;
2126
2127 i = PyInt_AsLong(arg);
2128 if (i == -1 && PyErr_Occurred())
2129 return -1;
2130 if (i < 0) {
2131 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2132 if (sq && sq->sq_length) {
2133 int n = (*sq->sq_length)(self);
2134 if (n < 0)
2135 return -1;
2136 i += n;
2137 }
2138 }
2139 return i;
2140}
2141
2142static PyObject *
2143wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2144{
2145 intargfunc func = (intargfunc)wrapped;
2146 PyObject *arg;
2147 int i;
2148
Guido van Rossumf4593e02001-10-03 12:09:30 +00002149 if (PyTuple_GET_SIZE(args) == 1) {
2150 arg = PyTuple_GET_ITEM(args, 0);
2151 i = getindex(self, arg);
2152 if (i == -1 && PyErr_Occurred())
2153 return NULL;
2154 return (*func)(self, i);
2155 }
2156 PyArg_ParseTuple(args, "O", &arg);
2157 assert(PyErr_Occurred());
2158 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002159}
2160
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002162 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002163 "x.__getitem__(i) <==> x[i]"},
2164 {0}
2165};
2166
2167static PyObject *
2168wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2169{
2170 intintargfunc func = (intintargfunc)wrapped;
2171 int i, j;
2172
2173 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2174 return NULL;
2175 return (*func)(self, i, j);
2176}
2177
2178static struct wrapperbase tab_getslice[] = {
2179 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2180 "x.__getslice__(i, j) <==> x[i:j]"},
2181 {0}
2182};
2183
2184static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002185wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002186{
2187 intobjargproc func = (intobjargproc)wrapped;
2188 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002189 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190
Guido van Rossum5d815f32001-08-17 21:57:47 +00002191 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2192 return NULL;
2193 i = getindex(self, arg);
2194 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002195 return NULL;
2196 res = (*func)(self, i, value);
2197 if (res == -1 && PyErr_Occurred())
2198 return NULL;
2199 Py_INCREF(Py_None);
2200 return Py_None;
2201}
2202
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002203static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002204wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002205{
2206 intobjargproc func = (intobjargproc)wrapped;
2207 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002208 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002209
Guido van Rossum5d815f32001-08-17 21:57:47 +00002210 if (!PyArg_ParseTuple(args, "O", &arg))
2211 return NULL;
2212 i = getindex(self, arg);
2213 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002214 return NULL;
2215 res = (*func)(self, i, NULL);
2216 if (res == -1 && PyErr_Occurred())
2217 return NULL;
2218 Py_INCREF(Py_None);
2219 return Py_None;
2220}
2221
Tim Peters6d6c1a32001-08-02 04:15:00 +00002222static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002223 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002224 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002225 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002226 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227 {0}
2228};
2229
2230static PyObject *
2231wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2232{
2233 intintobjargproc func = (intintobjargproc)wrapped;
2234 int i, j, res;
2235 PyObject *value;
2236
2237 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2238 return NULL;
2239 res = (*func)(self, i, j, value);
2240 if (res == -1 && PyErr_Occurred())
2241 return NULL;
2242 Py_INCREF(Py_None);
2243 return Py_None;
2244}
2245
2246static struct wrapperbase tab_setslice[] = {
2247 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2248 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
2249 {0}
2250};
2251
2252/* XXX objobjproc is a misnomer; should be objargpred */
2253static PyObject *
2254wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2255{
2256 objobjproc func = (objobjproc)wrapped;
2257 int res;
2258 PyObject *value;
2259
2260 if (!PyArg_ParseTuple(args, "O", &value))
2261 return NULL;
2262 res = (*func)(self, value);
2263 if (res == -1 && PyErr_Occurred())
2264 return NULL;
2265 return PyInt_FromLong((long)res);
2266}
2267
2268static struct wrapperbase tab_contains[] = {
2269 {"__contains__", (wrapperfunc)wrap_objobjproc,
2270 "x.__contains__(y) <==> y in x"},
2271 {0}
2272};
2273
2274static PyObject *
2275wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2276{
2277 objobjargproc func = (objobjargproc)wrapped;
2278 int res;
2279 PyObject *key, *value;
2280
2281 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2282 return NULL;
2283 res = (*func)(self, key, value);
2284 if (res == -1 && PyErr_Occurred())
2285 return NULL;
2286 Py_INCREF(Py_None);
2287 return Py_None;
2288}
2289
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002290static PyObject *
2291wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2292{
2293 objobjargproc func = (objobjargproc)wrapped;
2294 int res;
2295 PyObject *key;
2296
2297 if (!PyArg_ParseTuple(args, "O", &key))
2298 return NULL;
2299 res = (*func)(self, key, NULL);
2300 if (res == -1 && PyErr_Occurred())
2301 return NULL;
2302 Py_INCREF(Py_None);
2303 return Py_None;
2304}
2305
Tim Peters6d6c1a32001-08-02 04:15:00 +00002306static struct wrapperbase tab_setitem[] = {
2307 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2308 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002309 {"__delitem__", (wrapperfunc)wrap_delitem,
2310 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002311 {0}
2312};
2313
2314static PyObject *
2315wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2316{
2317 cmpfunc func = (cmpfunc)wrapped;
2318 int res;
2319 PyObject *other;
2320
2321 if (!PyArg_ParseTuple(args, "O", &other))
2322 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002323 if (other->ob_type->tp_compare != func &&
2324 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002325 PyErr_Format(
2326 PyExc_TypeError,
2327 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2328 self->ob_type->tp_name,
2329 self->ob_type->tp_name,
2330 other->ob_type->tp_name);
2331 return NULL;
2332 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002333 res = (*func)(self, other);
2334 if (PyErr_Occurred())
2335 return NULL;
2336 return PyInt_FromLong((long)res);
2337}
2338
2339static struct wrapperbase tab_cmp[] = {
2340 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2341 "x.__cmp__(y) <==> cmp(x,y)"},
2342 {0}
2343};
2344
2345static struct wrapperbase tab_repr[] = {
2346 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2347 "x.__repr__() <==> repr(x)"},
2348 {0}
2349};
2350
2351static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002352 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2353 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002354 {0}
2355};
2356
2357static PyObject *
2358wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2359{
2360 setattrofunc func = (setattrofunc)wrapped;
2361 int res;
2362 PyObject *name, *value;
2363
2364 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2365 return NULL;
2366 res = (*func)(self, name, value);
2367 if (res < 0)
2368 return NULL;
2369 Py_INCREF(Py_None);
2370 return Py_None;
2371}
2372
2373static PyObject *
2374wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2375{
2376 setattrofunc func = (setattrofunc)wrapped;
2377 int res;
2378 PyObject *name;
2379
2380 if (!PyArg_ParseTuple(args, "O", &name))
2381 return NULL;
2382 res = (*func)(self, name, NULL);
2383 if (res < 0)
2384 return NULL;
2385 Py_INCREF(Py_None);
2386 return Py_None;
2387}
2388
2389static struct wrapperbase tab_setattr[] = {
2390 {"__setattr__", (wrapperfunc)wrap_setattr,
2391 "x.__setattr__('name', value) <==> x.name = value"},
2392 {"__delattr__", (wrapperfunc)wrap_delattr,
2393 "x.__delattr__('name') <==> del x.name"},
2394 {0}
2395};
2396
2397static PyObject *
2398wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2399{
2400 hashfunc func = (hashfunc)wrapped;
2401 long res;
2402
2403 if (!PyArg_ParseTuple(args, ""))
2404 return NULL;
2405 res = (*func)(self);
2406 if (res == -1 && PyErr_Occurred())
2407 return NULL;
2408 return PyInt_FromLong(res);
2409}
2410
2411static struct wrapperbase tab_hash[] = {
2412 {"__hash__", (wrapperfunc)wrap_hashfunc,
2413 "x.__hash__() <==> hash(x)"},
2414 {0}
2415};
2416
2417static PyObject *
2418wrap_call(PyObject *self, PyObject *args, void *wrapped)
2419{
2420 ternaryfunc func = (ternaryfunc)wrapped;
2421
2422 /* XXX What about keyword arguments? */
2423 return (*func)(self, args, NULL);
2424}
2425
2426static struct wrapperbase tab_call[] = {
2427 {"__call__", (wrapperfunc)wrap_call,
2428 "x.__call__(...) <==> x(...)"},
2429 {0}
2430};
2431
2432static struct wrapperbase tab_str[] = {
2433 {"__str__", (wrapperfunc)wrap_unaryfunc,
2434 "x.__str__() <==> str(x)"},
2435 {0}
2436};
2437
2438static PyObject *
2439wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2440{
2441 richcmpfunc func = (richcmpfunc)wrapped;
2442 PyObject *other;
2443
2444 if (!PyArg_ParseTuple(args, "O", &other))
2445 return NULL;
2446 return (*func)(self, other, op);
2447}
2448
2449#undef RICHCMP_WRAPPER
2450#define RICHCMP_WRAPPER(NAME, OP) \
2451static PyObject * \
2452richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2453{ \
2454 return wrap_richcmpfunc(self, args, wrapped, OP); \
2455}
2456
Jack Jansen8e938b42001-08-08 15:29:49 +00002457RICHCMP_WRAPPER(lt, Py_LT)
2458RICHCMP_WRAPPER(le, Py_LE)
2459RICHCMP_WRAPPER(eq, Py_EQ)
2460RICHCMP_WRAPPER(ne, Py_NE)
2461RICHCMP_WRAPPER(gt, Py_GT)
2462RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002463
2464#undef RICHCMP_ENTRY
2465#define RICHCMP_ENTRY(NAME, EXPR) \
2466 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2467 "x.__" #NAME "__(y) <==> " EXPR}
2468
2469static struct wrapperbase tab_richcmp[] = {
2470 RICHCMP_ENTRY(lt, "x<y"),
2471 RICHCMP_ENTRY(le, "x<=y"),
2472 RICHCMP_ENTRY(eq, "x==y"),
2473 RICHCMP_ENTRY(ne, "x!=y"),
2474 RICHCMP_ENTRY(gt, "x>y"),
2475 RICHCMP_ENTRY(ge, "x>=y"),
2476 {0}
2477};
2478
2479static struct wrapperbase tab_iter[] = {
2480 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2481 {0}
2482};
2483
2484static PyObject *
2485wrap_next(PyObject *self, PyObject *args, void *wrapped)
2486{
2487 unaryfunc func = (unaryfunc)wrapped;
2488 PyObject *res;
2489
2490 if (!PyArg_ParseTuple(args, ""))
2491 return NULL;
2492 res = (*func)(self);
2493 if (res == NULL && !PyErr_Occurred())
2494 PyErr_SetNone(PyExc_StopIteration);
2495 return res;
2496}
2497
2498static struct wrapperbase tab_next[] = {
2499 {"next", (wrapperfunc)wrap_next,
2500 "x.next() -> the next value, or raise StopIteration"},
2501 {0}
2502};
2503
2504static PyObject *
2505wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2506{
2507 descrgetfunc func = (descrgetfunc)wrapped;
2508 PyObject *obj;
2509 PyObject *type = NULL;
2510
2511 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2512 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002513 return (*func)(self, obj, type);
2514}
2515
2516static struct wrapperbase tab_descr_get[] = {
2517 {"__get__", (wrapperfunc)wrap_descr_get,
2518 "descr.__get__(obj, type) -> value"},
2519 {0}
2520};
2521
2522static PyObject *
2523wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2524{
2525 descrsetfunc func = (descrsetfunc)wrapped;
2526 PyObject *obj, *value;
2527 int ret;
2528
2529 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2530 return NULL;
2531 ret = (*func)(self, obj, value);
2532 if (ret < 0)
2533 return NULL;
2534 Py_INCREF(Py_None);
2535 return Py_None;
2536}
2537
2538static struct wrapperbase tab_descr_set[] = {
2539 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2540 "descr.__set__(obj, value)"},
2541 {0}
2542};
2543
2544static PyObject *
2545wrap_init(PyObject *self, PyObject *args, void *wrapped)
2546{
2547 initproc func = (initproc)wrapped;
2548
2549 /* XXX What about keyword arguments? */
2550 if (func(self, args, NULL) < 0)
2551 return NULL;
2552 Py_INCREF(Py_None);
2553 return Py_None;
2554}
2555
2556static struct wrapperbase tab_init[] = {
2557 {"__init__", (wrapperfunc)wrap_init,
2558 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002559 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002560 {0}
2561};
2562
2563static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002564tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002565{
Barry Warsaw60f01882001-08-22 19:24:42 +00002566 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002567 PyObject *arg0, *res;
2568
2569 if (self == NULL || !PyType_Check(self))
2570 Py_FatalError("__new__() called with non-type 'self'");
2571 type = (PyTypeObject *)self;
2572 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002573 PyErr_Format(PyExc_TypeError,
2574 "%s.__new__(): not enough arguments",
2575 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002576 return NULL;
2577 }
2578 arg0 = PyTuple_GET_ITEM(args, 0);
2579 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002580 PyErr_Format(PyExc_TypeError,
2581 "%s.__new__(X): X is not a type object (%s)",
2582 type->tp_name,
2583 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002584 return NULL;
2585 }
2586 subtype = (PyTypeObject *)arg0;
2587 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002588 PyErr_Format(PyExc_TypeError,
2589 "%s.__new__(%s): %s is not a subtype of %s",
2590 type->tp_name,
2591 subtype->tp_name,
2592 subtype->tp_name,
2593 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002594 return NULL;
2595 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002596
2597 /* Check that the use doesn't do something silly and unsafe like
2598 object.__new__(dictionary). To do this, we check that the
2599 most derived base that's not a heap type is this type. */
2600 staticbase = subtype;
2601 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2602 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002603 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002604 PyErr_Format(PyExc_TypeError,
2605 "%s.__new__(%s) is not safe, use %s.__new__()",
2606 type->tp_name,
2607 subtype->tp_name,
2608 staticbase == NULL ? "?" : staticbase->tp_name);
2609 return NULL;
2610 }
2611
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002612 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2613 if (args == NULL)
2614 return NULL;
2615 res = type->tp_new(subtype, args, kwds);
2616 Py_DECREF(args);
2617 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002618}
2619
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002620static struct PyMethodDef tp_new_methoddef[] = {
2621 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2622 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002623 {0}
2624};
2625
2626static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002627add_tp_new_wrapper(PyTypeObject *type)
2628{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002629 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002630
Guido van Rossumf040ede2001-08-07 16:40:56 +00002631 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2632 return 0;
2633 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002634 if (func == NULL)
2635 return -1;
2636 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2637}
2638
Guido van Rossum13d52f02001-08-10 21:24:08 +00002639static int
2640add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2641{
2642 PyObject *dict = type->tp_defined;
2643
2644 for (; wraps->name != NULL; wraps++) {
2645 PyObject *descr;
2646 if (PyDict_GetItemString(dict, wraps->name))
2647 continue;
2648 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2649 if (descr == NULL)
2650 return -1;
2651 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2652 return -1;
2653 Py_DECREF(descr);
2654 }
2655 return 0;
2656}
2657
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002658/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002659 dictionary with method descriptors for function slots. For each
2660 function slot (like tp_repr) that's defined in the type, one or
2661 more corresponding descriptors are added in the type's tp_defined
2662 dictionary under the appropriate name (like __repr__). Some
2663 function slots cause more than one descriptor to be added (for
2664 example, the nb_add slot adds both __add__ and __radd__
2665 descriptors) and some function slots compete for the same
2666 descriptor (for example both sq_item and mp_subscript generate a
2667 __getitem__ descriptor). This only adds new descriptors and
2668 doesn't overwrite entries in tp_defined that were previously
2669 defined. The descriptors contain a reference to the C function
2670 they must call, so that it's safe if they are copied into a
2671 subtype's __dict__ and the subtype has a different C function in
2672 its slot -- calling the method defined by the descriptor will call
2673 the C function that was used to create it, rather than the C
2674 function present in the slot when it is called. (This is important
2675 because a subtype may have a C function in the slot that calls the
2676 method from the dictionary, and we want to avoid infinite recursion
2677 here.) */
2678
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002679static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002680add_operators(PyTypeObject *type)
2681{
2682 PySequenceMethods *sq;
2683 PyMappingMethods *mp;
2684 PyNumberMethods *nb;
2685
2686#undef ADD
2687#define ADD(SLOT, TABLE) \
2688 if (SLOT) { \
2689 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2690 return -1; \
2691 }
2692
2693 if ((sq = type->tp_as_sequence) != NULL) {
2694 ADD(sq->sq_length, tab_len);
2695 ADD(sq->sq_concat, tab_concat);
2696 ADD(sq->sq_repeat, tab_mul_int);
2697 ADD(sq->sq_item, tab_getitem_int);
2698 ADD(sq->sq_slice, tab_getslice);
2699 ADD(sq->sq_ass_item, tab_setitem_int);
2700 ADD(sq->sq_ass_slice, tab_setslice);
2701 ADD(sq->sq_contains, tab_contains);
2702 ADD(sq->sq_inplace_concat, tab_iadd);
2703 ADD(sq->sq_inplace_repeat, tab_imul_int);
2704 }
2705
2706 if ((mp = type->tp_as_mapping) != NULL) {
2707 if (sq->sq_length == NULL)
2708 ADD(mp->mp_length, tab_len);
2709 ADD(mp->mp_subscript, tab_getitem);
2710 ADD(mp->mp_ass_subscript, tab_setitem);
2711 }
2712
2713 /* We don't support "old-style numbers" because their binary
2714 operators require that both arguments have the same type;
2715 the wrappers here only work for new-style numbers. */
2716 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2717 (nb = type->tp_as_number) != NULL) {
2718 ADD(nb->nb_add, tab_add);
2719 ADD(nb->nb_subtract, tab_sub);
2720 ADD(nb->nb_multiply, tab_mul);
2721 ADD(nb->nb_divide, tab_div);
2722 ADD(nb->nb_remainder, tab_mod);
2723 ADD(nb->nb_divmod, tab_divmod);
2724 ADD(nb->nb_power, tab_pow);
2725 ADD(nb->nb_negative, tab_neg);
2726 ADD(nb->nb_positive, tab_pos);
2727 ADD(nb->nb_absolute, tab_abs);
2728 ADD(nb->nb_nonzero, tab_nonzero);
2729 ADD(nb->nb_invert, tab_invert);
2730 ADD(nb->nb_lshift, tab_lshift);
2731 ADD(nb->nb_rshift, tab_rshift);
2732 ADD(nb->nb_and, tab_and);
2733 ADD(nb->nb_xor, tab_xor);
2734 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002735 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002736 ADD(nb->nb_int, tab_int);
2737 ADD(nb->nb_long, tab_long);
2738 ADD(nb->nb_float, tab_float);
2739 ADD(nb->nb_oct, tab_oct);
2740 ADD(nb->nb_hex, tab_hex);
2741 ADD(nb->nb_inplace_add, tab_iadd);
2742 ADD(nb->nb_inplace_subtract, tab_isub);
2743 ADD(nb->nb_inplace_multiply, tab_imul);
2744 ADD(nb->nb_inplace_divide, tab_idiv);
2745 ADD(nb->nb_inplace_remainder, tab_imod);
2746 ADD(nb->nb_inplace_power, tab_ipow);
2747 ADD(nb->nb_inplace_lshift, tab_ilshift);
2748 ADD(nb->nb_inplace_rshift, tab_irshift);
2749 ADD(nb->nb_inplace_and, tab_iand);
2750 ADD(nb->nb_inplace_xor, tab_ixor);
2751 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum874f15a2001-09-25 21:16:33 +00002752 if (type->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2753 ADD(nb->nb_floor_divide, tab_floordiv);
2754 ADD(nb->nb_true_divide, tab_truediv);
2755 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2756 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2757 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758 }
2759
2760 ADD(type->tp_getattro, tab_getattr);
2761 ADD(type->tp_setattro, tab_setattr);
2762 ADD(type->tp_compare, tab_cmp);
2763 ADD(type->tp_repr, tab_repr);
2764 ADD(type->tp_hash, tab_hash);
2765 ADD(type->tp_call, tab_call);
2766 ADD(type->tp_str, tab_str);
2767 ADD(type->tp_richcompare, tab_richcmp);
2768 ADD(type->tp_iter, tab_iter);
2769 ADD(type->tp_iternext, tab_next);
2770 ADD(type->tp_descr_get, tab_descr_get);
2771 ADD(type->tp_descr_set, tab_descr_set);
2772 ADD(type->tp_init, tab_init);
2773
Guido van Rossumf040ede2001-08-07 16:40:56 +00002774 if (type->tp_new != NULL) {
2775 if (add_tp_new_wrapper(type) < 0)
2776 return -1;
2777 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778
2779 return 0;
2780}
2781
Guido van Rossumf040ede2001-08-07 16:40:56 +00002782/* Slot wrappers that call the corresponding __foo__ slot. See comments
2783 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784
Guido van Rossumdc91b992001-08-08 22:26:22 +00002785#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002787FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002789 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002790 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791}
2792
Guido van Rossumdc91b992001-08-08 22:26:22 +00002793#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002795FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002797 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002798 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799}
2800
Guido van Rossumdc91b992001-08-08 22:26:22 +00002801
2802#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002804FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002805{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002806 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002807 int do_other = self->ob_type != other->ob_type && \
2808 other->ob_type->tp_as_number != NULL && \
2809 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002810 if (self->ob_type->tp_as_number != NULL && \
2811 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2812 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002813 if (do_other && \
2814 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2815 r = call_maybe( \
2816 other, ROPSTR, &rcache_str, "(O)", self); \
2817 if (r != Py_NotImplemented) \
2818 return r; \
2819 Py_DECREF(r); \
2820 do_other = 0; \
2821 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002822 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002823 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002824 if (r != Py_NotImplemented || \
2825 other->ob_type == self->ob_type) \
2826 return r; \
2827 Py_DECREF(r); \
2828 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002829 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002830 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002831 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002832 } \
2833 Py_INCREF(Py_NotImplemented); \
2834 return Py_NotImplemented; \
2835}
2836
2837#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2838 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2839
2840#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2841static PyObject * \
2842FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2843{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002844 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002845 return call_method(self, OPSTR, &cache_str, \
2846 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002847}
2848
2849static int
2850slot_sq_length(PyObject *self)
2851{
Guido van Rossum2730b132001-08-28 18:22:14 +00002852 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002853 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002854 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002855
2856 if (res == NULL)
2857 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002858 len = (int)PyInt_AsLong(res);
2859 Py_DECREF(res);
2860 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002861}
2862
Guido van Rossumdc91b992001-08-08 22:26:22 +00002863SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2864SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002865
2866/* Super-optimized version of slot_sq_item.
2867 Other slots could do the same... */
2868static PyObject *
2869slot_sq_item(PyObject *self, int i)
2870{
2871 static PyObject *getitem_str;
2872 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2873 descrgetfunc f;
2874
2875 if (getitem_str == NULL) {
2876 getitem_str = PyString_InternFromString("__getitem__");
2877 if (getitem_str == NULL)
2878 return NULL;
2879 }
2880 func = _PyType_Lookup(self->ob_type, getitem_str);
2881 if (func != NULL) {
2882 if (func->ob_type == &PyWrapperDescr_Type) {
2883 PyWrapperDescrObject *wrapper =
2884 (PyWrapperDescrObject *)func;
2885 if (wrapper->d_base->wrapper == wrap_sq_item) {
2886 intargfunc f;
2887 f = (intargfunc)(wrapper->d_wrapped);
2888 return f(self, i);
2889 }
2890 }
2891 if ((f = func->ob_type->tp_descr_get) == NULL)
2892 Py_INCREF(func);
2893 else
2894 func = f(func, self, (PyObject *)(self->ob_type));
2895 ival = PyInt_FromLong(i);
2896 if (ival != NULL) {
2897 args = PyTuple_New(1);
2898 if (args != NULL) {
2899 PyTuple_SET_ITEM(args, 0, ival);
2900 retval = PyObject_Call(func, args, NULL);
2901 Py_XDECREF(args);
2902 Py_XDECREF(func);
2903 return retval;
2904 }
2905 }
2906 }
2907 else {
2908 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2909 }
2910 Py_XDECREF(args);
2911 Py_XDECREF(ival);
2912 Py_XDECREF(func);
2913 return NULL;
2914}
2915
Guido van Rossumdc91b992001-08-08 22:26:22 +00002916SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002917
2918static int
2919slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2920{
2921 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002922 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002923
2924 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002925 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002926 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002928 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002929 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002930 if (res == NULL)
2931 return -1;
2932 Py_DECREF(res);
2933 return 0;
2934}
2935
2936static int
2937slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2938{
2939 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002940 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002941
2942 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002943 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002944 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002945 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002946 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002947 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002948 if (res == NULL)
2949 return -1;
2950 Py_DECREF(res);
2951 return 0;
2952}
2953
2954static int
2955slot_sq_contains(PyObject *self, PyObject *value)
2956{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002957 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002958 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002959
Guido van Rossum55f20992001-10-01 17:18:22 +00002960 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002961
2962 if (func != NULL) {
2963 args = Py_BuildValue("(O)", value);
2964 if (args == NULL)
2965 res = NULL;
2966 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002967 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002968 Py_DECREF(args);
2969 }
2970 Py_DECREF(func);
2971 if (res == NULL)
2972 return -1;
2973 return PyObject_IsTrue(res);
2974 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002975 else if (PyErr_Occurred())
2976 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002977 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002978 return _PySequence_IterSearch(self, value,
2979 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002980 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002981}
2982
Guido van Rossumdc91b992001-08-08 22:26:22 +00002983SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2984SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002985
2986#define slot_mp_length slot_sq_length
2987
Guido van Rossumdc91b992001-08-08 22:26:22 +00002988SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002989
2990static int
2991slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2992{
2993 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002994 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995
2996 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002997 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002998 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002999 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003000 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003001 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003002 if (res == NULL)
3003 return -1;
3004 Py_DECREF(res);
3005 return 0;
3006}
3007
Guido van Rossumdc91b992001-08-08 22:26:22 +00003008SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3009SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3010SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3011SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3012SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3013SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3014
3015staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3016
3017SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3018 nb_power, "__pow__", "__rpow__")
3019
3020static PyObject *
3021slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3022{
Guido van Rossum2730b132001-08-28 18:22:14 +00003023 static PyObject *pow_str;
3024
Guido van Rossumdc91b992001-08-08 22:26:22 +00003025 if (modulus == Py_None)
3026 return slot_nb_power_binary(self, other);
3027 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003028 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003029 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003030}
3031
3032SLOT0(slot_nb_negative, "__neg__")
3033SLOT0(slot_nb_positive, "__pos__")
3034SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035
3036static int
3037slot_nb_nonzero(PyObject *self)
3038{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003039 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003040 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003041
Guido van Rossum55f20992001-10-01 17:18:22 +00003042 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003043 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003044 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003045 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003046 func = lookup_maybe(self, "__len__", &len_str);
3047 if (func == NULL) {
3048 if (PyErr_Occurred())
3049 return -1;
3050 else
3051 return 1;
3052 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003053 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003054 res = PyObject_CallObject(func, NULL);
3055 Py_DECREF(func);
3056 if (res == NULL)
3057 return -1;
3058 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003059}
3060
Guido van Rossumdc91b992001-08-08 22:26:22 +00003061SLOT0(slot_nb_invert, "__invert__")
3062SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3063SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3064SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3065SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3066SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003067
3068static int
3069slot_nb_coerce(PyObject **a, PyObject **b)
3070{
3071 static PyObject *coerce_str;
3072 PyObject *self = *a, *other = *b;
3073
3074 if (self->ob_type->tp_as_number != NULL &&
3075 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3076 PyObject *r;
3077 r = call_maybe(
3078 self, "__coerce__", &coerce_str, "(O)", other);
3079 if (r == NULL)
3080 return -1;
3081 if (r == Py_NotImplemented) {
3082 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003083 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003084 else {
3085 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3086 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003087 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003088 Py_DECREF(r);
3089 return -1;
3090 }
3091 *a = PyTuple_GET_ITEM(r, 0);
3092 Py_INCREF(*a);
3093 *b = PyTuple_GET_ITEM(r, 1);
3094 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003095 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003096 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003097 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003098 }
3099 if (other->ob_type->tp_as_number != NULL &&
3100 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3101 PyObject *r;
3102 r = call_maybe(
3103 other, "__coerce__", &coerce_str, "(O)", self);
3104 if (r == NULL)
3105 return -1;
3106 if (r == Py_NotImplemented) {
3107 Py_DECREF(r);
3108 return 1;
3109 }
3110 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3111 PyErr_SetString(PyExc_TypeError,
3112 "__coerce__ didn't return a 2-tuple");
3113 Py_DECREF(r);
3114 return -1;
3115 }
3116 *a = PyTuple_GET_ITEM(r, 1);
3117 Py_INCREF(*a);
3118 *b = PyTuple_GET_ITEM(r, 0);
3119 Py_INCREF(*b);
3120 Py_DECREF(r);
3121 return 0;
3122 }
3123 return 1;
3124}
3125
Guido van Rossumdc91b992001-08-08 22:26:22 +00003126SLOT0(slot_nb_int, "__int__")
3127SLOT0(slot_nb_long, "__long__")
3128SLOT0(slot_nb_float, "__float__")
3129SLOT0(slot_nb_oct, "__oct__")
3130SLOT0(slot_nb_hex, "__hex__")
3131SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3132SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3133SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3134SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3135SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3136SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3137SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3138SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3139SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3140SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3141SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3142SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3143 "__floordiv__", "__rfloordiv__")
3144SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3145SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3146SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003147
3148static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003149half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003150{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003151 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003152 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003153 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003154
Guido van Rossum60718732001-08-28 17:47:51 +00003155 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003156 if (func == NULL) {
3157 PyErr_Clear();
3158 }
3159 else {
3160 args = Py_BuildValue("(O)", other);
3161 if (args == NULL)
3162 res = NULL;
3163 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003164 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003165 Py_DECREF(args);
3166 }
3167 if (res != Py_NotImplemented) {
3168 if (res == NULL)
3169 return -2;
3170 c = PyInt_AsLong(res);
3171 Py_DECREF(res);
3172 if (c == -1 && PyErr_Occurred())
3173 return -2;
3174 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3175 }
3176 Py_DECREF(res);
3177 }
3178 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003179}
3180
Guido van Rossumab3b0342001-09-18 20:38:53 +00003181/* This slot is published for the benefit of try_3way_compare in object.c */
3182int
3183_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003184{
3185 int c;
3186
Guido van Rossumab3b0342001-09-18 20:38:53 +00003187 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003188 c = half_compare(self, other);
3189 if (c <= 1)
3190 return c;
3191 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003192 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003193 c = half_compare(other, self);
3194 if (c < -1)
3195 return -2;
3196 if (c <= 1)
3197 return -c;
3198 }
3199 return (void *)self < (void *)other ? -1 :
3200 (void *)self > (void *)other ? 1 : 0;
3201}
3202
3203static PyObject *
3204slot_tp_repr(PyObject *self)
3205{
3206 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003207 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003208
Guido van Rossum60718732001-08-28 17:47:51 +00003209 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003210 if (func != NULL) {
3211 res = PyEval_CallObject(func, NULL);
3212 Py_DECREF(func);
3213 return res;
3214 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003215 PyErr_Clear();
3216 return PyString_FromFormat("<%s object at %p>",
3217 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003218}
3219
3220static PyObject *
3221slot_tp_str(PyObject *self)
3222{
3223 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003224 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003225
Guido van Rossum60718732001-08-28 17:47:51 +00003226 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003227 if (func != NULL) {
3228 res = PyEval_CallObject(func, NULL);
3229 Py_DECREF(func);
3230 return res;
3231 }
3232 else {
3233 PyErr_Clear();
3234 return slot_tp_repr(self);
3235 }
3236}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003237
3238static long
3239slot_tp_hash(PyObject *self)
3240{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003241 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003242 static PyObject *hash_str, *eq_str, *cmp_str;
3243
Tim Peters6d6c1a32001-08-02 04:15:00 +00003244 long h;
3245
Guido van Rossum60718732001-08-28 17:47:51 +00003246 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003247
3248 if (func != NULL) {
3249 res = PyEval_CallObject(func, NULL);
3250 Py_DECREF(func);
3251 if (res == NULL)
3252 return -1;
3253 h = PyInt_AsLong(res);
3254 }
3255 else {
3256 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003257 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003258 if (func == NULL) {
3259 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003260 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003261 }
3262 if (func != NULL) {
3263 Py_DECREF(func);
3264 PyErr_SetString(PyExc_TypeError, "unhashable type");
3265 return -1;
3266 }
3267 PyErr_Clear();
3268 h = _Py_HashPointer((void *)self);
3269 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003270 if (h == -1 && !PyErr_Occurred())
3271 h = -2;
3272 return h;
3273}
3274
3275static PyObject *
3276slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3277{
Guido van Rossum60718732001-08-28 17:47:51 +00003278 static PyObject *call_str;
3279 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003280 PyObject *res;
3281
3282 if (meth == NULL)
3283 return NULL;
3284 res = PyObject_Call(meth, args, kwds);
3285 Py_DECREF(meth);
3286 return res;
3287}
3288
Tim Peters6d6c1a32001-08-02 04:15:00 +00003289static PyObject *
3290slot_tp_getattro(PyObject *self, PyObject *name)
3291{
3292 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003293 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003294 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003295
Guido van Rossum8e248182001-08-12 05:17:56 +00003296 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003297 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003298 if (getattr_str == NULL)
3299 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003300 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003301 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003302 if (getattr == NULL) {
3303 /* Avoid further slowdowns */
3304 if (tp->tp_getattro == slot_tp_getattro)
3305 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003306 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003307 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003308 return PyObject_CallFunction(getattr, "OO", self, name);
3309}
3310
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003311static PyObject *
3312slot_tp_getattr_hook(PyObject *self, PyObject *name)
3313{
3314 PyTypeObject *tp = self->ob_type;
3315 PyObject *getattr, *getattribute, *res;
3316 static PyObject *getattribute_str = NULL;
3317 static PyObject *getattr_str = NULL;
3318
3319 if (getattr_str == NULL) {
3320 getattr_str = PyString_InternFromString("__getattr__");
3321 if (getattr_str == NULL)
3322 return NULL;
3323 }
3324 if (getattribute_str == NULL) {
3325 getattribute_str =
3326 PyString_InternFromString("__getattribute__");
3327 if (getattribute_str == NULL)
3328 return NULL;
3329 }
3330 getattr = _PyType_Lookup(tp, getattr_str);
3331 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003332 if (getattribute != NULL &&
3333 getattribute->ob_type == &PyWrapperDescr_Type &&
3334 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3335 PyObject_GenericGetAttr)
3336 getattribute = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003337 if (getattr == NULL && getattribute == NULL) {
3338 /* Avoid further slowdowns */
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003339 /* XXX This is questionable: it means that a class that
3340 isn't born with __getattr__ or __getattribute__ cannot
3341 acquire them in later life. But it's a relatively big
3342 speedup, so I'm keeping it in for now. If this is
3343 removed, you can also remove the "def __getattr__" from
3344 class C (marked with another XXX comment) in dynamics()
3345 in Lib/test/test_descr.py. */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003346 if (tp->tp_getattro == slot_tp_getattr_hook)
3347 tp->tp_getattro = PyObject_GenericGetAttr;
3348 return PyObject_GenericGetAttr(self, name);
3349 }
3350 if (getattribute == NULL)
3351 res = PyObject_GenericGetAttr(self, name);
3352 else
3353 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003354 if (getattr != NULL &&
3355 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003356 PyErr_Clear();
3357 res = PyObject_CallFunction(getattr, "OO", self, name);
3358 }
3359 return res;
3360}
3361
Tim Peters6d6c1a32001-08-02 04:15:00 +00003362static int
3363slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3364{
3365 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003366 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367
3368 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003369 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003370 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003371 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003372 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003373 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003374 if (res == NULL)
3375 return -1;
3376 Py_DECREF(res);
3377 return 0;
3378}
3379
3380/* Map rich comparison operators to their __xx__ namesakes */
3381static char *name_op[] = {
3382 "__lt__",
3383 "__le__",
3384 "__eq__",
3385 "__ne__",
3386 "__gt__",
3387 "__ge__",
3388};
3389
3390static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003391half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003392{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003393 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003394 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003395
Guido van Rossum60718732001-08-28 17:47:51 +00003396 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003397 if (func == NULL) {
3398 PyErr_Clear();
3399 Py_INCREF(Py_NotImplemented);
3400 return Py_NotImplemented;
3401 }
3402 args = Py_BuildValue("(O)", other);
3403 if (args == NULL)
3404 res = NULL;
3405 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003406 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003407 Py_DECREF(args);
3408 }
3409 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003410 return res;
3411}
3412
Guido van Rossumb8f63662001-08-15 23:57:02 +00003413/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3414static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3415
3416static PyObject *
3417slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3418{
3419 PyObject *res;
3420
3421 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3422 res = half_richcompare(self, other, op);
3423 if (res != Py_NotImplemented)
3424 return res;
3425 Py_DECREF(res);
3426 }
3427 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3428 res = half_richcompare(other, self, swapped_op[op]);
3429 if (res != Py_NotImplemented) {
3430 return res;
3431 }
3432 Py_DECREF(res);
3433 }
3434 Py_INCREF(Py_NotImplemented);
3435 return Py_NotImplemented;
3436}
3437
3438static PyObject *
3439slot_tp_iter(PyObject *self)
3440{
3441 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003442 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003443
Guido van Rossum60718732001-08-28 17:47:51 +00003444 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003445 if (func != NULL) {
3446 res = PyObject_CallObject(func, NULL);
3447 Py_DECREF(func);
3448 return res;
3449 }
3450 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003451 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003452 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003453 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003454 return NULL;
3455 }
3456 Py_DECREF(func);
3457 return PySeqIter_New(self);
3458}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003459
3460static PyObject *
3461slot_tp_iternext(PyObject *self)
3462{
Guido van Rossum2730b132001-08-28 18:22:14 +00003463 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003464 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003465}
3466
Guido van Rossum1a493502001-08-17 16:47:50 +00003467static PyObject *
3468slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3469{
3470 PyTypeObject *tp = self->ob_type;
3471 PyObject *get;
3472 static PyObject *get_str = NULL;
3473
3474 if (get_str == NULL) {
3475 get_str = PyString_InternFromString("__get__");
3476 if (get_str == NULL)
3477 return NULL;
3478 }
3479 get = _PyType_Lookup(tp, get_str);
3480 if (get == NULL) {
3481 /* Avoid further slowdowns */
3482 if (tp->tp_descr_get == slot_tp_descr_get)
3483 tp->tp_descr_get = NULL;
3484 Py_INCREF(self);
3485 return self;
3486 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003487 if (obj == NULL)
3488 obj = Py_None;
3489 if (type == NULL)
3490 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003491 return PyObject_CallFunction(get, "OOO", self, obj, type);
3492}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003493
3494static int
3495slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3496{
Guido van Rossum2c252392001-08-24 10:13:31 +00003497 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003498 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003499
3500 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003501 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003502 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003503 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003504 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003505 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003506 if (res == NULL)
3507 return -1;
3508 Py_DECREF(res);
3509 return 0;
3510}
3511
3512static int
3513slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3514{
Guido van Rossum60718732001-08-28 17:47:51 +00003515 static PyObject *init_str;
3516 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003517 PyObject *res;
3518
3519 if (meth == NULL)
3520 return -1;
3521 res = PyObject_Call(meth, args, kwds);
3522 Py_DECREF(meth);
3523 if (res == NULL)
3524 return -1;
3525 Py_DECREF(res);
3526 return 0;
3527}
3528
3529static PyObject *
3530slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3531{
3532 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3533 PyObject *newargs, *x;
3534 int i, n;
3535
3536 if (func == NULL)
3537 return NULL;
3538 assert(PyTuple_Check(args));
3539 n = PyTuple_GET_SIZE(args);
3540 newargs = PyTuple_New(n+1);
3541 if (newargs == NULL)
3542 return NULL;
3543 Py_INCREF(type);
3544 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3545 for (i = 0; i < n; i++) {
3546 x = PyTuple_GET_ITEM(args, i);
3547 Py_INCREF(x);
3548 PyTuple_SET_ITEM(newargs, i+1, x);
3549 }
3550 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003551 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003552 Py_DECREF(func);
3553 return x;
3554}
3555
Guido van Rossumf040ede2001-08-07 16:40:56 +00003556/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003557 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003558 The dict argument is the dictionary argument passed to type_new(),
3559 which is the local namespace of the class statement, in other
3560 words, it contains the methods. For each special method (like
3561 __repr__) defined in the dictionary, the corresponding function
3562 slot in the type object (like tp_repr) is set to a special function
3563 whose name is 'slot_' followed by the slot name and whose signature
3564 is whatever is required for that slot. These slot functions look
3565 up the corresponding method in the type's dictionary and call it.
3566 The slot functions have to take care of the various peculiarities
3567 of the mapping between slots and special methods, such as mapping
3568 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3569 etc.) or mapping multiple slots to a single method (sq_item,
3570 mp_subscript <--> __getitem__). */
3571
Tim Peters6d6c1a32001-08-02 04:15:00 +00003572static void
3573override_slots(PyTypeObject *type, PyObject *dict)
3574{
3575 PySequenceMethods *sq = type->tp_as_sequence;
3576 PyMappingMethods *mp = type->tp_as_mapping;
3577 PyNumberMethods *nb = type->tp_as_number;
3578
Guido van Rossumdc91b992001-08-08 22:26:22 +00003579#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003580 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003581 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003582 }
3583
Guido van Rossumdc91b992001-08-08 22:26:22 +00003584#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003585 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003586 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003587 }
3588
Guido van Rossumdc91b992001-08-08 22:26:22 +00003589#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003590 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003591 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003592 }
3593
Guido van Rossumdc91b992001-08-08 22:26:22 +00003594#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003595 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003596 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003597 }
3598
Guido van Rossumdc91b992001-08-08 22:26:22 +00003599 SQSLOT("__len__", sq_length, slot_sq_length);
3600 SQSLOT("__add__", sq_concat, slot_sq_concat);
3601 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3602 SQSLOT("__getitem__", sq_item, slot_sq_item);
3603 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3604 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3605 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3606 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3607 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3608 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3609 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3610 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003611
Guido van Rossumdc91b992001-08-08 22:26:22 +00003612 MPSLOT("__len__", mp_length, slot_mp_length);
3613 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3614 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3615 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003616
Guido van Rossumdc91b992001-08-08 22:26:22 +00003617 NBSLOT("__add__", nb_add, slot_nb_add);
3618 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3619 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3620 NBSLOT("__div__", nb_divide, slot_nb_divide);
3621 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3622 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3623 NBSLOT("__pow__", nb_power, slot_nb_power);
3624 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3625 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3626 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3627 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3628 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3629 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3630 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3631 NBSLOT("__and__", nb_and, slot_nb_and);
3632 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3633 NBSLOT("__or__", nb_or, slot_nb_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003634 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003635 NBSLOT("__int__", nb_int, slot_nb_int);
3636 NBSLOT("__long__", nb_long, slot_nb_long);
3637 NBSLOT("__float__", nb_float, slot_nb_float);
3638 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3639 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3640 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3641 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3642 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3643 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3644 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3645 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3646 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3647 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3648 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3649 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3650 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3651 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3652 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3653 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3654 slot_nb_inplace_floor_divide);
3655 NBSLOT("__itruediv__", nb_inplace_true_divide,
3656 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003657
Guido van Rossum8e248182001-08-12 05:17:56 +00003658 if (dict == NULL ||
3659 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003660 PyDict_GetItemString(dict, "__repr__"))
3661 type->tp_print = NULL;
3662
Guido van Rossumab3b0342001-09-18 20:38:53 +00003663 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003664 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3665 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3666 TPSLOT("__call__", tp_call, slot_tp_call);
3667 TPSLOT("__str__", tp_str, slot_tp_str);
Guido van Rossum867a8d22001-09-21 19:29:08 +00003668 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003669 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003670 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3671 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3672 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3673 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3674 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3675 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3676 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3677 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3678 TPSLOT("next", tp_iternext, slot_tp_iternext);
3679 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3680 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3681 TPSLOT("__init__", tp_init, slot_tp_init);
3682 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003684
3685
3686/* Cooperative 'super' */
3687
3688typedef struct {
3689 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003690 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003691 PyObject *obj;
3692} superobject;
3693
Guido van Rossum6f799372001-09-20 20:46:19 +00003694static PyMemberDef super_members[] = {
3695 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3696 "the class invoking super()"},
3697 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3698 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003699 {0}
3700};
3701
Guido van Rossum705f0f52001-08-24 16:47:00 +00003702static void
3703super_dealloc(PyObject *self)
3704{
3705 superobject *su = (superobject *)self;
3706
Guido van Rossum048eb752001-10-02 21:24:57 +00003707 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003708 Py_XDECREF(su->obj);
3709 Py_XDECREF(su->type);
3710 self->ob_type->tp_free(self);
3711}
3712
3713static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003714super_repr(PyObject *self)
3715{
3716 superobject *su = (superobject *)self;
3717
3718 if (su->obj)
3719 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003720 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003721 su->type ? su->type->tp_name : "NULL",
3722 su->obj->ob_type->tp_name);
3723 else
3724 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003725 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003726 su->type ? su->type->tp_name : "NULL");
3727}
3728
3729static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003730super_getattro(PyObject *self, PyObject *name)
3731{
3732 superobject *su = (superobject *)self;
3733
3734 if (su->obj != NULL) {
3735 PyObject *mro, *res, *tmp;
3736 descrgetfunc f;
3737 int i, n;
3738
Guido van Rossume705ef12001-08-29 15:47:06 +00003739 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003740 if (mro == NULL)
3741 n = 0;
3742 else {
3743 assert(PyTuple_Check(mro));
3744 n = PyTuple_GET_SIZE(mro);
3745 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003746 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003747 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003748 break;
3749 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003750 if (i >= n && PyType_Check(su->obj)) {
3751 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003752 if (mro == NULL)
3753 n = 0;
3754 else {
3755 assert(PyTuple_Check(mro));
3756 n = PyTuple_GET_SIZE(mro);
3757 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003758 for (i = 0; i < n; i++) {
3759 if ((PyObject *)(su->type) ==
3760 PyTuple_GET_ITEM(mro, i))
3761 break;
3762 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003763 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003764 i++;
3765 res = NULL;
3766 for (; i < n; i++) {
3767 tmp = PyTuple_GET_ITEM(mro, i);
3768 assert(PyType_Check(tmp));
3769 res = PyDict_GetItem(
3770 ((PyTypeObject *)tmp)->tp_defined, name);
3771 if (res != NULL) {
3772 Py_INCREF(res);
3773 f = res->ob_type->tp_descr_get;
3774 if (f != NULL) {
3775 tmp = f(res, su->obj, res);
3776 Py_DECREF(res);
3777 res = tmp;
3778 }
3779 return res;
3780 }
3781 }
3782 }
3783 return PyObject_GenericGetAttr(self, name);
3784}
3785
3786static PyObject *
3787super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3788{
3789 superobject *su = (superobject *)self;
3790 superobject *new;
3791
3792 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3793 /* Not binding to an object, or already bound */
3794 Py_INCREF(self);
3795 return self;
3796 }
3797 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3798 if (new == NULL)
3799 return NULL;
3800 Py_INCREF(su->type);
3801 Py_INCREF(obj);
3802 new->type = su->type;
3803 new->obj = obj;
3804 return (PyObject *)new;
3805}
3806
3807static int
3808super_init(PyObject *self, PyObject *args, PyObject *kwds)
3809{
3810 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003811 PyTypeObject *type;
3812 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003813
3814 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3815 return -1;
3816 if (obj == Py_None)
3817 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003818 if (obj != NULL &&
3819 !PyType_IsSubtype(obj->ob_type, type) &&
3820 !(PyType_Check(obj) &&
3821 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003822 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003823 "super(type, obj): "
3824 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003825 return -1;
3826 }
3827 Py_INCREF(type);
3828 Py_XINCREF(obj);
3829 su->type = type;
3830 su->obj = obj;
3831 return 0;
3832}
3833
3834static char super_doc[] =
3835"super(type) -> unbound super object\n"
3836"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003837"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003838"Typical use to call a cooperative superclass method:\n"
3839"class C(B):\n"
3840" def meth(self, arg):\n"
3841" super(C, self).meth(arg)";
3842
Guido van Rossum048eb752001-10-02 21:24:57 +00003843static int
3844super_traverse(PyObject *self, visitproc visit, void *arg)
3845{
3846 superobject *su = (superobject *)self;
3847 int err;
3848
3849#define VISIT(SLOT) \
3850 if (SLOT) { \
3851 err = visit((PyObject *)(SLOT), arg); \
3852 if (err) \
3853 return err; \
3854 }
3855
3856 VISIT(su->obj);
3857 VISIT(su->type);
3858
3859#undef VISIT
3860
3861 return 0;
3862}
3863
Guido van Rossum705f0f52001-08-24 16:47:00 +00003864PyTypeObject PySuper_Type = {
3865 PyObject_HEAD_INIT(&PyType_Type)
3866 0, /* ob_size */
3867 "super", /* tp_name */
3868 sizeof(superobject), /* tp_basicsize */
3869 0, /* tp_itemsize */
3870 /* methods */
3871 super_dealloc, /* tp_dealloc */
3872 0, /* tp_print */
3873 0, /* tp_getattr */
3874 0, /* tp_setattr */
3875 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003876 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003877 0, /* tp_as_number */
3878 0, /* tp_as_sequence */
3879 0, /* tp_as_mapping */
3880 0, /* tp_hash */
3881 0, /* tp_call */
3882 0, /* tp_str */
3883 super_getattro, /* tp_getattro */
3884 0, /* tp_setattro */
3885 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00003886 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3887 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003888 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00003889 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003890 0, /* tp_clear */
3891 0, /* tp_richcompare */
3892 0, /* tp_weaklistoffset */
3893 0, /* tp_iter */
3894 0, /* tp_iternext */
3895 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003896 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003897 0, /* tp_getset */
3898 0, /* tp_base */
3899 0, /* tp_dict */
3900 super_descr_get, /* tp_descr_get */
3901 0, /* tp_descr_set */
3902 0, /* tp_dictoffset */
3903 super_init, /* tp_init */
3904 PyType_GenericAlloc, /* tp_alloc */
3905 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00003906 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003907};