blob: 14a7e86c81337279ed5b07fc75a69328f78baeeb [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
Tim Petersa91e9642001-11-14 23:32:33 +0000580static int
581fill_classic_mro(PyObject *mro, PyObject *cls)
582{
583 PyObject *bases, *base;
584 int i, n;
585
586 assert(PyList_Check(mro));
587 assert(PyClass_Check(cls));
588 i = PySequence_Contains(mro, cls);
589 if (i < 0)
590 return -1;
591 if (!i) {
592 if (PyList_Append(mro, cls) < 0)
593 return -1;
594 }
595 bases = ((PyClassObject *)cls)->cl_bases;
596 assert(bases && PyTuple_Check(bases));
597 n = PyTuple_GET_SIZE(bases);
598 for (i = 0; i < n; i++) {
599 base = PyTuple_GET_ITEM(bases, i);
600 if (fill_classic_mro(mro, base) < 0)
601 return -1;
602 }
603 return 0;
604}
605
606static PyObject *
607classic_mro(PyObject *cls)
608{
609 PyObject *mro;
610
611 assert(PyClass_Check(cls));
612 mro = PyList_New(0);
613 if (mro != NULL) {
614 if (fill_classic_mro(mro, cls) == 0)
615 return mro;
616 Py_DECREF(mro);
617 }
618 return NULL;
619}
620
Tim Peters6d6c1a32001-08-02 04:15:00 +0000621static PyObject *
622mro_implementation(PyTypeObject *type)
623{
624 int i, n, ok;
625 PyObject *bases, *result;
626
627 bases = type->tp_bases;
628 n = PyTuple_GET_SIZE(bases);
629 result = Py_BuildValue("[O]", (PyObject *)type);
630 if (result == NULL)
631 return NULL;
632 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000633 PyObject *base = PyTuple_GET_ITEM(bases, i);
634 PyObject *parentMRO;
635 if (PyType_Check(base))
636 parentMRO = PySequence_List(
637 ((PyTypeObject*)base)->tp_mro);
638 else
639 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640 if (parentMRO == NULL) {
641 Py_DECREF(result);
642 return NULL;
643 }
644 if (serious_order_disagreements(result, parentMRO)) {
645 Py_DECREF(result);
646 return NULL;
647 }
648 ok = conservative_merge(result, parentMRO);
649 Py_DECREF(parentMRO);
650 if (ok < 0) {
651 Py_DECREF(result);
652 return NULL;
653 }
654 }
655 return result;
656}
657
658static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000659mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000660{
661 PyTypeObject *type = (PyTypeObject *)self;
662
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663 return mro_implementation(type);
664}
665
666static int
667mro_internal(PyTypeObject *type)
668{
669 PyObject *mro, *result, *tuple;
670
671 if (type->ob_type == &PyType_Type) {
672 result = mro_implementation(type);
673 }
674 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000675 static PyObject *mro_str;
676 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677 if (mro == NULL)
678 return -1;
679 result = PyObject_CallObject(mro, NULL);
680 Py_DECREF(mro);
681 }
682 if (result == NULL)
683 return -1;
684 tuple = PySequence_Tuple(result);
685 Py_DECREF(result);
686 type->tp_mro = tuple;
687 return 0;
688}
689
690
691/* Calculate the best base amongst multiple base classes.
692 This is the first one that's on the path to the "solid base". */
693
694static PyTypeObject *
695best_base(PyObject *bases)
696{
697 int i, n;
698 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000699 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700
701 assert(PyTuple_Check(bases));
702 n = PyTuple_GET_SIZE(bases);
703 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000704 base = NULL;
705 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000706 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000707 base_proto = PyTuple_GET_ITEM(bases, i);
708 if (PyClass_Check(base_proto))
709 continue;
710 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000711 PyErr_SetString(
712 PyExc_TypeError,
713 "bases must be types");
714 return NULL;
715 }
Tim Petersa91e9642001-11-14 23:32:33 +0000716 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000717 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000718 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000719 return NULL;
720 }
721 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000722 if (winner == NULL) {
723 winner = candidate;
724 base = base_i;
725 }
726 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000727 ;
728 else if (PyType_IsSubtype(candidate, winner)) {
729 winner = candidate;
730 base = base_i;
731 }
732 else {
733 PyErr_SetString(
734 PyExc_TypeError,
735 "multiple bases have "
736 "instance lay-out conflict");
737 return NULL;
738 }
739 }
740 assert(base != NULL);
741 return base;
742}
743
744static int
745extra_ivars(PyTypeObject *type, PyTypeObject *base)
746{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000747 size_t t_size = type->tp_basicsize;
748 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000749
Guido van Rossum9676b222001-08-17 20:32:36 +0000750 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000751 if (type->tp_itemsize || base->tp_itemsize) {
752 /* If itemsize is involved, stricter rules */
753 return t_size != b_size ||
754 type->tp_itemsize != base->tp_itemsize;
755 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000756 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
757 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
758 t_size -= sizeof(PyObject *);
759 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
760 type->tp_dictoffset + sizeof(PyObject *) == t_size)
761 t_size -= sizeof(PyObject *);
762
763 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000764}
765
766static PyTypeObject *
767solid_base(PyTypeObject *type)
768{
769 PyTypeObject *base;
770
771 if (type->tp_base)
772 base = solid_base(type->tp_base);
773 else
774 base = &PyBaseObject_Type;
775 if (extra_ivars(type, base))
776 return type;
777 else
778 return base;
779}
780
781staticforward void object_dealloc(PyObject *);
782staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000783staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000784staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000785
786static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000787subtype_dict(PyObject *obj, void *context)
788{
789 PyObject **dictptr = _PyObject_GetDictPtr(obj);
790 PyObject *dict;
791
792 if (dictptr == NULL) {
793 PyErr_SetString(PyExc_AttributeError,
794 "This object has no __dict__");
795 return NULL;
796 }
797 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000798 if (dict == NULL)
799 *dictptr = dict = PyDict_New();
800 Py_XINCREF(dict);
801 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000802}
803
Guido van Rossum6661be32001-10-26 04:26:12 +0000804static int
805subtype_setdict(PyObject *obj, PyObject *value, void *context)
806{
807 PyObject **dictptr = _PyObject_GetDictPtr(obj);
808 PyObject *dict;
809
810 if (dictptr == NULL) {
811 PyErr_SetString(PyExc_AttributeError,
812 "This object has no __dict__");
813 return -1;
814 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000815 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000816 PyErr_SetString(PyExc_TypeError,
817 "__dict__ must be set to a dictionary");
818 return -1;
819 }
820 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000821 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000822 *dictptr = value;
823 Py_XDECREF(dict);
824 return 0;
825}
826
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000827static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000828 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000829 {0},
830};
831
832static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000833type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
834{
835 PyObject *name, *bases, *dict;
836 static char *kwlist[] = {"name", "bases", "dict", 0};
837 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000838 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000840 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000841 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000842
Tim Peters3abca122001-10-27 19:37:48 +0000843 assert(args != NULL && PyTuple_Check(args));
844 assert(kwds == NULL || PyDict_Check(kwds));
845
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000846 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +0000847 {
848 const int nargs = PyTuple_GET_SIZE(args);
849 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
850
851 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
852 PyObject *x = PyTuple_GET_ITEM(args, 0);
853 Py_INCREF(x->ob_type);
854 return (PyObject *) x->ob_type;
855 }
856
857 /* SF bug 475327 -- if that didn't trigger, we need 3
858 arguments. but PyArg_ParseTupleAndKeywords below may give
859 a msg saying type() needs exactly 3. */
860 if (nargs + nkwds != 3) {
861 PyErr_SetString(PyExc_TypeError,
862 "type() takes 1 or 3 arguments");
863 return NULL;
864 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000865 }
866
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000867 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
869 &name,
870 &PyTuple_Type, &bases,
871 &PyDict_Type, &dict))
872 return NULL;
873
874 /* Determine the proper metatype to deal with this,
875 and check for metatype conflicts while we're at it.
876 Note that if some other metatype wins to contract,
877 it's possible that its instances are not types. */
878 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000879 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000880 for (i = 0; i < nbases; i++) {
881 tmp = PyTuple_GET_ITEM(bases, i);
882 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +0000883 if (tmptype == &PyClass_Type)
884 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000885 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000886 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000887 if (PyType_IsSubtype(tmptype, winner)) {
888 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000889 continue;
890 }
891 PyErr_SetString(PyExc_TypeError,
892 "metatype conflict among bases");
893 return NULL;
894 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000895 if (winner != metatype) {
896 if (winner->tp_new != type_new) /* Pass it to the winner */
897 return winner->tp_new(winner, args, kwds);
898 metatype = winner;
899 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000900
901 /* Adjust for empty tuple bases */
902 if (nbases == 0) {
903 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
904 if (bases == NULL)
905 return NULL;
906 nbases = 1;
907 }
908 else
909 Py_INCREF(bases);
910
911 /* XXX From here until type is allocated, "return NULL" leaks bases! */
912
913 /* Calculate best base, and check that all bases are type objects */
914 base = best_base(bases);
915 if (base == NULL)
916 return NULL;
917 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
918 PyErr_Format(PyExc_TypeError,
919 "type '%.100s' is not an acceptable base type",
920 base->tp_name);
921 return NULL;
922 }
923
Tim Peters6d6c1a32001-08-02 04:15:00 +0000924 /* Check for a __slots__ sequence variable in dict, and count it */
925 slots = PyDict_GetItemString(dict, "__slots__");
926 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000927 add_dict = 0;
928 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000929 if (slots != NULL) {
930 /* Make it into a tuple */
931 if (PyString_Check(slots))
932 slots = Py_BuildValue("(O)", slots);
933 else
934 slots = PySequence_Tuple(slots);
935 if (slots == NULL)
936 return NULL;
937 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000938 if (nslots > 0 && base->tp_itemsize != 0) {
939 PyErr_Format(PyExc_TypeError,
940 "nonempty __slots__ "
941 "not supported for subtype of '%s'",
942 base->tp_name);
943 return NULL;
944 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000945 for (i = 0; i < nslots; i++) {
946 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
947 PyErr_SetString(PyExc_TypeError,
948 "__slots__ must be a sequence of strings");
949 Py_DECREF(slots);
950 return NULL;
951 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000952 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000953 }
954 }
955 if (slots == NULL && base->tp_dictoffset == 0 &&
956 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +0000957 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000958 add_dict++;
959 }
Guido van Rossumc4141872001-08-30 04:43:35 +0000960 if (slots == NULL && base->tp_weaklistoffset == 0 &&
961 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +0000962 nslots++;
963 add_weak++;
964 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000965
966 /* XXX From here until type is safely allocated,
967 "return NULL" may leak slots! */
968
969 /* Allocate the type object */
970 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
971 if (type == NULL)
972 return NULL;
973
974 /* Keep name and slots alive in the extended type object */
975 et = (etype *)type;
976 Py_INCREF(name);
977 et->name = name;
978 et->slots = slots;
979
Guido van Rossumdc91b992001-08-08 22:26:22 +0000980 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000981 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
982 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +0000983 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
984 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +0000985
986 /* It's a new-style number unless it specifically inherits any
987 old-style numeric behavior */
988 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
989 (base->tp_as_number == NULL))
990 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
991
992 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993 type->tp_as_number = &et->as_number;
994 type->tp_as_sequence = &et->as_sequence;
995 type->tp_as_mapping = &et->as_mapping;
996 type->tp_as_buffer = &et->as_buffer;
997 type->tp_name = PyString_AS_STRING(name);
998
999 /* Set tp_base and tp_bases */
1000 type->tp_bases = bases;
1001 Py_INCREF(base);
1002 type->tp_base = base;
1003
Guido van Rossum687ae002001-10-15 22:03:32 +00001004 /* Initialize tp_dict from passed-in dict */
1005 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001006 if (dict == NULL) {
1007 Py_DECREF(type);
1008 return NULL;
1009 }
1010
Guido van Rossumc3542212001-08-16 09:18:56 +00001011 /* Set __module__ in the dict */
1012 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1013 tmp = PyEval_GetGlobals();
1014 if (tmp != NULL) {
1015 tmp = PyDict_GetItemString(tmp, "__name__");
1016 if (tmp != NULL) {
1017 if (PyDict_SetItemString(dict, "__module__",
1018 tmp) < 0)
1019 return NULL;
1020 }
1021 }
1022 }
1023
Tim Peters2f93e282001-10-04 05:27:00 +00001024 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
1025 and is a string (tp_doc is a char* -- can't copy a general object
1026 into it).
1027 XXX What if it's a Unicode string? Don't know -- this ignores it.
1028 */
1029 {
1030 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1031 if (doc != NULL && PyString_Check(doc)) {
1032 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001033 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001034 if (type->tp_doc == NULL) {
1035 Py_DECREF(type);
1036 return NULL;
1037 }
1038 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1039 }
1040 }
1041
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042 /* Special-case __new__: if it's a plain function,
1043 make it a static function */
1044 tmp = PyDict_GetItemString(dict, "__new__");
1045 if (tmp != NULL && PyFunction_Check(tmp)) {
1046 tmp = PyStaticMethod_New(tmp);
1047 if (tmp == NULL) {
1048 Py_DECREF(type);
1049 return NULL;
1050 }
1051 PyDict_SetItemString(dict, "__new__", tmp);
1052 Py_DECREF(tmp);
1053 }
1054
1055 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1056 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001057 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001058 if (slots != NULL) {
1059 for (i = 0; i < nslots; i++, mp++) {
1060 mp->name = PyString_AS_STRING(
1061 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001062 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001063 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001064 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001065 strcmp(mp->name, "__weakref__") == 0) {
1066 mp->type = T_OBJECT;
Guido van Rossum9676b222001-08-17 20:32:36 +00001067 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001068 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069 slotoffset += sizeof(PyObject *);
1070 }
1071 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001072 else {
1073 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001074 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001075 type->tp_dictoffset =
1076 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001077 else
1078 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001079 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001080 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001081 }
1082 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001083 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001084 type->tp_weaklistoffset = slotoffset;
1085 mp->name = "__weakref__";
1086 mp->type = T_OBJECT;
1087 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001088 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001089 mp++;
1090 slotoffset += sizeof(PyObject *);
1091 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001092 }
1093 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001094 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001095 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001096
1097 /* Special case some slots */
1098 if (type->tp_dictoffset != 0 || nslots > 0) {
1099 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1100 type->tp_getattro = PyObject_GenericGetAttr;
1101 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1102 type->tp_setattro = PyObject_GenericSetAttr;
1103 }
1104 type->tp_dealloc = subtype_dealloc;
1105
Guido van Rossum9475a232001-10-05 20:51:39 +00001106 /* Enable GC unless there are really no instance variables possible */
1107 if (!(type->tp_basicsize == sizeof(PyObject) &&
1108 type->tp_itemsize == 0))
1109 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1110
Tim Peters6d6c1a32001-08-02 04:15:00 +00001111 /* Always override allocation strategy to use regular heap */
1112 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001113 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1114 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001115 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001116 type->tp_clear = base->tp_clear;
1117 }
1118 else
1119 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001120
1121 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001122 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 Py_DECREF(type);
1124 return NULL;
1125 }
1126
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001127 /* Put the proper slots in place */
1128 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001129
Tim Peters6d6c1a32001-08-02 04:15:00 +00001130 return (PyObject *)type;
1131}
1132
1133/* Internal API to look for a name through the MRO.
1134 This returns a borrowed reference, and doesn't set an exception! */
1135PyObject *
1136_PyType_Lookup(PyTypeObject *type, PyObject *name)
1137{
1138 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001139 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001140
Guido van Rossum687ae002001-10-15 22:03:32 +00001141 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001142 mro = type->tp_mro;
1143 assert(PyTuple_Check(mro));
1144 n = PyTuple_GET_SIZE(mro);
1145 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001146 base = PyTuple_GET_ITEM(mro, i);
1147 if (PyClass_Check(base))
1148 dict = ((PyClassObject *)base)->cl_dict;
1149 else {
1150 assert(PyType_Check(base));
1151 dict = ((PyTypeObject *)base)->tp_dict;
1152 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001153 assert(dict && PyDict_Check(dict));
1154 res = PyDict_GetItem(dict, name);
1155 if (res != NULL)
1156 return res;
1157 }
1158 return NULL;
1159}
1160
1161/* This is similar to PyObject_GenericGetAttr(),
1162 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1163static PyObject *
1164type_getattro(PyTypeObject *type, PyObject *name)
1165{
1166 PyTypeObject *metatype = type->ob_type;
1167 PyObject *descr, *res;
1168 descrgetfunc f;
1169
1170 /* Initialize this type (we'll assume the metatype is initialized) */
1171 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001172 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173 return NULL;
1174 }
1175
1176 /* Get a descriptor from the metatype */
1177 descr = _PyType_Lookup(metatype, name);
1178 f = NULL;
1179 if (descr != NULL) {
1180 f = descr->ob_type->tp_descr_get;
1181 if (f != NULL && PyDescr_IsData(descr))
1182 return f(descr,
1183 (PyObject *)type, (PyObject *)metatype);
1184 }
1185
Guido van Rossum687ae002001-10-15 22:03:32 +00001186 /* Look in tp_dict of this type and its bases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001187 res = _PyType_Lookup(type, name);
1188 if (res != NULL) {
1189 f = res->ob_type->tp_descr_get;
1190 if (f != NULL)
1191 return f(res, (PyObject *)NULL, (PyObject *)type);
1192 Py_INCREF(res);
1193 return res;
1194 }
1195
1196 /* Use the descriptor from the metatype */
1197 if (f != NULL) {
1198 res = f(descr, (PyObject *)type, (PyObject *)metatype);
1199 return res;
1200 }
1201 if (descr != NULL) {
1202 Py_INCREF(descr);
1203 return descr;
1204 }
1205
1206 /* Give up */
1207 PyErr_Format(PyExc_AttributeError,
1208 "type object '%.50s' has no attribute '%.400s'",
1209 type->tp_name, PyString_AS_STRING(name));
1210 return NULL;
1211}
1212
1213static int
1214type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1215{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001216 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1217 PyErr_Format(
1218 PyExc_TypeError,
1219 "can't set attributes of built-in/extension type '%s'",
1220 type->tp_name);
1221 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001222 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001223 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1224 return -1;
1225 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001226}
1227
1228static void
1229type_dealloc(PyTypeObject *type)
1230{
1231 etype *et;
1232
1233 /* Assert this is a heap-allocated type object */
1234 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001235 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001236 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 et = (etype *)type;
1238 Py_XDECREF(type->tp_base);
1239 Py_XDECREF(type->tp_dict);
1240 Py_XDECREF(type->tp_bases);
1241 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001242 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001243 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 Py_XDECREF(et->name);
1245 Py_XDECREF(et->slots);
1246 type->ob_type->tp_free((PyObject *)type);
1247}
1248
Guido van Rossum1c450732001-10-08 15:18:27 +00001249static PyObject *
1250type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1251{
1252 PyObject *list, *raw, *ref;
1253 int i, n;
1254
1255 list = PyList_New(0);
1256 if (list == NULL)
1257 return NULL;
1258 raw = type->tp_subclasses;
1259 if (raw == NULL)
1260 return list;
1261 assert(PyList_Check(raw));
1262 n = PyList_GET_SIZE(raw);
1263 for (i = 0; i < n; i++) {
1264 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001265 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001266 ref = PyWeakref_GET_OBJECT(ref);
1267 if (ref != Py_None) {
1268 if (PyList_Append(list, ref) < 0) {
1269 Py_DECREF(list);
1270 return NULL;
1271 }
1272 }
1273 }
1274 return list;
1275}
1276
Tim Peters6d6c1a32001-08-02 04:15:00 +00001277static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001278 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001279 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001280 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1281 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282 {0}
1283};
1284
1285static char type_doc[] =
1286"type(object) -> the object's type\n"
1287"type(name, bases, dict) -> a new type";
1288
Guido van Rossum048eb752001-10-02 21:24:57 +00001289static int
1290type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1291{
1292 etype *et;
1293 int err;
1294
1295 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1296 return 0;
1297
1298 et = (etype *)type;
1299
1300#define VISIT(SLOT) \
1301 if (SLOT) { \
1302 err = visit((PyObject *)(SLOT), arg); \
1303 if (err) \
1304 return err; \
1305 }
1306
1307 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001308 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001309 VISIT(type->tp_mro);
1310 VISIT(type->tp_bases);
1311 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001312 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001313 VISIT(et->slots);
1314
1315#undef VISIT
1316
1317 return 0;
1318}
1319
1320static int
1321type_clear(PyTypeObject *type)
1322{
1323 etype *et;
1324 PyObject *tmp;
1325
1326 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1327 return 0;
1328
1329 et = (etype *)type;
1330
1331#define CLEAR(SLOT) \
1332 if (SLOT) { \
1333 tmp = (PyObject *)(SLOT); \
1334 SLOT = NULL; \
1335 Py_DECREF(tmp); \
1336 }
1337
1338 CLEAR(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001339 CLEAR(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001340 CLEAR(type->tp_mro);
1341 CLEAR(type->tp_bases);
1342 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001343 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001344 CLEAR(et->slots);
1345
Tim Peters2f93e282001-10-04 05:27:00 +00001346 if (type->tp_doc != NULL) {
1347 PyObject_FREE(type->tp_doc);
1348 type->tp_doc = NULL;
1349 }
1350
Guido van Rossum048eb752001-10-02 21:24:57 +00001351#undef CLEAR
1352
1353 return 0;
1354}
1355
1356static int
1357type_is_gc(PyTypeObject *type)
1358{
1359 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1360}
1361
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001362PyTypeObject PyType_Type = {
1363 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364 0, /* ob_size */
1365 "type", /* tp_name */
1366 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001367 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001368 (destructor)type_dealloc, /* tp_dealloc */
1369 0, /* tp_print */
1370 0, /* tp_getattr */
1371 0, /* tp_setattr */
1372 type_compare, /* tp_compare */
1373 (reprfunc)type_repr, /* tp_repr */
1374 0, /* tp_as_number */
1375 0, /* tp_as_sequence */
1376 0, /* tp_as_mapping */
1377 (hashfunc)_Py_HashPointer, /* tp_hash */
1378 (ternaryfunc)type_call, /* tp_call */
1379 0, /* tp_str */
1380 (getattrofunc)type_getattro, /* tp_getattro */
1381 (setattrofunc)type_setattro, /* tp_setattro */
1382 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001383 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1384 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001386 (traverseproc)type_traverse, /* tp_traverse */
1387 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001388 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001389 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001390 0, /* tp_iter */
1391 0, /* tp_iternext */
1392 type_methods, /* tp_methods */
1393 type_members, /* tp_members */
1394 type_getsets, /* tp_getset */
1395 0, /* tp_base */
1396 0, /* tp_dict */
1397 0, /* tp_descr_get */
1398 0, /* tp_descr_set */
1399 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1400 0, /* tp_init */
1401 0, /* tp_alloc */
1402 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001403 _PyObject_GC_Del, /* tp_free */
1404 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001405};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001406
1407
1408/* The base type of all types (eventually)... except itself. */
1409
1410static int
1411object_init(PyObject *self, PyObject *args, PyObject *kwds)
1412{
1413 return 0;
1414}
1415
1416static void
1417object_dealloc(PyObject *self)
1418{
1419 self->ob_type->tp_free(self);
1420}
1421
Guido van Rossum8e248182001-08-12 05:17:56 +00001422static PyObject *
1423object_repr(PyObject *self)
1424{
Guido van Rossum76e69632001-08-16 18:52:43 +00001425 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001426 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001427
Guido van Rossum76e69632001-08-16 18:52:43 +00001428 type = self->ob_type;
1429 mod = type_module(type, NULL);
1430 if (mod == NULL)
1431 PyErr_Clear();
1432 else if (!PyString_Check(mod)) {
1433 Py_DECREF(mod);
1434 mod = NULL;
1435 }
1436 name = type_name(type, NULL);
1437 if (name == NULL)
1438 return NULL;
1439 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001440 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001441 PyString_AS_STRING(mod),
1442 PyString_AS_STRING(name),
1443 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001444 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001445 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001446 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001447 Py_XDECREF(mod);
1448 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001449 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001450}
1451
Guido van Rossumb8f63662001-08-15 23:57:02 +00001452static PyObject *
1453object_str(PyObject *self)
1454{
1455 unaryfunc f;
1456
1457 f = self->ob_type->tp_repr;
1458 if (f == NULL)
1459 f = object_repr;
1460 return f(self);
1461}
1462
Guido van Rossum8e248182001-08-12 05:17:56 +00001463static long
1464object_hash(PyObject *self)
1465{
1466 return _Py_HashPointer(self);
1467}
Guido van Rossum8e248182001-08-12 05:17:56 +00001468
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001469static PyObject *
1470object_get_class(PyObject *self, void *closure)
1471{
1472 Py_INCREF(self->ob_type);
1473 return (PyObject *)(self->ob_type);
1474}
1475
1476static int
1477equiv_structs(PyTypeObject *a, PyTypeObject *b)
1478{
1479 return a == b ||
1480 (a != NULL &&
1481 b != NULL &&
1482 a->tp_basicsize == b->tp_basicsize &&
1483 a->tp_itemsize == b->tp_itemsize &&
1484 a->tp_dictoffset == b->tp_dictoffset &&
1485 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1486 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1487 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1488}
1489
1490static int
1491same_slots_added(PyTypeObject *a, PyTypeObject *b)
1492{
1493 PyTypeObject *base = a->tp_base;
1494 int size;
1495
1496 if (base != b->tp_base)
1497 return 0;
1498 if (equiv_structs(a, base) && equiv_structs(b, base))
1499 return 1;
1500 size = base->tp_basicsize;
1501 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1502 size += sizeof(PyObject *);
1503 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1504 size += sizeof(PyObject *);
1505 return size == a->tp_basicsize && size == b->tp_basicsize;
1506}
1507
1508static int
1509object_set_class(PyObject *self, PyObject *value, void *closure)
1510{
1511 PyTypeObject *old = self->ob_type;
1512 PyTypeObject *new, *newbase, *oldbase;
1513
1514 if (!PyType_Check(value)) {
1515 PyErr_Format(PyExc_TypeError,
1516 "__class__ must be set to new-style class, not '%s' object",
1517 value->ob_type->tp_name);
1518 return -1;
1519 }
1520 new = (PyTypeObject *)value;
1521 newbase = new;
1522 oldbase = old;
1523 while (equiv_structs(newbase, newbase->tp_base))
1524 newbase = newbase->tp_base;
1525 while (equiv_structs(oldbase, oldbase->tp_base))
1526 oldbase = oldbase->tp_base;
1527 if (newbase != oldbase &&
1528 (newbase->tp_base != oldbase->tp_base ||
1529 !same_slots_added(newbase, oldbase))) {
1530 PyErr_Format(PyExc_TypeError,
1531 "__class__ assignment: "
1532 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001533 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001534 old->tp_name);
1535 return -1;
1536 }
1537 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1538 Py_INCREF(new);
1539 }
1540 self->ob_type = new;
1541 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1542 Py_DECREF(old);
1543 }
1544 return 0;
1545}
1546
1547static PyGetSetDef object_getsets[] = {
1548 {"__class__", object_get_class, object_set_class,
1549 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550 {0}
1551};
1552
Guido van Rossum3926a632001-09-25 16:25:58 +00001553static PyObject *
1554object_reduce(PyObject *self, PyObject *args)
1555{
1556 /* Call copy_reg._reduce(self) */
1557 static PyObject *copy_reg_str;
1558 PyObject *copy_reg, *res;
1559
1560 if (!copy_reg_str) {
1561 copy_reg_str = PyString_InternFromString("copy_reg");
1562 if (copy_reg_str == NULL)
1563 return NULL;
1564 }
1565 copy_reg = PyImport_Import(copy_reg_str);
1566 if (!copy_reg)
1567 return NULL;
1568 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1569 Py_DECREF(copy_reg);
1570 return res;
1571}
1572
1573static PyMethodDef object_methods[] = {
1574 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1575 {0}
1576};
1577
Tim Peters6d6c1a32001-08-02 04:15:00 +00001578PyTypeObject PyBaseObject_Type = {
1579 PyObject_HEAD_INIT(&PyType_Type)
1580 0, /* ob_size */
1581 "object", /* tp_name */
1582 sizeof(PyObject), /* tp_basicsize */
1583 0, /* tp_itemsize */
1584 (destructor)object_dealloc, /* tp_dealloc */
1585 0, /* tp_print */
1586 0, /* tp_getattr */
1587 0, /* tp_setattr */
1588 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001589 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001590 0, /* tp_as_number */
1591 0, /* tp_as_sequence */
1592 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001593 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001594 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001595 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001596 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001597 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001598 0, /* tp_as_buffer */
1599 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1600 "The most base type", /* tp_doc */
1601 0, /* tp_traverse */
1602 0, /* tp_clear */
1603 0, /* tp_richcompare */
1604 0, /* tp_weaklistoffset */
1605 0, /* tp_iter */
1606 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001607 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001608 0, /* tp_members */
1609 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001610 0, /* tp_base */
1611 0, /* tp_dict */
1612 0, /* tp_descr_get */
1613 0, /* tp_descr_set */
1614 0, /* tp_dictoffset */
1615 object_init, /* tp_init */
1616 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001617 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001618 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001619};
1620
1621
1622/* Initialize the __dict__ in a type object */
1623
1624static int
1625add_methods(PyTypeObject *type, PyMethodDef *meth)
1626{
Guido van Rossum687ae002001-10-15 22:03:32 +00001627 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628
1629 for (; meth->ml_name != NULL; meth++) {
1630 PyObject *descr;
1631 if (PyDict_GetItemString(dict, meth->ml_name))
1632 continue;
1633 descr = PyDescr_NewMethod(type, meth);
1634 if (descr == NULL)
1635 return -1;
1636 if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
1637 return -1;
1638 Py_DECREF(descr);
1639 }
1640 return 0;
1641}
1642
1643static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001644add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645{
Guido van Rossum687ae002001-10-15 22:03:32 +00001646 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001647
1648 for (; memb->name != NULL; memb++) {
1649 PyObject *descr;
1650 if (PyDict_GetItemString(dict, memb->name))
1651 continue;
1652 descr = PyDescr_NewMember(type, memb);
1653 if (descr == NULL)
1654 return -1;
1655 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1656 return -1;
1657 Py_DECREF(descr);
1658 }
1659 return 0;
1660}
1661
1662static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001663add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001664{
Guido van Rossum687ae002001-10-15 22:03:32 +00001665 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001666
1667 for (; gsp->name != NULL; gsp++) {
1668 PyObject *descr;
1669 if (PyDict_GetItemString(dict, gsp->name))
1670 continue;
1671 descr = PyDescr_NewGetSet(type, gsp);
1672
1673 if (descr == NULL)
1674 return -1;
1675 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1676 return -1;
1677 Py_DECREF(descr);
1678 }
1679 return 0;
1680}
1681
Guido van Rossum13d52f02001-08-10 21:24:08 +00001682static void
1683inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684{
1685 int oldsize, newsize;
1686
Guido van Rossum13d52f02001-08-10 21:24:08 +00001687 /* Special flag magic */
1688 if (!type->tp_as_buffer && base->tp_as_buffer) {
1689 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1690 type->tp_flags |=
1691 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1692 }
1693 if (!type->tp_as_sequence && base->tp_as_sequence) {
1694 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1695 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1696 }
1697 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1698 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1699 if ((!type->tp_as_number && base->tp_as_number) ||
1700 (!type->tp_as_sequence && base->tp_as_sequence)) {
1701 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1702 if (!type->tp_as_number && !type->tp_as_sequence) {
1703 type->tp_flags |= base->tp_flags &
1704 Py_TPFLAGS_HAVE_INPLACEOPS;
1705 }
1706 }
1707 /* Wow */
1708 }
1709 if (!type->tp_as_number && base->tp_as_number) {
1710 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1711 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1712 }
1713
1714 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001715 oldsize = base->tp_basicsize;
1716 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1717 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1718 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001719 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1720 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001721 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001722 if (type->tp_traverse == NULL)
1723 type->tp_traverse = base->tp_traverse;
1724 if (type->tp_clear == NULL)
1725 type->tp_clear = base->tp_clear;
1726 }
1727 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1728 if (base != &PyBaseObject_Type ||
1729 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1730 if (type->tp_new == NULL)
1731 type->tp_new = base->tp_new;
1732 }
1733 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001734 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001735
1736 /* Copy other non-function slots */
1737
1738#undef COPYVAL
1739#define COPYVAL(SLOT) \
1740 if (type->SLOT == 0) type->SLOT = base->SLOT
1741
1742 COPYVAL(tp_itemsize);
1743 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1744 COPYVAL(tp_weaklistoffset);
1745 }
1746 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1747 COPYVAL(tp_dictoffset);
1748 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001749}
1750
1751static void
1752inherit_slots(PyTypeObject *type, PyTypeObject *base)
1753{
1754 PyTypeObject *basebase;
1755
1756#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001757#undef COPYSLOT
1758#undef COPYNUM
1759#undef COPYSEQ
1760#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001761#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001762
1763#define SLOTDEFINED(SLOT) \
1764 (base->SLOT != 0 && \
1765 (basebase == NULL || base->SLOT != basebase->SLOT))
1766
Tim Peters6d6c1a32001-08-02 04:15:00 +00001767#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001768 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001769
1770#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1771#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1772#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001773#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774
Guido van Rossum13d52f02001-08-10 21:24:08 +00001775 /* This won't inherit indirect slots (from tp_as_number etc.)
1776 if type doesn't provide the space. */
1777
1778 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1779 basebase = base->tp_base;
1780 if (basebase->tp_as_number == NULL)
1781 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001782 COPYNUM(nb_add);
1783 COPYNUM(nb_subtract);
1784 COPYNUM(nb_multiply);
1785 COPYNUM(nb_divide);
1786 COPYNUM(nb_remainder);
1787 COPYNUM(nb_divmod);
1788 COPYNUM(nb_power);
1789 COPYNUM(nb_negative);
1790 COPYNUM(nb_positive);
1791 COPYNUM(nb_absolute);
1792 COPYNUM(nb_nonzero);
1793 COPYNUM(nb_invert);
1794 COPYNUM(nb_lshift);
1795 COPYNUM(nb_rshift);
1796 COPYNUM(nb_and);
1797 COPYNUM(nb_xor);
1798 COPYNUM(nb_or);
1799 COPYNUM(nb_coerce);
1800 COPYNUM(nb_int);
1801 COPYNUM(nb_long);
1802 COPYNUM(nb_float);
1803 COPYNUM(nb_oct);
1804 COPYNUM(nb_hex);
1805 COPYNUM(nb_inplace_add);
1806 COPYNUM(nb_inplace_subtract);
1807 COPYNUM(nb_inplace_multiply);
1808 COPYNUM(nb_inplace_divide);
1809 COPYNUM(nb_inplace_remainder);
1810 COPYNUM(nb_inplace_power);
1811 COPYNUM(nb_inplace_lshift);
1812 COPYNUM(nb_inplace_rshift);
1813 COPYNUM(nb_inplace_and);
1814 COPYNUM(nb_inplace_xor);
1815 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001816 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1817 COPYNUM(nb_true_divide);
1818 COPYNUM(nb_floor_divide);
1819 COPYNUM(nb_inplace_true_divide);
1820 COPYNUM(nb_inplace_floor_divide);
1821 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001822 }
1823
Guido van Rossum13d52f02001-08-10 21:24:08 +00001824 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1825 basebase = base->tp_base;
1826 if (basebase->tp_as_sequence == NULL)
1827 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001828 COPYSEQ(sq_length);
1829 COPYSEQ(sq_concat);
1830 COPYSEQ(sq_repeat);
1831 COPYSEQ(sq_item);
1832 COPYSEQ(sq_slice);
1833 COPYSEQ(sq_ass_item);
1834 COPYSEQ(sq_ass_slice);
1835 COPYSEQ(sq_contains);
1836 COPYSEQ(sq_inplace_concat);
1837 COPYSEQ(sq_inplace_repeat);
1838 }
1839
Guido van Rossum13d52f02001-08-10 21:24:08 +00001840 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1841 basebase = base->tp_base;
1842 if (basebase->tp_as_mapping == NULL)
1843 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 COPYMAP(mp_length);
1845 COPYMAP(mp_subscript);
1846 COPYMAP(mp_ass_subscript);
1847 }
1848
Tim Petersfc57ccb2001-10-12 02:38:24 +00001849 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1850 basebase = base->tp_base;
1851 if (basebase->tp_as_buffer == NULL)
1852 basebase = NULL;
1853 COPYBUF(bf_getreadbuffer);
1854 COPYBUF(bf_getwritebuffer);
1855 COPYBUF(bf_getsegcount);
1856 COPYBUF(bf_getcharbuffer);
1857 }
1858
Guido van Rossum13d52f02001-08-10 21:24:08 +00001859 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001860
Tim Peters6d6c1a32001-08-02 04:15:00 +00001861 COPYSLOT(tp_dealloc);
1862 COPYSLOT(tp_print);
1863 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1864 type->tp_getattr = base->tp_getattr;
1865 type->tp_getattro = base->tp_getattro;
1866 }
1867 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1868 type->tp_setattr = base->tp_setattr;
1869 type->tp_setattro = base->tp_setattro;
1870 }
1871 /* tp_compare see tp_richcompare */
1872 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00001873 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001874 COPYSLOT(tp_call);
1875 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001876 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00001877 if (type->tp_compare == NULL &&
1878 type->tp_richcompare == NULL &&
1879 type->tp_hash == NULL)
1880 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001881 type->tp_compare = base->tp_compare;
1882 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00001883 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001884 }
1885 }
1886 else {
1887 COPYSLOT(tp_compare);
1888 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001889 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1890 COPYSLOT(tp_iter);
1891 COPYSLOT(tp_iternext);
1892 }
1893 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1894 COPYSLOT(tp_descr_get);
1895 COPYSLOT(tp_descr_set);
1896 COPYSLOT(tp_dictoffset);
1897 COPYSLOT(tp_init);
1898 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001899 COPYSLOT(tp_free);
1900 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001901}
1902
Guido van Rossum13d52f02001-08-10 21:24:08 +00001903staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00001904staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00001905
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001907PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001908{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001909 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910 PyTypeObject *base;
1911 int i, n;
1912
Guido van Rossumd614f972001-08-10 17:39:49 +00001913 if (type->tp_flags & Py_TPFLAGS_READY) {
1914 assert(type->tp_dict != NULL);
1915 return 0;
1916 }
1917 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00001918
1919 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001920
1921 /* Initialize tp_base (defaults to BaseObject unless that's us) */
1922 base = type->tp_base;
1923 if (base == NULL && type != &PyBaseObject_Type)
1924 base = type->tp_base = &PyBaseObject_Type;
1925
1926 /* Initialize tp_bases */
1927 bases = type->tp_bases;
1928 if (bases == NULL) {
1929 if (base == NULL)
1930 bases = PyTuple_New(0);
1931 else
1932 bases = Py_BuildValue("(O)", base);
1933 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001934 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001935 type->tp_bases = bases;
1936 }
1937
1938 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00001939 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001940 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001941 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001942 }
1943
Guido van Rossum687ae002001-10-15 22:03:32 +00001944 /* Initialize tp_dict */
1945 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001946 if (dict == NULL) {
1947 dict = PyDict_New();
1948 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00001949 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00001950 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001951 }
1952
Guido van Rossum687ae002001-10-15 22:03:32 +00001953 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001954 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001955 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001956 if (type->tp_methods != NULL) {
1957 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001958 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001959 }
1960 if (type->tp_members != NULL) {
1961 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001962 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001963 }
1964 if (type->tp_getset != NULL) {
1965 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00001966 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001967 }
1968
Tim Peters6d6c1a32001-08-02 04:15:00 +00001969 /* Calculate method resolution order */
1970 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00001971 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972 }
1973
Guido van Rossum13d52f02001-08-10 21:24:08 +00001974 /* Inherit special flags from dominant base */
1975 if (type->tp_base != NULL)
1976 inherit_special(type, type->tp_base);
1977
Tim Peters6d6c1a32001-08-02 04:15:00 +00001978 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001979 bases = type->tp_mro;
1980 assert(bases != NULL);
1981 assert(PyTuple_Check(bases));
1982 n = PyTuple_GET_SIZE(bases);
1983 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001984 PyObject *b = PyTuple_GET_ITEM(bases, i);
1985 if (PyType_Check(b))
1986 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001987 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001988
Guido van Rossum13d52f02001-08-10 21:24:08 +00001989 /* Some more special stuff */
1990 base = type->tp_base;
1991 if (base != NULL) {
1992 if (type->tp_as_number == NULL)
1993 type->tp_as_number = base->tp_as_number;
1994 if (type->tp_as_sequence == NULL)
1995 type->tp_as_sequence = base->tp_as_sequence;
1996 if (type->tp_as_mapping == NULL)
1997 type->tp_as_mapping = base->tp_as_mapping;
1998 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001999
Guido van Rossum1c450732001-10-08 15:18:27 +00002000 /* Link into each base class's list of subclasses */
2001 bases = type->tp_bases;
2002 n = PyTuple_GET_SIZE(bases);
2003 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002004 PyObject *b = PyTuple_GET_ITEM(bases, i);
2005 if (PyType_Check(b) &&
2006 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002007 goto error;
2008 }
2009
Guido van Rossum13d52f02001-08-10 21:24:08 +00002010 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002011 assert(type->tp_dict != NULL);
2012 type->tp_flags =
2013 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002015
2016 error:
2017 type->tp_flags &= ~Py_TPFLAGS_READYING;
2018 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019}
2020
Guido van Rossum1c450732001-10-08 15:18:27 +00002021static int
2022add_subclass(PyTypeObject *base, PyTypeObject *type)
2023{
2024 int i;
2025 PyObject *list, *ref, *new;
2026
2027 list = base->tp_subclasses;
2028 if (list == NULL) {
2029 base->tp_subclasses = list = PyList_New(0);
2030 if (list == NULL)
2031 return -1;
2032 }
2033 assert(PyList_Check(list));
2034 new = PyWeakref_NewRef((PyObject *)type, NULL);
2035 i = PyList_GET_SIZE(list);
2036 while (--i >= 0) {
2037 ref = PyList_GET_ITEM(list, i);
2038 assert(PyWeakref_CheckRef(ref));
2039 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2040 return PyList_SetItem(list, i, new);
2041 }
2042 i = PyList_Append(list, new);
2043 Py_DECREF(new);
2044 return i;
2045}
2046
Tim Peters6d6c1a32001-08-02 04:15:00 +00002047
2048/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2049
2050/* There's a wrapper *function* for each distinct function typedef used
2051 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2052 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2053 Most tables have only one entry; the tables for binary operators have two
2054 entries, one regular and one with reversed arguments. */
2055
2056static PyObject *
2057wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2058{
2059 inquiry func = (inquiry)wrapped;
2060 int res;
2061
2062 if (!PyArg_ParseTuple(args, ""))
2063 return NULL;
2064 res = (*func)(self);
2065 if (res == -1 && PyErr_Occurred())
2066 return NULL;
2067 return PyInt_FromLong((long)res);
2068}
2069
Tim Peters6d6c1a32001-08-02 04:15:00 +00002070static PyObject *
2071wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2072{
2073 binaryfunc func = (binaryfunc)wrapped;
2074 PyObject *other;
2075
2076 if (!PyArg_ParseTuple(args, "O", &other))
2077 return NULL;
2078 return (*func)(self, other);
2079}
2080
2081static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002082wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2083{
2084 binaryfunc func = (binaryfunc)wrapped;
2085 PyObject *other;
2086
2087 if (!PyArg_ParseTuple(args, "O", &other))
2088 return NULL;
2089 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002090 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002091 Py_INCREF(Py_NotImplemented);
2092 return Py_NotImplemented;
2093 }
2094 return (*func)(self, other);
2095}
2096
2097static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2099{
2100 binaryfunc func = (binaryfunc)wrapped;
2101 PyObject *other;
2102
2103 if (!PyArg_ParseTuple(args, "O", &other))
2104 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002105 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002106 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002107 Py_INCREF(Py_NotImplemented);
2108 return Py_NotImplemented;
2109 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110 return (*func)(other, self);
2111}
2112
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002113static PyObject *
2114wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2115{
2116 coercion func = (coercion)wrapped;
2117 PyObject *other, *res;
2118 int ok;
2119
2120 if (!PyArg_ParseTuple(args, "O", &other))
2121 return NULL;
2122 ok = func(&self, &other);
2123 if (ok < 0)
2124 return NULL;
2125 if (ok > 0) {
2126 Py_INCREF(Py_NotImplemented);
2127 return Py_NotImplemented;
2128 }
2129 res = PyTuple_New(2);
2130 if (res == NULL) {
2131 Py_DECREF(self);
2132 Py_DECREF(other);
2133 return NULL;
2134 }
2135 PyTuple_SET_ITEM(res, 0, self);
2136 PyTuple_SET_ITEM(res, 1, other);
2137 return res;
2138}
2139
Tim Peters6d6c1a32001-08-02 04:15:00 +00002140static PyObject *
2141wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2142{
2143 ternaryfunc func = (ternaryfunc)wrapped;
2144 PyObject *other;
2145 PyObject *third = Py_None;
2146
2147 /* Note: This wrapper only works for __pow__() */
2148
2149 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2150 return NULL;
2151 return (*func)(self, other, third);
2152}
2153
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002154static PyObject *
2155wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2156{
2157 ternaryfunc func = (ternaryfunc)wrapped;
2158 PyObject *other;
2159 PyObject *third = Py_None;
2160
2161 /* Note: This wrapper only works for __pow__() */
2162
2163 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2164 return NULL;
2165 return (*func)(other, self, third);
2166}
2167
Tim Peters6d6c1a32001-08-02 04:15:00 +00002168static PyObject *
2169wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2170{
2171 unaryfunc func = (unaryfunc)wrapped;
2172
2173 if (!PyArg_ParseTuple(args, ""))
2174 return NULL;
2175 return (*func)(self);
2176}
2177
Tim Peters6d6c1a32001-08-02 04:15:00 +00002178static PyObject *
2179wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2180{
2181 intargfunc func = (intargfunc)wrapped;
2182 int i;
2183
2184 if (!PyArg_ParseTuple(args, "i", &i))
2185 return NULL;
2186 return (*func)(self, i);
2187}
2188
Guido van Rossum5d815f32001-08-17 21:57:47 +00002189static int
2190getindex(PyObject *self, PyObject *arg)
2191{
2192 int i;
2193
2194 i = PyInt_AsLong(arg);
2195 if (i == -1 && PyErr_Occurred())
2196 return -1;
2197 if (i < 0) {
2198 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2199 if (sq && sq->sq_length) {
2200 int n = (*sq->sq_length)(self);
2201 if (n < 0)
2202 return -1;
2203 i += n;
2204 }
2205 }
2206 return i;
2207}
2208
2209static PyObject *
2210wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2211{
2212 intargfunc func = (intargfunc)wrapped;
2213 PyObject *arg;
2214 int i;
2215
Guido van Rossumf4593e02001-10-03 12:09:30 +00002216 if (PyTuple_GET_SIZE(args) == 1) {
2217 arg = PyTuple_GET_ITEM(args, 0);
2218 i = getindex(self, arg);
2219 if (i == -1 && PyErr_Occurred())
2220 return NULL;
2221 return (*func)(self, i);
2222 }
2223 PyArg_ParseTuple(args, "O", &arg);
2224 assert(PyErr_Occurred());
2225 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002226}
2227
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228static PyObject *
2229wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2230{
2231 intintargfunc func = (intintargfunc)wrapped;
2232 int i, j;
2233
2234 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2235 return NULL;
2236 return (*func)(self, i, j);
2237}
2238
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002240wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241{
2242 intobjargproc func = (intobjargproc)wrapped;
2243 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002244 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002245
Guido van Rossum5d815f32001-08-17 21:57:47 +00002246 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2247 return NULL;
2248 i = getindex(self, arg);
2249 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002250 return NULL;
2251 res = (*func)(self, i, value);
2252 if (res == -1 && PyErr_Occurred())
2253 return NULL;
2254 Py_INCREF(Py_None);
2255 return Py_None;
2256}
2257
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002258static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002259wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002260{
2261 intobjargproc func = (intobjargproc)wrapped;
2262 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002263 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002264
Guido van Rossum5d815f32001-08-17 21:57:47 +00002265 if (!PyArg_ParseTuple(args, "O", &arg))
2266 return NULL;
2267 i = getindex(self, arg);
2268 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002269 return NULL;
2270 res = (*func)(self, i, NULL);
2271 if (res == -1 && PyErr_Occurred())
2272 return NULL;
2273 Py_INCREF(Py_None);
2274 return Py_None;
2275}
2276
Tim Peters6d6c1a32001-08-02 04:15:00 +00002277static PyObject *
2278wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2279{
2280 intintobjargproc func = (intintobjargproc)wrapped;
2281 int i, j, res;
2282 PyObject *value;
2283
2284 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2285 return NULL;
2286 res = (*func)(self, i, j, value);
2287 if (res == -1 && PyErr_Occurred())
2288 return NULL;
2289 Py_INCREF(Py_None);
2290 return Py_None;
2291}
2292
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002293static PyObject *
2294wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2295{
2296 intintobjargproc func = (intintobjargproc)wrapped;
2297 int i, j, res;
2298
2299 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2300 return NULL;
2301 res = (*func)(self, i, j, NULL);
2302 if (res == -1 && PyErr_Occurred())
2303 return NULL;
2304 Py_INCREF(Py_None);
2305 return Py_None;
2306}
2307
Tim Peters6d6c1a32001-08-02 04:15:00 +00002308/* XXX objobjproc is a misnomer; should be objargpred */
2309static PyObject *
2310wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2311{
2312 objobjproc func = (objobjproc)wrapped;
2313 int res;
2314 PyObject *value;
2315
2316 if (!PyArg_ParseTuple(args, "O", &value))
2317 return NULL;
2318 res = (*func)(self, value);
2319 if (res == -1 && PyErr_Occurred())
2320 return NULL;
2321 return PyInt_FromLong((long)res);
2322}
2323
Tim Peters6d6c1a32001-08-02 04:15:00 +00002324static PyObject *
2325wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2326{
2327 objobjargproc func = (objobjargproc)wrapped;
2328 int res;
2329 PyObject *key, *value;
2330
2331 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2332 return NULL;
2333 res = (*func)(self, key, value);
2334 if (res == -1 && PyErr_Occurred())
2335 return NULL;
2336 Py_INCREF(Py_None);
2337 return Py_None;
2338}
2339
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002340static PyObject *
2341wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2342{
2343 objobjargproc func = (objobjargproc)wrapped;
2344 int res;
2345 PyObject *key;
2346
2347 if (!PyArg_ParseTuple(args, "O", &key))
2348 return NULL;
2349 res = (*func)(self, key, NULL);
2350 if (res == -1 && PyErr_Occurred())
2351 return NULL;
2352 Py_INCREF(Py_None);
2353 return Py_None;
2354}
2355
Tim Peters6d6c1a32001-08-02 04:15:00 +00002356static PyObject *
2357wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2358{
2359 cmpfunc func = (cmpfunc)wrapped;
2360 int res;
2361 PyObject *other;
2362
2363 if (!PyArg_ParseTuple(args, "O", &other))
2364 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002365 if (other->ob_type->tp_compare != func &&
2366 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002367 PyErr_Format(
2368 PyExc_TypeError,
2369 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2370 self->ob_type->tp_name,
2371 self->ob_type->tp_name,
2372 other->ob_type->tp_name);
2373 return NULL;
2374 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002375 res = (*func)(self, other);
2376 if (PyErr_Occurred())
2377 return NULL;
2378 return PyInt_FromLong((long)res);
2379}
2380
Tim Peters6d6c1a32001-08-02 04:15:00 +00002381static PyObject *
2382wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2383{
2384 setattrofunc func = (setattrofunc)wrapped;
2385 int res;
2386 PyObject *name, *value;
2387
2388 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2389 return NULL;
2390 res = (*func)(self, name, value);
2391 if (res < 0)
2392 return NULL;
2393 Py_INCREF(Py_None);
2394 return Py_None;
2395}
2396
2397static PyObject *
2398wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2399{
2400 setattrofunc func = (setattrofunc)wrapped;
2401 int res;
2402 PyObject *name;
2403
2404 if (!PyArg_ParseTuple(args, "O", &name))
2405 return NULL;
2406 res = (*func)(self, name, NULL);
2407 if (res < 0)
2408 return NULL;
2409 Py_INCREF(Py_None);
2410 return Py_None;
2411}
2412
Tim Peters6d6c1a32001-08-02 04:15:00 +00002413static PyObject *
2414wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2415{
2416 hashfunc func = (hashfunc)wrapped;
2417 long res;
2418
2419 if (!PyArg_ParseTuple(args, ""))
2420 return NULL;
2421 res = (*func)(self);
2422 if (res == -1 && PyErr_Occurred())
2423 return NULL;
2424 return PyInt_FromLong(res);
2425}
2426
Tim Peters6d6c1a32001-08-02 04:15:00 +00002427static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002428wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002429{
2430 ternaryfunc func = (ternaryfunc)wrapped;
2431
Guido van Rossumc8e56452001-10-22 00:43:43 +00002432 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002433}
2434
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435static PyObject *
2436wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2437{
2438 richcmpfunc func = (richcmpfunc)wrapped;
2439 PyObject *other;
2440
2441 if (!PyArg_ParseTuple(args, "O", &other))
2442 return NULL;
2443 return (*func)(self, other, op);
2444}
2445
2446#undef RICHCMP_WRAPPER
2447#define RICHCMP_WRAPPER(NAME, OP) \
2448static PyObject * \
2449richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2450{ \
2451 return wrap_richcmpfunc(self, args, wrapped, OP); \
2452}
2453
Jack Jansen8e938b42001-08-08 15:29:49 +00002454RICHCMP_WRAPPER(lt, Py_LT)
2455RICHCMP_WRAPPER(le, Py_LE)
2456RICHCMP_WRAPPER(eq, Py_EQ)
2457RICHCMP_WRAPPER(ne, Py_NE)
2458RICHCMP_WRAPPER(gt, Py_GT)
2459RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002460
Tim Peters6d6c1a32001-08-02 04:15:00 +00002461static PyObject *
2462wrap_next(PyObject *self, PyObject *args, void *wrapped)
2463{
2464 unaryfunc func = (unaryfunc)wrapped;
2465 PyObject *res;
2466
2467 if (!PyArg_ParseTuple(args, ""))
2468 return NULL;
2469 res = (*func)(self);
2470 if (res == NULL && !PyErr_Occurred())
2471 PyErr_SetNone(PyExc_StopIteration);
2472 return res;
2473}
2474
Tim Peters6d6c1a32001-08-02 04:15:00 +00002475static PyObject *
2476wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2477{
2478 descrgetfunc func = (descrgetfunc)wrapped;
2479 PyObject *obj;
2480 PyObject *type = NULL;
2481
2482 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2483 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484 return (*func)(self, obj, type);
2485}
2486
Tim Peters6d6c1a32001-08-02 04:15:00 +00002487static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002488wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002489{
2490 descrsetfunc func = (descrsetfunc)wrapped;
2491 PyObject *obj, *value;
2492 int ret;
2493
2494 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2495 return NULL;
2496 ret = (*func)(self, obj, value);
2497 if (ret < 0)
2498 return NULL;
2499 Py_INCREF(Py_None);
2500 return Py_None;
2501}
2502
Tim Peters6d6c1a32001-08-02 04:15:00 +00002503static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002504wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002505{
2506 initproc func = (initproc)wrapped;
2507
Guido van Rossumc8e56452001-10-22 00:43:43 +00002508 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002509 return NULL;
2510 Py_INCREF(Py_None);
2511 return Py_None;
2512}
2513
Tim Peters6d6c1a32001-08-02 04:15:00 +00002514static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002515tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002516{
Barry Warsaw60f01882001-08-22 19:24:42 +00002517 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002518 PyObject *arg0, *res;
2519
2520 if (self == NULL || !PyType_Check(self))
2521 Py_FatalError("__new__() called with non-type 'self'");
2522 type = (PyTypeObject *)self;
2523 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002524 PyErr_Format(PyExc_TypeError,
2525 "%s.__new__(): not enough arguments",
2526 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002527 return NULL;
2528 }
2529 arg0 = PyTuple_GET_ITEM(args, 0);
2530 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002531 PyErr_Format(PyExc_TypeError,
2532 "%s.__new__(X): X is not a type object (%s)",
2533 type->tp_name,
2534 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002535 return NULL;
2536 }
2537 subtype = (PyTypeObject *)arg0;
2538 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002539 PyErr_Format(PyExc_TypeError,
2540 "%s.__new__(%s): %s is not a subtype of %s",
2541 type->tp_name,
2542 subtype->tp_name,
2543 subtype->tp_name,
2544 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002545 return NULL;
2546 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002547
2548 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002549 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002550 most derived base that's not a heap type is this type. */
2551 staticbase = subtype;
2552 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2553 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002554 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002555 PyErr_Format(PyExc_TypeError,
2556 "%s.__new__(%s) is not safe, use %s.__new__()",
2557 type->tp_name,
2558 subtype->tp_name,
2559 staticbase == NULL ? "?" : staticbase->tp_name);
2560 return NULL;
2561 }
2562
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002563 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2564 if (args == NULL)
2565 return NULL;
2566 res = type->tp_new(subtype, args, kwds);
2567 Py_DECREF(args);
2568 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002569}
2570
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002571static struct PyMethodDef tp_new_methoddef[] = {
2572 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2573 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002574 {0}
2575};
2576
2577static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002578add_tp_new_wrapper(PyTypeObject *type)
2579{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002580 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002581
Guido van Rossum687ae002001-10-15 22:03:32 +00002582 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002583 return 0;
2584 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002585 if (func == NULL)
2586 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002587 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002588}
2589
Guido van Rossumf040ede2001-08-07 16:40:56 +00002590/* Slot wrappers that call the corresponding __foo__ slot. See comments
2591 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002592
Guido van Rossumdc91b992001-08-08 22:26:22 +00002593#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002594static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002595FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002596{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002597 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002598 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002599}
2600
Guido van Rossumdc91b992001-08-08 22:26:22 +00002601#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002602static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002603FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002604{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002605 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002606 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002607}
2608
Guido van Rossumdc91b992001-08-08 22:26:22 +00002609
2610#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002611static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002612FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002613{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002614 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002615 int do_other = self->ob_type != other->ob_type && \
2616 other->ob_type->tp_as_number != NULL && \
2617 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002618 if (self->ob_type->tp_as_number != NULL && \
2619 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2620 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002621 if (do_other && \
2622 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2623 r = call_maybe( \
2624 other, ROPSTR, &rcache_str, "(O)", self); \
2625 if (r != Py_NotImplemented) \
2626 return r; \
2627 Py_DECREF(r); \
2628 do_other = 0; \
2629 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002630 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002631 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002632 if (r != Py_NotImplemented || \
2633 other->ob_type == self->ob_type) \
2634 return r; \
2635 Py_DECREF(r); \
2636 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002637 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002638 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002639 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002640 } \
2641 Py_INCREF(Py_NotImplemented); \
2642 return Py_NotImplemented; \
2643}
2644
2645#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2646 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2647
2648#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2649static PyObject * \
2650FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2651{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002652 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002653 return call_method(self, OPSTR, &cache_str, \
2654 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002655}
2656
2657static int
2658slot_sq_length(PyObject *self)
2659{
Guido van Rossum2730b132001-08-28 18:22:14 +00002660 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002661 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002662 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002663
2664 if (res == NULL)
2665 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002666 len = (int)PyInt_AsLong(res);
2667 Py_DECREF(res);
2668 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002669}
2670
Guido van Rossumdc91b992001-08-08 22:26:22 +00002671SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2672SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002673
2674/* Super-optimized version of slot_sq_item.
2675 Other slots could do the same... */
2676static PyObject *
2677slot_sq_item(PyObject *self, int i)
2678{
2679 static PyObject *getitem_str;
2680 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2681 descrgetfunc f;
2682
2683 if (getitem_str == NULL) {
2684 getitem_str = PyString_InternFromString("__getitem__");
2685 if (getitem_str == NULL)
2686 return NULL;
2687 }
2688 func = _PyType_Lookup(self->ob_type, getitem_str);
2689 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002690 if ((f = func->ob_type->tp_descr_get) == NULL)
2691 Py_INCREF(func);
2692 else
2693 func = f(func, self, (PyObject *)(self->ob_type));
2694 ival = PyInt_FromLong(i);
2695 if (ival != NULL) {
2696 args = PyTuple_New(1);
2697 if (args != NULL) {
2698 PyTuple_SET_ITEM(args, 0, ival);
2699 retval = PyObject_Call(func, args, NULL);
2700 Py_XDECREF(args);
2701 Py_XDECREF(func);
2702 return retval;
2703 }
2704 }
2705 }
2706 else {
2707 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2708 }
2709 Py_XDECREF(args);
2710 Py_XDECREF(ival);
2711 Py_XDECREF(func);
2712 return NULL;
2713}
2714
Guido van Rossumdc91b992001-08-08 22:26:22 +00002715SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716
2717static int
2718slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2719{
2720 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002721 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002722
2723 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002724 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002725 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002727 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002728 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002729 if (res == NULL)
2730 return -1;
2731 Py_DECREF(res);
2732 return 0;
2733}
2734
2735static int
2736slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2737{
2738 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002739 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002740
2741 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002742 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002743 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002744 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002745 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002746 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002747 if (res == NULL)
2748 return -1;
2749 Py_DECREF(res);
2750 return 0;
2751}
2752
2753static int
2754slot_sq_contains(PyObject *self, PyObject *value)
2755{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002756 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002757 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758
Guido van Rossum55f20992001-10-01 17:18:22 +00002759 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002760
2761 if (func != NULL) {
2762 args = Py_BuildValue("(O)", value);
2763 if (args == NULL)
2764 res = NULL;
2765 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002766 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002767 Py_DECREF(args);
2768 }
2769 Py_DECREF(func);
2770 if (res == NULL)
2771 return -1;
2772 return PyObject_IsTrue(res);
2773 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002774 else if (PyErr_Occurred())
2775 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002776 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002777 return _PySequence_IterSearch(self, value,
2778 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002779 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780}
2781
Guido van Rossumdc91b992001-08-08 22:26:22 +00002782SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2783SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784
2785#define slot_mp_length slot_sq_length
2786
Guido van Rossumdc91b992001-08-08 22:26:22 +00002787SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788
2789static int
2790slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2791{
2792 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002793 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794
2795 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002796 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002797 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002798 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002799 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002800 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801 if (res == NULL)
2802 return -1;
2803 Py_DECREF(res);
2804 return 0;
2805}
2806
Guido van Rossumdc91b992001-08-08 22:26:22 +00002807SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2808SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2809SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2810SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2811SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2812SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2813
2814staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2815
2816SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2817 nb_power, "__pow__", "__rpow__")
2818
2819static PyObject *
2820slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2821{
Guido van Rossum2730b132001-08-28 18:22:14 +00002822 static PyObject *pow_str;
2823
Guido van Rossumdc91b992001-08-08 22:26:22 +00002824 if (modulus == Py_None)
2825 return slot_nb_power_binary(self, other);
2826 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002827 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002828 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002829}
2830
2831SLOT0(slot_nb_negative, "__neg__")
2832SLOT0(slot_nb_positive, "__pos__")
2833SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002834
2835static int
2836slot_nb_nonzero(PyObject *self)
2837{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002838 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002839 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002840
Guido van Rossum55f20992001-10-01 17:18:22 +00002841 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002842 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00002843 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00002844 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00002845 func = lookup_maybe(self, "__len__", &len_str);
2846 if (func == NULL) {
2847 if (PyErr_Occurred())
2848 return -1;
2849 else
2850 return 1;
2851 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00002852 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002853 res = PyObject_CallObject(func, NULL);
2854 Py_DECREF(func);
2855 if (res == NULL)
2856 return -1;
2857 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002858}
2859
Guido van Rossumdc91b992001-08-08 22:26:22 +00002860SLOT0(slot_nb_invert, "__invert__")
2861SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2862SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2863SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2864SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2865SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002866
2867static int
2868slot_nb_coerce(PyObject **a, PyObject **b)
2869{
2870 static PyObject *coerce_str;
2871 PyObject *self = *a, *other = *b;
2872
2873 if (self->ob_type->tp_as_number != NULL &&
2874 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
2875 PyObject *r;
2876 r = call_maybe(
2877 self, "__coerce__", &coerce_str, "(O)", other);
2878 if (r == NULL)
2879 return -1;
2880 if (r == Py_NotImplemented) {
2881 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002882 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002883 else {
2884 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
2885 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002886 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00002887 Py_DECREF(r);
2888 return -1;
2889 }
2890 *a = PyTuple_GET_ITEM(r, 0);
2891 Py_INCREF(*a);
2892 *b = PyTuple_GET_ITEM(r, 1);
2893 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002894 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00002895 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002896 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002897 }
2898 if (other->ob_type->tp_as_number != NULL &&
2899 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
2900 PyObject *r;
2901 r = call_maybe(
2902 other, "__coerce__", &coerce_str, "(O)", self);
2903 if (r == NULL)
2904 return -1;
2905 if (r == Py_NotImplemented) {
2906 Py_DECREF(r);
2907 return 1;
2908 }
2909 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
2910 PyErr_SetString(PyExc_TypeError,
2911 "__coerce__ didn't return a 2-tuple");
2912 Py_DECREF(r);
2913 return -1;
2914 }
2915 *a = PyTuple_GET_ITEM(r, 1);
2916 Py_INCREF(*a);
2917 *b = PyTuple_GET_ITEM(r, 0);
2918 Py_INCREF(*b);
2919 Py_DECREF(r);
2920 return 0;
2921 }
2922 return 1;
2923}
2924
Guido van Rossumdc91b992001-08-08 22:26:22 +00002925SLOT0(slot_nb_int, "__int__")
2926SLOT0(slot_nb_long, "__long__")
2927SLOT0(slot_nb_float, "__float__")
2928SLOT0(slot_nb_oct, "__oct__")
2929SLOT0(slot_nb_hex, "__hex__")
2930SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2931SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2932SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2933SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2934SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2935SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2936SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2937SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2938SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2939SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2940SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2941SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2942 "__floordiv__", "__rfloordiv__")
2943SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2944SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2945SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946
2947static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00002948half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002949{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002950 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002951 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002952 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002953
Guido van Rossum60718732001-08-28 17:47:51 +00002954 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002955 if (func == NULL) {
2956 PyErr_Clear();
2957 }
2958 else {
2959 args = Py_BuildValue("(O)", other);
2960 if (args == NULL)
2961 res = NULL;
2962 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002963 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002964 Py_DECREF(args);
2965 }
2966 if (res != Py_NotImplemented) {
2967 if (res == NULL)
2968 return -2;
2969 c = PyInt_AsLong(res);
2970 Py_DECREF(res);
2971 if (c == -1 && PyErr_Occurred())
2972 return -2;
2973 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
2974 }
2975 Py_DECREF(res);
2976 }
2977 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002978}
2979
Guido van Rossumab3b0342001-09-18 20:38:53 +00002980/* This slot is published for the benefit of try_3way_compare in object.c */
2981int
2982_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00002983{
2984 int c;
2985
Guido van Rossumab3b0342001-09-18 20:38:53 +00002986 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002987 c = half_compare(self, other);
2988 if (c <= 1)
2989 return c;
2990 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00002991 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002992 c = half_compare(other, self);
2993 if (c < -1)
2994 return -2;
2995 if (c <= 1)
2996 return -c;
2997 }
2998 return (void *)self < (void *)other ? -1 :
2999 (void *)self > (void *)other ? 1 : 0;
3000}
3001
3002static PyObject *
3003slot_tp_repr(PyObject *self)
3004{
3005 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003006 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003007
Guido van Rossum60718732001-08-28 17:47:51 +00003008 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003009 if (func != NULL) {
3010 res = PyEval_CallObject(func, NULL);
3011 Py_DECREF(func);
3012 return res;
3013 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003014 PyErr_Clear();
3015 return PyString_FromFormat("<%s object at %p>",
3016 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003017}
3018
3019static PyObject *
3020slot_tp_str(PyObject *self)
3021{
3022 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003023 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003024
Guido van Rossum60718732001-08-28 17:47:51 +00003025 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003026 if (func != NULL) {
3027 res = PyEval_CallObject(func, NULL);
3028 Py_DECREF(func);
3029 return res;
3030 }
3031 else {
3032 PyErr_Clear();
3033 return slot_tp_repr(self);
3034 }
3035}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003036
3037static long
3038slot_tp_hash(PyObject *self)
3039{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003040 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003041 static PyObject *hash_str, *eq_str, *cmp_str;
3042
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043 long h;
3044
Guido van Rossum60718732001-08-28 17:47:51 +00003045 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003046
3047 if (func != NULL) {
3048 res = PyEval_CallObject(func, NULL);
3049 Py_DECREF(func);
3050 if (res == NULL)
3051 return -1;
3052 h = PyInt_AsLong(res);
3053 }
3054 else {
3055 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003056 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003057 if (func == NULL) {
3058 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003059 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003060 }
3061 if (func != NULL) {
3062 Py_DECREF(func);
3063 PyErr_SetString(PyExc_TypeError, "unhashable type");
3064 return -1;
3065 }
3066 PyErr_Clear();
3067 h = _Py_HashPointer((void *)self);
3068 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069 if (h == -1 && !PyErr_Occurred())
3070 h = -2;
3071 return h;
3072}
3073
3074static PyObject *
3075slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3076{
Guido van Rossum60718732001-08-28 17:47:51 +00003077 static PyObject *call_str;
3078 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003079 PyObject *res;
3080
3081 if (meth == NULL)
3082 return NULL;
3083 res = PyObject_Call(meth, args, kwds);
3084 Py_DECREF(meth);
3085 return res;
3086}
3087
Guido van Rossum14a6f832001-10-17 13:59:09 +00003088/* There are two slot dispatch functions for tp_getattro.
3089
3090 - slot_tp_getattro() is used when __getattribute__ is overridden
3091 but no __getattr__ hook is present;
3092
3093 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3094
3095 The code in update_slot() and fixup_slot_dispatchers() always installs
3096 slot_tp_getattr_hook(); this detects the absence of __getattr__ and then
3097 installs the simpler slot if necessary. */
3098
Tim Peters6d6c1a32001-08-02 04:15:00 +00003099static PyObject *
3100slot_tp_getattro(PyObject *self, PyObject *name)
3101{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003102 static PyObject *getattribute_str = NULL;
3103 return call_method(self, "__getattribute__", &getattribute_str,
3104 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105}
3106
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003107static PyObject *
3108slot_tp_getattr_hook(PyObject *self, PyObject *name)
3109{
3110 PyTypeObject *tp = self->ob_type;
3111 PyObject *getattr, *getattribute, *res;
3112 static PyObject *getattribute_str = NULL;
3113 static PyObject *getattr_str = NULL;
3114
3115 if (getattr_str == NULL) {
3116 getattr_str = PyString_InternFromString("__getattr__");
3117 if (getattr_str == NULL)
3118 return NULL;
3119 }
3120 if (getattribute_str == NULL) {
3121 getattribute_str =
3122 PyString_InternFromString("__getattribute__");
3123 if (getattribute_str == NULL)
3124 return NULL;
3125 }
3126 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003127 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003128 /* No __getattr__ hook: use a simpler dispatcher */
3129 tp->tp_getattro = slot_tp_getattro;
3130 return slot_tp_getattro(self, name);
3131 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003132 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003133 if (getattribute == NULL ||
3134 (getattribute->ob_type == &PyWrapperDescr_Type &&
3135 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3136 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003137 res = PyObject_GenericGetAttr(self, name);
3138 else
3139 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003140 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003141 PyErr_Clear();
3142 res = PyObject_CallFunction(getattr, "OO", self, name);
3143 }
3144 return res;
3145}
3146
Tim Peters6d6c1a32001-08-02 04:15:00 +00003147static int
3148slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3149{
3150 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003151 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152
3153 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003154 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003155 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003156 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003157 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003158 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003159 if (res == NULL)
3160 return -1;
3161 Py_DECREF(res);
3162 return 0;
3163}
3164
3165/* Map rich comparison operators to their __xx__ namesakes */
3166static char *name_op[] = {
3167 "__lt__",
3168 "__le__",
3169 "__eq__",
3170 "__ne__",
3171 "__gt__",
3172 "__ge__",
3173};
3174
3175static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003176half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003177{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003178 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003179 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003180
Guido van Rossum60718732001-08-28 17:47:51 +00003181 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003182 if (func == NULL) {
3183 PyErr_Clear();
3184 Py_INCREF(Py_NotImplemented);
3185 return Py_NotImplemented;
3186 }
3187 args = Py_BuildValue("(O)", other);
3188 if (args == NULL)
3189 res = NULL;
3190 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003191 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003192 Py_DECREF(args);
3193 }
3194 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003195 return res;
3196}
3197
Guido van Rossumb8f63662001-08-15 23:57:02 +00003198/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3199static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3200
3201static PyObject *
3202slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3203{
3204 PyObject *res;
3205
3206 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3207 res = half_richcompare(self, other, op);
3208 if (res != Py_NotImplemented)
3209 return res;
3210 Py_DECREF(res);
3211 }
3212 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3213 res = half_richcompare(other, self, swapped_op[op]);
3214 if (res != Py_NotImplemented) {
3215 return res;
3216 }
3217 Py_DECREF(res);
3218 }
3219 Py_INCREF(Py_NotImplemented);
3220 return Py_NotImplemented;
3221}
3222
3223static PyObject *
3224slot_tp_iter(PyObject *self)
3225{
3226 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003227 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003228
Guido van Rossum60718732001-08-28 17:47:51 +00003229 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003230 if (func != NULL) {
3231 res = PyObject_CallObject(func, NULL);
3232 Py_DECREF(func);
3233 return res;
3234 }
3235 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003236 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003237 if (func == NULL) {
Tim Peters8b13b3e2001-09-30 05:58:42 +00003238 PyErr_SetString(PyExc_TypeError, "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003239 return NULL;
3240 }
3241 Py_DECREF(func);
3242 return PySeqIter_New(self);
3243}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003244
3245static PyObject *
3246slot_tp_iternext(PyObject *self)
3247{
Guido van Rossum2730b132001-08-28 18:22:14 +00003248 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003249 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003250}
3251
Guido van Rossum1a493502001-08-17 16:47:50 +00003252static PyObject *
3253slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3254{
3255 PyTypeObject *tp = self->ob_type;
3256 PyObject *get;
3257 static PyObject *get_str = NULL;
3258
3259 if (get_str == NULL) {
3260 get_str = PyString_InternFromString("__get__");
3261 if (get_str == NULL)
3262 return NULL;
3263 }
3264 get = _PyType_Lookup(tp, get_str);
3265 if (get == NULL) {
3266 /* Avoid further slowdowns */
3267 if (tp->tp_descr_get == slot_tp_descr_get)
3268 tp->tp_descr_get = NULL;
3269 Py_INCREF(self);
3270 return self;
3271 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003272 if (obj == NULL)
3273 obj = Py_None;
3274 if (type == NULL)
3275 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003276 return PyObject_CallFunction(get, "OOO", self, obj, type);
3277}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003278
3279static int
3280slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3281{
Guido van Rossum2c252392001-08-24 10:13:31 +00003282 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003283 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003284
3285 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003286 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003287 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003288 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003289 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003290 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003291 if (res == NULL)
3292 return -1;
3293 Py_DECREF(res);
3294 return 0;
3295}
3296
3297static int
3298slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3299{
Guido van Rossum60718732001-08-28 17:47:51 +00003300 static PyObject *init_str;
3301 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003302 PyObject *res;
3303
3304 if (meth == NULL)
3305 return -1;
3306 res = PyObject_Call(meth, args, kwds);
3307 Py_DECREF(meth);
3308 if (res == NULL)
3309 return -1;
3310 Py_DECREF(res);
3311 return 0;
3312}
3313
3314static PyObject *
3315slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3316{
3317 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3318 PyObject *newargs, *x;
3319 int i, n;
3320
3321 if (func == NULL)
3322 return NULL;
3323 assert(PyTuple_Check(args));
3324 n = PyTuple_GET_SIZE(args);
3325 newargs = PyTuple_New(n+1);
3326 if (newargs == NULL)
3327 return NULL;
3328 Py_INCREF(type);
3329 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3330 for (i = 0; i < n; i++) {
3331 x = PyTuple_GET_ITEM(args, i);
3332 Py_INCREF(x);
3333 PyTuple_SET_ITEM(newargs, i+1, x);
3334 }
3335 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003336 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003337 Py_DECREF(func);
3338 return x;
3339}
3340
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003341
3342/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3343 functions. The offsets here are relative to the 'etype' structure, which
3344 incorporates the additional structures used for numbers, sequences and
3345 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3346 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3347 slots (e.g. __str__ affects tp_str as well as tp_repr). */
3348
Guido van Rossum6d204072001-10-21 00:44:31 +00003349typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003350
3351#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003352#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003353#undef ETSLOT
3354#undef SQSLOT
3355#undef MPSLOT
3356#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003357#undef UNSLOT
3358#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003359#undef BINSLOT
3360#undef RBINSLOT
3361
Guido van Rossum6d204072001-10-21 00:44:31 +00003362#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3363 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003364#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3365 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3366 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003367#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3368 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3369#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3370 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3371#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3372 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3373#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3374 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3375#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3376 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3377 "x." NAME "() <==> " DOC)
3378#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3379 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3380 "x." NAME "(y) <==> x" DOC "y")
3381#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3382 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3383 "x." NAME "(y) <==> x" DOC "y")
3384#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3385 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3386 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003387
3388static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003389 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3390 "x.__len__() <==> len(x)"),
3391 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3392 "x.__add__(y) <==> x+y"),
3393 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3394 "x.__mul__(n) <==> x*n"),
3395 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3396 "x.__rmul__(n) <==> n*x"),
3397 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3398 "x.__getitem__(y) <==> x[y]"),
3399 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3400 "x.__getslice__(i, j) <==> x[i:j]"),
3401 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3402 "x.__setitem__(i, y) <==> x[i]=y"),
3403 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3404 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003405 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003406 wrap_intintobjargproc,
3407 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3408 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3409 "x.__delslice__(i, j) <==> del x[i:j]"),
3410 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3411 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003412 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003413 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003414 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003415 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003416
Guido van Rossum6d204072001-10-21 00:44:31 +00003417 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3418 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003419 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003420 wrap_binaryfunc,
3421 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003422 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003423 wrap_objobjargproc,
3424 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003425 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003426 wrap_delitem,
3427 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003428
Guido van Rossum6d204072001-10-21 00:44:31 +00003429 BINSLOT("__add__", nb_add, slot_nb_add,
3430 "+"),
3431 RBINSLOT("__radd__", nb_add, slot_nb_add,
3432 "+"),
3433 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3434 "-"),
3435 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3436 "-"),
3437 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3438 "*"),
3439 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3440 "*"),
3441 BINSLOT("__div__", nb_divide, slot_nb_divide,
3442 "/"),
3443 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3444 "/"),
3445 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3446 "%"),
3447 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3448 "%"),
3449 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3450 "divmod(x, y)"),
3451 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3452 "divmod(y, x)"),
3453 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3454 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3455 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3456 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3457 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3458 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3459 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3460 "abs(x)"),
3461 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_unaryfunc,
3462 "x != 0"),
3463 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3464 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3465 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3466 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3467 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3468 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3469 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3470 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3471 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3472 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3473 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3474 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3475 "x.__coerce__(y) <==> coerce(x, y)"),
3476 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3477 "int(x)"),
3478 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3479 "long(x)"),
3480 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3481 "float(x)"),
3482 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3483 "oct(x)"),
3484 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3485 "hex(x)"),
3486 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3487 wrap_binaryfunc, "+"),
3488 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3489 wrap_binaryfunc, "-"),
3490 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3491 wrap_binaryfunc, "*"),
3492 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3493 wrap_binaryfunc, "/"),
3494 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3495 wrap_binaryfunc, "%"),
3496 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3497 wrap_ternaryfunc, "**"),
3498 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3499 wrap_binaryfunc, "<<"),
3500 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3501 wrap_binaryfunc, ">>"),
3502 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3503 wrap_binaryfunc, "&"),
3504 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3505 wrap_binaryfunc, "^"),
3506 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3507 wrap_binaryfunc, "|"),
3508 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3509 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3510 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3511 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3512 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3513 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3514 IBSLOT("__itruediv__", nb_inplace_true_divide,
3515 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003516
Guido van Rossum6d204072001-10-21 00:44:31 +00003517 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3518 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003519 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003520 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3521 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003522 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003523 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3524 "x.__cmp__(y) <==> cmp(x,y)"),
3525 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3526 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003527 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3528 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003529 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003530 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3531 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3532 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3533 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3534 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3535 "x.__setattr__('name', value) <==> x.name = value"),
3536 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3537 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3538 "x.__delattr__('name') <==> del x.name"),
3539 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3540 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3541 "x.__lt__(y) <==> x<y"),
3542 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3543 "x.__le__(y) <==> x<=y"),
3544 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3545 "x.__eq__(y) <==> x==y"),
3546 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3547 "x.__ne__(y) <==> x!=y"),
3548 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3549 "x.__gt__(y) <==> x>y"),
3550 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3551 "x.__ge__(y) <==> x>=y"),
3552 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3553 "x.__iter__() <==> iter(x)"),
3554 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3555 "x.next() -> the next value, or raise StopIteration"),
3556 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3557 "descr.__get__(obj[, type]) -> value"),
3558 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3559 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003560 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003561 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003562 "see x.__class__.__doc__ for signature",
3563 PyWrapperFlag_KEYWORDS),
3564 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003565 {NULL}
3566};
3567
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003568static void **
3569slotptr(PyTypeObject *type, int offset)
3570{
3571 char *ptr;
3572
3573 assert(offset >= 0);
3574 assert(offset < offsetof(etype, as_buffer));
3575 if (offset >= offsetof(etype, as_mapping)) {
3576 ptr = (void *)type->tp_as_mapping;
3577 offset -= offsetof(etype, as_mapping);
3578 }
3579 else if (offset >= offsetof(etype, as_sequence)) {
3580 ptr = (void *)type->tp_as_sequence;
3581 offset -= offsetof(etype, as_sequence);
3582 }
3583 else if (offset >= offsetof(etype, as_number)) {
3584 ptr = (void *)type->tp_as_number;
3585 offset -= offsetof(etype, as_number);
3586 }
3587 else {
3588 ptr = (void *)type;
3589 }
3590 if (ptr != NULL)
3591 ptr += offset;
3592 return (void **)ptr;
3593}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003594
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003595staticforward int recurse_down_subclasses(PyTypeObject *type,
3596 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003597
3598static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003599update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003600{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003601 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003602
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003603 for (pp = pp0; *pp; pp++) {
3604 slotdef *p = *pp;
3605 PyObject *descr;
3606 PyWrapperDescrObject *d;
3607 void *generic = NULL, *specific = NULL;
3608 int use_generic = 0;
3609 int offset = p->offset;
3610 void **ptr = slotptr(type, offset);
3611 if (ptr == NULL)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003612 continue;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003613 do {
3614 descr = _PyType_Lookup(type, p->name_strobj);
3615 if (descr == NULL)
3616 continue;
3617 generic = p->function;
3618 if (descr->ob_type == &PyWrapperDescr_Type) {
3619 d = (PyWrapperDescrObject *)descr;
3620 if (d->d_base->wrapper == p->wrapper &&
3621 PyType_IsSubtype(type, d->d_type)) {
3622 if (specific == NULL ||
3623 specific == d->d_wrapped)
3624 specific = d->d_wrapped;
3625 else
3626 use_generic = 1;
3627 }
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003628 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003629 else
3630 use_generic = 1;
3631 } while ((++p)->offset == offset);
3632 if (specific && !use_generic)
3633 *ptr = specific;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003634 else
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003635 *ptr = generic;
3636 }
3637 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003638}
3639
3640static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003641recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003642{
3643 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003644 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003645 int i, n;
3646
3647 subclasses = type->tp_subclasses;
3648 if (subclasses == NULL)
3649 return 0;
3650 assert(PyList_Check(subclasses));
3651 n = PyList_GET_SIZE(subclasses);
3652 for (i = 0; i < n; i++) {
3653 ref = PyList_GET_ITEM(subclasses, i);
3654 assert(PyWeakref_CheckRef(ref));
3655 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3656 if (subclass == NULL)
3657 continue;
3658 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003659 /* Avoid recursing down into unaffected classes */
3660 dict = subclass->tp_dict;
3661 if (dict != NULL && PyDict_Check(dict) &&
3662 PyDict_GetItem(dict, name) != NULL)
3663 continue;
3664 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003665 return -1;
3666 }
3667 return 0;
3668}
3669
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003670static int
3671slotdef_cmp(const void *aa, const void *bb)
3672{
3673 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3674 int c = a->offset - b->offset;
3675 if (c != 0)
3676 return c;
3677 else
3678 return a - b;
3679}
3680
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003681static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003682init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003683{
3684 slotdef *p;
3685 static int initialized = 0;
3686
3687 if (initialized)
3688 return;
3689 for (p = slotdefs; p->name; p++) {
3690 p->name_strobj = PyString_InternFromString(p->name);
3691 if (!p->name_strobj)
3692 Py_FatalError("XXX ouch");
3693 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003694 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3695 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003696 initialized = 1;
3697}
3698
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003699static int
3700update_slot(PyTypeObject *type, PyObject *name)
3701{
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003702 slotdef *ptrs[10];
3703 slotdef *p;
3704 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003705 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003706
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003707 init_slotdefs();
3708 pp = ptrs;
3709 for (p = slotdefs; p->name; p++) {
3710 /* XXX assume name is interned! */
3711 if (p->name_strobj == name)
3712 *pp++ = p;
3713 }
3714 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003715 for (pp = ptrs; *pp; pp++) {
3716 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003717 offset = p->offset;
3718 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003719 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003720 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003721 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003722 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003723}
3724
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003726fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003727{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003728 slotdef *p;
3729 PyObject *mro, *descr;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003730 PyWrapperDescrObject *d;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003731 int i, n, offset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003732 void **ptr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003733 void *generic, *specific;
3734 int use_generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003735
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003736 init_slotdefs();
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003737 mro = type->tp_mro;
3738 assert(PyTuple_Check(mro));
3739 n = PyTuple_GET_SIZE(mro);
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003740 for (p = slotdefs; p->name; ) {
3741 offset = p->offset;
3742 ptr = slotptr(type, offset);
3743 if (!ptr) {
3744 do {
3745 ++p;
3746 } while (p->offset == offset);
3747 continue;
3748 }
3749 generic = specific = NULL;
3750 use_generic = 0;
3751 do {
3752 descr = NULL;
3753 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003754 PyObject *b = PyTuple_GET_ITEM(mro, i);
3755 PyObject *dict = NULL;
3756 if (PyType_Check(b))
3757 dict = ((PyTypeObject *)b)->tp_dict;
3758 else if (PyClass_Check(b))
3759 dict = ((PyClassObject *)b)->cl_dict;
3760 if (dict != NULL) {
3761 descr = PyDict_GetItem(
3762 dict, p->name_strobj);
3763 if (descr != NULL)
3764 break;
3765 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003766 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003767 if (descr == NULL)
3768 continue;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003769 generic = p->function;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003770 if (descr->ob_type == &PyWrapperDescr_Type) {
3771 d = (PyWrapperDescrObject *)descr;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003772 if (d->d_base->wrapper == p->wrapper &&
Guido van Rossumcaf59042001-10-17 07:15:43 +00003773 PyType_IsSubtype(type, d->d_type))
3774 {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003775 if (specific == NULL ||
Guido van Rossumcaf59042001-10-17 07:15:43 +00003776 specific == d->d_wrapped)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003777 specific = d->d_wrapped;
3778 else
3779 use_generic = 1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003780 }
3781 }
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003782 else
3783 use_generic = 1;
3784 } while ((++p)->offset == offset);
3785 if (specific && !use_generic)
3786 *ptr = specific;
3787 else
3788 *ptr = generic;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003789 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003790}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003791
Guido van Rossum6d204072001-10-21 00:44:31 +00003792/* This function is called by PyType_Ready() to populate the type's
3793 dictionary with method descriptors for function slots. For each
3794 function slot (like tp_repr) that's defined in the type, one or
3795 more corresponding descriptors are added in the type's tp_dict
3796 dictionary under the appropriate name (like __repr__). Some
3797 function slots cause more than one descriptor to be added (for
3798 example, the nb_add slot adds both __add__ and __radd__
3799 descriptors) and some function slots compete for the same
3800 descriptor (for example both sq_item and mp_subscript generate a
3801 __getitem__ descriptor). This only adds new descriptors and
3802 doesn't overwrite entries in tp_dict that were previously
3803 defined. The descriptors contain a reference to the C function
3804 they must call, so that it's safe if they are copied into a
3805 subtype's __dict__ and the subtype has a different C function in
3806 its slot -- calling the method defined by the descriptor will call
3807 the C function that was used to create it, rather than the C
3808 function present in the slot when it is called. (This is important
3809 because a subtype may have a C function in the slot that calls the
3810 method from the dictionary, and we want to avoid infinite recursion
3811 here.) */
3812
3813static int
3814add_operators(PyTypeObject *type)
3815{
3816 PyObject *dict = type->tp_dict;
3817 slotdef *p;
3818 PyObject *descr;
3819 void **ptr;
3820
3821 init_slotdefs();
3822 for (p = slotdefs; p->name; p++) {
3823 if (p->wrapper == NULL)
3824 continue;
3825 ptr = slotptr(type, p->offset);
3826 if (!ptr || !*ptr)
3827 continue;
3828 if (PyDict_GetItem(dict, p->name_strobj))
3829 continue;
3830 descr = PyDescr_NewWrapper(type, p, *ptr);
3831 if (descr == NULL)
3832 return -1;
3833 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
3834 return -1;
3835 Py_DECREF(descr);
3836 }
3837 if (type->tp_new != NULL) {
3838 if (add_tp_new_wrapper(type) < 0)
3839 return -1;
3840 }
3841 return 0;
3842}
3843
Guido van Rossum705f0f52001-08-24 16:47:00 +00003844
3845/* Cooperative 'super' */
3846
3847typedef struct {
3848 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00003849 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003850 PyObject *obj;
3851} superobject;
3852
Guido van Rossum6f799372001-09-20 20:46:19 +00003853static PyMemberDef super_members[] = {
3854 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
3855 "the class invoking super()"},
3856 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
3857 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003858 {0}
3859};
3860
Guido van Rossum705f0f52001-08-24 16:47:00 +00003861static void
3862super_dealloc(PyObject *self)
3863{
3864 superobject *su = (superobject *)self;
3865
Guido van Rossum048eb752001-10-02 21:24:57 +00003866 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00003867 Py_XDECREF(su->obj);
3868 Py_XDECREF(su->type);
3869 self->ob_type->tp_free(self);
3870}
3871
3872static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003873super_repr(PyObject *self)
3874{
3875 superobject *su = (superobject *)self;
3876
3877 if (su->obj)
3878 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003879 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003880 su->type ? su->type->tp_name : "NULL",
3881 su->obj->ob_type->tp_name);
3882 else
3883 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00003884 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003885 su->type ? su->type->tp_name : "NULL");
3886}
3887
3888static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00003889super_getattro(PyObject *self, PyObject *name)
3890{
3891 superobject *su = (superobject *)self;
3892
3893 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00003894 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum705f0f52001-08-24 16:47:00 +00003895 descrgetfunc f;
3896 int i, n;
3897
Guido van Rossume705ef12001-08-29 15:47:06 +00003898 mro = su->obj->ob_type->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003899 if (mro == NULL)
3900 n = 0;
3901 else {
3902 assert(PyTuple_Check(mro));
3903 n = PyTuple_GET_SIZE(mro);
3904 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003905 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00003906 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00003907 break;
3908 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003909 if (i >= n && PyType_Check(su->obj)) {
3910 mro = ((PyTypeObject *)(su->obj))->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00003911 if (mro == NULL)
3912 n = 0;
3913 else {
3914 assert(PyTuple_Check(mro));
3915 n = PyTuple_GET_SIZE(mro);
3916 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003917 for (i = 0; i < n; i++) {
3918 if ((PyObject *)(su->type) ==
3919 PyTuple_GET_ITEM(mro, i))
3920 break;
3921 }
Guido van Rossume705ef12001-08-29 15:47:06 +00003922 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003923 i++;
3924 res = NULL;
3925 for (; i < n; i++) {
3926 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00003927 if (PyType_Check(tmp))
3928 dict = ((PyTypeObject *)tmp)->tp_dict;
3929 else if (PyClass_Check(tmp))
3930 dict = ((PyClassObject *)tmp)->cl_dict;
3931 else
3932 continue;
3933 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00003934 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00003935 Py_INCREF(res);
3936 f = res->ob_type->tp_descr_get;
3937 if (f != NULL) {
3938 tmp = f(res, su->obj, res);
3939 Py_DECREF(res);
3940 res = tmp;
3941 }
3942 return res;
3943 }
3944 }
3945 }
3946 return PyObject_GenericGetAttr(self, name);
3947}
3948
Guido van Rossum5b443c62001-12-03 15:38:28 +00003949static int
3950supercheck(PyTypeObject *type, PyObject *obj)
3951{
3952 if (!PyType_IsSubtype(obj->ob_type, type) &&
3953 !(PyType_Check(obj) &&
3954 PyType_IsSubtype((PyTypeObject *)obj, type))) {
3955 PyErr_SetString(PyExc_TypeError,
3956 "super(type, obj): "
3957 "obj must be an instance or subtype of type");
3958 return -1;
3959 }
3960 else
3961 return 0;
3962}
3963
Guido van Rossum705f0f52001-08-24 16:47:00 +00003964static PyObject *
3965super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3966{
3967 superobject *su = (superobject *)self;
3968 superobject *new;
3969
3970 if (obj == NULL || obj == Py_None || su->obj != NULL) {
3971 /* Not binding to an object, or already bound */
3972 Py_INCREF(self);
3973 return self;
3974 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00003975 if (su->ob_type != &PySuper_Type)
3976 /* If su is an instance of a subclass of super,
3977 call its type */
3978 return PyObject_CallFunction((PyObject *)su->ob_type,
3979 "OO", su->type, obj);
3980 else {
3981 /* Inline the common case */
3982 if (supercheck(su->type, obj) < 0)
3983 return NULL;
3984 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
3985 NULL, NULL);
3986 if (new == NULL)
3987 return NULL;
3988 Py_INCREF(su->type);
3989 Py_INCREF(obj);
3990 new->type = su->type;
3991 new->obj = obj;
3992 return (PyObject *)new;
3993 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00003994}
3995
3996static int
3997super_init(PyObject *self, PyObject *args, PyObject *kwds)
3998{
3999 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004000 PyTypeObject *type;
4001 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004002
4003 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4004 return -1;
4005 if (obj == Py_None)
4006 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004007 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004008 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004009 Py_INCREF(type);
4010 Py_XINCREF(obj);
4011 su->type = type;
4012 su->obj = obj;
4013 return 0;
4014}
4015
4016static char super_doc[] =
4017"super(type) -> unbound super object\n"
4018"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004019"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004020"Typical use to call a cooperative superclass method:\n"
4021"class C(B):\n"
4022" def meth(self, arg):\n"
4023" super(C, self).meth(arg)";
4024
Guido van Rossum048eb752001-10-02 21:24:57 +00004025static int
4026super_traverse(PyObject *self, visitproc visit, void *arg)
4027{
4028 superobject *su = (superobject *)self;
4029 int err;
4030
4031#define VISIT(SLOT) \
4032 if (SLOT) { \
4033 err = visit((PyObject *)(SLOT), arg); \
4034 if (err) \
4035 return err; \
4036 }
4037
4038 VISIT(su->obj);
4039 VISIT(su->type);
4040
4041#undef VISIT
4042
4043 return 0;
4044}
4045
Guido van Rossum705f0f52001-08-24 16:47:00 +00004046PyTypeObject PySuper_Type = {
4047 PyObject_HEAD_INIT(&PyType_Type)
4048 0, /* ob_size */
4049 "super", /* tp_name */
4050 sizeof(superobject), /* tp_basicsize */
4051 0, /* tp_itemsize */
4052 /* methods */
4053 super_dealloc, /* tp_dealloc */
4054 0, /* tp_print */
4055 0, /* tp_getattr */
4056 0, /* tp_setattr */
4057 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004058 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004059 0, /* tp_as_number */
4060 0, /* tp_as_sequence */
4061 0, /* tp_as_mapping */
4062 0, /* tp_hash */
4063 0, /* tp_call */
4064 0, /* tp_str */
4065 super_getattro, /* tp_getattro */
4066 0, /* tp_setattro */
4067 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004068 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4069 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004070 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004071 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004072 0, /* tp_clear */
4073 0, /* tp_richcompare */
4074 0, /* tp_weaklistoffset */
4075 0, /* tp_iter */
4076 0, /* tp_iternext */
4077 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004078 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004079 0, /* tp_getset */
4080 0, /* tp_base */
4081 0, /* tp_dict */
4082 super_descr_get, /* tp_descr_get */
4083 0, /* tp_descr_set */
4084 0, /* tp_dictoffset */
4085 super_init, /* tp_init */
4086 PyType_GenericAlloc, /* tp_alloc */
4087 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004088 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004089};