blob: 61cbeae377782d9e96ba07149891658c45b36f9c [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;
Guido van Rossum9ee4b942002-05-24 18:47:47 +00001625 if (new->tp_dealloc != old->tp_dealloc ||
1626 new->tp_free != old->tp_free)
1627 {
1628 PyErr_Format(PyExc_TypeError,
1629 "__class__ assignment: "
1630 "'%s' deallocator differs from '%s'",
1631 new->tp_name,
1632 old->tp_name);
1633 return -1;
1634 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001635 newbase = new;
1636 oldbase = old;
1637 while (equiv_structs(newbase, newbase->tp_base))
1638 newbase = newbase->tp_base;
1639 while (equiv_structs(oldbase, oldbase->tp_base))
1640 oldbase = oldbase->tp_base;
1641 if (newbase != oldbase &&
1642 (newbase->tp_base != oldbase->tp_base ||
1643 !same_slots_added(newbase, oldbase))) {
1644 PyErr_Format(PyExc_TypeError,
1645 "__class__ assignment: "
1646 "'%s' object layout differs from '%s'",
Tim Peters2f93e282001-10-04 05:27:00 +00001647 new->tp_name,
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001648 old->tp_name);
1649 return -1;
1650 }
1651 if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1652 Py_INCREF(new);
1653 }
1654 self->ob_type = new;
1655 if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
1656 Py_DECREF(old);
1657 }
1658 return 0;
1659}
1660
1661static PyGetSetDef object_getsets[] = {
1662 {"__class__", object_get_class, object_set_class,
1663 "the object's class"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001664 {0}
1665};
1666
Guido van Rossum3926a632001-09-25 16:25:58 +00001667static PyObject *
1668object_reduce(PyObject *self, PyObject *args)
1669{
1670 /* Call copy_reg._reduce(self) */
1671 static PyObject *copy_reg_str;
1672 PyObject *copy_reg, *res;
1673
1674 if (!copy_reg_str) {
1675 copy_reg_str = PyString_InternFromString("copy_reg");
1676 if (copy_reg_str == NULL)
1677 return NULL;
1678 }
1679 copy_reg = PyImport_Import(copy_reg_str);
1680 if (!copy_reg)
1681 return NULL;
1682 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
1683 Py_DECREF(copy_reg);
1684 return res;
1685}
1686
1687static PyMethodDef object_methods[] = {
1688 {"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
1689 {0}
1690};
1691
Tim Peters6d6c1a32001-08-02 04:15:00 +00001692PyTypeObject PyBaseObject_Type = {
1693 PyObject_HEAD_INIT(&PyType_Type)
1694 0, /* ob_size */
1695 "object", /* tp_name */
1696 sizeof(PyObject), /* tp_basicsize */
1697 0, /* tp_itemsize */
1698 (destructor)object_dealloc, /* tp_dealloc */
1699 0, /* tp_print */
1700 0, /* tp_getattr */
1701 0, /* tp_setattr */
1702 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001703 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001704 0, /* tp_as_number */
1705 0, /* tp_as_sequence */
1706 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001707 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001708 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00001709 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001710 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001711 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001712 0, /* tp_as_buffer */
1713 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1714 "The most base type", /* tp_doc */
1715 0, /* tp_traverse */
1716 0, /* tp_clear */
1717 0, /* tp_richcompare */
1718 0, /* tp_weaklistoffset */
1719 0, /* tp_iter */
1720 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00001721 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001722 0, /* tp_members */
1723 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001724 0, /* tp_base */
1725 0, /* tp_dict */
1726 0, /* tp_descr_get */
1727 0, /* tp_descr_set */
1728 0, /* tp_dictoffset */
1729 object_init, /* tp_init */
1730 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00001731 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001732 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001733};
1734
1735
1736/* Initialize the __dict__ in a type object */
1737
Fred Drake7bf97152002-03-28 05:33:33 +00001738static PyObject *
1739create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
1740{
1741 PyObject *cfunc;
1742 PyObject *result;
1743
1744 cfunc = PyCFunction_New(meth, NULL);
1745 if (cfunc == NULL)
1746 return NULL;
1747 result = func(cfunc);
1748 Py_DECREF(cfunc);
1749 return result;
1750}
1751
Tim Peters6d6c1a32001-08-02 04:15:00 +00001752static int
1753add_methods(PyTypeObject *type, PyMethodDef *meth)
1754{
Guido van Rossum687ae002001-10-15 22:03:32 +00001755 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001756
1757 for (; meth->ml_name != NULL; meth++) {
1758 PyObject *descr;
1759 if (PyDict_GetItemString(dict, meth->ml_name))
1760 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00001761 if (meth->ml_flags & METH_CLASS) {
1762 if (meth->ml_flags & METH_STATIC) {
1763 PyErr_SetString(PyExc_ValueError,
1764 "method cannot be both class and static");
1765 return -1;
1766 }
1767 descr = create_specialmethod(meth, PyClassMethod_New);
1768 }
1769 else if (meth->ml_flags & METH_STATIC) {
1770 descr = create_specialmethod(meth, PyStaticMethod_New);
1771 }
1772 else {
1773 descr = PyDescr_NewMethod(type, meth);
1774 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775 if (descr == NULL)
1776 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00001777 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778 return -1;
1779 Py_DECREF(descr);
1780 }
1781 return 0;
1782}
1783
1784static int
Guido van Rossum6f799372001-09-20 20:46:19 +00001785add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001786{
Guido van Rossum687ae002001-10-15 22:03:32 +00001787 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788
1789 for (; memb->name != NULL; memb++) {
1790 PyObject *descr;
1791 if (PyDict_GetItemString(dict, memb->name))
1792 continue;
1793 descr = PyDescr_NewMember(type, memb);
1794 if (descr == NULL)
1795 return -1;
1796 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1797 return -1;
1798 Py_DECREF(descr);
1799 }
1800 return 0;
1801}
1802
1803static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00001804add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001805{
Guido van Rossum687ae002001-10-15 22:03:32 +00001806 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807
1808 for (; gsp->name != NULL; gsp++) {
1809 PyObject *descr;
1810 if (PyDict_GetItemString(dict, gsp->name))
1811 continue;
1812 descr = PyDescr_NewGetSet(type, gsp);
1813
1814 if (descr == NULL)
1815 return -1;
1816 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1817 return -1;
1818 Py_DECREF(descr);
1819 }
1820 return 0;
1821}
1822
Guido van Rossum13d52f02001-08-10 21:24:08 +00001823static void
1824inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001825{
1826 int oldsize, newsize;
1827
Guido van Rossum13d52f02001-08-10 21:24:08 +00001828 /* Special flag magic */
1829 if (!type->tp_as_buffer && base->tp_as_buffer) {
1830 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
1831 type->tp_flags |=
1832 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
1833 }
1834 if (!type->tp_as_sequence && base->tp_as_sequence) {
1835 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
1836 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1837 }
1838 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1839 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1840 if ((!type->tp_as_number && base->tp_as_number) ||
1841 (!type->tp_as_sequence && base->tp_as_sequence)) {
1842 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1843 if (!type->tp_as_number && !type->tp_as_sequence) {
1844 type->tp_flags |= base->tp_flags &
1845 Py_TPFLAGS_HAVE_INPLACEOPS;
1846 }
1847 }
1848 /* Wow */
1849 }
1850 if (!type->tp_as_number && base->tp_as_number) {
1851 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1852 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1853 }
1854
1855 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00001856 oldsize = base->tp_basicsize;
1857 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
1858 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
1859 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00001860 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1861 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00001862 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001863 if (type->tp_traverse == NULL)
1864 type->tp_traverse = base->tp_traverse;
1865 if (type->tp_clear == NULL)
1866 type->tp_clear = base->tp_clear;
1867 }
1868 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00001869 /* The condition below could use some explanation.
1870 It appears that tp_new is not inherited for static types
1871 whose base class is 'object'; this seems to be a precaution
1872 so that old extension types don't suddenly become
1873 callable (object.__new__ wouldn't insure the invariants
1874 that the extension type's own factory function ensures).
1875 Heap types, of course, are under our control, so they do
1876 inherit tp_new; static extension types that specify some
1877 other built-in type as the default are considered
1878 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00001879 if (base != &PyBaseObject_Type ||
1880 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1881 if (type->tp_new == NULL)
1882 type->tp_new = base->tp_new;
1883 }
1884 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00001885 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00001886
1887 /* Copy other non-function slots */
1888
1889#undef COPYVAL
1890#define COPYVAL(SLOT) \
1891 if (type->SLOT == 0) type->SLOT = base->SLOT
1892
1893 COPYVAL(tp_itemsize);
1894 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1895 COPYVAL(tp_weaklistoffset);
1896 }
1897 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1898 COPYVAL(tp_dictoffset);
1899 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00001900}
1901
1902static void
1903inherit_slots(PyTypeObject *type, PyTypeObject *base)
1904{
1905 PyTypeObject *basebase;
1906
1907#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00001908#undef COPYSLOT
1909#undef COPYNUM
1910#undef COPYSEQ
1911#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00001912#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00001913
1914#define SLOTDEFINED(SLOT) \
1915 (base->SLOT != 0 && \
1916 (basebase == NULL || base->SLOT != basebase->SLOT))
1917
Tim Peters6d6c1a32001-08-02 04:15:00 +00001918#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00001919 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00001920
1921#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1922#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1923#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00001924#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001925
Guido van Rossum13d52f02001-08-10 21:24:08 +00001926 /* This won't inherit indirect slots (from tp_as_number etc.)
1927 if type doesn't provide the space. */
1928
1929 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1930 basebase = base->tp_base;
1931 if (basebase->tp_as_number == NULL)
1932 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001933 COPYNUM(nb_add);
1934 COPYNUM(nb_subtract);
1935 COPYNUM(nb_multiply);
1936 COPYNUM(nb_divide);
1937 COPYNUM(nb_remainder);
1938 COPYNUM(nb_divmod);
1939 COPYNUM(nb_power);
1940 COPYNUM(nb_negative);
1941 COPYNUM(nb_positive);
1942 COPYNUM(nb_absolute);
1943 COPYNUM(nb_nonzero);
1944 COPYNUM(nb_invert);
1945 COPYNUM(nb_lshift);
1946 COPYNUM(nb_rshift);
1947 COPYNUM(nb_and);
1948 COPYNUM(nb_xor);
1949 COPYNUM(nb_or);
1950 COPYNUM(nb_coerce);
1951 COPYNUM(nb_int);
1952 COPYNUM(nb_long);
1953 COPYNUM(nb_float);
1954 COPYNUM(nb_oct);
1955 COPYNUM(nb_hex);
1956 COPYNUM(nb_inplace_add);
1957 COPYNUM(nb_inplace_subtract);
1958 COPYNUM(nb_inplace_multiply);
1959 COPYNUM(nb_inplace_divide);
1960 COPYNUM(nb_inplace_remainder);
1961 COPYNUM(nb_inplace_power);
1962 COPYNUM(nb_inplace_lshift);
1963 COPYNUM(nb_inplace_rshift);
1964 COPYNUM(nb_inplace_and);
1965 COPYNUM(nb_inplace_xor);
1966 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00001967 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1968 COPYNUM(nb_true_divide);
1969 COPYNUM(nb_floor_divide);
1970 COPYNUM(nb_inplace_true_divide);
1971 COPYNUM(nb_inplace_floor_divide);
1972 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001973 }
1974
Guido van Rossum13d52f02001-08-10 21:24:08 +00001975 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1976 basebase = base->tp_base;
1977 if (basebase->tp_as_sequence == NULL)
1978 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001979 COPYSEQ(sq_length);
1980 COPYSEQ(sq_concat);
1981 COPYSEQ(sq_repeat);
1982 COPYSEQ(sq_item);
1983 COPYSEQ(sq_slice);
1984 COPYSEQ(sq_ass_item);
1985 COPYSEQ(sq_ass_slice);
1986 COPYSEQ(sq_contains);
1987 COPYSEQ(sq_inplace_concat);
1988 COPYSEQ(sq_inplace_repeat);
1989 }
1990
Guido van Rossum13d52f02001-08-10 21:24:08 +00001991 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1992 basebase = base->tp_base;
1993 if (basebase->tp_as_mapping == NULL)
1994 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001995 COPYMAP(mp_length);
1996 COPYMAP(mp_subscript);
1997 COPYMAP(mp_ass_subscript);
1998 }
1999
Tim Petersfc57ccb2001-10-12 02:38:24 +00002000 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2001 basebase = base->tp_base;
2002 if (basebase->tp_as_buffer == NULL)
2003 basebase = NULL;
2004 COPYBUF(bf_getreadbuffer);
2005 COPYBUF(bf_getwritebuffer);
2006 COPYBUF(bf_getsegcount);
2007 COPYBUF(bf_getcharbuffer);
2008 }
2009
Guido van Rossum13d52f02001-08-10 21:24:08 +00002010 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002011
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012 COPYSLOT(tp_dealloc);
2013 COPYSLOT(tp_print);
2014 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2015 type->tp_getattr = base->tp_getattr;
2016 type->tp_getattro = base->tp_getattro;
2017 }
2018 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2019 type->tp_setattr = base->tp_setattr;
2020 type->tp_setattro = base->tp_setattro;
2021 }
2022 /* tp_compare see tp_richcompare */
2023 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002024 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025 COPYSLOT(tp_call);
2026 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002027 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002028 if (type->tp_compare == NULL &&
2029 type->tp_richcompare == NULL &&
2030 type->tp_hash == NULL)
2031 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002032 type->tp_compare = base->tp_compare;
2033 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002034 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035 }
2036 }
2037 else {
2038 COPYSLOT(tp_compare);
2039 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2041 COPYSLOT(tp_iter);
2042 COPYSLOT(tp_iternext);
2043 }
2044 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2045 COPYSLOT(tp_descr_get);
2046 COPYSLOT(tp_descr_set);
2047 COPYSLOT(tp_dictoffset);
2048 COPYSLOT(tp_init);
2049 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002050 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002051 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002052 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002053}
2054
Guido van Rossum13d52f02001-08-10 21:24:08 +00002055staticforward int add_operators(PyTypeObject *);
Guido van Rossum1c450732001-10-08 15:18:27 +00002056staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002057
Tim Peters6d6c1a32001-08-02 04:15:00 +00002058int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002059PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002060{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002061 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002062 PyTypeObject *base;
2063 int i, n;
2064
Guido van Rossumd614f972001-08-10 17:39:49 +00002065 if (type->tp_flags & Py_TPFLAGS_READY) {
2066 assert(type->tp_dict != NULL);
2067 return 0;
2068 }
2069 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002070
2071 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002072
2073 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2074 base = type->tp_base;
2075 if (base == NULL && type != &PyBaseObject_Type)
2076 base = type->tp_base = &PyBaseObject_Type;
2077
Guido van Rossum0986d822002-04-08 01:38:42 +00002078 /* Initialize ob_type if NULL. This means extensions that want to be
2079 compilable separately on Windows can call PyType_Ready() instead of
2080 initializing the ob_type field of their type objects. */
2081 if (type->ob_type == NULL)
2082 type->ob_type = base->ob_type;
2083
Tim Peters6d6c1a32001-08-02 04:15:00 +00002084 /* Initialize tp_bases */
2085 bases = type->tp_bases;
2086 if (bases == NULL) {
2087 if (base == NULL)
2088 bases = PyTuple_New(0);
2089 else
2090 bases = Py_BuildValue("(O)", base);
2091 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002092 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002093 type->tp_bases = bases;
2094 }
2095
2096 /* Initialize the base class */
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002097 if (base && base->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002098 if (PyType_Ready(base) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002099 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002100 }
2101
Guido van Rossum687ae002001-10-15 22:03:32 +00002102 /* Initialize tp_dict */
2103 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002104 if (dict == NULL) {
2105 dict = PyDict_New();
2106 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002107 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002108 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002109 }
2110
Guido van Rossum687ae002001-10-15 22:03:32 +00002111 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002112 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002113 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002114 if (type->tp_methods != NULL) {
2115 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002116 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002117 }
2118 if (type->tp_members != NULL) {
2119 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002120 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002121 }
2122 if (type->tp_getset != NULL) {
2123 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002124 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002125 }
2126
Tim Peters6d6c1a32001-08-02 04:15:00 +00002127 /* Calculate method resolution order */
2128 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002129 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002130 }
2131
Guido van Rossum13d52f02001-08-10 21:24:08 +00002132 /* Inherit special flags from dominant base */
2133 if (type->tp_base != NULL)
2134 inherit_special(type, type->tp_base);
2135
Tim Peters6d6c1a32001-08-02 04:15:00 +00002136 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002137 bases = type->tp_mro;
2138 assert(bases != NULL);
2139 assert(PyTuple_Check(bases));
2140 n = PyTuple_GET_SIZE(bases);
2141 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002142 PyObject *b = PyTuple_GET_ITEM(bases, i);
2143 if (PyType_Check(b))
2144 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002145 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002146
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002147 /* if the type dictionary doesn't contain a __doc__, set it from
2148 the tp_doc slot.
2149 */
2150 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2151 if (type->tp_doc != NULL) {
2152 PyObject *doc = PyString_FromString(type->tp_doc);
2153 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2154 Py_DECREF(doc);
2155 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002156 PyDict_SetItemString(type->tp_dict,
2157 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002158 }
2159 }
2160
Guido van Rossum13d52f02001-08-10 21:24:08 +00002161 /* Some more special stuff */
2162 base = type->tp_base;
2163 if (base != NULL) {
2164 if (type->tp_as_number == NULL)
2165 type->tp_as_number = base->tp_as_number;
2166 if (type->tp_as_sequence == NULL)
2167 type->tp_as_sequence = base->tp_as_sequence;
2168 if (type->tp_as_mapping == NULL)
2169 type->tp_as_mapping = base->tp_as_mapping;
2170 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002171
Guido van Rossum1c450732001-10-08 15:18:27 +00002172 /* Link into each base class's list of subclasses */
2173 bases = type->tp_bases;
2174 n = PyTuple_GET_SIZE(bases);
2175 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002176 PyObject *b = PyTuple_GET_ITEM(bases, i);
2177 if (PyType_Check(b) &&
2178 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002179 goto error;
2180 }
2181
Guido van Rossum13d52f02001-08-10 21:24:08 +00002182 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002183 assert(type->tp_dict != NULL);
2184 type->tp_flags =
2185 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002186 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002187
2188 error:
2189 type->tp_flags &= ~Py_TPFLAGS_READYING;
2190 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002191}
2192
Guido van Rossum1c450732001-10-08 15:18:27 +00002193static int
2194add_subclass(PyTypeObject *base, PyTypeObject *type)
2195{
2196 int i;
2197 PyObject *list, *ref, *new;
2198
2199 list = base->tp_subclasses;
2200 if (list == NULL) {
2201 base->tp_subclasses = list = PyList_New(0);
2202 if (list == NULL)
2203 return -1;
2204 }
2205 assert(PyList_Check(list));
2206 new = PyWeakref_NewRef((PyObject *)type, NULL);
2207 i = PyList_GET_SIZE(list);
2208 while (--i >= 0) {
2209 ref = PyList_GET_ITEM(list, i);
2210 assert(PyWeakref_CheckRef(ref));
2211 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2212 return PyList_SetItem(list, i, new);
2213 }
2214 i = PyList_Append(list, new);
2215 Py_DECREF(new);
2216 return i;
2217}
2218
Tim Peters6d6c1a32001-08-02 04:15:00 +00002219
2220/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2221
2222/* There's a wrapper *function* for each distinct function typedef used
2223 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2224 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2225 Most tables have only one entry; the tables for binary operators have two
2226 entries, one regular and one with reversed arguments. */
2227
2228static PyObject *
2229wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2230{
2231 inquiry func = (inquiry)wrapped;
2232 int res;
2233
2234 if (!PyArg_ParseTuple(args, ""))
2235 return NULL;
2236 res = (*func)(self);
2237 if (res == -1 && PyErr_Occurred())
2238 return NULL;
2239 return PyInt_FromLong((long)res);
2240}
2241
Tim Peters6d6c1a32001-08-02 04:15:00 +00002242static PyObject *
2243wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2244{
2245 binaryfunc func = (binaryfunc)wrapped;
2246 PyObject *other;
2247
2248 if (!PyArg_ParseTuple(args, "O", &other))
2249 return NULL;
2250 return (*func)(self, other);
2251}
2252
2253static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002254wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2255{
2256 binaryfunc func = (binaryfunc)wrapped;
2257 PyObject *other;
2258
2259 if (!PyArg_ParseTuple(args, "O", &other))
2260 return NULL;
2261 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002262 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002263 Py_INCREF(Py_NotImplemented);
2264 return Py_NotImplemented;
2265 }
2266 return (*func)(self, other);
2267}
2268
2269static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002270wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2271{
2272 binaryfunc func = (binaryfunc)wrapped;
2273 PyObject *other;
2274
2275 if (!PyArg_ParseTuple(args, "O", &other))
2276 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002277 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002278 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002279 Py_INCREF(Py_NotImplemented);
2280 return Py_NotImplemented;
2281 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002282 return (*func)(other, self);
2283}
2284
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002285static PyObject *
2286wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2287{
2288 coercion func = (coercion)wrapped;
2289 PyObject *other, *res;
2290 int ok;
2291
2292 if (!PyArg_ParseTuple(args, "O", &other))
2293 return NULL;
2294 ok = func(&self, &other);
2295 if (ok < 0)
2296 return NULL;
2297 if (ok > 0) {
2298 Py_INCREF(Py_NotImplemented);
2299 return Py_NotImplemented;
2300 }
2301 res = PyTuple_New(2);
2302 if (res == NULL) {
2303 Py_DECREF(self);
2304 Py_DECREF(other);
2305 return NULL;
2306 }
2307 PyTuple_SET_ITEM(res, 0, self);
2308 PyTuple_SET_ITEM(res, 1, other);
2309 return res;
2310}
2311
Tim Peters6d6c1a32001-08-02 04:15:00 +00002312static PyObject *
2313wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2314{
2315 ternaryfunc func = (ternaryfunc)wrapped;
2316 PyObject *other;
2317 PyObject *third = Py_None;
2318
2319 /* Note: This wrapper only works for __pow__() */
2320
2321 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2322 return NULL;
2323 return (*func)(self, other, third);
2324}
2325
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002326static PyObject *
2327wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2328{
2329 ternaryfunc func = (ternaryfunc)wrapped;
2330 PyObject *other;
2331 PyObject *third = Py_None;
2332
2333 /* Note: This wrapper only works for __pow__() */
2334
2335 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2336 return NULL;
2337 return (*func)(other, self, third);
2338}
2339
Tim Peters6d6c1a32001-08-02 04:15:00 +00002340static PyObject *
2341wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2342{
2343 unaryfunc func = (unaryfunc)wrapped;
2344
2345 if (!PyArg_ParseTuple(args, ""))
2346 return NULL;
2347 return (*func)(self);
2348}
2349
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350static PyObject *
2351wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
2352{
2353 intargfunc func = (intargfunc)wrapped;
2354 int i;
2355
2356 if (!PyArg_ParseTuple(args, "i", &i))
2357 return NULL;
2358 return (*func)(self, i);
2359}
2360
Guido van Rossum5d815f32001-08-17 21:57:47 +00002361static int
2362getindex(PyObject *self, PyObject *arg)
2363{
2364 int i;
2365
2366 i = PyInt_AsLong(arg);
2367 if (i == -1 && PyErr_Occurred())
2368 return -1;
2369 if (i < 0) {
2370 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
2371 if (sq && sq->sq_length) {
2372 int n = (*sq->sq_length)(self);
2373 if (n < 0)
2374 return -1;
2375 i += n;
2376 }
2377 }
2378 return i;
2379}
2380
2381static PyObject *
2382wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
2383{
2384 intargfunc func = (intargfunc)wrapped;
2385 PyObject *arg;
2386 int i;
2387
Guido van Rossumf4593e02001-10-03 12:09:30 +00002388 if (PyTuple_GET_SIZE(args) == 1) {
2389 arg = PyTuple_GET_ITEM(args, 0);
2390 i = getindex(self, arg);
2391 if (i == -1 && PyErr_Occurred())
2392 return NULL;
2393 return (*func)(self, i);
2394 }
2395 PyArg_ParseTuple(args, "O", &arg);
2396 assert(PyErr_Occurred());
2397 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002398}
2399
Tim Peters6d6c1a32001-08-02 04:15:00 +00002400static PyObject *
2401wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
2402{
2403 intintargfunc func = (intintargfunc)wrapped;
2404 int i, j;
2405
2406 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2407 return NULL;
2408 return (*func)(self, i, j);
2409}
2410
Tim Peters6d6c1a32001-08-02 04:15:00 +00002411static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002412wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002413{
2414 intobjargproc func = (intobjargproc)wrapped;
2415 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002416 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002417
Guido van Rossum5d815f32001-08-17 21:57:47 +00002418 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
2419 return NULL;
2420 i = getindex(self, arg);
2421 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00002422 return NULL;
2423 res = (*func)(self, i, value);
2424 if (res == -1 && PyErr_Occurred())
2425 return NULL;
2426 Py_INCREF(Py_None);
2427 return Py_None;
2428}
2429
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002430static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00002431wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002432{
2433 intobjargproc func = (intobjargproc)wrapped;
2434 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00002435 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002436
Guido van Rossum5d815f32001-08-17 21:57:47 +00002437 if (!PyArg_ParseTuple(args, "O", &arg))
2438 return NULL;
2439 i = getindex(self, arg);
2440 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002441 return NULL;
2442 res = (*func)(self, i, NULL);
2443 if (res == -1 && PyErr_Occurred())
2444 return NULL;
2445 Py_INCREF(Py_None);
2446 return Py_None;
2447}
2448
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449static PyObject *
2450wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
2451{
2452 intintobjargproc func = (intintobjargproc)wrapped;
2453 int i, j, res;
2454 PyObject *value;
2455
2456 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
2457 return NULL;
2458 res = (*func)(self, i, j, value);
2459 if (res == -1 && PyErr_Occurred())
2460 return NULL;
2461 Py_INCREF(Py_None);
2462 return Py_None;
2463}
2464
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002465static PyObject *
2466wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
2467{
2468 intintobjargproc func = (intintobjargproc)wrapped;
2469 int i, j, res;
2470
2471 if (!PyArg_ParseTuple(args, "ii", &i, &j))
2472 return NULL;
2473 res = (*func)(self, i, j, NULL);
2474 if (res == -1 && PyErr_Occurred())
2475 return NULL;
2476 Py_INCREF(Py_None);
2477 return Py_None;
2478}
2479
Tim Peters6d6c1a32001-08-02 04:15:00 +00002480/* XXX objobjproc is a misnomer; should be objargpred */
2481static PyObject *
2482wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
2483{
2484 objobjproc func = (objobjproc)wrapped;
2485 int res;
2486 PyObject *value;
2487
2488 if (!PyArg_ParseTuple(args, "O", &value))
2489 return NULL;
2490 res = (*func)(self, value);
2491 if (res == -1 && PyErr_Occurred())
2492 return NULL;
2493 return PyInt_FromLong((long)res);
2494}
2495
Tim Peters6d6c1a32001-08-02 04:15:00 +00002496static PyObject *
2497wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
2498{
2499 objobjargproc func = (objobjargproc)wrapped;
2500 int res;
2501 PyObject *key, *value;
2502
2503 if (!PyArg_ParseTuple(args, "OO", &key, &value))
2504 return NULL;
2505 res = (*func)(self, key, value);
2506 if (res == -1 && PyErr_Occurred())
2507 return NULL;
2508 Py_INCREF(Py_None);
2509 return Py_None;
2510}
2511
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00002512static PyObject *
2513wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
2514{
2515 objobjargproc func = (objobjargproc)wrapped;
2516 int res;
2517 PyObject *key;
2518
2519 if (!PyArg_ParseTuple(args, "O", &key))
2520 return NULL;
2521 res = (*func)(self, key, NULL);
2522 if (res == -1 && PyErr_Occurred())
2523 return NULL;
2524 Py_INCREF(Py_None);
2525 return Py_None;
2526}
2527
Tim Peters6d6c1a32001-08-02 04:15:00 +00002528static PyObject *
2529wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
2530{
2531 cmpfunc func = (cmpfunc)wrapped;
2532 int res;
2533 PyObject *other;
2534
2535 if (!PyArg_ParseTuple(args, "O", &other))
2536 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00002537 if (other->ob_type->tp_compare != func &&
2538 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00002539 PyErr_Format(
2540 PyExc_TypeError,
2541 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
2542 self->ob_type->tp_name,
2543 self->ob_type->tp_name,
2544 other->ob_type->tp_name);
2545 return NULL;
2546 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002547 res = (*func)(self, other);
2548 if (PyErr_Occurred())
2549 return NULL;
2550 return PyInt_FromLong((long)res);
2551}
2552
Tim Peters6d6c1a32001-08-02 04:15:00 +00002553static PyObject *
2554wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
2555{
2556 setattrofunc func = (setattrofunc)wrapped;
2557 int res;
2558 PyObject *name, *value;
2559
2560 if (!PyArg_ParseTuple(args, "OO", &name, &value))
2561 return NULL;
2562 res = (*func)(self, name, value);
2563 if (res < 0)
2564 return NULL;
2565 Py_INCREF(Py_None);
2566 return Py_None;
2567}
2568
2569static PyObject *
2570wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
2571{
2572 setattrofunc func = (setattrofunc)wrapped;
2573 int res;
2574 PyObject *name;
2575
2576 if (!PyArg_ParseTuple(args, "O", &name))
2577 return NULL;
2578 res = (*func)(self, name, NULL);
2579 if (res < 0)
2580 return NULL;
2581 Py_INCREF(Py_None);
2582 return Py_None;
2583}
2584
Tim Peters6d6c1a32001-08-02 04:15:00 +00002585static PyObject *
2586wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
2587{
2588 hashfunc func = (hashfunc)wrapped;
2589 long res;
2590
2591 if (!PyArg_ParseTuple(args, ""))
2592 return NULL;
2593 res = (*func)(self);
2594 if (res == -1 && PyErr_Occurred())
2595 return NULL;
2596 return PyInt_FromLong(res);
2597}
2598
Tim Peters6d6c1a32001-08-02 04:15:00 +00002599static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002600wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002601{
2602 ternaryfunc func = (ternaryfunc)wrapped;
2603
Guido van Rossumc8e56452001-10-22 00:43:43 +00002604 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002605}
2606
Tim Peters6d6c1a32001-08-02 04:15:00 +00002607static PyObject *
2608wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
2609{
2610 richcmpfunc func = (richcmpfunc)wrapped;
2611 PyObject *other;
2612
2613 if (!PyArg_ParseTuple(args, "O", &other))
2614 return NULL;
2615 return (*func)(self, other, op);
2616}
2617
2618#undef RICHCMP_WRAPPER
2619#define RICHCMP_WRAPPER(NAME, OP) \
2620static PyObject * \
2621richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
2622{ \
2623 return wrap_richcmpfunc(self, args, wrapped, OP); \
2624}
2625
Jack Jansen8e938b42001-08-08 15:29:49 +00002626RICHCMP_WRAPPER(lt, Py_LT)
2627RICHCMP_WRAPPER(le, Py_LE)
2628RICHCMP_WRAPPER(eq, Py_EQ)
2629RICHCMP_WRAPPER(ne, Py_NE)
2630RICHCMP_WRAPPER(gt, Py_GT)
2631RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002632
Tim Peters6d6c1a32001-08-02 04:15:00 +00002633static PyObject *
2634wrap_next(PyObject *self, PyObject *args, void *wrapped)
2635{
2636 unaryfunc func = (unaryfunc)wrapped;
2637 PyObject *res;
2638
2639 if (!PyArg_ParseTuple(args, ""))
2640 return NULL;
2641 res = (*func)(self);
2642 if (res == NULL && !PyErr_Occurred())
2643 PyErr_SetNone(PyExc_StopIteration);
2644 return res;
2645}
2646
Tim Peters6d6c1a32001-08-02 04:15:00 +00002647static PyObject *
2648wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
2649{
2650 descrgetfunc func = (descrgetfunc)wrapped;
2651 PyObject *obj;
2652 PyObject *type = NULL;
2653
2654 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
2655 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002656 return (*func)(self, obj, type);
2657}
2658
Tim Peters6d6c1a32001-08-02 04:15:00 +00002659static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002660wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002661{
2662 descrsetfunc func = (descrsetfunc)wrapped;
2663 PyObject *obj, *value;
2664 int ret;
2665
2666 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
2667 return NULL;
2668 ret = (*func)(self, obj, value);
2669 if (ret < 0)
2670 return NULL;
2671 Py_INCREF(Py_None);
2672 return Py_None;
2673}
2674
Tim Peters6d6c1a32001-08-02 04:15:00 +00002675static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00002676wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002677{
2678 initproc func = (initproc)wrapped;
2679
Guido van Rossumc8e56452001-10-22 00:43:43 +00002680 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002681 return NULL;
2682 Py_INCREF(Py_None);
2683 return Py_None;
2684}
2685
Tim Peters6d6c1a32001-08-02 04:15:00 +00002686static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002687tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002688{
Barry Warsaw60f01882001-08-22 19:24:42 +00002689 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002690 PyObject *arg0, *res;
2691
2692 if (self == NULL || !PyType_Check(self))
2693 Py_FatalError("__new__() called with non-type 'self'");
2694 type = (PyTypeObject *)self;
2695 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002696 PyErr_Format(PyExc_TypeError,
2697 "%s.__new__(): not enough arguments",
2698 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002699 return NULL;
2700 }
2701 arg0 = PyTuple_GET_ITEM(args, 0);
2702 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002703 PyErr_Format(PyExc_TypeError,
2704 "%s.__new__(X): X is not a type object (%s)",
2705 type->tp_name,
2706 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002707 return NULL;
2708 }
2709 subtype = (PyTypeObject *)arg0;
2710 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002711 PyErr_Format(PyExc_TypeError,
2712 "%s.__new__(%s): %s is not a subtype of %s",
2713 type->tp_name,
2714 subtype->tp_name,
2715 subtype->tp_name,
2716 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002717 return NULL;
2718 }
Barry Warsaw60f01882001-08-22 19:24:42 +00002719
2720 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00002721 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00002722 most derived base that's not a heap type is this type. */
2723 staticbase = subtype;
2724 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
2725 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00002726 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00002727 PyErr_Format(PyExc_TypeError,
2728 "%s.__new__(%s) is not safe, use %s.__new__()",
2729 type->tp_name,
2730 subtype->tp_name,
2731 staticbase == NULL ? "?" : staticbase->tp_name);
2732 return NULL;
2733 }
2734
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002735 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
2736 if (args == NULL)
2737 return NULL;
2738 res = type->tp_new(subtype, args, kwds);
2739 Py_DECREF(args);
2740 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002741}
2742
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002743static struct PyMethodDef tp_new_methoddef[] = {
2744 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
2745 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002746 {0}
2747};
2748
2749static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002750add_tp_new_wrapper(PyTypeObject *type)
2751{
Guido van Rossumf040ede2001-08-07 16:40:56 +00002752 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002753
Guido van Rossum687ae002001-10-15 22:03:32 +00002754 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00002755 return 0;
2756 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002757 if (func == NULL)
2758 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00002759 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00002760}
2761
Guido van Rossumf040ede2001-08-07 16:40:56 +00002762/* Slot wrappers that call the corresponding __foo__ slot. See comments
2763 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002764
Guido van Rossumdc91b992001-08-08 22:26:22 +00002765#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002767FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002768{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00002769 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002770 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771}
2772
Guido van Rossumdc91b992001-08-08 22:26:22 +00002773#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002774static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002775FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002776{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002777 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002778 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002779}
2780
Guido van Rossumdc91b992001-08-08 22:26:22 +00002781
2782#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002783static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002784FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002785{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002786 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002787 int do_other = self->ob_type != other->ob_type && \
2788 other->ob_type->tp_as_number != NULL && \
2789 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002790 if (self->ob_type->tp_as_number != NULL && \
2791 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2792 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00002793 if (do_other && \
2794 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
2795 r = call_maybe( \
2796 other, ROPSTR, &rcache_str, "(O)", self); \
2797 if (r != Py_NotImplemented) \
2798 return r; \
2799 Py_DECREF(r); \
2800 do_other = 0; \
2801 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002802 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002803 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002804 if (r != Py_NotImplemented || \
2805 other->ob_type == self->ob_type) \
2806 return r; \
2807 Py_DECREF(r); \
2808 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00002809 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00002810 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00002811 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00002812 } \
2813 Py_INCREF(Py_NotImplemented); \
2814 return Py_NotImplemented; \
2815}
2816
2817#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2818 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2819
2820#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2821static PyObject * \
2822FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2823{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00002824 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00002825 return call_method(self, OPSTR, &cache_str, \
2826 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00002827}
2828
2829static int
2830slot_sq_length(PyObject *self)
2831{
Guido van Rossum2730b132001-08-28 18:22:14 +00002832 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00002833 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00002834 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002835
2836 if (res == NULL)
2837 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00002838 len = (int)PyInt_AsLong(res);
2839 Py_DECREF(res);
2840 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002841}
2842
Guido van Rossumdc91b992001-08-08 22:26:22 +00002843SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2844SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00002845
2846/* Super-optimized version of slot_sq_item.
2847 Other slots could do the same... */
2848static PyObject *
2849slot_sq_item(PyObject *self, int i)
2850{
2851 static PyObject *getitem_str;
2852 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
2853 descrgetfunc f;
2854
2855 if (getitem_str == NULL) {
2856 getitem_str = PyString_InternFromString("__getitem__");
2857 if (getitem_str == NULL)
2858 return NULL;
2859 }
2860 func = _PyType_Lookup(self->ob_type, getitem_str);
2861 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00002862 if ((f = func->ob_type->tp_descr_get) == NULL)
2863 Py_INCREF(func);
2864 else
2865 func = f(func, self, (PyObject *)(self->ob_type));
2866 ival = PyInt_FromLong(i);
2867 if (ival != NULL) {
2868 args = PyTuple_New(1);
2869 if (args != NULL) {
2870 PyTuple_SET_ITEM(args, 0, ival);
2871 retval = PyObject_Call(func, args, NULL);
2872 Py_XDECREF(args);
2873 Py_XDECREF(func);
2874 return retval;
2875 }
2876 }
2877 }
2878 else {
2879 PyErr_SetObject(PyExc_AttributeError, getitem_str);
2880 }
2881 Py_XDECREF(args);
2882 Py_XDECREF(ival);
2883 Py_XDECREF(func);
2884 return NULL;
2885}
2886
Guido van Rossumdc91b992001-08-08 22:26:22 +00002887SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888
2889static int
2890slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2891{
2892 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002893 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002894
2895 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002896 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002897 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002898 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002899 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002900 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002901 if (res == NULL)
2902 return -1;
2903 Py_DECREF(res);
2904 return 0;
2905}
2906
2907static int
2908slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2909{
2910 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002911 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002912
2913 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002914 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002915 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002916 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002917 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002918 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002919 if (res == NULL)
2920 return -1;
2921 Py_DECREF(res);
2922 return 0;
2923}
2924
2925static int
2926slot_sq_contains(PyObject *self, PyObject *value)
2927{
Guido van Rossumb8f63662001-08-15 23:57:02 +00002928 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00002929 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002930
Guido van Rossum55f20992001-10-01 17:18:22 +00002931 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002932
2933 if (func != NULL) {
2934 args = Py_BuildValue("(O)", value);
2935 if (args == NULL)
2936 res = NULL;
2937 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00002938 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002939 Py_DECREF(args);
2940 }
2941 Py_DECREF(func);
2942 if (res == NULL)
2943 return -1;
2944 return PyObject_IsTrue(res);
2945 }
Guido van Rossum55f20992001-10-01 17:18:22 +00002946 else if (PyErr_Occurred())
2947 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002948 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00002949 return _PySequence_IterSearch(self, value,
2950 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002951 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002952}
2953
Guido van Rossumdc91b992001-08-08 22:26:22 +00002954SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2955SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956
2957#define slot_mp_length slot_sq_length
2958
Guido van Rossumdc91b992001-08-08 22:26:22 +00002959SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00002960
2961static int
2962slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2963{
2964 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00002965 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002966
2967 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00002968 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002969 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970 else
Guido van Rossum2730b132001-08-28 18:22:14 +00002971 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00002972 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002973 if (res == NULL)
2974 return -1;
2975 Py_DECREF(res);
2976 return 0;
2977}
2978
Guido van Rossumdc91b992001-08-08 22:26:22 +00002979SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2980SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2981SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2982SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2983SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2984SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2985
2986staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2987
2988SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2989 nb_power, "__pow__", "__rpow__")
2990
2991static PyObject *
2992slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2993{
Guido van Rossum2730b132001-08-28 18:22:14 +00002994 static PyObject *pow_str;
2995
Guido van Rossumdc91b992001-08-08 22:26:22 +00002996 if (modulus == Py_None)
2997 return slot_nb_power_binary(self, other);
2998 /* Three-arg power doesn't use __rpow__ */
Guido van Rossum2730b132001-08-28 18:22:14 +00002999 return call_method(self, "__pow__", &pow_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003000 "(OO)", other, modulus);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003001}
3002
3003SLOT0(slot_nb_negative, "__neg__")
3004SLOT0(slot_nb_positive, "__pos__")
3005SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003006
3007static int
3008slot_nb_nonzero(PyObject *self)
3009{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003010 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003011 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012
Guido van Rossum55f20992001-10-01 17:18:22 +00003013 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003014 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003015 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003016 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003017 func = lookup_maybe(self, "__len__", &len_str);
3018 if (func == NULL) {
3019 if (PyErr_Occurred())
3020 return -1;
3021 else
3022 return 1;
3023 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003024 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003025 res = PyObject_CallObject(func, NULL);
3026 Py_DECREF(func);
3027 if (res == NULL)
3028 return -1;
3029 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030}
3031
Guido van Rossumdc91b992001-08-08 22:26:22 +00003032SLOT0(slot_nb_invert, "__invert__")
3033SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3034SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3035SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3036SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3037SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003038
3039static int
3040slot_nb_coerce(PyObject **a, PyObject **b)
3041{
3042 static PyObject *coerce_str;
3043 PyObject *self = *a, *other = *b;
3044
3045 if (self->ob_type->tp_as_number != NULL &&
3046 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3047 PyObject *r;
3048 r = call_maybe(
3049 self, "__coerce__", &coerce_str, "(O)", other);
3050 if (r == NULL)
3051 return -1;
3052 if (r == Py_NotImplemented) {
3053 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003054 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003055 else {
3056 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3057 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003058 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003059 Py_DECREF(r);
3060 return -1;
3061 }
3062 *a = PyTuple_GET_ITEM(r, 0);
3063 Py_INCREF(*a);
3064 *b = PyTuple_GET_ITEM(r, 1);
3065 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003066 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003067 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003068 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003069 }
3070 if (other->ob_type->tp_as_number != NULL &&
3071 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3072 PyObject *r;
3073 r = call_maybe(
3074 other, "__coerce__", &coerce_str, "(O)", self);
3075 if (r == NULL)
3076 return -1;
3077 if (r == Py_NotImplemented) {
3078 Py_DECREF(r);
3079 return 1;
3080 }
3081 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3082 PyErr_SetString(PyExc_TypeError,
3083 "__coerce__ didn't return a 2-tuple");
3084 Py_DECREF(r);
3085 return -1;
3086 }
3087 *a = PyTuple_GET_ITEM(r, 1);
3088 Py_INCREF(*a);
3089 *b = PyTuple_GET_ITEM(r, 0);
3090 Py_INCREF(*b);
3091 Py_DECREF(r);
3092 return 0;
3093 }
3094 return 1;
3095}
3096
Guido van Rossumdc91b992001-08-08 22:26:22 +00003097SLOT0(slot_nb_int, "__int__")
3098SLOT0(slot_nb_long, "__long__")
3099SLOT0(slot_nb_float, "__float__")
3100SLOT0(slot_nb_oct, "__oct__")
3101SLOT0(slot_nb_hex, "__hex__")
3102SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3103SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3104SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3105SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3106SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
3107SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
3108SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3109SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3110SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3111SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3112SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3113SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3114 "__floordiv__", "__rfloordiv__")
3115SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3116SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3117SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118
3119static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003120half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003121{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003122 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003123 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003124 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003125
Guido van Rossum60718732001-08-28 17:47:51 +00003126 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003127 if (func == NULL) {
3128 PyErr_Clear();
3129 }
3130 else {
3131 args = Py_BuildValue("(O)", other);
3132 if (args == NULL)
3133 res = NULL;
3134 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003135 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003136 Py_DECREF(args);
3137 }
3138 if (res != Py_NotImplemented) {
3139 if (res == NULL)
3140 return -2;
3141 c = PyInt_AsLong(res);
3142 Py_DECREF(res);
3143 if (c == -1 && PyErr_Occurred())
3144 return -2;
3145 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3146 }
3147 Py_DECREF(res);
3148 }
3149 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003150}
3151
Guido van Rossumab3b0342001-09-18 20:38:53 +00003152/* This slot is published for the benefit of try_3way_compare in object.c */
3153int
3154_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003155{
3156 int c;
3157
Guido van Rossumab3b0342001-09-18 20:38:53 +00003158 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003159 c = half_compare(self, other);
3160 if (c <= 1)
3161 return c;
3162 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003163 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003164 c = half_compare(other, self);
3165 if (c < -1)
3166 return -2;
3167 if (c <= 1)
3168 return -c;
3169 }
3170 return (void *)self < (void *)other ? -1 :
3171 (void *)self > (void *)other ? 1 : 0;
3172}
3173
3174static PyObject *
3175slot_tp_repr(PyObject *self)
3176{
3177 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003178 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003179
Guido van Rossum60718732001-08-28 17:47:51 +00003180 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003181 if (func != NULL) {
3182 res = PyEval_CallObject(func, NULL);
3183 Py_DECREF(func);
3184 return res;
3185 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003186 PyErr_Clear();
3187 return PyString_FromFormat("<%s object at %p>",
3188 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003189}
3190
3191static PyObject *
3192slot_tp_str(PyObject *self)
3193{
3194 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003195 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003196
Guido van Rossum60718732001-08-28 17:47:51 +00003197 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003198 if (func != NULL) {
3199 res = PyEval_CallObject(func, NULL);
3200 Py_DECREF(func);
3201 return res;
3202 }
3203 else {
3204 PyErr_Clear();
3205 return slot_tp_repr(self);
3206 }
3207}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003208
3209static long
3210slot_tp_hash(PyObject *self)
3211{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003212 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003213 static PyObject *hash_str, *eq_str, *cmp_str;
3214
Tim Peters6d6c1a32001-08-02 04:15:00 +00003215 long h;
3216
Guido van Rossum60718732001-08-28 17:47:51 +00003217 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003218
3219 if (func != NULL) {
3220 res = PyEval_CallObject(func, NULL);
3221 Py_DECREF(func);
3222 if (res == NULL)
3223 return -1;
3224 h = PyInt_AsLong(res);
3225 }
3226 else {
3227 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003228 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003229 if (func == NULL) {
3230 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003231 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003232 }
3233 if (func != NULL) {
3234 Py_DECREF(func);
3235 PyErr_SetString(PyExc_TypeError, "unhashable type");
3236 return -1;
3237 }
3238 PyErr_Clear();
3239 h = _Py_HashPointer((void *)self);
3240 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003241 if (h == -1 && !PyErr_Occurred())
3242 h = -2;
3243 return h;
3244}
3245
3246static PyObject *
3247slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3248{
Guido van Rossum60718732001-08-28 17:47:51 +00003249 static PyObject *call_str;
3250 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003251 PyObject *res;
3252
3253 if (meth == NULL)
3254 return NULL;
3255 res = PyObject_Call(meth, args, kwds);
3256 Py_DECREF(meth);
3257 return res;
3258}
3259
Guido van Rossum14a6f832001-10-17 13:59:09 +00003260/* There are two slot dispatch functions for tp_getattro.
3261
3262 - slot_tp_getattro() is used when __getattribute__ is overridden
3263 but no __getattr__ hook is present;
3264
3265 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3266
Guido van Rossumc334df52002-04-04 23:44:47 +00003267 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3268 detects the absence of __getattr__ and then installs the simpler slot if
3269 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003270
Tim Peters6d6c1a32001-08-02 04:15:00 +00003271static PyObject *
3272slot_tp_getattro(PyObject *self, PyObject *name)
3273{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003274 static PyObject *getattribute_str = NULL;
3275 return call_method(self, "__getattribute__", &getattribute_str,
3276 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003277}
3278
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003279static PyObject *
3280slot_tp_getattr_hook(PyObject *self, PyObject *name)
3281{
3282 PyTypeObject *tp = self->ob_type;
3283 PyObject *getattr, *getattribute, *res;
3284 static PyObject *getattribute_str = NULL;
3285 static PyObject *getattr_str = NULL;
3286
3287 if (getattr_str == NULL) {
3288 getattr_str = PyString_InternFromString("__getattr__");
3289 if (getattr_str == NULL)
3290 return NULL;
3291 }
3292 if (getattribute_str == NULL) {
3293 getattribute_str =
3294 PyString_InternFromString("__getattribute__");
3295 if (getattribute_str == NULL)
3296 return NULL;
3297 }
3298 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003299 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003300 /* No __getattr__ hook: use a simpler dispatcher */
3301 tp->tp_getattro = slot_tp_getattro;
3302 return slot_tp_getattro(self, name);
3303 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003304 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003305 if (getattribute == NULL ||
3306 (getattribute->ob_type == &PyWrapperDescr_Type &&
3307 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
3308 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003309 res = PyObject_GenericGetAttr(self, name);
3310 else
3311 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003312 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003313 PyErr_Clear();
3314 res = PyObject_CallFunction(getattr, "OO", self, name);
3315 }
3316 return res;
3317}
3318
Tim Peters6d6c1a32001-08-02 04:15:00 +00003319static int
3320slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
3321{
3322 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003323 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324
3325 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003326 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003327 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003328 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003329 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003330 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003331 if (res == NULL)
3332 return -1;
3333 Py_DECREF(res);
3334 return 0;
3335}
3336
3337/* Map rich comparison operators to their __xx__ namesakes */
3338static char *name_op[] = {
3339 "__lt__",
3340 "__le__",
3341 "__eq__",
3342 "__ne__",
3343 "__gt__",
3344 "__ge__",
3345};
3346
3347static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00003348half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003349{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003350 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003351 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352
Guido van Rossum60718732001-08-28 17:47:51 +00003353 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003354 if (func == NULL) {
3355 PyErr_Clear();
3356 Py_INCREF(Py_NotImplemented);
3357 return Py_NotImplemented;
3358 }
3359 args = Py_BuildValue("(O)", other);
3360 if (args == NULL)
3361 res = NULL;
3362 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003363 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003364 Py_DECREF(args);
3365 }
3366 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003367 return res;
3368}
3369
Guido van Rossumb8f63662001-08-15 23:57:02 +00003370/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
3371static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
3372
3373static PyObject *
3374slot_tp_richcompare(PyObject *self, PyObject *other, int op)
3375{
3376 PyObject *res;
3377
3378 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
3379 res = half_richcompare(self, other, op);
3380 if (res != Py_NotImplemented)
3381 return res;
3382 Py_DECREF(res);
3383 }
3384 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
3385 res = half_richcompare(other, self, swapped_op[op]);
3386 if (res != Py_NotImplemented) {
3387 return res;
3388 }
3389 Py_DECREF(res);
3390 }
3391 Py_INCREF(Py_NotImplemented);
3392 return Py_NotImplemented;
3393}
3394
3395static PyObject *
3396slot_tp_iter(PyObject *self)
3397{
3398 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003399 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003400
Guido van Rossum60718732001-08-28 17:47:51 +00003401 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003402 if (func != NULL) {
3403 res = PyObject_CallObject(func, NULL);
3404 Py_DECREF(func);
3405 return res;
3406 }
3407 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003408 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003409 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00003410 PyErr_SetString(PyExc_TypeError,
3411 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00003412 return NULL;
3413 }
3414 Py_DECREF(func);
3415 return PySeqIter_New(self);
3416}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003417
3418static PyObject *
3419slot_tp_iternext(PyObject *self)
3420{
Guido van Rossum2730b132001-08-28 18:22:14 +00003421 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003422 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423}
3424
Guido van Rossum1a493502001-08-17 16:47:50 +00003425static PyObject *
3426slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
3427{
3428 PyTypeObject *tp = self->ob_type;
3429 PyObject *get;
3430 static PyObject *get_str = NULL;
3431
3432 if (get_str == NULL) {
3433 get_str = PyString_InternFromString("__get__");
3434 if (get_str == NULL)
3435 return NULL;
3436 }
3437 get = _PyType_Lookup(tp, get_str);
3438 if (get == NULL) {
3439 /* Avoid further slowdowns */
3440 if (tp->tp_descr_get == slot_tp_descr_get)
3441 tp->tp_descr_get = NULL;
3442 Py_INCREF(self);
3443 return self;
3444 }
Guido van Rossum2c252392001-08-24 10:13:31 +00003445 if (obj == NULL)
3446 obj = Py_None;
3447 if (type == NULL)
3448 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00003449 return PyObject_CallFunction(get, "OOO", self, obj, type);
3450}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003451
3452static int
3453slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
3454{
Guido van Rossum2c252392001-08-24 10:13:31 +00003455 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003456 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00003457
3458 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00003459 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003460 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00003461 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003462 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003463 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003464 if (res == NULL)
3465 return -1;
3466 Py_DECREF(res);
3467 return 0;
3468}
3469
3470static int
3471slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
3472{
Guido van Rossum60718732001-08-28 17:47:51 +00003473 static PyObject *init_str;
3474 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003475 PyObject *res;
3476
3477 if (meth == NULL)
3478 return -1;
3479 res = PyObject_Call(meth, args, kwds);
3480 Py_DECREF(meth);
3481 if (res == NULL)
3482 return -1;
3483 Py_DECREF(res);
3484 return 0;
3485}
3486
3487static PyObject *
3488slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3489{
3490 PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
3491 PyObject *newargs, *x;
3492 int i, n;
3493
3494 if (func == NULL)
3495 return NULL;
3496 assert(PyTuple_Check(args));
3497 n = PyTuple_GET_SIZE(args);
3498 newargs = PyTuple_New(n+1);
3499 if (newargs == NULL)
3500 return NULL;
3501 Py_INCREF(type);
3502 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
3503 for (i = 0; i < n; i++) {
3504 x = PyTuple_GET_ITEM(args, i);
3505 Py_INCREF(x);
3506 PyTuple_SET_ITEM(newargs, i+1, x);
3507 }
3508 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00003509 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003510 Py_DECREF(func);
3511 return x;
3512}
3513
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003514
3515/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
3516 functions. The offsets here are relative to the 'etype' structure, which
3517 incorporates the additional structures used for numbers, sequences and
3518 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
3519 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00003520 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
3521 terminated with an all-zero entry. (This table is further initialized and
3522 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003523
Guido van Rossum6d204072001-10-21 00:44:31 +00003524typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003525
3526#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00003527#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003528#undef ETSLOT
3529#undef SQSLOT
3530#undef MPSLOT
3531#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00003532#undef UNSLOT
3533#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003534#undef BINSLOT
3535#undef RBINSLOT
3536
Guido van Rossum6d204072001-10-21 00:44:31 +00003537#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3538 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
Guido van Rossumc8e56452001-10-22 00:43:43 +00003539#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
3540 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
3541 DOC, FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00003542#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3543 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3544#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3545 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
3546#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3547 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
3548#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3549 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
3550#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3551 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3552 "x." NAME "() <==> " DOC)
3553#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
3554 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
3555 "x." NAME "(y) <==> x" DOC "y")
3556#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
3557 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
3558 "x." NAME "(y) <==> x" DOC "y")
3559#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
3560 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
3561 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003562
3563static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00003564 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
3565 "x.__len__() <==> len(x)"),
3566 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
3567 "x.__add__(y) <==> x+y"),
3568 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3569 "x.__mul__(n) <==> x*n"),
3570 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
3571 "x.__rmul__(n) <==> n*x"),
3572 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
3573 "x.__getitem__(y) <==> x[y]"),
3574 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
3575 "x.__getslice__(i, j) <==> x[i:j]"),
3576 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
3577 "x.__setitem__(i, y) <==> x[i]=y"),
3578 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
3579 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003580 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00003581 wrap_intintobjargproc,
3582 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
3583 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
3584 "x.__delslice__(i, j) <==> del x[i:j]"),
3585 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
3586 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003587 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003588 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003589 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00003590 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003591
Guido van Rossum6d204072001-10-21 00:44:31 +00003592 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
3593 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00003594 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003595 wrap_binaryfunc,
3596 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003597 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003598 wrap_objobjargproc,
3599 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003600 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00003601 wrap_delitem,
3602 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003603
Guido van Rossum6d204072001-10-21 00:44:31 +00003604 BINSLOT("__add__", nb_add, slot_nb_add,
3605 "+"),
3606 RBINSLOT("__radd__", nb_add, slot_nb_add,
3607 "+"),
3608 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
3609 "-"),
3610 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
3611 "-"),
3612 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
3613 "*"),
3614 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
3615 "*"),
3616 BINSLOT("__div__", nb_divide, slot_nb_divide,
3617 "/"),
3618 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
3619 "/"),
3620 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
3621 "%"),
3622 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
3623 "%"),
3624 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
3625 "divmod(x, y)"),
3626 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
3627 "divmod(y, x)"),
3628 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
3629 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
3630 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
3631 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
3632 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
3633 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
3634 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
3635 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00003636 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00003637 "x != 0"),
3638 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
3639 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
3640 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
3641 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
3642 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
3643 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
3644 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
3645 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
3646 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
3647 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
3648 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
3649 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
3650 "x.__coerce__(y) <==> coerce(x, y)"),
3651 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
3652 "int(x)"),
3653 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
3654 "long(x)"),
3655 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
3656 "float(x)"),
3657 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
3658 "oct(x)"),
3659 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
3660 "hex(x)"),
3661 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
3662 wrap_binaryfunc, "+"),
3663 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
3664 wrap_binaryfunc, "-"),
3665 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
3666 wrap_binaryfunc, "*"),
3667 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
3668 wrap_binaryfunc, "/"),
3669 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
3670 wrap_binaryfunc, "%"),
3671 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
3672 wrap_ternaryfunc, "**"),
3673 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
3674 wrap_binaryfunc, "<<"),
3675 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
3676 wrap_binaryfunc, ">>"),
3677 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
3678 wrap_binaryfunc, "&"),
3679 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
3680 wrap_binaryfunc, "^"),
3681 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
3682 wrap_binaryfunc, "|"),
3683 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3684 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
3685 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
3686 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
3687 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
3688 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
3689 IBSLOT("__itruediv__", nb_inplace_true_divide,
3690 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003691
Guido van Rossum6d204072001-10-21 00:44:31 +00003692 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
3693 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003694 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003695 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
3696 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00003697 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00003698 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
3699 "x.__cmp__(y) <==> cmp(x,y)"),
3700 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
3701 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003702 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
3703 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003704 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00003705 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
3706 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
3707 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
3708 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
3709 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
3710 "x.__setattr__('name', value) <==> x.name = value"),
3711 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
3712 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
3713 "x.__delattr__('name') <==> del x.name"),
3714 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
3715 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
3716 "x.__lt__(y) <==> x<y"),
3717 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
3718 "x.__le__(y) <==> x<=y"),
3719 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
3720 "x.__eq__(y) <==> x==y"),
3721 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
3722 "x.__ne__(y) <==> x!=y"),
3723 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
3724 "x.__gt__(y) <==> x>y"),
3725 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
3726 "x.__ge__(y) <==> x>=y"),
3727 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
3728 "x.__iter__() <==> iter(x)"),
3729 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
3730 "x.next() -> the next value, or raise StopIteration"),
3731 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
3732 "descr.__get__(obj[, type]) -> value"),
3733 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
3734 "descr.__set__(obj, value)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00003735 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00003736 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00003737 "see x.__class__.__doc__ for signature",
3738 PyWrapperFlag_KEYWORDS),
3739 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003740 {NULL}
3741};
3742
Guido van Rossumc334df52002-04-04 23:44:47 +00003743/* Given a type pointer and an offset gotten from a slotdef entry, return a
3744 pointer to the actual slot. This is not quite the same as simply adding
3745 the offset to the type pointer, since it takes care to indirect through the
3746 proper indirection pointer (as_buffer, etc.); it returns NULL if the
3747 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003748static void **
3749slotptr(PyTypeObject *type, int offset)
3750{
3751 char *ptr;
3752
3753 assert(offset >= 0);
3754 assert(offset < offsetof(etype, as_buffer));
3755 if (offset >= offsetof(etype, as_mapping)) {
3756 ptr = (void *)type->tp_as_mapping;
3757 offset -= offsetof(etype, as_mapping);
3758 }
3759 else if (offset >= offsetof(etype, as_sequence)) {
3760 ptr = (void *)type->tp_as_sequence;
3761 offset -= offsetof(etype, as_sequence);
3762 }
3763 else if (offset >= offsetof(etype, as_number)) {
3764 ptr = (void *)type->tp_as_number;
3765 offset -= offsetof(etype, as_number);
3766 }
3767 else {
3768 ptr = (void *)type;
3769 }
3770 if (ptr != NULL)
3771 ptr += offset;
3772 return (void **)ptr;
3773}
Guido van Rossumf040ede2001-08-07 16:40:56 +00003774
Guido van Rossumc334df52002-04-04 23:44:47 +00003775/* Length of array of slotdef pointers used to store slots with the
3776 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
3777 the same __name__, for any __name__. Since that's a static property, it is
3778 appropriate to declare fixed-size arrays for this. */
3779#define MAX_EQUIV 10
3780
3781/* Return a slot pointer for a given name, but ONLY if the attribute has
3782 exactly one slot function. The name must be an interned string. */
3783static void **
3784resolve_slotdups(PyTypeObject *type, PyObject *name)
3785{
3786 /* XXX Maybe this could be optimized more -- but is it worth it? */
3787
3788 /* pname and ptrs act as a little cache */
3789 static PyObject *pname;
3790 static slotdef *ptrs[MAX_EQUIV];
3791 slotdef *p, **pp;
3792 void **res, **ptr;
3793
3794 if (pname != name) {
3795 /* Collect all slotdefs that match name into ptrs. */
3796 pname = name;
3797 pp = ptrs;
3798 for (p = slotdefs; p->name_strobj; p++) {
3799 if (p->name_strobj == name)
3800 *pp++ = p;
3801 }
3802 *pp = NULL;
3803 }
3804
3805 /* Look in all matching slots of the type; if exactly one of these has
3806 a filled-in slot, return its value. Otherwise return NULL. */
3807 res = NULL;
3808 for (pp = ptrs; *pp; pp++) {
3809 ptr = slotptr(type, (*pp)->offset);
3810 if (ptr == NULL || *ptr == NULL)
3811 continue;
3812 if (res != NULL)
3813 return NULL;
3814 res = ptr;
3815 }
3816 return res;
3817}
3818
3819/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
3820 does some incredibly complex thinking and then sticks something into the
3821 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
3822 interests, and then stores a generic wrapper or a specific function into
3823 the slot.) Return a pointer to the next slotdef with a different offset,
3824 because that's convenient for fixup_slot_dispatchers(). */
3825static slotdef *
3826update_one_slot(PyTypeObject *type, slotdef *p)
3827{
3828 PyObject *descr;
3829 PyWrapperDescrObject *d;
3830 void *generic = NULL, *specific = NULL;
3831 int use_generic = 0;
3832 int offset = p->offset;
3833 void **ptr = slotptr(type, offset);
3834
3835 if (ptr == NULL) {
3836 do {
3837 ++p;
3838 } while (p->offset == offset);
3839 return p;
3840 }
3841 do {
3842 descr = _PyType_Lookup(type, p->name_strobj);
3843 if (descr == NULL)
3844 continue;
3845 if (descr->ob_type == &PyWrapperDescr_Type) {
3846 void **tptr = resolve_slotdups(type, p->name_strobj);
3847 if (tptr == NULL || tptr == ptr)
3848 generic = p->function;
3849 d = (PyWrapperDescrObject *)descr;
3850 if (d->d_base->wrapper == p->wrapper &&
3851 PyType_IsSubtype(type, d->d_type))
3852 {
3853 if (specific == NULL ||
3854 specific == d->d_wrapped)
3855 specific = d->d_wrapped;
3856 else
3857 use_generic = 1;
3858 }
3859 }
3860 else {
3861 use_generic = 1;
3862 generic = p->function;
3863 }
3864 } while ((++p)->offset == offset);
3865 if (specific && !use_generic)
3866 *ptr = specific;
3867 else
3868 *ptr = generic;
3869 return p;
3870}
3871
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003872staticforward int recurse_down_subclasses(PyTypeObject *type,
3873 slotdef **pp, PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003874
Guido van Rossumc334df52002-04-04 23:44:47 +00003875/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
3876 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003877static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003878update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003879{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003880 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003881
Guido van Rossumc334df52002-04-04 23:44:47 +00003882 for (pp = pp0; *pp; pp++)
3883 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003884 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003885}
3886
Guido van Rossumc334df52002-04-04 23:44:47 +00003887/* Update the slots whose slotdefs are gathered in the pp array in all (direct
3888 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003889static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003890recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003891{
3892 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003893 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003894 int i, n;
3895
3896 subclasses = type->tp_subclasses;
3897 if (subclasses == NULL)
3898 return 0;
3899 assert(PyList_Check(subclasses));
3900 n = PyList_GET_SIZE(subclasses);
3901 for (i = 0; i < n; i++) {
3902 ref = PyList_GET_ITEM(subclasses, i);
3903 assert(PyWeakref_CheckRef(ref));
3904 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
3905 if (subclass == NULL)
3906 continue;
3907 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003908 /* Avoid recursing down into unaffected classes */
3909 dict = subclass->tp_dict;
3910 if (dict != NULL && PyDict_Check(dict) &&
3911 PyDict_GetItem(dict, name) != NULL)
3912 continue;
3913 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003914 return -1;
3915 }
3916 return 0;
3917}
3918
Guido van Rossumc334df52002-04-04 23:44:47 +00003919/* Comparison function for qsort() to compare slotdefs by their offset, and
3920 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003921static int
3922slotdef_cmp(const void *aa, const void *bb)
3923{
3924 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
3925 int c = a->offset - b->offset;
3926 if (c != 0)
3927 return c;
3928 else
3929 return a - b;
3930}
3931
Guido van Rossumc334df52002-04-04 23:44:47 +00003932/* Initialize the slotdefs table by adding interned string objects for the
3933 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003934static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003935init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003936{
3937 slotdef *p;
3938 static int initialized = 0;
3939
3940 if (initialized)
3941 return;
3942 for (p = slotdefs; p->name; p++) {
3943 p->name_strobj = PyString_InternFromString(p->name);
3944 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00003945 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003946 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003947 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
3948 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003949 initialized = 1;
3950}
3951
Guido van Rossumc334df52002-04-04 23:44:47 +00003952/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003953static int
3954update_slot(PyTypeObject *type, PyObject *name)
3955{
Guido van Rossumc334df52002-04-04 23:44:47 +00003956 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003957 slotdef *p;
3958 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003959 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003960
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003961 init_slotdefs();
3962 pp = ptrs;
3963 for (p = slotdefs; p->name; p++) {
3964 /* XXX assume name is interned! */
3965 if (p->name_strobj == name)
3966 *pp++ = p;
3967 }
3968 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003969 for (pp = ptrs; *pp; pp++) {
3970 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003971 offset = p->offset;
3972 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003973 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003974 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003975 }
Guido van Rossumc334df52002-04-04 23:44:47 +00003976 if (ptrs[0] == NULL)
3977 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00003978 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00003979}
3980
Guido van Rossumc334df52002-04-04 23:44:47 +00003981/* Store the proper functions in the slot dispatches at class (type)
3982 definition time, based upon which operations the class overrides in its
3983 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003984static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003985fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003986{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003987 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003988
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003989 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00003990 for (p = slotdefs; p->name; )
3991 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003992}
Guido van Rossum705f0f52001-08-24 16:47:00 +00003993
Guido van Rossum6d204072001-10-21 00:44:31 +00003994/* This function is called by PyType_Ready() to populate the type's
3995 dictionary with method descriptors for function slots. For each
3996 function slot (like tp_repr) that's defined in the type, one or
3997 more corresponding descriptors are added in the type's tp_dict
3998 dictionary under the appropriate name (like __repr__). Some
3999 function slots cause more than one descriptor to be added (for
4000 example, the nb_add slot adds both __add__ and __radd__
4001 descriptors) and some function slots compete for the same
4002 descriptor (for example both sq_item and mp_subscript generate a
4003 __getitem__ descriptor). This only adds new descriptors and
4004 doesn't overwrite entries in tp_dict that were previously
4005 defined. The descriptors contain a reference to the C function
4006 they must call, so that it's safe if they are copied into a
4007 subtype's __dict__ and the subtype has a different C function in
4008 its slot -- calling the method defined by the descriptor will call
4009 the C function that was used to create it, rather than the C
4010 function present in the slot when it is called. (This is important
4011 because a subtype may have a C function in the slot that calls the
4012 method from the dictionary, and we want to avoid infinite recursion
4013 here.) */
4014
4015static int
4016add_operators(PyTypeObject *type)
4017{
4018 PyObject *dict = type->tp_dict;
4019 slotdef *p;
4020 PyObject *descr;
4021 void **ptr;
4022
4023 init_slotdefs();
4024 for (p = slotdefs; p->name; p++) {
4025 if (p->wrapper == NULL)
4026 continue;
4027 ptr = slotptr(type, p->offset);
4028 if (!ptr || !*ptr)
4029 continue;
4030 if (PyDict_GetItem(dict, p->name_strobj))
4031 continue;
4032 descr = PyDescr_NewWrapper(type, p, *ptr);
4033 if (descr == NULL)
4034 return -1;
4035 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4036 return -1;
4037 Py_DECREF(descr);
4038 }
4039 if (type->tp_new != NULL) {
4040 if (add_tp_new_wrapper(type) < 0)
4041 return -1;
4042 }
4043 return 0;
4044}
4045
Guido van Rossum705f0f52001-08-24 16:47:00 +00004046
4047/* Cooperative 'super' */
4048
4049typedef struct {
4050 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004051 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004052 PyObject *obj;
4053} superobject;
4054
Guido van Rossum6f799372001-09-20 20:46:19 +00004055static PyMemberDef super_members[] = {
4056 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4057 "the class invoking super()"},
4058 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4059 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004060 {0}
4061};
4062
Guido van Rossum705f0f52001-08-24 16:47:00 +00004063static void
4064super_dealloc(PyObject *self)
4065{
4066 superobject *su = (superobject *)self;
4067
Guido van Rossum048eb752001-10-02 21:24:57 +00004068 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004069 Py_XDECREF(su->obj);
4070 Py_XDECREF(su->type);
4071 self->ob_type->tp_free(self);
4072}
4073
4074static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004075super_repr(PyObject *self)
4076{
4077 superobject *su = (superobject *)self;
4078
4079 if (su->obj)
4080 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004081 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004082 su->type ? su->type->tp_name : "NULL",
4083 su->obj->ob_type->tp_name);
4084 else
4085 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004086 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004087 su->type ? su->type->tp_name : "NULL");
4088}
4089
4090static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004091super_getattro(PyObject *self, PyObject *name)
4092{
4093 superobject *su = (superobject *)self;
4094
4095 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004096 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004097 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004098 descrgetfunc f;
4099 int i, n;
4100
Guido van Rossum155db9a2002-04-02 17:53:47 +00004101 starttype = su->obj->ob_type;
4102 mro = starttype->tp_mro;
4103
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004104 if (mro == NULL)
4105 n = 0;
4106 else {
4107 assert(PyTuple_Check(mro));
4108 n = PyTuple_GET_SIZE(mro);
4109 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004110 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004111 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004112 break;
4113 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004114 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004115 starttype = (PyTypeObject *)(su->obj);
4116 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004117 if (mro == NULL)
4118 n = 0;
4119 else {
4120 assert(PyTuple_Check(mro));
4121 n = PyTuple_GET_SIZE(mro);
4122 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004123 for (i = 0; i < n; i++) {
4124 if ((PyObject *)(su->type) ==
4125 PyTuple_GET_ITEM(mro, i))
4126 break;
4127 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004128 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004129 i++;
4130 res = NULL;
4131 for (; i < n; i++) {
4132 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004133 if (PyType_Check(tmp))
4134 dict = ((PyTypeObject *)tmp)->tp_dict;
4135 else if (PyClass_Check(tmp))
4136 dict = ((PyClassObject *)tmp)->cl_dict;
4137 else
4138 continue;
4139 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004140 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004141 Py_INCREF(res);
4142 f = res->ob_type->tp_descr_get;
4143 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004144 tmp = f(res, su->obj,
4145 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004146 Py_DECREF(res);
4147 res = tmp;
4148 }
4149 return res;
4150 }
4151 }
4152 }
4153 return PyObject_GenericGetAttr(self, name);
4154}
4155
Guido van Rossum5b443c62001-12-03 15:38:28 +00004156static int
4157supercheck(PyTypeObject *type, PyObject *obj)
4158{
4159 if (!PyType_IsSubtype(obj->ob_type, type) &&
4160 !(PyType_Check(obj) &&
4161 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4162 PyErr_SetString(PyExc_TypeError,
4163 "super(type, obj): "
4164 "obj must be an instance or subtype of type");
4165 return -1;
4166 }
4167 else
4168 return 0;
4169}
4170
Guido van Rossum705f0f52001-08-24 16:47:00 +00004171static PyObject *
4172super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4173{
4174 superobject *su = (superobject *)self;
4175 superobject *new;
4176
4177 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4178 /* Not binding to an object, or already bound */
4179 Py_INCREF(self);
4180 return self;
4181 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004182 if (su->ob_type != &PySuper_Type)
4183 /* If su is an instance of a subclass of super,
4184 call its type */
4185 return PyObject_CallFunction((PyObject *)su->ob_type,
4186 "OO", su->type, obj);
4187 else {
4188 /* Inline the common case */
4189 if (supercheck(su->type, obj) < 0)
4190 return NULL;
4191 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
4192 NULL, NULL);
4193 if (new == NULL)
4194 return NULL;
4195 Py_INCREF(su->type);
4196 Py_INCREF(obj);
4197 new->type = su->type;
4198 new->obj = obj;
4199 return (PyObject *)new;
4200 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004201}
4202
4203static int
4204super_init(PyObject *self, PyObject *args, PyObject *kwds)
4205{
4206 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00004207 PyTypeObject *type;
4208 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004209
4210 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
4211 return -1;
4212 if (obj == Py_None)
4213 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00004214 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00004215 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004216 Py_INCREF(type);
4217 Py_XINCREF(obj);
4218 su->type = type;
4219 su->obj = obj;
4220 return 0;
4221}
4222
4223static char super_doc[] =
4224"super(type) -> unbound super object\n"
4225"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00004226"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00004227"Typical use to call a cooperative superclass method:\n"
4228"class C(B):\n"
4229" def meth(self, arg):\n"
4230" super(C, self).meth(arg)";
4231
Guido van Rossum048eb752001-10-02 21:24:57 +00004232static int
4233super_traverse(PyObject *self, visitproc visit, void *arg)
4234{
4235 superobject *su = (superobject *)self;
4236 int err;
4237
4238#define VISIT(SLOT) \
4239 if (SLOT) { \
4240 err = visit((PyObject *)(SLOT), arg); \
4241 if (err) \
4242 return err; \
4243 }
4244
4245 VISIT(su->obj);
4246 VISIT(su->type);
4247
4248#undef VISIT
4249
4250 return 0;
4251}
4252
Guido van Rossum705f0f52001-08-24 16:47:00 +00004253PyTypeObject PySuper_Type = {
4254 PyObject_HEAD_INIT(&PyType_Type)
4255 0, /* ob_size */
4256 "super", /* tp_name */
4257 sizeof(superobject), /* tp_basicsize */
4258 0, /* tp_itemsize */
4259 /* methods */
4260 super_dealloc, /* tp_dealloc */
4261 0, /* tp_print */
4262 0, /* tp_getattr */
4263 0, /* tp_setattr */
4264 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004265 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004266 0, /* tp_as_number */
4267 0, /* tp_as_sequence */
4268 0, /* tp_as_mapping */
4269 0, /* tp_hash */
4270 0, /* tp_call */
4271 0, /* tp_str */
4272 super_getattro, /* tp_getattro */
4273 0, /* tp_setattro */
4274 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00004275 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4276 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004277 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00004278 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004279 0, /* tp_clear */
4280 0, /* tp_richcompare */
4281 0, /* tp_weaklistoffset */
4282 0, /* tp_iter */
4283 0, /* tp_iternext */
4284 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004285 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004286 0, /* tp_getset */
4287 0, /* tp_base */
4288 0, /* tp_dict */
4289 super_descr_get, /* tp_descr_get */
4290 0, /* tp_descr_set */
4291 0, /* tp_dictoffset */
4292 super_init, /* tp_init */
4293 PyType_GenericAlloc, /* tp_alloc */
4294 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00004295 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00004296};