blob: 39214e7a6f18e158698d4a6b84458a35ee062a1a [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__");
Guido van Rossum687ae002001-10-15 22:03:32 +000047 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000048 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{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000059 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000060 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 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000081}
82
Neil Schemenauerf23473f2001-10-21 22:28:58 +000083static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000084 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +000085 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000086 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 {0}
88};
89
Martin v. Löwis0163d6d2001-06-09 07:34:05 +000090static int
91type_compare(PyObject *v, PyObject *w)
92{
93 /* This is called with type objects only. So we
94 can just compare the addresses. */
95 Py_uintptr_t vv = (Py_uintptr_t)v;
96 Py_uintptr_t ww = (Py_uintptr_t)w;
97 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
98}
99
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000100static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000101type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000102{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000103 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000104 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000105
106 mod = type_module(type, NULL);
107 if (mod == NULL)
108 PyErr_Clear();
109 else if (!PyString_Check(mod)) {
110 Py_DECREF(mod);
111 mod = NULL;
112 }
113 name = type_name(type, NULL);
114 if (name == NULL)
115 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000116
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000117 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
118 kind = "class";
119 else
120 kind = "type";
121
Barry Warsaw7ce36942001-08-24 18:34:26 +0000122 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000123 rtn = PyString_FromFormat("<%s '%s.%s'>",
124 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000125 PyString_AS_STRING(mod),
126 PyString_AS_STRING(name));
127 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000128 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000129 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000130
Guido van Rossumc3542212001-08-16 09:18:56 +0000131 Py_XDECREF(mod);
132 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000133 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000134}
135
Tim Peters6d6c1a32001-08-02 04:15:00 +0000136static PyObject *
137type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
138{
139 PyObject *obj;
140
141 if (type->tp_new == NULL) {
142 PyErr_Format(PyExc_TypeError,
143 "cannot create '%.100s' instances",
144 type->tp_name);
145 return NULL;
146 }
147
Tim Peters3f996e72001-09-13 19:18:27 +0000148 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000149 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000150 /* Ugly exception: when the call was type(something),
151 don't call tp_init on the result. */
152 if (type == &PyType_Type &&
153 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
154 (kwds == NULL ||
155 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
156 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000157 type = obj->ob_type;
158 if (type->tp_init != NULL &&
159 type->tp_init(obj, args, kwds) < 0) {
160 Py_DECREF(obj);
161 obj = NULL;
162 }
163 }
164 return obj;
165}
166
167PyObject *
168PyType_GenericAlloc(PyTypeObject *type, int nitems)
169{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000170 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000171 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000172
173 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000174 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000175 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000176 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000177
Neil Schemenauerc806c882001-08-29 23:54:54 +0000178 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000179 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000180
Neil Schemenauerc806c882001-08-29 23:54:54 +0000181 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000182
Tim Peters6d6c1a32001-08-02 04:15:00 +0000183 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
184 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000185
Tim Peters6d6c1a32001-08-02 04:15:00 +0000186 if (type->tp_itemsize == 0)
187 PyObject_INIT(obj, type);
188 else
189 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000190
Tim Peters6d6c1a32001-08-02 04:15:00 +0000191 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000192 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000193 return obj;
194}
195
196PyObject *
197PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
198{
199 return type->tp_alloc(type, 0);
200}
201
Guido van Rossum9475a232001-10-05 20:51:39 +0000202/* Helpers for subtyping */
203
204static int
205subtype_traverse(PyObject *self, visitproc visit, void *arg)
206{
207 PyTypeObject *type, *base;
208 traverseproc f;
209 int err;
210
211 /* Find the nearest base with a different tp_traverse */
212 type = self->ob_type;
213 base = type->tp_base;
214 while ((f = base->tp_traverse) == subtype_traverse) {
215 base = base->tp_base;
216 assert(base);
217 }
218
219 if (type->tp_dictoffset != base->tp_dictoffset) {
220 PyObject **dictptr = _PyObject_GetDictPtr(self);
221 if (dictptr && *dictptr) {
222 err = visit(*dictptr, arg);
223 if (err)
224 return err;
225 }
226 }
227
228 if (f)
229 return f(self, visit, arg);
230 return 0;
231}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000232
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000233staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
234
235static int
236call_finalizer(PyObject *self)
237{
238 static PyObject *del_str = NULL;
239 PyObject *del, *res;
240 PyObject *error_type, *error_value, *error_traceback;
241
242 /* Temporarily resurrect the object. */
243#ifdef Py_TRACE_REFS
244#ifndef Py_REF_DEBUG
245# error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
246#endif
247 /* much too complicated if Py_TRACE_REFS defined */
248 _Py_NewReference((PyObject *)self);
249#ifdef COUNT_ALLOCS
250 /* compensate for boost in _Py_NewReference; note that
251 * _Py_RefTotal was also boosted; we'll knock that down later.
252 */
253 self->ob_type->tp_allocs--;
254#endif
255#else /* !Py_TRACE_REFS */
256 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
257 Py_INCREF(self);
258#endif /* !Py_TRACE_REFS */
259
260 /* Save the current exception, if any. */
261 PyErr_Fetch(&error_type, &error_value, &error_traceback);
262
263 /* Execute __del__ method, if any. */
264 del = lookup_maybe(self, "__del__", &del_str);
265 if (del != NULL) {
266 res = PyEval_CallObject(del, NULL);
267 if (res == NULL)
268 PyErr_WriteUnraisable(del);
269 else
270 Py_DECREF(res);
271 Py_DECREF(del);
272 }
273
274 /* Restore the saved exception. */
275 PyErr_Restore(error_type, error_value, error_traceback);
276
277 /* Undo the temporary resurrection; can't use DECREF here, it would
278 * cause a recursive call.
279 */
280#ifdef Py_REF_DEBUG
281 /* _Py_RefTotal was boosted either by _Py_NewReference or
282 * Py_INCREF above.
283 */
284 _Py_RefTotal--;
285#endif
286 if (--self->ob_refcnt > 0) {
287#ifdef COUNT_ALLOCS
288 self->ob_type->tp_frees--;
289#endif
290 _PyObject_GC_TRACK(self);
291 return -1; /* __del__ added a reference; don't delete now */
292 }
293#ifdef Py_TRACE_REFS
294 _Py_ForgetReference((PyObject *)self);
295#ifdef COUNT_ALLOCS
296 /* compensate for increment in _Py_ForgetReference */
297 self->ob_type->tp_frees--;
298#endif
299#endif
300
301 return 0;
302}
303
Tim Peters6d6c1a32001-08-02 04:15:00 +0000304static void
305subtype_dealloc(PyObject *self)
306{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000307 PyTypeObject *type, *base;
308 destructor f;
309
310 /* This exists so we can DECREF self->ob_type */
311
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000312 if (call_finalizer(self) < 0)
313 return;
314
Tim Peters6d6c1a32001-08-02 04:15:00 +0000315 /* Find the nearest base with a different tp_dealloc */
316 type = self->ob_type;
317 base = type->tp_base;
318 while ((f = base->tp_dealloc) == subtype_dealloc) {
319 base = base->tp_base;
320 assert(base);
321 }
322
323 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000324 if (type->tp_dictoffset && !base->tp_dictoffset) {
325 PyObject **dictptr = _PyObject_GetDictPtr(self);
326 if (dictptr != NULL) {
327 PyObject *dict = *dictptr;
328 if (dict != NULL) {
329 Py_DECREF(dict);
330 *dictptr = NULL;
331 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000332 }
333 }
334
Guido van Rossum9676b222001-08-17 20:32:36 +0000335 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000336 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000337 PyObject_ClearWeakRefs(self);
338
Tim Peters6d6c1a32001-08-02 04:15:00 +0000339 /* Finalize GC if the base doesn't do GC and we do */
340 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000341 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000342
343 /* Call the base tp_dealloc() */
344 assert(f);
345 f(self);
346
347 /* Can't reference self beyond this point */
348 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
349 Py_DECREF(type);
350 }
351}
352
Tim Peters6d6c1a32001-08-02 04:15:00 +0000353staticforward PyTypeObject *solid_base(PyTypeObject *type);
354
355typedef struct {
356 PyTypeObject type;
357 PyNumberMethods as_number;
358 PySequenceMethods as_sequence;
359 PyMappingMethods as_mapping;
360 PyBufferProcs as_buffer;
361 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000362 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000363} etype;
364
365/* type test with subclassing support */
366
367int
368PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
369{
370 PyObject *mro;
371
Guido van Rossum9478d072001-09-07 18:52:13 +0000372 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
373 return b == a || b == &PyBaseObject_Type;
374
Tim Peters6d6c1a32001-08-02 04:15:00 +0000375 mro = a->tp_mro;
376 if (mro != NULL) {
377 /* Deal with multiple inheritance without recursion
378 by walking the MRO tuple */
379 int i, n;
380 assert(PyTuple_Check(mro));
381 n = PyTuple_GET_SIZE(mro);
382 for (i = 0; i < n; i++) {
383 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
384 return 1;
385 }
386 return 0;
387 }
388 else {
389 /* a is not completely initilized yet; follow tp_base */
390 do {
391 if (a == b)
392 return 1;
393 a = a->tp_base;
394 } while (a != NULL);
395 return b == &PyBaseObject_Type;
396 }
397}
398
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000399/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000400 without looking in the instance dictionary
401 (so we can't use PyObject_GetAttr) but still binding
402 it to the instance. The arguments are the object,
403 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000404 static variable used to cache the interned Python string.
405
406 Two variants:
407
408 - lookup_maybe() returns NULL without raising an exception
409 when the _PyType_Lookup() call fails;
410
411 - lookup_method() always raises an exception upon errors.
412*/
Guido van Rossum60718732001-08-28 17:47:51 +0000413
414static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000415lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000416{
417 PyObject *res;
418
419 if (*attrobj == NULL) {
420 *attrobj = PyString_InternFromString(attrstr);
421 if (*attrobj == NULL)
422 return NULL;
423 }
424 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000425 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000426 descrgetfunc f;
427 if ((f = res->ob_type->tp_descr_get) == NULL)
428 Py_INCREF(res);
429 else
430 res = f(res, self, (PyObject *)(self->ob_type));
431 }
432 return res;
433}
434
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000435static PyObject *
436lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
437{
438 PyObject *res = lookup_maybe(self, attrstr, attrobj);
439 if (res == NULL && !PyErr_Occurred())
440 PyErr_SetObject(PyExc_AttributeError, *attrobj);
441 return res;
442}
443
Guido van Rossum2730b132001-08-28 18:22:14 +0000444/* A variation of PyObject_CallMethod that uses lookup_method()
445 instead of PyObject_GetAttrString(). This uses the same convention
446 as lookup_method to cache the interned name string object. */
447
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000448static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000449call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
450{
451 va_list va;
452 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000453 va_start(va, format);
454
Guido van Rossumda21c012001-10-03 00:50:18 +0000455 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000456 if (func == NULL) {
457 va_end(va);
458 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000459 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000460 return NULL;
461 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000462
463 if (format && *format)
464 args = Py_VaBuildValue(format, va);
465 else
466 args = PyTuple_New(0);
467
468 va_end(va);
469
470 if (args == NULL)
471 return NULL;
472
473 assert(PyTuple_Check(args));
474 retval = PyObject_Call(func, args, NULL);
475
476 Py_DECREF(args);
477 Py_DECREF(func);
478
479 return retval;
480}
481
482/* Clone of call_method() that returns NotImplemented when the lookup fails. */
483
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000484static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000485call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
486{
487 va_list va;
488 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000489 va_start(va, format);
490
Guido van Rossumda21c012001-10-03 00:50:18 +0000491 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000492 if (func == NULL) {
493 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000494 if (!PyErr_Occurred()) {
495 Py_INCREF(Py_NotImplemented);
496 return Py_NotImplemented;
497 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000498 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000499 }
500
501 if (format && *format)
502 args = Py_VaBuildValue(format, va);
503 else
504 args = PyTuple_New(0);
505
506 va_end(va);
507
Guido van Rossum717ce002001-09-14 16:58:08 +0000508 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000509 return NULL;
510
Guido van Rossum717ce002001-09-14 16:58:08 +0000511 assert(PyTuple_Check(args));
512 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000513
514 Py_DECREF(args);
515 Py_DECREF(func);
516
517 return retval;
518}
519
Tim Peters6d6c1a32001-08-02 04:15:00 +0000520/* Method resolution order algorithm from "Putting Metaclasses to Work"
521 by Forman and Danforth (Addison-Wesley 1999). */
522
523static int
524conservative_merge(PyObject *left, PyObject *right)
525{
526 int left_size;
527 int right_size;
528 int i, j, r, ok;
529 PyObject *temp, *rr;
530
531 assert(PyList_Check(left));
532 assert(PyList_Check(right));
533
534 again:
535 left_size = PyList_GET_SIZE(left);
536 right_size = PyList_GET_SIZE(right);
537 for (i = 0; i < left_size; i++) {
538 for (j = 0; j < right_size; j++) {
539 if (PyList_GET_ITEM(left, i) ==
540 PyList_GET_ITEM(right, j)) {
541 /* found a merge point */
542 temp = PyList_New(0);
543 if (temp == NULL)
544 return -1;
545 for (r = 0; r < j; r++) {
546 rr = PyList_GET_ITEM(right, r);
547 ok = PySequence_Contains(left, rr);
548 if (ok < 0) {
549 Py_DECREF(temp);
550 return -1;
551 }
552 if (!ok) {
553 ok = PyList_Append(temp, rr);
554 if (ok < 0) {
555 Py_DECREF(temp);
556 return -1;
557 }
558 }
559 }
560 ok = PyList_SetSlice(left, i, i, temp);
561 Py_DECREF(temp);
562 if (ok < 0)
563 return -1;
564 ok = PyList_SetSlice(right, 0, j+1, NULL);
565 if (ok < 0)
566 return -1;
567 goto again;
568 }
569 }
570 }
571 return PyList_SetSlice(left, left_size, left_size, right);
572}
573
574static int
575serious_order_disagreements(PyObject *left, PyObject *right)
576{
577 return 0; /* XXX later -- for now, we cheat: "don't do that" */
578}
579
580static PyObject *
581mro_implementation(PyTypeObject *type)
582{
583 int i, n, ok;
584 PyObject *bases, *result;
585
586 bases = type->tp_bases;
587 n = PyTuple_GET_SIZE(bases);
588 result = Py_BuildValue("[O]", (PyObject *)type);
589 if (result == NULL)
590 return NULL;
591 for (i = 0; i < n; i++) {
592 PyTypeObject *base =
593 (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
594 PyObject *parentMRO = PySequence_List(base->tp_mro);
595 if (parentMRO == NULL) {
596 Py_DECREF(result);
597 return NULL;
598 }
599 if (serious_order_disagreements(result, parentMRO)) {
600 Py_DECREF(result);
601 return NULL;
602 }
603 ok = conservative_merge(result, parentMRO);
604 Py_DECREF(parentMRO);
605 if (ok < 0) {
606 Py_DECREF(result);
607 return NULL;
608 }
609 }
610 return result;
611}
612
613static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000614mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000615{
616 PyTypeObject *type = (PyTypeObject *)self;
617
Tim Peters6d6c1a32001-08-02 04:15:00 +0000618 return mro_implementation(type);
619}
620
621static int
622mro_internal(PyTypeObject *type)
623{
624 PyObject *mro, *result, *tuple;
625
626 if (type->ob_type == &PyType_Type) {
627 result = mro_implementation(type);
628 }
629 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000630 static PyObject *mro_str;
631 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000632 if (mro == NULL)
633 return -1;
634 result = PyObject_CallObject(mro, NULL);
635 Py_DECREF(mro);
636 }
637 if (result == NULL)
638 return -1;
639 tuple = PySequence_Tuple(result);
640 Py_DECREF(result);
641 type->tp_mro = tuple;
642 return 0;
643}
644
645
646/* Calculate the best base amongst multiple base classes.
647 This is the first one that's on the path to the "solid base". */
648
649static PyTypeObject *
650best_base(PyObject *bases)
651{
652 int i, n;
653 PyTypeObject *base, *winner, *candidate, *base_i;
654
655 assert(PyTuple_Check(bases));
656 n = PyTuple_GET_SIZE(bases);
657 assert(n > 0);
658 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
659 winner = &PyBaseObject_Type;
660 for (i = 0; i < n; i++) {
661 base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
662 if (!PyType_Check((PyObject *)base_i)) {
663 PyErr_SetString(
664 PyExc_TypeError,
665 "bases must be types");
666 return NULL;
667 }
668 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000669 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000670 return NULL;
671 }
672 candidate = solid_base(base_i);
673 if (PyType_IsSubtype(winner, candidate))
674 ;
675 else if (PyType_IsSubtype(candidate, winner)) {
676 winner = candidate;
677 base = base_i;
678 }
679 else {
680 PyErr_SetString(
681 PyExc_TypeError,
682 "multiple bases have "
683 "instance lay-out conflict");
684 return NULL;
685 }
686 }
687 assert(base != NULL);
688 return base;
689}
690
691static int
692extra_ivars(PyTypeObject *type, PyTypeObject *base)
693{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000694 size_t t_size = type->tp_basicsize;
695 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000696
Guido van Rossum9676b222001-08-17 20:32:36 +0000697 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000698 if (type->tp_itemsize || base->tp_itemsize) {
699 /* If itemsize is involved, stricter rules */
700 return t_size != b_size ||
701 type->tp_itemsize != base->tp_itemsize;
702 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000703 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
704 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
705 t_size -= sizeof(PyObject *);
706 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
707 type->tp_dictoffset + sizeof(PyObject *) == t_size)
708 t_size -= sizeof(PyObject *);
709
710 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000711}
712
713static PyTypeObject *
714solid_base(PyTypeObject *type)
715{
716 PyTypeObject *base;
717
718 if (type->tp_base)
719 base = solid_base(type->tp_base);
720 else
721 base = &PyBaseObject_Type;
722 if (extra_ivars(type, base))
723 return type;
724 else
725 return base;
726}
727
728staticforward void object_dealloc(PyObject *);
729staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000730staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000731staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000732
733static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000734subtype_dict(PyObject *obj, void *context)
735{
736 PyObject **dictptr = _PyObject_GetDictPtr(obj);
737 PyObject *dict;
738
739 if (dictptr == NULL) {
740 PyErr_SetString(PyExc_AttributeError,
741 "This object has no __dict__");
742 return NULL;
743 }
744 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000745 if (dict == NULL)
746 *dictptr = dict = PyDict_New();
747 Py_XINCREF(dict);
748 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000749}
750
Guido van Rossum6661be32001-10-26 04:26:12 +0000751static int
752subtype_setdict(PyObject *obj, PyObject *value, void *context)
753{
754 PyObject **dictptr = _PyObject_GetDictPtr(obj);
755 PyObject *dict;
756
757 if (dictptr == NULL) {
758 PyErr_SetString(PyExc_AttributeError,
759 "This object has no __dict__");
760 return -1;
761 }
762 if (value == NULL || !PyDict_Check(value)) {
763 PyErr_SetString(PyExc_TypeError,
764 "__dict__ must be set to a dictionary");
765 return -1;
766 }
767 dict = *dictptr;
768 Py_INCREF(value);
769 *dictptr = value;
770 Py_XDECREF(dict);
771 return 0;
772}
773
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000774static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000775 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000776 {0},
777};
778
779static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000780type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
781{
782 PyObject *name, *bases, *dict;
783 static char *kwlist[] = {"name", "bases", "dict", 0};
784 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000785 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000786 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000787 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000788 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000789
Tim Peters3abca122001-10-27 19:37:48 +0000790 assert(args != NULL && PyTuple_Check(args));
791 assert(kwds == NULL || PyDict_Check(kwds));
792
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000793 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +0000794 {
795 const int nargs = PyTuple_GET_SIZE(args);
796 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
797
798 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
799 PyObject *x = PyTuple_GET_ITEM(args, 0);
800 Py_INCREF(x->ob_type);
801 return (PyObject *) x->ob_type;
802 }
803
804 /* SF bug 475327 -- if that didn't trigger, we need 3
805 arguments. but PyArg_ParseTupleAndKeywords below may give
806 a msg saying type() needs exactly 3. */
807 if (nargs + nkwds != 3) {
808 PyErr_SetString(PyExc_TypeError,
809 "type() takes 1 or 3 arguments");
810 return NULL;
811 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000812 }
813
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000814 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000815 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
816 &name,
817 &PyTuple_Type, &bases,
818 &PyDict_Type, &dict))
819 return NULL;
820
821 /* Determine the proper metatype to deal with this,
822 and check for metatype conflicts while we're at it.
823 Note that if some other metatype wins to contract,
824 it's possible that its instances are not types. */
825 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000826 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000827 for (i = 0; i < nbases; i++) {
828 tmp = PyTuple_GET_ITEM(bases, i);
829 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000830 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000832 if (PyType_IsSubtype(tmptype, winner)) {
833 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834 continue;
835 }
836 PyErr_SetString(PyExc_TypeError,
837 "metatype conflict among bases");
838 return NULL;
839 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000840 if (winner != metatype) {
841 if (winner->tp_new != type_new) /* Pass it to the winner */
842 return winner->tp_new(winner, args, kwds);
843 metatype = winner;
844 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000845
846 /* Adjust for empty tuple bases */
847 if (nbases == 0) {
848 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
849 if (bases == NULL)
850 return NULL;
851 nbases = 1;
852 }
853 else
854 Py_INCREF(bases);
855
856 /* XXX From here until type is allocated, "return NULL" leaks bases! */
857
858 /* Calculate best base, and check that all bases are type objects */
859 base = best_base(bases);
860 if (base == NULL)
861 return NULL;
862 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
863 PyErr_Format(PyExc_TypeError,
864 "type '%.100s' is not an acceptable base type",
865 base->tp_name);
866 return NULL;
867 }
868
Tim Peters6d6c1a32001-08-02 04:15:00 +0000869 /* Check for a __slots__ sequence variable in dict, and count it */
870 slots = PyDict_GetItemString(dict, "__slots__");
871 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000872 add_dict = 0;
873 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000874 if (slots != NULL) {
875 /* Make it into a tuple */
876 if (PyString_Check(slots))
877 slots = Py_BuildValue("(O)", slots);
878 else
879 slots = PySequence_Tuple(slots);
880 if (slots == NULL)
881 return NULL;
882 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000883 if (nslots > 0 && base->tp_itemsize != 0) {
884 PyErr_Format(PyExc_TypeError,
885 "nonempty __slots__ "
886 "not supported for subtype of '%s'",
887 base->tp_name);
888 return NULL;
889 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000890 for (i = 0; i < nslots; i++) {
891 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
892 PyErr_SetString(PyExc_TypeError,
893 "__slots__ must be a sequence of strings");
894 Py_DECREF(slots);
895 return NULL;
896 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000897 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000898 }
899 }
900 if (slots == NULL && base->tp_dictoffset == 0 &&
901 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000902 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000903 add_dict++;
904 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000905 if (slots == NULL && base->tp_weaklistoffset == 0 &&
906 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000907 nslots++;
908 add_weak++;
909 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000910
911 /* XXX From here until type is safely allocated,
912 "return NULL" may leak slots! */
913
914 /* Allocate the type object */
915 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
916 if (type == NULL)
917 return NULL;
918
919 /* Keep name and slots alive in the extended type object */
920 et = (etype *)type;
921 Py_INCREF(name);
922 et->name = name;
923 et->slots = slots;
924
Guido van Rossumdc91b992001-08-08 22:26:22 +0000925 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000926 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
927 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000928 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
929 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000930
931 /* It's a new-style number unless it specifically inherits any
932 old-style numeric behavior */
933 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
934 (base->tp_as_number == NULL))
935 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
936
937 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000938 type->tp_as_number = &et->as_number;
939 type->tp_as_sequence = &et->as_sequence;
940 type->tp_as_mapping = &et->as_mapping;
941 type->tp_as_buffer = &et->as_buffer;
942 type->tp_name = PyString_AS_STRING(name);
943
944 /* Set tp_base and tp_bases */
945 type->tp_bases = bases;
946 Py_INCREF(base);
947 type->tp_base = base;
948
Guido van Rossum687ae002001-10-15 22:03:32 +0000949 /* Initialize tp_dict from passed-in dict */
950 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000951 if (dict == NULL) {
952 Py_DECREF(type);
953 return NULL;
954 }
955
Guido van Rossumc3542212001-08-16 09:18:56 +0000956 /* Set __module__ in the dict */
957 if (PyDict_GetItemString(dict, "__module__") == NULL) {
958 tmp = PyEval_GetGlobals();
959 if (tmp != NULL) {
960 tmp = PyDict_GetItemString(tmp, "__name__");
961 if (tmp != NULL) {
962 if (PyDict_SetItemString(dict, "__module__",
963 tmp) < 0)
964 return NULL;
965 }
966 }
967 }
968
Tim Peters2f93e282001-10-04 05:27:00 +0000969 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
970 and is a string (tp_doc is a char* -- can't copy a general object
971 into it).
972 XXX What if it's a Unicode string? Don't know -- this ignores it.
973 */
974 {
975 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
976 if (doc != NULL && PyString_Check(doc)) {
977 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +0000978 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +0000979 if (type->tp_doc == NULL) {
980 Py_DECREF(type);
981 return NULL;
982 }
983 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
984 }
985 }
986
Tim Peters6d6c1a32001-08-02 04:15:00 +0000987 /* Special-case __new__: if it's a plain function,
988 make it a static function */
989 tmp = PyDict_GetItemString(dict, "__new__");
990 if (tmp != NULL && PyFunction_Check(tmp)) {
991 tmp = PyStaticMethod_New(tmp);
992 if (tmp == NULL) {
993 Py_DECREF(type);
994 return NULL;
995 }
996 PyDict_SetItemString(dict, "__new__", tmp);
997 Py_DECREF(tmp);
998 }
999
1000 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1001 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001002 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003 if (slots != NULL) {
1004 for (i = 0; i < nslots; i++, mp++) {
1005 mp->name = PyString_AS_STRING(
1006 PyTuple_GET_ITEM(slots, i));
1007 mp->type = T_OBJECT;
1008 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001009 if (base->tp_weaklistoffset == 0 &&
1010 strcmp(mp->name, "__weakref__") == 0)
1011 type->tp_weaklistoffset = slotoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001012 slotoffset += sizeof(PyObject *);
1013 }
1014 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001015 else {
1016 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001017 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001018 type->tp_dictoffset =
1019 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001020 else
1021 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001022 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001023 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001024 }
1025 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001026 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001027 type->tp_weaklistoffset = slotoffset;
1028 mp->name = "__weakref__";
1029 mp->type = T_OBJECT;
1030 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001031 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001032 mp++;
1033 slotoffset += sizeof(PyObject *);
1034 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001035 }
1036 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001037 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001038 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039
1040 /* Special case some slots */
1041 if (type->tp_dictoffset != 0 || nslots > 0) {
1042 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1043 type->tp_getattro = PyObject_GenericGetAttr;
1044 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1045 type->tp_setattro = PyObject_GenericSetAttr;
1046 }
1047 type->tp_dealloc = subtype_dealloc;
1048
Guido van Rossum9475a232001-10-05 20:51:39 +00001049 /* Enable GC unless there are really no instance variables possible */
1050 if (!(type->tp_basicsize == sizeof(PyObject) &&
1051 type->tp_itemsize == 0))
1052 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1053
Tim Peters6d6c1a32001-08-02 04:15:00 +00001054 /* Always override allocation strategy to use regular heap */
1055 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001056 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1057 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001058 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001059 type->tp_clear = base->tp_clear;
1060 }
1061 else
1062 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001063
1064 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001065 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066 Py_DECREF(type);
1067 return NULL;
1068 }
1069
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001070 /* Put the proper slots in place */
1071 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001072
Tim Peters6d6c1a32001-08-02 04:15:00 +00001073 return (PyObject *)type;
1074}
1075
1076/* Internal API to look for a name through the MRO.
1077 This returns a borrowed reference, and doesn't set an exception! */
1078PyObject *
1079_PyType_Lookup(PyTypeObject *type, PyObject *name)
1080{
1081 int i, n;
1082 PyObject *mro, *res, *dict;
1083
Guido van Rossum687ae002001-10-15 22:03:32 +00001084 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001085 mro = type->tp_mro;
1086 assert(PyTuple_Check(mro));
1087 n = PyTuple_GET_SIZE(mro);
1088 for (i = 0; i < n; i++) {
1089 type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
1090 assert(PyType_Check(type));
Guido van Rossum687ae002001-10-15 22:03:32 +00001091 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001092 assert(dict && PyDict_Check(dict));
1093 res = PyDict_GetItem(dict, name);
1094 if (res != NULL)
1095 return res;
1096 }
1097 return NULL;
1098}
1099
1100/* This is similar to PyObject_GenericGetAttr(),
1101 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1102static PyObject *
1103type_getattro(PyTypeObject *type, PyObject *name)
1104{
1105 PyTypeObject *metatype = type->ob_type;
1106 PyObject *descr, *res;
1107 descrgetfunc f;
1108
1109 /* Initialize this type (we'll assume the metatype is initialized) */
1110 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001111 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112 return NULL;
1113 }
1114
1115 /* Get a descriptor from the metatype */
1116 descr = _PyType_Lookup(metatype, name);
1117 f = NULL;
1118 if (descr != NULL) {
1119 f = descr->ob_type->tp_descr_get;
1120 if (f != NULL && PyDescr_IsData(descr))
1121 return f(descr,
1122 (PyObject *)type, (PyObject *)metatype);
1123 }
1124
Guido van Rossum687ae002001-10-15 22:03:32 +00001125 /* Look in tp_dict of this type and its bases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001126 res = _PyType_Lookup(type, name);
1127 if (res != NULL) {
1128 f = res->ob_type->tp_descr_get;
1129 if (f != NULL)
1130 return f(res, (PyObject *)NULL, (PyObject *)type);
1131 Py_INCREF(res);
1132 return res;
1133 }
1134
1135 /* Use the descriptor from the metatype */
1136 if (f != NULL) {
1137 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1138 return res;
1139 }
1140 if (descr != NULL) {
1141 Py_INCREF(descr);
1142 return descr;
1143 }
1144
1145 /* Give up */
1146 PyErr_Format(PyExc_AttributeError,
1147 "type object '%.50s' has no attribute '%.400s'",
1148 type->tp_name, PyString_AS_STRING(name));
1149 return NULL;
1150}
1151
1152static int
1153type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1154{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001155 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1156 PyErr_Format(
1157 PyExc_TypeError,
1158 "can't set attributes of built-in/extension type '%s'",
1159 type->tp_name);
1160 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001161 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001162 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1163 return -1;
1164 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165}
1166
1167static void
1168type_dealloc(PyTypeObject *type)
1169{
1170 etype *et;
1171
1172 /* Assert this is a heap-allocated type object */
1173 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001174 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001175 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176 et = (etype *)type;
1177 Py_XDECREF(type->tp_base);
1178 Py_XDECREF(type->tp_dict);
1179 Py_XDECREF(type->tp_bases);
1180 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001181 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001182 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183 Py_XDECREF(et->name);
1184 Py_XDECREF(et->slots);
1185 type->ob_type->tp_free((PyObject *)type);
1186}
1187
Guido van Rossum1c450732001-10-08 15:18:27 +00001188static PyObject *
1189type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1190{
1191 PyObject *list, *raw, *ref;
1192 int i, n;
1193
1194 list = PyList_New(0);
1195 if (list == NULL)
1196 return NULL;
1197 raw = type->tp_subclasses;
1198 if (raw == NULL)
1199 return list;
1200 assert(PyList_Check(raw));
1201 n = PyList_GET_SIZE(raw);
1202 for (i = 0; i < n; i++) {
1203 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001204 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001205 ref = PyWeakref_GET_OBJECT(ref);
1206 if (ref != Py_None) {
1207 if (PyList_Append(list, ref) < 0) {
1208 Py_DECREF(list);
1209 return NULL;
1210 }
1211 }
1212 }
1213 return list;
1214}
1215
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001217 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001218 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001219 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1220 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221 {0}
1222};
1223
1224static char type_doc[] =
1225"type(object) -> the object's type\n"
1226"type(name, bases, dict) -> a new type";
1227
Guido van Rossum048eb752001-10-02 21:24:57 +00001228static int
1229type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1230{
1231 etype *et;
1232 int err;
1233
1234 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1235 return 0;
1236
1237 et = (etype *)type;
1238
1239#define VISIT(SLOT) \
1240 if (SLOT) { \
1241 err = visit((PyObject *)(SLOT), arg); \
1242 if (err) \
1243 return err; \
1244 }
1245
1246 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001247 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001248 VISIT(type->tp_mro);
1249 VISIT(type->tp_bases);
1250 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001251 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001252 VISIT(et->slots);
1253
1254#undef VISIT
1255
1256 return 0;
1257}
1258
1259static int
1260type_clear(PyTypeObject *type)
1261{
1262 etype *et;
1263 PyObject *tmp;
1264
1265 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1266 return 0;
1267
1268 et = (etype *)type;
1269
1270#define CLEAR(SLOT) \
1271 if (SLOT) { \
1272 tmp = (PyObject *)(SLOT); \
1273 SLOT = NULL; \
1274 Py_DECREF(tmp); \
1275 }
1276
1277 CLEAR(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001278 CLEAR(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001279 CLEAR(type->tp_mro);
1280 CLEAR(type->tp_bases);
1281 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001282 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001283 CLEAR(et->slots);
1284
Tim Peters2f93e282001-10-04 05:27:00 +00001285 if (type->tp_doc != NULL) {
1286 PyObject_FREE(type->tp_doc);
1287 type->tp_doc = NULL;
1288 }
1289
Guido van Rossum048eb752001-10-02 21:24:57 +00001290#undef CLEAR
1291
1292 return 0;
1293}
1294
1295static int
1296type_is_gc(PyTypeObject *type)
1297{
1298 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1299}
1300
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001301PyTypeObject PyType_Type = {
1302 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 0, /* ob_size */
1304 "type", /* tp_name */
1305 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001306 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001307 (destructor)type_dealloc, /* tp_dealloc */
1308 0, /* tp_print */
1309 0, /* tp_getattr */
1310 0, /* tp_setattr */
1311 type_compare, /* tp_compare */
1312 (reprfunc)type_repr, /* tp_repr */
1313 0, /* tp_as_number */
1314 0, /* tp_as_sequence */
1315 0, /* tp_as_mapping */
1316 (hashfunc)_Py_HashPointer, /* tp_hash */
1317 (ternaryfunc)type_call, /* tp_call */
1318 0, /* tp_str */
1319 (getattrofunc)type_getattro, /* tp_getattro */
1320 (setattrofunc)type_setattro, /* tp_setattro */
1321 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001322 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1323 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001324 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001325 (traverseproc)type_traverse, /* tp_traverse */
1326 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001328 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001329 0, /* tp_iter */
1330 0, /* tp_iternext */
1331 type_methods, /* tp_methods */
1332 type_members, /* tp_members */
1333 type_getsets, /* tp_getset */
1334 0, /* tp_base */
1335 0, /* tp_dict */
1336 0, /* tp_descr_get */
1337 0, /* tp_descr_set */
1338 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1339 0, /* tp_init */
1340 0, /* tp_alloc */
1341 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001342 _PyObject_GC_Del, /* tp_free */
1343 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001344};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001345
1346
1347/* The base type of all types (eventually)... except itself. */
1348
1349static int
1350object_init(PyObject *self, PyObject *args, PyObject *kwds)
1351{
1352 return 0;
1353}
1354
1355static void
1356object_dealloc(PyObject *self)
1357{
1358 self->ob_type->tp_free(self);
1359}
1360
Guido van Rossum8e248182001-08-12 05:17:56 +00001361static PyObject *
1362object_repr(PyObject *self)
1363{
Guido van Rossum76e69632001-08-16 18:52:43 +00001364 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001365 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001366
Guido van Rossum76e69632001-08-16 18:52:43 +00001367 type = self->ob_type;
1368 mod = type_module(type, NULL);
1369 if (mod == NULL)
1370 PyErr_Clear();
1371 else if (!PyString_Check(mod)) {
1372 Py_DECREF(mod);
1373 mod = NULL;
1374 }
1375 name = type_name(type, NULL);
1376 if (name == NULL)
1377 return NULL;
1378 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001379 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001380 PyString_AS_STRING(mod),
1381 PyString_AS_STRING(name),
1382 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001383 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001384 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001385 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001386 Py_XDECREF(mod);
1387 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001388 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001389}
1390
Guido van Rossumb8f63662001-08-15 23:57:02 +00001391static PyObject *
1392object_str(PyObject *self)
1393{
1394 unaryfunc f;
1395
1396 f = self->ob_type->tp_repr;
1397 if (f == NULL)
1398 f = object_repr;
1399 return f(self);
1400}
1401
Guido van Rossum8e248182001-08-12 05:17:56 +00001402static long
1403object_hash(PyObject *self)
1404{
1405 return _Py_HashPointer(self);
1406}
Guido van Rossum8e248182001-08-12 05:17:56 +00001407
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001408static PyObject *
1409object_get_class(PyObject *self, void *closure)
1410{
1411 Py_INCREF(self->ob_type);
1412 return (PyObject *)(self->ob_type);
1413}
1414
1415static int
1416equiv_structs(PyTypeObject *a, PyTypeObject *b)
1417{
1418 return a == b ||
1419 (a != NULL &&
1420 b != NULL &&
1421 a->tp_basicsize == b->tp_basicsize &&
1422 a->tp_itemsize == b->tp_itemsize &&
1423 a->tp_dictoffset == b->tp_dictoffset &&
1424 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1425 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1426 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1427}
1428
1429static int
1430same_slots_added(PyTypeObject *a, PyTypeObject *b)
1431{
1432 PyTypeObject *base = a->tp_base;
1433 int size;
1434
1435 if (base != b->tp_base)
1436 return 0;
1437 if (equiv_structs(a, base) && equiv_structs(b, base))
1438 return 1;
1439 size = base->tp_basicsize;
1440 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1441 size += sizeof(PyObject *);
1442 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1443 size += sizeof(PyObject *);
1444 return size == a->tp_basicsize && size == b->tp_basicsize;
1445}
1446
1447static int
1448object_set_class(PyObject *self, PyObject *value, void *closure)
1449{
1450 PyTypeObject *old = self->ob_type;
1451 PyTypeObject *new, *newbase, *oldbase;
1452
1453 if (!PyType_Check(value)) {
1454 PyErr_Format(PyExc_TypeError,
1455 "__class__ must be set to new-style class, not '%s' object",
1456 value->ob_type->tp_name);
1457 return -1;
1458 }
1459 new = (PyTypeObject *)value;
1460 newbase = new;
1461 oldbase = old;
1462 while (equiv_structs(newbase, newbase->tp_base))
1463 newbase = newbase->tp_base;
1464 while (equiv_structs(oldbase, oldbase->tp_base))
1465 oldbase = oldbase->tp_base;
1466 if (newbase != oldbase &&
1467 (newbase->tp_base != oldbase->tp_base ||
1468 !same_slots_added(newbase, oldbase))) {
1469 PyErr_Format(PyExc_TypeError,
1470 "__class__ assignment: "
1471 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001472 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001473 old->tp_name);
1474 return -1;
1475 }
1476 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1477 Py_INCREF(new);
1478 }
1479 self->ob_type = new;
1480 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1481 Py_DECREF(old);
1482 }
1483 return 0;
1484}
1485
1486static PyGetSetDef object_getsets[] = {
1487 {"__class__", object_get_class, object_set_class,
1488 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001489 {0}
1490};
1491
Guido van Rossum3926a632001-09-25 16:25:58 +00001492static PyObject *
1493object_reduce(PyObject *self, PyObject *args)
1494{
1495 /* Call copy_reg._reduce(self) */
1496 static PyObject *copy_reg_str;
1497 PyObject *copy_reg, *res;
1498
1499 if (!copy_reg_str) {
1500 copy_reg_str = PyString_InternFromString("copy_reg");
1501 if (copy_reg_str == NULL)
1502 return NULL;
1503 }
1504 copy_reg = PyImport_Import(copy_reg_str);
1505 if (!copy_reg)
1506 return NULL;
1507 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1508 Py_DECREF(copy_reg);
1509 return res;
1510}
1511
1512static PyMethodDef object_methods[] = {
1513 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1514 {0}
1515};
1516
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517PyTypeObject PyBaseObject_Type = {
1518 PyObject_HEAD_INIT(&PyType_Type)
1519 0, /* ob_size */
1520 "object", /* tp_name */
1521 sizeof(PyObject), /* tp_basicsize */
1522 0, /* tp_itemsize */
1523 (destructor)object_dealloc, /* tp_dealloc */
1524 0, /* tp_print */
1525 0, /* tp_getattr */
1526 0, /* tp_setattr */
1527 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001528 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529 0, /* tp_as_number */
1530 0, /* tp_as_sequence */
1531 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001532 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001533 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001534 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001535 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001536 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001537 0, /* tp_as_buffer */
1538 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1539 "The most base type", /* tp_doc */
1540 0, /* tp_traverse */
1541 0, /* tp_clear */
1542 0, /* tp_richcompare */
1543 0, /* tp_weaklistoffset */
1544 0, /* tp_iter */
1545 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001546 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001547 0, /* tp_members */
1548 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001549 0, /* tp_base */
1550 0, /* tp_dict */
1551 0, /* tp_descr_get */
1552 0, /* tp_descr_set */
1553 0, /* tp_dictoffset */
1554 object_init, /* tp_init */
1555 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001556 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001557 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001558};
1559
1560
1561/* Initialize the __dict__ in a type object */
1562
1563static int
1564add_methods(PyTypeObject *type, PyMethodDef *meth)
1565{
Guido van Rossum687ae002001-10-15 22:03:32 +00001566 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567
1568 for (; meth->ml_name != NULL; meth++) {
1569 PyObject *descr;
1570 if (PyDict_GetItemString(dict, meth->ml_name))
1571 continue;
1572 descr = PyDescr_NewMethod(type, meth);
1573 if (descr == NULL)
1574 return -1;
1575 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1576 return -1;
1577 Py_DECREF(descr);
1578 }
1579 return 0;
1580}
1581
1582static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001583add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001584{
Guido van Rossum687ae002001-10-15 22:03:32 +00001585 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586
1587 for (; memb->name != NULL; memb++) {
1588 PyObject *descr;
1589 if (PyDict_GetItemString(dict, memb->name))
1590 continue;
1591 descr = PyDescr_NewMember(type, memb);
1592 if (descr == NULL)
1593 return -1;
1594 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1595 return -1;
1596 Py_DECREF(descr);
1597 }
1598 return 0;
1599}
1600
1601static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001602add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603{
Guido van Rossum687ae002001-10-15 22:03:32 +00001604 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001605
1606 for (; gsp->name != NULL; gsp++) {
1607 PyObject *descr;
1608 if (PyDict_GetItemString(dict, gsp->name))
1609 continue;
1610 descr = PyDescr_NewGetSet(type, gsp);
1611
1612 if (descr == NULL)
1613 return -1;
1614 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1615 return -1;
1616 Py_DECREF(descr);
1617 }
1618 return 0;
1619}
1620
Guido van Rossum13d52f02001-08-10 21:24:08 +00001621static void
1622inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001623{
1624 int oldsize, newsize;
1625
Guido van Rossum13d52f02001-08-10 21:24:08 +00001626 /* Special flag magic */
1627 if (!type->tp_as_buffer && base->tp_as_buffer) {
1628 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1629 type->tp_flags |=
1630 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1631 }
1632 if (!type->tp_as_sequence && base->tp_as_sequence) {
1633 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1634 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1635 }
1636 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1637 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1638 if ((!type->tp_as_number && base->tp_as_number) ||
1639 (!type->tp_as_sequence && base->tp_as_sequence)) {
1640 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1641 if (!type->tp_as_number && !type->tp_as_sequence) {
1642 type->tp_flags |= base->tp_flags &
1643 Py_TPFLAGS_HAVE_INPLACEOPS;
1644 }
1645 }
1646 /* Wow */
1647 }
1648 if (!type->tp_as_number && base->tp_as_number) {
1649 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1650 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1651 }
1652
1653 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001654 oldsize = base->tp_basicsize;
1655 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1656 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1657 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001658 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1659 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001660 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001661 if (type->tp_traverse == NULL)
1662 type->tp_traverse = base->tp_traverse;
1663 if (type->tp_clear == NULL)
1664 type->tp_clear = base->tp_clear;
1665 }
1666 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1667 if (base != &PyBaseObject_Type ||
1668 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1669 if (type->tp_new == NULL)
1670 type->tp_new = base->tp_new;
1671 }
1672 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001673 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001674
1675 /* Copy other non-function slots */
1676
1677#undef COPYVAL
1678#define COPYVAL(SLOT) \
1679 if (type->SLOT == 0) type->SLOT = base->SLOT
1680
1681 COPYVAL(tp_itemsize);
1682 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1683 COPYVAL(tp_weaklistoffset);
1684 }
1685 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1686 COPYVAL(tp_dictoffset);
1687 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001688}
1689
1690static void
1691inherit_slots(PyTypeObject *type, PyTypeObject *base)
1692{
1693 PyTypeObject *basebase;
1694
1695#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001696#undef COPYSLOT
1697#undef COPYNUM
1698#undef COPYSEQ
1699#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001700#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001701
1702#define SLOTDEFINED(SLOT) \
1703 (base->SLOT != 0 && \
1704 (basebase == NULL || base->SLOT != basebase->SLOT))
1705
Tim Peters6d6c1a32001-08-02 04:15:00 +00001706#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001707 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001708
1709#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1710#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1711#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001712#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713
Guido van Rossum13d52f02001-08-10 21:24:08 +00001714 /* This won't inherit indirect slots (from tp_as_number etc.)
1715 if type doesn't provide the space. */
1716
1717 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1718 basebase = base->tp_base;
1719 if (basebase->tp_as_number == NULL)
1720 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721 COPYNUM(nb_add);
1722 COPYNUM(nb_subtract);
1723 COPYNUM(nb_multiply);
1724 COPYNUM(nb_divide);
1725 COPYNUM(nb_remainder);
1726 COPYNUM(nb_divmod);
1727 COPYNUM(nb_power);
1728 COPYNUM(nb_negative);
1729 COPYNUM(nb_positive);
1730 COPYNUM(nb_absolute);
1731 COPYNUM(nb_nonzero);
1732 COPYNUM(nb_invert);
1733 COPYNUM(nb_lshift);
1734 COPYNUM(nb_rshift);
1735 COPYNUM(nb_and);
1736 COPYNUM(nb_xor);
1737 COPYNUM(nb_or);
1738 COPYNUM(nb_coerce);
1739 COPYNUM(nb_int);
1740 COPYNUM(nb_long);
1741 COPYNUM(nb_float);
1742 COPYNUM(nb_oct);
1743 COPYNUM(nb_hex);
1744 COPYNUM(nb_inplace_add);
1745 COPYNUM(nb_inplace_subtract);
1746 COPYNUM(nb_inplace_multiply);
1747 COPYNUM(nb_inplace_divide);
1748 COPYNUM(nb_inplace_remainder);
1749 COPYNUM(nb_inplace_power);
1750 COPYNUM(nb_inplace_lshift);
1751 COPYNUM(nb_inplace_rshift);
1752 COPYNUM(nb_inplace_and);
1753 COPYNUM(nb_inplace_xor);
1754 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001755 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1756 COPYNUM(nb_true_divide);
1757 COPYNUM(nb_floor_divide);
1758 COPYNUM(nb_inplace_true_divide);
1759 COPYNUM(nb_inplace_floor_divide);
1760 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001761 }
1762
Guido van Rossum13d52f02001-08-10 21:24:08 +00001763 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1764 basebase = base->tp_base;
1765 if (basebase->tp_as_sequence == NULL)
1766 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001767 COPYSEQ(sq_length);
1768 COPYSEQ(sq_concat);
1769 COPYSEQ(sq_repeat);
1770 COPYSEQ(sq_item);
1771 COPYSEQ(sq_slice);
1772 COPYSEQ(sq_ass_item);
1773 COPYSEQ(sq_ass_slice);
1774 COPYSEQ(sq_contains);
1775 COPYSEQ(sq_inplace_concat);
1776 COPYSEQ(sq_inplace_repeat);
1777 }
1778
Guido van Rossum13d52f02001-08-10 21:24:08 +00001779 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1780 basebase = base->tp_base;
1781 if (basebase->tp_as_mapping == NULL)
1782 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783 COPYMAP(mp_length);
1784 COPYMAP(mp_subscript);
1785 COPYMAP(mp_ass_subscript);
1786 }
1787
Tim Petersfc57ccb2001-10-12 02:38:24 +00001788 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1789 basebase = base->tp_base;
1790 if (basebase->tp_as_buffer == NULL)
1791 basebase = NULL;
1792 COPYBUF(bf_getreadbuffer);
1793 COPYBUF(bf_getwritebuffer);
1794 COPYBUF(bf_getsegcount);
1795 COPYBUF(bf_getcharbuffer);
1796 }
1797
Guido van Rossum13d52f02001-08-10 21:24:08 +00001798 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799
Tim Peters6d6c1a32001-08-02 04:15:00 +00001800 COPYSLOT(tp_dealloc);
1801 COPYSLOT(tp_print);
1802 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1803 type->tp_getattr = base->tp_getattr;
1804 type->tp_getattro = base->tp_getattro;
1805 }
1806 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1807 type->tp_setattr = base->tp_setattr;
1808 type->tp_setattro = base->tp_setattro;
1809 }
1810 /* tp_compare see tp_richcompare */
1811 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001812 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001813 COPYSLOT(tp_call);
1814 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001816 if (type->tp_compare == NULL &&
1817 type->tp_richcompare == NULL &&
1818 type->tp_hash == NULL)
1819 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001820 type->tp_compare = base->tp_compare;
1821 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001822 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001823 }
1824 }
1825 else {
1826 COPYSLOT(tp_compare);
1827 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001828 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1829 COPYSLOT(tp_iter);
1830 COPYSLOT(tp_iternext);
1831 }
1832 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1833 COPYSLOT(tp_descr_get);
1834 COPYSLOT(tp_descr_set);
1835 COPYSLOT(tp_dictoffset);
1836 COPYSLOT(tp_init);
1837 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001838 COPYSLOT(tp_free);
1839 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001840}
1841
Guido van Rossum13d52f02001-08-10 21:24:08 +00001842staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00001843staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001844
Tim Peters6d6c1a32001-08-02 04:15:00 +00001845int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001846PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001848 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001849 PyTypeObject *base;
1850 int i, n;
1851
Guido van Rossumd614f972001-08-10 17:39:49 +00001852 if (type->tp_flags & Py_TPFLAGS_READY) {
1853 assert(type->tp_dict != NULL);
1854 return 0;
1855 }
1856 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00001857
1858 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859
1860 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1861 base = type->tp_base;
1862 if (base == NULL && type != &PyBaseObject_Type)
1863 base = type->tp_base = &PyBaseObject_Type;
1864
1865 /* Initialize tp_bases */
1866 bases = type->tp_bases;
1867 if (bases == NULL) {
1868 if (base == NULL)
1869 bases = PyTuple_New(0);
1870 else
1871 bases = Py_BuildValue("(O)", base);
1872 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001873 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001874 type->tp_bases = bases;
1875 }
1876
1877 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001878 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001879 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001880 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001881 }
1882
Guido van Rossum687ae002001-10-15 22:03:32 +00001883 /* Initialize tp_dict */
1884 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001885 if (dict == NULL) {
1886 dict = PyDict_New();
1887 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001888 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00001889 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001890 }
1891
Guido van Rossum687ae002001-10-15 22:03:32 +00001892 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001893 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001894 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001895 if (type->tp_methods != NULL) {
1896 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001897 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001898 }
1899 if (type->tp_members != NULL) {
1900 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001901 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001902 }
1903 if (type->tp_getset != NULL) {
1904 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001905 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906 }
1907
Tim Peters6d6c1a32001-08-02 04:15:00 +00001908 /* Calculate method resolution order */
1909 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001910 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001911 }
1912
Guido van Rossum13d52f02001-08-10 21:24:08 +00001913 /* Inherit special flags from dominant base */
1914 if (type->tp_base != NULL)
1915 inherit_special(type, type->tp_base);
1916
Tim Peters6d6c1a32001-08-02 04:15:00 +00001917 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001918 bases = type->tp_mro;
1919 assert(bases != NULL);
1920 assert(PyTuple_Check(bases));
1921 n = PyTuple_GET_SIZE(bases);
1922 for (i = 1; i < n; i++) {
1923 base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1924 assert(PyType_Check(base));
1925 inherit_slots(type, base);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001926 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001927
Guido van Rossum13d52f02001-08-10 21:24:08 +00001928 /* Some more special stuff */
1929 base = type->tp_base;
1930 if (base != NULL) {
1931 if (type->tp_as_number == NULL)
1932 type->tp_as_number = base->tp_as_number;
1933 if (type->tp_as_sequence == NULL)
1934 type->tp_as_sequence = base->tp_as_sequence;
1935 if (type->tp_as_mapping == NULL)
1936 type->tp_as_mapping = base->tp_as_mapping;
1937 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001938
Guido van Rossum1c450732001-10-08 15:18:27 +00001939 /* Link into each base class's list of subclasses */
1940 bases = type->tp_bases;
1941 n = PyTuple_GET_SIZE(bases);
1942 for (i = 0; i < n; i++) {
1943 base = (PyTypeObject *) PyTuple_GET_ITEM(bases, i);
1944 if (add_subclass((PyTypeObject *)base, type) < 0)
1945 goto error;
1946 }
1947
Guido van Rossum13d52f02001-08-10 21:24:08 +00001948 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00001949 assert(type->tp_dict != NULL);
1950 type->tp_flags =
1951 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00001953
1954 error:
1955 type->tp_flags &= ~Py_TPFLAGS_READYING;
1956 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001957}
1958
Guido van Rossum1c450732001-10-08 15:18:27 +00001959static int
1960add_subclass(PyTypeObject *base, PyTypeObject *type)
1961{
1962 int i;
1963 PyObject *list, *ref, *new;
1964
1965 list = base->tp_subclasses;
1966 if (list == NULL) {
1967 base->tp_subclasses = list = PyList_New(0);
1968 if (list == NULL)
1969 return -1;
1970 }
1971 assert(PyList_Check(list));
1972 new = PyWeakref_NewRef((PyObject *)type, NULL);
1973 i = PyList_GET_SIZE(list);
1974 while (--i >= 0) {
1975 ref = PyList_GET_ITEM(list, i);
1976 assert(PyWeakref_CheckRef(ref));
1977 if (PyWeakref_GET_OBJECT(ref) == Py_None)
1978 return PyList_SetItem(list, i, new);
1979 }
1980 i = PyList_Append(list, new);
1981 Py_DECREF(new);
1982 return i;
1983}
1984
Tim Peters6d6c1a32001-08-02 04:15:00 +00001985
1986/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1987
1988/* There's a wrapper *function* for each distinct function typedef used
1989 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
1990 wrapper *table* for each distinct operation (e.g. __len__, __add__).
1991 Most tables have only one entry; the tables for binary operators have two
1992 entries, one regular and one with reversed arguments. */
1993
1994static PyObject *
1995wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1996{
1997 inquiry func = (inquiry)wrapped;
1998 int res;
1999
2000 if (!PyArg_ParseTuple(args, ""))
2001 return NULL;
2002 res = (*func)(self);
2003 if (res == -1 && PyErr_Occurred())
2004 return NULL;
2005 return PyInt_FromLong((long)res);
2006}
2007
Tim Peters6d6c1a32001-08-02 04:15:00 +00002008static PyObject *
2009wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2010{
2011 binaryfunc func = (binaryfunc)wrapped;
2012 PyObject *other;
2013
2014 if (!PyArg_ParseTuple(args, "O", &other))
2015 return NULL;
2016 return (*func)(self, other);
2017}
2018
2019static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002020wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2021{
2022 binaryfunc func = (binaryfunc)wrapped;
2023 PyObject *other;
2024
2025 if (!PyArg_ParseTuple(args, "O", &other))
2026 return NULL;
2027 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002028 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002029 Py_INCREF(Py_NotImplemented);
2030 return Py_NotImplemented;
2031 }
2032 return (*func)(self, other);
2033}
2034
2035static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002036wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2037{
2038 binaryfunc func = (binaryfunc)wrapped;
2039 PyObject *other;
2040
2041 if (!PyArg_ParseTuple(args, "O", &other))
2042 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002043 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002044 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002045 Py_INCREF(Py_NotImplemented);
2046 return Py_NotImplemented;
2047 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048 return (*func)(other, self);
2049}
2050
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002051static PyObject *
2052wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2053{
2054 coercion func = (coercion)wrapped;
2055 PyObject *other, *res;
2056 int ok;
2057
2058 if (!PyArg_ParseTuple(args, "O", &other))
2059 return NULL;
2060 ok = func(&self, &other);
2061 if (ok < 0)
2062 return NULL;
2063 if (ok > 0) {
2064 Py_INCREF(Py_NotImplemented);
2065 return Py_NotImplemented;
2066 }
2067 res = PyTuple_New(2);
2068 if (res == NULL) {
2069 Py_DECREF(self);
2070 Py_DECREF(other);
2071 return NULL;
2072 }
2073 PyTuple_SET_ITEM(res, 0, self);
2074 PyTuple_SET_ITEM(res, 1, other);
2075 return res;
2076}
2077
Tim Peters6d6c1a32001-08-02 04:15:00 +00002078static PyObject *
2079wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2080{
2081 ternaryfunc func = (ternaryfunc)wrapped;
2082 PyObject *other;
2083 PyObject *third = Py_None;
2084
2085 /* Note: This wrapper only works for __pow__() */
2086
2087 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2088 return NULL;
2089 return (*func)(self, other, third);
2090}
2091
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002092static PyObject *
2093wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2094{
2095 ternaryfunc func = (ternaryfunc)wrapped;
2096 PyObject *other;
2097 PyObject *third = Py_None;
2098
2099 /* Note: This wrapper only works for __pow__() */
2100
2101 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2102 return NULL;
2103 return (*func)(other, self, third);
2104}
2105
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106static PyObject *
2107wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2108{
2109 unaryfunc func = (unaryfunc)wrapped;
2110
2111 if (!PyArg_ParseTuple(args, ""))
2112 return NULL;
2113 return (*func)(self);
2114}
2115
Tim Peters6d6c1a32001-08-02 04:15:00 +00002116static PyObject *
2117wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2118{
2119 intargfunc func = (intargfunc)wrapped;
2120 int i;
2121
2122 if (!PyArg_ParseTuple(args, "i", &i))
2123 return NULL;
2124 return (*func)(self, i);
2125}
2126
Guido van Rossum5d815f32001-08-17 21:57:47 +00002127static int
2128getindex(PyObject *self, PyObject *arg)
2129{
2130 int i;
2131
2132 i = PyInt_AsLong(arg);
2133 if (i == -1 && PyErr_Occurred())
2134 return -1;
2135 if (i < 0) {
2136 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2137 if (sq && sq->sq_length) {
2138 int n = (*sq->sq_length)(self);
2139 if (n < 0)
2140 return -1;
2141 i += n;
2142 }
2143 }
2144 return i;
2145}
2146
2147static PyObject *
2148wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2149{
2150 intargfunc func = (intargfunc)wrapped;
2151 PyObject *arg;
2152 int i;
2153
Guido van Rossumf4593e02001-10-03 12:09:30 +00002154 if (PyTuple_GET_SIZE(args) == 1) {
2155 arg = PyTuple_GET_ITEM(args, 0);
2156 i = getindex(self, arg);
2157 if (i == -1 && PyErr_Occurred())
2158 return NULL;
2159 return (*func)(self, i);
2160 }
2161 PyArg_ParseTuple(args, "O", &arg);
2162 assert(PyErr_Occurred());
2163 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002164}
2165
Tim Peters6d6c1a32001-08-02 04:15:00 +00002166static PyObject *
2167wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2168{
2169 intintargfunc func = (intintargfunc)wrapped;
2170 int i, j;
2171
2172 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2173 return NULL;
2174 return (*func)(self, i, j);
2175}
2176
Tim Peters6d6c1a32001-08-02 04:15:00 +00002177static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002178wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002179{
2180 intobjargproc func = (intobjargproc)wrapped;
2181 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002182 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002183
Guido van Rossum5d815f32001-08-17 21:57:47 +00002184 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2185 return NULL;
2186 i = getindex(self, arg);
2187 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002188 return NULL;
2189 res = (*func)(self, i, value);
2190 if (res == -1 && PyErr_Occurred())
2191 return NULL;
2192 Py_INCREF(Py_None);
2193 return Py_None;
2194}
2195
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002196static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002197wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002198{
2199 intobjargproc func = (intobjargproc)wrapped;
2200 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002201 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002202
Guido van Rossum5d815f32001-08-17 21:57:47 +00002203 if (!PyArg_ParseTuple(args, "O", &arg))
2204 return NULL;
2205 i = getindex(self, arg);
2206 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002207 return NULL;
2208 res = (*func)(self, i, NULL);
2209 if (res == -1 && PyErr_Occurred())
2210 return NULL;
2211 Py_INCREF(Py_None);
2212 return Py_None;
2213}
2214
Tim Peters6d6c1a32001-08-02 04:15:00 +00002215static PyObject *
2216wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2217{
2218 intintobjargproc func = (intintobjargproc)wrapped;
2219 int i, j, res;
2220 PyObject *value;
2221
2222 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2223 return NULL;
2224 res = (*func)(self, i, j, value);
2225 if (res == -1 && PyErr_Occurred())
2226 return NULL;
2227 Py_INCREF(Py_None);
2228 return Py_None;
2229}
2230
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002231static PyObject *
2232wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2233{
2234 intintobjargproc func = (intintobjargproc)wrapped;
2235 int i, j, res;
2236
2237 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2238 return NULL;
2239 res = (*func)(self, i, j, NULL);
2240 if (res == -1 && PyErr_Occurred())
2241 return NULL;
2242 Py_INCREF(Py_None);
2243 return Py_None;
2244}
2245
Tim Peters6d6c1a32001-08-02 04:15:00 +00002246/* XXX objobjproc is a misnomer; should be objargpred */
2247static PyObject *
2248wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2249{
2250 objobjproc func = (objobjproc)wrapped;
2251 int res;
2252 PyObject *value;
2253
2254 if (!PyArg_ParseTuple(args, "O", &value))
2255 return NULL;
2256 res = (*func)(self, value);
2257 if (res == -1 && PyErr_Occurred())
2258 return NULL;
2259 return PyInt_FromLong((long)res);
2260}
2261
Tim Peters6d6c1a32001-08-02 04:15:00 +00002262static PyObject *
2263wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2264{
2265 objobjargproc func = (objobjargproc)wrapped;
2266 int res;
2267 PyObject *key, *value;
2268
2269 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2270 return NULL;
2271 res = (*func)(self, key, value);
2272 if (res == -1 && PyErr_Occurred())
2273 return NULL;
2274 Py_INCREF(Py_None);
2275 return Py_None;
2276}
2277
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002278static PyObject *
2279wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2280{
2281 objobjargproc func = (objobjargproc)wrapped;
2282 int res;
2283 PyObject *key;
2284
2285 if (!PyArg_ParseTuple(args, "O", &key))
2286 return NULL;
2287 res = (*func)(self, key, NULL);
2288 if (res == -1 && PyErr_Occurred())
2289 return NULL;
2290 Py_INCREF(Py_None);
2291 return Py_None;
2292}
2293
Tim Peters6d6c1a32001-08-02 04:15:00 +00002294static PyObject *
2295wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2296{
2297 cmpfunc func = (cmpfunc)wrapped;
2298 int res;
2299 PyObject *other;
2300
2301 if (!PyArg_ParseTuple(args, "O", &other))
2302 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002303 if (other->ob_type->tp_compare != func &&
2304 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002305 PyErr_Format(
2306 PyExc_TypeError,
2307 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2308 self->ob_type->tp_name,
2309 self->ob_type->tp_name,
2310 other->ob_type->tp_name);
2311 return NULL;
2312 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002313 res = (*func)(self, other);
2314 if (PyErr_Occurred())
2315 return NULL;
2316 return PyInt_FromLong((long)res);
2317}
2318
Tim Peters6d6c1a32001-08-02 04:15:00 +00002319static PyObject *
2320wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2321{
2322 setattrofunc func = (setattrofunc)wrapped;
2323 int res;
2324 PyObject *name, *value;
2325
2326 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2327 return NULL;
2328 res = (*func)(self, name, value);
2329 if (res < 0)
2330 return NULL;
2331 Py_INCREF(Py_None);
2332 return Py_None;
2333}
2334
2335static PyObject *
2336wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2337{
2338 setattrofunc func = (setattrofunc)wrapped;
2339 int res;
2340 PyObject *name;
2341
2342 if (!PyArg_ParseTuple(args, "O", &name))
2343 return NULL;
2344 res = (*func)(self, name, NULL);
2345 if (res < 0)
2346 return NULL;
2347 Py_INCREF(Py_None);
2348 return Py_None;
2349}
2350
Tim Peters6d6c1a32001-08-02 04:15:00 +00002351static PyObject *
2352wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2353{
2354 hashfunc func = (hashfunc)wrapped;
2355 long res;
2356
2357 if (!PyArg_ParseTuple(args, ""))
2358 return NULL;
2359 res = (*func)(self);
2360 if (res == -1 && PyErr_Occurred())
2361 return NULL;
2362 return PyInt_FromLong(res);
2363}
2364
Tim Peters6d6c1a32001-08-02 04:15:00 +00002365static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002366wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002367{
2368 ternaryfunc func = (ternaryfunc)wrapped;
2369
Guido van Rossumc8e56452001-10-22 00:43:43 +00002370 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002371}
2372
Tim Peters6d6c1a32001-08-02 04:15:00 +00002373static PyObject *
2374wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2375{
2376 richcmpfunc func = (richcmpfunc)wrapped;
2377 PyObject *other;
2378
2379 if (!PyArg_ParseTuple(args, "O", &other))
2380 return NULL;
2381 return (*func)(self, other, op);
2382}
2383
2384#undef RICHCMP_WRAPPER
2385#define RICHCMP_WRAPPER(NAME, OP) \
2386static PyObject * \
2387richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2388{ \
2389 return wrap_richcmpfunc(self, args, wrapped, OP); \
2390}
2391
Jack Jansen8e938b42001-08-08 15:29:49 +00002392RICHCMP_WRAPPER(lt, Py_LT)
2393RICHCMP_WRAPPER(le, Py_LE)
2394RICHCMP_WRAPPER(eq, Py_EQ)
2395RICHCMP_WRAPPER(ne, Py_NE)
2396RICHCMP_WRAPPER(gt, Py_GT)
2397RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002398
Tim Peters6d6c1a32001-08-02 04:15:00 +00002399static PyObject *
2400wrap_next(PyObject *self, PyObject *args, void *wrapped)
2401{
2402 unaryfunc func = (unaryfunc)wrapped;
2403 PyObject *res;
2404
2405 if (!PyArg_ParseTuple(args, ""))
2406 return NULL;
2407 res = (*func)(self);
2408 if (res == NULL && !PyErr_Occurred())
2409 PyErr_SetNone(PyExc_StopIteration);
2410 return res;
2411}
2412
Tim Peters6d6c1a32001-08-02 04:15:00 +00002413static PyObject *
2414wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2415{
2416 descrgetfunc func = (descrgetfunc)wrapped;
2417 PyObject *obj;
2418 PyObject *type = NULL;
2419
2420 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2421 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002422 return (*func)(self, obj, type);
2423}
2424
Tim Peters6d6c1a32001-08-02 04:15:00 +00002425static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002426wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002427{
2428 descrsetfunc func = (descrsetfunc)wrapped;
2429 PyObject *obj, *value;
2430 int ret;
2431
2432 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2433 return NULL;
2434 ret = (*func)(self, obj, value);
2435 if (ret < 0)
2436 return NULL;
2437 Py_INCREF(Py_None);
2438 return Py_None;
2439}
2440
Tim Peters6d6c1a32001-08-02 04:15:00 +00002441static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002442wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002443{
2444 initproc func = (initproc)wrapped;
2445
Guido van Rossumc8e56452001-10-22 00:43:43 +00002446 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002447 return NULL;
2448 Py_INCREF(Py_None);
2449 return Py_None;
2450}
2451
Tim Peters6d6c1a32001-08-02 04:15:00 +00002452static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002453tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002454{
Barry Warsaw60f01882001-08-22 19:24:42 +00002455 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002456 PyObject *arg0, *res;
2457
2458 if (self == NULL || !PyType_Check(self))
2459 Py_FatalError("__new__() called with non-type 'self'");
2460 type = (PyTypeObject *)self;
2461 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002462 PyErr_Format(PyExc_TypeError,
2463 "%s.__new__(): not enough arguments",
2464 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002465 return NULL;
2466 }
2467 arg0 = PyTuple_GET_ITEM(args, 0);
2468 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002469 PyErr_Format(PyExc_TypeError,
2470 "%s.__new__(X): X is not a type object (%s)",
2471 type->tp_name,
2472 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002473 return NULL;
2474 }
2475 subtype = (PyTypeObject *)arg0;
2476 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002477 PyErr_Format(PyExc_TypeError,
2478 "%s.__new__(%s): %s is not a subtype of %s",
2479 type->tp_name,
2480 subtype->tp_name,
2481 subtype->tp_name,
2482 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002483 return NULL;
2484 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002485
2486 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002487 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002488 most derived base that's not a heap type is this type. */
2489 staticbase = subtype;
2490 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2491 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002492 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002493 PyErr_Format(PyExc_TypeError,
2494 "%s.__new__(%s) is not safe, use %s.__new__()",
2495 type->tp_name,
2496 subtype->tp_name,
2497 staticbase == NULL ? "?" : staticbase->tp_name);
2498 return NULL;
2499 }
2500
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002501 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2502 if (args == NULL)
2503 return NULL;
2504 res = type->tp_new(subtype, args, kwds);
2505 Py_DECREF(args);
2506 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002507}
2508
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002509static struct PyMethodDef tp_new_methoddef[] = {
2510 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2511 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002512 {0}
2513};
2514
2515static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002516add_tp_new_wrapper(PyTypeObject *type)
2517{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002518 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002519
Guido van Rossum687ae002001-10-15 22:03:32 +00002520 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002521 return 0;
2522 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002523 if (func == NULL)
2524 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002525 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002526}
2527
Guido van Rossumf040ede2001-08-07 16:40:56 +00002528/* Slot wrappers that call the corresponding __foo__ slot. See comments
2529 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002530
Guido van Rossumdc91b992001-08-08 22:26:22 +00002531#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002532static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002533FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002534{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002535 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002536 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002537}
2538
Guido van Rossumdc91b992001-08-08 22:26:22 +00002539#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002540static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002541FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002542{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002543 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002544 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002545}
2546
Guido van Rossumdc91b992001-08-08 22:26:22 +00002547
2548#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002549static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002550FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002551{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002552 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002553 int do_other = self->ob_type != other->ob_type && \
2554 other->ob_type->tp_as_number != NULL && \
2555 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002556 if (self->ob_type->tp_as_number != NULL && \
2557 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2558 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002559 if (do_other && \
2560 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2561 r = call_maybe( \
2562 other, ROPSTR, &rcache_str, "(O)", self); \
2563 if (r != Py_NotImplemented) \
2564 return r; \
2565 Py_DECREF(r); \
2566 do_other = 0; \
2567 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002568 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002569 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002570 if (r != Py_NotImplemented || \
2571 other->ob_type == self->ob_type) \
2572 return r; \
2573 Py_DECREF(r); \
2574 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002575 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002576 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002577 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002578 } \
2579 Py_INCREF(Py_NotImplemented); \
2580 return Py_NotImplemented; \
2581}
2582
2583#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2584 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2585
2586#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2587static PyObject * \
2588FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2589{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002590 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002591 return call_method(self, OPSTR, &cache_str, \
2592 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002593}
2594
2595static int
2596slot_sq_length(PyObject *self)
2597{
Guido van Rossum2730b132001-08-28 18:22:14 +00002598 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002599 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002600 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002601
2602 if (res == NULL)
2603 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002604 len = (int)PyInt_AsLong(res);
2605 Py_DECREF(res);
2606 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002607}
2608
Guido van Rossumdc91b992001-08-08 22:26:22 +00002609SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2610SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002611
2612/* Super-optimized version of slot_sq_item.
2613 Other slots could do the same... */
2614static PyObject *
2615slot_sq_item(PyObject *self, int i)
2616{
2617 static PyObject *getitem_str;
2618 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2619 descrgetfunc f;
2620
2621 if (getitem_str == NULL) {
2622 getitem_str = PyString_InternFromString("__getitem__");
2623 if (getitem_str == NULL)
2624 return NULL;
2625 }
2626 func = _PyType_Lookup(self->ob_type, getitem_str);
2627 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002628 if ((f = func->ob_type->tp_descr_get) == NULL)
2629 Py_INCREF(func);
2630 else
2631 func = f(func, self, (PyObject *)(self->ob_type));
2632 ival = PyInt_FromLong(i);
2633 if (ival != NULL) {
2634 args = PyTuple_New(1);
2635 if (args != NULL) {
2636 PyTuple_SET_ITEM(args, 0, ival);
2637 retval = PyObject_Call(func, args, NULL);
2638 Py_XDECREF(args);
2639 Py_XDECREF(func);
2640 return retval;
2641 }
2642 }
2643 }
2644 else {
2645 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2646 }
2647 Py_XDECREF(args);
2648 Py_XDECREF(ival);
2649 Py_XDECREF(func);
2650 return NULL;
2651}
2652
Guido van Rossumdc91b992001-08-08 22:26:22 +00002653SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002654
2655static int
2656slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2657{
2658 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002659 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002660
2661 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002662 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002663 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002664 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002665 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002666 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667 if (res == NULL)
2668 return -1;
2669 Py_DECREF(res);
2670 return 0;
2671}
2672
2673static int
2674slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2675{
2676 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002677 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002678
2679 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002680 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002681 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002683 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002684 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002685 if (res == NULL)
2686 return -1;
2687 Py_DECREF(res);
2688 return 0;
2689}
2690
2691static int
2692slot_sq_contains(PyObject *self, PyObject *value)
2693{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002694 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002695 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696
Guido van Rossum55f20992001-10-01 17:18:22 +00002697 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002698
2699 if (func != NULL) {
2700 args = Py_BuildValue("(O)", value);
2701 if (args == NULL)
2702 res = NULL;
2703 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002704 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002705 Py_DECREF(args);
2706 }
2707 Py_DECREF(func);
2708 if (res == NULL)
2709 return -1;
2710 return PyObject_IsTrue(res);
2711 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002712 else if (PyErr_Occurred())
2713 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002714 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002715 return _PySequence_IterSearch(self, value,
2716 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002717 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002718}
2719
Guido van Rossumdc91b992001-08-08 22:26:22 +00002720SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2721SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002722
2723#define slot_mp_length slot_sq_length
2724
Guido van Rossumdc91b992001-08-08 22:26:22 +00002725SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726
2727static int
2728slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2729{
2730 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002731 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002732
2733 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002734 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002735 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002736 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002737 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002738 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002739 if (res == NULL)
2740 return -1;
2741 Py_DECREF(res);
2742 return 0;
2743}
2744
Guido van Rossumdc91b992001-08-08 22:26:22 +00002745SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2746SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2747SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2748SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2749SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2750SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2751
2752staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2753
2754SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2755 nb_power, "__pow__", "__rpow__")
2756
2757static PyObject *
2758slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2759{
Guido van Rossum2730b132001-08-28 18:22:14 +00002760 static PyObject *pow_str;
2761
Guido van Rossumdc91b992001-08-08 22:26:22 +00002762 if (modulus == Py_None)
2763 return slot_nb_power_binary(self, other);
2764 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002765 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002766 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002767}
2768
2769SLOT0(slot_nb_negative, "__neg__")
2770SLOT0(slot_nb_positive, "__pos__")
2771SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772
2773static int
2774slot_nb_nonzero(PyObject *self)
2775{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002776 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002777 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778
Guido van Rossum55f20992001-10-01 17:18:22 +00002779 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002780 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00002781 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00002782 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00002783 func = lookup_maybe(self, "__len__", &len_str);
2784 if (func == NULL) {
2785 if (PyErr_Occurred())
2786 return -1;
2787 else
2788 return 1;
2789 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00002790 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002791 res = PyObject_CallObject(func, NULL);
2792 Py_DECREF(func);
2793 if (res == NULL)
2794 return -1;
2795 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796}
2797
Guido van Rossumdc91b992001-08-08 22:26:22 +00002798SLOT0(slot_nb_invert, "__invert__")
2799SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2800SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2801SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2802SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2803SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002804
2805static int
2806slot_nb_coerce(PyObject **a, PyObject **b)
2807{
2808 static PyObject *coerce_str;
2809 PyObject *self = *a, *other = *b;
2810
2811 if (self->ob_type->tp_as_number != NULL &&
2812 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
2813 PyObject *r;
2814 r = call_maybe(
2815 self, "__coerce__", &coerce_str, "(O)", other);
2816 if (r == NULL)
2817 return -1;
2818 if (r == Py_NotImplemented) {
2819 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002820 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002821 else {
2822 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
2823 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002824 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00002825 Py_DECREF(r);
2826 return -1;
2827 }
2828 *a = PyTuple_GET_ITEM(r, 0);
2829 Py_INCREF(*a);
2830 *b = PyTuple_GET_ITEM(r, 1);
2831 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002832 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00002833 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002834 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002835 }
2836 if (other->ob_type->tp_as_number != NULL &&
2837 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
2838 PyObject *r;
2839 r = call_maybe(
2840 other, "__coerce__", &coerce_str, "(O)", self);
2841 if (r == NULL)
2842 return -1;
2843 if (r == Py_NotImplemented) {
2844 Py_DECREF(r);
2845 return 1;
2846 }
2847 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
2848 PyErr_SetString(PyExc_TypeError,
2849 "__coerce__ didn't return a 2-tuple");
2850 Py_DECREF(r);
2851 return -1;
2852 }
2853 *a = PyTuple_GET_ITEM(r, 1);
2854 Py_INCREF(*a);
2855 *b = PyTuple_GET_ITEM(r, 0);
2856 Py_INCREF(*b);
2857 Py_DECREF(r);
2858 return 0;
2859 }
2860 return 1;
2861}
2862
Guido van Rossumdc91b992001-08-08 22:26:22 +00002863SLOT0(slot_nb_int, "__int__")
2864SLOT0(slot_nb_long, "__long__")
2865SLOT0(slot_nb_float, "__float__")
2866SLOT0(slot_nb_oct, "__oct__")
2867SLOT0(slot_nb_hex, "__hex__")
2868SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2869SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2870SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2871SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2872SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2873SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2874SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2875SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2876SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2877SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2878SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2879SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2880 "__floordiv__", "__rfloordiv__")
2881SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2882SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2883SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002884
2885static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002886half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002887{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002888 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002889 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002890 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002891
Guido van Rossum60718732001-08-28 17:47:51 +00002892 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002893 if (func == NULL) {
2894 PyErr_Clear();
2895 }
2896 else {
2897 args = Py_BuildValue("(O)", other);
2898 if (args == NULL)
2899 res = NULL;
2900 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002901 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002902 Py_DECREF(args);
2903 }
2904 if (res != Py_NotImplemented) {
2905 if (res == NULL)
2906 return -2;
2907 c = PyInt_AsLong(res);
2908 Py_DECREF(res);
2909 if (c == -1 && PyErr_Occurred())
2910 return -2;
2911 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2912 }
2913 Py_DECREF(res);
2914 }
2915 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002916}
2917
Guido van Rossumab3b0342001-09-18 20:38:53 +00002918/* This slot is published for the benefit of try_3way_compare in object.c */
2919int
2920_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00002921{
2922 int c;
2923
Guido van Rossumab3b0342001-09-18 20:38:53 +00002924 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002925 c = half_compare(self, other);
2926 if (c <= 1)
2927 return c;
2928 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00002929 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002930 c = half_compare(other, self);
2931 if (c < -1)
2932 return -2;
2933 if (c <= 1)
2934 return -c;
2935 }
2936 return (void *)self < (void *)other ? -1 :
2937 (void *)self > (void *)other ? 1 : 0;
2938}
2939
2940static PyObject *
2941slot_tp_repr(PyObject *self)
2942{
2943 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002944 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002945
Guido van Rossum60718732001-08-28 17:47:51 +00002946 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002947 if (func != NULL) {
2948 res = PyEval_CallObject(func, NULL);
2949 Py_DECREF(func);
2950 return res;
2951 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00002952 PyErr_Clear();
2953 return PyString_FromFormat("<%s object at %p>",
2954 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002955}
2956
2957static PyObject *
2958slot_tp_str(PyObject *self)
2959{
2960 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002961 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002962
Guido van Rossum60718732001-08-28 17:47:51 +00002963 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002964 if (func != NULL) {
2965 res = PyEval_CallObject(func, NULL);
2966 Py_DECREF(func);
2967 return res;
2968 }
2969 else {
2970 PyErr_Clear();
2971 return slot_tp_repr(self);
2972 }
2973}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974
2975static long
2976slot_tp_hash(PyObject *self)
2977{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002978 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002979 static PyObject *hash_str, *eq_str, *cmp_str;
2980
Tim Peters6d6c1a32001-08-02 04:15:00 +00002981 long h;
2982
Guido van Rossum60718732001-08-28 17:47:51 +00002983 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002984
2985 if (func != NULL) {
2986 res = PyEval_CallObject(func, NULL);
2987 Py_DECREF(func);
2988 if (res == NULL)
2989 return -1;
2990 h = PyInt_AsLong(res);
2991 }
2992 else {
2993 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002994 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002995 if (func == NULL) {
2996 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00002997 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002998 }
2999 if (func != NULL) {
3000 Py_DECREF(func);
3001 PyErr_SetString(PyExc_TypeError, "unhashable type");
3002 return -1;
3003 }
3004 PyErr_Clear();
3005 h = _Py_HashPointer((void *)self);
3006 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003007 if (h == -1 && !PyErr_Occurred())
3008 h = -2;
3009 return h;
3010}
3011
3012static PyObject *
3013slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3014{
Guido van Rossum60718732001-08-28 17:47:51 +00003015 static PyObject *call_str;
3016 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003017 PyObject *res;
3018
3019 if (meth == NULL)
3020 return NULL;
3021 res = PyObject_Call(meth, args, kwds);
3022 Py_DECREF(meth);
3023 return res;
3024}
3025
Guido van Rossum14a6f832001-10-17 13:59:09 +00003026/* There are two slot dispatch functions for tp_getattro.
3027
3028 - slot_tp_getattro() is used when __getattribute__ is overridden
3029 but no __getattr__ hook is present;
3030
3031 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3032
3033 The code in update_slot() and fixup_slot_dispatchers() always installs
3034 slot_tp_getattr_hook(); this detects the absence of __getattr__ and then
3035 installs the simpler slot if necessary. */
3036
Tim Peters6d6c1a32001-08-02 04:15:00 +00003037static PyObject *
3038slot_tp_getattro(PyObject *self, PyObject *name)
3039{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003040 static PyObject *getattribute_str = NULL;
3041 return call_method(self, "__getattribute__", &getattribute_str,
3042 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043}
3044
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003045static PyObject *
3046slot_tp_getattr_hook(PyObject *self, PyObject *name)
3047{
3048 PyTypeObject *tp = self->ob_type;
3049 PyObject *getattr, *getattribute, *res;
3050 static PyObject *getattribute_str = NULL;
3051 static PyObject *getattr_str = NULL;
3052
3053 if (getattr_str == NULL) {
3054 getattr_str = PyString_InternFromString("__getattr__");
3055 if (getattr_str == NULL)
3056 return NULL;
3057 }
3058 if (getattribute_str == NULL) {
3059 getattribute_str =
3060 PyString_InternFromString("__getattribute__");
3061 if (getattribute_str == NULL)
3062 return NULL;
3063 }
3064 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003065 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003066 /* No __getattr__ hook: use a simpler dispatcher */
3067 tp->tp_getattro = slot_tp_getattro;
3068 return slot_tp_getattro(self, name);
3069 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003070 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003071 if (getattribute == NULL ||
3072 (getattribute->ob_type == &PyWrapperDescr_Type &&
3073 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3074 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003075 res = PyObject_GenericGetAttr(self, name);
3076 else
3077 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003078 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003079 PyErr_Clear();
3080 res = PyObject_CallFunction(getattr, "OO", self, name);
3081 }
3082 return res;
3083}
3084
Tim Peters6d6c1a32001-08-02 04:15:00 +00003085static int
3086slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3087{
3088 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003089 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003090
3091 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003092 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003093 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003094 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003095 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003096 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003097 if (res == NULL)
3098 return -1;
3099 Py_DECREF(res);
3100 return 0;
3101}
3102
3103/* Map rich comparison operators to their __xx__ namesakes */
3104static char *name_op[] = {
3105 "__lt__",
3106 "__le__",
3107 "__eq__",
3108 "__ne__",
3109 "__gt__",
3110 "__ge__",
3111};
3112
3113static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003114half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003116 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003117 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118
Guido van Rossum60718732001-08-28 17:47:51 +00003119 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003120 if (func == NULL) {
3121 PyErr_Clear();
3122 Py_INCREF(Py_NotImplemented);
3123 return Py_NotImplemented;
3124 }
3125 args = Py_BuildValue("(O)", other);
3126 if (args == NULL)
3127 res = NULL;
3128 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003129 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003130 Py_DECREF(args);
3131 }
3132 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003133 return res;
3134}
3135
Guido van Rossumb8f63662001-08-15 23:57:02 +00003136/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3137static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3138
3139static PyObject *
3140slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3141{
3142 PyObject *res;
3143
3144 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3145 res = half_richcompare(self, other, op);
3146 if (res != Py_NotImplemented)
3147 return res;
3148 Py_DECREF(res);
3149 }
3150 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3151 res = half_richcompare(other, self, swapped_op[op]);
3152 if (res != Py_NotImplemented) {
3153 return res;
3154 }
3155 Py_DECREF(res);
3156 }
3157 Py_INCREF(Py_NotImplemented);
3158 return Py_NotImplemented;
3159}
3160
3161static PyObject *
3162slot_tp_iter(PyObject *self)
3163{
3164 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003165 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003166
Guido van Rossum60718732001-08-28 17:47:51 +00003167 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003168 if (func != NULL) {
3169 res = PyObject_CallObject(func, NULL);
3170 Py_DECREF(func);
3171 return res;
3172 }
3173 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003174 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003175 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003176 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003177 return NULL;
3178 }
3179 Py_DECREF(func);
3180 return PySeqIter_New(self);
3181}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003182
3183static PyObject *
3184slot_tp_iternext(PyObject *self)
3185{
Guido van Rossum2730b132001-08-28 18:22:14 +00003186 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003187 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188}
3189
Guido van Rossum1a493502001-08-17 16:47:50 +00003190static PyObject *
3191slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3192{
3193 PyTypeObject *tp = self->ob_type;
3194 PyObject *get;
3195 static PyObject *get_str = NULL;
3196
3197 if (get_str == NULL) {
3198 get_str = PyString_InternFromString("__get__");
3199 if (get_str == NULL)
3200 return NULL;
3201 }
3202 get = _PyType_Lookup(tp, get_str);
3203 if (get == NULL) {
3204 /* Avoid further slowdowns */
3205 if (tp->tp_descr_get == slot_tp_descr_get)
3206 tp->tp_descr_get = NULL;
3207 Py_INCREF(self);
3208 return self;
3209 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003210 if (obj == NULL)
3211 obj = Py_None;
3212 if (type == NULL)
3213 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003214 return PyObject_CallFunction(get, "OOO", self, obj, type);
3215}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003216
3217static int
3218slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3219{
Guido van Rossum2c252392001-08-24 10:13:31 +00003220 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003221 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003222
3223 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003224 res = call_method(self, "__del__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003225 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003226 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003227 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003228 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003229 if (res == NULL)
3230 return -1;
3231 Py_DECREF(res);
3232 return 0;
3233}
3234
3235static int
3236slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3237{
Guido van Rossum60718732001-08-28 17:47:51 +00003238 static PyObject *init_str;
3239 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003240 PyObject *res;
3241
3242 if (meth == NULL)
3243 return -1;
3244 res = PyObject_Call(meth, args, kwds);
3245 Py_DECREF(meth);
3246 if (res == NULL)
3247 return -1;
3248 Py_DECREF(res);
3249 return 0;
3250}
3251
3252static PyObject *
3253slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3254{
3255 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3256 PyObject *newargs, *x;
3257 int i, n;
3258
3259 if (func == NULL)
3260 return NULL;
3261 assert(PyTuple_Check(args));
3262 n = PyTuple_GET_SIZE(args);
3263 newargs = PyTuple_New(n+1);
3264 if (newargs == NULL)
3265 return NULL;
3266 Py_INCREF(type);
3267 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3268 for (i = 0; i < n; i++) {
3269 x = PyTuple_GET_ITEM(args, i);
3270 Py_INCREF(x);
3271 PyTuple_SET_ITEM(newargs, i+1, x);
3272 }
3273 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003274 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003275 Py_DECREF(func);
3276 return x;
3277}
3278
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003279
3280/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3281 functions. The offsets here are relative to the 'etype' structure, which
3282 incorporates the additional structures used for numbers, sequences and
3283 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3284 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3285 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3286
Guido van Rossum6d204072001-10-21 00:44:31 +00003287typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003288
3289#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003290#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003291#undef ETSLOT
3292#undef SQSLOT
3293#undef MPSLOT
3294#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003295#undef UNSLOT
3296#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003297#undef BINSLOT
3298#undef RBINSLOT
3299
Guido van Rossum6d204072001-10-21 00:44:31 +00003300#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3301 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003302#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3303 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3304 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003305#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3306 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3307#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3308 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3309#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3310 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3311#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3312 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3313#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3314 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3315 "x." NAME "() <==> " DOC)
3316#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3317 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3318 "x." NAME "(y) <==> x" DOC "y")
3319#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3320 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3321 "x." NAME "(y) <==> x" DOC "y")
3322#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3323 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3324 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003325
3326static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003327 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3328 "x.__len__() <==> len(x)"),
3329 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3330 "x.__add__(y) <==> x+y"),
3331 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3332 "x.__mul__(n) <==> x*n"),
3333 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3334 "x.__rmul__(n) <==> n*x"),
3335 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3336 "x.__getitem__(y) <==> x[y]"),
3337 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3338 "x.__getslice__(i, j) <==> x[i:j]"),
3339 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3340 "x.__setitem__(i, y) <==> x[i]=y"),
3341 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3342 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003343 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003344 wrap_intintobjargproc,
3345 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3346 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3347 "x.__delslice__(i, j) <==> del x[i:j]"),
3348 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3349 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003350 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003351 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003352 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003353 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003354
Guido van Rossum6d204072001-10-21 00:44:31 +00003355 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3356 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003357 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003358 wrap_binaryfunc,
3359 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003360 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003361 wrap_objobjargproc,
3362 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003363 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003364 wrap_delitem,
3365 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003366
Guido van Rossum6d204072001-10-21 00:44:31 +00003367 BINSLOT("__add__", nb_add, slot_nb_add,
3368 "+"),
3369 RBINSLOT("__radd__", nb_add, slot_nb_add,
3370 "+"),
3371 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3372 "-"),
3373 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3374 "-"),
3375 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3376 "*"),
3377 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3378 "*"),
3379 BINSLOT("__div__", nb_divide, slot_nb_divide,
3380 "/"),
3381 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3382 "/"),
3383 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3384 "%"),
3385 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3386 "%"),
3387 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3388 "divmod(x, y)"),
3389 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3390 "divmod(y, x)"),
3391 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3392 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3393 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3394 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3395 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3396 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3397 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3398 "abs(x)"),
3399 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_unaryfunc,
3400 "x != 0"),
3401 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3402 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3403 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3404 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3405 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3406 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3407 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3408 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3409 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3410 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3411 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3412 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3413 "x.__coerce__(y) <==> coerce(x, y)"),
3414 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3415 "int(x)"),
3416 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3417 "long(x)"),
3418 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3419 "float(x)"),
3420 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3421 "oct(x)"),
3422 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3423 "hex(x)"),
3424 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3425 wrap_binaryfunc, "+"),
3426 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3427 wrap_binaryfunc, "-"),
3428 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3429 wrap_binaryfunc, "*"),
3430 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3431 wrap_binaryfunc, "/"),
3432 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3433 wrap_binaryfunc, "%"),
3434 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3435 wrap_ternaryfunc, "**"),
3436 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3437 wrap_binaryfunc, "<<"),
3438 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3439 wrap_binaryfunc, ">>"),
3440 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3441 wrap_binaryfunc, "&"),
3442 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3443 wrap_binaryfunc, "^"),
3444 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3445 wrap_binaryfunc, "|"),
3446 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3447 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3448 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3449 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3450 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3451 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3452 IBSLOT("__itruediv__", nb_inplace_true_divide,
3453 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003454
Guido van Rossum6d204072001-10-21 00:44:31 +00003455 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3456 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003457 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003458 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3459 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003460 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003461 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3462 "x.__cmp__(y) <==> cmp(x,y)"),
3463 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3464 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003465 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3466 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003467 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003468 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3469 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3470 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3471 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3472 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3473 "x.__setattr__('name', value) <==> x.name = value"),
3474 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3475 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3476 "x.__delattr__('name') <==> del x.name"),
3477 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3478 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3479 "x.__lt__(y) <==> x<y"),
3480 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3481 "x.__le__(y) <==> x<=y"),
3482 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3483 "x.__eq__(y) <==> x==y"),
3484 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3485 "x.__ne__(y) <==> x!=y"),
3486 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3487 "x.__gt__(y) <==> x>y"),
3488 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3489 "x.__ge__(y) <==> x>=y"),
3490 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3491 "x.__iter__() <==> iter(x)"),
3492 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3493 "x.next() -> the next value, or raise StopIteration"),
3494 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3495 "descr.__get__(obj[, type]) -> value"),
3496 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3497 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003498 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003499 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003500 "see x.__class__.__doc__ for signature",
3501 PyWrapperFlag_KEYWORDS),
3502 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003503 {NULL}
3504};
3505
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003506static void **
3507slotptr(PyTypeObject *type, int offset)
3508{
3509 char *ptr;
3510
3511 assert(offset >= 0);
3512 assert(offset < offsetof(etype, as_buffer));
3513 if (offset >= offsetof(etype, as_mapping)) {
3514 ptr = (void *)type->tp_as_mapping;
3515 offset -= offsetof(etype, as_mapping);
3516 }
3517 else if (offset >= offsetof(etype, as_sequence)) {
3518 ptr = (void *)type->tp_as_sequence;
3519 offset -= offsetof(etype, as_sequence);
3520 }
3521 else if (offset >= offsetof(etype, as_number)) {
3522 ptr = (void *)type->tp_as_number;
3523 offset -= offsetof(etype, as_number);
3524 }
3525 else {
3526 ptr = (void *)type;
3527 }
3528 if (ptr != NULL)
3529 ptr += offset;
3530 return (void **)ptr;
3531}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003532
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003533staticforward int recurse_down_subclasses(PyTypeObject *type,
3534 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003535
3536static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003537update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003538{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003539 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003540
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003541 for (pp = pp0; *pp; pp++) {
3542 slotdef *p = *pp;
3543 PyObject *descr;
3544 PyWrapperDescrObject *d;
3545 void *generic = NULL, *specific = NULL;
3546 int use_generic = 0;
3547 int offset = p->offset;
3548 void **ptr = slotptr(type, offset);
3549 if (ptr == NULL)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003550 continue;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003551 do {
3552 descr = _PyType_Lookup(type, p->name_strobj);
3553 if (descr == NULL)
3554 continue;
3555 generic = p->function;
3556 if (descr->ob_type == &PyWrapperDescr_Type) {
3557 d = (PyWrapperDescrObject *)descr;
3558 if (d->d_base->wrapper == p->wrapper &&
3559 PyType_IsSubtype(type, d->d_type)) {
3560 if (specific == NULL ||
3561 specific == d->d_wrapped)
3562 specific = d->d_wrapped;
3563 else
3564 use_generic = 1;
3565 }
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003566 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003567 else
3568 use_generic = 1;
3569 } while ((++p)->offset == offset);
3570 if (specific && !use_generic)
3571 *ptr = specific;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003572 else
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003573 *ptr = generic;
3574 }
3575 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003576}
3577
3578static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003579recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003580{
3581 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003582 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003583 int i, n;
3584
3585 subclasses = type->tp_subclasses;
3586 if (subclasses == NULL)
3587 return 0;
3588 assert(PyList_Check(subclasses));
3589 n = PyList_GET_SIZE(subclasses);
3590 for (i = 0; i < n; i++) {
3591 ref = PyList_GET_ITEM(subclasses, i);
3592 assert(PyWeakref_CheckRef(ref));
3593 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3594 if (subclass == NULL)
3595 continue;
3596 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003597 /* Avoid recursing down into unaffected classes */
3598 dict = subclass->tp_dict;
3599 if (dict != NULL && PyDict_Check(dict) &&
3600 PyDict_GetItem(dict, name) != NULL)
3601 continue;
3602 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003603 return -1;
3604 }
3605 return 0;
3606}
3607
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003608static int
3609slotdef_cmp(const void *aa, const void *bb)
3610{
3611 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3612 int c = a->offset - b->offset;
3613 if (c != 0)
3614 return c;
3615 else
3616 return a - b;
3617}
3618
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003619static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003620init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003621{
3622 slotdef *p;
3623 static int initialized = 0;
3624
3625 if (initialized)
3626 return;
3627 for (p = slotdefs; p->name; p++) {
3628 p->name_strobj = PyString_InternFromString(p->name);
3629 if (!p->name_strobj)
3630 Py_FatalError("XXX ouch");
3631 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003632 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3633 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003634 initialized = 1;
3635}
3636
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003637static int
3638update_slot(PyTypeObject *type, PyObject *name)
3639{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003640 slotdef *ptrs[10];
3641 slotdef *p;
3642 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003643 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003644
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003645 init_slotdefs();
3646 pp = ptrs;
3647 for (p = slotdefs; p->name; p++) {
3648 /* XXX assume name is interned! */
3649 if (p->name_strobj == name)
3650 *pp++ = p;
3651 }
3652 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003653 for (pp = ptrs; *pp; pp++) {
3654 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003655 offset = p->offset;
3656 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003657 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003658 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003659 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003660 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003661}
3662
Tim Peters6d6c1a32001-08-02 04:15:00 +00003663static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003664fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003665{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003666 slotdef *p;
3667 PyObject *mro, *descr;
3668 PyTypeObject *base;
3669 PyWrapperDescrObject *d;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003670 int i, n, offset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003671 void **ptr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003672 void *generic, *specific;
3673 int use_generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003675 init_slotdefs();
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003676 mro = type->tp_mro;
3677 assert(PyTuple_Check(mro));
3678 n = PyTuple_GET_SIZE(mro);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003679 for (p = slotdefs; p->name; ) {
3680 offset = p->offset;
3681 ptr = slotptr(type, offset);
3682 if (!ptr) {
3683 do {
3684 ++p;
3685 } while (p->offset == offset);
3686 continue;
3687 }
3688 generic = specific = NULL;
3689 use_generic = 0;
3690 do {
3691 descr = NULL;
3692 for (i = 0; i < n; i++) {
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003693 base = (PyTypeObject *)
3694 PyTuple_GET_ITEM(mro, i);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003695 assert(PyType_Check(base));
3696 descr = PyDict_GetItem(
Guido van Rossum687ae002001-10-15 22:03:32 +00003697 base->tp_dict, p->name_strobj);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003698 if (descr != NULL)
3699 break;
3700 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003701 if (descr == NULL)
3702 continue;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003703 generic = p->function;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003704 if (descr->ob_type == &PyWrapperDescr_Type) {
3705 d = (PyWrapperDescrObject *)descr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003706 if (d->d_base->wrapper == p->wrapper &&
Guido van Rossumcaf59042001-10-17 07:15:43 +00003707 PyType_IsSubtype(type, d->d_type))
3708 {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003709 if (specific == NULL ||
Guido van Rossumcaf59042001-10-17 07:15:43 +00003710 specific == d->d_wrapped)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003711 specific = d->d_wrapped;
3712 else
3713 use_generic = 1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003714 }
3715 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003716 else
3717 use_generic = 1;
3718 } while ((++p)->offset == offset);
3719 if (specific && !use_generic)
3720 *ptr = specific;
3721 else
3722 *ptr = generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003723 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003724}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003725
Guido van Rossum6d204072001-10-21 00:44:31 +00003726/* This function is called by PyType_Ready() to populate the type's
3727 dictionary with method descriptors for function slots. For each
3728 function slot (like tp_repr) that's defined in the type, one or
3729 more corresponding descriptors are added in the type's tp_dict
3730 dictionary under the appropriate name (like __repr__). Some
3731 function slots cause more than one descriptor to be added (for
3732 example, the nb_add slot adds both __add__ and __radd__
3733 descriptors) and some function slots compete for the same
3734 descriptor (for example both sq_item and mp_subscript generate a
3735 __getitem__ descriptor). This only adds new descriptors and
3736 doesn't overwrite entries in tp_dict that were previously
3737 defined. The descriptors contain a reference to the C function
3738 they must call, so that it's safe if they are copied into a
3739 subtype's __dict__ and the subtype has a different C function in
3740 its slot -- calling the method defined by the descriptor will call
3741 the C function that was used to create it, rather than the C
3742 function present in the slot when it is called. (This is important
3743 because a subtype may have a C function in the slot that calls the
3744 method from the dictionary, and we want to avoid infinite recursion
3745 here.) */
3746
3747static int
3748add_operators(PyTypeObject *type)
3749{
3750 PyObject *dict = type->tp_dict;
3751 slotdef *p;
3752 PyObject *descr;
3753 void **ptr;
3754
3755 init_slotdefs();
3756 for (p = slotdefs; p->name; p++) {
3757 if (p->wrapper == NULL)
3758 continue;
3759 ptr = slotptr(type, p->offset);
3760 if (!ptr || !*ptr)
3761 continue;
3762 if (PyDict_GetItem(dict, p->name_strobj))
3763 continue;
3764 descr = PyDescr_NewWrapper(type, p, *ptr);
3765 if (descr == NULL)
3766 return -1;
3767 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
3768 return -1;
3769 Py_DECREF(descr);
3770 }
3771 if (type->tp_new != NULL) {
3772 if (add_tp_new_wrapper(type) < 0)
3773 return -1;
3774 }
3775 return 0;
3776}
3777
Guido van Rossum705f0f52001-08-24 16:47:00 +00003778
3779/* Cooperative 'super' */
3780
3781typedef struct {
3782 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003783 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003784 PyObject *obj;
3785} superobject;
3786
Guido van Rossum6f799372001-09-20 20:46:19 +00003787static PyMemberDef super_members[] = {
3788 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3789 "the class invoking super()"},
3790 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3791 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003792 {0}
3793};
3794
Guido van Rossum705f0f52001-08-24 16:47:00 +00003795static void
3796super_dealloc(PyObject *self)
3797{
3798 superobject *su = (superobject *)self;
3799
Guido van Rossum048eb752001-10-02 21:24:57 +00003800 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003801 Py_XDECREF(su->obj);
3802 Py_XDECREF(su->type);
3803 self->ob_type->tp_free(self);
3804}
3805
3806static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003807super_repr(PyObject *self)
3808{
3809 superobject *su = (superobject *)self;
3810
3811 if (su->obj)
3812 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003813 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003814 su->type ? su->type->tp_name : "NULL",
3815 su->obj->ob_type->tp_name);
3816 else
3817 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003818 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003819 su->type ? su->type->tp_name : "NULL");
3820}
3821
3822static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003823super_getattro(PyObject *self, PyObject *name)
3824{
3825 superobject *su = (superobject *)self;
3826
3827 if (su->obj != NULL) {
3828 PyObject *mro, *res, *tmp;
3829 descrgetfunc f;
3830 int i, n;
3831
Guido van Rossume705ef12001-08-29 15:47:06 +00003832 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003833 if (mro == NULL)
3834 n = 0;
3835 else {
3836 assert(PyTuple_Check(mro));
3837 n = PyTuple_GET_SIZE(mro);
3838 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003839 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003840 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003841 break;
3842 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003843 if (i >= n && PyType_Check(su->obj)) {
3844 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003845 if (mro == NULL)
3846 n = 0;
3847 else {
3848 assert(PyTuple_Check(mro));
3849 n = PyTuple_GET_SIZE(mro);
3850 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003851 for (i = 0; i < n; i++) {
3852 if ((PyObject *)(su->type) ==
3853 PyTuple_GET_ITEM(mro, i))
3854 break;
3855 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003856 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003857 i++;
3858 res = NULL;
3859 for (; i < n; i++) {
3860 tmp = PyTuple_GET_ITEM(mro, i);
3861 assert(PyType_Check(tmp));
3862 res = PyDict_GetItem(
Guido van Rossum687ae002001-10-15 22:03:32 +00003863 ((PyTypeObject *)tmp)->tp_dict, name);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003864 if (res != NULL) {
3865 Py_INCREF(res);
3866 f = res->ob_type->tp_descr_get;
3867 if (f != NULL) {
3868 tmp = f(res, su->obj, res);
3869 Py_DECREF(res);
3870 res = tmp;
3871 }
3872 return res;
3873 }
3874 }
3875 }
3876 return PyObject_GenericGetAttr(self, name);
3877}
3878
3879static PyObject *
3880super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3881{
3882 superobject *su = (superobject *)self;
3883 superobject *new;
3884
3885 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3886 /* Not binding to an object, or already bound */
3887 Py_INCREF(self);
3888 return self;
3889 }
3890 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL);
3891 if (new == NULL)
3892 return NULL;
3893 Py_INCREF(su->type);
3894 Py_INCREF(obj);
3895 new->type = su->type;
3896 new->obj = obj;
3897 return (PyObject *)new;
3898}
3899
3900static int
3901super_init(PyObject *self, PyObject *args, PyObject *kwds)
3902{
3903 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00003904 PyTypeObject *type;
3905 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003906
3907 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
3908 return -1;
3909 if (obj == Py_None)
3910 obj = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00003911 if (obj != NULL &&
3912 !PyType_IsSubtype(obj->ob_type, type) &&
3913 !(PyType_Check(obj) &&
3914 PyType_IsSubtype((PyTypeObject *)obj, type))) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003915 PyErr_SetString(PyExc_TypeError,
Guido van Rossume705ef12001-08-29 15:47:06 +00003916 "super(type, obj): "
3917 "obj must be an instance or subtype of type");
Guido van Rossum705f0f52001-08-24 16:47:00 +00003918 return -1;
3919 }
3920 Py_INCREF(type);
3921 Py_XINCREF(obj);
3922 su->type = type;
3923 su->obj = obj;
3924 return 0;
3925}
3926
3927static char super_doc[] =
3928"super(type) -> unbound super object\n"
3929"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00003930"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00003931"Typical use to call a cooperative superclass method:\n"
3932"class C(B):\n"
3933" def meth(self, arg):\n"
3934" super(C, self).meth(arg)";
3935
Guido van Rossum048eb752001-10-02 21:24:57 +00003936static int
3937super_traverse(PyObject *self, visitproc visit, void *arg)
3938{
3939 superobject *su = (superobject *)self;
3940 int err;
3941
3942#define VISIT(SLOT) \
3943 if (SLOT) { \
3944 err = visit((PyObject *)(SLOT), arg); \
3945 if (err) \
3946 return err; \
3947 }
3948
3949 VISIT(su->obj);
3950 VISIT(su->type);
3951
3952#undef VISIT
3953
3954 return 0;
3955}
3956
Guido van Rossum705f0f52001-08-24 16:47:00 +00003957PyTypeObject PySuper_Type = {
3958 PyObject_HEAD_INIT(&PyType_Type)
3959 0, /* ob_size */
3960 "super", /* tp_name */
3961 sizeof(superobject), /* tp_basicsize */
3962 0, /* tp_itemsize */
3963 /* methods */
3964 super_dealloc, /* tp_dealloc */
3965 0, /* tp_print */
3966 0, /* tp_getattr */
3967 0, /* tp_setattr */
3968 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003969 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003970 0, /* tp_as_number */
3971 0, /* tp_as_sequence */
3972 0, /* tp_as_mapping */
3973 0, /* tp_hash */
3974 0, /* tp_call */
3975 0, /* tp_str */
3976 super_getattro, /* tp_getattro */
3977 0, /* tp_setattro */
3978 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00003979 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3980 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003981 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00003982 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003983 0, /* tp_clear */
3984 0, /* tp_richcompare */
3985 0, /* tp_weaklistoffset */
3986 0, /* tp_iter */
3987 0, /* tp_iternext */
3988 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003989 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00003990 0, /* tp_getset */
3991 0, /* tp_base */
3992 0, /* tp_dict */
3993 super_descr_get, /* tp_descr_get */
3994 0, /* tp_descr_set */
3995 0, /* tp_dictoffset */
3996 super_init, /* tp_init */
3997 PyType_GenericAlloc, /* tp_alloc */
3998 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00003999 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004000};