blob: 9a20fa4e049c590628ad11cd3804f2aae0711d72 [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;
Guido van Rossum6ca7d412002-04-18 00:22:00 +000085 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +000086 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +000087 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +000088 if (result == NULL) {
89 result = Py_None;
90 Py_INCREF(result);
91 }
92 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +000093 result = result->ob_type->tp_descr_get(result, NULL,
94 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +000095 }
96 else {
97 Py_INCREF(result);
98 }
Tim Peters24008312002-03-17 18:56:20 +000099 return result;
100}
101
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000102static PyGetSetDef type_getsets[] = {
Guido van Rossumc3542212001-08-16 09:18:56 +0000103 {"__name__", (getter)type_name, NULL, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000104 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000105 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000106 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000107 {0}
108};
109
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000110static int
111type_compare(PyObject *v, PyObject *w)
112{
113 /* This is called with type objects only. So we
114 can just compare the addresses. */
115 Py_uintptr_t vv = (Py_uintptr_t)v;
116 Py_uintptr_t ww = (Py_uintptr_t)w;
117 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
118}
119
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000120static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000121type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000122{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000123 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000124 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000125
126 mod = type_module(type, NULL);
127 if (mod == NULL)
128 PyErr_Clear();
129 else if (!PyString_Check(mod)) {
130 Py_DECREF(mod);
131 mod = NULL;
132 }
133 name = type_name(type, NULL);
134 if (name == NULL)
135 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000136
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000137 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
138 kind = "class";
139 else
140 kind = "type";
141
Barry Warsaw7ce36942001-08-24 18:34:26 +0000142 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000143 rtn = PyString_FromFormat("<%s '%s.%s'>",
144 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000145 PyString_AS_STRING(mod),
146 PyString_AS_STRING(name));
147 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000148 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000149 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000150
Guido van Rossumc3542212001-08-16 09:18:56 +0000151 Py_XDECREF(mod);
152 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000153 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154}
155
Tim Peters6d6c1a32001-08-02 04:15:00 +0000156static PyObject *
157type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
158{
159 PyObject *obj;
160
161 if (type->tp_new == NULL) {
162 PyErr_Format(PyExc_TypeError,
163 "cannot create '%.100s' instances",
164 type->tp_name);
165 return NULL;
166 }
167
Tim Peters3f996e72001-09-13 19:18:27 +0000168 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000169 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000170 /* Ugly exception: when the call was type(something),
171 don't call tp_init on the result. */
172 if (type == &PyType_Type &&
173 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
174 (kwds == NULL ||
175 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
176 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000177 /* If the returned object is not an instance of type,
178 it won't be initialized. */
179 if (!PyType_IsSubtype(obj->ob_type, type))
180 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000181 type = obj->ob_type;
182 if (type->tp_init != NULL &&
183 type->tp_init(obj, args, kwds) < 0) {
184 Py_DECREF(obj);
185 obj = NULL;
186 }
187 }
188 return obj;
189}
190
191PyObject *
192PyType_GenericAlloc(PyTypeObject *type, int nitems)
193{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000194 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000195 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000196
197 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000198 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000199 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000200 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000201
Neil Schemenauerc806c882001-08-29 23:54:54 +0000202 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000203 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000204
Neil Schemenauerc806c882001-08-29 23:54:54 +0000205 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000206
Tim Peters6d6c1a32001-08-02 04:15:00 +0000207 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
208 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000209
Tim Peters6d6c1a32001-08-02 04:15:00 +0000210 if (type->tp_itemsize == 0)
211 PyObject_INIT(obj, type);
212 else
213 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000214
Tim Peters6d6c1a32001-08-02 04:15:00 +0000215 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000216 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000217 return obj;
218}
219
220PyObject *
221PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
222{
223 return type->tp_alloc(type, 0);
224}
225
Guido van Rossum9475a232001-10-05 20:51:39 +0000226/* Helpers for subtyping */
227
228static int
229subtype_traverse(PyObject *self, visitproc visit, void *arg)
230{
231 PyTypeObject *type, *base;
232 traverseproc f;
233 int err;
234
235 /* Find the nearest base with a different tp_traverse */
236 type = self->ob_type;
237 base = type->tp_base;
238 while ((f = base->tp_traverse) == subtype_traverse) {
239 base = base->tp_base;
240 assert(base);
241 }
242
243 if (type->tp_dictoffset != base->tp_dictoffset) {
244 PyObject **dictptr = _PyObject_GetDictPtr(self);
245 if (dictptr && *dictptr) {
246 err = visit(*dictptr, arg);
247 if (err)
248 return err;
249 }
250 }
251
252 if (f)
253 return f(self, visit, arg);
254 return 0;
255}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000256
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000257staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);
258
259static int
260call_finalizer(PyObject *self)
261{
262 static PyObject *del_str = NULL;
263 PyObject *del, *res;
264 PyObject *error_type, *error_value, *error_traceback;
265
266 /* Temporarily resurrect the object. */
267#ifdef Py_TRACE_REFS
268#ifndef Py_REF_DEBUG
269# error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
270#endif
271 /* much too complicated if Py_TRACE_REFS defined */
272 _Py_NewReference((PyObject *)self);
273#ifdef COUNT_ALLOCS
274 /* compensate for boost in _Py_NewReference; note that
275 * _Py_RefTotal was also boosted; we'll knock that down later.
276 */
277 self->ob_type->tp_allocs--;
278#endif
279#else /* !Py_TRACE_REFS */
280 /* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
281 Py_INCREF(self);
282#endif /* !Py_TRACE_REFS */
283
284 /* Save the current exception, if any. */
285 PyErr_Fetch(&error_type, &error_value, &error_traceback);
286
287 /* Execute __del__ method, if any. */
288 del = lookup_maybe(self, "__del__", &del_str);
289 if (del != NULL) {
290 res = PyEval_CallObject(del, NULL);
291 if (res == NULL)
292 PyErr_WriteUnraisable(del);
293 else
294 Py_DECREF(res);
295 Py_DECREF(del);
296 }
297
298 /* Restore the saved exception. */
299 PyErr_Restore(error_type, error_value, error_traceback);
300
301 /* Undo the temporary resurrection; can't use DECREF here, it would
302 * cause a recursive call.
303 */
304#ifdef Py_REF_DEBUG
305 /* _Py_RefTotal was boosted either by _Py_NewReference or
306 * Py_INCREF above.
307 */
308 _Py_RefTotal--;
309#endif
310 if (--self->ob_refcnt > 0) {
311#ifdef COUNT_ALLOCS
312 self->ob_type->tp_frees--;
313#endif
314 _PyObject_GC_TRACK(self);
315 return -1; /* __del__ added a reference; don't delete now */
316 }
317#ifdef Py_TRACE_REFS
318 _Py_ForgetReference((PyObject *)self);
319#ifdef COUNT_ALLOCS
320 /* compensate for increment in _Py_ForgetReference */
321 self->ob_type->tp_frees--;
322#endif
323#endif
324
325 return 0;
326}
327
Tim Peters6d6c1a32001-08-02 04:15:00 +0000328static void
329subtype_dealloc(PyObject *self)
330{
Guido van Rossum14227b42001-12-06 02:35:58 +0000331 PyTypeObject *type, *base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000332 destructor f;
333
334 /* This exists so we can DECREF self->ob_type */
335
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000336 if (call_finalizer(self) < 0)
337 return;
338
Tim Peters6d6c1a32001-08-02 04:15:00 +0000339 /* Find the nearest base with a different tp_dealloc */
340 type = self->ob_type;
Guido van Rossum14227b42001-12-06 02:35:58 +0000341 base = type->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000342 while ((f = base->tp_dealloc) == subtype_dealloc) {
343 base = base->tp_base;
344 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000345 }
346
347 /* Clear __slots__ variables */
348 if (type->tp_basicsize != base->tp_basicsize &&
349 type->tp_itemsize == 0)
350 {
351 char *addr = ((char *)self);
352 char *p = addr + base->tp_basicsize;
353 char *q = addr + type->tp_basicsize;
354 for (; p < q; p += sizeof(PyObject *)) {
355 PyObject **pp;
356 if (p == addr + type->tp_dictoffset ||
357 p == addr + type->tp_weaklistoffset)
358 continue;
359 pp = (PyObject **)p;
360 if (*pp != NULL) {
361 Py_DECREF(*pp);
362 *pp = NULL;
Guido van Rossum33bab012001-12-05 22:45:48 +0000363 }
364 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000365 }
366
367 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000368 if (type->tp_dictoffset && !base->tp_dictoffset) {
369 PyObject **dictptr = _PyObject_GetDictPtr(self);
370 if (dictptr != NULL) {
371 PyObject *dict = *dictptr;
372 if (dict != NULL) {
373 Py_DECREF(dict);
374 *dictptr = NULL;
375 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000376 }
377 }
378
Guido van Rossum9676b222001-08-17 20:32:36 +0000379 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000380 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000381 PyObject_ClearWeakRefs(self);
382
Tim Peters6d6c1a32001-08-02 04:15:00 +0000383 /* Finalize GC if the base doesn't do GC and we do */
384 if (PyType_IS_GC(type) && !PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000385 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000386
387 /* Call the base tp_dealloc() */
388 assert(f);
389 f(self);
390
391 /* Can't reference self beyond this point */
392 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
393 Py_DECREF(type);
394 }
395}
396
Tim Peters6d6c1a32001-08-02 04:15:00 +0000397staticforward PyTypeObject *solid_base(PyTypeObject *type);
398
399typedef struct {
400 PyTypeObject type;
401 PyNumberMethods as_number;
402 PySequenceMethods as_sequence;
403 PyMappingMethods as_mapping;
404 PyBufferProcs as_buffer;
405 PyObject *name, *slots;
Guido van Rossum6f799372001-09-20 20:46:19 +0000406 PyMemberDef members[1];
Tim Peters6d6c1a32001-08-02 04:15:00 +0000407} etype;
408
409/* type test with subclassing support */
410
411int
412PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
413{
414 PyObject *mro;
415
Guido van Rossum9478d072001-09-07 18:52:13 +0000416 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
417 return b == a || b == &PyBaseObject_Type;
418
Tim Peters6d6c1a32001-08-02 04:15:00 +0000419 mro = a->tp_mro;
420 if (mro != NULL) {
421 /* Deal with multiple inheritance without recursion
422 by walking the MRO tuple */
423 int i, n;
424 assert(PyTuple_Check(mro));
425 n = PyTuple_GET_SIZE(mro);
426 for (i = 0; i < n; i++) {
427 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
428 return 1;
429 }
430 return 0;
431 }
432 else {
433 /* a is not completely initilized yet; follow tp_base */
434 do {
435 if (a == b)
436 return 1;
437 a = a->tp_base;
438 } while (a != NULL);
439 return b == &PyBaseObject_Type;
440 }
441}
442
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000443/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000444 without looking in the instance dictionary
445 (so we can't use PyObject_GetAttr) but still binding
446 it to the instance. The arguments are the object,
447 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000448 static variable used to cache the interned Python string.
449
450 Two variants:
451
452 - lookup_maybe() returns NULL without raising an exception
453 when the _PyType_Lookup() call fails;
454
455 - lookup_method() always raises an exception upon errors.
456*/
Guido van Rossum60718732001-08-28 17:47:51 +0000457
458static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000459lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000460{
461 PyObject *res;
462
463 if (*attrobj == NULL) {
464 *attrobj = PyString_InternFromString(attrstr);
465 if (*attrobj == NULL)
466 return NULL;
467 }
468 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000469 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000470 descrgetfunc f;
471 if ((f = res->ob_type->tp_descr_get) == NULL)
472 Py_INCREF(res);
473 else
474 res = f(res, self, (PyObject *)(self->ob_type));
475 }
476 return res;
477}
478
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000479static PyObject *
480lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
481{
482 PyObject *res = lookup_maybe(self, attrstr, attrobj);
483 if (res == NULL && !PyErr_Occurred())
484 PyErr_SetObject(PyExc_AttributeError, *attrobj);
485 return res;
486}
487
Guido van Rossum2730b132001-08-28 18:22:14 +0000488/* A variation of PyObject_CallMethod that uses lookup_method()
489 instead of PyObject_GetAttrString(). This uses the same convention
490 as lookup_method to cache the interned name string object. */
491
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000492static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000493call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
494{
495 va_list va;
496 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000497 va_start(va, format);
498
Guido van Rossumda21c012001-10-03 00:50:18 +0000499 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000500 if (func == NULL) {
501 va_end(va);
502 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000503 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000504 return NULL;
505 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000506
507 if (format && *format)
508 args = Py_VaBuildValue(format, va);
509 else
510 args = PyTuple_New(0);
511
512 va_end(va);
513
514 if (args == NULL)
515 return NULL;
516
517 assert(PyTuple_Check(args));
518 retval = PyObject_Call(func, args, NULL);
519
520 Py_DECREF(args);
521 Py_DECREF(func);
522
523 return retval;
524}
525
526/* Clone of call_method() that returns NotImplemented when the lookup fails. */
527
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000528static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000529call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
530{
531 va_list va;
532 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000533 va_start(va, format);
534
Guido van Rossumda21c012001-10-03 00:50:18 +0000535 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000536 if (func == NULL) {
537 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000538 if (!PyErr_Occurred()) {
539 Py_INCREF(Py_NotImplemented);
540 return Py_NotImplemented;
541 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000542 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000543 }
544
545 if (format && *format)
546 args = Py_VaBuildValue(format, va);
547 else
548 args = PyTuple_New(0);
549
550 va_end(va);
551
Guido van Rossum717ce002001-09-14 16:58:08 +0000552 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000553 return NULL;
554
Guido van Rossum717ce002001-09-14 16:58:08 +0000555 assert(PyTuple_Check(args));
556 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000557
558 Py_DECREF(args);
559 Py_DECREF(func);
560
561 return retval;
562}
563
Tim Peters6d6c1a32001-08-02 04:15:00 +0000564/* Method resolution order algorithm from "Putting Metaclasses to Work"
565 by Forman and Danforth (Addison-Wesley 1999). */
566
567static int
568conservative_merge(PyObject *left, PyObject *right)
569{
570 int left_size;
571 int right_size;
572 int i, j, r, ok;
573 PyObject *temp, *rr;
574
575 assert(PyList_Check(left));
576 assert(PyList_Check(right));
577
578 again:
579 left_size = PyList_GET_SIZE(left);
580 right_size = PyList_GET_SIZE(right);
581 for (i = 0; i < left_size; i++) {
582 for (j = 0; j < right_size; j++) {
583 if (PyList_GET_ITEM(left, i) ==
584 PyList_GET_ITEM(right, j)) {
585 /* found a merge point */
586 temp = PyList_New(0);
587 if (temp == NULL)
588 return -1;
589 for (r = 0; r < j; r++) {
590 rr = PyList_GET_ITEM(right, r);
591 ok = PySequence_Contains(left, rr);
592 if (ok < 0) {
593 Py_DECREF(temp);
594 return -1;
595 }
596 if (!ok) {
597 ok = PyList_Append(temp, rr);
598 if (ok < 0) {
599 Py_DECREF(temp);
600 return -1;
601 }
602 }
603 }
604 ok = PyList_SetSlice(left, i, i, temp);
605 Py_DECREF(temp);
606 if (ok < 0)
607 return -1;
608 ok = PyList_SetSlice(right, 0, j+1, NULL);
609 if (ok < 0)
610 return -1;
611 goto again;
612 }
613 }
614 }
615 return PyList_SetSlice(left, left_size, left_size, right);
616}
617
618static int
619serious_order_disagreements(PyObject *left, PyObject *right)
620{
621 return 0; /* XXX later -- for now, we cheat: "don't do that" */
622}
623
Tim Petersa91e9642001-11-14 23:32:33 +0000624static int
625fill_classic_mro(PyObject *mro, PyObject *cls)
626{
627 PyObject *bases, *base;
628 int i, n;
629
630 assert(PyList_Check(mro));
631 assert(PyClass_Check(cls));
632 i = PySequence_Contains(mro, cls);
633 if (i < 0)
634 return -1;
635 if (!i) {
636 if (PyList_Append(mro, cls) < 0)
637 return -1;
638 }
639 bases = ((PyClassObject *)cls)->cl_bases;
640 assert(bases && PyTuple_Check(bases));
641 n = PyTuple_GET_SIZE(bases);
642 for (i = 0; i < n; i++) {
643 base = PyTuple_GET_ITEM(bases, i);
644 if (fill_classic_mro(mro, base) < 0)
645 return -1;
646 }
647 return 0;
648}
649
650static PyObject *
651classic_mro(PyObject *cls)
652{
653 PyObject *mro;
654
655 assert(PyClass_Check(cls));
656 mro = PyList_New(0);
657 if (mro != NULL) {
658 if (fill_classic_mro(mro, cls) == 0)
659 return mro;
660 Py_DECREF(mro);
661 }
662 return NULL;
663}
664
Tim Peters6d6c1a32001-08-02 04:15:00 +0000665static PyObject *
666mro_implementation(PyTypeObject *type)
667{
668 int i, n, ok;
669 PyObject *bases, *result;
670
671 bases = type->tp_bases;
672 n = PyTuple_GET_SIZE(bases);
673 result = Py_BuildValue("[O]", (PyObject *)type);
674 if (result == NULL)
675 return NULL;
676 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000677 PyObject *base = PyTuple_GET_ITEM(bases, i);
678 PyObject *parentMRO;
679 if (PyType_Check(base))
680 parentMRO = PySequence_List(
681 ((PyTypeObject*)base)->tp_mro);
682 else
683 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000684 if (parentMRO == NULL) {
685 Py_DECREF(result);
686 return NULL;
687 }
688 if (serious_order_disagreements(result, parentMRO)) {
689 Py_DECREF(result);
690 return NULL;
691 }
692 ok = conservative_merge(result, parentMRO);
693 Py_DECREF(parentMRO);
694 if (ok < 0) {
695 Py_DECREF(result);
696 return NULL;
697 }
698 }
699 return result;
700}
701
702static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000703mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000704{
705 PyTypeObject *type = (PyTypeObject *)self;
706
Tim Peters6d6c1a32001-08-02 04:15:00 +0000707 return mro_implementation(type);
708}
709
710static int
711mro_internal(PyTypeObject *type)
712{
713 PyObject *mro, *result, *tuple;
714
715 if (type->ob_type == &PyType_Type) {
716 result = mro_implementation(type);
717 }
718 else {
Guido van Rossum60718732001-08-28 17:47:51 +0000719 static PyObject *mro_str;
720 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000721 if (mro == NULL)
722 return -1;
723 result = PyObject_CallObject(mro, NULL);
724 Py_DECREF(mro);
725 }
726 if (result == NULL)
727 return -1;
728 tuple = PySequence_Tuple(result);
729 Py_DECREF(result);
730 type->tp_mro = tuple;
731 return 0;
732}
733
734
735/* Calculate the best base amongst multiple base classes.
736 This is the first one that's on the path to the "solid base". */
737
738static PyTypeObject *
739best_base(PyObject *bases)
740{
741 int i, n;
742 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +0000743 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000744
745 assert(PyTuple_Check(bases));
746 n = PyTuple_GET_SIZE(bases);
747 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +0000748 base = NULL;
749 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000750 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +0000751 base_proto = PyTuple_GET_ITEM(bases, i);
752 if (PyClass_Check(base_proto))
753 continue;
754 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000755 PyErr_SetString(
756 PyExc_TypeError,
757 "bases must be types");
758 return NULL;
759 }
Tim Petersa91e9642001-11-14 23:32:33 +0000760 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000761 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000762 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000763 return NULL;
764 }
765 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +0000766 if (winner == NULL) {
767 winner = candidate;
768 base = base_i;
769 }
770 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000771 ;
772 else if (PyType_IsSubtype(candidate, winner)) {
773 winner = candidate;
774 base = base_i;
775 }
776 else {
777 PyErr_SetString(
778 PyExc_TypeError,
779 "multiple bases have "
780 "instance lay-out conflict");
781 return NULL;
782 }
783 }
Guido van Rossume54616c2001-12-14 04:19:56 +0000784 if (base == NULL)
785 PyErr_SetString(PyExc_TypeError,
786 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000787 return base;
788}
789
790static int
791extra_ivars(PyTypeObject *type, PyTypeObject *base)
792{
Neil Schemenauerc806c882001-08-29 23:54:54 +0000793 size_t t_size = type->tp_basicsize;
794 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000795
Guido van Rossum9676b222001-08-17 20:32:36 +0000796 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000797 if (type->tp_itemsize || base->tp_itemsize) {
798 /* If itemsize is involved, stricter rules */
799 return t_size != b_size ||
800 type->tp_itemsize != base->tp_itemsize;
801 }
Guido van Rossum9676b222001-08-17 20:32:36 +0000802 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
803 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
804 t_size -= sizeof(PyObject *);
805 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
806 type->tp_dictoffset + sizeof(PyObject *) == t_size)
807 t_size -= sizeof(PyObject *);
808
809 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000810}
811
812static PyTypeObject *
813solid_base(PyTypeObject *type)
814{
815 PyTypeObject *base;
816
817 if (type->tp_base)
818 base = solid_base(type->tp_base);
819 else
820 base = &PyBaseObject_Type;
821 if (extra_ivars(type, base))
822 return type;
823 else
824 return base;
825}
826
827staticforward void object_dealloc(PyObject *);
828staticforward int object_init(PyObject *, PyObject *, PyObject *);
Guido van Rossum875eeaa2001-10-11 18:33:53 +0000829staticforward int update_slot(PyTypeObject *, PyObject *);
Guido van Rossum7b9144b2001-10-09 19:39:46 +0000830staticforward void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831
832static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000833subtype_dict(PyObject *obj, void *context)
834{
835 PyObject **dictptr = _PyObject_GetDictPtr(obj);
836 PyObject *dict;
837
838 if (dictptr == NULL) {
839 PyErr_SetString(PyExc_AttributeError,
840 "This object has no __dict__");
841 return NULL;
842 }
843 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +0000844 if (dict == NULL)
845 *dictptr = dict = PyDict_New();
846 Py_XINCREF(dict);
847 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000848}
849
Guido van Rossum6661be32001-10-26 04:26:12 +0000850static int
851subtype_setdict(PyObject *obj, PyObject *value, void *context)
852{
853 PyObject **dictptr = _PyObject_GetDictPtr(obj);
854 PyObject *dict;
855
856 if (dictptr == NULL) {
857 PyErr_SetString(PyExc_AttributeError,
858 "This object has no __dict__");
859 return -1;
860 }
Guido van Rossumd331cb52001-12-05 19:46:42 +0000861 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +0000862 PyErr_SetString(PyExc_TypeError,
863 "__dict__ must be set to a dictionary");
864 return -1;
865 }
866 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +0000867 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +0000868 *dictptr = value;
869 Py_XDECREF(dict);
870 return 0;
871}
872
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000873static PyGetSetDef subtype_getsets[] = {
Guido van Rossum6661be32001-10-26 04:26:12 +0000874 {"__dict__", subtype_dict, subtype_setdict, NULL},
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000875 {0},
876};
877
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000878/* bozo: __getstate__ that raises TypeError */
879
880static PyObject *
881bozo_func(PyObject *self, PyObject *args)
882{
883 PyErr_SetString(PyExc_TypeError,
884 "a class that defines __slots__ without "
885 "defining __getstate__ cannot be pickled");
886 return NULL;
887}
888
Neal Norwitz93c1e232002-03-31 16:06:11 +0000889static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +0000890
891static PyObject *bozo_obj = NULL;
892
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000893static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000894type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
895{
896 PyObject *name, *bases, *dict;
897 static char *kwlist[] = {"name", "bases", "dict", 0};
898 PyObject *slots, *tmp;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000899 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000900 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +0000901 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +0000902 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000903
Tim Peters3abca122001-10-27 19:37:48 +0000904 assert(args != NULL && PyTuple_Check(args));
905 assert(kwds == NULL || PyDict_Check(kwds));
906
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000907 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +0000908 {
909 const int nargs = PyTuple_GET_SIZE(args);
910 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
911
912 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
913 PyObject *x = PyTuple_GET_ITEM(args, 0);
914 Py_INCREF(x->ob_type);
915 return (PyObject *) x->ob_type;
916 }
917
918 /* SF bug 475327 -- if that didn't trigger, we need 3
919 arguments. but PyArg_ParseTupleAndKeywords below may give
920 a msg saying type() needs exactly 3. */
921 if (nargs + nkwds != 3) {
922 PyErr_SetString(PyExc_TypeError,
923 "type() takes 1 or 3 arguments");
924 return NULL;
925 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000926 }
927
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000928 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000929 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
930 &name,
931 &PyTuple_Type, &bases,
932 &PyDict_Type, &dict))
933 return NULL;
934
935 /* Determine the proper metatype to deal with this,
936 and check for metatype conflicts while we're at it.
937 Note that if some other metatype wins to contract,
938 it's possible that its instances are not types. */
939 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000940 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000941 for (i = 0; i < nbases; i++) {
942 tmp = PyTuple_GET_ITEM(bases, i);
943 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +0000944 if (tmptype == &PyClass_Type)
945 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000946 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000947 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000948 if (PyType_IsSubtype(tmptype, winner)) {
949 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000950 continue;
951 }
952 PyErr_SetString(PyExc_TypeError,
953 "metatype conflict among bases");
954 return NULL;
955 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +0000956 if (winner != metatype) {
957 if (winner->tp_new != type_new) /* Pass it to the winner */
958 return winner->tp_new(winner, args, kwds);
959 metatype = winner;
960 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000961
962 /* Adjust for empty tuple bases */
963 if (nbases == 0) {
964 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
965 if (bases == NULL)
966 return NULL;
967 nbases = 1;
968 }
969 else
970 Py_INCREF(bases);
971
972 /* XXX From here until type is allocated, "return NULL" leaks bases! */
973
974 /* Calculate best base, and check that all bases are type objects */
975 base = best_base(bases);
976 if (base == NULL)
977 return NULL;
978 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
979 PyErr_Format(PyExc_TypeError,
980 "type '%.100s' is not an acceptable base type",
981 base->tp_name);
982 return NULL;
983 }
984
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985 /* Check for a __slots__ sequence variable in dict, and count it */
986 slots = PyDict_GetItemString(dict, "__slots__");
987 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +0000988 add_dict = 0;
989 add_weak = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000990 if (slots != NULL) {
991 /* Make it into a tuple */
992 if (PyString_Check(slots))
993 slots = Py_BuildValue("(O)", slots);
994 else
995 slots = PySequence_Tuple(slots);
996 if (slots == NULL)
997 return NULL;
998 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +0000999 if (nslots > 0 && base->tp_itemsize != 0) {
1000 PyErr_Format(PyExc_TypeError,
1001 "nonempty __slots__ "
1002 "not supported for subtype of '%s'",
1003 base->tp_name);
1004 return NULL;
1005 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001006 for (i = 0; i < nslots; i++) {
1007 if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
1008 PyErr_SetString(PyExc_TypeError,
1009 "__slots__ must be a sequence of strings");
1010 Py_DECREF(slots);
1011 return NULL;
1012 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001013 /* XXX Check against null bytes in name */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014 }
1015 }
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001016 if (slots != NULL) {
1017 /* See if *this* class defines __getstate__ */
1018 PyObject *getstate = PyDict_GetItemString(dict,
1019 "__getstate__");
1020 if (getstate == NULL) {
1021 /* If not, provide a bozo that raises TypeError */
1022 if (bozo_obj == NULL) {
1023 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
1024 if (bozo_obj == NULL) {
1025 /* XXX decref various things */
1026 return NULL;
1027 }
1028 }
1029 if (PyDict_SetItemString(dict,
1030 "__getstate__",
1031 bozo_obj) < 0) {
1032 /* XXX decref various things */
1033 return NULL;
1034 }
1035 }
1036 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001037 if (slots == NULL && base->tp_dictoffset == 0 &&
1038 (base->tp_setattro == PyObject_GenericSetAttr ||
Guido van Rossum9676b222001-08-17 20:32:36 +00001039 base->tp_setattro == NULL)) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001040 add_dict++;
1041 }
Guido van Rossumc4141872001-08-30 04:43:35 +00001042 if (slots == NULL && base->tp_weaklistoffset == 0 &&
1043 base->tp_itemsize == 0) {
Guido van Rossum9676b222001-08-17 20:32:36 +00001044 nslots++;
1045 add_weak++;
1046 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047
1048 /* XXX From here until type is safely allocated,
1049 "return NULL" may leak slots! */
1050
1051 /* Allocate the type object */
1052 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1053 if (type == NULL)
1054 return NULL;
1055
1056 /* Keep name and slots alive in the extended type object */
1057 et = (etype *)type;
1058 Py_INCREF(name);
1059 et->name = name;
1060 et->slots = slots;
1061
Guido van Rossumdc91b992001-08-08 22:26:22 +00001062 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001063 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1064 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001065 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1066 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001067
1068 /* It's a new-style number unless it specifically inherits any
1069 old-style numeric behavior */
1070 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1071 (base->tp_as_number == NULL))
1072 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1073
1074 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075 type->tp_as_number = &et->as_number;
1076 type->tp_as_sequence = &et->as_sequence;
1077 type->tp_as_mapping = &et->as_mapping;
1078 type->tp_as_buffer = &et->as_buffer;
1079 type->tp_name = PyString_AS_STRING(name);
1080
1081 /* Set tp_base and tp_bases */
1082 type->tp_bases = bases;
1083 Py_INCREF(base);
1084 type->tp_base = base;
1085
Guido van Rossum687ae002001-10-15 22:03:32 +00001086 /* Initialize tp_dict from passed-in dict */
1087 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001088 if (dict == NULL) {
1089 Py_DECREF(type);
1090 return NULL;
1091 }
1092
Guido van Rossumc3542212001-08-16 09:18:56 +00001093 /* Set __module__ in the dict */
1094 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1095 tmp = PyEval_GetGlobals();
1096 if (tmp != NULL) {
1097 tmp = PyDict_GetItemString(tmp, "__name__");
1098 if (tmp != NULL) {
1099 if (PyDict_SetItemString(dict, "__module__",
1100 tmp) < 0)
1101 return NULL;
1102 }
1103 }
1104 }
1105
Tim Peters2f93e282001-10-04 05:27:00 +00001106 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001107 and is a string. The __doc__ accessor will first look for tp_doc;
1108 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001109 */
1110 {
1111 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1112 if (doc != NULL && PyString_Check(doc)) {
1113 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001114 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001115 if (type->tp_doc == NULL) {
1116 Py_DECREF(type);
1117 return NULL;
1118 }
1119 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1120 }
1121 }
1122
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 /* Special-case __new__: if it's a plain function,
1124 make it a static function */
1125 tmp = PyDict_GetItemString(dict, "__new__");
1126 if (tmp != NULL && PyFunction_Check(tmp)) {
1127 tmp = PyStaticMethod_New(tmp);
1128 if (tmp == NULL) {
1129 Py_DECREF(type);
1130 return NULL;
1131 }
1132 PyDict_SetItemString(dict, "__new__", tmp);
1133 Py_DECREF(tmp);
1134 }
1135
1136 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1137 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001138 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139 if (slots != NULL) {
1140 for (i = 0; i < nslots; i++, mp++) {
1141 mp->name = PyString_AS_STRING(
1142 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001143 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001144 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001145 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001146 strcmp(mp->name, "__weakref__") == 0) {
1147 mp->type = T_OBJECT;
Guido van Rossum9676b222001-08-17 20:32:36 +00001148 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001149 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001150 slotoffset += sizeof(PyObject *);
1151 }
1152 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001153 else {
1154 if (add_dict) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001155 if (base->tp_itemsize)
Guido van Rossum048eb752001-10-02 21:24:57 +00001156 type->tp_dictoffset =
1157 -(long)sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001158 else
1159 type->tp_dictoffset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001160 slotoffset += sizeof(PyObject *);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001161 type->tp_getset = subtype_getsets;
Guido van Rossum9676b222001-08-17 20:32:36 +00001162 }
1163 if (add_weak) {
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001164 assert(!base->tp_itemsize);
Guido van Rossum9676b222001-08-17 20:32:36 +00001165 type->tp_weaklistoffset = slotoffset;
1166 mp->name = "__weakref__";
1167 mp->type = T_OBJECT;
1168 mp->offset = slotoffset;
Tim Peters26f68f52001-09-18 00:23:33 +00001169 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001170 mp++;
1171 slotoffset += sizeof(PyObject *);
1172 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173 }
1174 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001175 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001176 type->tp_members = et->members;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177
1178 /* Special case some slots */
1179 if (type->tp_dictoffset != 0 || nslots > 0) {
1180 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1181 type->tp_getattro = PyObject_GenericGetAttr;
1182 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1183 type->tp_setattro = PyObject_GenericSetAttr;
1184 }
1185 type->tp_dealloc = subtype_dealloc;
1186
Guido van Rossum9475a232001-10-05 20:51:39 +00001187 /* Enable GC unless there are really no instance variables possible */
1188 if (!(type->tp_basicsize == sizeof(PyObject) &&
1189 type->tp_itemsize == 0))
1190 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1191
Tim Peters6d6c1a32001-08-02 04:15:00 +00001192 /* Always override allocation strategy to use regular heap */
1193 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001194 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001195 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001196 type->tp_traverse = subtype_traverse;
Guido van Rossum048eb752001-10-02 21:24:57 +00001197 type->tp_clear = base->tp_clear;
1198 }
1199 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001200 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001201
1202 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001203 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001204 Py_DECREF(type);
1205 return NULL;
1206 }
1207
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001208 /* Put the proper slots in place */
1209 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001210
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211 return (PyObject *)type;
1212}
1213
1214/* Internal API to look for a name through the MRO.
1215 This returns a borrowed reference, and doesn't set an exception! */
1216PyObject *
1217_PyType_Lookup(PyTypeObject *type, PyObject *name)
1218{
1219 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001220 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221
Guido van Rossum687ae002001-10-15 22:03:32 +00001222 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001223 mro = type->tp_mro;
1224 assert(PyTuple_Check(mro));
1225 n = PyTuple_GET_SIZE(mro);
1226 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001227 base = PyTuple_GET_ITEM(mro, i);
1228 if (PyClass_Check(base))
1229 dict = ((PyClassObject *)base)->cl_dict;
1230 else {
1231 assert(PyType_Check(base));
1232 dict = ((PyTypeObject *)base)->tp_dict;
1233 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001234 assert(dict && PyDict_Check(dict));
1235 res = PyDict_GetItem(dict, name);
1236 if (res != NULL)
1237 return res;
1238 }
1239 return NULL;
1240}
1241
1242/* This is similar to PyObject_GenericGetAttr(),
1243 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1244static PyObject *
1245type_getattro(PyTypeObject *type, PyObject *name)
1246{
1247 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001248 PyObject *meta_attribute, *attribute;
1249 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001250
1251 /* Initialize this type (we'll assume the metatype is initialized) */
1252 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001253 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001254 return NULL;
1255 }
1256
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001257 /* No readable descriptor found yet */
1258 meta_get = NULL;
1259
1260 /* Look for the attribute in the metatype */
1261 meta_attribute = _PyType_Lookup(metatype, name);
1262
1263 if (meta_attribute != NULL) {
1264 meta_get = meta_attribute->ob_type->tp_descr_get;
1265
1266 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1267 /* Data descriptors implement tp_descr_set to intercept
1268 * writes. Assume the attribute is not overridden in
1269 * type's tp_dict (and bases): call the descriptor now.
1270 */
1271 return meta_get(meta_attribute, (PyObject *)type,
1272 (PyObject *)metatype);
1273 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001274 }
1275
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001276 /* No data descriptor found on metatype. Look in tp_dict of this
1277 * type and its bases */
1278 attribute = _PyType_Lookup(type, name);
1279 if (attribute != NULL) {
1280 /* Implement descriptor functionality, if any */
1281 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1282 if (local_get != NULL) {
1283 /* NULL 2nd argument indicates the descriptor was
1284 * found on the target object itself (or a base) */
1285 return local_get(attribute, (PyObject *)NULL,
1286 (PyObject *)type);
1287 }
1288
1289 Py_INCREF(attribute);
1290 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291 }
1292
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001293 /* No attribute found in local __dict__ (or bases): use the
1294 * descriptor from the metatype, if any */
1295 if (meta_get != NULL)
1296 return meta_get(meta_attribute, (PyObject *)type,
1297 (PyObject *)metatype);
1298
1299 /* If an ordinary attribute was found on the metatype, return it now */
1300 if (meta_attribute != NULL) {
1301 Py_INCREF(meta_attribute);
1302 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 }
1304
1305 /* Give up */
1306 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001307 "type object '%.50s' has no attribute '%.400s'",
1308 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001309 return NULL;
1310}
1311
1312static int
1313type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1314{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001315 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1316 PyErr_Format(
1317 PyExc_TypeError,
1318 "can't set attributes of built-in/extension type '%s'",
1319 type->tp_name);
1320 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001321 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001322 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1323 return -1;
1324 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325}
1326
1327static void
1328type_dealloc(PyTypeObject *type)
1329{
1330 etype *et;
1331
1332 /* Assert this is a heap-allocated type object */
1333 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001334 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001335 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001336 et = (etype *)type;
1337 Py_XDECREF(type->tp_base);
1338 Py_XDECREF(type->tp_dict);
1339 Py_XDECREF(type->tp_bases);
1340 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001341 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001342 Py_XDECREF(type->tp_subclasses);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001343 Py_XDECREF(et->name);
1344 Py_XDECREF(et->slots);
1345 type->ob_type->tp_free((PyObject *)type);
1346}
1347
Guido van Rossum1c450732001-10-08 15:18:27 +00001348static PyObject *
1349type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1350{
1351 PyObject *list, *raw, *ref;
1352 int i, n;
1353
1354 list = PyList_New(0);
1355 if (list == NULL)
1356 return NULL;
1357 raw = type->tp_subclasses;
1358 if (raw == NULL)
1359 return list;
1360 assert(PyList_Check(raw));
1361 n = PyList_GET_SIZE(raw);
1362 for (i = 0; i < n; i++) {
1363 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001364 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001365 ref = PyWeakref_GET_OBJECT(ref);
1366 if (ref != Py_None) {
1367 if (PyList_Append(list, ref) < 0) {
1368 Py_DECREF(list);
1369 return NULL;
1370 }
1371 }
1372 }
1373 return list;
1374}
1375
Tim Peters6d6c1a32001-08-02 04:15:00 +00001376static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001377 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001378 "mro() -> list\nreturn a type's method resolution order"},
Guido van Rossum1c450732001-10-08 15:18:27 +00001379 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
1380 "__subclasses__() -> list of immediate subclasses"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001381 {0}
1382};
1383
1384static char type_doc[] =
1385"type(object) -> the object's type\n"
1386"type(name, bases, dict) -> a new type";
1387
Guido van Rossum048eb752001-10-02 21:24:57 +00001388static int
1389type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1390{
1391 etype *et;
1392 int err;
1393
1394 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1395 return 0;
1396
1397 et = (etype *)type;
1398
1399#define VISIT(SLOT) \
1400 if (SLOT) { \
1401 err = visit((PyObject *)(SLOT), arg); \
1402 if (err) \
1403 return err; \
1404 }
1405
1406 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001407 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001408 VISIT(type->tp_mro);
1409 VISIT(type->tp_bases);
1410 VISIT(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001411 VISIT(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001412 VISIT(et->slots);
1413
1414#undef VISIT
1415
1416 return 0;
1417}
1418
1419static int
1420type_clear(PyTypeObject *type)
1421{
1422 etype *et;
1423 PyObject *tmp;
1424
1425 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1426 return 0;
1427
1428 et = (etype *)type;
1429
1430#define CLEAR(SLOT) \
1431 if (SLOT) { \
1432 tmp = (PyObject *)(SLOT); \
1433 SLOT = NULL; \
1434 Py_DECREF(tmp); \
1435 }
1436
1437 CLEAR(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00001438 CLEAR(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00001439 CLEAR(type->tp_mro);
1440 CLEAR(type->tp_bases);
1441 CLEAR(type->tp_base);
Guido van Rossum1c450732001-10-08 15:18:27 +00001442 CLEAR(type->tp_subclasses);
Guido van Rossum048eb752001-10-02 21:24:57 +00001443 CLEAR(et->slots);
1444
Tim Peters2f93e282001-10-04 05:27:00 +00001445 if (type->tp_doc != NULL) {
1446 PyObject_FREE(type->tp_doc);
1447 type->tp_doc = NULL;
1448 }
1449
Guido van Rossum048eb752001-10-02 21:24:57 +00001450#undef CLEAR
1451
1452 return 0;
1453}
1454
1455static int
1456type_is_gc(PyTypeObject *type)
1457{
1458 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
1459}
1460
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001461PyTypeObject PyType_Type = {
1462 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463 0, /* ob_size */
1464 "type", /* tp_name */
1465 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00001466 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001467 (destructor)type_dealloc, /* tp_dealloc */
1468 0, /* tp_print */
1469 0, /* tp_getattr */
1470 0, /* tp_setattr */
1471 type_compare, /* tp_compare */
1472 (reprfunc)type_repr, /* tp_repr */
1473 0, /* tp_as_number */
1474 0, /* tp_as_sequence */
1475 0, /* tp_as_mapping */
1476 (hashfunc)_Py_HashPointer, /* tp_hash */
1477 (ternaryfunc)type_call, /* tp_call */
1478 0, /* tp_str */
1479 (getattrofunc)type_getattro, /* tp_getattro */
1480 (setattrofunc)type_setattro, /* tp_setattro */
1481 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00001482 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1483 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00001485 (traverseproc)type_traverse, /* tp_traverse */
1486 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001487 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00001488 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001489 0, /* tp_iter */
1490 0, /* tp_iternext */
1491 type_methods, /* tp_methods */
1492 type_members, /* tp_members */
1493 type_getsets, /* tp_getset */
1494 0, /* tp_base */
1495 0, /* tp_dict */
1496 0, /* tp_descr_get */
1497 0, /* tp_descr_set */
1498 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
1499 0, /* tp_init */
1500 0, /* tp_alloc */
1501 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001502 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00001503 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001504};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001505
1506
1507/* The base type of all types (eventually)... except itself. */
1508
1509static int
1510object_init(PyObject *self, PyObject *args, PyObject *kwds)
1511{
1512 return 0;
1513}
1514
1515static void
1516object_dealloc(PyObject *self)
1517{
1518 self->ob_type->tp_free(self);
1519}
1520
Guido van Rossum8e248182001-08-12 05:17:56 +00001521static PyObject *
1522object_repr(PyObject *self)
1523{
Guido van Rossum76e69632001-08-16 18:52:43 +00001524 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00001525 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001526
Guido van Rossum76e69632001-08-16 18:52:43 +00001527 type = self->ob_type;
1528 mod = type_module(type, NULL);
1529 if (mod == NULL)
1530 PyErr_Clear();
1531 else if (!PyString_Check(mod)) {
1532 Py_DECREF(mod);
1533 mod = NULL;
1534 }
1535 name = type_name(type, NULL);
1536 if (name == NULL)
1537 return NULL;
1538 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001539 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001540 PyString_AS_STRING(mod),
1541 PyString_AS_STRING(name),
1542 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001543 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00001544 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00001545 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00001546 Py_XDECREF(mod);
1547 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00001548 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00001549}
1550
Guido van Rossumb8f63662001-08-15 23:57:02 +00001551static PyObject *
1552object_str(PyObject *self)
1553{
1554 unaryfunc f;
1555
1556 f = self->ob_type->tp_repr;
1557 if (f == NULL)
1558 f = object_repr;
1559 return f(self);
1560}
1561
Guido van Rossum8e248182001-08-12 05:17:56 +00001562static long
1563object_hash(PyObject *self)
1564{
1565 return _Py_HashPointer(self);
1566}
Guido van Rossum8e248182001-08-12 05:17:56 +00001567
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001568static PyObject *
1569object_get_class(PyObject *self, void *closure)
1570{
1571 Py_INCREF(self->ob_type);
1572 return (PyObject *)(self->ob_type);
1573}
1574
1575static int
1576equiv_structs(PyTypeObject *a, PyTypeObject *b)
1577{
1578 return a == b ||
1579 (a != NULL &&
1580 b != NULL &&
1581 a->tp_basicsize == b->tp_basicsize &&
1582 a->tp_itemsize == b->tp_itemsize &&
1583 a->tp_dictoffset == b->tp_dictoffset &&
1584 a->tp_weaklistoffset == b->tp_weaklistoffset &&
1585 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
1586 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
1587}
1588
1589static int
1590same_slots_added(PyTypeObject *a, PyTypeObject *b)
1591{
1592 PyTypeObject *base = a->tp_base;
1593 int size;
1594
1595 if (base != b->tp_base)
1596 return 0;
1597 if (equiv_structs(a, base) && equiv_structs(b, base))
1598 return 1;
1599 size = base->tp_basicsize;
1600 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
1601 size += sizeof(PyObject *);
1602 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
1603 size += sizeof(PyObject *);
1604 return size == a->tp_basicsize && size == b->tp_basicsize;
1605}
1606
1607static int
1608object_set_class(PyObject *self, PyObject *value, void *closure)
1609{
1610 PyTypeObject *old = self->ob_type;
1611 PyTypeObject *new, *newbase, *oldbase;
1612
Guido van Rossumb6b89422002-04-15 01:03:30 +00001613 if (value == NULL) {
1614 PyErr_SetString(PyExc_TypeError,
1615 "can't delete __class__ attribute");
1616 return -1;
1617 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001618 if (!PyType_Check(value)) {
1619 PyErr_Format(PyExc_TypeError,
1620 "__class__ must be set to new-style class, not '%s' object",
1621 value->ob_type->tp_name);
1622 return -1;
1623 }
1624 new = (PyTypeObject *)value;
1625 newbase = new;
1626 oldbase = old;
1627 while (equiv_structs(newbase, newbase->tp_base))
1628 newbase = newbase->tp_base;
1629 while (equiv_structs(oldbase, oldbase->tp_base))
1630 oldbase = oldbase->tp_base;
1631 if (newbase != oldbase &&
1632 (newbase->tp_base != oldbase->tp_base ||
1633 !same_slots_added(newbase, oldbase))) {
1634 PyErr_Format(PyExc_TypeError,
1635 "__class__ assignment: "
1636 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001637 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001638 old->tp_name);
1639 return -1;
1640 }
1641 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1642 Py_INCREF(new);
1643 }
1644 self->ob_type = new;
1645 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1646 Py_DECREF(old);
1647 }
1648 return 0;
1649}
1650
1651static PyGetSetDef object_getsets[] = {
1652 {"__class__", object_get_class, object_set_class,
1653 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001654 {0}
1655};
1656
Guido van Rossum3926a632001-09-25 16:25:58 +00001657static PyObject *
1658object_reduce(PyObject *self, PyObject *args)
1659{
1660 /* Call copy_reg._reduce(self) */
1661 static PyObject *copy_reg_str;
1662 PyObject *copy_reg, *res;
1663
1664 if (!copy_reg_str) {
1665 copy_reg_str = PyString_InternFromString("copy_reg");
1666 if (copy_reg_str == NULL)
1667 return NULL;
1668 }
1669 copy_reg = PyImport_Import(copy_reg_str);
1670 if (!copy_reg)
1671 return NULL;
1672 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1673 Py_DECREF(copy_reg);
1674 return res;
1675}
1676
1677static PyMethodDef object_methods[] = {
1678 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1679 {0}
1680};
1681
Tim Peters6d6c1a32001-08-02 04:15:00 +00001682PyTypeObject PyBaseObject_Type = {
1683 PyObject_HEAD_INIT(&PyType_Type)
1684 0, /* ob_size */
1685 "object", /* tp_name */
1686 sizeof(PyObject), /* tp_basicsize */
1687 0, /* tp_itemsize */
1688 (destructor)object_dealloc, /* tp_dealloc */
1689 0, /* tp_print */
1690 0, /* tp_getattr */
1691 0, /* tp_setattr */
1692 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001693 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001694 0, /* tp_as_number */
1695 0, /* tp_as_sequence */
1696 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001697 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001699 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001700 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001701 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001702 0, /* tp_as_buffer */
1703 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1704 "The most base type", /* tp_doc */
1705 0, /* tp_traverse */
1706 0, /* tp_clear */
1707 0, /* tp_richcompare */
1708 0, /* tp_weaklistoffset */
1709 0, /* tp_iter */
1710 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001711 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001712 0, /* tp_members */
1713 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001714 0, /* tp_base */
1715 0, /* tp_dict */
1716 0, /* tp_descr_get */
1717 0, /* tp_descr_set */
1718 0, /* tp_dictoffset */
1719 object_init, /* tp_init */
1720 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001721 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001722 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001723};
1724
1725
1726/* Initialize the __dict__ in a type object */
1727
Fred Drake7bf97152002-03-28 05:33:33 +00001728static PyObject *
1729create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1730{
1731 PyObject *cfunc;
1732 PyObject *result;
1733
1734 cfunc = PyCFunction_New(meth, NULL);
1735 if (cfunc == NULL)
1736 return NULL;
1737 result = func(cfunc);
1738 Py_DECREF(cfunc);
1739 return result;
1740}
1741
Tim Peters6d6c1a32001-08-02 04:15:00 +00001742static int
1743add_methods(PyTypeObject *type, PyMethodDef *meth)
1744{
Guido van Rossum687ae002001-10-15 22:03:32 +00001745 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001746
1747 for (; meth->ml_name != NULL; meth++) {
1748 PyObject *descr;
1749 if (PyDict_GetItemString(dict, meth->ml_name))
1750 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001751 if (meth->ml_flags & METH_CLASS) {
1752 if (meth->ml_flags & METH_STATIC) {
1753 PyErr_SetString(PyExc_ValueError,
1754 "method cannot be both class and static");
1755 return -1;
1756 }
1757 descr = create_specialmethod(meth, PyClassMethod_New);
1758 }
1759 else if (meth->ml_flags & METH_STATIC) {
1760 descr = create_specialmethod(meth, PyStaticMethod_New);
1761 }
1762 else {
1763 descr = PyDescr_NewMethod(type, meth);
1764 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001765 if (descr == NULL)
1766 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001767 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768 return -1;
1769 Py_DECREF(descr);
1770 }
1771 return 0;
1772}
1773
1774static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001775add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776{
Guido van Rossum687ae002001-10-15 22:03:32 +00001777 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778
1779 for (; memb->name != NULL; memb++) {
1780 PyObject *descr;
1781 if (PyDict_GetItemString(dict, memb->name))
1782 continue;
1783 descr = PyDescr_NewMember(type, memb);
1784 if (descr == NULL)
1785 return -1;
1786 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1787 return -1;
1788 Py_DECREF(descr);
1789 }
1790 return 0;
1791}
1792
1793static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001794add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795{
Guido van Rossum687ae002001-10-15 22:03:32 +00001796 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001797
1798 for (; gsp->name != NULL; gsp++) {
1799 PyObject *descr;
1800 if (PyDict_GetItemString(dict, gsp->name))
1801 continue;
1802 descr = PyDescr_NewGetSet(type, gsp);
1803
1804 if (descr == NULL)
1805 return -1;
1806 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1807 return -1;
1808 Py_DECREF(descr);
1809 }
1810 return 0;
1811}
1812
Guido van Rossum13d52f02001-08-10 21:24:08 +00001813static void
1814inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815{
1816 int oldsize, newsize;
1817
Guido van Rossum13d52f02001-08-10 21:24:08 +00001818 /* Special flag magic */
1819 if (!type->tp_as_buffer && base->tp_as_buffer) {
1820 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1821 type->tp_flags |=
1822 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1823 }
1824 if (!type->tp_as_sequence && base->tp_as_sequence) {
1825 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1826 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1827 }
1828 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1829 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1830 if ((!type->tp_as_number && base->tp_as_number) ||
1831 (!type->tp_as_sequence && base->tp_as_sequence)) {
1832 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1833 if (!type->tp_as_number && !type->tp_as_sequence) {
1834 type->tp_flags |= base->tp_flags &
1835 Py_TPFLAGS_HAVE_INPLACEOPS;
1836 }
1837 }
1838 /* Wow */
1839 }
1840 if (!type->tp_as_number && base->tp_as_number) {
1841 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1842 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1843 }
1844
1845 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001846 oldsize = base->tp_basicsize;
1847 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1848 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1849 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001850 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1851 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001852 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001853 if (type->tp_traverse == NULL)
1854 type->tp_traverse = base->tp_traverse;
1855 if (type->tp_clear == NULL)
1856 type->tp_clear = base->tp_clear;
1857 }
1858 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001859 /* The condition below could use some explanation.
1860 It appears that tp_new is not inherited for static types
1861 whose base class is 'object'; this seems to be a precaution
1862 so that old extension types don't suddenly become
1863 callable (object.__new__ wouldn't insure the invariants
1864 that the extension type's own factory function ensures).
1865 Heap types, of course, are under our control, so they do
1866 inherit tp_new; static extension types that specify some
1867 other built-in type as the default are considered
1868 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001869 if (base != &PyBaseObject_Type ||
1870 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1871 if (type->tp_new == NULL)
1872 type->tp_new = base->tp_new;
1873 }
1874 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001875 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001876
1877 /* Copy other non-function slots */
1878
1879#undef COPYVAL
1880#define COPYVAL(SLOT) \
1881 if (type->SLOT == 0) type->SLOT = base->SLOT
1882
1883 COPYVAL(tp_itemsize);
1884 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1885 COPYVAL(tp_weaklistoffset);
1886 }
1887 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1888 COPYVAL(tp_dictoffset);
1889 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001890}
1891
1892static void
1893inherit_slots(PyTypeObject *type, PyTypeObject *base)
1894{
1895 PyTypeObject *basebase;
1896
1897#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001898#undef COPYSLOT
1899#undef COPYNUM
1900#undef COPYSEQ
1901#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001902#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001903
1904#define SLOTDEFINED(SLOT) \
1905 (base->SLOT != 0 && \
1906 (basebase == NULL || base->SLOT != basebase->SLOT))
1907
Tim Peters6d6c1a32001-08-02 04:15:00 +00001908#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001909 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910
1911#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1912#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1913#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001914#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001915
Guido van Rossum13d52f02001-08-10 21:24:08 +00001916 /* This won't inherit indirect slots (from tp_as_number etc.)
1917 if type doesn't provide the space. */
1918
1919 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1920 basebase = base->tp_base;
1921 if (basebase->tp_as_number == NULL)
1922 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001923 COPYNUM(nb_add);
1924 COPYNUM(nb_subtract);
1925 COPYNUM(nb_multiply);
1926 COPYNUM(nb_divide);
1927 COPYNUM(nb_remainder);
1928 COPYNUM(nb_divmod);
1929 COPYNUM(nb_power);
1930 COPYNUM(nb_negative);
1931 COPYNUM(nb_positive);
1932 COPYNUM(nb_absolute);
1933 COPYNUM(nb_nonzero);
1934 COPYNUM(nb_invert);
1935 COPYNUM(nb_lshift);
1936 COPYNUM(nb_rshift);
1937 COPYNUM(nb_and);
1938 COPYNUM(nb_xor);
1939 COPYNUM(nb_or);
1940 COPYNUM(nb_coerce);
1941 COPYNUM(nb_int);
1942 COPYNUM(nb_long);
1943 COPYNUM(nb_float);
1944 COPYNUM(nb_oct);
1945 COPYNUM(nb_hex);
1946 COPYNUM(nb_inplace_add);
1947 COPYNUM(nb_inplace_subtract);
1948 COPYNUM(nb_inplace_multiply);
1949 COPYNUM(nb_inplace_divide);
1950 COPYNUM(nb_inplace_remainder);
1951 COPYNUM(nb_inplace_power);
1952 COPYNUM(nb_inplace_lshift);
1953 COPYNUM(nb_inplace_rshift);
1954 COPYNUM(nb_inplace_and);
1955 COPYNUM(nb_inplace_xor);
1956 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001957 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1958 COPYNUM(nb_true_divide);
1959 COPYNUM(nb_floor_divide);
1960 COPYNUM(nb_inplace_true_divide);
1961 COPYNUM(nb_inplace_floor_divide);
1962 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001963 }
1964
Guido van Rossum13d52f02001-08-10 21:24:08 +00001965 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1966 basebase = base->tp_base;
1967 if (basebase->tp_as_sequence == NULL)
1968 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001969 COPYSEQ(sq_length);
1970 COPYSEQ(sq_concat);
1971 COPYSEQ(sq_repeat);
1972 COPYSEQ(sq_item);
1973 COPYSEQ(sq_slice);
1974 COPYSEQ(sq_ass_item);
1975 COPYSEQ(sq_ass_slice);
1976 COPYSEQ(sq_contains);
1977 COPYSEQ(sq_inplace_concat);
1978 COPYSEQ(sq_inplace_repeat);
1979 }
1980
Guido van Rossum13d52f02001-08-10 21:24:08 +00001981 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1982 basebase = base->tp_base;
1983 if (basebase->tp_as_mapping == NULL)
1984 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001985 COPYMAP(mp_length);
1986 COPYMAP(mp_subscript);
1987 COPYMAP(mp_ass_subscript);
1988 }
1989
Tim Petersfc57ccb2001-10-12 02:38:24 +00001990 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
1991 basebase = base->tp_base;
1992 if (basebase->tp_as_buffer == NULL)
1993 basebase = NULL;
1994 COPYBUF(bf_getreadbuffer);
1995 COPYBUF(bf_getwritebuffer);
1996 COPYBUF(bf_getsegcount);
1997 COPYBUF(bf_getcharbuffer);
1998 }
1999
Guido van Rossum13d52f02001-08-10 21:24:08 +00002000 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002001
Tim Peters6d6c1a32001-08-02 04:15:00 +00002002 COPYSLOT(tp_dealloc);
2003 COPYSLOT(tp_print);
2004 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2005 type->tp_getattr = base->tp_getattr;
2006 type->tp_getattro = base->tp_getattro;
2007 }
2008 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2009 type->tp_setattr = base->tp_setattr;
2010 type->tp_setattro = base->tp_setattro;
2011 }
2012 /* tp_compare see tp_richcompare */
2013 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002014 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002015 COPYSLOT(tp_call);
2016 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002017 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002018 if (type->tp_compare == NULL &&
2019 type->tp_richcompare == NULL &&
2020 type->tp_hash == NULL)
2021 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002022 type->tp_compare = base->tp_compare;
2023 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002024 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025 }
2026 }
2027 else {
2028 COPYSLOT(tp_compare);
2029 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002030 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2031 COPYSLOT(tp_iter);
2032 COPYSLOT(tp_iternext);
2033 }
2034 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2035 COPYSLOT(tp_descr_get);
2036 COPYSLOT(tp_descr_set);
2037 COPYSLOT(tp_dictoffset);
2038 COPYSLOT(tp_init);
2039 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002041 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002042 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043}
2044
Guido van Rossum13d52f02001-08-10 21:24:08 +00002045staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002046staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002047
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002049PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002050{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002051 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002052 PyTypeObject *base;
2053 int i, n;
2054
Guido van Rossumd614f972001-08-10 17:39:49 +00002055 if (type->tp_flags & Py_TPFLAGS_READY) {
2056 assert(type->tp_dict != NULL);
2057 return 0;
2058 }
2059 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002060
2061 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002062
2063 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2064 base = type->tp_base;
2065 if (base == NULL && type != &PyBaseObject_Type)
2066 base = type->tp_base = &PyBaseObject_Type;
2067
Guido van Rossum0986d822002-04-08 01:38:42 +00002068 /* Initialize ob_type if NULL. This means extensions that want to be
2069 compilable separately on Windows can call PyType_Ready() instead of
2070 initializing the ob_type field of their type objects. */
2071 if (type->ob_type == NULL)
2072 type->ob_type = base->ob_type;
2073
Tim Peters6d6c1a32001-08-02 04:15:00 +00002074 /* Initialize tp_bases */
2075 bases = type->tp_bases;
2076 if (bases == NULL) {
2077 if (base == NULL)
2078 bases = PyTuple_New(0);
2079 else
2080 bases = Py_BuildValue("(O)", base);
2081 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002082 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002083 type->tp_bases = bases;
2084 }
2085
2086 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002087 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002088 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002089 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002090 }
2091
Guido van Rossum687ae002001-10-15 22:03:32 +00002092 /* Initialize tp_dict */
2093 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002094 if (dict == NULL) {
2095 dict = PyDict_New();
2096 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002097 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002098 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002099 }
2100
Guido van Rossum687ae002001-10-15 22:03:32 +00002101 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002103 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002104 if (type->tp_methods != NULL) {
2105 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002106 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002107 }
2108 if (type->tp_members != NULL) {
2109 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002110 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002111 }
2112 if (type->tp_getset != NULL) {
2113 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002114 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002115 }
2116
Tim Peters6d6c1a32001-08-02 04:15:00 +00002117 /* Calculate method resolution order */
2118 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002119 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002120 }
2121
Guido van Rossum13d52f02001-08-10 21:24:08 +00002122 /* Inherit special flags from dominant base */
2123 if (type->tp_base != NULL)
2124 inherit_special(type, type->tp_base);
2125
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002127 bases = type->tp_mro;
2128 assert(bases != NULL);
2129 assert(PyTuple_Check(bases));
2130 n = PyTuple_GET_SIZE(bases);
2131 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002132 PyObject *b = PyTuple_GET_ITEM(bases, i);
2133 if (PyType_Check(b))
2134 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002135 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002136
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002137 /* if the type dictionary doesn't contain a __doc__, set it from
2138 the tp_doc slot.
2139 */
2140 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2141 if (type->tp_doc != NULL) {
2142 PyObject *doc = PyString_FromString(type->tp_doc);
2143 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2144 Py_DECREF(doc);
2145 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002146 PyDict_SetItemString(type->tp_dict,
2147 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002148 }
2149 }
2150
Guido van Rossum13d52f02001-08-10 21:24:08 +00002151 /* Some more special stuff */
2152 base = type->tp_base;
2153 if (base != NULL) {
2154 if (type->tp_as_number == NULL)
2155 type->tp_as_number = base->tp_as_number;
2156 if (type->tp_as_sequence == NULL)
2157 type->tp_as_sequence = base->tp_as_sequence;
2158 if (type->tp_as_mapping == NULL)
2159 type->tp_as_mapping = base->tp_as_mapping;
2160 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002161
Guido van Rossum1c450732001-10-08 15:18:27 +00002162 /* Link into each base class's list of subclasses */
2163 bases = type->tp_bases;
2164 n = PyTuple_GET_SIZE(bases);
2165 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002166 PyObject *b = PyTuple_GET_ITEM(bases, i);
2167 if (PyType_Check(b) &&
2168 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002169 goto error;
2170 }
2171
Guido van Rossum13d52f02001-08-10 21:24:08 +00002172 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002173 assert(type->tp_dict != NULL);
2174 type->tp_flags =
2175 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002176 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002177
2178 error:
2179 type->tp_flags &= ~Py_TPFLAGS_READYING;
2180 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002181}
2182
Guido van Rossum1c450732001-10-08 15:18:27 +00002183static int
2184add_subclass(PyTypeObject *base, PyTypeObject *type)
2185{
2186 int i;
2187 PyObject *list, *ref, *new;
2188
2189 list = base->tp_subclasses;
2190 if (list == NULL) {
2191 base->tp_subclasses = list = PyList_New(0);
2192 if (list == NULL)
2193 return -1;
2194 }
2195 assert(PyList_Check(list));
2196 new = PyWeakref_NewRef((PyObject *)type, NULL);
2197 i = PyList_GET_SIZE(list);
2198 while (--i >= 0) {
2199 ref = PyList_GET_ITEM(list, i);
2200 assert(PyWeakref_CheckRef(ref));
2201 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2202 return PyList_SetItem(list, i, new);
2203 }
2204 i = PyList_Append(list, new);
2205 Py_DECREF(new);
2206 return i;
2207}
2208
Tim Peters6d6c1a32001-08-02 04:15:00 +00002209
2210/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2211
2212/* There's a wrapper *function* for each distinct function typedef used
2213 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2214 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2215 Most tables have only one entry; the tables for binary operators have two
2216 entries, one regular and one with reversed arguments. */
2217
2218static PyObject *
2219wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2220{
2221 inquiry func = (inquiry)wrapped;
2222 int res;
2223
2224 if (!PyArg_ParseTuple(args, ""))
2225 return NULL;
2226 res = (*func)(self);
2227 if (res == -1 && PyErr_Occurred())
2228 return NULL;
2229 return PyInt_FromLong((long)res);
2230}
2231
Tim Peters6d6c1a32001-08-02 04:15:00 +00002232static PyObject *
2233wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2234{
2235 binaryfunc func = (binaryfunc)wrapped;
2236 PyObject *other;
2237
2238 if (!PyArg_ParseTuple(args, "O", &other))
2239 return NULL;
2240 return (*func)(self, other);
2241}
2242
2243static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002244wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2245{
2246 binaryfunc func = (binaryfunc)wrapped;
2247 PyObject *other;
2248
2249 if (!PyArg_ParseTuple(args, "O", &other))
2250 return NULL;
2251 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002252 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002253 Py_INCREF(Py_NotImplemented);
2254 return Py_NotImplemented;
2255 }
2256 return (*func)(self, other);
2257}
2258
2259static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002260wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2261{
2262 binaryfunc func = (binaryfunc)wrapped;
2263 PyObject *other;
2264
2265 if (!PyArg_ParseTuple(args, "O", &other))
2266 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002267 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002268 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002269 Py_INCREF(Py_NotImplemented);
2270 return Py_NotImplemented;
2271 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002272 return (*func)(other, self);
2273}
2274
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002275static PyObject *
2276wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2277{
2278 coercion func = (coercion)wrapped;
2279 PyObject *other, *res;
2280 int ok;
2281
2282 if (!PyArg_ParseTuple(args, "O", &other))
2283 return NULL;
2284 ok = func(&self, &other);
2285 if (ok < 0)
2286 return NULL;
2287 if (ok > 0) {
2288 Py_INCREF(Py_NotImplemented);
2289 return Py_NotImplemented;
2290 }
2291 res = PyTuple_New(2);
2292 if (res == NULL) {
2293 Py_DECREF(self);
2294 Py_DECREF(other);
2295 return NULL;
2296 }
2297 PyTuple_SET_ITEM(res, 0, self);
2298 PyTuple_SET_ITEM(res, 1, other);
2299 return res;
2300}
2301
Tim Peters6d6c1a32001-08-02 04:15:00 +00002302static PyObject *
2303wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2304{
2305 ternaryfunc func = (ternaryfunc)wrapped;
2306 PyObject *other;
2307 PyObject *third = Py_None;
2308
2309 /* Note: This wrapper only works for __pow__() */
2310
2311 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2312 return NULL;
2313 return (*func)(self, other, third);
2314}
2315
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002316static PyObject *
2317wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2318{
2319 ternaryfunc func = (ternaryfunc)wrapped;
2320 PyObject *other;
2321 PyObject *third = Py_None;
2322
2323 /* Note: This wrapper only works for __pow__() */
2324
2325 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2326 return NULL;
2327 return (*func)(other, self, third);
2328}
2329
Tim Peters6d6c1a32001-08-02 04:15:00 +00002330static PyObject *
2331wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2332{
2333 unaryfunc func = (unaryfunc)wrapped;
2334
2335 if (!PyArg_ParseTuple(args, ""))
2336 return NULL;
2337 return (*func)(self);
2338}
2339
Tim Peters6d6c1a32001-08-02 04:15:00 +00002340static PyObject *
2341wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2342{
2343 intargfunc func = (intargfunc)wrapped;
2344 int i;
2345
2346 if (!PyArg_ParseTuple(args, "i", &i))
2347 return NULL;
2348 return (*func)(self, i);
2349}
2350
Guido van Rossum5d815f32001-08-17 21:57:47 +00002351static int
2352getindex(PyObject *self, PyObject *arg)
2353{
2354 int i;
2355
2356 i = PyInt_AsLong(arg);
2357 if (i == -1 && PyErr_Occurred())
2358 return -1;
2359 if (i < 0) {
2360 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2361 if (sq && sq->sq_length) {
2362 int n = (*sq->sq_length)(self);
2363 if (n < 0)
2364 return -1;
2365 i += n;
2366 }
2367 }
2368 return i;
2369}
2370
2371static PyObject *
2372wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2373{
2374 intargfunc func = (intargfunc)wrapped;
2375 PyObject *arg;
2376 int i;
2377
Guido van Rossumf4593e02001-10-03 12:09:30 +00002378 if (PyTuple_GET_SIZE(args) == 1) {
2379 arg = PyTuple_GET_ITEM(args, 0);
2380 i = getindex(self, arg);
2381 if (i == -1 && PyErr_Occurred())
2382 return NULL;
2383 return (*func)(self, i);
2384 }
2385 PyArg_ParseTuple(args, "O", &arg);
2386 assert(PyErr_Occurred());
2387 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002388}
2389
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390static PyObject *
2391wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2392{
2393 intintargfunc func = (intintargfunc)wrapped;
2394 int i, j;
2395
2396 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2397 return NULL;
2398 return (*func)(self, i, j);
2399}
2400
Tim Peters6d6c1a32001-08-02 04:15:00 +00002401static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002402wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002403{
2404 intobjargproc func = (intobjargproc)wrapped;
2405 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002406 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002407
Guido van Rossum5d815f32001-08-17 21:57:47 +00002408 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2409 return NULL;
2410 i = getindex(self, arg);
2411 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002412 return NULL;
2413 res = (*func)(self, i, value);
2414 if (res == -1 && PyErr_Occurred())
2415 return NULL;
2416 Py_INCREF(Py_None);
2417 return Py_None;
2418}
2419
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002420static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002421wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002422{
2423 intobjargproc func = (intobjargproc)wrapped;
2424 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002425 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002426
Guido van Rossum5d815f32001-08-17 21:57:47 +00002427 if (!PyArg_ParseTuple(args, "O", &arg))
2428 return NULL;
2429 i = getindex(self, arg);
2430 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002431 return NULL;
2432 res = (*func)(self, i, NULL);
2433 if (res == -1 && PyErr_Occurred())
2434 return NULL;
2435 Py_INCREF(Py_None);
2436 return Py_None;
2437}
2438
Tim Peters6d6c1a32001-08-02 04:15:00 +00002439static PyObject *
2440wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2441{
2442 intintobjargproc func = (intintobjargproc)wrapped;
2443 int i, j, res;
2444 PyObject *value;
2445
2446 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2447 return NULL;
2448 res = (*func)(self, i, j, value);
2449 if (res == -1 && PyErr_Occurred())
2450 return NULL;
2451 Py_INCREF(Py_None);
2452 return Py_None;
2453}
2454
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002455static PyObject *
2456wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2457{
2458 intintobjargproc func = (intintobjargproc)wrapped;
2459 int i, j, res;
2460
2461 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2462 return NULL;
2463 res = (*func)(self, i, j, NULL);
2464 if (res == -1 && PyErr_Occurred())
2465 return NULL;
2466 Py_INCREF(Py_None);
2467 return Py_None;
2468}
2469
Tim Peters6d6c1a32001-08-02 04:15:00 +00002470/* XXX objobjproc is a misnomer; should be objargpred */
2471static PyObject *
2472wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2473{
2474 objobjproc func = (objobjproc)wrapped;
2475 int res;
2476 PyObject *value;
2477
2478 if (!PyArg_ParseTuple(args, "O", &value))
2479 return NULL;
2480 res = (*func)(self, value);
2481 if (res == -1 && PyErr_Occurred())
2482 return NULL;
2483 return PyInt_FromLong((long)res);
2484}
2485
Tim Peters6d6c1a32001-08-02 04:15:00 +00002486static PyObject *
2487wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2488{
2489 objobjargproc func = (objobjargproc)wrapped;
2490 int res;
2491 PyObject *key, *value;
2492
2493 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2494 return NULL;
2495 res = (*func)(self, key, value);
2496 if (res == -1 && PyErr_Occurred())
2497 return NULL;
2498 Py_INCREF(Py_None);
2499 return Py_None;
2500}
2501
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002502static PyObject *
2503wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2504{
2505 objobjargproc func = (objobjargproc)wrapped;
2506 int res;
2507 PyObject *key;
2508
2509 if (!PyArg_ParseTuple(args, "O", &key))
2510 return NULL;
2511 res = (*func)(self, key, NULL);
2512 if (res == -1 && PyErr_Occurred())
2513 return NULL;
2514 Py_INCREF(Py_None);
2515 return Py_None;
2516}
2517
Tim Peters6d6c1a32001-08-02 04:15:00 +00002518static PyObject *
2519wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2520{
2521 cmpfunc func = (cmpfunc)wrapped;
2522 int res;
2523 PyObject *other;
2524
2525 if (!PyArg_ParseTuple(args, "O", &other))
2526 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002527 if (other->ob_type->tp_compare != func &&
2528 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002529 PyErr_Format(
2530 PyExc_TypeError,
2531 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2532 self->ob_type->tp_name,
2533 self->ob_type->tp_name,
2534 other->ob_type->tp_name);
2535 return NULL;
2536 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002537 res = (*func)(self, other);
2538 if (PyErr_Occurred())
2539 return NULL;
2540 return PyInt_FromLong((long)res);
2541}
2542
Tim Peters6d6c1a32001-08-02 04:15:00 +00002543static PyObject *
2544wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2545{
2546 setattrofunc func = (setattrofunc)wrapped;
2547 int res;
2548 PyObject *name, *value;
2549
2550 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2551 return NULL;
2552 res = (*func)(self, name, value);
2553 if (res < 0)
2554 return NULL;
2555 Py_INCREF(Py_None);
2556 return Py_None;
2557}
2558
2559static PyObject *
2560wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2561{
2562 setattrofunc func = (setattrofunc)wrapped;
2563 int res;
2564 PyObject *name;
2565
2566 if (!PyArg_ParseTuple(args, "O", &name))
2567 return NULL;
2568 res = (*func)(self, name, NULL);
2569 if (res < 0)
2570 return NULL;
2571 Py_INCREF(Py_None);
2572 return Py_None;
2573}
2574
Tim Peters6d6c1a32001-08-02 04:15:00 +00002575static PyObject *
2576wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2577{
2578 hashfunc func = (hashfunc)wrapped;
2579 long res;
2580
2581 if (!PyArg_ParseTuple(args, ""))
2582 return NULL;
2583 res = (*func)(self);
2584 if (res == -1 && PyErr_Occurred())
2585 return NULL;
2586 return PyInt_FromLong(res);
2587}
2588
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002590wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002591{
2592 ternaryfunc func = (ternaryfunc)wrapped;
2593
Guido van Rossumc8e56452001-10-22 00:43:43 +00002594 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002595}
2596
Tim Peters6d6c1a32001-08-02 04:15:00 +00002597static PyObject *
2598wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2599{
2600 richcmpfunc func = (richcmpfunc)wrapped;
2601 PyObject *other;
2602
2603 if (!PyArg_ParseTuple(args, "O", &other))
2604 return NULL;
2605 return (*func)(self, other, op);
2606}
2607
2608#undef RICHCMP_WRAPPER
2609#define RICHCMP_WRAPPER(NAME, OP) \
2610static PyObject * \
2611richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2612{ \
2613 return wrap_richcmpfunc(self, args, wrapped, OP); \
2614}
2615
Jack Jansen8e938b42001-08-08 15:29:49 +00002616RICHCMP_WRAPPER(lt, Py_LT)
2617RICHCMP_WRAPPER(le, Py_LE)
2618RICHCMP_WRAPPER(eq, Py_EQ)
2619RICHCMP_WRAPPER(ne, Py_NE)
2620RICHCMP_WRAPPER(gt, Py_GT)
2621RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002622
Tim Peters6d6c1a32001-08-02 04:15:00 +00002623static PyObject *
2624wrap_next(PyObject *self, PyObject *args, void *wrapped)
2625{
2626 unaryfunc func = (unaryfunc)wrapped;
2627 PyObject *res;
2628
2629 if (!PyArg_ParseTuple(args, ""))
2630 return NULL;
2631 res = (*func)(self);
2632 if (res == NULL && !PyErr_Occurred())
2633 PyErr_SetNone(PyExc_StopIteration);
2634 return res;
2635}
2636
Tim Peters6d6c1a32001-08-02 04:15:00 +00002637static PyObject *
2638wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2639{
2640 descrgetfunc func = (descrgetfunc)wrapped;
2641 PyObject *obj;
2642 PyObject *type = NULL;
2643
2644 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2645 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002646 return (*func)(self, obj, type);
2647}
2648
Tim Peters6d6c1a32001-08-02 04:15:00 +00002649static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002650wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002651{
2652 descrsetfunc func = (descrsetfunc)wrapped;
2653 PyObject *obj, *value;
2654 int ret;
2655
2656 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2657 return NULL;
2658 ret = (*func)(self, obj, value);
2659 if (ret < 0)
2660 return NULL;
2661 Py_INCREF(Py_None);
2662 return Py_None;
2663}
2664
Tim Peters6d6c1a32001-08-02 04:15:00 +00002665static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002666wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667{
2668 initproc func = (initproc)wrapped;
2669
Guido van Rossumc8e56452001-10-22 00:43:43 +00002670 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002671 return NULL;
2672 Py_INCREF(Py_None);
2673 return Py_None;
2674}
2675
Tim Peters6d6c1a32001-08-02 04:15:00 +00002676static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002677tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002678{
Barry Warsaw60f01882001-08-22 19:24:42 +00002679 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002680 PyObject *arg0, *res;
2681
2682 if (self == NULL || !PyType_Check(self))
2683 Py_FatalError("__new__() called with non-type 'self'");
2684 type = (PyTypeObject *)self;
2685 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002686 PyErr_Format(PyExc_TypeError,
2687 "%s.__new__(): not enough arguments",
2688 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002689 return NULL;
2690 }
2691 arg0 = PyTuple_GET_ITEM(args, 0);
2692 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002693 PyErr_Format(PyExc_TypeError,
2694 "%s.__new__(X): X is not a type object (%s)",
2695 type->tp_name,
2696 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002697 return NULL;
2698 }
2699 subtype = (PyTypeObject *)arg0;
2700 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002701 PyErr_Format(PyExc_TypeError,
2702 "%s.__new__(%s): %s is not a subtype of %s",
2703 type->tp_name,
2704 subtype->tp_name,
2705 subtype->tp_name,
2706 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002707 return NULL;
2708 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002709
2710 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002711 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002712 most derived base that's not a heap type is this type. */
2713 staticbase = subtype;
2714 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2715 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002716 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002717 PyErr_Format(PyExc_TypeError,
2718 "%s.__new__(%s) is not safe, use %s.__new__()",
2719 type->tp_name,
2720 subtype->tp_name,
2721 staticbase == NULL ? "?" : staticbase->tp_name);
2722 return NULL;
2723 }
2724
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002725 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2726 if (args == NULL)
2727 return NULL;
2728 res = type->tp_new(subtype, args, kwds);
2729 Py_DECREF(args);
2730 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731}
2732
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002733static struct PyMethodDef tp_new_methoddef[] = {
2734 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2735 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002736 {0}
2737};
2738
2739static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002740add_tp_new_wrapper(PyTypeObject *type)
2741{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002742 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002743
Guido van Rossum687ae002001-10-15 22:03:32 +00002744 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002745 return 0;
2746 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002747 if (func == NULL)
2748 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002749 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002750}
2751
Guido van Rossumf040ede2001-08-07 16:40:56 +00002752/* Slot wrappers that call the corresponding __foo__ slot. See comments
2753 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002754
Guido van Rossumdc91b992001-08-08 22:26:22 +00002755#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002756static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002757FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002759 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002760 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002761}
2762
Guido van Rossumdc91b992001-08-08 22:26:22 +00002763#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002764static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002765FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002767 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002768 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769}
2770
Guido van Rossumdc91b992001-08-08 22:26:22 +00002771
2772#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002773static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002774FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002775{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002776 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002777 int do_other = self->ob_type != other->ob_type && \
2778 other->ob_type->tp_as_number != NULL && \
2779 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002780 if (self->ob_type->tp_as_number != NULL && \
2781 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2782 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002783 if (do_other && \
2784 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2785 r = call_maybe( \
2786 other, ROPSTR, &rcache_str, "(O)", self); \
2787 if (r != Py_NotImplemented) \
2788 return r; \
2789 Py_DECREF(r); \
2790 do_other = 0; \
2791 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002792 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002793 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002794 if (r != Py_NotImplemented || \
2795 other->ob_type == self->ob_type) \
2796 return r; \
2797 Py_DECREF(r); \
2798 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002799 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002800 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002801 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002802 } \
2803 Py_INCREF(Py_NotImplemented); \
2804 return Py_NotImplemented; \
2805}
2806
2807#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2808 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2809
2810#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2811static PyObject * \
2812FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2813{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002814 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002815 return call_method(self, OPSTR, &cache_str, \
2816 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817}
2818
2819static int
2820slot_sq_length(PyObject *self)
2821{
Guido van Rossum2730b132001-08-28 18:22:14 +00002822 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002823 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002824 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002825
2826 if (res == NULL)
2827 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002828 len = (int)PyInt_AsLong(res);
2829 Py_DECREF(res);
2830 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002831}
2832
Guido van Rossumdc91b992001-08-08 22:26:22 +00002833SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2834SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002835
2836/* Super-optimized version of slot_sq_item.
2837 Other slots could do the same... */
2838static PyObject *
2839slot_sq_item(PyObject *self, int i)
2840{
2841 static PyObject *getitem_str;
2842 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2843 descrgetfunc f;
2844
2845 if (getitem_str == NULL) {
2846 getitem_str = PyString_InternFromString("__getitem__");
2847 if (getitem_str == NULL)
2848 return NULL;
2849 }
2850 func = _PyType_Lookup(self->ob_type, getitem_str);
2851 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002852 if ((f = func->ob_type->tp_descr_get) == NULL)
2853 Py_INCREF(func);
2854 else
2855 func = f(func, self, (PyObject *)(self->ob_type));
2856 ival = PyInt_FromLong(i);
2857 if (ival != NULL) {
2858 args = PyTuple_New(1);
2859 if (args != NULL) {
2860 PyTuple_SET_ITEM(args, 0, ival);
2861 retval = PyObject_Call(func, args, NULL);
2862 Py_XDECREF(args);
2863 Py_XDECREF(func);
2864 return retval;
2865 }
2866 }
2867 }
2868 else {
2869 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2870 }
2871 Py_XDECREF(args);
2872 Py_XDECREF(ival);
2873 Py_XDECREF(func);
2874 return NULL;
2875}
2876
Guido van Rossumdc91b992001-08-08 22:26:22 +00002877SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002878
2879static int
2880slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2881{
2882 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002883 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002884
2885 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002886 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002887 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002889 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002890 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002891 if (res == NULL)
2892 return -1;
2893 Py_DECREF(res);
2894 return 0;
2895}
2896
2897static int
2898slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2899{
2900 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002901 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002902
2903 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002904 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002905 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002906 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002907 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002908 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002909 if (res == NULL)
2910 return -1;
2911 Py_DECREF(res);
2912 return 0;
2913}
2914
2915static int
2916slot_sq_contains(PyObject *self, PyObject *value)
2917{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002918 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002919 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002920
Guido van Rossum55f20992001-10-01 17:18:22 +00002921 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002922
2923 if (func != NULL) {
2924 args = Py_BuildValue("(O)", value);
2925 if (args == NULL)
2926 res = NULL;
2927 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002928 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002929 Py_DECREF(args);
2930 }
2931 Py_DECREF(func);
2932 if (res == NULL)
2933 return -1;
2934 return PyObject_IsTrue(res);
2935 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002936 else if (PyErr_Occurred())
2937 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002938 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002939 return _PySequence_IterSearch(self, value,
2940 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002941 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002942}
2943
Guido van Rossumdc91b992001-08-08 22:26:22 +00002944SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2945SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946
2947#define slot_mp_length slot_sq_length
2948
Guido van Rossumdc91b992001-08-08 22:26:22 +00002949SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002950
2951static int
2952slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2953{
2954 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002955 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956
2957 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002958 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002959 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002960 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002961 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002962 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002963 if (res == NULL)
2964 return -1;
2965 Py_DECREF(res);
2966 return 0;
2967}
2968
Guido van Rossumdc91b992001-08-08 22:26:22 +00002969SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2970SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2971SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2972SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2973SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2974SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2975
2976staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2977
2978SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2979 nb_power, "__pow__", "__rpow__")
2980
2981static PyObject *
2982slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2983{
Guido van Rossum2730b132001-08-28 18:22:14 +00002984 static PyObject *pow_str;
2985
Guido van Rossumdc91b992001-08-08 22:26:22 +00002986 if (modulus == Py_None)
2987 return slot_nb_power_binary(self, other);
2988 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002989 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002990 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002991}
2992
2993SLOT0(slot_nb_negative, "__neg__")
2994SLOT0(slot_nb_positive, "__pos__")
2995SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002996
2997static int
2998slot_nb_nonzero(PyObject *self)
2999{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003000 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003001 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003002
Guido van Rossum55f20992001-10-01 17:18:22 +00003003 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003004 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003005 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003006 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003007 func = lookup_maybe(self, "__len__", &len_str);
3008 if (func == NULL) {
3009 if (PyErr_Occurred())
3010 return -1;
3011 else
3012 return 1;
3013 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003014 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003015 res = PyObject_CallObject(func, NULL);
3016 Py_DECREF(func);
3017 if (res == NULL)
3018 return -1;
3019 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003020}
3021
Guido van Rossumdc91b992001-08-08 22:26:22 +00003022SLOT0(slot_nb_invert, "__invert__")
3023SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3024SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3025SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3026SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3027SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003028
3029static int
3030slot_nb_coerce(PyObject **a, PyObject **b)
3031{
3032 static PyObject *coerce_str;
3033 PyObject *self = *a, *other = *b;
3034
3035 if (self->ob_type->tp_as_number != NULL &&
3036 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3037 PyObject *r;
3038 r = call_maybe(
3039 self, "__coerce__", &coerce_str, "(O)", other);
3040 if (r == NULL)
3041 return -1;
3042 if (r == Py_NotImplemented) {
3043 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003044 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003045 else {
3046 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3047 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003048 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003049 Py_DECREF(r);
3050 return -1;
3051 }
3052 *a = PyTuple_GET_ITEM(r, 0);
3053 Py_INCREF(*a);
3054 *b = PyTuple_GET_ITEM(r, 1);
3055 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003056 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003057 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003058 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003059 }
3060 if (other->ob_type->tp_as_number != NULL &&
3061 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3062 PyObject *r;
3063 r = call_maybe(
3064 other, "__coerce__", &coerce_str, "(O)", self);
3065 if (r == NULL)
3066 return -1;
3067 if (r == Py_NotImplemented) {
3068 Py_DECREF(r);
3069 return 1;
3070 }
3071 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3072 PyErr_SetString(PyExc_TypeError,
3073 "__coerce__ didn't return a 2-tuple");
3074 Py_DECREF(r);
3075 return -1;
3076 }
3077 *a = PyTuple_GET_ITEM(r, 1);
3078 Py_INCREF(*a);
3079 *b = PyTuple_GET_ITEM(r, 0);
3080 Py_INCREF(*b);
3081 Py_DECREF(r);
3082 return 0;
3083 }
3084 return 1;
3085}
3086
Guido van Rossumdc91b992001-08-08 22:26:22 +00003087SLOT0(slot_nb_int, "__int__")
3088SLOT0(slot_nb_long, "__long__")
3089SLOT0(slot_nb_float, "__float__")
3090SLOT0(slot_nb_oct, "__oct__")
3091SLOT0(slot_nb_hex, "__hex__")
3092SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3093SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3094SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3095SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3096SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3097SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3098SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3099SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3100SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3101SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3102SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3103SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3104 "__floordiv__", "__rfloordiv__")
3105SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3106SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3107SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003108
3109static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003110half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003111{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003112 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003113 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003114 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115
Guido van Rossum60718732001-08-28 17:47:51 +00003116 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003117 if (func == NULL) {
3118 PyErr_Clear();
3119 }
3120 else {
3121 args = Py_BuildValue("(O)", other);
3122 if (args == NULL)
3123 res = NULL;
3124 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003125 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003126 Py_DECREF(args);
3127 }
3128 if (res != Py_NotImplemented) {
3129 if (res == NULL)
3130 return -2;
3131 c = PyInt_AsLong(res);
3132 Py_DECREF(res);
3133 if (c == -1 && PyErr_Occurred())
3134 return -2;
3135 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3136 }
3137 Py_DECREF(res);
3138 }
3139 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003140}
3141
Guido van Rossumab3b0342001-09-18 20:38:53 +00003142/* This slot is published for the benefit of try_3way_compare in object.c */
3143int
3144_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003145{
3146 int c;
3147
Guido van Rossumab3b0342001-09-18 20:38:53 +00003148 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003149 c = half_compare(self, other);
3150 if (c <= 1)
3151 return c;
3152 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003153 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003154 c = half_compare(other, self);
3155 if (c < -1)
3156 return -2;
3157 if (c <= 1)
3158 return -c;
3159 }
3160 return (void *)self < (void *)other ? -1 :
3161 (void *)self > (void *)other ? 1 : 0;
3162}
3163
3164static PyObject *
3165slot_tp_repr(PyObject *self)
3166{
3167 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003168 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003169
Guido van Rossum60718732001-08-28 17:47:51 +00003170 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003171 if (func != NULL) {
3172 res = PyEval_CallObject(func, NULL);
3173 Py_DECREF(func);
3174 return res;
3175 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003176 PyErr_Clear();
3177 return PyString_FromFormat("<%s object at %p>",
3178 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003179}
3180
3181static PyObject *
3182slot_tp_str(PyObject *self)
3183{
3184 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003185 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003186
Guido van Rossum60718732001-08-28 17:47:51 +00003187 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003188 if (func != NULL) {
3189 res = PyEval_CallObject(func, NULL);
3190 Py_DECREF(func);
3191 return res;
3192 }
3193 else {
3194 PyErr_Clear();
3195 return slot_tp_repr(self);
3196 }
3197}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003198
3199static long
3200slot_tp_hash(PyObject *self)
3201{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003202 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003203 static PyObject *hash_str, *eq_str, *cmp_str;
3204
Tim Peters6d6c1a32001-08-02 04:15:00 +00003205 long h;
3206
Guido van Rossum60718732001-08-28 17:47:51 +00003207 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003208
3209 if (func != NULL) {
3210 res = PyEval_CallObject(func, NULL);
3211 Py_DECREF(func);
3212 if (res == NULL)
3213 return -1;
3214 h = PyInt_AsLong(res);
3215 }
3216 else {
3217 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003218 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003219 if (func == NULL) {
3220 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003221 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003222 }
3223 if (func != NULL) {
3224 Py_DECREF(func);
3225 PyErr_SetString(PyExc_TypeError, "unhashable type");
3226 return -1;
3227 }
3228 PyErr_Clear();
3229 h = _Py_HashPointer((void *)self);
3230 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003231 if (h == -1 && !PyErr_Occurred())
3232 h = -2;
3233 return h;
3234}
3235
3236static PyObject *
3237slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3238{
Guido van Rossum60718732001-08-28 17:47:51 +00003239 static PyObject *call_str;
3240 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003241 PyObject *res;
3242
3243 if (meth == NULL)
3244 return NULL;
3245 res = PyObject_Call(meth, args, kwds);
3246 Py_DECREF(meth);
3247 return res;
3248}
3249
Guido van Rossum14a6f832001-10-17 13:59:09 +00003250/* There are two slot dispatch functions for tp_getattro.
3251
3252 - slot_tp_getattro() is used when __getattribute__ is overridden
3253 but no __getattr__ hook is present;
3254
3255 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3256
Guido van Rossumc334df52002-04-04 23:44:47 +00003257 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3258 detects the absence of __getattr__ and then installs the simpler slot if
3259 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003260
Tim Peters6d6c1a32001-08-02 04:15:00 +00003261static PyObject *
3262slot_tp_getattro(PyObject *self, PyObject *name)
3263{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003264 static PyObject *getattribute_str = NULL;
3265 return call_method(self, "__getattribute__", &getattribute_str,
3266 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003267}
3268
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003269static PyObject *
3270slot_tp_getattr_hook(PyObject *self, PyObject *name)
3271{
3272 PyTypeObject *tp = self->ob_type;
3273 PyObject *getattr, *getattribute, *res;
3274 static PyObject *getattribute_str = NULL;
3275 static PyObject *getattr_str = NULL;
3276
3277 if (getattr_str == NULL) {
3278 getattr_str = PyString_InternFromString("__getattr__");
3279 if (getattr_str == NULL)
3280 return NULL;
3281 }
3282 if (getattribute_str == NULL) {
3283 getattribute_str =
3284 PyString_InternFromString("__getattribute__");
3285 if (getattribute_str == NULL)
3286 return NULL;
3287 }
3288 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003289 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003290 /* No __getattr__ hook: use a simpler dispatcher */
3291 tp->tp_getattro = slot_tp_getattro;
3292 return slot_tp_getattro(self, name);
3293 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003294 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003295 if (getattribute == NULL ||
3296 (getattribute->ob_type == &PyWrapperDescr_Type &&
3297 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3298 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003299 res = PyObject_GenericGetAttr(self, name);
3300 else
3301 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003302 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003303 PyErr_Clear();
3304 res = PyObject_CallFunction(getattr, "OO", self, name);
3305 }
3306 return res;
3307}
3308
Tim Peters6d6c1a32001-08-02 04:15:00 +00003309static int
3310slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3311{
3312 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003313 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003314
3315 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003316 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003317 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003318 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003319 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003320 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003321 if (res == NULL)
3322 return -1;
3323 Py_DECREF(res);
3324 return 0;
3325}
3326
3327/* Map rich comparison operators to their __xx__ namesakes */
3328static char *name_op[] = {
3329 "__lt__",
3330 "__le__",
3331 "__eq__",
3332 "__ne__",
3333 "__gt__",
3334 "__ge__",
3335};
3336
3337static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003338half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003339{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003340 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003341 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003342
Guido van Rossum60718732001-08-28 17:47:51 +00003343 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003344 if (func == NULL) {
3345 PyErr_Clear();
3346 Py_INCREF(Py_NotImplemented);
3347 return Py_NotImplemented;
3348 }
3349 args = Py_BuildValue("(O)", other);
3350 if (args == NULL)
3351 res = NULL;
3352 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003353 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003354 Py_DECREF(args);
3355 }
3356 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003357 return res;
3358}
3359
Guido van Rossumb8f63662001-08-15 23:57:02 +00003360/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3361static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3362
3363static PyObject *
3364slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3365{
3366 PyObject *res;
3367
3368 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3369 res = half_richcompare(self, other, op);
3370 if (res != Py_NotImplemented)
3371 return res;
3372 Py_DECREF(res);
3373 }
3374 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3375 res = half_richcompare(other, self, swapped_op[op]);
3376 if (res != Py_NotImplemented) {
3377 return res;
3378 }
3379 Py_DECREF(res);
3380 }
3381 Py_INCREF(Py_NotImplemented);
3382 return Py_NotImplemented;
3383}
3384
3385static PyObject *
3386slot_tp_iter(PyObject *self)
3387{
3388 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003389 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003390
Guido van Rossum60718732001-08-28 17:47:51 +00003391 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003392 if (func != NULL) {
3393 res = PyObject_CallObject(func, NULL);
3394 Py_DECREF(func);
3395 return res;
3396 }
3397 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003398 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003399 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003400 PyErr_SetString(PyExc_TypeError,
3401 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003402 return NULL;
3403 }
3404 Py_DECREF(func);
3405 return PySeqIter_New(self);
3406}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003407
3408static PyObject *
3409slot_tp_iternext(PyObject *self)
3410{
Guido van Rossum2730b132001-08-28 18:22:14 +00003411 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003412 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413}
3414
Guido van Rossum1a493502001-08-17 16:47:50 +00003415static PyObject *
3416slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3417{
3418 PyTypeObject *tp = self->ob_type;
3419 PyObject *get;
3420 static PyObject *get_str = NULL;
3421
3422 if (get_str == NULL) {
3423 get_str = PyString_InternFromString("__get__");
3424 if (get_str == NULL)
3425 return NULL;
3426 }
3427 get = _PyType_Lookup(tp, get_str);
3428 if (get == NULL) {
3429 /* Avoid further slowdowns */
3430 if (tp->tp_descr_get == slot_tp_descr_get)
3431 tp->tp_descr_get = NULL;
3432 Py_INCREF(self);
3433 return self;
3434 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003435 if (obj == NULL)
3436 obj = Py_None;
3437 if (type == NULL)
3438 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003439 return PyObject_CallFunction(get, "OOO", self, obj, type);
3440}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441
3442static int
3443slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3444{
Guido van Rossum2c252392001-08-24 10:13:31 +00003445 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003446 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003447
3448 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003449 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003450 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003451 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003452 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003453 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003454 if (res == NULL)
3455 return -1;
3456 Py_DECREF(res);
3457 return 0;
3458}
3459
3460static int
3461slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3462{
Guido van Rossum60718732001-08-28 17:47:51 +00003463 static PyObject *init_str;
3464 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003465 PyObject *res;
3466
3467 if (meth == NULL)
3468 return -1;
3469 res = PyObject_Call(meth, args, kwds);
3470 Py_DECREF(meth);
3471 if (res == NULL)
3472 return -1;
3473 Py_DECREF(res);
3474 return 0;
3475}
3476
3477static PyObject *
3478slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3479{
3480 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3481 PyObject *newargs, *x;
3482 int i, n;
3483
3484 if (func == NULL)
3485 return NULL;
3486 assert(PyTuple_Check(args));
3487 n = PyTuple_GET_SIZE(args);
3488 newargs = PyTuple_New(n+1);
3489 if (newargs == NULL)
3490 return NULL;
3491 Py_INCREF(type);
3492 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3493 for (i = 0; i < n; i++) {
3494 x = PyTuple_GET_ITEM(args, i);
3495 Py_INCREF(x);
3496 PyTuple_SET_ITEM(newargs, i+1, x);
3497 }
3498 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003499 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003500 Py_DECREF(func);
3501 return x;
3502}
3503
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003504
3505/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3506 functions. The offsets here are relative to the 'etype' structure, which
3507 incorporates the additional structures used for numbers, sequences and
3508 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3509 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003510 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3511 terminated with an all-zero entry. (This table is further initialized and
3512 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003513
Guido van Rossum6d204072001-10-21 00:44:31 +00003514typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003515
3516#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003517#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003518#undef ETSLOT
3519#undef SQSLOT
3520#undef MPSLOT
3521#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003522#undef UNSLOT
3523#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003524#undef BINSLOT
3525#undef RBINSLOT
3526
Guido van Rossum6d204072001-10-21 00:44:31 +00003527#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3528 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003529#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3530 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3531 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003532#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3533 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3534#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3535 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3536#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3537 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3538#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3539 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3540#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3541 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3542 "x." NAME "() <==> " DOC)
3543#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3544 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3545 "x." NAME "(y) <==> x" DOC "y")
3546#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3547 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3548 "x." NAME "(y) <==> x" DOC "y")
3549#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3550 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3551 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003552
3553static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003554 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3555 "x.__len__() <==> len(x)"),
3556 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3557 "x.__add__(y) <==> x+y"),
3558 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3559 "x.__mul__(n) <==> x*n"),
3560 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3561 "x.__rmul__(n) <==> n*x"),
3562 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3563 "x.__getitem__(y) <==> x[y]"),
3564 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3565 "x.__getslice__(i, j) <==> x[i:j]"),
3566 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3567 "x.__setitem__(i, y) <==> x[i]=y"),
3568 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3569 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003570 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003571 wrap_intintobjargproc,
3572 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3573 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3574 "x.__delslice__(i, j) <==> del x[i:j]"),
3575 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3576 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003577 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003578 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003579 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003580 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003581
Guido van Rossum6d204072001-10-21 00:44:31 +00003582 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3583 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003584 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003585 wrap_binaryfunc,
3586 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003587 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003588 wrap_objobjargproc,
3589 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003590 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003591 wrap_delitem,
3592 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003593
Guido van Rossum6d204072001-10-21 00:44:31 +00003594 BINSLOT("__add__", nb_add, slot_nb_add,
3595 "+"),
3596 RBINSLOT("__radd__", nb_add, slot_nb_add,
3597 "+"),
3598 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3599 "-"),
3600 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3601 "-"),
3602 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3603 "*"),
3604 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3605 "*"),
3606 BINSLOT("__div__", nb_divide, slot_nb_divide,
3607 "/"),
3608 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3609 "/"),
3610 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3611 "%"),
3612 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3613 "%"),
3614 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3615 "divmod(x, y)"),
3616 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3617 "divmod(y, x)"),
3618 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3619 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3620 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3621 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3622 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3623 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3624 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3625 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003626 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003627 "x != 0"),
3628 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3629 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3630 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3631 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3632 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3633 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3634 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3635 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3636 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3637 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3638 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3639 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3640 "x.__coerce__(y) <==> coerce(x, y)"),
3641 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3642 "int(x)"),
3643 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3644 "long(x)"),
3645 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3646 "float(x)"),
3647 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3648 "oct(x)"),
3649 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3650 "hex(x)"),
3651 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3652 wrap_binaryfunc, "+"),
3653 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3654 wrap_binaryfunc, "-"),
3655 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3656 wrap_binaryfunc, "*"),
3657 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3658 wrap_binaryfunc, "/"),
3659 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3660 wrap_binaryfunc, "%"),
3661 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3662 wrap_ternaryfunc, "**"),
3663 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3664 wrap_binaryfunc, "<<"),
3665 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3666 wrap_binaryfunc, ">>"),
3667 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3668 wrap_binaryfunc, "&"),
3669 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3670 wrap_binaryfunc, "^"),
3671 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3672 wrap_binaryfunc, "|"),
3673 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3674 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3675 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3676 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3677 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3678 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3679 IBSLOT("__itruediv__", nb_inplace_true_divide,
3680 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003681
Guido van Rossum6d204072001-10-21 00:44:31 +00003682 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3683 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003684 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003685 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3686 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003687 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003688 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3689 "x.__cmp__(y) <==> cmp(x,y)"),
3690 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3691 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003692 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3693 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003694 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003695 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3696 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3697 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3698 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3699 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3700 "x.__setattr__('name', value) <==> x.name = value"),
3701 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3702 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3703 "x.__delattr__('name') <==> del x.name"),
3704 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3705 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3706 "x.__lt__(y) <==> x<y"),
3707 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3708 "x.__le__(y) <==> x<=y"),
3709 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3710 "x.__eq__(y) <==> x==y"),
3711 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3712 "x.__ne__(y) <==> x!=y"),
3713 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3714 "x.__gt__(y) <==> x>y"),
3715 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3716 "x.__ge__(y) <==> x>=y"),
3717 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3718 "x.__iter__() <==> iter(x)"),
3719 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3720 "x.next() -> the next value, or raise StopIteration"),
3721 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3722 "descr.__get__(obj[, type]) -> value"),
3723 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3724 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003725 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003726 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003727 "see x.__class__.__doc__ for signature",
3728 PyWrapperFlag_KEYWORDS),
3729 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003730 {NULL}
3731};
3732
Guido van Rossumc334df52002-04-04 23:44:47 +00003733/* Given a type pointer and an offset gotten from a slotdef entry, return a
3734 pointer to the actual slot. This is not quite the same as simply adding
3735 the offset to the type pointer, since it takes care to indirect through the
3736 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3737 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003738static void **
3739slotptr(PyTypeObject *type, int offset)
3740{
3741 char *ptr;
3742
3743 assert(offset >= 0);
3744 assert(offset < offsetof(etype, as_buffer));
3745 if (offset >= offsetof(etype, as_mapping)) {
3746 ptr = (void *)type->tp_as_mapping;
3747 offset -= offsetof(etype, as_mapping);
3748 }
3749 else if (offset >= offsetof(etype, as_sequence)) {
3750 ptr = (void *)type->tp_as_sequence;
3751 offset -= offsetof(etype, as_sequence);
3752 }
3753 else if (offset >= offsetof(etype, as_number)) {
3754 ptr = (void *)type->tp_as_number;
3755 offset -= offsetof(etype, as_number);
3756 }
3757 else {
3758 ptr = (void *)type;
3759 }
3760 if (ptr != NULL)
3761 ptr += offset;
3762 return (void **)ptr;
3763}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003764
Guido van Rossumc334df52002-04-04 23:44:47 +00003765/* Length of array of slotdef pointers used to store slots with the
3766 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3767 the same __name__, for any __name__. Since that's a static property, it is
3768 appropriate to declare fixed-size arrays for this. */
3769#define MAX_EQUIV 10
3770
3771/* Return a slot pointer for a given name, but ONLY if the attribute has
3772 exactly one slot function. The name must be an interned string. */
3773static void **
3774resolve_slotdups(PyTypeObject *type, PyObject *name)
3775{
3776 /* XXX Maybe this could be optimized more -- but is it worth it? */
3777
3778 /* pname and ptrs act as a little cache */
3779 static PyObject *pname;
3780 static slotdef *ptrs[MAX_EQUIV];
3781 slotdef *p, **pp;
3782 void **res, **ptr;
3783
3784 if (pname != name) {
3785 /* Collect all slotdefs that match name into ptrs. */
3786 pname = name;
3787 pp = ptrs;
3788 for (p = slotdefs; p->name_strobj; p++) {
3789 if (p->name_strobj == name)
3790 *pp++ = p;
3791 }
3792 *pp = NULL;
3793 }
3794
3795 /* Look in all matching slots of the type; if exactly one of these has
3796 a filled-in slot, return its value. Otherwise return NULL. */
3797 res = NULL;
3798 for (pp = ptrs; *pp; pp++) {
3799 ptr = slotptr(type, (*pp)->offset);
3800 if (ptr == NULL || *ptr == NULL)
3801 continue;
3802 if (res != NULL)
3803 return NULL;
3804 res = ptr;
3805 }
3806 return res;
3807}
3808
3809/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3810 does some incredibly complex thinking and then sticks something into the
3811 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3812 interests, and then stores a generic wrapper or a specific function into
3813 the slot.) Return a pointer to the next slotdef with a different offset,
3814 because that's convenient for fixup_slot_dispatchers(). */
3815static slotdef *
3816update_one_slot(PyTypeObject *type, slotdef *p)
3817{
3818 PyObject *descr;
3819 PyWrapperDescrObject *d;
3820 void *generic = NULL, *specific = NULL;
3821 int use_generic = 0;
3822 int offset = p->offset;
3823 void **ptr = slotptr(type, offset);
3824
3825 if (ptr == NULL) {
3826 do {
3827 ++p;
3828 } while (p->offset == offset);
3829 return p;
3830 }
3831 do {
3832 descr = _PyType_Lookup(type, p->name_strobj);
3833 if (descr == NULL)
3834 continue;
3835 if (descr->ob_type == &PyWrapperDescr_Type) {
3836 void **tptr = resolve_slotdups(type, p->name_strobj);
3837 if (tptr == NULL || tptr == ptr)
3838 generic = p->function;
3839 d = (PyWrapperDescrObject *)descr;
3840 if (d->d_base->wrapper == p->wrapper &&
3841 PyType_IsSubtype(type, d->d_type))
3842 {
3843 if (specific == NULL ||
3844 specific == d->d_wrapped)
3845 specific = d->d_wrapped;
3846 else
3847 use_generic = 1;
3848 }
3849 }
3850 else {
3851 use_generic = 1;
3852 generic = p->function;
3853 }
3854 } while ((++p)->offset == offset);
3855 if (specific && !use_generic)
3856 *ptr = specific;
3857 else
3858 *ptr = generic;
3859 return p;
3860}
3861
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003862staticforward int recurse_down_subclasses(PyTypeObject *type,
3863 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003864
Guido van Rossumc334df52002-04-04 23:44:47 +00003865/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
3866 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003867static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003868update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003869{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003870 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003871
Guido van Rossumc334df52002-04-04 23:44:47 +00003872 for (pp = pp0; *pp; pp++)
3873 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003874 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003875}
3876
Guido van Rossumc334df52002-04-04 23:44:47 +00003877/* Update the slots whose slotdefs are gathered in the pp array in all (direct
3878 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003879static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003880recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003881{
3882 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003883 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003884 int i, n;
3885
3886 subclasses = type->tp_subclasses;
3887 if (subclasses == NULL)
3888 return 0;
3889 assert(PyList_Check(subclasses));
3890 n = PyList_GET_SIZE(subclasses);
3891 for (i = 0; i < n; i++) {
3892 ref = PyList_GET_ITEM(subclasses, i);
3893 assert(PyWeakref_CheckRef(ref));
3894 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3895 if (subclass == NULL)
3896 continue;
3897 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003898 /* Avoid recursing down into unaffected classes */
3899 dict = subclass->tp_dict;
3900 if (dict != NULL && PyDict_Check(dict) &&
3901 PyDict_GetItem(dict, name) != NULL)
3902 continue;
3903 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003904 return -1;
3905 }
3906 return 0;
3907}
3908
Guido van Rossumc334df52002-04-04 23:44:47 +00003909/* Comparison function for qsort() to compare slotdefs by their offset, and
3910 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003911static int
3912slotdef_cmp(const void *aa, const void *bb)
3913{
3914 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3915 int c = a->offset - b->offset;
3916 if (c != 0)
3917 return c;
3918 else
3919 return a - b;
3920}
3921
Guido van Rossumc334df52002-04-04 23:44:47 +00003922/* Initialize the slotdefs table by adding interned string objects for the
3923 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003924static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003925init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003926{
3927 slotdef *p;
3928 static int initialized = 0;
3929
3930 if (initialized)
3931 return;
3932 for (p = slotdefs; p->name; p++) {
3933 p->name_strobj = PyString_InternFromString(p->name);
3934 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00003935 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003936 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003937 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3938 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003939 initialized = 1;
3940}
3941
Guido van Rossumc334df52002-04-04 23:44:47 +00003942/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003943static int
3944update_slot(PyTypeObject *type, PyObject *name)
3945{
Guido van Rossumc334df52002-04-04 23:44:47 +00003946 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003947 slotdef *p;
3948 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003949 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003950
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003951 init_slotdefs();
3952 pp = ptrs;
3953 for (p = slotdefs; p->name; p++) {
3954 /* XXX assume name is interned! */
3955 if (p->name_strobj == name)
3956 *pp++ = p;
3957 }
3958 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003959 for (pp = ptrs; *pp; pp++) {
3960 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003961 offset = p->offset;
3962 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003963 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003964 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003965 }
Guido van Rossumc334df52002-04-04 23:44:47 +00003966 if (ptrs[0] == NULL)
3967 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003968 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003969}
3970
Guido van Rossumc334df52002-04-04 23:44:47 +00003971/* Store the proper functions in the slot dispatches at class (type)
3972 definition time, based upon which operations the class overrides in its
3973 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003974static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003975fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003976{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003977 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003979 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00003980 for (p = slotdefs; p->name; )
3981 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003982}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003983
Guido van Rossum6d204072001-10-21 00:44:31 +00003984/* This function is called by PyType_Ready() to populate the type's
3985 dictionary with method descriptors for function slots. For each
3986 function slot (like tp_repr) that's defined in the type, one or
3987 more corresponding descriptors are added in the type's tp_dict
3988 dictionary under the appropriate name (like __repr__). Some
3989 function slots cause more than one descriptor to be added (for
3990 example, the nb_add slot adds both __add__ and __radd__
3991 descriptors) and some function slots compete for the same
3992 descriptor (for example both sq_item and mp_subscript generate a
3993 __getitem__ descriptor). This only adds new descriptors and
3994 doesn't overwrite entries in tp_dict that were previously
3995 defined. The descriptors contain a reference to the C function
3996 they must call, so that it's safe if they are copied into a
3997 subtype's __dict__ and the subtype has a different C function in
3998 its slot -- calling the method defined by the descriptor will call
3999 the C function that was used to create it, rather than the C
4000 function present in the slot when it is called. (This is important
4001 because a subtype may have a C function in the slot that calls the
4002 method from the dictionary, and we want to avoid infinite recursion
4003 here.) */
4004
4005static int
4006add_operators(PyTypeObject *type)
4007{
4008 PyObject *dict = type->tp_dict;
4009 slotdef *p;
4010 PyObject *descr;
4011 void **ptr;
4012
4013 init_slotdefs();
4014 for (p = slotdefs; p->name; p++) {
4015 if (p->wrapper == NULL)
4016 continue;
4017 ptr = slotptr(type, p->offset);
4018 if (!ptr || !*ptr)
4019 continue;
4020 if (PyDict_GetItem(dict, p->name_strobj))
4021 continue;
4022 descr = PyDescr_NewWrapper(type, p, *ptr);
4023 if (descr == NULL)
4024 return -1;
4025 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4026 return -1;
4027 Py_DECREF(descr);
4028 }
4029 if (type->tp_new != NULL) {
4030 if (add_tp_new_wrapper(type) < 0)
4031 return -1;
4032 }
4033 return 0;
4034}
4035
Guido van Rossum705f0f52001-08-24 16:47:00 +00004036
4037/* Cooperative 'super' */
4038
4039typedef struct {
4040 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004041 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004042 PyObject *obj;
4043} superobject;
4044
Guido van Rossum6f799372001-09-20 20:46:19 +00004045static PyMemberDef super_members[] = {
4046 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4047 "the class invoking super()"},
4048 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4049 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004050 {0}
4051};
4052
Guido van Rossum705f0f52001-08-24 16:47:00 +00004053static void
4054super_dealloc(PyObject *self)
4055{
4056 superobject *su = (superobject *)self;
4057
Guido van Rossum048eb752001-10-02 21:24:57 +00004058 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004059 Py_XDECREF(su->obj);
4060 Py_XDECREF(su->type);
4061 self->ob_type->tp_free(self);
4062}
4063
4064static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004065super_repr(PyObject *self)
4066{
4067 superobject *su = (superobject *)self;
4068
4069 if (su->obj)
4070 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004071 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004072 su->type ? su->type->tp_name : "NULL",
4073 su->obj->ob_type->tp_name);
4074 else
4075 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004076 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004077 su->type ? su->type->tp_name : "NULL");
4078}
4079
4080static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004081super_getattro(PyObject *self, PyObject *name)
4082{
4083 superobject *su = (superobject *)self;
4084
4085 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004086 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004087 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004088 descrgetfunc f;
4089 int i, n;
4090
Guido van Rossum155db9a2002-04-02 17:53:47 +00004091 starttype = su->obj->ob_type;
4092 mro = starttype->tp_mro;
4093
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 Rossum705f0f52001-08-24 16:47:00 +00004100 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004101 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004102 break;
4103 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004104 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004105 starttype = (PyTypeObject *)(su->obj);
4106 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004107 if (mro == NULL)
4108 n = 0;
4109 else {
4110 assert(PyTuple_Check(mro));
4111 n = PyTuple_GET_SIZE(mro);
4112 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004113 for (i = 0; i < n; i++) {
4114 if ((PyObject *)(su->type) ==
4115 PyTuple_GET_ITEM(mro, i))
4116 break;
4117 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004118 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004119 i++;
4120 res = NULL;
4121 for (; i < n; i++) {
4122 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004123 if (PyType_Check(tmp))
4124 dict = ((PyTypeObject *)tmp)->tp_dict;
4125 else if (PyClass_Check(tmp))
4126 dict = ((PyClassObject *)tmp)->cl_dict;
4127 else
4128 continue;
4129 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004130 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004131 Py_INCREF(res);
4132 f = res->ob_type->tp_descr_get;
4133 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004134 tmp = f(res, su->obj,
4135 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004136 Py_DECREF(res);
4137 res = tmp;
4138 }
4139 return res;
4140 }
4141 }
4142 }
4143 return PyObject_GenericGetAttr(self, name);
4144}
4145
Guido van Rossum5b443c62001-12-03 15:38:28 +00004146static int
4147supercheck(PyTypeObject *type, PyObject *obj)
4148{
4149 if (!PyType_IsSubtype(obj->ob_type, type) &&
4150 !(PyType_Check(obj) &&
4151 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4152 PyErr_SetString(PyExc_TypeError,
4153 "super(type, obj): "
4154 "obj must be an instance or subtype of type");
4155 return -1;
4156 }
4157 else
4158 return 0;
4159}
4160
Guido van Rossum705f0f52001-08-24 16:47:00 +00004161static PyObject *
4162super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4163{
4164 superobject *su = (superobject *)self;
4165 superobject *new;
4166
4167 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4168 /* Not binding to an object, or already bound */
4169 Py_INCREF(self);
4170 return self;
4171 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004172 if (su->ob_type != &PySuper_Type)
4173 /* If su is an instance of a subclass of super,
4174 call its type */
4175 return PyObject_CallFunction((PyObject *)su->ob_type,
4176 "OO", su->type, obj);
4177 else {
4178 /* Inline the common case */
4179 if (supercheck(su->type, obj) < 0)
4180 return NULL;
4181 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4182 NULL, NULL);
4183 if (new == NULL)
4184 return NULL;
4185 Py_INCREF(su->type);
4186 Py_INCREF(obj);
4187 new->type = su->type;
4188 new->obj = obj;
4189 return (PyObject *)new;
4190 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004191}
4192
4193static int
4194super_init(PyObject *self, PyObject *args, PyObject *kwds)
4195{
4196 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004197 PyTypeObject *type;
4198 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004199
4200 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4201 return -1;
4202 if (obj == Py_None)
4203 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004204 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004205 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004206 Py_INCREF(type);
4207 Py_XINCREF(obj);
4208 su->type = type;
4209 su->obj = obj;
4210 return 0;
4211}
4212
4213static char super_doc[] =
4214"super(type) -> unbound super object\n"
4215"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004216"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004217"Typical use to call a cooperative superclass method:\n"
4218"class C(B):\n"
4219" def meth(self, arg):\n"
4220" super(C, self).meth(arg)";
4221
Guido van Rossum048eb752001-10-02 21:24:57 +00004222static int
4223super_traverse(PyObject *self, visitproc visit, void *arg)
4224{
4225 superobject *su = (superobject *)self;
4226 int err;
4227
4228#define VISIT(SLOT) \
4229 if (SLOT) { \
4230 err = visit((PyObject *)(SLOT), arg); \
4231 if (err) \
4232 return err; \
4233 }
4234
4235 VISIT(su->obj);
4236 VISIT(su->type);
4237
4238#undef VISIT
4239
4240 return 0;
4241}
4242
Guido van Rossum705f0f52001-08-24 16:47:00 +00004243PyTypeObject PySuper_Type = {
4244 PyObject_HEAD_INIT(&PyType_Type)
4245 0, /* ob_size */
4246 "super", /* tp_name */
4247 sizeof(superobject), /* tp_basicsize */
4248 0, /* tp_itemsize */
4249 /* methods */
4250 super_dealloc, /* tp_dealloc */
4251 0, /* tp_print */
4252 0, /* tp_getattr */
4253 0, /* tp_setattr */
4254 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004255 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004256 0, /* tp_as_number */
4257 0, /* tp_as_sequence */
4258 0, /* tp_as_mapping */
4259 0, /* tp_hash */
4260 0, /* tp_call */
4261 0, /* tp_str */
4262 super_getattro, /* tp_getattro */
4263 0, /* tp_setattro */
4264 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004265 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4266 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004267 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004268 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004269 0, /* tp_clear */
4270 0, /* tp_richcompare */
4271 0, /* tp_weaklistoffset */
4272 0, /* tp_iter */
4273 0, /* tp_iternext */
4274 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004275 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004276 0, /* tp_getset */
4277 0, /* tp_base */
4278 0, /* tp_dict */
4279 super_descr_get, /* tp_descr_get */
4280 0, /* tp_descr_set */
4281 0, /* tp_dictoffset */
4282 super_init, /* tp_init */
4283 PyType_GenericAlloc, /* tp_alloc */
4284 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004285 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004286};