blob: 849840c8cf0a040203dbdbad8aba9617bae7c913 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum6f799372001-09-20 20:46:19 +00006static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00007 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
8 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
9 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000010 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000011 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
12 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
13 {"__dictoffset__", T_LONG,
14 offsetof(PyTypeObject, tp_dictoffset), READONLY},
15 {"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
16 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
17 {0}
18};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000019
Guido van Rossumc0b618a1997-05-02 03:12:38 +000020static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000021type_name(PyTypeObject *type, void *context)
22{
23 char *s;
24
25 s = strrchr(type->tp_name, '.');
26 if (s == NULL)
27 s = type->tp_name;
28 else
29 s++;
30 return PyString_FromString(s);
31}
32
33static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000034type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000035{
Guido van Rossumc3542212001-08-16 09:18:56 +000036 PyObject *mod;
37 char *s;
38
39 s = strrchr(type->tp_name, '.');
40 if (s != NULL)
41 return PyString_FromStringAndSize(type->tp_name,
42 (int)(s - type->tp_name));
43 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
44 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +000045 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Guido van Rossumc3542212001-08-16 09:18:56 +000046 if (mod != NULL && PyString_Check(mod)) {
47 Py_INCREF(mod);
48 return mod;
49 }
50 PyErr_SetString(PyExc_AttributeError, "__module__");
51 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000052}
53
Guido van Rossum3926a632001-09-25 16:25:58 +000054static int
55type_set_module(PyTypeObject *type, PyObject *value, void *context)
56{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +000057 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
Guido van Rossum3926a632001-09-25 16:25:58 +000058 strrchr(type->tp_name, '.')) {
59 PyErr_Format(PyExc_TypeError,
60 "can't set %s.__module__", type->tp_name);
61 return -1;
62 }
63 if (!value) {
64 PyErr_Format(PyExc_TypeError,
65 "can't delete %s.__module__", type->tp_name);
66 return -1;
67 }
68 return PyDict_SetItemString(type->tp_dict, "__module__", value);
69}
70
Tim Peters6d6c1a32001-08-02 04:15:00 +000071static PyObject *
72type_dict(PyTypeObject *type, void *context)
73{
74 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075 Py_INCREF(Py_None);
76 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +000077 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000078 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +000079}
80
Tim Peters24008312002-03-17 18:56:20 +000081static PyObject *
82type_get_doc(PyTypeObject *type, void *context)
83{
84 PyObject *result;
85 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
86 if (type->tp_doc == NULL) {
87 Py_INCREF(Py_None);
88 return Py_None;
89 }
90 return PyString_FromString(type->tp_doc);
91 }
92 result = PyDict_GetItemString(type->tp_dict, "__doc__");
93 Py_INCREF(result);
94 return result;
95}
96
Neil Schemenauerf23473f2001-10-21 22:28:58 +000097static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +000098 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +000099 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000101 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000102 {0}
103};
104
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000105static int
106type_compare(PyObject *v, PyObject *w)
107{
108 /* This is called with type objects only. So we
109 can just compare the addresses. */
110 Py_uintptr_t vv = (Py_uintptr_t)v;
111 Py_uintptr_t ww = (Py_uintptr_t)w;
112 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
113}
114
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000116type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000118 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000119 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000120
121 mod = type_module(type, NULL);
122 if (mod == NULL)
123 PyErr_Clear();
124 else if (!PyString_Check(mod)) {
125 Py_DECREF(mod);
126 mod = NULL;
127 }
128 name = type_name(type, NULL);
129 if (name == NULL)
130 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000131
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000132 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
133 kind = "class";
134 else
135 kind = "type";
136
Barry Warsaw7ce36942001-08-24 18:34:26 +0000137 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000138 rtn = PyString_FromFormat("<%s '%s.%s'>",
139 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000140 PyString_AS_STRING(mod),
141 PyString_AS_STRING(name));
142 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000143 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000144 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000145
Guido van Rossumc3542212001-08-16 09:18:56 +0000146 Py_XDECREF(mod);
147 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000148 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149}
150
Tim Peters6d6c1a32001-08-02 04:15:00 +0000151static PyObject *
152type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
153{
154 PyObject *obj;
155
156 if (type->tp_new == NULL) {
157 PyErr_Format(PyExc_TypeError,
158 "cannot create '%.100s' instances",
159 type->tp_name);
160 return NULL;
161 }
162
Tim Peters3f996e72001-09-13 19:18:27 +0000163 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000164 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000165 /* Ugly exception: when the call was type(something),
166 don't call tp_init on the result. */
167 if (type == &PyType_Type &&
168 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
169 (kwds == NULL ||
170 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
171 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000172 type = obj->ob_type;
173 if (type->tp_init != NULL &&
174 type->tp_init(obj, args, kwds) < 0) {
175 Py_DECREF(obj);
176 obj = NULL;
177 }
178 }
179 return obj;
180}
181
182PyObject *
183PyType_GenericAlloc(PyTypeObject *type, int nitems)
184{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000185 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000186 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000187
188 if (PyType_IS_GC(type))
Tim Peters6d483d32001-10-06 21:27:34 +0000189 obj = _PyObject_GC_Malloc(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000190 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000191 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000192
Neil Schemenauerc806c882001-08-29 23:54:54 +0000193 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000194 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000195
Neil Schemenauerc806c882001-08-29 23:54:54 +0000196 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000197
Tim Peters6d6c1a32001-08-02 04:15:00 +0000198 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
199 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000200
Tim Peters6d6c1a32001-08-02 04:15:00 +0000201 if (type->tp_itemsize == 0)
202 PyObject_INIT(obj, type);
203 else
204 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000205
Tim Peters6d6c1a32001-08-02 04:15:00 +0000206 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000207 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000208 return obj;
209}
210
211PyObject *
212PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
213{
214 return type->tp_alloc(type, 0);
215}
216
Guido van Rossum9475a232001-10-05 20:51:39 +0000217/* Helpers for subtyping */
218
219static int
220subtype_traverse(PyObject *self, visitproc visit, void *arg)
221{
222 PyTypeObject *type, *base;
223 traverseproc f;
224 int err;
225
226 /* Find the nearest base with a different tp_traverse */
227 type = self->ob_type;
228 base = type->tp_base;
229 while ((f = base->tp_traverse) == subtype_traverse) {
230 base = base->tp_base;
231 assert(base);
232 }
233
234 if (type->tp_dictoffset != base->tp_dictoffset) {
235 PyObject **dictptr = _PyObject_GetDictPtr(self);
236 if (dictptr && *dictptr) {
237 err = visit(*dictptr, arg);
238 if (err)
239 return err;
240 }
241 }
242
243 if (f)
244 return f(self, visit, arg);
245 return 0;
246}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000247
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000248staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
249
250static int
251call_finalizer(PyObject *self)
252{
253 static PyObject *del_str = NULL;
254 PyObject *del, *res;
255 PyObject *error_type, *error_value, *error_traceback;
256
257 /* Temporarily resurrect the object. */
258#ifdef Py_TRACE_REFS
259#ifndef Py_REF_DEBUG
260# error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
261#endif
262 /* much too complicated if Py_TRACE_REFS defined */
263 _Py_NewReference((PyObject *)self);
264#ifdef COUNT_ALLOCS
265 /* compensate for boost in _Py_NewReference; note that
266 * _Py_RefTotal was also boosted; we'll knock that down later.
267 */
268 self->ob_type->tp_allocs--;
269#endif
270#else /* !Py_TRACE_REFS */
271 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
272 Py_INCREF(self);
273#endif /* !Py_TRACE_REFS */
274
275 /* Save the current exception, if any. */
276 PyErr_Fetch(&error_type, &error_value, &error_traceback);
277
278 /* Execute __del__ method, if any. */
279 del = lookup_maybe(self, "__del__", &del_str);
280 if (del != NULL) {
281 res = PyEval_CallObject(del, NULL);
282 if (res == NULL)
283 PyErr_WriteUnraisable(del);
284 else
285 Py_DECREF(res);
286 Py_DECREF(del);
287 }
288
289 /* Restore the saved exception. */
290 PyErr_Restore(error_type, error_value, error_traceback);
291
292 /* Undo the temporary resurrection; can't use DECREF here, it would
293 * cause a recursive call.
294 */
295#ifdef Py_REF_DEBUG
296 /* _Py_RefTotal was boosted either by _Py_NewReference or
297 * Py_INCREF above.
298 */
299 _Py_RefTotal--;
300#endif
301 if (--self->ob_refcnt > 0) {
302#ifdef COUNT_ALLOCS
303 self->ob_type->tp_frees--;
304#endif
305 _PyObject_GC_TRACK(self);
306 return -1; /* __del__ added a reference; don't delete now */
307 }
308#ifdef Py_TRACE_REFS
309 _Py_ForgetReference((PyObject *)self);
310#ifdef COUNT_ALLOCS
311 /* compensate for increment in _Py_ForgetReference */
312 self->ob_type->tp_frees--;
313#endif
314#endif
315
316 return 0;
317}
318
Tim Peters6d6c1a32001-08-02 04:15:00 +0000319static void
320subtype_dealloc(PyObject *self)
321{
Guido van Rossum14227b42001-12-06 02:35:58 +0000322 PyTypeObject *type, *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000323 destructor f;
324
325 /* This exists so we can DECREF self->ob_type */
326
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000327 if (call_finalizer(self) < 0)
328 return;
329
Tim Peters6d6c1a32001-08-02 04:15:00 +0000330 /* Find the nearest base with a different tp_dealloc */
331 type = self->ob_type;
Guido van Rossum14227b42001-12-06 02:35:58 +0000332 base = type->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000333 while ((f = base->tp_dealloc) == subtype_dealloc) {
334 base = base->tp_base;
335 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000336 }
337
338 /* Clear __slots__ variables */
339 if (type->tp_basicsize != base->tp_basicsize &&
340 type->tp_itemsize == 0)
341 {
342 char *addr = ((char *)self);
343 char *p = addr + base->tp_basicsize;
344 char *q = addr + type->tp_basicsize;
345 for (; p < q; p += sizeof(PyObject *)) {
346 PyObject **pp;
347 if (p == addr + type->tp_dictoffset ||
348 p == addr + type->tp_weaklistoffset)
349 continue;
350 pp = (PyObject **)p;
351 if (*pp != NULL) {
352 Py_DECREF(*pp);
353 *pp = NULL;
Guido van Rossum33bab012001-12-05 22:45:48 +0000354 }
355 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000356 }
357
358 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000359 if (type->tp_dictoffset && !base->tp_dictoffset) {
360 PyObject **dictptr = _PyObject_GetDictPtr(self);
361 if (dictptr != NULL) {
362 PyObject *dict = *dictptr;
363 if (dict != NULL) {
364 Py_DECREF(dict);
365 *dictptr = NULL;
366 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000367 }
368 }
369
Guido van Rossum9676b222001-08-17 20:32:36 +0000370 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000371 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000372 PyObject_ClearWeakRefs(self);
373
Tim Peters6d6c1a32001-08-02 04:15:00 +0000374 /* Finalize GC if the base doesn't do GC and we do */
375 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000376 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000377
378 /* Call the base tp_dealloc() */
379 assert(f);
380 f(self);
381
382 /* Can't reference self beyond this point */
383 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
384 Py_DECREF(type);
385 }
386}
387
Tim Peters6d6c1a32001-08-02 04:15:00 +0000388staticforward PyTypeObject *solid_base(PyTypeObject *type);
389
390typedef struct {
391 PyTypeObject type;
392 PyNumberMethods as_number;
393 PySequenceMethods as_sequence;
394 PyMappingMethods as_mapping;
395 PyBufferProcs as_buffer;
396 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000397 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000398} etype;
399
400/* type test with subclassing support */
401
402int
403PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
404{
405 PyObject *mro;
406
Guido van Rossum9478d072001-09-07 18:52:13 +0000407 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
408 return b == a || b == &PyBaseObject_Type;
409
Tim Peters6d6c1a32001-08-02 04:15:00 +0000410 mro = a->tp_mro;
411 if (mro != NULL) {
412 /* Deal with multiple inheritance without recursion
413 by walking the MRO tuple */
414 int i, n;
415 assert(PyTuple_Check(mro));
416 n = PyTuple_GET_SIZE(mro);
417 for (i = 0; i < n; i++) {
418 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
419 return 1;
420 }
421 return 0;
422 }
423 else {
424 /* a is not completely initilized yet; follow tp_base */
425 do {
426 if (a == b)
427 return 1;
428 a = a->tp_base;
429 } while (a != NULL);
430 return b == &PyBaseObject_Type;
431 }
432}
433
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000434/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000435 without looking in the instance dictionary
436 (so we can't use PyObject_GetAttr) but still binding
437 it to the instance. The arguments are the object,
438 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000439 static variable used to cache the interned Python string.
440
441 Two variants:
442
443 - lookup_maybe() returns NULL without raising an exception
444 when the _PyType_Lookup() call fails;
445
446 - lookup_method() always raises an exception upon errors.
447*/
Guido van Rossum60718732001-08-28 17:47:51 +0000448
449static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000450lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000451{
452 PyObject *res;
453
454 if (*attrobj == NULL) {
455 *attrobj = PyString_InternFromString(attrstr);
456 if (*attrobj == NULL)
457 return NULL;
458 }
459 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000460 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000461 descrgetfunc f;
462 if ((f = res->ob_type->tp_descr_get) == NULL)
463 Py_INCREF(res);
464 else
465 res = f(res, self, (PyObject *)(self->ob_type));
466 }
467 return res;
468}
469
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000470static PyObject *
471lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
472{
473 PyObject *res = lookup_maybe(self, attrstr, attrobj);
474 if (res == NULL && !PyErr_Occurred())
475 PyErr_SetObject(PyExc_AttributeError, *attrobj);
476 return res;
477}
478
Guido van Rossum2730b132001-08-28 18:22:14 +0000479/* A variation of PyObject_CallMethod that uses lookup_method()
480 instead of PyObject_GetAttrString(). This uses the same convention
481 as lookup_method to cache the interned name string object. */
482
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000483static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000484call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
485{
486 va_list va;
487 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000488 va_start(va, format);
489
Guido van Rossumda21c012001-10-03 00:50:18 +0000490 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000491 if (func == NULL) {
492 va_end(va);
493 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000494 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000495 return NULL;
496 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000497
498 if (format && *format)
499 args = Py_VaBuildValue(format, va);
500 else
501 args = PyTuple_New(0);
502
503 va_end(va);
504
505 if (args == NULL)
506 return NULL;
507
508 assert(PyTuple_Check(args));
509 retval = PyObject_Call(func, args, NULL);
510
511 Py_DECREF(args);
512 Py_DECREF(func);
513
514 return retval;
515}
516
517/* Clone of call_method() that returns NotImplemented when the lookup fails. */
518
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000519static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000520call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
521{
522 va_list va;
523 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000524 va_start(va, format);
525
Guido van Rossumda21c012001-10-03 00:50:18 +0000526 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000527 if (func == NULL) {
528 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000529 if (!PyErr_Occurred()) {
530 Py_INCREF(Py_NotImplemented);
531 return Py_NotImplemented;
532 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000533 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000534 }
535
536 if (format && *format)
537 args = Py_VaBuildValue(format, va);
538 else
539 args = PyTuple_New(0);
540
541 va_end(va);
542
Guido van Rossum717ce002001-09-14 16:58:08 +0000543 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000544 return NULL;
545
Guido van Rossum717ce002001-09-14 16:58:08 +0000546 assert(PyTuple_Check(args));
547 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000548
549 Py_DECREF(args);
550 Py_DECREF(func);
551
552 return retval;
553}
554
Tim Peters6d6c1a32001-08-02 04:15:00 +0000555/* Method resolution order algorithm from "Putting Metaclasses to Work"
556 by Forman and Danforth (Addison-Wesley 1999). */
557
558static int
559conservative_merge(PyObject *left, PyObject *right)
560{
561 int left_size;
562 int right_size;
563 int i, j, r, ok;
564 PyObject *temp, *rr;
565
566 assert(PyList_Check(left));
567 assert(PyList_Check(right));
568
569 again:
570 left_size = PyList_GET_SIZE(left);
571 right_size = PyList_GET_SIZE(right);
572 for (i = 0; i < left_size; i++) {
573 for (j = 0; j < right_size; j++) {
574 if (PyList_GET_ITEM(left, i) ==
575 PyList_GET_ITEM(right, j)) {
576 /* found a merge point */
577 temp = PyList_New(0);
578 if (temp == NULL)
579 return -1;
580 for (r = 0; r < j; r++) {
581 rr = PyList_GET_ITEM(right, r);
582 ok = PySequence_Contains(left, rr);
583 if (ok < 0) {
584 Py_DECREF(temp);
585 return -1;
586 }
587 if (!ok) {
588 ok = PyList_Append(temp, rr);
589 if (ok < 0) {
590 Py_DECREF(temp);
591 return -1;
592 }
593 }
594 }
595 ok = PyList_SetSlice(left, i, i, temp);
596 Py_DECREF(temp);
597 if (ok < 0)
598 return -1;
599 ok = PyList_SetSlice(right, 0, j+1, NULL);
600 if (ok < 0)
601 return -1;
602 goto again;
603 }
604 }
605 }
606 return PyList_SetSlice(left, left_size, left_size, right);
607}
608
609static int
610serious_order_disagreements(PyObject *left, PyObject *right)
611{
612 return 0; /* XXX later -- for now, we cheat: "don't do that" */
613}
614
Tim Petersa91e9642001-11-14 23:32:33 +0000615static int
616fill_classic_mro(PyObject *mro, PyObject *cls)
617{
618 PyObject *bases, *base;
619 int i, n;
620
621 assert(PyList_Check(mro));
622 assert(PyClass_Check(cls));
623 i = PySequence_Contains(mro, cls);
624 if (i < 0)
625 return -1;
626 if (!i) {
627 if (PyList_Append(mro, cls) < 0)
628 return -1;
629 }
630 bases = ((PyClassObject *)cls)->cl_bases;
631 assert(bases && PyTuple_Check(bases));
632 n = PyTuple_GET_SIZE(bases);
633 for (i = 0; i < n; i++) {
634 base = PyTuple_GET_ITEM(bases, i);
635 if (fill_classic_mro(mro, base) < 0)
636 return -1;
637 }
638 return 0;
639}
640
641static PyObject *
642classic_mro(PyObject *cls)
643{
644 PyObject *mro;
645
646 assert(PyClass_Check(cls));
647 mro = PyList_New(0);
648 if (mro != NULL) {
649 if (fill_classic_mro(mro, cls) == 0)
650 return mro;
651 Py_DECREF(mro);
652 }
653 return NULL;
654}
655
Tim Peters6d6c1a32001-08-02 04:15:00 +0000656static PyObject *
657mro_implementation(PyTypeObject *type)
658{
659 int i, n, ok;
660 PyObject *bases, *result;
661
662 bases = type->tp_bases;
663 n = PyTuple_GET_SIZE(bases);
664 result = Py_BuildValue("[O]", (PyObject *)type);
665 if (result == NULL)
666 return NULL;
667 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000668 PyObject *base = PyTuple_GET_ITEM(bases, i);
669 PyObject *parentMRO;
670 if (PyType_Check(base))
671 parentMRO = PySequence_List(
672 ((PyTypeObject*)base)->tp_mro);
673 else
674 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675 if (parentMRO == NULL) {
676 Py_DECREF(result);
677 return NULL;
678 }
679 if (serious_order_disagreements(result, parentMRO)) {
680 Py_DECREF(result);
681 return NULL;
682 }
683 ok = conservative_merge(result, parentMRO);
684 Py_DECREF(parentMRO);
685 if (ok < 0) {
686 Py_DECREF(result);
687 return NULL;
688 }
689 }
690 return result;
691}
692
693static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000694mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000695{
696 PyTypeObject *type = (PyTypeObject *)self;
697
Tim Peters6d6c1a32001-08-02 04:15:00 +0000698 return mro_implementation(type);
699}
700
701static int
702mro_internal(PyTypeObject *type)
703{
704 PyObject *mro, *result, *tuple;
705
706 if (type->ob_type == &PyType_Type) {
707 result = mro_implementation(type);
708 }
709 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000710 static PyObject *mro_str;
711 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000712 if (mro == NULL)
713 return -1;
714 result = PyObject_CallObject(mro, NULL);
715 Py_DECREF(mro);
716 }
717 if (result == NULL)
718 return -1;
719 tuple = PySequence_Tuple(result);
720 Py_DECREF(result);
721 type->tp_mro = tuple;
722 return 0;
723}
724
725
726/* Calculate the best base amongst multiple base classes.
727 This is the first one that's on the path to the "solid base". */
728
729static PyTypeObject *
730best_base(PyObject *bases)
731{
732 int i, n;
733 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000734 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000735
736 assert(PyTuple_Check(bases));
737 n = PyTuple_GET_SIZE(bases);
738 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000739 base = NULL;
740 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000742 base_proto = PyTuple_GET_ITEM(bases, i);
743 if (PyClass_Check(base_proto))
744 continue;
745 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000746 PyErr_SetString(
747 PyExc_TypeError,
748 "bases must be types");
749 return NULL;
750 }
Tim Petersa91e9642001-11-14 23:32:33 +0000751 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000752 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000753 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000754 return NULL;
755 }
756 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000757 if (winner == NULL) {
758 winner = candidate;
759 base = base_i;
760 }
761 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000762 ;
763 else if (PyType_IsSubtype(candidate, winner)) {
764 winner = candidate;
765 base = base_i;
766 }
767 else {
768 PyErr_SetString(
769 PyExc_TypeError,
770 "multiple bases have "
771 "instance lay-out conflict");
772 return NULL;
773 }
774 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000775 if (base == NULL)
776 PyErr_SetString(PyExc_TypeError,
777 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778 return base;
779}
780
781static int
782extra_ivars(PyTypeObject *type, PyTypeObject *base)
783{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000784 size_t t_size = type->tp_basicsize;
785 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000786
Guido van Rossum9676b222001-08-17 20:32:36 +0000787 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000788 if (type->tp_itemsize || base->tp_itemsize) {
789 /* If itemsize is involved, stricter rules */
790 return t_size != b_size ||
791 type->tp_itemsize != base->tp_itemsize;
792 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000793 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
794 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
795 t_size -= sizeof(PyObject *);
796 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
797 type->tp_dictoffset + sizeof(PyObject *) == t_size)
798 t_size -= sizeof(PyObject *);
799
800 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000801}
802
803static PyTypeObject *
804solid_base(PyTypeObject *type)
805{
806 PyTypeObject *base;
807
808 if (type->tp_base)
809 base = solid_base(type->tp_base);
810 else
811 base = &PyBaseObject_Type;
812 if (extra_ivars(type, base))
813 return type;
814 else
815 return base;
816}
817
818staticforward void object_dealloc(PyObject *);
819staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000820staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000821staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000822
823static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000824subtype_dict(PyObject *obj, void *context)
825{
826 PyObject **dictptr = _PyObject_GetDictPtr(obj);
827 PyObject *dict;
828
829 if (dictptr == NULL) {
830 PyErr_SetString(PyExc_AttributeError,
831 "This object has no __dict__");
832 return NULL;
833 }
834 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000835 if (dict == NULL)
836 *dictptr = dict = PyDict_New();
837 Py_XINCREF(dict);
838 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000839}
840
Guido van Rossum6661be32001-10-26 04:26:12 +0000841static int
842subtype_setdict(PyObject *obj, PyObject *value, void *context)
843{
844 PyObject **dictptr = _PyObject_GetDictPtr(obj);
845 PyObject *dict;
846
847 if (dictptr == NULL) {
848 PyErr_SetString(PyExc_AttributeError,
849 "This object has no __dict__");
850 return -1;
851 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000852 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000853 PyErr_SetString(PyExc_TypeError,
854 "__dict__ must be set to a dictionary");
855 return -1;
856 }
857 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000858 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000859 *dictptr = value;
860 Py_XDECREF(dict);
861 return 0;
862}
863
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000864static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000865 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000866 {0},
867};
868
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000869/* bozo: __getstate__ that raises TypeError */
870
871static PyObject *
872bozo_func(PyObject *self, PyObject *args)
873{
874 PyErr_SetString(PyExc_TypeError,
875 "a class that defines __slots__ without "
876 "defining __getstate__ cannot be pickled");
877 return NULL;
878}
879
Neal Norwitz93c1e232002-03-31 16:06:11 +0000880static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000881
882static PyObject *bozo_obj = NULL;
883
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000884static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000885type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
886{
887 PyObject *name, *bases, *dict;
888 static char *kwlist[] = {"name", "bases", "dict", 0};
889 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000890 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000891 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000892 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000893 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000894
Tim Peters3abca122001-10-27 19:37:48 +0000895 assert(args != NULL && PyTuple_Check(args));
896 assert(kwds == NULL || PyDict_Check(kwds));
897
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000898 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +0000899 {
900 const int nargs = PyTuple_GET_SIZE(args);
901 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
902
903 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
904 PyObject *x = PyTuple_GET_ITEM(args, 0);
905 Py_INCREF(x->ob_type);
906 return (PyObject *) x->ob_type;
907 }
908
909 /* SF bug 475327 -- if that didn't trigger, we need 3
910 arguments. but PyArg_ParseTupleAndKeywords below may give
911 a msg saying type() needs exactly 3. */
912 if (nargs + nkwds != 3) {
913 PyErr_SetString(PyExc_TypeError,
914 "type() takes 1 or 3 arguments");
915 return NULL;
916 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000917 }
918
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000919 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000920 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
921 &name,
922 &PyTuple_Type, &bases,
923 &PyDict_Type, &dict))
924 return NULL;
925
926 /* Determine the proper metatype to deal with this,
927 and check for metatype conflicts while we're at it.
928 Note that if some other metatype wins to contract,
929 it's possible that its instances are not types. */
930 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000931 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000932 for (i = 0; i < nbases; i++) {
933 tmp = PyTuple_GET_ITEM(bases, i);
934 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +0000935 if (tmptype == &PyClass_Type)
936 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000937 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000938 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000939 if (PyType_IsSubtype(tmptype, winner)) {
940 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000941 continue;
942 }
943 PyErr_SetString(PyExc_TypeError,
944 "metatype conflict among bases");
945 return NULL;
946 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000947 if (winner != metatype) {
948 if (winner->tp_new != type_new) /* Pass it to the winner */
949 return winner->tp_new(winner, args, kwds);
950 metatype = winner;
951 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000952
953 /* Adjust for empty tuple bases */
954 if (nbases == 0) {
955 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
956 if (bases == NULL)
957 return NULL;
958 nbases = 1;
959 }
960 else
961 Py_INCREF(bases);
962
963 /* XXX From here until type is allocated, "return NULL" leaks bases! */
964
965 /* Calculate best base, and check that all bases are type objects */
966 base = best_base(bases);
967 if (base == NULL)
968 return NULL;
969 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
970 PyErr_Format(PyExc_TypeError,
971 "type '%.100s' is not an acceptable base type",
972 base->tp_name);
973 return NULL;
974 }
975
Tim Peters6d6c1a32001-08-02 04:15:00 +0000976 /* Check for a __slots__ sequence variable in dict, and count it */
977 slots = PyDict_GetItemString(dict, "__slots__");
978 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000979 add_dict = 0;
980 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000981 if (slots != NULL) {
982 /* Make it into a tuple */
983 if (PyString_Check(slots))
984 slots = Py_BuildValue("(O)", slots);
985 else
986 slots = PySequence_Tuple(slots);
987 if (slots == NULL)
988 return NULL;
989 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000990 if (nslots > 0 && base->tp_itemsize != 0) {
991 PyErr_Format(PyExc_TypeError,
992 "nonempty __slots__ "
993 "not supported for subtype of '%s'",
994 base->tp_name);
995 return NULL;
996 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997 for (i = 0; i < nslots; i++) {
998 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
999 PyErr_SetString(PyExc_TypeError,
1000 "__slots__ must be a sequence of strings");
1001 Py_DECREF(slots);
1002 return NULL;
1003 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001004 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005 }
1006 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001007 if (slots != NULL) {
1008 /* See if *this* class defines __getstate__ */
1009 PyObject *getstate = PyDict_GetItemString(dict,
1010 "__getstate__");
1011 if (getstate == NULL) {
1012 /* If not, provide a bozo that raises TypeError */
1013 if (bozo_obj == NULL) {
1014 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1015 if (bozo_obj == NULL) {
1016 /* XXX decref various things */
1017 return NULL;
1018 }
1019 }
1020 if (PyDict_SetItemString(dict,
1021 "__getstate__",
1022 bozo_obj) < 0) {
1023 /* XXX decref various things */
1024 return NULL;
1025 }
1026 }
1027 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001028 if (slots == NULL && base->tp_dictoffset == 0 &&
1029 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001030 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001031 add_dict++;
1032 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001033 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1034 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001035 nslots++;
1036 add_weak++;
1037 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001038
1039 /* XXX From here until type is safely allocated,
1040 "return NULL" may leak slots! */
1041
1042 /* Allocate the type object */
1043 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1044 if (type == NULL)
1045 return NULL;
1046
1047 /* Keep name and slots alive in the extended type object */
1048 et = (etype *)type;
1049 Py_INCREF(name);
1050 et->name = name;
1051 et->slots = slots;
1052
Guido van Rossumdc91b992001-08-08 22:26:22 +00001053 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001054 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1055 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001056 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1057 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001058
1059 /* It's a new-style number unless it specifically inherits any
1060 old-style numeric behavior */
1061 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1062 (base->tp_as_number == NULL))
1063 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1064
1065 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066 type->tp_as_number = &et->as_number;
1067 type->tp_as_sequence = &et->as_sequence;
1068 type->tp_as_mapping = &et->as_mapping;
1069 type->tp_as_buffer = &et->as_buffer;
1070 type->tp_name = PyString_AS_STRING(name);
1071
1072 /* Set tp_base and tp_bases */
1073 type->tp_bases = bases;
1074 Py_INCREF(base);
1075 type->tp_base = base;
1076
Guido van Rossum687ae002001-10-15 22:03:32 +00001077 /* Initialize tp_dict from passed-in dict */
1078 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079 if (dict == NULL) {
1080 Py_DECREF(type);
1081 return NULL;
1082 }
1083
Guido van Rossumc3542212001-08-16 09:18:56 +00001084 /* Set __module__ in the dict */
1085 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1086 tmp = PyEval_GetGlobals();
1087 if (tmp != NULL) {
1088 tmp = PyDict_GetItemString(tmp, "__name__");
1089 if (tmp != NULL) {
1090 if (PyDict_SetItemString(dict, "__module__",
1091 tmp) < 0)
1092 return NULL;
1093 }
1094 }
1095 }
1096
Tim Peters2f93e282001-10-04 05:27:00 +00001097 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001098 and is a string. The __doc__ accessor will first look for tp_doc;
1099 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001100 */
1101 {
1102 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1103 if (doc != NULL && PyString_Check(doc)) {
1104 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001105 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001106 if (type->tp_doc == NULL) {
1107 Py_DECREF(type);
1108 return NULL;
1109 }
1110 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1111 }
1112 }
1113
Tim Peters6d6c1a32001-08-02 04:15:00 +00001114 /* Special-case __new__: if it's a plain function,
1115 make it a static function */
1116 tmp = PyDict_GetItemString(dict, "__new__");
1117 if (tmp != NULL && PyFunction_Check(tmp)) {
1118 tmp = PyStaticMethod_New(tmp);
1119 if (tmp == NULL) {
1120 Py_DECREF(type);
1121 return NULL;
1122 }
1123 PyDict_SetItemString(dict, "__new__", tmp);
1124 Py_DECREF(tmp);
1125 }
1126
1127 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1128 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001129 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001130 if (slots != NULL) {
1131 for (i = 0; i < nslots; i++, mp++) {
1132 mp->name = PyString_AS_STRING(
1133 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001134 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001136 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001137 strcmp(mp->name, "__weakref__") == 0) {
1138 mp->type = T_OBJECT;
Guido van Rossum9676b222001-08-17 20:32:36 +00001139 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001140 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001141 slotoffset += sizeof(PyObject *);
1142 }
1143 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001144 else {
1145 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001146 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001147 type->tp_dictoffset =
1148 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001149 else
1150 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001151 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001152 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001153 }
1154 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001155 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001156 type->tp_weaklistoffset = slotoffset;
1157 mp->name = "__weakref__";
1158 mp->type = T_OBJECT;
1159 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001160 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001161 mp++;
1162 slotoffset += sizeof(PyObject *);
1163 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001164 }
1165 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001166 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001167 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168
1169 /* Special case some slots */
1170 if (type->tp_dictoffset != 0 || nslots > 0) {
1171 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1172 type->tp_getattro = PyObject_GenericGetAttr;
1173 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1174 type->tp_setattro = PyObject_GenericSetAttr;
1175 }
1176 type->tp_dealloc = subtype_dealloc;
1177
Guido van Rossum9475a232001-10-05 20:51:39 +00001178 /* Enable GC unless there are really no instance variables possible */
1179 if (!(type->tp_basicsize == sizeof(PyObject) &&
1180 type->tp_itemsize == 0))
1181 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1182
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183 /* Always override allocation strategy to use regular heap */
1184 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001185 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1186 type->tp_free = _PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001187 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001188 type->tp_clear = base->tp_clear;
1189 }
1190 else
1191 type->tp_free = _PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001192
1193 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001194 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 Py_DECREF(type);
1196 return NULL;
1197 }
1198
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001199 /* Put the proper slots in place */
1200 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001201
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 return (PyObject *)type;
1203}
1204
1205/* Internal API to look for a name through the MRO.
1206 This returns a borrowed reference, and doesn't set an exception! */
1207PyObject *
1208_PyType_Lookup(PyTypeObject *type, PyObject *name)
1209{
1210 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001211 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212
Guido van Rossum687ae002001-10-15 22:03:32 +00001213 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001214 mro = type->tp_mro;
1215 assert(PyTuple_Check(mro));
1216 n = PyTuple_GET_SIZE(mro);
1217 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001218 base = PyTuple_GET_ITEM(mro, i);
1219 if (PyClass_Check(base))
1220 dict = ((PyClassObject *)base)->cl_dict;
1221 else {
1222 assert(PyType_Check(base));
1223 dict = ((PyTypeObject *)base)->tp_dict;
1224 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001225 assert(dict && PyDict_Check(dict));
1226 res = PyDict_GetItem(dict, name);
1227 if (res != NULL)
1228 return res;
1229 }
1230 return NULL;
1231}
1232
1233/* This is similar to PyObject_GenericGetAttr(),
1234 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1235static PyObject *
1236type_getattro(PyTypeObject *type, PyObject *name)
1237{
1238 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001239 PyObject *meta_attribute, *attribute;
1240 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001241
1242 /* Initialize this type (we'll assume the metatype is initialized) */
1243 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001244 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 return NULL;
1246 }
1247
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001248 /* No readable descriptor found yet */
1249 meta_get = NULL;
1250
1251 /* Look for the attribute in the metatype */
1252 meta_attribute = _PyType_Lookup(metatype, name);
1253
1254 if (meta_attribute != NULL) {
1255 meta_get = meta_attribute->ob_type->tp_descr_get;
1256
1257 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1258 /* Data descriptors implement tp_descr_set to intercept
1259 * writes. Assume the attribute is not overridden in
1260 * type's tp_dict (and bases): call the descriptor now.
1261 */
1262 return meta_get(meta_attribute, (PyObject *)type,
1263 (PyObject *)metatype);
1264 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265 }
1266
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001267 /* No data descriptor found on metatype. Look in tp_dict of this
1268 * type and its bases */
1269 attribute = _PyType_Lookup(type, name);
1270 if (attribute != NULL) {
1271 /* Implement descriptor functionality, if any */
1272 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1273 if (local_get != NULL) {
1274 /* NULL 2nd argument indicates the descriptor was
1275 * found on the target object itself (or a base) */
1276 return local_get(attribute, (PyObject *)NULL,
1277 (PyObject *)type);
1278 }
1279
1280 Py_INCREF(attribute);
1281 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282 }
1283
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001284 /* No attribute found in local __dict__ (or bases): use the
1285 * descriptor from the metatype, if any */
1286 if (meta_get != NULL)
1287 return meta_get(meta_attribute, (PyObject *)type,
1288 (PyObject *)metatype);
1289
1290 /* If an ordinary attribute was found on the metatype, return it now */
1291 if (meta_attribute != NULL) {
1292 Py_INCREF(meta_attribute);
1293 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 }
1295
1296 /* Give up */
1297 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001298 "type object '%.50s' has no attribute '%.400s'",
1299 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001300 return NULL;
1301}
1302
1303static int
1304type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1305{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001306 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1307 PyErr_Format(
1308 PyExc_TypeError,
1309 "can't set attributes of built-in/extension type '%s'",
1310 type->tp_name);
1311 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001312 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001313 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1314 return -1;
1315 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316}
1317
1318static void
1319type_dealloc(PyTypeObject *type)
1320{
1321 etype *et;
1322
1323 /* Assert this is a heap-allocated type object */
1324 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001325 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001326 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327 et = (etype *)type;
1328 Py_XDECREF(type->tp_base);
1329 Py_XDECREF(type->tp_dict);
1330 Py_XDECREF(type->tp_bases);
1331 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001332 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001333 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334 Py_XDECREF(et->name);
1335 Py_XDECREF(et->slots);
1336 type->ob_type->tp_free((PyObject *)type);
1337}
1338
Guido van Rossum1c450732001-10-08 15:18:27 +00001339static PyObject *
1340type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1341{
1342 PyObject *list, *raw, *ref;
1343 int i, n;
1344
1345 list = PyList_New(0);
1346 if (list == NULL)
1347 return NULL;
1348 raw = type->tp_subclasses;
1349 if (raw == NULL)
1350 return list;
1351 assert(PyList_Check(raw));
1352 n = PyList_GET_SIZE(raw);
1353 for (i = 0; i < n; i++) {
1354 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001355 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001356 ref = PyWeakref_GET_OBJECT(ref);
1357 if (ref != Py_None) {
1358 if (PyList_Append(list, ref) < 0) {
1359 Py_DECREF(list);
1360 return NULL;
1361 }
1362 }
1363 }
1364 return list;
1365}
1366
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001368 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001370 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1371 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372 {0}
1373};
1374
1375static char type_doc[] =
1376"type(object) -> the object's type\n"
1377"type(name, bases, dict) -> a new type";
1378
Guido van Rossum048eb752001-10-02 21:24:57 +00001379static int
1380type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1381{
1382 etype *et;
1383 int err;
1384
1385 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1386 return 0;
1387
1388 et = (etype *)type;
1389
1390#define VISIT(SLOT) \
1391 if (SLOT) { \
1392 err = visit((PyObject *)(SLOT), arg); \
1393 if (err) \
1394 return err; \
1395 }
1396
1397 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001398 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001399 VISIT(type->tp_mro);
1400 VISIT(type->tp_bases);
1401 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001402 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001403 VISIT(et->slots);
1404
1405#undef VISIT
1406
1407 return 0;
1408}
1409
1410static int
1411type_clear(PyTypeObject *type)
1412{
1413 etype *et;
1414 PyObject *tmp;
1415
1416 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1417 return 0;
1418
1419 et = (etype *)type;
1420
1421#define CLEAR(SLOT) \
1422 if (SLOT) { \
1423 tmp = (PyObject *)(SLOT); \
1424 SLOT = NULL; \
1425 Py_DECREF(tmp); \
1426 }
1427
1428 CLEAR(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001429 CLEAR(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001430 CLEAR(type->tp_mro);
1431 CLEAR(type->tp_bases);
1432 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001433 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001434 CLEAR(et->slots);
1435
Tim Peters2f93e282001-10-04 05:27:00 +00001436 if (type->tp_doc != NULL) {
1437 PyObject_FREE(type->tp_doc);
1438 type->tp_doc = NULL;
1439 }
1440
Guido van Rossum048eb752001-10-02 21:24:57 +00001441#undef CLEAR
1442
1443 return 0;
1444}
1445
1446static int
1447type_is_gc(PyTypeObject *type)
1448{
1449 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1450}
1451
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001452PyTypeObject PyType_Type = {
1453 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001454 0, /* ob_size */
1455 "type", /* tp_name */
1456 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001457 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458 (destructor)type_dealloc, /* tp_dealloc */
1459 0, /* tp_print */
1460 0, /* tp_getattr */
1461 0, /* tp_setattr */
1462 type_compare, /* tp_compare */
1463 (reprfunc)type_repr, /* tp_repr */
1464 0, /* tp_as_number */
1465 0, /* tp_as_sequence */
1466 0, /* tp_as_mapping */
1467 (hashfunc)_Py_HashPointer, /* tp_hash */
1468 (ternaryfunc)type_call, /* tp_call */
1469 0, /* tp_str */
1470 (getattrofunc)type_getattro, /* tp_getattro */
1471 (setattrofunc)type_setattro, /* tp_setattro */
1472 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001473 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1474 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001475 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001476 (traverseproc)type_traverse, /* tp_traverse */
1477 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001478 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001479 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001480 0, /* tp_iter */
1481 0, /* tp_iternext */
1482 type_methods, /* tp_methods */
1483 type_members, /* tp_members */
1484 type_getsets, /* tp_getset */
1485 0, /* tp_base */
1486 0, /* tp_dict */
1487 0, /* tp_descr_get */
1488 0, /* tp_descr_set */
1489 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1490 0, /* tp_init */
1491 0, /* tp_alloc */
1492 type_new, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00001493 _PyObject_GC_Del, /* tp_free */
1494 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001495};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496
1497
1498/* The base type of all types (eventually)... except itself. */
1499
1500static int
1501object_init(PyObject *self, PyObject *args, PyObject *kwds)
1502{
1503 return 0;
1504}
1505
1506static void
1507object_dealloc(PyObject *self)
1508{
1509 self->ob_type->tp_free(self);
1510}
1511
Guido van Rossum8e248182001-08-12 05:17:56 +00001512static PyObject *
1513object_repr(PyObject *self)
1514{
Guido van Rossum76e69632001-08-16 18:52:43 +00001515 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001516 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001517
Guido van Rossum76e69632001-08-16 18:52:43 +00001518 type = self->ob_type;
1519 mod = type_module(type, NULL);
1520 if (mod == NULL)
1521 PyErr_Clear();
1522 else if (!PyString_Check(mod)) {
1523 Py_DECREF(mod);
1524 mod = NULL;
1525 }
1526 name = type_name(type, NULL);
1527 if (name == NULL)
1528 return NULL;
1529 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001530 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001531 PyString_AS_STRING(mod),
1532 PyString_AS_STRING(name),
1533 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001534 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001535 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001536 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001537 Py_XDECREF(mod);
1538 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001539 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001540}
1541
Guido van Rossumb8f63662001-08-15 23:57:02 +00001542static PyObject *
1543object_str(PyObject *self)
1544{
1545 unaryfunc f;
1546
1547 f = self->ob_type->tp_repr;
1548 if (f == NULL)
1549 f = object_repr;
1550 return f(self);
1551}
1552
Guido van Rossum8e248182001-08-12 05:17:56 +00001553static long
1554object_hash(PyObject *self)
1555{
1556 return _Py_HashPointer(self);
1557}
Guido van Rossum8e248182001-08-12 05:17:56 +00001558
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001559static PyObject *
1560object_get_class(PyObject *self, void *closure)
1561{
1562 Py_INCREF(self->ob_type);
1563 return (PyObject *)(self->ob_type);
1564}
1565
1566static int
1567equiv_structs(PyTypeObject *a, PyTypeObject *b)
1568{
1569 return a == b ||
1570 (a != NULL &&
1571 b != NULL &&
1572 a->tp_basicsize == b->tp_basicsize &&
1573 a->tp_itemsize == b->tp_itemsize &&
1574 a->tp_dictoffset == b->tp_dictoffset &&
1575 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1576 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1577 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1578}
1579
1580static int
1581same_slots_added(PyTypeObject *a, PyTypeObject *b)
1582{
1583 PyTypeObject *base = a->tp_base;
1584 int size;
1585
1586 if (base != b->tp_base)
1587 return 0;
1588 if (equiv_structs(a, base) && equiv_structs(b, base))
1589 return 1;
1590 size = base->tp_basicsize;
1591 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1592 size += sizeof(PyObject *);
1593 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1594 size += sizeof(PyObject *);
1595 return size == a->tp_basicsize && size == b->tp_basicsize;
1596}
1597
1598static int
1599object_set_class(PyObject *self, PyObject *value, void *closure)
1600{
1601 PyTypeObject *old = self->ob_type;
1602 PyTypeObject *new, *newbase, *oldbase;
1603
1604 if (!PyType_Check(value)) {
1605 PyErr_Format(PyExc_TypeError,
1606 "__class__ must be set to new-style class, not '%s' object",
1607 value->ob_type->tp_name);
1608 return -1;
1609 }
1610 new = (PyTypeObject *)value;
1611 newbase = new;
1612 oldbase = old;
1613 while (equiv_structs(newbase, newbase->tp_base))
1614 newbase = newbase->tp_base;
1615 while (equiv_structs(oldbase, oldbase->tp_base))
1616 oldbase = oldbase->tp_base;
1617 if (newbase != oldbase &&
1618 (newbase->tp_base != oldbase->tp_base ||
1619 !same_slots_added(newbase, oldbase))) {
1620 PyErr_Format(PyExc_TypeError,
1621 "__class__ assignment: "
1622 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001623 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001624 old->tp_name);
1625 return -1;
1626 }
1627 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1628 Py_INCREF(new);
1629 }
1630 self->ob_type = new;
1631 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1632 Py_DECREF(old);
1633 }
1634 return 0;
1635}
1636
1637static PyGetSetDef object_getsets[] = {
1638 {"__class__", object_get_class, object_set_class,
1639 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001640 {0}
1641};
1642
Guido van Rossum3926a632001-09-25 16:25:58 +00001643static PyObject *
1644object_reduce(PyObject *self, PyObject *args)
1645{
1646 /* Call copy_reg._reduce(self) */
1647 static PyObject *copy_reg_str;
1648 PyObject *copy_reg, *res;
1649
1650 if (!copy_reg_str) {
1651 copy_reg_str = PyString_InternFromString("copy_reg");
1652 if (copy_reg_str == NULL)
1653 return NULL;
1654 }
1655 copy_reg = PyImport_Import(copy_reg_str);
1656 if (!copy_reg)
1657 return NULL;
1658 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1659 Py_DECREF(copy_reg);
1660 return res;
1661}
1662
1663static PyMethodDef object_methods[] = {
1664 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1665 {0}
1666};
1667
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668PyTypeObject PyBaseObject_Type = {
1669 PyObject_HEAD_INIT(&PyType_Type)
1670 0, /* ob_size */
1671 "object", /* tp_name */
1672 sizeof(PyObject), /* tp_basicsize */
1673 0, /* tp_itemsize */
1674 (destructor)object_dealloc, /* tp_dealloc */
1675 0, /* tp_print */
1676 0, /* tp_getattr */
1677 0, /* tp_setattr */
1678 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001679 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001680 0, /* tp_as_number */
1681 0, /* tp_as_sequence */
1682 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001683 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001685 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001687 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688 0, /* tp_as_buffer */
1689 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1690 "The most base type", /* tp_doc */
1691 0, /* tp_traverse */
1692 0, /* tp_clear */
1693 0, /* tp_richcompare */
1694 0, /* tp_weaklistoffset */
1695 0, /* tp_iter */
1696 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001697 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001698 0, /* tp_members */
1699 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001700 0, /* tp_base */
1701 0, /* tp_dict */
1702 0, /* tp_descr_get */
1703 0, /* tp_descr_set */
1704 0, /* tp_dictoffset */
1705 object_init, /* tp_init */
1706 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001707 PyType_GenericNew, /* tp_new */
Guido van Rossum9475a232001-10-05 20:51:39 +00001708 _PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001709};
1710
1711
1712/* Initialize the __dict__ in a type object */
1713
Fred Drake7bf97152002-03-28 05:33:33 +00001714static PyObject *
1715create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1716{
1717 PyObject *cfunc;
1718 PyObject *result;
1719
1720 cfunc = PyCFunction_New(meth, NULL);
1721 if (cfunc == NULL)
1722 return NULL;
1723 result = func(cfunc);
1724 Py_DECREF(cfunc);
1725 return result;
1726}
1727
Tim Peters6d6c1a32001-08-02 04:15:00 +00001728static int
1729add_methods(PyTypeObject *type, PyMethodDef *meth)
1730{
Guido van Rossum687ae002001-10-15 22:03:32 +00001731 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001732
1733 for (; meth->ml_name != NULL; meth++) {
1734 PyObject *descr;
1735 if (PyDict_GetItemString(dict, meth->ml_name))
1736 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001737 if (meth->ml_flags & METH_CLASS) {
1738 if (meth->ml_flags & METH_STATIC) {
1739 PyErr_SetString(PyExc_ValueError,
1740 "method cannot be both class and static");
1741 return -1;
1742 }
1743 descr = create_specialmethod(meth, PyClassMethod_New);
1744 }
1745 else if (meth->ml_flags & METH_STATIC) {
1746 descr = create_specialmethod(meth, PyStaticMethod_New);
1747 }
1748 else {
1749 descr = PyDescr_NewMethod(type, meth);
1750 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001751 if (descr == NULL)
1752 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001753 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001754 return -1;
1755 Py_DECREF(descr);
1756 }
1757 return 0;
1758}
1759
1760static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001761add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762{
Guido van Rossum687ae002001-10-15 22:03:32 +00001763 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764
1765 for (; memb->name != NULL; memb++) {
1766 PyObject *descr;
1767 if (PyDict_GetItemString(dict, memb->name))
1768 continue;
1769 descr = PyDescr_NewMember(type, memb);
1770 if (descr == NULL)
1771 return -1;
1772 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1773 return -1;
1774 Py_DECREF(descr);
1775 }
1776 return 0;
1777}
1778
1779static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001780add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001781{
Guido van Rossum687ae002001-10-15 22:03:32 +00001782 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001783
1784 for (; gsp->name != NULL; gsp++) {
1785 PyObject *descr;
1786 if (PyDict_GetItemString(dict, gsp->name))
1787 continue;
1788 descr = PyDescr_NewGetSet(type, gsp);
1789
1790 if (descr == NULL)
1791 return -1;
1792 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1793 return -1;
1794 Py_DECREF(descr);
1795 }
1796 return 0;
1797}
1798
Guido van Rossum13d52f02001-08-10 21:24:08 +00001799static void
1800inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001801{
1802 int oldsize, newsize;
1803
Guido van Rossum13d52f02001-08-10 21:24:08 +00001804 /* Special flag magic */
1805 if (!type->tp_as_buffer && base->tp_as_buffer) {
1806 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1807 type->tp_flags |=
1808 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1809 }
1810 if (!type->tp_as_sequence && base->tp_as_sequence) {
1811 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1812 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1813 }
1814 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1815 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1816 if ((!type->tp_as_number && base->tp_as_number) ||
1817 (!type->tp_as_sequence && base->tp_as_sequence)) {
1818 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1819 if (!type->tp_as_number && !type->tp_as_sequence) {
1820 type->tp_flags |= base->tp_flags &
1821 Py_TPFLAGS_HAVE_INPLACEOPS;
1822 }
1823 }
1824 /* Wow */
1825 }
1826 if (!type->tp_as_number && base->tp_as_number) {
1827 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1828 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1829 }
1830
1831 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001832 oldsize = base->tp_basicsize;
1833 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1834 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1835 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001836 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1837 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001838 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001839 if (type->tp_traverse == NULL)
1840 type->tp_traverse = base->tp_traverse;
1841 if (type->tp_clear == NULL)
1842 type->tp_clear = base->tp_clear;
1843 }
1844 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001845 /* The condition below could use some explanation.
1846 It appears that tp_new is not inherited for static types
1847 whose base class is 'object'; this seems to be a precaution
1848 so that old extension types don't suddenly become
1849 callable (object.__new__ wouldn't insure the invariants
1850 that the extension type's own factory function ensures).
1851 Heap types, of course, are under our control, so they do
1852 inherit tp_new; static extension types that specify some
1853 other built-in type as the default are considered
1854 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001855 if (base != &PyBaseObject_Type ||
1856 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1857 if (type->tp_new == NULL)
1858 type->tp_new = base->tp_new;
1859 }
1860 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001861 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001862
1863 /* Copy other non-function slots */
1864
1865#undef COPYVAL
1866#define COPYVAL(SLOT) \
1867 if (type->SLOT == 0) type->SLOT = base->SLOT
1868
1869 COPYVAL(tp_itemsize);
1870 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1871 COPYVAL(tp_weaklistoffset);
1872 }
1873 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1874 COPYVAL(tp_dictoffset);
1875 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001876}
1877
1878static void
1879inherit_slots(PyTypeObject *type, PyTypeObject *base)
1880{
1881 PyTypeObject *basebase;
1882
1883#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001884#undef COPYSLOT
1885#undef COPYNUM
1886#undef COPYSEQ
1887#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001888#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001889
1890#define SLOTDEFINED(SLOT) \
1891 (base->SLOT != 0 && \
1892 (basebase == NULL || base->SLOT != basebase->SLOT))
1893
Tim Peters6d6c1a32001-08-02 04:15:00 +00001894#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001895 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001896
1897#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1898#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1899#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001900#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001901
Guido van Rossum13d52f02001-08-10 21:24:08 +00001902 /* This won't inherit indirect slots (from tp_as_number etc.)
1903 if type doesn't provide the space. */
1904
1905 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1906 basebase = base->tp_base;
1907 if (basebase->tp_as_number == NULL)
1908 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001909 COPYNUM(nb_add);
1910 COPYNUM(nb_subtract);
1911 COPYNUM(nb_multiply);
1912 COPYNUM(nb_divide);
1913 COPYNUM(nb_remainder);
1914 COPYNUM(nb_divmod);
1915 COPYNUM(nb_power);
1916 COPYNUM(nb_negative);
1917 COPYNUM(nb_positive);
1918 COPYNUM(nb_absolute);
1919 COPYNUM(nb_nonzero);
1920 COPYNUM(nb_invert);
1921 COPYNUM(nb_lshift);
1922 COPYNUM(nb_rshift);
1923 COPYNUM(nb_and);
1924 COPYNUM(nb_xor);
1925 COPYNUM(nb_or);
1926 COPYNUM(nb_coerce);
1927 COPYNUM(nb_int);
1928 COPYNUM(nb_long);
1929 COPYNUM(nb_float);
1930 COPYNUM(nb_oct);
1931 COPYNUM(nb_hex);
1932 COPYNUM(nb_inplace_add);
1933 COPYNUM(nb_inplace_subtract);
1934 COPYNUM(nb_inplace_multiply);
1935 COPYNUM(nb_inplace_divide);
1936 COPYNUM(nb_inplace_remainder);
1937 COPYNUM(nb_inplace_power);
1938 COPYNUM(nb_inplace_lshift);
1939 COPYNUM(nb_inplace_rshift);
1940 COPYNUM(nb_inplace_and);
1941 COPYNUM(nb_inplace_xor);
1942 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001943 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1944 COPYNUM(nb_true_divide);
1945 COPYNUM(nb_floor_divide);
1946 COPYNUM(nb_inplace_true_divide);
1947 COPYNUM(nb_inplace_floor_divide);
1948 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001949 }
1950
Guido van Rossum13d52f02001-08-10 21:24:08 +00001951 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1952 basebase = base->tp_base;
1953 if (basebase->tp_as_sequence == NULL)
1954 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001955 COPYSEQ(sq_length);
1956 COPYSEQ(sq_concat);
1957 COPYSEQ(sq_repeat);
1958 COPYSEQ(sq_item);
1959 COPYSEQ(sq_slice);
1960 COPYSEQ(sq_ass_item);
1961 COPYSEQ(sq_ass_slice);
1962 COPYSEQ(sq_contains);
1963 COPYSEQ(sq_inplace_concat);
1964 COPYSEQ(sq_inplace_repeat);
1965 }
1966
Guido van Rossum13d52f02001-08-10 21:24:08 +00001967 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1968 basebase = base->tp_base;
1969 if (basebase->tp_as_mapping == NULL)
1970 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001971 COPYMAP(mp_length);
1972 COPYMAP(mp_subscript);
1973 COPYMAP(mp_ass_subscript);
1974 }
1975
Tim Petersfc57ccb2001-10-12 02:38:24 +00001976 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1977 basebase = base->tp_base;
1978 if (basebase->tp_as_buffer == NULL)
1979 basebase = NULL;
1980 COPYBUF(bf_getreadbuffer);
1981 COPYBUF(bf_getwritebuffer);
1982 COPYBUF(bf_getsegcount);
1983 COPYBUF(bf_getcharbuffer);
1984 }
1985
Guido van Rossum13d52f02001-08-10 21:24:08 +00001986 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987
Tim Peters6d6c1a32001-08-02 04:15:00 +00001988 COPYSLOT(tp_dealloc);
1989 COPYSLOT(tp_print);
1990 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1991 type->tp_getattr = base->tp_getattr;
1992 type->tp_getattro = base->tp_getattro;
1993 }
1994 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1995 type->tp_setattr = base->tp_setattr;
1996 type->tp_setattro = base->tp_setattro;
1997 }
1998 /* tp_compare see tp_richcompare */
1999 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002000 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002001 COPYSLOT(tp_call);
2002 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002004 if (type->tp_compare == NULL &&
2005 type->tp_richcompare == NULL &&
2006 type->tp_hash == NULL)
2007 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002008 type->tp_compare = base->tp_compare;
2009 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002010 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002011 }
2012 }
2013 else {
2014 COPYSLOT(tp_compare);
2015 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2017 COPYSLOT(tp_iter);
2018 COPYSLOT(tp_iternext);
2019 }
2020 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2021 COPYSLOT(tp_descr_get);
2022 COPYSLOT(tp_descr_set);
2023 COPYSLOT(tp_dictoffset);
2024 COPYSLOT(tp_init);
2025 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002027 COPYSLOT(tp_new);
2028 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002030}
2031
Guido van Rossum13d52f02001-08-10 21:24:08 +00002032staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002033staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002034
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002036PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002037{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002038 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002039 PyTypeObject *base;
2040 int i, n;
2041
Guido van Rossumd614f972001-08-10 17:39:49 +00002042 if (type->tp_flags & Py_TPFLAGS_READY) {
2043 assert(type->tp_dict != NULL);
2044 return 0;
2045 }
2046 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002047
2048 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002049
Guido van Rossumf884b742001-12-17 17:14:22 +00002050 /* Initialize ob_type if NULL. This means extensions that want to be
2051 compilable separately on Windows can call PyType_Ready() instead of
2052 initializing the ob_type field of their type objects. */
2053 if (type->ob_type == NULL)
2054 type->ob_type = &PyType_Type;
2055
Tim Peters6d6c1a32001-08-02 04:15:00 +00002056 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2057 base = type->tp_base;
2058 if (base == NULL && type != &PyBaseObject_Type)
2059 base = type->tp_base = &PyBaseObject_Type;
2060
2061 /* Initialize tp_bases */
2062 bases = type->tp_bases;
2063 if (bases == NULL) {
2064 if (base == NULL)
2065 bases = PyTuple_New(0);
2066 else
2067 bases = Py_BuildValue("(O)", base);
2068 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002069 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002070 type->tp_bases = bases;
2071 }
2072
2073 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002074 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002075 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002076 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002077 }
2078
Guido van Rossum687ae002001-10-15 22:03:32 +00002079 /* Initialize tp_dict */
2080 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002081 if (dict == NULL) {
2082 dict = PyDict_New();
2083 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002084 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002085 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002086 }
2087
Guido van Rossum687ae002001-10-15 22:03:32 +00002088 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002090 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002091 if (type->tp_methods != NULL) {
2092 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002093 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002094 }
2095 if (type->tp_members != NULL) {
2096 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002097 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098 }
2099 if (type->tp_getset != NULL) {
2100 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002101 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102 }
2103
Tim Peters6d6c1a32001-08-02 04:15:00 +00002104 /* Calculate method resolution order */
2105 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002106 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002107 }
2108
Guido van Rossum13d52f02001-08-10 21:24:08 +00002109 /* Inherit special flags from dominant base */
2110 if (type->tp_base != NULL)
2111 inherit_special(type, type->tp_base);
2112
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002114 bases = type->tp_mro;
2115 assert(bases != NULL);
2116 assert(PyTuple_Check(bases));
2117 n = PyTuple_GET_SIZE(bases);
2118 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002119 PyObject *b = PyTuple_GET_ITEM(bases, i);
2120 if (PyType_Check(b))
2121 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002122 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002123
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002124 /* if the type dictionary doesn't contain a __doc__, set it from
2125 the tp_doc slot.
2126 */
2127 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2128 if (type->tp_doc != NULL) {
2129 PyObject *doc = PyString_FromString(type->tp_doc);
2130 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2131 Py_DECREF(doc);
2132 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002133 PyDict_SetItemString(type->tp_dict,
2134 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002135 }
2136 }
2137
Guido van Rossum13d52f02001-08-10 21:24:08 +00002138 /* Some more special stuff */
2139 base = type->tp_base;
2140 if (base != NULL) {
2141 if (type->tp_as_number == NULL)
2142 type->tp_as_number = base->tp_as_number;
2143 if (type->tp_as_sequence == NULL)
2144 type->tp_as_sequence = base->tp_as_sequence;
2145 if (type->tp_as_mapping == NULL)
2146 type->tp_as_mapping = base->tp_as_mapping;
2147 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002148
Guido van Rossum1c450732001-10-08 15:18:27 +00002149 /* Link into each base class's list of subclasses */
2150 bases = type->tp_bases;
2151 n = PyTuple_GET_SIZE(bases);
2152 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002153 PyObject *b = PyTuple_GET_ITEM(bases, i);
2154 if (PyType_Check(b) &&
2155 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002156 goto error;
2157 }
2158
Guido van Rossum13d52f02001-08-10 21:24:08 +00002159 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002160 assert(type->tp_dict != NULL);
2161 type->tp_flags =
2162 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002163 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002164
2165 error:
2166 type->tp_flags &= ~Py_TPFLAGS_READYING;
2167 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002168}
2169
Guido van Rossum1c450732001-10-08 15:18:27 +00002170static int
2171add_subclass(PyTypeObject *base, PyTypeObject *type)
2172{
2173 int i;
2174 PyObject *list, *ref, *new;
2175
2176 list = base->tp_subclasses;
2177 if (list == NULL) {
2178 base->tp_subclasses = list = PyList_New(0);
2179 if (list == NULL)
2180 return -1;
2181 }
2182 assert(PyList_Check(list));
2183 new = PyWeakref_NewRef((PyObject *)type, NULL);
2184 i = PyList_GET_SIZE(list);
2185 while (--i >= 0) {
2186 ref = PyList_GET_ITEM(list, i);
2187 assert(PyWeakref_CheckRef(ref));
2188 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2189 return PyList_SetItem(list, i, new);
2190 }
2191 i = PyList_Append(list, new);
2192 Py_DECREF(new);
2193 return i;
2194}
2195
Tim Peters6d6c1a32001-08-02 04:15:00 +00002196
2197/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2198
2199/* There's a wrapper *function* for each distinct function typedef used
2200 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2201 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2202 Most tables have only one entry; the tables for binary operators have two
2203 entries, one regular and one with reversed arguments. */
2204
2205static PyObject *
2206wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2207{
2208 inquiry func = (inquiry)wrapped;
2209 int res;
2210
2211 if (!PyArg_ParseTuple(args, ""))
2212 return NULL;
2213 res = (*func)(self);
2214 if (res == -1 && PyErr_Occurred())
2215 return NULL;
2216 return PyInt_FromLong((long)res);
2217}
2218
Tim Peters6d6c1a32001-08-02 04:15:00 +00002219static PyObject *
2220wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2221{
2222 binaryfunc func = (binaryfunc)wrapped;
2223 PyObject *other;
2224
2225 if (!PyArg_ParseTuple(args, "O", &other))
2226 return NULL;
2227 return (*func)(self, other);
2228}
2229
2230static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002231wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2232{
2233 binaryfunc func = (binaryfunc)wrapped;
2234 PyObject *other;
2235
2236 if (!PyArg_ParseTuple(args, "O", &other))
2237 return NULL;
2238 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002239 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002240 Py_INCREF(Py_NotImplemented);
2241 return Py_NotImplemented;
2242 }
2243 return (*func)(self, other);
2244}
2245
2246static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002247wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2248{
2249 binaryfunc func = (binaryfunc)wrapped;
2250 PyObject *other;
2251
2252 if (!PyArg_ParseTuple(args, "O", &other))
2253 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002254 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002255 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002256 Py_INCREF(Py_NotImplemented);
2257 return Py_NotImplemented;
2258 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259 return (*func)(other, self);
2260}
2261
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002262static PyObject *
2263wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2264{
2265 coercion func = (coercion)wrapped;
2266 PyObject *other, *res;
2267 int ok;
2268
2269 if (!PyArg_ParseTuple(args, "O", &other))
2270 return NULL;
2271 ok = func(&self, &other);
2272 if (ok < 0)
2273 return NULL;
2274 if (ok > 0) {
2275 Py_INCREF(Py_NotImplemented);
2276 return Py_NotImplemented;
2277 }
2278 res = PyTuple_New(2);
2279 if (res == NULL) {
2280 Py_DECREF(self);
2281 Py_DECREF(other);
2282 return NULL;
2283 }
2284 PyTuple_SET_ITEM(res, 0, self);
2285 PyTuple_SET_ITEM(res, 1, other);
2286 return res;
2287}
2288
Tim Peters6d6c1a32001-08-02 04:15:00 +00002289static PyObject *
2290wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2291{
2292 ternaryfunc func = (ternaryfunc)wrapped;
2293 PyObject *other;
2294 PyObject *third = Py_None;
2295
2296 /* Note: This wrapper only works for __pow__() */
2297
2298 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2299 return NULL;
2300 return (*func)(self, other, third);
2301}
2302
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002303static PyObject *
2304wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2305{
2306 ternaryfunc func = (ternaryfunc)wrapped;
2307 PyObject *other;
2308 PyObject *third = Py_None;
2309
2310 /* Note: This wrapper only works for __pow__() */
2311
2312 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2313 return NULL;
2314 return (*func)(other, self, third);
2315}
2316
Tim Peters6d6c1a32001-08-02 04:15:00 +00002317static PyObject *
2318wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2319{
2320 unaryfunc func = (unaryfunc)wrapped;
2321
2322 if (!PyArg_ParseTuple(args, ""))
2323 return NULL;
2324 return (*func)(self);
2325}
2326
Tim Peters6d6c1a32001-08-02 04:15:00 +00002327static PyObject *
2328wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2329{
2330 intargfunc func = (intargfunc)wrapped;
2331 int i;
2332
2333 if (!PyArg_ParseTuple(args, "i", &i))
2334 return NULL;
2335 return (*func)(self, i);
2336}
2337
Guido van Rossum5d815f32001-08-17 21:57:47 +00002338static int
2339getindex(PyObject *self, PyObject *arg)
2340{
2341 int i;
2342
2343 i = PyInt_AsLong(arg);
2344 if (i == -1 && PyErr_Occurred())
2345 return -1;
2346 if (i < 0) {
2347 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2348 if (sq && sq->sq_length) {
2349 int n = (*sq->sq_length)(self);
2350 if (n < 0)
2351 return -1;
2352 i += n;
2353 }
2354 }
2355 return i;
2356}
2357
2358static PyObject *
2359wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2360{
2361 intargfunc func = (intargfunc)wrapped;
2362 PyObject *arg;
2363 int i;
2364
Guido van Rossumf4593e02001-10-03 12:09:30 +00002365 if (PyTuple_GET_SIZE(args) == 1) {
2366 arg = PyTuple_GET_ITEM(args, 0);
2367 i = getindex(self, arg);
2368 if (i == -1 && PyErr_Occurred())
2369 return NULL;
2370 return (*func)(self, i);
2371 }
2372 PyArg_ParseTuple(args, "O", &arg);
2373 assert(PyErr_Occurred());
2374 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002375}
2376
Tim Peters6d6c1a32001-08-02 04:15:00 +00002377static PyObject *
2378wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2379{
2380 intintargfunc func = (intintargfunc)wrapped;
2381 int i, j;
2382
2383 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2384 return NULL;
2385 return (*func)(self, i, j);
2386}
2387
Tim Peters6d6c1a32001-08-02 04:15:00 +00002388static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002389wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390{
2391 intobjargproc func = (intobjargproc)wrapped;
2392 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002393 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002394
Guido van Rossum5d815f32001-08-17 21:57:47 +00002395 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2396 return NULL;
2397 i = getindex(self, arg);
2398 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002399 return NULL;
2400 res = (*func)(self, i, value);
2401 if (res == -1 && PyErr_Occurred())
2402 return NULL;
2403 Py_INCREF(Py_None);
2404 return Py_None;
2405}
2406
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002407static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002408wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002409{
2410 intobjargproc func = (intobjargproc)wrapped;
2411 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002412 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002413
Guido van Rossum5d815f32001-08-17 21:57:47 +00002414 if (!PyArg_ParseTuple(args, "O", &arg))
2415 return NULL;
2416 i = getindex(self, arg);
2417 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002418 return NULL;
2419 res = (*func)(self, i, NULL);
2420 if (res == -1 && PyErr_Occurred())
2421 return NULL;
2422 Py_INCREF(Py_None);
2423 return Py_None;
2424}
2425
Tim Peters6d6c1a32001-08-02 04:15:00 +00002426static PyObject *
2427wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2428{
2429 intintobjargproc func = (intintobjargproc)wrapped;
2430 int i, j, res;
2431 PyObject *value;
2432
2433 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2434 return NULL;
2435 res = (*func)(self, i, j, value);
2436 if (res == -1 && PyErr_Occurred())
2437 return NULL;
2438 Py_INCREF(Py_None);
2439 return Py_None;
2440}
2441
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002442static PyObject *
2443wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2444{
2445 intintobjargproc func = (intintobjargproc)wrapped;
2446 int i, j, res;
2447
2448 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2449 return NULL;
2450 res = (*func)(self, i, j, NULL);
2451 if (res == -1 && PyErr_Occurred())
2452 return NULL;
2453 Py_INCREF(Py_None);
2454 return Py_None;
2455}
2456
Tim Peters6d6c1a32001-08-02 04:15:00 +00002457/* XXX objobjproc is a misnomer; should be objargpred */
2458static PyObject *
2459wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2460{
2461 objobjproc func = (objobjproc)wrapped;
2462 int res;
2463 PyObject *value;
2464
2465 if (!PyArg_ParseTuple(args, "O", &value))
2466 return NULL;
2467 res = (*func)(self, value);
2468 if (res == -1 && PyErr_Occurred())
2469 return NULL;
2470 return PyInt_FromLong((long)res);
2471}
2472
Tim Peters6d6c1a32001-08-02 04:15:00 +00002473static PyObject *
2474wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2475{
2476 objobjargproc func = (objobjargproc)wrapped;
2477 int res;
2478 PyObject *key, *value;
2479
2480 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2481 return NULL;
2482 res = (*func)(self, key, value);
2483 if (res == -1 && PyErr_Occurred())
2484 return NULL;
2485 Py_INCREF(Py_None);
2486 return Py_None;
2487}
2488
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002489static PyObject *
2490wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2491{
2492 objobjargproc func = (objobjargproc)wrapped;
2493 int res;
2494 PyObject *key;
2495
2496 if (!PyArg_ParseTuple(args, "O", &key))
2497 return NULL;
2498 res = (*func)(self, key, NULL);
2499 if (res == -1 && PyErr_Occurred())
2500 return NULL;
2501 Py_INCREF(Py_None);
2502 return Py_None;
2503}
2504
Tim Peters6d6c1a32001-08-02 04:15:00 +00002505static PyObject *
2506wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2507{
2508 cmpfunc func = (cmpfunc)wrapped;
2509 int res;
2510 PyObject *other;
2511
2512 if (!PyArg_ParseTuple(args, "O", &other))
2513 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002514 if (other->ob_type->tp_compare != func &&
2515 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002516 PyErr_Format(
2517 PyExc_TypeError,
2518 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2519 self->ob_type->tp_name,
2520 self->ob_type->tp_name,
2521 other->ob_type->tp_name);
2522 return NULL;
2523 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002524 res = (*func)(self, other);
2525 if (PyErr_Occurred())
2526 return NULL;
2527 return PyInt_FromLong((long)res);
2528}
2529
Tim Peters6d6c1a32001-08-02 04:15:00 +00002530static PyObject *
2531wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2532{
2533 setattrofunc func = (setattrofunc)wrapped;
2534 int res;
2535 PyObject *name, *value;
2536
2537 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2538 return NULL;
2539 res = (*func)(self, name, value);
2540 if (res < 0)
2541 return NULL;
2542 Py_INCREF(Py_None);
2543 return Py_None;
2544}
2545
2546static PyObject *
2547wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2548{
2549 setattrofunc func = (setattrofunc)wrapped;
2550 int res;
2551 PyObject *name;
2552
2553 if (!PyArg_ParseTuple(args, "O", &name))
2554 return NULL;
2555 res = (*func)(self, name, NULL);
2556 if (res < 0)
2557 return NULL;
2558 Py_INCREF(Py_None);
2559 return Py_None;
2560}
2561
Tim Peters6d6c1a32001-08-02 04:15:00 +00002562static PyObject *
2563wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2564{
2565 hashfunc func = (hashfunc)wrapped;
2566 long res;
2567
2568 if (!PyArg_ParseTuple(args, ""))
2569 return NULL;
2570 res = (*func)(self);
2571 if (res == -1 && PyErr_Occurred())
2572 return NULL;
2573 return PyInt_FromLong(res);
2574}
2575
Tim Peters6d6c1a32001-08-02 04:15:00 +00002576static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002577wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002578{
2579 ternaryfunc func = (ternaryfunc)wrapped;
2580
Guido van Rossumc8e56452001-10-22 00:43:43 +00002581 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002582}
2583
Tim Peters6d6c1a32001-08-02 04:15:00 +00002584static PyObject *
2585wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2586{
2587 richcmpfunc func = (richcmpfunc)wrapped;
2588 PyObject *other;
2589
2590 if (!PyArg_ParseTuple(args, "O", &other))
2591 return NULL;
2592 return (*func)(self, other, op);
2593}
2594
2595#undef RICHCMP_WRAPPER
2596#define RICHCMP_WRAPPER(NAME, OP) \
2597static PyObject * \
2598richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2599{ \
2600 return wrap_richcmpfunc(self, args, wrapped, OP); \
2601}
2602
Jack Jansen8e938b42001-08-08 15:29:49 +00002603RICHCMP_WRAPPER(lt, Py_LT)
2604RICHCMP_WRAPPER(le, Py_LE)
2605RICHCMP_WRAPPER(eq, Py_EQ)
2606RICHCMP_WRAPPER(ne, Py_NE)
2607RICHCMP_WRAPPER(gt, Py_GT)
2608RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002609
Tim Peters6d6c1a32001-08-02 04:15:00 +00002610static PyObject *
2611wrap_next(PyObject *self, PyObject *args, void *wrapped)
2612{
2613 unaryfunc func = (unaryfunc)wrapped;
2614 PyObject *res;
2615
2616 if (!PyArg_ParseTuple(args, ""))
2617 return NULL;
2618 res = (*func)(self);
2619 if (res == NULL && !PyErr_Occurred())
2620 PyErr_SetNone(PyExc_StopIteration);
2621 return res;
2622}
2623
Tim Peters6d6c1a32001-08-02 04:15:00 +00002624static PyObject *
2625wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2626{
2627 descrgetfunc func = (descrgetfunc)wrapped;
2628 PyObject *obj;
2629 PyObject *type = NULL;
2630
2631 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2632 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002633 return (*func)(self, obj, type);
2634}
2635
Tim Peters6d6c1a32001-08-02 04:15:00 +00002636static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002637wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002638{
2639 descrsetfunc func = (descrsetfunc)wrapped;
2640 PyObject *obj, *value;
2641 int ret;
2642
2643 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2644 return NULL;
2645 ret = (*func)(self, obj, value);
2646 if (ret < 0)
2647 return NULL;
2648 Py_INCREF(Py_None);
2649 return Py_None;
2650}
2651
Tim Peters6d6c1a32001-08-02 04:15:00 +00002652static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002653wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002654{
2655 initproc func = (initproc)wrapped;
2656
Guido van Rossumc8e56452001-10-22 00:43:43 +00002657 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002658 return NULL;
2659 Py_INCREF(Py_None);
2660 return Py_None;
2661}
2662
Tim Peters6d6c1a32001-08-02 04:15:00 +00002663static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002664tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002665{
Barry Warsaw60f01882001-08-22 19:24:42 +00002666 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002667 PyObject *arg0, *res;
2668
2669 if (self == NULL || !PyType_Check(self))
2670 Py_FatalError("__new__() called with non-type 'self'");
2671 type = (PyTypeObject *)self;
2672 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002673 PyErr_Format(PyExc_TypeError,
2674 "%s.__new__(): not enough arguments",
2675 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002676 return NULL;
2677 }
2678 arg0 = PyTuple_GET_ITEM(args, 0);
2679 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002680 PyErr_Format(PyExc_TypeError,
2681 "%s.__new__(X): X is not a type object (%s)",
2682 type->tp_name,
2683 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002684 return NULL;
2685 }
2686 subtype = (PyTypeObject *)arg0;
2687 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002688 PyErr_Format(PyExc_TypeError,
2689 "%s.__new__(%s): %s is not a subtype of %s",
2690 type->tp_name,
2691 subtype->tp_name,
2692 subtype->tp_name,
2693 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002694 return NULL;
2695 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002696
2697 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002698 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002699 most derived base that's not a heap type is this type. */
2700 staticbase = subtype;
2701 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2702 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002703 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002704 PyErr_Format(PyExc_TypeError,
2705 "%s.__new__(%s) is not safe, use %s.__new__()",
2706 type->tp_name,
2707 subtype->tp_name,
2708 staticbase == NULL ? "?" : staticbase->tp_name);
2709 return NULL;
2710 }
2711
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002712 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2713 if (args == NULL)
2714 return NULL;
2715 res = type->tp_new(subtype, args, kwds);
2716 Py_DECREF(args);
2717 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002718}
2719
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002720static struct PyMethodDef tp_new_methoddef[] = {
2721 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2722 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723 {0}
2724};
2725
2726static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002727add_tp_new_wrapper(PyTypeObject *type)
2728{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002729 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002730
Guido van Rossum687ae002001-10-15 22:03:32 +00002731 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002732 return 0;
2733 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002734 if (func == NULL)
2735 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002736 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002737}
2738
Guido van Rossumf040ede2001-08-07 16:40:56 +00002739/* Slot wrappers that call the corresponding __foo__ slot. See comments
2740 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002741
Guido van Rossumdc91b992001-08-08 22:26:22 +00002742#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002743static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002744FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002746 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002747 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748}
2749
Guido van Rossumdc91b992001-08-08 22:26:22 +00002750#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002752FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002753{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002754 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002755 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002756}
2757
Guido van Rossumdc91b992001-08-08 22:26:22 +00002758
2759#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002760static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002761FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002762{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002763 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002764 int do_other = self->ob_type != other->ob_type && \
2765 other->ob_type->tp_as_number != NULL && \
2766 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002767 if (self->ob_type->tp_as_number != NULL && \
2768 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2769 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002770 if (do_other && \
2771 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2772 r = call_maybe( \
2773 other, ROPSTR, &rcache_str, "(O)", self); \
2774 if (r != Py_NotImplemented) \
2775 return r; \
2776 Py_DECREF(r); \
2777 do_other = 0; \
2778 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002779 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002780 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002781 if (r != Py_NotImplemented || \
2782 other->ob_type == self->ob_type) \
2783 return r; \
2784 Py_DECREF(r); \
2785 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002786 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002787 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002788 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002789 } \
2790 Py_INCREF(Py_NotImplemented); \
2791 return Py_NotImplemented; \
2792}
2793
2794#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2795 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2796
2797#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2798static PyObject * \
2799FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2800{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002801 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002802 return call_method(self, OPSTR, &cache_str, \
2803 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002804}
2805
2806static int
2807slot_sq_length(PyObject *self)
2808{
Guido van Rossum2730b132001-08-28 18:22:14 +00002809 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002810 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002811 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812
2813 if (res == NULL)
2814 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002815 len = (int)PyInt_AsLong(res);
2816 Py_DECREF(res);
2817 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002818}
2819
Guido van Rossumdc91b992001-08-08 22:26:22 +00002820SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2821SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002822
2823/* Super-optimized version of slot_sq_item.
2824 Other slots could do the same... */
2825static PyObject *
2826slot_sq_item(PyObject *self, int i)
2827{
2828 static PyObject *getitem_str;
2829 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2830 descrgetfunc f;
2831
2832 if (getitem_str == NULL) {
2833 getitem_str = PyString_InternFromString("__getitem__");
2834 if (getitem_str == NULL)
2835 return NULL;
2836 }
2837 func = _PyType_Lookup(self->ob_type, getitem_str);
2838 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002839 if ((f = func->ob_type->tp_descr_get) == NULL)
2840 Py_INCREF(func);
2841 else
2842 func = f(func, self, (PyObject *)(self->ob_type));
2843 ival = PyInt_FromLong(i);
2844 if (ival != NULL) {
2845 args = PyTuple_New(1);
2846 if (args != NULL) {
2847 PyTuple_SET_ITEM(args, 0, ival);
2848 retval = PyObject_Call(func, args, NULL);
2849 Py_XDECREF(args);
2850 Py_XDECREF(func);
2851 return retval;
2852 }
2853 }
2854 }
2855 else {
2856 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2857 }
2858 Py_XDECREF(args);
2859 Py_XDECREF(ival);
2860 Py_XDECREF(func);
2861 return NULL;
2862}
2863
Guido van Rossumdc91b992001-08-08 22:26:22 +00002864SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002865
2866static int
2867slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2868{
2869 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002870 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002871
2872 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002873 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002874 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002875 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002876 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002877 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002878 if (res == NULL)
2879 return -1;
2880 Py_DECREF(res);
2881 return 0;
2882}
2883
2884static int
2885slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2886{
2887 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002888 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002889
2890 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002891 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002892 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002893 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002894 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002895 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002896 if (res == NULL)
2897 return -1;
2898 Py_DECREF(res);
2899 return 0;
2900}
2901
2902static int
2903slot_sq_contains(PyObject *self, PyObject *value)
2904{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002905 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002906 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002907
Guido van Rossum55f20992001-10-01 17:18:22 +00002908 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002909
2910 if (func != NULL) {
2911 args = Py_BuildValue("(O)", value);
2912 if (args == NULL)
2913 res = NULL;
2914 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002915 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002916 Py_DECREF(args);
2917 }
2918 Py_DECREF(func);
2919 if (res == NULL)
2920 return -1;
2921 return PyObject_IsTrue(res);
2922 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002923 else if (PyErr_Occurred())
2924 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002925 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002926 return _PySequence_IterSearch(self, value,
2927 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002928 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002929}
2930
Guido van Rossumdc91b992001-08-08 22:26:22 +00002931SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2932SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002933
2934#define slot_mp_length slot_sq_length
2935
Guido van Rossumdc91b992001-08-08 22:26:22 +00002936SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002937
2938static int
2939slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2940{
2941 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002942 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002943
2944 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002945 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002946 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002947 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002948 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002949 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002950 if (res == NULL)
2951 return -1;
2952 Py_DECREF(res);
2953 return 0;
2954}
2955
Guido van Rossumdc91b992001-08-08 22:26:22 +00002956SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2957SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2958SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2959SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2960SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2961SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2962
2963staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2964
2965SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2966 nb_power, "__pow__", "__rpow__")
2967
2968static PyObject *
2969slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2970{
Guido van Rossum2730b132001-08-28 18:22:14 +00002971 static PyObject *pow_str;
2972
Guido van Rossumdc91b992001-08-08 22:26:22 +00002973 if (modulus == Py_None)
2974 return slot_nb_power_binary(self, other);
2975 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002976 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002977 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002978}
2979
2980SLOT0(slot_nb_negative, "__neg__")
2981SLOT0(slot_nb_positive, "__pos__")
2982SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002983
2984static int
2985slot_nb_nonzero(PyObject *self)
2986{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002987 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00002988 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002989
Guido van Rossum55f20992001-10-01 17:18:22 +00002990 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002991 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00002992 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00002993 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00002994 func = lookup_maybe(self, "__len__", &len_str);
2995 if (func == NULL) {
2996 if (PyErr_Occurred())
2997 return -1;
2998 else
2999 return 1;
3000 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003001 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003002 res = PyObject_CallObject(func, NULL);
3003 Py_DECREF(func);
3004 if (res == NULL)
3005 return -1;
3006 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003007}
3008
Guido van Rossumdc91b992001-08-08 22:26:22 +00003009SLOT0(slot_nb_invert, "__invert__")
3010SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3011SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3012SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3013SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3014SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003015
3016static int
3017slot_nb_coerce(PyObject **a, PyObject **b)
3018{
3019 static PyObject *coerce_str;
3020 PyObject *self = *a, *other = *b;
3021
3022 if (self->ob_type->tp_as_number != NULL &&
3023 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3024 PyObject *r;
3025 r = call_maybe(
3026 self, "__coerce__", &coerce_str, "(O)", other);
3027 if (r == NULL)
3028 return -1;
3029 if (r == Py_NotImplemented) {
3030 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003031 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003032 else {
3033 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3034 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003035 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003036 Py_DECREF(r);
3037 return -1;
3038 }
3039 *a = PyTuple_GET_ITEM(r, 0);
3040 Py_INCREF(*a);
3041 *b = PyTuple_GET_ITEM(r, 1);
3042 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003043 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003044 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003045 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003046 }
3047 if (other->ob_type->tp_as_number != NULL &&
3048 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3049 PyObject *r;
3050 r = call_maybe(
3051 other, "__coerce__", &coerce_str, "(O)", self);
3052 if (r == NULL)
3053 return -1;
3054 if (r == Py_NotImplemented) {
3055 Py_DECREF(r);
3056 return 1;
3057 }
3058 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3059 PyErr_SetString(PyExc_TypeError,
3060 "__coerce__ didn't return a 2-tuple");
3061 Py_DECREF(r);
3062 return -1;
3063 }
3064 *a = PyTuple_GET_ITEM(r, 1);
3065 Py_INCREF(*a);
3066 *b = PyTuple_GET_ITEM(r, 0);
3067 Py_INCREF(*b);
3068 Py_DECREF(r);
3069 return 0;
3070 }
3071 return 1;
3072}
3073
Guido van Rossumdc91b992001-08-08 22:26:22 +00003074SLOT0(slot_nb_int, "__int__")
3075SLOT0(slot_nb_long, "__long__")
3076SLOT0(slot_nb_float, "__float__")
3077SLOT0(slot_nb_oct, "__oct__")
3078SLOT0(slot_nb_hex, "__hex__")
3079SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3080SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3081SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3082SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3083SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3084SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3085SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3086SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3087SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3088SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3089SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3090SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3091 "__floordiv__", "__rfloordiv__")
3092SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3093SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3094SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003095
3096static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003097half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003099 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003100 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003101 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003102
Guido van Rossum60718732001-08-28 17:47:51 +00003103 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003104 if (func == NULL) {
3105 PyErr_Clear();
3106 }
3107 else {
3108 args = Py_BuildValue("(O)", other);
3109 if (args == NULL)
3110 res = NULL;
3111 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003112 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003113 Py_DECREF(args);
3114 }
3115 if (res != Py_NotImplemented) {
3116 if (res == NULL)
3117 return -2;
3118 c = PyInt_AsLong(res);
3119 Py_DECREF(res);
3120 if (c == -1 && PyErr_Occurred())
3121 return -2;
3122 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3123 }
3124 Py_DECREF(res);
3125 }
3126 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003127}
3128
Guido van Rossumab3b0342001-09-18 20:38:53 +00003129/* This slot is published for the benefit of try_3way_compare in object.c */
3130int
3131_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003132{
3133 int c;
3134
Guido van Rossumab3b0342001-09-18 20:38:53 +00003135 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003136 c = half_compare(self, other);
3137 if (c <= 1)
3138 return c;
3139 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003140 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003141 c = half_compare(other, self);
3142 if (c < -1)
3143 return -2;
3144 if (c <= 1)
3145 return -c;
3146 }
3147 return (void *)self < (void *)other ? -1 :
3148 (void *)self > (void *)other ? 1 : 0;
3149}
3150
3151static PyObject *
3152slot_tp_repr(PyObject *self)
3153{
3154 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003155 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003156
Guido van Rossum60718732001-08-28 17:47:51 +00003157 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003158 if (func != NULL) {
3159 res = PyEval_CallObject(func, NULL);
3160 Py_DECREF(func);
3161 return res;
3162 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003163 PyErr_Clear();
3164 return PyString_FromFormat("<%s object at %p>",
3165 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003166}
3167
3168static PyObject *
3169slot_tp_str(PyObject *self)
3170{
3171 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003172 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003173
Guido van Rossum60718732001-08-28 17:47:51 +00003174 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003175 if (func != NULL) {
3176 res = PyEval_CallObject(func, NULL);
3177 Py_DECREF(func);
3178 return res;
3179 }
3180 else {
3181 PyErr_Clear();
3182 return slot_tp_repr(self);
3183 }
3184}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003185
3186static long
3187slot_tp_hash(PyObject *self)
3188{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003189 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003190 static PyObject *hash_str, *eq_str, *cmp_str;
3191
Tim Peters6d6c1a32001-08-02 04:15:00 +00003192 long h;
3193
Guido van Rossum60718732001-08-28 17:47:51 +00003194 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003195
3196 if (func != NULL) {
3197 res = PyEval_CallObject(func, NULL);
3198 Py_DECREF(func);
3199 if (res == NULL)
3200 return -1;
3201 h = PyInt_AsLong(res);
3202 }
3203 else {
3204 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003205 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003206 if (func == NULL) {
3207 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003208 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003209 }
3210 if (func != NULL) {
3211 Py_DECREF(func);
3212 PyErr_SetString(PyExc_TypeError, "unhashable type");
3213 return -1;
3214 }
3215 PyErr_Clear();
3216 h = _Py_HashPointer((void *)self);
3217 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218 if (h == -1 && !PyErr_Occurred())
3219 h = -2;
3220 return h;
3221}
3222
3223static PyObject *
3224slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3225{
Guido van Rossum60718732001-08-28 17:47:51 +00003226 static PyObject *call_str;
3227 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003228 PyObject *res;
3229
3230 if (meth == NULL)
3231 return NULL;
3232 res = PyObject_Call(meth, args, kwds);
3233 Py_DECREF(meth);
3234 return res;
3235}
3236
Guido van Rossum14a6f832001-10-17 13:59:09 +00003237/* There are two slot dispatch functions for tp_getattro.
3238
3239 - slot_tp_getattro() is used when __getattribute__ is overridden
3240 but no __getattr__ hook is present;
3241
3242 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3243
Guido van Rossumc334df52002-04-04 23:44:47 +00003244 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3245 detects the absence of __getattr__ and then installs the simpler slot if
3246 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003247
Tim Peters6d6c1a32001-08-02 04:15:00 +00003248static PyObject *
3249slot_tp_getattro(PyObject *self, PyObject *name)
3250{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003251 static PyObject *getattribute_str = NULL;
3252 return call_method(self, "__getattribute__", &getattribute_str,
3253 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003254}
3255
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003256static PyObject *
3257slot_tp_getattr_hook(PyObject *self, PyObject *name)
3258{
3259 PyTypeObject *tp = self->ob_type;
3260 PyObject *getattr, *getattribute, *res;
3261 static PyObject *getattribute_str = NULL;
3262 static PyObject *getattr_str = NULL;
3263
3264 if (getattr_str == NULL) {
3265 getattr_str = PyString_InternFromString("__getattr__");
3266 if (getattr_str == NULL)
3267 return NULL;
3268 }
3269 if (getattribute_str == NULL) {
3270 getattribute_str =
3271 PyString_InternFromString("__getattribute__");
3272 if (getattribute_str == NULL)
3273 return NULL;
3274 }
3275 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003276 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003277 /* No __getattr__ hook: use a simpler dispatcher */
3278 tp->tp_getattro = slot_tp_getattro;
3279 return slot_tp_getattro(self, name);
3280 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003281 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003282 if (getattribute == NULL ||
3283 (getattribute->ob_type == &PyWrapperDescr_Type &&
3284 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3285 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003286 res = PyObject_GenericGetAttr(self, name);
3287 else
3288 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003289 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003290 PyErr_Clear();
3291 res = PyObject_CallFunction(getattr, "OO", self, name);
3292 }
3293 return res;
3294}
3295
Tim Peters6d6c1a32001-08-02 04:15:00 +00003296static int
3297slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3298{
3299 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003300 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003301
3302 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003303 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003304 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003305 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003306 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003307 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003308 if (res == NULL)
3309 return -1;
3310 Py_DECREF(res);
3311 return 0;
3312}
3313
3314/* Map rich comparison operators to their __xx__ namesakes */
3315static char *name_op[] = {
3316 "__lt__",
3317 "__le__",
3318 "__eq__",
3319 "__ne__",
3320 "__gt__",
3321 "__ge__",
3322};
3323
3324static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003325half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003326{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003327 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003328 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003329
Guido van Rossum60718732001-08-28 17:47:51 +00003330 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003331 if (func == NULL) {
3332 PyErr_Clear();
3333 Py_INCREF(Py_NotImplemented);
3334 return Py_NotImplemented;
3335 }
3336 args = Py_BuildValue("(O)", other);
3337 if (args == NULL)
3338 res = NULL;
3339 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003340 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003341 Py_DECREF(args);
3342 }
3343 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003344 return res;
3345}
3346
Guido van Rossumb8f63662001-08-15 23:57:02 +00003347/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3348static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3349
3350static PyObject *
3351slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3352{
3353 PyObject *res;
3354
3355 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3356 res = half_richcompare(self, other, op);
3357 if (res != Py_NotImplemented)
3358 return res;
3359 Py_DECREF(res);
3360 }
3361 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3362 res = half_richcompare(other, self, swapped_op[op]);
3363 if (res != Py_NotImplemented) {
3364 return res;
3365 }
3366 Py_DECREF(res);
3367 }
3368 Py_INCREF(Py_NotImplemented);
3369 return Py_NotImplemented;
3370}
3371
3372static PyObject *
3373slot_tp_iter(PyObject *self)
3374{
3375 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003376 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003377
Guido van Rossum60718732001-08-28 17:47:51 +00003378 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003379 if (func != NULL) {
3380 res = PyObject_CallObject(func, NULL);
3381 Py_DECREF(func);
3382 return res;
3383 }
3384 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003385 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003386 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003387 PyErr_SetString(PyExc_TypeError,
3388 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003389 return NULL;
3390 }
3391 Py_DECREF(func);
3392 return PySeqIter_New(self);
3393}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003394
3395static PyObject *
3396slot_tp_iternext(PyObject *self)
3397{
Guido van Rossum2730b132001-08-28 18:22:14 +00003398 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003399 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003400}
3401
Guido van Rossum1a493502001-08-17 16:47:50 +00003402static PyObject *
3403slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3404{
3405 PyTypeObject *tp = self->ob_type;
3406 PyObject *get;
3407 static PyObject *get_str = NULL;
3408
3409 if (get_str == NULL) {
3410 get_str = PyString_InternFromString("__get__");
3411 if (get_str == NULL)
3412 return NULL;
3413 }
3414 get = _PyType_Lookup(tp, get_str);
3415 if (get == NULL) {
3416 /* Avoid further slowdowns */
3417 if (tp->tp_descr_get == slot_tp_descr_get)
3418 tp->tp_descr_get = NULL;
3419 Py_INCREF(self);
3420 return self;
3421 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003422 if (obj == NULL)
3423 obj = Py_None;
3424 if (type == NULL)
3425 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003426 return PyObject_CallFunction(get, "OOO", self, obj, type);
3427}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003428
3429static int
3430slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3431{
Guido van Rossum2c252392001-08-24 10:13:31 +00003432 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003433 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003434
3435 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003436 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003437 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003438 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003439 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003440 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441 if (res == NULL)
3442 return -1;
3443 Py_DECREF(res);
3444 return 0;
3445}
3446
3447static int
3448slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3449{
Guido van Rossum60718732001-08-28 17:47:51 +00003450 static PyObject *init_str;
3451 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003452 PyObject *res;
3453
3454 if (meth == NULL)
3455 return -1;
3456 res = PyObject_Call(meth, args, kwds);
3457 Py_DECREF(meth);
3458 if (res == NULL)
3459 return -1;
3460 Py_DECREF(res);
3461 return 0;
3462}
3463
3464static PyObject *
3465slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3466{
3467 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3468 PyObject *newargs, *x;
3469 int i, n;
3470
3471 if (func == NULL)
3472 return NULL;
3473 assert(PyTuple_Check(args));
3474 n = PyTuple_GET_SIZE(args);
3475 newargs = PyTuple_New(n+1);
3476 if (newargs == NULL)
3477 return NULL;
3478 Py_INCREF(type);
3479 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3480 for (i = 0; i < n; i++) {
3481 x = PyTuple_GET_ITEM(args, i);
3482 Py_INCREF(x);
3483 PyTuple_SET_ITEM(newargs, i+1, x);
3484 }
3485 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003486 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003487 Py_DECREF(func);
3488 return x;
3489}
3490
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003491
3492/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3493 functions. The offsets here are relative to the 'etype' structure, which
3494 incorporates the additional structures used for numbers, sequences and
3495 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3496 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003497 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3498 terminated with an all-zero entry. (This table is further initialized and
3499 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003500
Guido van Rossum6d204072001-10-21 00:44:31 +00003501typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003502
3503#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003504#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003505#undef ETSLOT
3506#undef SQSLOT
3507#undef MPSLOT
3508#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003509#undef UNSLOT
3510#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003511#undef BINSLOT
3512#undef RBINSLOT
3513
Guido van Rossum6d204072001-10-21 00:44:31 +00003514#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3515 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003516#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3517 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3518 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003519#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3520 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3521#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3522 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3523#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3524 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3525#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3526 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3527#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3528 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3529 "x." NAME "() <==> " DOC)
3530#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3531 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3532 "x." NAME "(y) <==> x" DOC "y")
3533#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3534 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3535 "x." NAME "(y) <==> x" DOC "y")
3536#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3537 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3538 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003539
3540static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003541 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3542 "x.__len__() <==> len(x)"),
3543 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3544 "x.__add__(y) <==> x+y"),
3545 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3546 "x.__mul__(n) <==> x*n"),
3547 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3548 "x.__rmul__(n) <==> n*x"),
3549 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3550 "x.__getitem__(y) <==> x[y]"),
3551 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3552 "x.__getslice__(i, j) <==> x[i:j]"),
3553 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3554 "x.__setitem__(i, y) <==> x[i]=y"),
3555 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3556 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003557 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003558 wrap_intintobjargproc,
3559 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3560 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3561 "x.__delslice__(i, j) <==> del x[i:j]"),
3562 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3563 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003564 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003565 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003566 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003567 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003568
Guido van Rossum6d204072001-10-21 00:44:31 +00003569 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3570 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003571 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003572 wrap_binaryfunc,
3573 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003574 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003575 wrap_objobjargproc,
3576 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003577 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003578 wrap_delitem,
3579 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003580
Guido van Rossum6d204072001-10-21 00:44:31 +00003581 BINSLOT("__add__", nb_add, slot_nb_add,
3582 "+"),
3583 RBINSLOT("__radd__", nb_add, slot_nb_add,
3584 "+"),
3585 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3586 "-"),
3587 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3588 "-"),
3589 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3590 "*"),
3591 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3592 "*"),
3593 BINSLOT("__div__", nb_divide, slot_nb_divide,
3594 "/"),
3595 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3596 "/"),
3597 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3598 "%"),
3599 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3600 "%"),
3601 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3602 "divmod(x, y)"),
3603 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3604 "divmod(y, x)"),
3605 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3606 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3607 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3608 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3609 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3610 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3611 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3612 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003613 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003614 "x != 0"),
3615 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3616 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3617 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3618 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3619 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3620 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3621 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3622 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3623 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3624 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3625 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3626 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3627 "x.__coerce__(y) <==> coerce(x, y)"),
3628 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3629 "int(x)"),
3630 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3631 "long(x)"),
3632 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3633 "float(x)"),
3634 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3635 "oct(x)"),
3636 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3637 "hex(x)"),
3638 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3639 wrap_binaryfunc, "+"),
3640 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3641 wrap_binaryfunc, "-"),
3642 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3643 wrap_binaryfunc, "*"),
3644 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3645 wrap_binaryfunc, "/"),
3646 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3647 wrap_binaryfunc, "%"),
3648 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3649 wrap_ternaryfunc, "**"),
3650 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3651 wrap_binaryfunc, "<<"),
3652 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3653 wrap_binaryfunc, ">>"),
3654 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3655 wrap_binaryfunc, "&"),
3656 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3657 wrap_binaryfunc, "^"),
3658 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3659 wrap_binaryfunc, "|"),
3660 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3661 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3662 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3663 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3664 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3665 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3666 IBSLOT("__itruediv__", nb_inplace_true_divide,
3667 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003668
Guido van Rossum6d204072001-10-21 00:44:31 +00003669 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3670 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003671 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003672 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3673 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003674 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003675 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3676 "x.__cmp__(y) <==> cmp(x,y)"),
3677 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3678 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003679 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3680 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003681 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003682 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3683 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3684 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3685 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3686 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3687 "x.__setattr__('name', value) <==> x.name = value"),
3688 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3689 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3690 "x.__delattr__('name') <==> del x.name"),
3691 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3692 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3693 "x.__lt__(y) <==> x<y"),
3694 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3695 "x.__le__(y) <==> x<=y"),
3696 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3697 "x.__eq__(y) <==> x==y"),
3698 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3699 "x.__ne__(y) <==> x!=y"),
3700 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3701 "x.__gt__(y) <==> x>y"),
3702 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3703 "x.__ge__(y) <==> x>=y"),
3704 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3705 "x.__iter__() <==> iter(x)"),
3706 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3707 "x.next() -> the next value, or raise StopIteration"),
3708 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3709 "descr.__get__(obj[, type]) -> value"),
3710 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3711 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003712 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003713 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003714 "see x.__class__.__doc__ for signature",
3715 PyWrapperFlag_KEYWORDS),
3716 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003717 {NULL}
3718};
3719
Guido van Rossumc334df52002-04-04 23:44:47 +00003720/* Given a type pointer and an offset gotten from a slotdef entry, return a
3721 pointer to the actual slot. This is not quite the same as simply adding
3722 the offset to the type pointer, since it takes care to indirect through the
3723 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3724 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003725static void **
3726slotptr(PyTypeObject *type, int offset)
3727{
3728 char *ptr;
3729
3730 assert(offset >= 0);
3731 assert(offset < offsetof(etype, as_buffer));
3732 if (offset >= offsetof(etype, as_mapping)) {
3733 ptr = (void *)type->tp_as_mapping;
3734 offset -= offsetof(etype, as_mapping);
3735 }
3736 else if (offset >= offsetof(etype, as_sequence)) {
3737 ptr = (void *)type->tp_as_sequence;
3738 offset -= offsetof(etype, as_sequence);
3739 }
3740 else if (offset >= offsetof(etype, as_number)) {
3741 ptr = (void *)type->tp_as_number;
3742 offset -= offsetof(etype, as_number);
3743 }
3744 else {
3745 ptr = (void *)type;
3746 }
3747 if (ptr != NULL)
3748 ptr += offset;
3749 return (void **)ptr;
3750}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003751
Guido van Rossumc334df52002-04-04 23:44:47 +00003752/* Length of array of slotdef pointers used to store slots with the
3753 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3754 the same __name__, for any __name__. Since that's a static property, it is
3755 appropriate to declare fixed-size arrays for this. */
3756#define MAX_EQUIV 10
3757
3758/* Return a slot pointer for a given name, but ONLY if the attribute has
3759 exactly one slot function. The name must be an interned string. */
3760static void **
3761resolve_slotdups(PyTypeObject *type, PyObject *name)
3762{
3763 /* XXX Maybe this could be optimized more -- but is it worth it? */
3764
3765 /* pname and ptrs act as a little cache */
3766 static PyObject *pname;
3767 static slotdef *ptrs[MAX_EQUIV];
3768 slotdef *p, **pp;
3769 void **res, **ptr;
3770
3771 if (pname != name) {
3772 /* Collect all slotdefs that match name into ptrs. */
3773 pname = name;
3774 pp = ptrs;
3775 for (p = slotdefs; p->name_strobj; p++) {
3776 if (p->name_strobj == name)
3777 *pp++ = p;
3778 }
3779 *pp = NULL;
3780 }
3781
3782 /* Look in all matching slots of the type; if exactly one of these has
3783 a filled-in slot, return its value. Otherwise return NULL. */
3784 res = NULL;
3785 for (pp = ptrs; *pp; pp++) {
3786 ptr = slotptr(type, (*pp)->offset);
3787 if (ptr == NULL || *ptr == NULL)
3788 continue;
3789 if (res != NULL)
3790 return NULL;
3791 res = ptr;
3792 }
3793 return res;
3794}
3795
3796/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3797 does some incredibly complex thinking and then sticks something into the
3798 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3799 interests, and then stores a generic wrapper or a specific function into
3800 the slot.) Return a pointer to the next slotdef with a different offset,
3801 because that's convenient for fixup_slot_dispatchers(). */
3802static slotdef *
3803update_one_slot(PyTypeObject *type, slotdef *p)
3804{
3805 PyObject *descr;
3806 PyWrapperDescrObject *d;
3807 void *generic = NULL, *specific = NULL;
3808 int use_generic = 0;
3809 int offset = p->offset;
3810 void **ptr = slotptr(type, offset);
3811
3812 if (ptr == NULL) {
3813 do {
3814 ++p;
3815 } while (p->offset == offset);
3816 return p;
3817 }
3818 do {
3819 descr = _PyType_Lookup(type, p->name_strobj);
3820 if (descr == NULL)
3821 continue;
3822 if (descr->ob_type == &PyWrapperDescr_Type) {
3823 void **tptr = resolve_slotdups(type, p->name_strobj);
3824 if (tptr == NULL || tptr == ptr)
3825 generic = p->function;
3826 d = (PyWrapperDescrObject *)descr;
3827 if (d->d_base->wrapper == p->wrapper &&
3828 PyType_IsSubtype(type, d->d_type))
3829 {
3830 if (specific == NULL ||
3831 specific == d->d_wrapped)
3832 specific = d->d_wrapped;
3833 else
3834 use_generic = 1;
3835 }
3836 }
3837 else {
3838 use_generic = 1;
3839 generic = p->function;
3840 }
3841 } while ((++p)->offset == offset);
3842 if (specific && !use_generic)
3843 *ptr = specific;
3844 else
3845 *ptr = generic;
3846 return p;
3847}
3848
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003849staticforward int recurse_down_subclasses(PyTypeObject *type,
3850 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003851
Guido van Rossumc334df52002-04-04 23:44:47 +00003852/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
3853 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003854static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003855update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003856{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003857 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003858
Guido van Rossumc334df52002-04-04 23:44:47 +00003859 for (pp = pp0; *pp; pp++)
3860 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003861 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003862}
3863
Guido van Rossumc334df52002-04-04 23:44:47 +00003864/* Update the slots whose slotdefs are gathered in the pp array in all (direct
3865 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003866static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003867recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003868{
3869 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003870 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003871 int i, n;
3872
3873 subclasses = type->tp_subclasses;
3874 if (subclasses == NULL)
3875 return 0;
3876 assert(PyList_Check(subclasses));
3877 n = PyList_GET_SIZE(subclasses);
3878 for (i = 0; i < n; i++) {
3879 ref = PyList_GET_ITEM(subclasses, i);
3880 assert(PyWeakref_CheckRef(ref));
3881 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3882 if (subclass == NULL)
3883 continue;
3884 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003885 /* Avoid recursing down into unaffected classes */
3886 dict = subclass->tp_dict;
3887 if (dict != NULL && PyDict_Check(dict) &&
3888 PyDict_GetItem(dict, name) != NULL)
3889 continue;
3890 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003891 return -1;
3892 }
3893 return 0;
3894}
3895
Guido van Rossumc334df52002-04-04 23:44:47 +00003896/* Comparison function for qsort() to compare slotdefs by their offset, and
3897 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003898static int
3899slotdef_cmp(const void *aa, const void *bb)
3900{
3901 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3902 int c = a->offset - b->offset;
3903 if (c != 0)
3904 return c;
3905 else
3906 return a - b;
3907}
3908
Guido van Rossumc334df52002-04-04 23:44:47 +00003909/* Initialize the slotdefs table by adding interned string objects for the
3910 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003911static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003912init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003913{
3914 slotdef *p;
3915 static int initialized = 0;
3916
3917 if (initialized)
3918 return;
3919 for (p = slotdefs; p->name; p++) {
3920 p->name_strobj = PyString_InternFromString(p->name);
3921 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00003922 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003923 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003924 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3925 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003926 initialized = 1;
3927}
3928
Guido van Rossumc334df52002-04-04 23:44:47 +00003929/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003930static int
3931update_slot(PyTypeObject *type, PyObject *name)
3932{
Guido van Rossumc334df52002-04-04 23:44:47 +00003933 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003934 slotdef *p;
3935 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003936 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003937
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003938 init_slotdefs();
3939 pp = ptrs;
3940 for (p = slotdefs; p->name; p++) {
3941 /* XXX assume name is interned! */
3942 if (p->name_strobj == name)
3943 *pp++ = p;
3944 }
3945 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003946 for (pp = ptrs; *pp; pp++) {
3947 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003948 offset = p->offset;
3949 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003950 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003951 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003952 }
Guido van Rossumc334df52002-04-04 23:44:47 +00003953 if (ptrs[0] == NULL)
3954 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003955 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003956}
3957
Guido van Rossumc334df52002-04-04 23:44:47 +00003958/* Store the proper functions in the slot dispatches at class (type)
3959 definition time, based upon which operations the class overrides in its
3960 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003961static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003962fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003963{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003964 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003965
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003966 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00003967 for (p = slotdefs; p->name; )
3968 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003969}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003970
Guido van Rossum6d204072001-10-21 00:44:31 +00003971/* This function is called by PyType_Ready() to populate the type's
3972 dictionary with method descriptors for function slots. For each
3973 function slot (like tp_repr) that's defined in the type, one or
3974 more corresponding descriptors are added in the type's tp_dict
3975 dictionary under the appropriate name (like __repr__). Some
3976 function slots cause more than one descriptor to be added (for
3977 example, the nb_add slot adds both __add__ and __radd__
3978 descriptors) and some function slots compete for the same
3979 descriptor (for example both sq_item and mp_subscript generate a
3980 __getitem__ descriptor). This only adds new descriptors and
3981 doesn't overwrite entries in tp_dict that were previously
3982 defined. The descriptors contain a reference to the C function
3983 they must call, so that it's safe if they are copied into a
3984 subtype's __dict__ and the subtype has a different C function in
3985 its slot -- calling the method defined by the descriptor will call
3986 the C function that was used to create it, rather than the C
3987 function present in the slot when it is called. (This is important
3988 because a subtype may have a C function in the slot that calls the
3989 method from the dictionary, and we want to avoid infinite recursion
3990 here.) */
3991
3992static int
3993add_operators(PyTypeObject *type)
3994{
3995 PyObject *dict = type->tp_dict;
3996 slotdef *p;
3997 PyObject *descr;
3998 void **ptr;
3999
4000 init_slotdefs();
4001 for (p = slotdefs; p->name; p++) {
4002 if (p->wrapper == NULL)
4003 continue;
4004 ptr = slotptr(type, p->offset);
4005 if (!ptr || !*ptr)
4006 continue;
4007 if (PyDict_GetItem(dict, p->name_strobj))
4008 continue;
4009 descr = PyDescr_NewWrapper(type, p, *ptr);
4010 if (descr == NULL)
4011 return -1;
4012 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4013 return -1;
4014 Py_DECREF(descr);
4015 }
4016 if (type->tp_new != NULL) {
4017 if (add_tp_new_wrapper(type) < 0)
4018 return -1;
4019 }
4020 return 0;
4021}
4022
Guido van Rossum705f0f52001-08-24 16:47:00 +00004023
4024/* Cooperative 'super' */
4025
4026typedef struct {
4027 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004028 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004029 PyObject *obj;
4030} superobject;
4031
Guido van Rossum6f799372001-09-20 20:46:19 +00004032static PyMemberDef super_members[] = {
4033 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4034 "the class invoking super()"},
4035 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4036 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004037 {0}
4038};
4039
Guido van Rossum705f0f52001-08-24 16:47:00 +00004040static void
4041super_dealloc(PyObject *self)
4042{
4043 superobject *su = (superobject *)self;
4044
Guido van Rossum048eb752001-10-02 21:24:57 +00004045 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004046 Py_XDECREF(su->obj);
4047 Py_XDECREF(su->type);
4048 self->ob_type->tp_free(self);
4049}
4050
4051static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004052super_repr(PyObject *self)
4053{
4054 superobject *su = (superobject *)self;
4055
4056 if (su->obj)
4057 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004058 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004059 su->type ? su->type->tp_name : "NULL",
4060 su->obj->ob_type->tp_name);
4061 else
4062 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004063 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004064 su->type ? su->type->tp_name : "NULL");
4065}
4066
4067static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004068super_getattro(PyObject *self, PyObject *name)
4069{
4070 superobject *su = (superobject *)self;
4071
4072 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004073 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004074 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004075 descrgetfunc f;
4076 int i, n;
4077
Guido van Rossum155db9a2002-04-02 17:53:47 +00004078 starttype = su->obj->ob_type;
4079 mro = starttype->tp_mro;
4080
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004081 if (mro == NULL)
4082 n = 0;
4083 else {
4084 assert(PyTuple_Check(mro));
4085 n = PyTuple_GET_SIZE(mro);
4086 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004087 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004088 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004089 break;
4090 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004091 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004092 starttype = (PyTypeObject *)(su->obj);
4093 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004094 if (mro == NULL)
4095 n = 0;
4096 else {
4097 assert(PyTuple_Check(mro));
4098 n = PyTuple_GET_SIZE(mro);
4099 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004100 for (i = 0; i < n; i++) {
4101 if ((PyObject *)(su->type) ==
4102 PyTuple_GET_ITEM(mro, i))
4103 break;
4104 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004105 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004106 i++;
4107 res = NULL;
4108 for (; i < n; i++) {
4109 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004110 if (PyType_Check(tmp))
4111 dict = ((PyTypeObject *)tmp)->tp_dict;
4112 else if (PyClass_Check(tmp))
4113 dict = ((PyClassObject *)tmp)->cl_dict;
4114 else
4115 continue;
4116 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004117 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004118 Py_INCREF(res);
4119 f = res->ob_type->tp_descr_get;
4120 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004121 tmp = f(res, su->obj,
4122 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004123 Py_DECREF(res);
4124 res = tmp;
4125 }
4126 return res;
4127 }
4128 }
4129 }
4130 return PyObject_GenericGetAttr(self, name);
4131}
4132
Guido van Rossum5b443c62001-12-03 15:38:28 +00004133static int
4134supercheck(PyTypeObject *type, PyObject *obj)
4135{
4136 if (!PyType_IsSubtype(obj->ob_type, type) &&
4137 !(PyType_Check(obj) &&
4138 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4139 PyErr_SetString(PyExc_TypeError,
4140 "super(type, obj): "
4141 "obj must be an instance or subtype of type");
4142 return -1;
4143 }
4144 else
4145 return 0;
4146}
4147
Guido van Rossum705f0f52001-08-24 16:47:00 +00004148static PyObject *
4149super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4150{
4151 superobject *su = (superobject *)self;
4152 superobject *new;
4153
4154 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4155 /* Not binding to an object, or already bound */
4156 Py_INCREF(self);
4157 return self;
4158 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004159 if (su->ob_type != &PySuper_Type)
4160 /* If su is an instance of a subclass of super,
4161 call its type */
4162 return PyObject_CallFunction((PyObject *)su->ob_type,
4163 "OO", su->type, obj);
4164 else {
4165 /* Inline the common case */
4166 if (supercheck(su->type, obj) < 0)
4167 return NULL;
4168 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4169 NULL, NULL);
4170 if (new == NULL)
4171 return NULL;
4172 Py_INCREF(su->type);
4173 Py_INCREF(obj);
4174 new->type = su->type;
4175 new->obj = obj;
4176 return (PyObject *)new;
4177 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004178}
4179
4180static int
4181super_init(PyObject *self, PyObject *args, PyObject *kwds)
4182{
4183 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004184 PyTypeObject *type;
4185 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004186
4187 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4188 return -1;
4189 if (obj == Py_None)
4190 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004191 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004192 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004193 Py_INCREF(type);
4194 Py_XINCREF(obj);
4195 su->type = type;
4196 su->obj = obj;
4197 return 0;
4198}
4199
4200static char super_doc[] =
4201"super(type) -> unbound super object\n"
4202"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004203"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004204"Typical use to call a cooperative superclass method:\n"
4205"class C(B):\n"
4206" def meth(self, arg):\n"
4207" super(C, self).meth(arg)";
4208
Guido van Rossum048eb752001-10-02 21:24:57 +00004209static int
4210super_traverse(PyObject *self, visitproc visit, void *arg)
4211{
4212 superobject *su = (superobject *)self;
4213 int err;
4214
4215#define VISIT(SLOT) \
4216 if (SLOT) { \
4217 err = visit((PyObject *)(SLOT), arg); \
4218 if (err) \
4219 return err; \
4220 }
4221
4222 VISIT(su->obj);
4223 VISIT(su->type);
4224
4225#undef VISIT
4226
4227 return 0;
4228}
4229
Guido van Rossum705f0f52001-08-24 16:47:00 +00004230PyTypeObject PySuper_Type = {
4231 PyObject_HEAD_INIT(&PyType_Type)
4232 0, /* ob_size */
4233 "super", /* tp_name */
4234 sizeof(superobject), /* tp_basicsize */
4235 0, /* tp_itemsize */
4236 /* methods */
4237 super_dealloc, /* tp_dealloc */
4238 0, /* tp_print */
4239 0, /* tp_getattr */
4240 0, /* tp_setattr */
4241 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004242 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004243 0, /* tp_as_number */
4244 0, /* tp_as_sequence */
4245 0, /* tp_as_mapping */
4246 0, /* tp_hash */
4247 0, /* tp_call */
4248 0, /* tp_str */
4249 super_getattro, /* tp_getattro */
4250 0, /* tp_setattro */
4251 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004252 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4253 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004254 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004255 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004256 0, /* tp_clear */
4257 0, /* tp_richcompare */
4258 0, /* tp_weaklistoffset */
4259 0, /* tp_iter */
4260 0, /* tp_iternext */
4261 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004262 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004263 0, /* tp_getset */
4264 0, /* tp_base */
4265 0, /* tp_dict */
4266 super_descr_get, /* tp_descr_get */
4267 0, /* tp_descr_set */
4268 0, /* tp_dictoffset */
4269 super_init, /* tp_init */
4270 PyType_GenericAlloc, /* tp_alloc */
4271 PyType_GenericNew, /* tp_new */
Guido van Rossum048eb752001-10-02 21:24:57 +00004272 _PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004273};