blob: 0ec81758124aa66cec84a1608d67aa1e3978b54f [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 Petersf2a67da2001-10-07 03:54:51 +0000194 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000195
196 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000197 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000198 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000199 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000200
Neil Schemenauerc806c882001-08-29 23:54:54 +0000201 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000202 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000203
Neil Schemenauerc806c882001-08-29 23:54:54 +0000204 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000205
Tim Peters6d6c1a32001-08-02 04:15:00 +0000206 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
207 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000208
Tim Peters6d6c1a32001-08-02 04:15:00 +0000209 if (type->tp_itemsize == 0)
210 PyObject_INIT(obj, type);
211 else
212 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000213
Tim Peters6d6c1a32001-08-02 04:15:00 +0000214 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000215 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000216 return obj;
217}
218
219PyObject *
220PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
221{
222 return type->tp_alloc(type, 0);
223}
224
Guido van Rossum9475a232001-10-05 20:51:39 +0000225/* Helpers for subtyping */
226
227static int
228subtype_traverse(PyObject *self, visitproc visit, void *arg)
229{
230 PyTypeObject *type, *base;
231 traverseproc f;
232 int err;
233
234 /* Find the nearest base with a different tp_traverse */
235 type = self->ob_type;
236 base = type->tp_base;
237 while ((f = base->tp_traverse) == subtype_traverse) {
238 base = base->tp_base;
239 assert(base);
240 }
241
242 if (type->tp_dictoffset != base->tp_dictoffset) {
243 PyObject **dictptr = _PyObject_GetDictPtr(self);
244 if (dictptr && *dictptr) {
245 err = visit(*dictptr, arg);
246 if (err)
247 return err;
248 }
249 }
250
251 if (f)
252 return f(self, visit, arg);
253 return 0;
254}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000255
256static void
257subtype_dealloc(PyObject *self)
258{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000259 PyTypeObject *type, *base;
260 destructor f;
261
262 /* This exists so we can DECREF self->ob_type */
263
264 /* Find the nearest base with a different tp_dealloc */
265 type = self->ob_type;
266 base = type->tp_base;
267 while ((f = base->tp_dealloc) == subtype_dealloc) {
268 base = base->tp_base;
269 assert(base);
270 }
271
272 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000273 if (type->tp_dictoffset && !base->tp_dictoffset) {
274 PyObject **dictptr = _PyObject_GetDictPtr(self);
275 if (dictptr != NULL) {
276 PyObject *dict = *dictptr;
277 if (dict != NULL) {
278 Py_DECREF(dict);
279 *dictptr = NULL;
280 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000281 }
282 }
283
Guido van Rossum9676b222001-08-17 20:32:36 +0000284 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000285 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000286 PyObject_ClearWeakRefs(self);
287
Tim Peters6d6c1a32001-08-02 04:15:00 +0000288 /* Finalize GC if the base doesn't do GC and we do */
289 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000290 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000291
292 /* Call the base tp_dealloc() */
293 assert(f);
294 f(self);
295
296 /* Can't reference self beyond this point */
297 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
298 Py_DECREF(type);
299 }
300}
301
302staticforward void override_slots(PyTypeObject *type, PyObject *dict);
303staticforward PyTypeObject *solid_base(PyTypeObject *type);
304
305typedef struct {
306 PyTypeObject type;
307 PyNumberMethods as_number;
308 PySequenceMethods as_sequence;
309 PyMappingMethods as_mapping;
310 PyBufferProcs as_buffer;
311 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000312 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000313} etype;
314
315/* type test with subclassing support */
316
317int
318PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
319{
320 PyObject *mro;
321
Guido van Rossum9478d072001-09-07 18:52:13 +0000322 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
323 return b == a || b == &PyBaseObject_Type;
324
Tim Peters6d6c1a32001-08-02 04:15:00 +0000325 mro = a->tp_mro;
326 if (mro != NULL) {
327 /* Deal with multiple inheritance without recursion
328 by walking the MRO tuple */
329 int i, n;
330 assert(PyTuple_Check(mro));
331 n = PyTuple_GET_SIZE(mro);
332 for (i = 0; i < n; i++) {
333 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
334 return 1;
335 }
336 return 0;
337 }
338 else {
339 /* a is not completely initilized yet; follow tp_base */
340 do {
341 if (a == b)
342 return 1;
343 a = a->tp_base;
344 } while (a != NULL);
345 return b == &PyBaseObject_Type;
346 }
347}
348
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000349/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000350 without looking in the instance dictionary
351 (so we can't use PyObject_GetAttr) but still binding
352 it to the instance. The arguments are the object,
353 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000354 static variable used to cache the interned Python string.
355
356 Two variants:
357
358 - lookup_maybe() returns NULL without raising an exception
359 when the _PyType_Lookup() call fails;
360
361 - lookup_method() always raises an exception upon errors.
362*/
Guido van Rossum60718732001-08-28 17:47:51 +0000363
364static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000365lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000366{
367 PyObject *res;
368
369 if (*attrobj == NULL) {
370 *attrobj = PyString_InternFromString(attrstr);
371 if (*attrobj == NULL)
372 return NULL;
373 }
374 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000375 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000376 descrgetfunc f;
377 if ((f = res->ob_type->tp_descr_get) == NULL)
378 Py_INCREF(res);
379 else
380 res = f(res, self, (PyObject *)(self->ob_type));
381 }
382 return res;
383}
384
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000385static PyObject *
386lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
387{
388 PyObject *res = lookup_maybe(self, attrstr, attrobj);
389 if (res == NULL && !PyErr_Occurred())
390 PyErr_SetObject(PyExc_AttributeError, *attrobj);
391 return res;
392}
393
Guido van Rossum2730b132001-08-28 18:22:14 +0000394/* A variation of PyObject_CallMethod that uses lookup_method()
395 instead of PyObject_GetAttrString(). This uses the same convention
396 as lookup_method to cache the interned name string object. */
397
398PyObject *
399call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
400{
401 va_list va;
402 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000403 va_start(va, format);
404
Guido van Rossumda21c012001-10-03 00:50:18 +0000405 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000406 if (func == NULL) {
407 va_end(va);
408 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000409 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000410 return NULL;
411 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000412
413 if (format && *format)
414 args = Py_VaBuildValue(format, va);
415 else
416 args = PyTuple_New(0);
417
418 va_end(va);
419
420 if (args == NULL)
421 return NULL;
422
423 assert(PyTuple_Check(args));
424 retval = PyObject_Call(func, args, NULL);
425
426 Py_DECREF(args);
427 Py_DECREF(func);
428
429 return retval;
430}
431
432/* Clone of call_method() that returns NotImplemented when the lookup fails. */
433
434PyObject *
435call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
436{
437 va_list va;
438 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000439 va_start(va, format);
440
Guido van Rossumda21c012001-10-03 00:50:18 +0000441 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000442 if (func == NULL) {
443 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000444 if (!PyErr_Occurred()) {
445 Py_INCREF(Py_NotImplemented);
446 return Py_NotImplemented;
447 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000448 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000449 }
450
451 if (format && *format)
452 args = Py_VaBuildValue(format, va);
453 else
454 args = PyTuple_New(0);
455
456 va_end(va);
457
Guido van Rossum717ce002001-09-14 16:58:08 +0000458 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000459 return NULL;
460
Guido van Rossum717ce002001-09-14 16:58:08 +0000461 assert(PyTuple_Check(args));
462 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000463
464 Py_DECREF(args);
465 Py_DECREF(func);
466
467 return retval;
468}
469
Tim Peters6d6c1a32001-08-02 04:15:00 +0000470/* Method resolution order algorithm from "Putting Metaclasses to Work"
471 by Forman and Danforth (Addison-Wesley 1999). */
472
473static int
474conservative_merge(PyObject *left, PyObject *right)
475{
476 int left_size;
477 int right_size;
478 int i, j, r, ok;
479 PyObject *temp, *rr;
480
481 assert(PyList_Check(left));
482 assert(PyList_Check(right));
483
484 again:
485 left_size = PyList_GET_SIZE(left);
486 right_size = PyList_GET_SIZE(right);
487 for (i = 0; i < left_size; i++) {
488 for (j = 0; j < right_size; j++) {
489 if (PyList_GET_ITEM(left, i) ==
490 PyList_GET_ITEM(right, j)) {
491 /* found a merge point */
492 temp = PyList_New(0);
493 if (temp == NULL)
494 return -1;
495 for (r = 0; r < j; r++) {
496 rr = PyList_GET_ITEM(right, r);
497 ok = PySequence_Contains(left, rr);
498 if (ok < 0) {
499 Py_DECREF(temp);
500 return -1;
501 }
502 if (!ok) {
503 ok = PyList_Append(temp, rr);
504 if (ok < 0) {
505 Py_DECREF(temp);
506 return -1;
507 }
508 }
509 }
510 ok = PyList_SetSlice(left, i, i, temp);
511 Py_DECREF(temp);
512 if (ok < 0)
513 return -1;
514 ok = PyList_SetSlice(right, 0, j+1, NULL);
515 if (ok < 0)
516 return -1;
517 goto again;
518 }
519 }
520 }
521 return PyList_SetSlice(left, left_size, left_size, right);
522}
523
524static int
525serious_order_disagreements(PyObject *left, PyObject *right)
526{
527 return 0; /* XXX later -- for now, we cheat: "don't do that" */
528}
529
530static PyObject *
531mro_implementation(PyTypeObject *type)
532{
533 int i, n, ok;
534 PyObject *bases, *result;
535
536 bases = type->tp_bases;
537 n = PyTuple_GET_SIZE(bases);
538 result = Py_BuildValue("[O]", (PyObject *)type);
539 if (result == NULL)
540 return NULL;
541 for (i = 0; i < n; i++) {
542 PyTypeObject *base =
543 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
544 PyObject *parentMRO = PySequence_List(base->tp_mro);
545 if (parentMRO == NULL) {
546 Py_DECREF(result);
547 return NULL;
548 }
549 if (serious_order_disagreements(result, parentMRO)) {
550 Py_DECREF(result);
551 return NULL;
552 }
553 ok = conservative_merge(result, parentMRO);
554 Py_DECREF(parentMRO);
555 if (ok < 0) {
556 Py_DECREF(result);
557 return NULL;
558 }
559 }
560 return result;
561}
562
563static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000564mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000565{
566 PyTypeObject *type = (PyTypeObject *)self;
567
Tim Peters6d6c1a32001-08-02 04:15:00 +0000568 return mro_implementation(type);
569}
570
571static int
572mro_internal(PyTypeObject *type)
573{
574 PyObject *mro, *result, *tuple;
575
576 if (type->ob_type == &PyType_Type) {
577 result = mro_implementation(type);
578 }
579 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000580 static PyObject *mro_str;
581 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000582 if (mro == NULL)
583 return -1;
584 result = PyObject_CallObject(mro, NULL);
585 Py_DECREF(mro);
586 }
587 if (result == NULL)
588 return -1;
589 tuple = PySequence_Tuple(result);
590 Py_DECREF(result);
591 type->tp_mro = tuple;
592 return 0;
593}
594
595
596/* Calculate the best base amongst multiple base classes.
597 This is the first one that's on the path to the "solid base". */
598
599static PyTypeObject *
600best_base(PyObject *bases)
601{
602 int i, n;
603 PyTypeObject *base, *winner, *candidate, *base_i;
604
605 assert(PyTuple_Check(bases));
606 n = PyTuple_GET_SIZE(bases);
607 assert(n > 0);
608 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
609 winner = &PyBaseObject_Type;
610 for (i = 0; i < n; i++) {
611 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
612 if (!PyType_Check((PyObject *)base_i)) {
613 PyErr_SetString(
614 PyExc_TypeError,
615 "bases must be types");
616 return NULL;
617 }
618 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000619 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000620 return NULL;
621 }
622 candidate = solid_base(base_i);
623 if (PyType_IsSubtype(winner, candidate))
624 ;
625 else if (PyType_IsSubtype(candidate, winner)) {
626 winner = candidate;
627 base = base_i;
628 }
629 else {
630 PyErr_SetString(
631 PyExc_TypeError,
632 "multiple bases have "
633 "instance lay-out conflict");
634 return NULL;
635 }
636 }
637 assert(base != NULL);
638 return base;
639}
640
641static int
642extra_ivars(PyTypeObject *type, PyTypeObject *base)
643{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000644 size_t t_size = type->tp_basicsize;
645 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000646
Guido van Rossum9676b222001-08-17 20:32:36 +0000647 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000648 if (type->tp_itemsize || base->tp_itemsize) {
649 /* If itemsize is involved, stricter rules */
650 return t_size != b_size ||
651 type->tp_itemsize != base->tp_itemsize;
652 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000653 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
654 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
655 t_size -= sizeof(PyObject *);
656 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
657 type->tp_dictoffset + sizeof(PyObject *) == t_size)
658 t_size -= sizeof(PyObject *);
659
660 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000661}
662
663static PyTypeObject *
664solid_base(PyTypeObject *type)
665{
666 PyTypeObject *base;
667
668 if (type->tp_base)
669 base = solid_base(type->tp_base);
670 else
671 base = &PyBaseObject_Type;
672 if (extra_ivars(type, base))
673 return type;
674 else
675 return base;
676}
677
678staticforward void object_dealloc(PyObject *);
679staticforward int object_init(PyObject *, PyObject *, PyObject *);
680
681static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000682subtype_dict(PyObject *obj, void *context)
683{
684 PyObject **dictptr = _PyObject_GetDictPtr(obj);
685 PyObject *dict;
686
687 if (dictptr == NULL) {
688 PyErr_SetString(PyExc_AttributeError,
689 "This object has no __dict__");
690 return NULL;
691 }
692 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000693 if (dict == NULL)
694 *dictptr = dict = PyDict_New();
695 Py_XINCREF(dict);
696 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000697}
698
Guido van Rossum32d34c82001-09-20 21:45:26 +0000699PyGetSetDef subtype_getsets[] = {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000700 {"__dict__", subtype_dict, NULL, NULL},
701 {0},
702};
703
704static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000705type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
706{
707 PyObject *name, *bases, *dict;
708 static char *kwlist[] = {"name", "bases", "dict", 0};
709 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000710 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000711 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000712 PyMemberDef *mp;
Guido van Rossum9676b222001-08-17 20:32:36 +0000713 int i, nbases, nslots, slotoffset, dynamic, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000714
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000715 /* Special case: type(x) should return x->ob_type */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000716 if (metatype == &PyType_Type &&
717 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
718 (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000719 PyObject *x = PyTuple_GET_ITEM(args, 0);
720 Py_INCREF(x->ob_type);
721 return (PyObject *) x->ob_type;
722 }
723
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000724 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000725 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
726 &name,
727 &PyTuple_Type, &bases,
728 &PyDict_Type, &dict))
729 return NULL;
730
731 /* Determine the proper metatype to deal with this,
732 and check for metatype conflicts while we're at it.
733 Note that if some other metatype wins to contract,
734 it's possible that its instances are not types. */
735 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000736 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000737 for (i = 0; i < nbases; i++) {
738 tmp = PyTuple_GET_ITEM(bases, i);
739 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000740 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000742 if (PyType_IsSubtype(tmptype, winner)) {
743 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000744 continue;
745 }
746 PyErr_SetString(PyExc_TypeError,
747 "metatype conflict among bases");
748 return NULL;
749 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000750 if (winner != metatype) {
751 if (winner->tp_new != type_new) /* Pass it to the winner */
752 return winner->tp_new(winner, args, kwds);
753 metatype = winner;
754 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000755
756 /* Adjust for empty tuple bases */
757 if (nbases == 0) {
758 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
759 if (bases == NULL)
760 return NULL;
761 nbases = 1;
762 }
763 else
764 Py_INCREF(bases);
765
766 /* XXX From here until type is allocated, "return NULL" leaks bases! */
767
768 /* Calculate best base, and check that all bases are type objects */
769 base = best_base(bases);
770 if (base == NULL)
771 return NULL;
772 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
773 PyErr_Format(PyExc_TypeError,
774 "type '%.100s' is not an acceptable base type",
775 base->tp_name);
776 return NULL;
777 }
778
Guido van Rossum1a493502001-08-17 16:47:50 +0000779 /* Should this be a dynamic class (i.e. modifiable __dict__)?
780 Look in two places for a variable named __dynamic__:
781 1) in the class dict
782 2) in the module dict (globals)
783 The first variable that is an int >= 0 is used.
Guido van Rossum50fda3b2001-10-04 19:46:06 +0000784 Otherwise, the default is dynamic. */
Guido van Rossum1a493502001-08-17 16:47:50 +0000785 dynamic = -1; /* Not yet determined */
786 /* Look in the class */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000787 tmp = PyDict_GetItemString(dict, "__dynamic__");
788 if (tmp != NULL) {
Guido van Rossum1a493502001-08-17 16:47:50 +0000789 dynamic = PyInt_AsLong(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000790 if (dynamic < 0)
Guido van Rossum1a493502001-08-17 16:47:50 +0000791 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +0000792 }
Guido van Rossum1a493502001-08-17 16:47:50 +0000793 if (dynamic < 0) {
794 /* Look in the module globals */
795 tmp = PyEval_GetGlobals();
796 if (tmp != NULL) {
797 tmp = PyDict_GetItemString(tmp, "__dynamic__");
798 if (tmp != NULL) {
799 dynamic = PyInt_AsLong(tmp);
800 if (dynamic < 0)
801 PyErr_Clear();
802 }
803 }
804 }
805 if (dynamic < 0) {
Guido van Rossum50fda3b2001-10-04 19:46:06 +0000806 /* Default to dynamic */
807 dynamic = 1;
808
Tim Peters6d6c1a32001-08-02 04:15:00 +0000809 }
810
811 /* Check for a __slots__ sequence variable in dict, and count it */
812 slots = PyDict_GetItemString(dict, "__slots__");
813 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000814 add_dict = 0;
815 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000816 if (slots != NULL) {
817 /* Make it into a tuple */
818 if (PyString_Check(slots))
819 slots = Py_BuildValue("(O)", slots);
820 else
821 slots = PySequence_Tuple(slots);
822 if (slots == NULL)
823 return NULL;
824 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000825 if (nslots > 0 && base->tp_itemsize != 0) {
826 PyErr_Format(PyExc_TypeError,
827 "nonempty __slots__ "
828 "not supported for subtype of '%s'",
829 base->tp_name);
830 return NULL;
831 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000832 for (i = 0; i < nslots; i++) {
833 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
834 PyErr_SetString(PyExc_TypeError,
835 "__slots__ must be a sequence of strings");
836 Py_DECREF(slots);
837 return NULL;
838 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000839 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000840 }
841 }
842 if (slots == NULL && base->tp_dictoffset == 0 &&
843 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000844 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000845 add_dict++;
846 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000847 if (slots == NULL && base->tp_weaklistoffset == 0 &&
848 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000849 nslots++;
850 add_weak++;
851 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852
853 /* XXX From here until type is safely allocated,
854 "return NULL" may leak slots! */
855
856 /* Allocate the type object */
857 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
858 if (type == NULL)
859 return NULL;
860
861 /* Keep name and slots alive in the extended type object */
862 et = (etype *)type;
863 Py_INCREF(name);
864 et->name = name;
865 et->slots = slots;
866
Guido van Rossumdc91b992001-08-08 22:26:22 +0000867 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
869 Py_TPFLAGS_BASETYPE;
870 if (dynamic)
871 type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000872 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
873 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000874
875 /* It's a new-style number unless it specifically inherits any
876 old-style numeric behavior */
877 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
878 (base->tp_as_number == NULL))
879 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
880
881 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000882 type->tp_as_number = &et->as_number;
883 type->tp_as_sequence = &et->as_sequence;
884 type->tp_as_mapping = &et->as_mapping;
885 type->tp_as_buffer = &et->as_buffer;
886 type->tp_name = PyString_AS_STRING(name);
887
888 /* Set tp_base and tp_bases */
889 type->tp_bases = bases;
890 Py_INCREF(base);
891 type->tp_base = base;
892
893 /* Initialize tp_defined from passed-in dict */
894 type->tp_defined = dict = PyDict_Copy(dict);
895 if (dict == NULL) {
896 Py_DECREF(type);
897 return NULL;
898 }
899
Guido van Rossumc3542212001-08-16 09:18:56 +0000900 /* Set __module__ in the dict */
901 if (PyDict_GetItemString(dict, "__module__") == NULL) {
902 tmp = PyEval_GetGlobals();
903 if (tmp != NULL) {
904 tmp = PyDict_GetItemString(tmp, "__name__");
905 if (tmp != NULL) {
906 if (PyDict_SetItemString(dict, "__module__",
907 tmp) < 0)
908 return NULL;
909 }
910 }
911 }
912
Tim Peters2f93e282001-10-04 05:27:00 +0000913 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
914 and is a string (tp_doc is a char* -- can't copy a general object
915 into it).
916 XXX What if it's a Unicode string? Don't know -- this ignores it.
917 */
918 {
919 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
920 if (doc != NULL && PyString_Check(doc)) {
921 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +0000922 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +0000923 if (type->tp_doc == NULL) {
924 Py_DECREF(type);
925 return NULL;
926 }
927 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
928 }
929 }
930
Tim Peters6d6c1a32001-08-02 04:15:00 +0000931 /* Special-case __new__: if it's a plain function,
932 make it a static function */
933 tmp = PyDict_GetItemString(dict, "__new__");
934 if (tmp != NULL && PyFunction_Check(tmp)) {
935 tmp = PyStaticMethod_New(tmp);
936 if (tmp == NULL) {
937 Py_DECREF(type);
938 return NULL;
939 }
940 PyDict_SetItemString(dict, "__new__", tmp);
941 Py_DECREF(tmp);
942 }
943
944 /* Add descriptors for custom slots from __slots__, or for __dict__ */
945 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +0000946 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000947 if (slots != NULL) {
948 for (i = 0; i < nslots; i++, mp++) {
949 mp->name = PyString_AS_STRING(
950 PyTuple_GET_ITEM(slots, i));
951 mp->type = T_OBJECT;
952 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000953 if (base->tp_weaklistoffset == 0 &&
954 strcmp(mp->name, "__weakref__") == 0)
955 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000956 slotoffset += sizeof(PyObject *);
957 }
958 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000959 else {
960 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000961 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +0000962 type->tp_dictoffset =
963 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000964 else
965 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +0000966 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000967 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +0000968 }
969 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000970 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +0000971 type->tp_weaklistoffset = slotoffset;
972 mp->name = "__weakref__";
973 mp->type = T_OBJECT;
974 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +0000975 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +0000976 mp++;
977 slotoffset += sizeof(PyObject *);
978 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000979 }
980 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000981 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +0000982 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000983
984 /* Special case some slots */
985 if (type->tp_dictoffset != 0 || nslots > 0) {
986 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
987 type->tp_getattro = PyObject_GenericGetAttr;
988 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
989 type->tp_setattro = PyObject_GenericSetAttr;
990 }
991 type->tp_dealloc = subtype_dealloc;
992
Guido van Rossum9475a232001-10-05 20:51:39 +0000993 /* Enable GC unless there are really no instance variables possible */
994 if (!(type->tp_basicsize == sizeof(PyObject) &&
995 type->tp_itemsize == 0))
996 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
997
Tim Peters6d6c1a32001-08-02 04:15:00 +0000998 /* Always override allocation strategy to use regular heap */
999 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001000 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1001 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001002 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001003 type->tp_clear = base->tp_clear;
1004 }
1005 else
1006 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007
1008 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001009 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001010 Py_DECREF(type);
1011 return NULL;
1012 }
1013
1014 /* Override slots that deserve it */
Guido van Rossum8e248182001-08-12 05:17:56 +00001015 if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
1016 override_slots(type, type->tp_defined);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001017
Tim Peters6d6c1a32001-08-02 04:15:00 +00001018 return (PyObject *)type;
1019}
1020
1021/* Internal API to look for a name through the MRO.
1022 This returns a borrowed reference, and doesn't set an exception! */
1023PyObject *
1024_PyType_Lookup(PyTypeObject *type, PyObject *name)
1025{
1026 int i, n;
1027 PyObject *mro, *res, *dict;
1028
1029 /* For static types, look in tp_dict */
1030 if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
1031 dict = type->tp_dict;
1032 assert(dict && PyDict_Check(dict));
1033 return PyDict_GetItem(dict, name);
1034 }
1035
1036 /* For dynamic types, look in tp_defined of types in MRO */
1037 mro = type->tp_mro;
1038 assert(PyTuple_Check(mro));
1039 n = PyTuple_GET_SIZE(mro);
1040 for (i = 0; i < n; i++) {
1041 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
1042 assert(PyType_Check(type));
1043 dict = type->tp_defined;
1044 assert(dict && PyDict_Check(dict));
1045 res = PyDict_GetItem(dict, name);
1046 if (res != NULL)
1047 return res;
1048 }
1049 return NULL;
1050}
1051
1052/* This is similar to PyObject_GenericGetAttr(),
1053 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1054static PyObject *
1055type_getattro(PyTypeObject *type, PyObject *name)
1056{
1057 PyTypeObject *metatype = type->ob_type;
1058 PyObject *descr, *res;
1059 descrgetfunc f;
1060
1061 /* Initialize this type (we'll assume the metatype is initialized) */
1062 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001063 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001064 return NULL;
1065 }
1066
1067 /* Get a descriptor from the metatype */
1068 descr = _PyType_Lookup(metatype, name);
1069 f = NULL;
1070 if (descr != NULL) {
1071 f = descr->ob_type->tp_descr_get;
1072 if (f != NULL && PyDescr_IsData(descr))
1073 return f(descr,
1074 (PyObject *)type, (PyObject *)metatype);
1075 }
1076
1077 /* Look in tp_defined of this type and its bases */
1078 res = _PyType_Lookup(type, name);
1079 if (res != NULL) {
1080 f = res->ob_type->tp_descr_get;
1081 if (f != NULL)
1082 return f(res, (PyObject *)NULL, (PyObject *)type);
1083 Py_INCREF(res);
1084 return res;
1085 }
1086
1087 /* Use the descriptor from the metatype */
1088 if (f != NULL) {
1089 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1090 return res;
1091 }
1092 if (descr != NULL) {
1093 Py_INCREF(descr);
1094 return descr;
1095 }
1096
1097 /* Give up */
1098 PyErr_Format(PyExc_AttributeError,
1099 "type object '%.50s' has no attribute '%.400s'",
1100 type->tp_name, PyString_AS_STRING(name));
1101 return NULL;
1102}
1103
1104static int
1105type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1106{
1107 if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
1108 return PyObject_GenericSetAttr((PyObject *)type, name, value);
1109 PyErr_SetString(PyExc_TypeError, "can't set type attributes");
1110 return -1;
1111}
1112
1113static void
1114type_dealloc(PyTypeObject *type)
1115{
1116 etype *et;
1117
1118 /* Assert this is a heap-allocated type object */
1119 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001120 _PyObject_GC_UNTRACK(type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121 et = (etype *)type;
1122 Py_XDECREF(type->tp_base);
1123 Py_XDECREF(type->tp_dict);
1124 Py_XDECREF(type->tp_bases);
1125 Py_XDECREF(type->tp_mro);
1126 Py_XDECREF(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001127 Py_XDECREF(et->name);
1128 Py_XDECREF(et->slots);
1129 type->ob_type->tp_free((PyObject *)type);
1130}
1131
1132static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001133 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001134 "mro() -> list\nreturn a type's method resolution order"},
1135 {0}
1136};
1137
1138static char type_doc[] =
1139"type(object) -> the object's type\n"
1140"type(name, bases, dict) -> a new type";
1141
Guido van Rossum048eb752001-10-02 21:24:57 +00001142static int
1143type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1144{
1145 etype *et;
1146 int err;
1147
1148 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1149 return 0;
1150
1151 et = (etype *)type;
1152
1153#define VISIT(SLOT) \
1154 if (SLOT) { \
1155 err = visit((PyObject *)(SLOT), arg); \
1156 if (err) \
1157 return err; \
1158 }
1159
1160 VISIT(type->tp_dict);
1161 VISIT(type->tp_defined);
1162 VISIT(type->tp_mro);
1163 VISIT(type->tp_bases);
1164 VISIT(type->tp_base);
1165 VISIT(et->slots);
1166
1167#undef VISIT
1168
1169 return 0;
1170}
1171
1172static int
1173type_clear(PyTypeObject *type)
1174{
1175 etype *et;
1176 PyObject *tmp;
1177
1178 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1179 return 0;
1180
1181 et = (etype *)type;
1182
1183#define CLEAR(SLOT) \
1184 if (SLOT) { \
1185 tmp = (PyObject *)(SLOT); \
1186 SLOT = NULL; \
1187 Py_DECREF(tmp); \
1188 }
1189
1190 CLEAR(type->tp_dict);
1191 CLEAR(type->tp_defined);
1192 CLEAR(type->tp_mro);
1193 CLEAR(type->tp_bases);
1194 CLEAR(type->tp_base);
1195 CLEAR(et->slots);
1196
Tim Peters2f93e282001-10-04 05:27:00 +00001197 if (type->tp_doc != NULL) {
1198 PyObject_FREE(type->tp_doc);
1199 type->tp_doc = NULL;
1200 }
1201
Guido van Rossum048eb752001-10-02 21:24:57 +00001202#undef CLEAR
1203
1204 return 0;
1205}
1206
1207static int
1208type_is_gc(PyTypeObject *type)
1209{
1210 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1211}
1212
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001213PyTypeObject PyType_Type = {
1214 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215 0, /* ob_size */
1216 "type", /* tp_name */
1217 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001218 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001219 (destructor)type_dealloc, /* tp_dealloc */
1220 0, /* tp_print */
1221 0, /* tp_getattr */
1222 0, /* tp_setattr */
1223 type_compare, /* tp_compare */
1224 (reprfunc)type_repr, /* tp_repr */
1225 0, /* tp_as_number */
1226 0, /* tp_as_sequence */
1227 0, /* tp_as_mapping */
1228 (hashfunc)_Py_HashPointer, /* tp_hash */
1229 (ternaryfunc)type_call, /* tp_call */
1230 0, /* tp_str */
1231 (getattrofunc)type_getattro, /* tp_getattro */
1232 (setattrofunc)type_setattro, /* tp_setattro */
1233 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001234 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1235 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001236 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001237 (traverseproc)type_traverse, /* tp_traverse */
1238 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001239 0, /* tp_richcompare */
1240 0, /* tp_weaklistoffset */
1241 0, /* tp_iter */
1242 0, /* tp_iternext */
1243 type_methods, /* tp_methods */
1244 type_members, /* tp_members */
1245 type_getsets, /* tp_getset */
1246 0, /* tp_base */
1247 0, /* tp_dict */
1248 0, /* tp_descr_get */
1249 0, /* tp_descr_set */
1250 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1251 0, /* tp_init */
1252 0, /* tp_alloc */
1253 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001254 _PyObject_GC_Del, /* tp_free */
1255 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001256};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001257
1258
1259/* The base type of all types (eventually)... except itself. */
1260
1261static int
1262object_init(PyObject *self, PyObject *args, PyObject *kwds)
1263{
1264 return 0;
1265}
1266
1267static void
1268object_dealloc(PyObject *self)
1269{
1270 self->ob_type->tp_free(self);
1271}
1272
Guido van Rossum8e248182001-08-12 05:17:56 +00001273static PyObject *
1274object_repr(PyObject *self)
1275{
Guido van Rossum76e69632001-08-16 18:52:43 +00001276 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001277 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001278
Guido van Rossum76e69632001-08-16 18:52:43 +00001279 type = self->ob_type;
1280 mod = type_module(type, NULL);
1281 if (mod == NULL)
1282 PyErr_Clear();
1283 else if (!PyString_Check(mod)) {
1284 Py_DECREF(mod);
1285 mod = NULL;
1286 }
1287 name = type_name(type, NULL);
1288 if (name == NULL)
1289 return NULL;
1290 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001291 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001292 PyString_AS_STRING(mod),
1293 PyString_AS_STRING(name),
1294 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001295 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001296 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001297 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001298 Py_XDECREF(mod);
1299 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001300 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001301}
1302
Guido van Rossumb8f63662001-08-15 23:57:02 +00001303static PyObject *
1304object_str(PyObject *self)
1305{
1306 unaryfunc f;
1307
1308 f = self->ob_type->tp_repr;
1309 if (f == NULL)
1310 f = object_repr;
1311 return f(self);
1312}
1313
Guido van Rossum8e248182001-08-12 05:17:56 +00001314static long
1315object_hash(PyObject *self)
1316{
1317 return _Py_HashPointer(self);
1318}
Guido van Rossum8e248182001-08-12 05:17:56 +00001319
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001320static PyObject *
1321object_get_class(PyObject *self, void *closure)
1322{
1323 Py_INCREF(self->ob_type);
1324 return (PyObject *)(self->ob_type);
1325}
1326
1327static int
1328equiv_structs(PyTypeObject *a, PyTypeObject *b)
1329{
1330 return a == b ||
1331 (a != NULL &&
1332 b != NULL &&
1333 a->tp_basicsize == b->tp_basicsize &&
1334 a->tp_itemsize == b->tp_itemsize &&
1335 a->tp_dictoffset == b->tp_dictoffset &&
1336 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1337 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1338 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1339}
1340
1341static int
1342same_slots_added(PyTypeObject *a, PyTypeObject *b)
1343{
1344 PyTypeObject *base = a->tp_base;
1345 int size;
1346
1347 if (base != b->tp_base)
1348 return 0;
1349 if (equiv_structs(a, base) && equiv_structs(b, base))
1350 return 1;
1351 size = base->tp_basicsize;
1352 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1353 size += sizeof(PyObject *);
1354 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1355 size += sizeof(PyObject *);
1356 return size == a->tp_basicsize && size == b->tp_basicsize;
1357}
1358
1359static int
1360object_set_class(PyObject *self, PyObject *value, void *closure)
1361{
1362 PyTypeObject *old = self->ob_type;
1363 PyTypeObject *new, *newbase, *oldbase;
1364
1365 if (!PyType_Check(value)) {
1366 PyErr_Format(PyExc_TypeError,
1367 "__class__ must be set to new-style class, not '%s' object",
1368 value->ob_type->tp_name);
1369 return -1;
1370 }
1371 new = (PyTypeObject *)value;
1372 newbase = new;
1373 oldbase = old;
1374 while (equiv_structs(newbase, newbase->tp_base))
1375 newbase = newbase->tp_base;
1376 while (equiv_structs(oldbase, oldbase->tp_base))
1377 oldbase = oldbase->tp_base;
1378 if (newbase != oldbase &&
1379 (newbase->tp_base != oldbase->tp_base ||
1380 !same_slots_added(newbase, oldbase))) {
1381 PyErr_Format(PyExc_TypeError,
1382 "__class__ assignment: "
1383 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001384 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001385 old->tp_name);
1386 return -1;
1387 }
1388 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1389 Py_INCREF(new);
1390 }
1391 self->ob_type = new;
1392 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1393 Py_DECREF(old);
1394 }
1395 return 0;
1396}
1397
1398static PyGetSetDef object_getsets[] = {
1399 {"__class__", object_get_class, object_set_class,
1400 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001401 {0}
1402};
1403
Guido van Rossum3926a632001-09-25 16:25:58 +00001404static PyObject *
1405object_reduce(PyObject *self, PyObject *args)
1406{
1407 /* Call copy_reg._reduce(self) */
1408 static PyObject *copy_reg_str;
1409 PyObject *copy_reg, *res;
1410
1411 if (!copy_reg_str) {
1412 copy_reg_str = PyString_InternFromString("copy_reg");
1413 if (copy_reg_str == NULL)
1414 return NULL;
1415 }
1416 copy_reg = PyImport_Import(copy_reg_str);
1417 if (!copy_reg)
1418 return NULL;
1419 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1420 Py_DECREF(copy_reg);
1421 return res;
1422}
1423
1424static PyMethodDef object_methods[] = {
1425 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1426 {0}
1427};
1428
Tim Peters6d6c1a32001-08-02 04:15:00 +00001429PyTypeObject PyBaseObject_Type = {
1430 PyObject_HEAD_INIT(&PyType_Type)
1431 0, /* ob_size */
1432 "object", /* tp_name */
1433 sizeof(PyObject), /* tp_basicsize */
1434 0, /* tp_itemsize */
1435 (destructor)object_dealloc, /* tp_dealloc */
1436 0, /* tp_print */
1437 0, /* tp_getattr */
1438 0, /* tp_setattr */
1439 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001440 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001441 0, /* tp_as_number */
1442 0, /* tp_as_sequence */
1443 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001444 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001445 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001446 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001447 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001448 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001449 0, /* tp_as_buffer */
1450 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1451 "The most base type", /* tp_doc */
1452 0, /* tp_traverse */
1453 0, /* tp_clear */
1454 0, /* tp_richcompare */
1455 0, /* tp_weaklistoffset */
1456 0, /* tp_iter */
1457 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001458 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001459 0, /* tp_members */
1460 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001461 0, /* tp_base */
1462 0, /* tp_dict */
1463 0, /* tp_descr_get */
1464 0, /* tp_descr_set */
1465 0, /* tp_dictoffset */
1466 object_init, /* tp_init */
1467 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001468 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001469 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470};
1471
1472
1473/* Initialize the __dict__ in a type object */
1474
1475static int
1476add_methods(PyTypeObject *type, PyMethodDef *meth)
1477{
1478 PyObject *dict = type->tp_defined;
1479
1480 for (; meth->ml_name != NULL; meth++) {
1481 PyObject *descr;
1482 if (PyDict_GetItemString(dict, meth->ml_name))
1483 continue;
1484 descr = PyDescr_NewMethod(type, meth);
1485 if (descr == NULL)
1486 return -1;
1487 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1488 return -1;
1489 Py_DECREF(descr);
1490 }
1491 return 0;
1492}
1493
1494static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001495add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496{
1497 PyObject *dict = type->tp_defined;
1498
1499 for (; memb->name != NULL; memb++) {
1500 PyObject *descr;
1501 if (PyDict_GetItemString(dict, memb->name))
1502 continue;
1503 descr = PyDescr_NewMember(type, memb);
1504 if (descr == NULL)
1505 return -1;
1506 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1507 return -1;
1508 Py_DECREF(descr);
1509 }
1510 return 0;
1511}
1512
1513static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001514add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001515{
1516 PyObject *dict = type->tp_defined;
1517
1518 for (; gsp->name != NULL; gsp++) {
1519 PyObject *descr;
1520 if (PyDict_GetItemString(dict, gsp->name))
1521 continue;
1522 descr = PyDescr_NewGetSet(type, gsp);
1523
1524 if (descr == NULL)
1525 return -1;
1526 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1527 return -1;
1528 Py_DECREF(descr);
1529 }
1530 return 0;
1531}
1532
Guido van Rossum13d52f02001-08-10 21:24:08 +00001533static void
1534inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001535{
1536 int oldsize, newsize;
1537
Guido van Rossum13d52f02001-08-10 21:24:08 +00001538 /* Special flag magic */
1539 if (!type->tp_as_buffer && base->tp_as_buffer) {
1540 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1541 type->tp_flags |=
1542 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1543 }
1544 if (!type->tp_as_sequence && base->tp_as_sequence) {
1545 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1546 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1547 }
1548 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1549 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1550 if ((!type->tp_as_number && base->tp_as_number) ||
1551 (!type->tp_as_sequence && base->tp_as_sequence)) {
1552 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1553 if (!type->tp_as_number && !type->tp_as_sequence) {
1554 type->tp_flags |= base->tp_flags &
1555 Py_TPFLAGS_HAVE_INPLACEOPS;
1556 }
1557 }
1558 /* Wow */
1559 }
1560 if (!type->tp_as_number && base->tp_as_number) {
1561 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1562 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1563 }
1564
1565 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001566 oldsize = base->tp_basicsize;
1567 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1568 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1569 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001570 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1571 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001572 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001573 if (type->tp_traverse == NULL)
1574 type->tp_traverse = base->tp_traverse;
1575 if (type->tp_clear == NULL)
1576 type->tp_clear = base->tp_clear;
1577 }
1578 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1579 if (base != &PyBaseObject_Type ||
1580 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1581 if (type->tp_new == NULL)
1582 type->tp_new = base->tp_new;
1583 }
1584 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001585 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001586
1587 /* Copy other non-function slots */
1588
1589#undef COPYVAL
1590#define COPYVAL(SLOT) \
1591 if (type->SLOT == 0) type->SLOT = base->SLOT
1592
1593 COPYVAL(tp_itemsize);
1594 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1595 COPYVAL(tp_weaklistoffset);
1596 }
1597 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1598 COPYVAL(tp_dictoffset);
1599 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001600}
1601
1602static void
1603inherit_slots(PyTypeObject *type, PyTypeObject *base)
1604{
1605 PyTypeObject *basebase;
1606
1607#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001608#undef COPYSLOT
1609#undef COPYNUM
1610#undef COPYSEQ
1611#undef COPYMAP
Guido van Rossum13d52f02001-08-10 21:24:08 +00001612
1613#define SLOTDEFINED(SLOT) \
1614 (base->SLOT != 0 && \
1615 (basebase == NULL || base->SLOT != basebase->SLOT))
1616
Tim Peters6d6c1a32001-08-02 04:15:00 +00001617#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001618 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001619
1620#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1621#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1622#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1623
Guido van Rossum13d52f02001-08-10 21:24:08 +00001624 /* This won't inherit indirect slots (from tp_as_number etc.)
1625 if type doesn't provide the space. */
1626
1627 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1628 basebase = base->tp_base;
1629 if (basebase->tp_as_number == NULL)
1630 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631 COPYNUM(nb_add);
1632 COPYNUM(nb_subtract);
1633 COPYNUM(nb_multiply);
1634 COPYNUM(nb_divide);
1635 COPYNUM(nb_remainder);
1636 COPYNUM(nb_divmod);
1637 COPYNUM(nb_power);
1638 COPYNUM(nb_negative);
1639 COPYNUM(nb_positive);
1640 COPYNUM(nb_absolute);
1641 COPYNUM(nb_nonzero);
1642 COPYNUM(nb_invert);
1643 COPYNUM(nb_lshift);
1644 COPYNUM(nb_rshift);
1645 COPYNUM(nb_and);
1646 COPYNUM(nb_xor);
1647 COPYNUM(nb_or);
1648 COPYNUM(nb_coerce);
1649 COPYNUM(nb_int);
1650 COPYNUM(nb_long);
1651 COPYNUM(nb_float);
1652 COPYNUM(nb_oct);
1653 COPYNUM(nb_hex);
1654 COPYNUM(nb_inplace_add);
1655 COPYNUM(nb_inplace_subtract);
1656 COPYNUM(nb_inplace_multiply);
1657 COPYNUM(nb_inplace_divide);
1658 COPYNUM(nb_inplace_remainder);
1659 COPYNUM(nb_inplace_power);
1660 COPYNUM(nb_inplace_lshift);
1661 COPYNUM(nb_inplace_rshift);
1662 COPYNUM(nb_inplace_and);
1663 COPYNUM(nb_inplace_xor);
1664 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001665 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1666 COPYNUM(nb_true_divide);
1667 COPYNUM(nb_floor_divide);
1668 COPYNUM(nb_inplace_true_divide);
1669 COPYNUM(nb_inplace_floor_divide);
1670 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001671 }
1672
Guido van Rossum13d52f02001-08-10 21:24:08 +00001673 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1674 basebase = base->tp_base;
1675 if (basebase->tp_as_sequence == NULL)
1676 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677 COPYSEQ(sq_length);
1678 COPYSEQ(sq_concat);
1679 COPYSEQ(sq_repeat);
1680 COPYSEQ(sq_item);
1681 COPYSEQ(sq_slice);
1682 COPYSEQ(sq_ass_item);
1683 COPYSEQ(sq_ass_slice);
1684 COPYSEQ(sq_contains);
1685 COPYSEQ(sq_inplace_concat);
1686 COPYSEQ(sq_inplace_repeat);
1687 }
1688
Guido van Rossum13d52f02001-08-10 21:24:08 +00001689 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1690 basebase = base->tp_base;
1691 if (basebase->tp_as_mapping == NULL)
1692 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001693 COPYMAP(mp_length);
1694 COPYMAP(mp_subscript);
1695 COPYMAP(mp_ass_subscript);
1696 }
1697
Guido van Rossum13d52f02001-08-10 21:24:08 +00001698 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001699
Tim Peters6d6c1a32001-08-02 04:15:00 +00001700 COPYSLOT(tp_dealloc);
1701 COPYSLOT(tp_print);
1702 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1703 type->tp_getattr = base->tp_getattr;
1704 type->tp_getattro = base->tp_getattro;
1705 }
1706 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1707 type->tp_setattr = base->tp_setattr;
1708 type->tp_setattro = base->tp_setattro;
1709 }
1710 /* tp_compare see tp_richcompare */
1711 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001712 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713 COPYSLOT(tp_call);
1714 COPYSLOT(tp_str);
1715 COPYSLOT(tp_as_buffer);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001716 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001717 if (type->tp_compare == NULL &&
1718 type->tp_richcompare == NULL &&
1719 type->tp_hash == NULL)
1720 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721 type->tp_compare = base->tp_compare;
1722 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001723 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001724 }
1725 }
1726 else {
1727 COPYSLOT(tp_compare);
1728 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001729 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1730 COPYSLOT(tp_iter);
1731 COPYSLOT(tp_iternext);
1732 }
1733 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1734 COPYSLOT(tp_descr_get);
1735 COPYSLOT(tp_descr_set);
1736 COPYSLOT(tp_dictoffset);
1737 COPYSLOT(tp_init);
1738 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001739 COPYSLOT(tp_free);
1740 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001741}
1742
Guido van Rossum13d52f02001-08-10 21:24:08 +00001743staticforward int add_operators(PyTypeObject *);
1744
Tim Peters6d6c1a32001-08-02 04:15:00 +00001745int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001746PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001747{
1748 PyObject *dict, *bases, *x;
1749 PyTypeObject *base;
1750 int i, n;
1751
Guido van Rossumd614f972001-08-10 17:39:49 +00001752 if (type->tp_flags & Py_TPFLAGS_READY) {
1753 assert(type->tp_dict != NULL);
1754 return 0;
1755 }
1756 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1757 assert(type->tp_dict == NULL);
1758
1759 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001760
1761 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1762 base = type->tp_base;
1763 if (base == NULL && type != &PyBaseObject_Type)
1764 base = type->tp_base = &PyBaseObject_Type;
1765
1766 /* Initialize tp_bases */
1767 bases = type->tp_bases;
1768 if (bases == NULL) {
1769 if (base == NULL)
1770 bases = PyTuple_New(0);
1771 else
1772 bases = Py_BuildValue("(O)", base);
1773 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001774 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775 type->tp_bases = bases;
1776 }
1777
1778 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001779 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001780 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001781 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001782 }
1783
1784 /* Initialize tp_defined */
1785 dict = type->tp_defined;
1786 if (dict == NULL) {
1787 dict = PyDict_New();
1788 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001789 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001790 type->tp_defined = dict;
1791 }
1792
1793 /* Add type-specific descriptors to tp_defined */
1794 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001795 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001796 if (type->tp_methods != NULL) {
1797 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001798 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799 }
1800 if (type->tp_members != NULL) {
1801 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001802 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001803 }
1804 if (type->tp_getset != NULL) {
1805 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001806 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807 }
1808
1809 /* Temporarily make tp_dict the same object as tp_defined.
1810 (This is needed to call mro(), and can stay this way for
1811 dynamic types). */
1812 Py_INCREF(type->tp_defined);
1813 type->tp_dict = type->tp_defined;
1814
1815 /* Calculate method resolution order */
1816 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001817 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001818 }
1819
Guido van Rossum13d52f02001-08-10 21:24:08 +00001820 /* Inherit special flags from dominant base */
1821 if (type->tp_base != NULL)
1822 inherit_special(type, type->tp_base);
1823
Tim Peters6d6c1a32001-08-02 04:15:00 +00001824 /* Initialize tp_dict properly */
Guido van Rossum8de86802001-08-12 03:43:35 +00001825 if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
Guido van Rossum8e248182001-08-12 05:17:56 +00001826 /* For a dynamic type, all slots are overridden */
1827 override_slots(type, NULL);
Guido van Rossum8de86802001-08-12 03:43:35 +00001828 }
1829 else {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001830 /* For a static type, tp_dict is the consolidation
Guido van Rossum13d52f02001-08-10 21:24:08 +00001831 of the tp_defined of its bases in MRO. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001832 Py_DECREF(type->tp_dict);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001833 type->tp_dict = PyDict_Copy(type->tp_defined);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834 if (type->tp_dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001835 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836 bases = type->tp_mro;
1837 assert(bases != NULL);
1838 assert(PyTuple_Check(bases));
1839 n = PyTuple_GET_SIZE(bases);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001840 for (i = 1; i < n; i++) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001841 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1842 assert(PyType_Check(base));
1843 x = base->tp_defined;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001844 if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001845 goto error;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001846 inherit_slots(type, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847 }
1848 }
1849
Guido van Rossum13d52f02001-08-10 21:24:08 +00001850 /* Some more special stuff */
1851 base = type->tp_base;
1852 if (base != NULL) {
1853 if (type->tp_as_number == NULL)
1854 type->tp_as_number = base->tp_as_number;
1855 if (type->tp_as_sequence == NULL)
1856 type->tp_as_sequence = base->tp_as_sequence;
1857 if (type->tp_as_mapping == NULL)
1858 type->tp_as_mapping = base->tp_as_mapping;
1859 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001860
Guido van Rossum13d52f02001-08-10 21:24:08 +00001861 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001862 assert(type->tp_dict != NULL);
1863 type->tp_flags =
1864 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001866
1867 error:
1868 type->tp_flags &= ~Py_TPFLAGS_READYING;
1869 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001870}
1871
1872
1873/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1874
1875/* There's a wrapper *function* for each distinct function typedef used
1876 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1877 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1878 Most tables have only one entry; the tables for binary operators have two
1879 entries, one regular and one with reversed arguments. */
1880
1881static PyObject *
1882wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1883{
1884 inquiry func = (inquiry)wrapped;
1885 int res;
1886
1887 if (!PyArg_ParseTuple(args, ""))
1888 return NULL;
1889 res = (*func)(self);
1890 if (res == -1 && PyErr_Occurred())
1891 return NULL;
1892 return PyInt_FromLong((long)res);
1893}
1894
1895static struct wrapperbase tab_len[] = {
1896 {"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1897 {0}
1898};
1899
1900static PyObject *
1901wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1902{
1903 binaryfunc func = (binaryfunc)wrapped;
1904 PyObject *other;
1905
1906 if (!PyArg_ParseTuple(args, "O", &other))
1907 return NULL;
1908 return (*func)(self, other);
1909}
1910
1911static PyObject *
1912wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1913{
1914 binaryfunc func = (binaryfunc)wrapped;
1915 PyObject *other;
1916
1917 if (!PyArg_ParseTuple(args, "O", &other))
1918 return NULL;
1919 return (*func)(other, self);
1920}
1921
1922#undef BINARY
1923#define BINARY(NAME, OP) \
1924static struct wrapperbase tab_##NAME[] = { \
1925 {"__" #NAME "__", \
1926 (wrapperfunc)wrap_binaryfunc, \
1927 "x.__" #NAME "__(y) <==> " #OP}, \
1928 {"__r" #NAME "__", \
1929 (wrapperfunc)wrap_binaryfunc_r, \
1930 "y.__r" #NAME "__(x) <==> " #OP}, \
1931 {0} \
1932}
1933
1934BINARY(add, "x+y");
1935BINARY(sub, "x-y");
1936BINARY(mul, "x*y");
1937BINARY(div, "x/y");
1938BINARY(mod, "x%y");
1939BINARY(divmod, "divmod(x,y)");
1940BINARY(lshift, "x<<y");
1941BINARY(rshift, "x>>y");
1942BINARY(and, "x&y");
1943BINARY(xor, "x^y");
1944BINARY(or, "x|y");
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00001945
1946static PyObject *
1947wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
1948{
1949 coercion func = (coercion)wrapped;
1950 PyObject *other, *res;
1951 int ok;
1952
1953 if (!PyArg_ParseTuple(args, "O", &other))
1954 return NULL;
1955 ok = func(&self, &other);
1956 if (ok < 0)
1957 return NULL;
1958 if (ok > 0) {
1959 Py_INCREF(Py_NotImplemented);
1960 return Py_NotImplemented;
1961 }
1962 res = PyTuple_New(2);
1963 if (res == NULL) {
1964 Py_DECREF(self);
1965 Py_DECREF(other);
1966 return NULL;
1967 }
1968 PyTuple_SET_ITEM(res, 0, self);
1969 PyTuple_SET_ITEM(res, 1, other);
1970 return res;
1971}
1972
1973static struct wrapperbase tab_coerce[] = {
1974 {"__coerce__", (wrapperfunc)wrap_coercefunc,
1975 "x.__coerce__(y) <==> coerce(x, y)"},
1976 {0}
1977};
1978
Guido van Rossum874f15a2001-09-25 21:16:33 +00001979BINARY(floordiv, "x//y");
1980BINARY(truediv, "x/y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001981
1982static PyObject *
1983wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1984{
1985 ternaryfunc func = (ternaryfunc)wrapped;
1986 PyObject *other;
1987 PyObject *third = Py_None;
1988
1989 /* Note: This wrapper only works for __pow__() */
1990
1991 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1992 return NULL;
1993 return (*func)(self, other, third);
1994}
1995
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00001996static PyObject *
1997wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1998{
1999 ternaryfunc func = (ternaryfunc)wrapped;
2000 PyObject *other;
2001 PyObject *third = Py_None;
2002
2003 /* Note: This wrapper only works for __pow__() */
2004
2005 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2006 return NULL;
2007 return (*func)(other, self, third);
2008}
2009
Tim Peters6d6c1a32001-08-02 04:15:00 +00002010#undef TERNARY
2011#define TERNARY(NAME, OP) \
2012static struct wrapperbase tab_##NAME[] = { \
2013 {"__" #NAME "__", \
2014 (wrapperfunc)wrap_ternaryfunc, \
2015 "x.__" #NAME "__(y, z) <==> " #OP}, \
2016 {"__r" #NAME "__", \
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002017 (wrapperfunc)wrap_ternaryfunc_r, \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002018 "y.__r" #NAME "__(x, z) <==> " #OP}, \
2019 {0} \
2020}
2021
2022TERNARY(pow, "(x**y) % z");
2023
2024#undef UNARY
2025#define UNARY(NAME, OP) \
2026static struct wrapperbase tab_##NAME[] = { \
2027 {"__" #NAME "__", \
2028 (wrapperfunc)wrap_unaryfunc, \
2029 "x.__" #NAME "__() <==> " #OP}, \
2030 {0} \
2031}
2032
2033static PyObject *
2034wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2035{
2036 unaryfunc func = (unaryfunc)wrapped;
2037
2038 if (!PyArg_ParseTuple(args, ""))
2039 return NULL;
2040 return (*func)(self);
2041}
2042
2043UNARY(neg, "-x");
2044UNARY(pos, "+x");
2045UNARY(abs, "abs(x)");
2046UNARY(nonzero, "x != 0");
2047UNARY(invert, "~x");
2048UNARY(int, "int(x)");
2049UNARY(long, "long(x)");
2050UNARY(float, "float(x)");
2051UNARY(oct, "oct(x)");
2052UNARY(hex, "hex(x)");
2053
2054#undef IBINARY
2055#define IBINARY(NAME, OP) \
2056static struct wrapperbase tab_##NAME[] = { \
2057 {"__" #NAME "__", \
2058 (wrapperfunc)wrap_binaryfunc, \
2059 "x.__" #NAME "__(y) <==> " #OP}, \
2060 {0} \
2061}
2062
2063IBINARY(iadd, "x+=y");
2064IBINARY(isub, "x-=y");
2065IBINARY(imul, "x*=y");
2066IBINARY(idiv, "x/=y");
2067IBINARY(imod, "x%=y");
2068IBINARY(ilshift, "x<<=y");
2069IBINARY(irshift, "x>>=y");
2070IBINARY(iand, "x&=y");
2071IBINARY(ixor, "x^=y");
2072IBINARY(ior, "x|=y");
Guido van Rossum874f15a2001-09-25 21:16:33 +00002073IBINARY(ifloordiv, "x//=y");
2074IBINARY(itruediv, "x/=y # true division");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002075
2076#undef ITERNARY
2077#define ITERNARY(NAME, OP) \
2078static struct wrapperbase tab_##NAME[] = { \
2079 {"__" #NAME "__", \
2080 (wrapperfunc)wrap_ternaryfunc, \
2081 "x.__" #NAME "__(y) <==> " #OP}, \
2082 {0} \
2083}
2084
2085ITERNARY(ipow, "x = (x**y) % z");
2086
2087static struct wrapperbase tab_getitem[] = {
2088 {"__getitem__", (wrapperfunc)wrap_binaryfunc,
2089 "x.__getitem__(y) <==> x[y]"},
2090 {0}
2091};
2092
2093static PyObject *
2094wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2095{
2096 intargfunc func = (intargfunc)wrapped;
2097 int i;
2098
2099 if (!PyArg_ParseTuple(args, "i", &i))
2100 return NULL;
2101 return (*func)(self, i);
2102}
2103
2104static struct wrapperbase tab_mul_int[] = {
2105 {"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
2106 {"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
2107 {0}
2108};
2109
2110static struct wrapperbase tab_concat[] = {
2111 {"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
2112 {0}
2113};
2114
2115static struct wrapperbase tab_imul_int[] = {
2116 {"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
2117 {0}
2118};
2119
Guido van Rossum5d815f32001-08-17 21:57:47 +00002120static int
2121getindex(PyObject *self, PyObject *arg)
2122{
2123 int i;
2124
2125 i = PyInt_AsLong(arg);
2126 if (i == -1 && PyErr_Occurred())
2127 return -1;
2128 if (i < 0) {
2129 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2130 if (sq && sq->sq_length) {
2131 int n = (*sq->sq_length)(self);
2132 if (n < 0)
2133 return -1;
2134 i += n;
2135 }
2136 }
2137 return i;
2138}
2139
2140static PyObject *
2141wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2142{
2143 intargfunc func = (intargfunc)wrapped;
2144 PyObject *arg;
2145 int i;
2146
Guido van Rossumf4593e02001-10-03 12:09:30 +00002147 if (PyTuple_GET_SIZE(args) == 1) {
2148 arg = PyTuple_GET_ITEM(args, 0);
2149 i = getindex(self, arg);
2150 if (i == -1 && PyErr_Occurred())
2151 return NULL;
2152 return (*func)(self, i);
2153 }
2154 PyArg_ParseTuple(args, "O", &arg);
2155 assert(PyErr_Occurred());
2156 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002157}
2158
Tim Peters6d6c1a32001-08-02 04:15:00 +00002159static struct wrapperbase tab_getitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002160 {"__getitem__", (wrapperfunc)wrap_sq_item,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161 "x.__getitem__(i) <==> x[i]"},
2162 {0}
2163};
2164
2165static PyObject *
2166wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2167{
2168 intintargfunc func = (intintargfunc)wrapped;
2169 int i, j;
2170
2171 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2172 return NULL;
2173 return (*func)(self, i, j);
2174}
2175
2176static struct wrapperbase tab_getslice[] = {
2177 {"__getslice__", (wrapperfunc)wrap_intintargfunc,
2178 "x.__getslice__(i, j) <==> x[i:j]"},
2179 {0}
2180};
2181
2182static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002183wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002184{
2185 intobjargproc func = (intobjargproc)wrapped;
2186 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002187 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002188
Guido van Rossum5d815f32001-08-17 21:57:47 +00002189 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2190 return NULL;
2191 i = getindex(self, arg);
2192 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002193 return NULL;
2194 res = (*func)(self, i, value);
2195 if (res == -1 && PyErr_Occurred())
2196 return NULL;
2197 Py_INCREF(Py_None);
2198 return Py_None;
2199}
2200
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002201static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002202wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002203{
2204 intobjargproc func = (intobjargproc)wrapped;
2205 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002206 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002207
Guido van Rossum5d815f32001-08-17 21:57:47 +00002208 if (!PyArg_ParseTuple(args, "O", &arg))
2209 return NULL;
2210 i = getindex(self, arg);
2211 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002212 return NULL;
2213 res = (*func)(self, i, NULL);
2214 if (res == -1 && PyErr_Occurred())
2215 return NULL;
2216 Py_INCREF(Py_None);
2217 return Py_None;
2218}
2219
Tim Peters6d6c1a32001-08-02 04:15:00 +00002220static struct wrapperbase tab_setitem_int[] = {
Guido van Rossum5d815f32001-08-17 21:57:47 +00002221 {"__setitem__", (wrapperfunc)wrap_sq_setitem,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002222 "x.__setitem__(i, y) <==> x[i]=y"},
Guido van Rossum5d815f32001-08-17 21:57:47 +00002223 {"__delitem__", (wrapperfunc)wrap_sq_delitem,
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002224 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002225 {0}
2226};
2227
2228static PyObject *
2229wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2230{
2231 intintobjargproc func = (intintobjargproc)wrapped;
2232 int i, j, res;
2233 PyObject *value;
2234
2235 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2236 return NULL;
2237 res = (*func)(self, i, j, value);
2238 if (res == -1 && PyErr_Occurred())
2239 return NULL;
2240 Py_INCREF(Py_None);
2241 return Py_None;
2242}
2243
2244static struct wrapperbase tab_setslice[] = {
2245 {"__setslice__", (wrapperfunc)wrap_intintobjargproc,
2246 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
2247 {0}
2248};
2249
2250/* XXX objobjproc is a misnomer; should be objargpred */
2251static PyObject *
2252wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2253{
2254 objobjproc func = (objobjproc)wrapped;
2255 int res;
2256 PyObject *value;
2257
2258 if (!PyArg_ParseTuple(args, "O", &value))
2259 return NULL;
2260 res = (*func)(self, value);
2261 if (res == -1 && PyErr_Occurred())
2262 return NULL;
2263 return PyInt_FromLong((long)res);
2264}
2265
2266static struct wrapperbase tab_contains[] = {
2267 {"__contains__", (wrapperfunc)wrap_objobjproc,
2268 "x.__contains__(y) <==> y in x"},
2269 {0}
2270};
2271
2272static PyObject *
2273wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2274{
2275 objobjargproc func = (objobjargproc)wrapped;
2276 int res;
2277 PyObject *key, *value;
2278
2279 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2280 return NULL;
2281 res = (*func)(self, key, value);
2282 if (res == -1 && PyErr_Occurred())
2283 return NULL;
2284 Py_INCREF(Py_None);
2285 return Py_None;
2286}
2287
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002288static PyObject *
2289wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2290{
2291 objobjargproc func = (objobjargproc)wrapped;
2292 int res;
2293 PyObject *key;
2294
2295 if (!PyArg_ParseTuple(args, "O", &key))
2296 return NULL;
2297 res = (*func)(self, key, NULL);
2298 if (res == -1 && PyErr_Occurred())
2299 return NULL;
2300 Py_INCREF(Py_None);
2301 return Py_None;
2302}
2303
Tim Peters6d6c1a32001-08-02 04:15:00 +00002304static struct wrapperbase tab_setitem[] = {
2305 {"__setitem__", (wrapperfunc)wrap_objobjargproc,
2306 "x.__setitem__(y, z) <==> x[y]=z"},
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002307 {"__delitem__", (wrapperfunc)wrap_delitem,
2308 "x.__delitem__(y) <==> del x[y]"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002309 {0}
2310};
2311
2312static PyObject *
2313wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2314{
2315 cmpfunc func = (cmpfunc)wrapped;
2316 int res;
2317 PyObject *other;
2318
2319 if (!PyArg_ParseTuple(args, "O", &other))
2320 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002321 if (other->ob_type->tp_compare != func &&
2322 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002323 PyErr_Format(
2324 PyExc_TypeError,
2325 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2326 self->ob_type->tp_name,
2327 self->ob_type->tp_name,
2328 other->ob_type->tp_name);
2329 return NULL;
2330 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002331 res = (*func)(self, other);
2332 if (PyErr_Occurred())
2333 return NULL;
2334 return PyInt_FromLong((long)res);
2335}
2336
2337static struct wrapperbase tab_cmp[] = {
2338 {"__cmp__", (wrapperfunc)wrap_cmpfunc,
2339 "x.__cmp__(y) <==> cmp(x,y)"},
2340 {0}
2341};
2342
2343static struct wrapperbase tab_repr[] = {
2344 {"__repr__", (wrapperfunc)wrap_unaryfunc,
2345 "x.__repr__() <==> repr(x)"},
2346 {0}
2347};
2348
2349static struct wrapperbase tab_getattr[] = {
Guido van Rossum867a8d22001-09-21 19:29:08 +00002350 {"__getattribute__", (wrapperfunc)wrap_binaryfunc,
2351 "x.__getattribute__('name') <==> x.name"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002352 {0}
2353};
2354
2355static PyObject *
2356wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2357{
2358 setattrofunc func = (setattrofunc)wrapped;
2359 int res;
2360 PyObject *name, *value;
2361
2362 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2363 return NULL;
2364 res = (*func)(self, name, value);
2365 if (res < 0)
2366 return NULL;
2367 Py_INCREF(Py_None);
2368 return Py_None;
2369}
2370
2371static PyObject *
2372wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2373{
2374 setattrofunc func = (setattrofunc)wrapped;
2375 int res;
2376 PyObject *name;
2377
2378 if (!PyArg_ParseTuple(args, "O", &name))
2379 return NULL;
2380 res = (*func)(self, name, NULL);
2381 if (res < 0)
2382 return NULL;
2383 Py_INCREF(Py_None);
2384 return Py_None;
2385}
2386
2387static struct wrapperbase tab_setattr[] = {
2388 {"__setattr__", (wrapperfunc)wrap_setattr,
2389 "x.__setattr__('name', value) <==> x.name = value"},
2390 {"__delattr__", (wrapperfunc)wrap_delattr,
2391 "x.__delattr__('name') <==> del x.name"},
2392 {0}
2393};
2394
2395static PyObject *
2396wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2397{
2398 hashfunc func = (hashfunc)wrapped;
2399 long res;
2400
2401 if (!PyArg_ParseTuple(args, ""))
2402 return NULL;
2403 res = (*func)(self);
2404 if (res == -1 && PyErr_Occurred())
2405 return NULL;
2406 return PyInt_FromLong(res);
2407}
2408
2409static struct wrapperbase tab_hash[] = {
2410 {"__hash__", (wrapperfunc)wrap_hashfunc,
2411 "x.__hash__() <==> hash(x)"},
2412 {0}
2413};
2414
2415static PyObject *
2416wrap_call(PyObject *self, PyObject *args, void *wrapped)
2417{
2418 ternaryfunc func = (ternaryfunc)wrapped;
2419
2420 /* XXX What about keyword arguments? */
2421 return (*func)(self, args, NULL);
2422}
2423
2424static struct wrapperbase tab_call[] = {
2425 {"__call__", (wrapperfunc)wrap_call,
2426 "x.__call__(...) <==> x(...)"},
2427 {0}
2428};
2429
2430static struct wrapperbase tab_str[] = {
2431 {"__str__", (wrapperfunc)wrap_unaryfunc,
2432 "x.__str__() <==> str(x)"},
2433 {0}
2434};
2435
2436static PyObject *
2437wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2438{
2439 richcmpfunc func = (richcmpfunc)wrapped;
2440 PyObject *other;
2441
2442 if (!PyArg_ParseTuple(args, "O", &other))
2443 return NULL;
2444 return (*func)(self, other, op);
2445}
2446
2447#undef RICHCMP_WRAPPER
2448#define RICHCMP_WRAPPER(NAME, OP) \
2449static PyObject * \
2450richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2451{ \
2452 return wrap_richcmpfunc(self, args, wrapped, OP); \
2453}
2454
Jack Jansen8e938b42001-08-08 15:29:49 +00002455RICHCMP_WRAPPER(lt, Py_LT)
2456RICHCMP_WRAPPER(le, Py_LE)
2457RICHCMP_WRAPPER(eq, Py_EQ)
2458RICHCMP_WRAPPER(ne, Py_NE)
2459RICHCMP_WRAPPER(gt, Py_GT)
2460RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002461
2462#undef RICHCMP_ENTRY
2463#define RICHCMP_ENTRY(NAME, EXPR) \
2464 {"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
2465 "x.__" #NAME "__(y) <==> " EXPR}
2466
2467static struct wrapperbase tab_richcmp[] = {
2468 RICHCMP_ENTRY(lt, "x<y"),
2469 RICHCMP_ENTRY(le, "x<=y"),
2470 RICHCMP_ENTRY(eq, "x==y"),
2471 RICHCMP_ENTRY(ne, "x!=y"),
2472 RICHCMP_ENTRY(gt, "x>y"),
2473 RICHCMP_ENTRY(ge, "x>=y"),
2474 {0}
2475};
2476
2477static struct wrapperbase tab_iter[] = {
2478 {"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
2479 {0}
2480};
2481
2482static PyObject *
2483wrap_next(PyObject *self, PyObject *args, void *wrapped)
2484{
2485 unaryfunc func = (unaryfunc)wrapped;
2486 PyObject *res;
2487
2488 if (!PyArg_ParseTuple(args, ""))
2489 return NULL;
2490 res = (*func)(self);
2491 if (res == NULL && !PyErr_Occurred())
2492 PyErr_SetNone(PyExc_StopIteration);
2493 return res;
2494}
2495
2496static struct wrapperbase tab_next[] = {
2497 {"next", (wrapperfunc)wrap_next,
2498 "x.next() -> the next value, or raise StopIteration"},
2499 {0}
2500};
2501
2502static PyObject *
2503wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2504{
2505 descrgetfunc func = (descrgetfunc)wrapped;
2506 PyObject *obj;
2507 PyObject *type = NULL;
2508
2509 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2510 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002511 return (*func)(self, obj, type);
2512}
2513
2514static struct wrapperbase tab_descr_get[] = {
2515 {"__get__", (wrapperfunc)wrap_descr_get,
2516 "descr.__get__(obj, type) -> value"},
2517 {0}
2518};
2519
2520static PyObject *
2521wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
2522{
2523 descrsetfunc func = (descrsetfunc)wrapped;
2524 PyObject *obj, *value;
2525 int ret;
2526
2527 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2528 return NULL;
2529 ret = (*func)(self, obj, value);
2530 if (ret < 0)
2531 return NULL;
2532 Py_INCREF(Py_None);
2533 return Py_None;
2534}
2535
2536static struct wrapperbase tab_descr_set[] = {
2537 {"__set__", (wrapperfunc)wrap_descrsetfunc,
2538 "descr.__set__(obj, value)"},
2539 {0}
2540};
2541
2542static PyObject *
2543wrap_init(PyObject *self, PyObject *args, void *wrapped)
2544{
2545 initproc func = (initproc)wrapped;
2546
2547 /* XXX What about keyword arguments? */
2548 if (func(self, args, NULL) < 0)
2549 return NULL;
2550 Py_INCREF(Py_None);
2551 return Py_None;
2552}
2553
2554static struct wrapperbase tab_init[] = {
2555 {"__init__", (wrapperfunc)wrap_init,
2556 "x.__init__(...) initializes x; "
Guido van Rossumd016e452001-10-01 13:17:24 +00002557 "see x.__class__.__doc__ for signature"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002558 {0}
2559};
2560
2561static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002562tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002563{
Barry Warsaw60f01882001-08-22 19:24:42 +00002564 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002565 PyObject *arg0, *res;
2566
2567 if (self == NULL || !PyType_Check(self))
2568 Py_FatalError("__new__() called with non-type 'self'");
2569 type = (PyTypeObject *)self;
2570 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002571 PyErr_Format(PyExc_TypeError,
2572 "%s.__new__(): not enough arguments",
2573 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002574 return NULL;
2575 }
2576 arg0 = PyTuple_GET_ITEM(args, 0);
2577 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002578 PyErr_Format(PyExc_TypeError,
2579 "%s.__new__(X): X is not a type object (%s)",
2580 type->tp_name,
2581 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002582 return NULL;
2583 }
2584 subtype = (PyTypeObject *)arg0;
2585 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002586 PyErr_Format(PyExc_TypeError,
2587 "%s.__new__(%s): %s is not a subtype of %s",
2588 type->tp_name,
2589 subtype->tp_name,
2590 subtype->tp_name,
2591 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002592 return NULL;
2593 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002594
2595 /* Check that the use doesn't do something silly and unsafe like
2596 object.__new__(dictionary). To do this, we check that the
2597 most derived base that's not a heap type is this type. */
2598 staticbase = subtype;
2599 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2600 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002601 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002602 PyErr_Format(PyExc_TypeError,
2603 "%s.__new__(%s) is not safe, use %s.__new__()",
2604 type->tp_name,
2605 subtype->tp_name,
2606 staticbase == NULL ? "?" : staticbase->tp_name);
2607 return NULL;
2608 }
2609
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002610 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2611 if (args == NULL)
2612 return NULL;
2613 res = type->tp_new(subtype, args, kwds);
2614 Py_DECREF(args);
2615 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616}
2617
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002618static struct PyMethodDef tp_new_methoddef[] = {
2619 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2620 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002621 {0}
2622};
2623
2624static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002625add_tp_new_wrapper(PyTypeObject *type)
2626{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002627 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002628
Guido van Rossumf040ede2001-08-07 16:40:56 +00002629 if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
2630 return 0;
2631 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002632 if (func == NULL)
2633 return -1;
2634 return PyDict_SetItemString(type->tp_defined, "__new__", func);
2635}
2636
Guido van Rossum13d52f02001-08-10 21:24:08 +00002637static int
2638add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
2639{
2640 PyObject *dict = type->tp_defined;
2641
2642 for (; wraps->name != NULL; wraps++) {
2643 PyObject *descr;
2644 if (PyDict_GetItemString(dict, wraps->name))
2645 continue;
2646 descr = PyDescr_NewWrapper(type, wraps, wrapped);
2647 if (descr == NULL)
2648 return -1;
2649 if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
2650 return -1;
2651 Py_DECREF(descr);
2652 }
2653 return 0;
2654}
2655
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002656/* This function is called by PyType_Ready() to populate the type's
Guido van Rossumf040ede2001-08-07 16:40:56 +00002657 dictionary with method descriptors for function slots. For each
2658 function slot (like tp_repr) that's defined in the type, one or
2659 more corresponding descriptors are added in the type's tp_defined
2660 dictionary under the appropriate name (like __repr__). Some
2661 function slots cause more than one descriptor to be added (for
2662 example, the nb_add slot adds both __add__ and __radd__
2663 descriptors) and some function slots compete for the same
2664 descriptor (for example both sq_item and mp_subscript generate a
2665 __getitem__ descriptor). This only adds new descriptors and
2666 doesn't overwrite entries in tp_defined that were previously
2667 defined. The descriptors contain a reference to the C function
2668 they must call, so that it's safe if they are copied into a
2669 subtype's __dict__ and the subtype has a different C function in
2670 its slot -- calling the method defined by the descriptor will call
2671 the C function that was used to create it, rather than the C
2672 function present in the slot when it is called. (This is important
2673 because a subtype may have a C function in the slot that calls the
2674 method from the dictionary, and we want to avoid infinite recursion
2675 here.) */
2676
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002677static int
Tim Peters6d6c1a32001-08-02 04:15:00 +00002678add_operators(PyTypeObject *type)
2679{
2680 PySequenceMethods *sq;
2681 PyMappingMethods *mp;
2682 PyNumberMethods *nb;
2683
2684#undef ADD
2685#define ADD(SLOT, TABLE) \
2686 if (SLOT) { \
2687 if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
2688 return -1; \
2689 }
2690
2691 if ((sq = type->tp_as_sequence) != NULL) {
2692 ADD(sq->sq_length, tab_len);
2693 ADD(sq->sq_concat, tab_concat);
2694 ADD(sq->sq_repeat, tab_mul_int);
2695 ADD(sq->sq_item, tab_getitem_int);
2696 ADD(sq->sq_slice, tab_getslice);
2697 ADD(sq->sq_ass_item, tab_setitem_int);
2698 ADD(sq->sq_ass_slice, tab_setslice);
2699 ADD(sq->sq_contains, tab_contains);
2700 ADD(sq->sq_inplace_concat, tab_iadd);
2701 ADD(sq->sq_inplace_repeat, tab_imul_int);
2702 }
2703
2704 if ((mp = type->tp_as_mapping) != NULL) {
2705 if (sq->sq_length == NULL)
2706 ADD(mp->mp_length, tab_len);
2707 ADD(mp->mp_subscript, tab_getitem);
2708 ADD(mp->mp_ass_subscript, tab_setitem);
2709 }
2710
2711 /* We don't support "old-style numbers" because their binary
2712 operators require that both arguments have the same type;
2713 the wrappers here only work for new-style numbers. */
2714 if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2715 (nb = type->tp_as_number) != NULL) {
2716 ADD(nb->nb_add, tab_add);
2717 ADD(nb->nb_subtract, tab_sub);
2718 ADD(nb->nb_multiply, tab_mul);
2719 ADD(nb->nb_divide, tab_div);
2720 ADD(nb->nb_remainder, tab_mod);
2721 ADD(nb->nb_divmod, tab_divmod);
2722 ADD(nb->nb_power, tab_pow);
2723 ADD(nb->nb_negative, tab_neg);
2724 ADD(nb->nb_positive, tab_pos);
2725 ADD(nb->nb_absolute, tab_abs);
2726 ADD(nb->nb_nonzero, tab_nonzero);
2727 ADD(nb->nb_invert, tab_invert);
2728 ADD(nb->nb_lshift, tab_lshift);
2729 ADD(nb->nb_rshift, tab_rshift);
2730 ADD(nb->nb_and, tab_and);
2731 ADD(nb->nb_xor, tab_xor);
2732 ADD(nb->nb_or, tab_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002733 ADD(nb->nb_coerce, tab_coerce);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002734 ADD(nb->nb_int, tab_int);
2735 ADD(nb->nb_long, tab_long);
2736 ADD(nb->nb_float, tab_float);
2737 ADD(nb->nb_oct, tab_oct);
2738 ADD(nb->nb_hex, tab_hex);
2739 ADD(nb->nb_inplace_add, tab_iadd);
2740 ADD(nb->nb_inplace_subtract, tab_isub);
2741 ADD(nb->nb_inplace_multiply, tab_imul);
2742 ADD(nb->nb_inplace_divide, tab_idiv);
2743 ADD(nb->nb_inplace_remainder, tab_imod);
2744 ADD(nb->nb_inplace_power, tab_ipow);
2745 ADD(nb->nb_inplace_lshift, tab_ilshift);
2746 ADD(nb->nb_inplace_rshift, tab_irshift);
2747 ADD(nb->nb_inplace_and, tab_iand);
2748 ADD(nb->nb_inplace_xor, tab_ixor);
2749 ADD(nb->nb_inplace_or, tab_ior);
Guido van Rossum874f15a2001-09-25 21:16:33 +00002750 if (type->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2751 ADD(nb->nb_floor_divide, tab_floordiv);
2752 ADD(nb->nb_true_divide, tab_truediv);
2753 ADD(nb->nb_inplace_floor_divide, tab_ifloordiv);
2754 ADD(nb->nb_inplace_true_divide, tab_itruediv);
2755 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002756 }
2757
2758 ADD(type->tp_getattro, tab_getattr);
2759 ADD(type->tp_setattro, tab_setattr);
2760 ADD(type->tp_compare, tab_cmp);
2761 ADD(type->tp_repr, tab_repr);
2762 ADD(type->tp_hash, tab_hash);
2763 ADD(type->tp_call, tab_call);
2764 ADD(type->tp_str, tab_str);
2765 ADD(type->tp_richcompare, tab_richcmp);
2766 ADD(type->tp_iter, tab_iter);
2767 ADD(type->tp_iternext, tab_next);
2768 ADD(type->tp_descr_get, tab_descr_get);
2769 ADD(type->tp_descr_set, tab_descr_set);
2770 ADD(type->tp_init, tab_init);
2771
Guido van Rossumf040ede2001-08-07 16:40:56 +00002772 if (type->tp_new != NULL) {
2773 if (add_tp_new_wrapper(type) < 0)
2774 return -1;
2775 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002776
2777 return 0;
2778}
2779
Guido van Rossumf040ede2001-08-07 16:40:56 +00002780/* Slot wrappers that call the corresponding __foo__ slot. See comments
2781 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782
Guido van Rossumdc91b992001-08-08 22:26:22 +00002783#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002785FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002787 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002788 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002789}
2790
Guido van Rossumdc91b992001-08-08 22:26:22 +00002791#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002792static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002793FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002795 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002796 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002797}
2798
Guido van Rossumdc91b992001-08-08 22:26:22 +00002799
2800#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002802FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002804 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002805 int do_other = self->ob_type != other->ob_type && \
2806 other->ob_type->tp_as_number != NULL && \
2807 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002808 if (self->ob_type->tp_as_number != NULL && \
2809 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2810 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002811 if (do_other && \
2812 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2813 r = call_maybe( \
2814 other, ROPSTR, &rcache_str, "(O)", self); \
2815 if (r != Py_NotImplemented) \
2816 return r; \
2817 Py_DECREF(r); \
2818 do_other = 0; \
2819 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002820 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002821 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002822 if (r != Py_NotImplemented || \
2823 other->ob_type == self->ob_type) \
2824 return r; \
2825 Py_DECREF(r); \
2826 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002827 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002828 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002829 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002830 } \
2831 Py_INCREF(Py_NotImplemented); \
2832 return Py_NotImplemented; \
2833}
2834
2835#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2836 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2837
2838#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2839static PyObject * \
2840FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2841{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002842 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002843 return call_method(self, OPSTR, &cache_str, \
2844 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002845}
2846
2847static int
2848slot_sq_length(PyObject *self)
2849{
Guido van Rossum2730b132001-08-28 18:22:14 +00002850 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002851 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002852 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002853
2854 if (res == NULL)
2855 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002856 len = (int)PyInt_AsLong(res);
2857 Py_DECREF(res);
2858 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002859}
2860
Guido van Rossumdc91b992001-08-08 22:26:22 +00002861SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2862SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002863
2864/* Super-optimized version of slot_sq_item.
2865 Other slots could do the same... */
2866static PyObject *
2867slot_sq_item(PyObject *self, int i)
2868{
2869 static PyObject *getitem_str;
2870 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2871 descrgetfunc f;
2872
2873 if (getitem_str == NULL) {
2874 getitem_str = PyString_InternFromString("__getitem__");
2875 if (getitem_str == NULL)
2876 return NULL;
2877 }
2878 func = _PyType_Lookup(self->ob_type, getitem_str);
2879 if (func != NULL) {
2880 if (func->ob_type == &PyWrapperDescr_Type) {
2881 PyWrapperDescrObject *wrapper =
2882 (PyWrapperDescrObject *)func;
2883 if (wrapper->d_base->wrapper == wrap_sq_item) {
2884 intargfunc f;
2885 f = (intargfunc)(wrapper->d_wrapped);
2886 return f(self, i);
2887 }
2888 }
2889 if ((f = func->ob_type->tp_descr_get) == NULL)
2890 Py_INCREF(func);
2891 else
2892 func = f(func, self, (PyObject *)(self->ob_type));
2893 ival = PyInt_FromLong(i);
2894 if (ival != NULL) {
2895 args = PyTuple_New(1);
2896 if (args != NULL) {
2897 PyTuple_SET_ITEM(args, 0, ival);
2898 retval = PyObject_Call(func, args, NULL);
2899 Py_XDECREF(args);
2900 Py_XDECREF(func);
2901 return retval;
2902 }
2903 }
2904 }
2905 else {
2906 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2907 }
2908 Py_XDECREF(args);
2909 Py_XDECREF(ival);
2910 Py_XDECREF(func);
2911 return NULL;
2912}
2913
Guido van Rossumdc91b992001-08-08 22:26:22 +00002914SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002915
2916static int
2917slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2918{
2919 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002920 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002921
2922 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002923 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002924 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002925 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002926 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002927 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002928 if (res == NULL)
2929 return -1;
2930 Py_DECREF(res);
2931 return 0;
2932}
2933
2934static int
2935slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2936{
2937 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002938 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002939
2940 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002941 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002942 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002943 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002944 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002945 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946 if (res == NULL)
2947 return -1;
2948 Py_DECREF(res);
2949 return 0;
2950}
2951
2952static int
2953slot_sq_contains(PyObject *self, PyObject *value)
2954{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002955 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002956 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002957
Guido van Rossum55f20992001-10-01 17:18:22 +00002958 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002959
2960 if (func != NULL) {
2961 args = Py_BuildValue("(O)", value);
2962 if (args == NULL)
2963 res = NULL;
2964 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002965 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002966 Py_DECREF(args);
2967 }
2968 Py_DECREF(func);
2969 if (res == NULL)
2970 return -1;
2971 return PyObject_IsTrue(res);
2972 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002973 else if (PyErr_Occurred())
2974 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002975 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002976 return _PySequence_IterSearch(self, value,
2977 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002978 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002979}
2980
Guido van Rossumdc91b992001-08-08 22:26:22 +00002981SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2982SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002983
2984#define slot_mp_length slot_sq_length
2985
Guido van Rossumdc91b992001-08-08 22:26:22 +00002986SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987
2988static int
2989slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2990{
2991 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002992 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002993
2994 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002995 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002996 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002997 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002998 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002999 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003000 if (res == NULL)
3001 return -1;
3002 Py_DECREF(res);
3003 return 0;
3004}
3005
Guido van Rossumdc91b992001-08-08 22:26:22 +00003006SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3007SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3008SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3009SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3010SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3011SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3012
3013staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
3014
3015SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3016 nb_power, "__pow__", "__rpow__")
3017
3018static PyObject *
3019slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3020{
Guido van Rossum2730b132001-08-28 18:22:14 +00003021 static PyObject *pow_str;
3022
Guido van Rossumdc91b992001-08-08 22:26:22 +00003023 if (modulus == Py_None)
3024 return slot_nb_power_binary(self, other);
3025 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00003026 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003027 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003028}
3029
3030SLOT0(slot_nb_negative, "__neg__")
3031SLOT0(slot_nb_positive, "__pos__")
3032SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003033
3034static int
3035slot_nb_nonzero(PyObject *self)
3036{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003037 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003038 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003039
Guido van Rossum55f20992001-10-01 17:18:22 +00003040 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003041 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003042 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003043 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003044 func = lookup_maybe(self, "__len__", &len_str);
3045 if (func == NULL) {
3046 if (PyErr_Occurred())
3047 return -1;
3048 else
3049 return 1;
3050 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003051 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003052 res = PyObject_CallObject(func, NULL);
3053 Py_DECREF(func);
3054 if (res == NULL)
3055 return -1;
3056 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003057}
3058
Guido van Rossumdc91b992001-08-08 22:26:22 +00003059SLOT0(slot_nb_invert, "__invert__")
3060SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3061SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3062SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3063SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3064SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003065
3066static int
3067slot_nb_coerce(PyObject **a, PyObject **b)
3068{
3069 static PyObject *coerce_str;
3070 PyObject *self = *a, *other = *b;
3071
3072 if (self->ob_type->tp_as_number != NULL &&
3073 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3074 PyObject *r;
3075 r = call_maybe(
3076 self, "__coerce__", &coerce_str, "(O)", other);
3077 if (r == NULL)
3078 return -1;
3079 if (r == Py_NotImplemented) {
3080 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003081 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003082 else {
3083 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3084 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003085 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003086 Py_DECREF(r);
3087 return -1;
3088 }
3089 *a = PyTuple_GET_ITEM(r, 0);
3090 Py_INCREF(*a);
3091 *b = PyTuple_GET_ITEM(r, 1);
3092 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003093 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003094 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003095 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003096 }
3097 if (other->ob_type->tp_as_number != NULL &&
3098 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3099 PyObject *r;
3100 r = call_maybe(
3101 other, "__coerce__", &coerce_str, "(O)", self);
3102 if (r == NULL)
3103 return -1;
3104 if (r == Py_NotImplemented) {
3105 Py_DECREF(r);
3106 return 1;
3107 }
3108 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3109 PyErr_SetString(PyExc_TypeError,
3110 "__coerce__ didn't return a 2-tuple");
3111 Py_DECREF(r);
3112 return -1;
3113 }
3114 *a = PyTuple_GET_ITEM(r, 1);
3115 Py_INCREF(*a);
3116 *b = PyTuple_GET_ITEM(r, 0);
3117 Py_INCREF(*b);
3118 Py_DECREF(r);
3119 return 0;
3120 }
3121 return 1;
3122}
3123
Guido van Rossumdc91b992001-08-08 22:26:22 +00003124SLOT0(slot_nb_int, "__int__")
3125SLOT0(slot_nb_long, "__long__")
3126SLOT0(slot_nb_float, "__float__")
3127SLOT0(slot_nb_oct, "__oct__")
3128SLOT0(slot_nb_hex, "__hex__")
3129SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3130SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3131SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3132SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3133SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3134SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3135SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3136SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3137SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3138SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3139SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3140SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3141 "__floordiv__", "__rfloordiv__")
3142SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3143SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3144SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003145
3146static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003147half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003148{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003149 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003150 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003151 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152
Guido van Rossum60718732001-08-28 17:47:51 +00003153 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003154 if (func == NULL) {
3155 PyErr_Clear();
3156 }
3157 else {
3158 args = Py_BuildValue("(O)", other);
3159 if (args == NULL)
3160 res = NULL;
3161 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003162 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003163 Py_DECREF(args);
3164 }
3165 if (res != Py_NotImplemented) {
3166 if (res == NULL)
3167 return -2;
3168 c = PyInt_AsLong(res);
3169 Py_DECREF(res);
3170 if (c == -1 && PyErr_Occurred())
3171 return -2;
3172 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3173 }
3174 Py_DECREF(res);
3175 }
3176 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003177}
3178
Guido van Rossumab3b0342001-09-18 20:38:53 +00003179/* This slot is published for the benefit of try_3way_compare in object.c */
3180int
3181_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003182{
3183 int c;
3184
Guido van Rossumab3b0342001-09-18 20:38:53 +00003185 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003186 c = half_compare(self, other);
3187 if (c <= 1)
3188 return c;
3189 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003190 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003191 c = half_compare(other, self);
3192 if (c < -1)
3193 return -2;
3194 if (c <= 1)
3195 return -c;
3196 }
3197 return (void *)self < (void *)other ? -1 :
3198 (void *)self > (void *)other ? 1 : 0;
3199}
3200
3201static PyObject *
3202slot_tp_repr(PyObject *self)
3203{
3204 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003205 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003206
Guido van Rossum60718732001-08-28 17:47:51 +00003207 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003208 if (func != NULL) {
3209 res = PyEval_CallObject(func, NULL);
3210 Py_DECREF(func);
3211 return res;
3212 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003213 PyErr_Clear();
3214 return PyString_FromFormat("<%s object at %p>",
3215 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003216}
3217
3218static PyObject *
3219slot_tp_str(PyObject *self)
3220{
3221 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003222 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003223
Guido van Rossum60718732001-08-28 17:47:51 +00003224 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003225 if (func != NULL) {
3226 res = PyEval_CallObject(func, NULL);
3227 Py_DECREF(func);
3228 return res;
3229 }
3230 else {
3231 PyErr_Clear();
3232 return slot_tp_repr(self);
3233 }
3234}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003235
3236static long
3237slot_tp_hash(PyObject *self)
3238{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003239 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003240 static PyObject *hash_str, *eq_str, *cmp_str;
3241
Tim Peters6d6c1a32001-08-02 04:15:00 +00003242 long h;
3243
Guido van Rossum60718732001-08-28 17:47:51 +00003244 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003245
3246 if (func != NULL) {
3247 res = PyEval_CallObject(func, NULL);
3248 Py_DECREF(func);
3249 if (res == NULL)
3250 return -1;
3251 h = PyInt_AsLong(res);
3252 }
3253 else {
3254 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003255 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003256 if (func == NULL) {
3257 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003258 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003259 }
3260 if (func != NULL) {
3261 Py_DECREF(func);
3262 PyErr_SetString(PyExc_TypeError, "unhashable type");
3263 return -1;
3264 }
3265 PyErr_Clear();
3266 h = _Py_HashPointer((void *)self);
3267 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003268 if (h == -1 && !PyErr_Occurred())
3269 h = -2;
3270 return h;
3271}
3272
3273static PyObject *
3274slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3275{
Guido van Rossum60718732001-08-28 17:47:51 +00003276 static PyObject *call_str;
3277 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003278 PyObject *res;
3279
3280 if (meth == NULL)
3281 return NULL;
3282 res = PyObject_Call(meth, args, kwds);
3283 Py_DECREF(meth);
3284 return res;
3285}
3286
Tim Peters6d6c1a32001-08-02 04:15:00 +00003287static PyObject *
3288slot_tp_getattro(PyObject *self, PyObject *name)
3289{
3290 PyTypeObject *tp = self->ob_type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003291 PyObject *getattr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003292 static PyObject *getattr_str = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003293
Guido van Rossum8e248182001-08-12 05:17:56 +00003294 if (getattr_str == NULL) {
Guido van Rossum867a8d22001-09-21 19:29:08 +00003295 getattr_str = PyString_InternFromString("__getattribute__");
Guido van Rossum8e248182001-08-12 05:17:56 +00003296 if (getattr_str == NULL)
3297 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003298 }
Guido van Rossum8e248182001-08-12 05:17:56 +00003299 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossumc3542212001-08-16 09:18:56 +00003300 if (getattr == NULL) {
3301 /* Avoid further slowdowns */
3302 if (tp->tp_getattro == slot_tp_getattro)
3303 tp->tp_getattro = PyObject_GenericGetAttr;
Guido van Rossum8e248182001-08-12 05:17:56 +00003304 return PyObject_GenericGetAttr(self, name);
Guido van Rossumc3542212001-08-16 09:18:56 +00003305 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003306 return PyObject_CallFunction(getattr, "OO", self, name);
3307}
3308
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003309static PyObject *
3310slot_tp_getattr_hook(PyObject *self, PyObject *name)
3311{
3312 PyTypeObject *tp = self->ob_type;
3313 PyObject *getattr, *getattribute, *res;
3314 static PyObject *getattribute_str = NULL;
3315 static PyObject *getattr_str = NULL;
3316
3317 if (getattr_str == NULL) {
3318 getattr_str = PyString_InternFromString("__getattr__");
3319 if (getattr_str == NULL)
3320 return NULL;
3321 }
3322 if (getattribute_str == NULL) {
3323 getattribute_str =
3324 PyString_InternFromString("__getattribute__");
3325 if (getattribute_str == NULL)
3326 return NULL;
3327 }
3328 getattr = _PyType_Lookup(tp, getattr_str);
3329 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003330 if (getattribute != NULL &&
3331 getattribute->ob_type == &PyWrapperDescr_Type &&
3332 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3333 PyObject_GenericGetAttr)
3334 getattribute = NULL;
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003335 if (getattr == NULL && getattribute == NULL) {
3336 /* Avoid further slowdowns */
Guido van Rossum1e1de1c2001-10-03 13:58:35 +00003337 /* XXX This is questionable: it means that a class that
3338 isn't born with __getattr__ or __getattribute__ cannot
3339 acquire them in later life. But it's a relatively big
3340 speedup, so I'm keeping it in for now. If this is
3341 removed, you can also remove the "def __getattr__" from
3342 class C (marked with another XXX comment) in dynamics()
3343 in Lib/test/test_descr.py. */
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003344 if (tp->tp_getattro == slot_tp_getattr_hook)
3345 tp->tp_getattro = PyObject_GenericGetAttr;
3346 return PyObject_GenericGetAttr(self, name);
3347 }
3348 if (getattribute == NULL)
3349 res = PyObject_GenericGetAttr(self, name);
3350 else
3351 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum3926a632001-09-25 16:25:58 +00003352 if (getattr != NULL &&
3353 res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003354 PyErr_Clear();
3355 res = PyObject_CallFunction(getattr, "OO", self, name);
3356 }
3357 return res;
3358}
3359
Tim Peters6d6c1a32001-08-02 04:15:00 +00003360static int
3361slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3362{
3363 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003364 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365
3366 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003367 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003368 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003369 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003370 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003371 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003372 if (res == NULL)
3373 return -1;
3374 Py_DECREF(res);
3375 return 0;
3376}
3377
3378/* Map rich comparison operators to their __xx__ namesakes */
3379static char *name_op[] = {
3380 "__lt__",
3381 "__le__",
3382 "__eq__",
3383 "__ne__",
3384 "__gt__",
3385 "__ge__",
3386};
3387
3388static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003389half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003390{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003391 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003392 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393
Guido van Rossum60718732001-08-28 17:47:51 +00003394 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003395 if (func == NULL) {
3396 PyErr_Clear();
3397 Py_INCREF(Py_NotImplemented);
3398 return Py_NotImplemented;
3399 }
3400 args = Py_BuildValue("(O)", other);
3401 if (args == NULL)
3402 res = NULL;
3403 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003404 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003405 Py_DECREF(args);
3406 }
3407 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003408 return res;
3409}
3410
Guido van Rossumb8f63662001-08-15 23:57:02 +00003411/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3412static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3413
3414static PyObject *
3415slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3416{
3417 PyObject *res;
3418
3419 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3420 res = half_richcompare(self, other, op);
3421 if (res != Py_NotImplemented)
3422 return res;
3423 Py_DECREF(res);
3424 }
3425 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3426 res = half_richcompare(other, self, swapped_op[op]);
3427 if (res != Py_NotImplemented) {
3428 return res;
3429 }
3430 Py_DECREF(res);
3431 }
3432 Py_INCREF(Py_NotImplemented);
3433 return Py_NotImplemented;
3434}
3435
3436static PyObject *
3437slot_tp_iter(PyObject *self)
3438{
3439 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003440 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003441
Guido van Rossum60718732001-08-28 17:47:51 +00003442 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003443 if (func != NULL) {
3444 res = PyObject_CallObject(func, NULL);
3445 Py_DECREF(func);
3446 return res;
3447 }
3448 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003449 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003450 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003451 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003452 return NULL;
3453 }
3454 Py_DECREF(func);
3455 return PySeqIter_New(self);
3456}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003457
3458static PyObject *
3459slot_tp_iternext(PyObject *self)
3460{
Guido van Rossum2730b132001-08-28 18:22:14 +00003461 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003462 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003463}
3464
Guido van Rossum1a493502001-08-17 16:47:50 +00003465static PyObject *
3466slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3467{
3468 PyTypeObject *tp = self->ob_type;
3469 PyObject *get;
3470 static PyObject *get_str = NULL;
3471
3472 if (get_str == NULL) {
3473 get_str = PyString_InternFromString("__get__");
3474 if (get_str == NULL)
3475 return NULL;
3476 }
3477 get = _PyType_Lookup(tp, get_str);
3478 if (get == NULL) {
3479 /* Avoid further slowdowns */
3480 if (tp->tp_descr_get == slot_tp_descr_get)
3481 tp->tp_descr_get = NULL;
3482 Py_INCREF(self);
3483 return self;
3484 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003485 if (obj == NULL)
3486 obj = Py_None;
3487 if (type == NULL)
3488 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003489 return PyObject_CallFunction(get, "OOO", self, obj, type);
3490}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003491
3492static int
3493slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3494{
Guido van Rossum2c252392001-08-24 10:13:31 +00003495 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003496 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003497
3498 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003499 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003500 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003501 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003502 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003503 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003504 if (res == NULL)
3505 return -1;
3506 Py_DECREF(res);
3507 return 0;
3508}
3509
3510static int
3511slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3512{
Guido van Rossum60718732001-08-28 17:47:51 +00003513 static PyObject *init_str;
3514 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003515 PyObject *res;
3516
3517 if (meth == NULL)
3518 return -1;
3519 res = PyObject_Call(meth, args, kwds);
3520 Py_DECREF(meth);
3521 if (res == NULL)
3522 return -1;
3523 Py_DECREF(res);
3524 return 0;
3525}
3526
3527static PyObject *
3528slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3529{
3530 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3531 PyObject *newargs, *x;
3532 int i, n;
3533
3534 if (func == NULL)
3535 return NULL;
3536 assert(PyTuple_Check(args));
3537 n = PyTuple_GET_SIZE(args);
3538 newargs = PyTuple_New(n+1);
3539 if (newargs == NULL)
3540 return NULL;
3541 Py_INCREF(type);
3542 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3543 for (i = 0; i < n; i++) {
3544 x = PyTuple_GET_ITEM(args, i);
3545 Py_INCREF(x);
3546 PyTuple_SET_ITEM(newargs, i+1, x);
3547 }
3548 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003549 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003550 Py_DECREF(func);
3551 return x;
3552}
3553
Guido van Rossumf040ede2001-08-07 16:40:56 +00003554/* This is called at the very end of type_new() (even after
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003555 PyType_Ready()) to complete the initialization of dynamic types.
Guido van Rossumf040ede2001-08-07 16:40:56 +00003556 The dict argument is the dictionary argument passed to type_new(),
3557 which is the local namespace of the class statement, in other
3558 words, it contains the methods. For each special method (like
3559 __repr__) defined in the dictionary, the corresponding function
3560 slot in the type object (like tp_repr) is set to a special function
3561 whose name is 'slot_' followed by the slot name and whose signature
3562 is whatever is required for that slot. These slot functions look
3563 up the corresponding method in the type's dictionary and call it.
3564 The slot functions have to take care of the various peculiarities
3565 of the mapping between slots and special methods, such as mapping
3566 one slot to multiple methods (tp_richcompare <--> __le__, __lt__
3567 etc.) or mapping multiple slots to a single method (sq_item,
3568 mp_subscript <--> __getitem__). */
3569
Tim Peters6d6c1a32001-08-02 04:15:00 +00003570static void
3571override_slots(PyTypeObject *type, PyObject *dict)
3572{
3573 PySequenceMethods *sq = type->tp_as_sequence;
3574 PyMappingMethods *mp = type->tp_as_mapping;
3575 PyNumberMethods *nb = type->tp_as_number;
3576
Guido van Rossumdc91b992001-08-08 22:26:22 +00003577#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003578 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003579 sq->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003580 }
3581
Guido van Rossumdc91b992001-08-08 22:26:22 +00003582#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003583 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003584 mp->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585 }
3586
Guido van Rossumdc91b992001-08-08 22:26:22 +00003587#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003588 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003589 nb->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003590 }
3591
Guido van Rossumdc91b992001-08-08 22:26:22 +00003592#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
Guido van Rossum8e248182001-08-12 05:17:56 +00003593 if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003594 type->SLOTNAME = FUNCNAME; \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003595 }
3596
Guido van Rossumdc91b992001-08-08 22:26:22 +00003597 SQSLOT("__len__", sq_length, slot_sq_length);
3598 SQSLOT("__add__", sq_concat, slot_sq_concat);
3599 SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
3600 SQSLOT("__getitem__", sq_item, slot_sq_item);
3601 SQSLOT("__getslice__", sq_slice, slot_sq_slice);
3602 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
3603 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
3604 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
3605 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
3606 SQSLOT("__contains__", sq_contains, slot_sq_contains);
3607 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
3608 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609
Guido van Rossumdc91b992001-08-08 22:26:22 +00003610 MPSLOT("__len__", mp_length, slot_mp_length);
3611 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
3612 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
3613 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003614
Guido van Rossumdc91b992001-08-08 22:26:22 +00003615 NBSLOT("__add__", nb_add, slot_nb_add);
3616 NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
3617 NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
3618 NBSLOT("__div__", nb_divide, slot_nb_divide);
3619 NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
3620 NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
3621 NBSLOT("__pow__", nb_power, slot_nb_power);
3622 NBSLOT("__neg__", nb_negative, slot_nb_negative);
3623 NBSLOT("__pos__", nb_positive, slot_nb_positive);
3624 NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
3625 NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
3626 NBSLOT("__invert__", nb_invert, slot_nb_invert);
3627 NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
3628 NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
3629 NBSLOT("__and__", nb_and, slot_nb_and);
3630 NBSLOT("__xor__", nb_xor, slot_nb_xor);
3631 NBSLOT("__or__", nb_or, slot_nb_or);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003632 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003633 NBSLOT("__int__", nb_int, slot_nb_int);
3634 NBSLOT("__long__", nb_long, slot_nb_long);
3635 NBSLOT("__float__", nb_float, slot_nb_float);
3636 NBSLOT("__oct__", nb_oct, slot_nb_oct);
3637 NBSLOT("__hex__", nb_hex, slot_nb_hex);
3638 NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
3639 NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
3640 NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
3641 NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
3642 NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
3643 NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
3644 NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
3645 NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
3646 NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
3647 NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
3648 NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
3649 NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
3650 NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
3651 NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3652 slot_nb_inplace_floor_divide);
3653 NBSLOT("__itruediv__", nb_inplace_true_divide,
3654 slot_nb_inplace_true_divide);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003655
Guido van Rossum8e248182001-08-12 05:17:56 +00003656 if (dict == NULL ||
3657 PyDict_GetItemString(dict, "__str__") ||
Tim Peters6d6c1a32001-08-02 04:15:00 +00003658 PyDict_GetItemString(dict, "__repr__"))
3659 type->tp_print = NULL;
3660
Guido van Rossumab3b0342001-09-18 20:38:53 +00003661 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003662 TPSLOT("__repr__", tp_repr, slot_tp_repr);
3663 TPSLOT("__hash__", tp_hash, slot_tp_hash);
3664 TPSLOT("__call__", tp_call, slot_tp_call);
3665 TPSLOT("__str__", tp_str, slot_tp_str);
Guido van Rossum867a8d22001-09-21 19:29:08 +00003666 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattro);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003667 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003668 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
3669 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
3670 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
3671 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
3672 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
3673 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
3674 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
3675 TPSLOT("__iter__", tp_iter, slot_tp_iter);
3676 TPSLOT("next", tp_iternext, slot_tp_iternext);
3677 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
3678 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
3679 TPSLOT("__init__", tp_init, slot_tp_init);
3680 TPSLOT("__new__", tp_new, slot_tp_new);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003681}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003682
3683
3684/* Cooperative 'super' */
3685
3686typedef struct {
3687 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003688 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003689 PyObject *obj;
3690} superobject;
3691
Guido van Rossum6f799372001-09-20 20:46:19 +00003692static PyMemberDef super_members[] = {
3693 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3694 "the class invoking super()"},
3695 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3696 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003697 {0}
3698};
3699
Guido van Rossum705f0f52001-08-24 16:47:00 +00003700static void
3701super_dealloc(PyObject *self)
3702{
3703 superobject *su = (superobject *)self;
3704
Guido van Rossum048eb752001-10-02 21:24:57 +00003705 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003706 Py_XDECREF(su->obj);
3707 Py_XDECREF(su->type);
3708 self->ob_type->tp_free(self);
3709}
3710
3711static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003712super_repr(PyObject *self)
3713{
3714 superobject *su = (superobject *)self;
3715
3716 if (su->obj)
3717 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003718 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003719 su->type ? su->type->tp_name : "NULL",
3720 su->obj->ob_type->tp_name);
3721 else
3722 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003723 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003724 su->type ? su->type->tp_name : "NULL");
3725}
3726
3727static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003728super_getattro(PyObject *self, PyObject *name)
3729{
3730 superobject *su = (superobject *)self;
3731
3732 if (su->obj != NULL) {
3733 PyObject *mro, *res, *tmp;
3734 descrgetfunc f;
3735 int i, n;
3736
Guido van Rossume705ef12001-08-29 15:47:06 +00003737 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003738 if (mro == NULL)
3739 n = 0;
3740 else {
3741 assert(PyTuple_Check(mro));
3742 n = PyTuple_GET_SIZE(mro);
3743 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003744 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003745 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003746 break;
3747 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003748 if (i >= n && PyType_Check(su->obj)) {
3749 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003750 if (mro == NULL)
3751 n = 0;
3752 else {
3753 assert(PyTuple_Check(mro));
3754 n = PyTuple_GET_SIZE(mro);
3755 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003756 for (i = 0; i < n; i++) {
3757 if ((PyObject *)(su->type) ==
3758 PyTuple_GET_ITEM(mro, i))
3759 break;
3760 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003761 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003762 i++;
3763 res = NULL;
3764 for (; i < n; i++) {
3765 tmp = PyTuple_GET_ITEM(mro, i);
3766 assert(PyType_Check(tmp));
3767 res = PyDict_GetItem(
3768 ((PyTypeObject *)tmp)->tp_defined, name);
3769 if (res != NULL) {
3770 Py_INCREF(res);
3771 f = res->ob_type->tp_descr_get;
3772 if (f != NULL) {
3773 tmp = f(res, su->obj, res);
3774 Py_DECREF(res);
3775 res = tmp;
3776 }
3777 return res;
3778 }
3779 }
3780 }
3781 return PyObject_GenericGetAttr(self, name);
3782}
3783
3784static PyObject *
3785super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3786{
3787 superobject *su = (superobject *)self;
3788 superobject *new;
3789
3790 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3791 /* Not binding to an object, or already bound */
3792 Py_INCREF(self);
3793 return self;
3794 }
3795 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3796 if (new == NULL)
3797 return NULL;
3798 Py_INCREF(su->type);
3799 Py_INCREF(obj);
3800 new->type = su->type;
3801 new->obj = obj;
3802 return (PyObject *)new;
3803}
3804
3805static int
3806super_init(PyObject *self, PyObject *args, PyObject *kwds)
3807{
3808 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003809 PyTypeObject *type;
3810 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003811
3812 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3813 return -1;
3814 if (obj == Py_None)
3815 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003816 if (obj != NULL &&
3817 !PyType_IsSubtype(obj->ob_type, type) &&
3818 !(PyType_Check(obj) &&
3819 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003820 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003821 "super(type, obj): "
3822 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003823 return -1;
3824 }
3825 Py_INCREF(type);
3826 Py_XINCREF(obj);
3827 su->type = type;
3828 su->obj = obj;
3829 return 0;
3830}
3831
3832static char super_doc[] =
3833"super(type) -> unbound super object\n"
3834"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003835"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003836"Typical use to call a cooperative superclass method:\n"
3837"class C(B):\n"
3838" def meth(self, arg):\n"
3839" super(C, self).meth(arg)";
3840
Guido van Rossum048eb752001-10-02 21:24:57 +00003841static int
3842super_traverse(PyObject *self, visitproc visit, void *arg)
3843{
3844 superobject *su = (superobject *)self;
3845 int err;
3846
3847#define VISIT(SLOT) \
3848 if (SLOT) { \
3849 err = visit((PyObject *)(SLOT), arg); \
3850 if (err) \
3851 return err; \
3852 }
3853
3854 VISIT(su->obj);
3855 VISIT(su->type);
3856
3857#undef VISIT
3858
3859 return 0;
3860}
3861
Guido van Rossum705f0f52001-08-24 16:47:00 +00003862PyTypeObject PySuper_Type = {
3863 PyObject_HEAD_INIT(&PyType_Type)
3864 0, /* ob_size */
3865 "super", /* tp_name */
3866 sizeof(superobject), /* tp_basicsize */
3867 0, /* tp_itemsize */
3868 /* methods */
3869 super_dealloc, /* tp_dealloc */
3870 0, /* tp_print */
3871 0, /* tp_getattr */
3872 0, /* tp_setattr */
3873 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003874 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003875 0, /* tp_as_number */
3876 0, /* tp_as_sequence */
3877 0, /* tp_as_mapping */
3878 0, /* tp_hash */
3879 0, /* tp_call */
3880 0, /* tp_str */
3881 super_getattro, /* tp_getattro */
3882 0, /* tp_setattro */
3883 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00003884 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3885 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003886 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00003887 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003888 0, /* tp_clear */
3889 0, /* tp_richcompare */
3890 0, /* tp_weaklistoffset */
3891 0, /* tp_iter */
3892 0, /* tp_iternext */
3893 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003894 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003895 0, /* tp_getset */
3896 0, /* tp_base */
3897 0, /* tp_dict */
3898 super_descr_get, /* tp_descr_get */
3899 0, /* tp_descr_set */
3900 0, /* tp_dictoffset */
3901 super_init, /* tp_init */
3902 PyType_GenericAlloc, /* tp_alloc */
3903 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00003904 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003905};