blob: 995d85f7ebf16ad72a0715eb88cfa9a5f4760e32 [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 Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
8/* The *real* layout of a type object when allocated on the heap */
9/* XXX Should we publish this in a header file? */
10typedef struct {
Guido van Rossum09638c12002-06-13 19:17:46 +000011 /* Note: there's a dependency on the order of these members
12 in slotptr() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000013 PyTypeObject type;
14 PyNumberMethods as_number;
Guido van Rossum9923ffe2002-06-04 19:52:53 +000015 PyMappingMethods as_mapping;
Guido van Rossum09638c12002-06-13 19:17:46 +000016 PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
17 so that the mapping wins when both
18 the mapping and the sequence define
19 a given operator (e.g. __getitem__).
20 see add_operators() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000021 PyBufferProcs as_buffer;
22 PyObject *name, *slots;
23 PyMemberDef members[1];
24} etype;
25
Guido van Rossum6f799372001-09-20 20:46:19 +000026static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000027 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
28 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
29 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000030 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000031 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
32 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
33 {"__dictoffset__", T_LONG,
34 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000035 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
36 {0}
37};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000038
Guido van Rossumc0b618a1997-05-02 03:12:38 +000039static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000040type_name(PyTypeObject *type, void *context)
41{
42 char *s;
43
44 s = strrchr(type->tp_name, '.');
45 if (s == NULL)
46 s = type->tp_name;
47 else
48 s++;
49 return PyString_FromString(s);
50}
51
Michael W. Hudson98bbc492002-11-26 14:47:27 +000052static int
53type_set_name(PyTypeObject *type, PyObject *value, void *context)
54{
55 etype* et;
56
57 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
58 PyErr_Format(PyExc_TypeError,
59 "can't set %s.__name__", type->tp_name);
60 return -1;
61 }
62 if (!value) {
63 PyErr_Format(PyExc_TypeError,
64 "can't delete %s.__name__", type->tp_name);
65 return -1;
66 }
67 if (!PyString_Check(value)) {
68 PyErr_Format(PyExc_TypeError,
69 "can only assign string to %s.__name__, not '%s'",
70 type->tp_name, value->ob_type->tp_name);
71 return -1;
72 }
73 if (strlen(PyString_AS_STRING(value))
74 != (size_t)PyString_GET_SIZE(value)) {
75 PyErr_Format(PyExc_ValueError,
76 "__name__ must not contain null bytes");
77 return -1;
78 }
79
80 et = (etype*)type;
81
82 Py_INCREF(value);
83
84 Py_DECREF(et->name);
85 et->name = value;
86
87 type->tp_name = PyString_AS_STRING(value);
88
89 return 0;
90}
91
Guido van Rossumc3542212001-08-16 09:18:56 +000092static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000093type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000094{
Guido van Rossumc3542212001-08-16 09:18:56 +000095 PyObject *mod;
96 char *s;
97
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(type->tp_name,
101 (int)(s - type->tp_name));
102 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
103 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +0000104 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000105 if (mod != NULL) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000106 Py_INCREF(mod);
107 return mod;
108 }
109 PyErr_SetString(PyExc_AttributeError, "__module__");
110 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000111}
112
Guido van Rossum3926a632001-09-25 16:25:58 +0000113static int
114type_set_module(PyTypeObject *type, PyObject *value, void *context)
115{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000116 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000117 PyErr_Format(PyExc_TypeError,
118 "can't set %s.__module__", type->tp_name);
119 return -1;
120 }
121 if (!value) {
122 PyErr_Format(PyExc_TypeError,
123 "can't delete %s.__module__", type->tp_name);
124 return -1;
125 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000126
Guido van Rossum3926a632001-09-25 16:25:58 +0000127 return PyDict_SetItemString(type->tp_dict, "__module__", value);
128}
129
Tim Peters6d6c1a32001-08-02 04:15:00 +0000130static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000131type_get_bases(PyTypeObject *type, void *context)
132{
133 Py_INCREF(type->tp_bases);
134 return type->tp_bases;
135}
136
137static PyTypeObject *best_base(PyObject *);
138static int mro_internal(PyTypeObject *);
139static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
140static int add_subclass(PyTypeObject*, PyTypeObject*);
141static void remove_subclass(PyTypeObject *, PyTypeObject *);
142static void update_all_slots(PyTypeObject *);
143
144static int
145mro_subclasses(PyTypeObject *type)
146{
147 PyTypeObject *subclass;
148 PyObject *ref, *subclasses, *old_mro;
149 int i, n, r;
150
151 subclasses = type->tp_subclasses;
152 if (subclasses == NULL)
153 return 0;
154 assert(PyList_Check(subclasses));
155 n = PyList_GET_SIZE(subclasses);
156 for (i = 0; i < n; i++) {
157 ref = PyList_GET_ITEM(subclasses, i);
158 assert(PyWeakref_CheckRef(ref));
159 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
160 assert(subclass != NULL);
161 if ((PyObject *)subclass == Py_None)
162 continue;
163 assert(PyType_Check(subclass));
164 old_mro = subclass->tp_mro;
165 if (mro_internal(subclass) < 0) {
166 subclass->tp_mro = old_mro;
167 r = -1;
168 }
169 else {
170 Py_DECREF(old_mro);
171 }
172 if (mro_subclasses(subclass) < 0)
173 r = -1;
174 }
175 return r;
176}
177
178static int
179type_set_bases(PyTypeObject *type, PyObject *value, void *context)
180{
181 int i, r = 0;
182 PyObject* ob;
183 PyTypeObject *new_base, *old_base;
184 PyObject *old_bases, *old_mro;
185
186 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
187 PyErr_Format(PyExc_TypeError,
188 "can't set %s.__bases__", type->tp_name);
189 return -1;
190 }
191 if (!value) {
192 PyErr_Format(PyExc_TypeError,
193 "can't delete %s.__bases__", type->tp_name);
194 return -1;
195 }
196 if (!PyTuple_Check(value)) {
197 PyErr_Format(PyExc_TypeError,
198 "can only assign tuple to %s.__bases__, not %s",
199 type->tp_name, value->ob_type->tp_name);
200 return -1;
201 }
202 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
203 ob = PyTuple_GET_ITEM(value, i);
204 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
205 PyErr_Format(
206 PyExc_TypeError,
207 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
208 type->tp_name, ob->ob_type->tp_name);
209 return -1;
210 }
211 if (PyType_IsSubtype(type, (PyTypeObject*)ob)) {
212 PyErr_SetString(PyExc_TypeError,
213 "a __bases__ item causes an inheritance cycle");
214 return -1;
215 }
216 }
217
218 new_base = best_base(value);
219
220 if (!new_base) {
221 return -1;
222 }
223
224 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
225 return -1;
226
227 Py_INCREF(new_base);
228 Py_INCREF(value);
229
230 old_bases = type->tp_bases;
231 old_base = type->tp_base;
232 old_mro = type->tp_mro;
233
234 type->tp_bases = value;
235 type->tp_base = new_base;
236
237 if (mro_internal(type) < 0) {
238 type->tp_bases = old_bases;
239 type->tp_base = old_base;
240 type->tp_mro = old_mro;
241
242 Py_DECREF(value);
243 Py_DECREF(new_base);
244
245 return -1;
246 }
247
248 if (mro_subclasses(type) < 0)
249 r = -1;
250
251 /* any base that was in __bases__ but now isn't, we
252 need to remove |type| from it's tp_subclasses.
253 conversely, any class now in __bases__ that wasn't
254 needs to have |type| added to it's subclasses. */
255
256 /* for now, sod that: just remove from all old_bases,
257 add to all new_bases */
258
259 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
260 ob = PyTuple_GET_ITEM(old_bases, i);
261 if (PyType_Check(ob)) {
262 remove_subclass(
263 (PyTypeObject*)ob, type);
264 }
265 }
266
267 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
268 ob = PyTuple_GET_ITEM(value, i);
269 if (PyType_Check(ob)) {
270 if (add_subclass((PyTypeObject*)ob, type) < 0)
271 r = -1;
272 }
273 }
274
275 update_all_slots(type);
276
277 Py_DECREF(old_bases);
278 Py_DECREF(old_base);
279 Py_DECREF(old_mro);
280
281 return r;
282}
283
284static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000285type_dict(PyTypeObject *type, void *context)
286{
287 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000288 Py_INCREF(Py_None);
289 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000290 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000291 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000292}
293
Tim Peters24008312002-03-17 18:56:20 +0000294static PyObject *
295type_get_doc(PyTypeObject *type, void *context)
296{
297 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000298 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000299 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000300 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000301 if (result == NULL) {
302 result = Py_None;
303 Py_INCREF(result);
304 }
305 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000306 result = result->ob_type->tp_descr_get(result, NULL,
307 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000308 }
309 else {
310 Py_INCREF(result);
311 }
Tim Peters24008312002-03-17 18:56:20 +0000312 return result;
313}
314
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000315static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000316 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
317 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000318 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000319 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000320 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000321 {0}
322};
323
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000324static int
325type_compare(PyObject *v, PyObject *w)
326{
327 /* This is called with type objects only. So we
328 can just compare the addresses. */
329 Py_uintptr_t vv = (Py_uintptr_t)v;
330 Py_uintptr_t ww = (Py_uintptr_t)w;
331 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
332}
333
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000334static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000335type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000336{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000337 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000338 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000339
340 mod = type_module(type, NULL);
341 if (mod == NULL)
342 PyErr_Clear();
343 else if (!PyString_Check(mod)) {
344 Py_DECREF(mod);
345 mod = NULL;
346 }
347 name = type_name(type, NULL);
348 if (name == NULL)
349 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000350
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000351 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
352 kind = "class";
353 else
354 kind = "type";
355
Barry Warsaw7ce36942001-08-24 18:34:26 +0000356 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000357 rtn = PyString_FromFormat("<%s '%s.%s'>",
358 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000359 PyString_AS_STRING(mod),
360 PyString_AS_STRING(name));
361 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000362 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000363 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000364
Guido van Rossumc3542212001-08-16 09:18:56 +0000365 Py_XDECREF(mod);
366 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000367 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368}
369
Tim Peters6d6c1a32001-08-02 04:15:00 +0000370static PyObject *
371type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
372{
373 PyObject *obj;
374
375 if (type->tp_new == NULL) {
376 PyErr_Format(PyExc_TypeError,
377 "cannot create '%.100s' instances",
378 type->tp_name);
379 return NULL;
380 }
381
Tim Peters3f996e72001-09-13 19:18:27 +0000382 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000383 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000384 /* Ugly exception: when the call was type(something),
385 don't call tp_init on the result. */
386 if (type == &PyType_Type &&
387 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
388 (kwds == NULL ||
389 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
390 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000391 /* If the returned object is not an instance of type,
392 it won't be initialized. */
393 if (!PyType_IsSubtype(obj->ob_type, type))
394 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000395 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000396 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
397 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000398 type->tp_init(obj, args, kwds) < 0) {
399 Py_DECREF(obj);
400 obj = NULL;
401 }
402 }
403 return obj;
404}
405
406PyObject *
407PyType_GenericAlloc(PyTypeObject *type, int nitems)
408{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000409 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000410 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000411
412 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000413 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000414 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000415 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000416
Neil Schemenauerc806c882001-08-29 23:54:54 +0000417 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000418 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000419
Neil Schemenauerc806c882001-08-29 23:54:54 +0000420 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000421
Tim Peters6d6c1a32001-08-02 04:15:00 +0000422 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
423 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000424
Tim Peters6d6c1a32001-08-02 04:15:00 +0000425 if (type->tp_itemsize == 0)
426 PyObject_INIT(obj, type);
427 else
428 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000429
Tim Peters6d6c1a32001-08-02 04:15:00 +0000430 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000431 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000432 return obj;
433}
434
435PyObject *
436PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
437{
438 return type->tp_alloc(type, 0);
439}
440
Guido van Rossum9475a232001-10-05 20:51:39 +0000441/* Helpers for subtyping */
442
443static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000444traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
445{
446 int i, n;
447 PyMemberDef *mp;
448
449 n = type->ob_size;
450 mp = ((etype *)type)->members;
451 for (i = 0; i < n; i++, mp++) {
452 if (mp->type == T_OBJECT_EX) {
453 char *addr = (char *)self + mp->offset;
454 PyObject *obj = *(PyObject **)addr;
455 if (obj != NULL) {
456 int err = visit(obj, arg);
457 if (err)
458 return err;
459 }
460 }
461 }
462 return 0;
463}
464
465static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000466subtype_traverse(PyObject *self, visitproc visit, void *arg)
467{
468 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000469 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000470
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000471 /* Find the nearest base with a different tp_traverse,
472 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000473 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000474 base = type;
475 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
476 if (base->ob_size) {
477 int err = traverse_slots(base, self, visit, arg);
478 if (err)
479 return err;
480 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000481 base = base->tp_base;
482 assert(base);
483 }
484
485 if (type->tp_dictoffset != base->tp_dictoffset) {
486 PyObject **dictptr = _PyObject_GetDictPtr(self);
487 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000488 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000489 if (err)
490 return err;
491 }
492 }
493
Guido van Rossuma3862092002-06-10 15:24:42 +0000494 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
495 /* For a heaptype, the instances count as references
496 to the type. Traverse the type so the collector
497 can find cycles involving this link. */
498 int err = visit((PyObject *)type, arg);
499 if (err)
500 return err;
501 }
502
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000503 if (basetraverse)
504 return basetraverse(self, visit, arg);
505 return 0;
506}
507
508static void
509clear_slots(PyTypeObject *type, PyObject *self)
510{
511 int i, n;
512 PyMemberDef *mp;
513
514 n = type->ob_size;
515 mp = ((etype *)type)->members;
516 for (i = 0; i < n; i++, mp++) {
517 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
518 char *addr = (char *)self + mp->offset;
519 PyObject *obj = *(PyObject **)addr;
520 if (obj != NULL) {
521 Py_DECREF(obj);
522 *(PyObject **)addr = NULL;
523 }
524 }
525 }
526}
527
528static int
529subtype_clear(PyObject *self)
530{
531 PyTypeObject *type, *base;
532 inquiry baseclear;
533
534 /* Find the nearest base with a different tp_clear
535 and clear slots while we're at it */
536 type = self->ob_type;
537 base = type;
538 while ((baseclear = base->tp_clear) == subtype_clear) {
539 if (base->ob_size)
540 clear_slots(base, self);
541 base = base->tp_base;
542 assert(base);
543 }
544
Guido van Rossuma3862092002-06-10 15:24:42 +0000545 /* There's no need to clear the instance dict (if any);
546 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000547
548 if (baseclear)
549 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000550 return 0;
551}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000552
553static void
554subtype_dealloc(PyObject *self)
555{
Guido van Rossum14227b42001-12-06 02:35:58 +0000556 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000557 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000558
Guido van Rossum22b13872002-08-06 21:41:44 +0000559 /* Extract the type; we expect it to be a heap type */
560 type = self->ob_type;
561 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000562
Guido van Rossum22b13872002-08-06 21:41:44 +0000563 /* Test whether the type has GC exactly once */
564
565 if (!PyType_IS_GC(type)) {
566 /* It's really rare to find a dynamic type that doesn't have
567 GC; it can only happen when deriving from 'object' and not
568 adding any slots or instance variables. This allows
569 certain simplifications: there's no need to call
570 clear_slots(), or DECREF the dict, or clear weakrefs. */
571
572 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000573 if (type->tp_del) {
574 type->tp_del(self);
575 if (self->ob_refcnt > 0)
576 return;
577 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000578
579 /* Find the nearest base with a different tp_dealloc */
580 base = type;
581 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
582 assert(base->ob_size == 0);
583 base = base->tp_base;
584 assert(base);
585 }
586
587 /* Call the base tp_dealloc() */
588 assert(basedealloc);
589 basedealloc(self);
590
591 /* Can't reference self beyond this point */
592 Py_DECREF(type);
593
594 /* Done */
595 return;
596 }
597
598 /* We get here only if the type has GC */
599
600 /* UnTrack and re-Track around the trashcan macro, alas */
Guido van Rossum0906e072002-08-07 20:42:09 +0000601 PyObject_GC_UnTrack(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000602 Py_TRASHCAN_SAFE_BEGIN(self);
603 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
604
605 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000606 if (type->tp_del) {
607 type->tp_del(self);
608 if (self->ob_refcnt > 0)
609 goto endlabel;
610 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000611
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000612 /* Find the nearest base with a different tp_dealloc
613 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000614 base = type;
615 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
616 if (base->ob_size)
617 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000618 base = base->tp_base;
619 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000620 }
621
Tim Peters6d6c1a32001-08-02 04:15:00 +0000622 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000623 if (type->tp_dictoffset && !base->tp_dictoffset) {
624 PyObject **dictptr = _PyObject_GetDictPtr(self);
625 if (dictptr != NULL) {
626 PyObject *dict = *dictptr;
627 if (dict != NULL) {
628 Py_DECREF(dict);
629 *dictptr = NULL;
630 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000631 }
632 }
633
Guido van Rossum9676b222001-08-17 20:32:36 +0000634 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000635 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000636 PyObject_ClearWeakRefs(self);
637
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000639 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000640 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000641
642 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000643 assert(basedealloc);
644 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000645
646 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000647 Py_DECREF(type);
648
Guido van Rossum0906e072002-08-07 20:42:09 +0000649 endlabel:
Guido van Rossum22b13872002-08-06 21:41:44 +0000650 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000651}
652
Jeremy Hylton938ace62002-07-17 16:30:39 +0000653static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000654
Tim Peters6d6c1a32001-08-02 04:15:00 +0000655/* type test with subclassing support */
656
657int
658PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
659{
660 PyObject *mro;
661
Guido van Rossum9478d072001-09-07 18:52:13 +0000662 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
663 return b == a || b == &PyBaseObject_Type;
664
Tim Peters6d6c1a32001-08-02 04:15:00 +0000665 mro = a->tp_mro;
666 if (mro != NULL) {
667 /* Deal with multiple inheritance without recursion
668 by walking the MRO tuple */
669 int i, n;
670 assert(PyTuple_Check(mro));
671 n = PyTuple_GET_SIZE(mro);
672 for (i = 0; i < n; i++) {
673 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
674 return 1;
675 }
676 return 0;
677 }
678 else {
679 /* a is not completely initilized yet; follow tp_base */
680 do {
681 if (a == b)
682 return 1;
683 a = a->tp_base;
684 } while (a != NULL);
685 return b == &PyBaseObject_Type;
686 }
687}
688
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000689/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000690 without looking in the instance dictionary
691 (so we can't use PyObject_GetAttr) but still binding
692 it to the instance. The arguments are the object,
693 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000694 static variable used to cache the interned Python string.
695
696 Two variants:
697
698 - lookup_maybe() returns NULL without raising an exception
699 when the _PyType_Lookup() call fails;
700
701 - lookup_method() always raises an exception upon errors.
702*/
Guido van Rossum60718732001-08-28 17:47:51 +0000703
704static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000705lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000706{
707 PyObject *res;
708
709 if (*attrobj == NULL) {
710 *attrobj = PyString_InternFromString(attrstr);
711 if (*attrobj == NULL)
712 return NULL;
713 }
714 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000715 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000716 descrgetfunc f;
717 if ((f = res->ob_type->tp_descr_get) == NULL)
718 Py_INCREF(res);
719 else
720 res = f(res, self, (PyObject *)(self->ob_type));
721 }
722 return res;
723}
724
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000725static PyObject *
726lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
727{
728 PyObject *res = lookup_maybe(self, attrstr, attrobj);
729 if (res == NULL && !PyErr_Occurred())
730 PyErr_SetObject(PyExc_AttributeError, *attrobj);
731 return res;
732}
733
Guido van Rossum2730b132001-08-28 18:22:14 +0000734/* A variation of PyObject_CallMethod that uses lookup_method()
735 instead of PyObject_GetAttrString(). This uses the same convention
736 as lookup_method to cache the interned name string object. */
737
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000738static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000739call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
740{
741 va_list va;
742 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000743 va_start(va, format);
744
Guido van Rossumda21c012001-10-03 00:50:18 +0000745 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000746 if (func == NULL) {
747 va_end(va);
748 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000749 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000750 return NULL;
751 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000752
753 if (format && *format)
754 args = Py_VaBuildValue(format, va);
755 else
756 args = PyTuple_New(0);
757
758 va_end(va);
759
760 if (args == NULL)
761 return NULL;
762
763 assert(PyTuple_Check(args));
764 retval = PyObject_Call(func, args, NULL);
765
766 Py_DECREF(args);
767 Py_DECREF(func);
768
769 return retval;
770}
771
772/* Clone of call_method() that returns NotImplemented when the lookup fails. */
773
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000774static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000775call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
776{
777 va_list va;
778 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000779 va_start(va, format);
780
Guido van Rossumda21c012001-10-03 00:50:18 +0000781 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000782 if (func == NULL) {
783 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000784 if (!PyErr_Occurred()) {
785 Py_INCREF(Py_NotImplemented);
786 return Py_NotImplemented;
787 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000788 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000789 }
790
791 if (format && *format)
792 args = Py_VaBuildValue(format, va);
793 else
794 args = PyTuple_New(0);
795
796 va_end(va);
797
Guido van Rossum717ce002001-09-14 16:58:08 +0000798 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000799 return NULL;
800
Guido van Rossum717ce002001-09-14 16:58:08 +0000801 assert(PyTuple_Check(args));
802 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000803
804 Py_DECREF(args);
805 Py_DECREF(func);
806
807 return retval;
808}
809
Tim Petersa91e9642001-11-14 23:32:33 +0000810static int
811fill_classic_mro(PyObject *mro, PyObject *cls)
812{
813 PyObject *bases, *base;
814 int i, n;
815
816 assert(PyList_Check(mro));
817 assert(PyClass_Check(cls));
818 i = PySequence_Contains(mro, cls);
819 if (i < 0)
820 return -1;
821 if (!i) {
822 if (PyList_Append(mro, cls) < 0)
823 return -1;
824 }
825 bases = ((PyClassObject *)cls)->cl_bases;
826 assert(bases && PyTuple_Check(bases));
827 n = PyTuple_GET_SIZE(bases);
828 for (i = 0; i < n; i++) {
829 base = PyTuple_GET_ITEM(bases, i);
830 if (fill_classic_mro(mro, base) < 0)
831 return -1;
832 }
833 return 0;
834}
835
836static PyObject *
837classic_mro(PyObject *cls)
838{
839 PyObject *mro;
840
841 assert(PyClass_Check(cls));
842 mro = PyList_New(0);
843 if (mro != NULL) {
844 if (fill_classic_mro(mro, cls) == 0)
845 return mro;
846 Py_DECREF(mro);
847 }
848 return NULL;
849}
850
Guido van Rossum1f121312002-11-14 19:49:16 +0000851/*
852 Method resolution order algorithm C3 described in
853 "A Monotonic Superclass Linearization for Dylan",
854 by Kim Barrett, Bob Cassel, Paul Haahr,
855 David A. Moon, Keith Playford, and P. Tucker Withington.
856 (OOPSLA 1996)
857
Guido van Rossum98f33732002-11-25 21:36:54 +0000858 Some notes about the rules implied by C3:
859
860 No duplicate bases.
861 It isn't legal to repeat a class in a list of base classes.
862
863 The next three properties are the 3 constraints in "C3".
864
865 Local precendece order.
866 If A precedes B in C's MRO, then A will precede B in the MRO of all
867 subclasses of C.
868
869 Monotonicity.
870 The MRO of a class must be an extension without reordering of the
871 MRO of each of its superclasses.
872
873 Extended Precedence Graph (EPG).
874 Linearization is consistent if there is a path in the EPG from
875 each class to all its successors in the linearization. See
876 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000877 */
878
879static int
880tail_contains(PyObject *list, int whence, PyObject *o) {
881 int j, size;
882 size = PyList_GET_SIZE(list);
883
884 for (j = whence+1; j < size; j++) {
885 if (PyList_GET_ITEM(list, j) == o)
886 return 1;
887 }
888 return 0;
889}
890
Guido van Rossum98f33732002-11-25 21:36:54 +0000891static PyObject *
892class_name(PyObject *cls)
893{
894 PyObject *name = PyObject_GetAttrString(cls, "__name__");
895 if (name == NULL) {
896 PyErr_Clear();
897 Py_XDECREF(name);
898 name = PyObject_Repr(cls);
899 }
900 if (name == NULL)
901 return NULL;
902 if (!PyString_Check(name)) {
903 Py_DECREF(name);
904 return NULL;
905 }
906 return name;
907}
908
909static int
910check_duplicates(PyObject *list)
911{
912 int i, j, n;
913 /* Let's use a quadratic time algorithm,
914 assuming that the bases lists is short.
915 */
916 n = PyList_GET_SIZE(list);
917 for (i = 0; i < n; i++) {
918 PyObject *o = PyList_GET_ITEM(list, i);
919 for (j = i + 1; j < n; j++) {
920 if (PyList_GET_ITEM(list, j) == o) {
921 o = class_name(o);
922 PyErr_Format(PyExc_TypeError,
923 "duplicate base class %s",
924 o ? PyString_AS_STRING(o) : "?");
925 Py_XDECREF(o);
926 return -1;
927 }
928 }
929 }
930 return 0;
931}
932
933/* Raise a TypeError for an MRO order disagreement.
934
935 It's hard to produce a good error message. In the absence of better
936 insight into error reporting, report the classes that were candidates
937 to be put next into the MRO. There is some conflict between the
938 order in which they should be put in the MRO, but it's hard to
939 diagnose what constraint can't be satisfied.
940*/
941
942static void
943set_mro_error(PyObject *to_merge, int *remain)
944{
945 int i, n, off, to_merge_size;
946 char buf[1000];
947 PyObject *k, *v;
948 PyObject *set = PyDict_New();
949
950 to_merge_size = PyList_GET_SIZE(to_merge);
951 for (i = 0; i < to_merge_size; i++) {
952 PyObject *L = PyList_GET_ITEM(to_merge, i);
953 if (remain[i] < PyList_GET_SIZE(L)) {
954 PyObject *c = PyList_GET_ITEM(L, remain[i]);
955 if (PyDict_SetItem(set, c, Py_None) < 0)
956 return;
957 }
958 }
959 n = PyDict_Size(set);
960
961 off = PyOS_snprintf(buf, sizeof(buf), "MRO conflict among bases");
962 i = 0;
963 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
964 PyObject *name = class_name(k);
965 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
966 name ? PyString_AS_STRING(name) : "?");
967 Py_XDECREF(name);
968 if (--n && off+1 < sizeof(buf)) {
969 buf[off++] = ',';
970 buf[off] = '\0';
971 }
972 }
973 PyErr_SetString(PyExc_TypeError, buf);
974 Py_DECREF(set);
975}
976
Guido van Rossum1f121312002-11-14 19:49:16 +0000977static int
978pmerge(PyObject *acc, PyObject* to_merge) {
979 int i, j, to_merge_size;
980 int *remain;
981 int ok, empty_cnt;
982
983 to_merge_size = PyList_GET_SIZE(to_merge);
984
Guido van Rossum98f33732002-11-25 21:36:54 +0000985 /* remain stores an index into each sublist of to_merge.
986 remain[i] is the index of the next base in to_merge[i]
987 that is not included in acc.
988 */
Guido van Rossum1f121312002-11-14 19:49:16 +0000989 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
990 if (remain == NULL)
991 return -1;
992 for (i = 0; i < to_merge_size; i++)
993 remain[i] = 0;
994
995 again:
996 empty_cnt = 0;
997 for (i = 0; i < to_merge_size; i++) {
998 PyObject *candidate;
999
1000 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1001
1002 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1003 empty_cnt++;
1004 continue;
1005 }
1006
Guido van Rossum98f33732002-11-25 21:36:54 +00001007 /* Choose next candidate for MRO.
1008
1009 The input sequences alone can determine the choice.
1010 If not, choose the class which appears in the MRO
1011 of the earliest direct superclass of the new class.
1012 */
1013
Guido van Rossum1f121312002-11-14 19:49:16 +00001014 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1015 for (j = 0; j < to_merge_size; j++) {
1016 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001017 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001018 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001019 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001020 }
1021 ok = PyList_Append(acc, candidate);
1022 if (ok < 0) {
1023 PyMem_Free(remain);
1024 return -1;
1025 }
1026 for (j = 0; j < to_merge_size; j++) {
1027 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1028 if (PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1029 remain[j]++;
1030 }
1031 }
1032 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001033 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001034 }
1035
Guido van Rossum98f33732002-11-25 21:36:54 +00001036 if (empty_cnt == to_merge_size) {
1037 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001038 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001039 }
1040 set_mro_error(to_merge, remain);
1041 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001042 return -1;
1043}
1044
Tim Peters6d6c1a32001-08-02 04:15:00 +00001045static PyObject *
1046mro_implementation(PyTypeObject *type)
1047{
1048 int i, n, ok;
1049 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001050 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001051
Guido van Rossum63517572002-06-18 16:44:57 +00001052 if(type->tp_dict == NULL) {
1053 if(PyType_Ready(type) < 0)
1054 return NULL;
1055 }
1056
Guido van Rossum98f33732002-11-25 21:36:54 +00001057 /* Find a superclass linearization that honors the constraints
1058 of the explicit lists of bases and the constraints implied by
1059 each base class.
1060
1061 to_merge is a list of lists, where each list is a superclass
1062 linearization implied by a base class. The last element of
1063 to_merge is the declared list of bases.
1064 */
1065
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066 bases = type->tp_bases;
1067 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001068
1069 to_merge = PyList_New(n+1);
1070 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001071 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001072
Tim Peters6d6c1a32001-08-02 04:15:00 +00001073 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001074 PyObject *base = PyTuple_GET_ITEM(bases, i);
1075 PyObject *parentMRO;
1076 if (PyType_Check(base))
1077 parentMRO = PySequence_List(
1078 ((PyTypeObject*)base)->tp_mro);
1079 else
1080 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001081 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001082 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001084 }
1085
1086 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001088
1089 bases_aslist = PySequence_List(bases);
1090 if (bases_aslist == NULL) {
1091 Py_DECREF(to_merge);
1092 return NULL;
1093 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001094 /* This is just a basic sanity check. */
1095 if (check_duplicates(bases_aslist) < 0) {
1096 Py_DECREF(to_merge);
1097 Py_DECREF(bases_aslist);
1098 return NULL;
1099 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001100 PyList_SET_ITEM(to_merge, n, bases_aslist);
1101
1102 result = Py_BuildValue("[O]", (PyObject *)type);
1103 if (result == NULL) {
1104 Py_DECREF(to_merge);
1105 return NULL;
1106 }
1107
1108 ok = pmerge(result, to_merge);
1109 Py_DECREF(to_merge);
1110 if (ok < 0) {
1111 Py_DECREF(result);
1112 return NULL;
1113 }
1114
Tim Peters6d6c1a32001-08-02 04:15:00 +00001115 return result;
1116}
1117
1118static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001119mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001120{
1121 PyTypeObject *type = (PyTypeObject *)self;
1122
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 return mro_implementation(type);
1124}
1125
1126static int
1127mro_internal(PyTypeObject *type)
1128{
1129 PyObject *mro, *result, *tuple;
1130
1131 if (type->ob_type == &PyType_Type) {
1132 result = mro_implementation(type);
1133 }
1134 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001135 static PyObject *mro_str;
1136 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001137 if (mro == NULL)
1138 return -1;
1139 result = PyObject_CallObject(mro, NULL);
1140 Py_DECREF(mro);
1141 }
1142 if (result == NULL)
1143 return -1;
1144 tuple = PySequence_Tuple(result);
1145 Py_DECREF(result);
1146 type->tp_mro = tuple;
1147 return 0;
1148}
1149
1150
1151/* Calculate the best base amongst multiple base classes.
1152 This is the first one that's on the path to the "solid base". */
1153
1154static PyTypeObject *
1155best_base(PyObject *bases)
1156{
1157 int i, n;
1158 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001159 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001160
1161 assert(PyTuple_Check(bases));
1162 n = PyTuple_GET_SIZE(bases);
1163 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001164 base = NULL;
1165 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001166 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001167 base_proto = PyTuple_GET_ITEM(bases, i);
1168 if (PyClass_Check(base_proto))
1169 continue;
1170 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171 PyErr_SetString(
1172 PyExc_TypeError,
1173 "bases must be types");
1174 return NULL;
1175 }
Tim Petersa91e9642001-11-14 23:32:33 +00001176 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001178 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001179 return NULL;
1180 }
1181 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001182 if (winner == NULL) {
1183 winner = candidate;
1184 base = base_i;
1185 }
1186 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001187 ;
1188 else if (PyType_IsSubtype(candidate, winner)) {
1189 winner = candidate;
1190 base = base_i;
1191 }
1192 else {
1193 PyErr_SetString(
1194 PyExc_TypeError,
1195 "multiple bases have "
1196 "instance lay-out conflict");
1197 return NULL;
1198 }
1199 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001200 if (base == NULL)
1201 PyErr_SetString(PyExc_TypeError,
1202 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 return base;
1204}
1205
1206static int
1207extra_ivars(PyTypeObject *type, PyTypeObject *base)
1208{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001209 size_t t_size = type->tp_basicsize;
1210 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211
Guido van Rossum9676b222001-08-17 20:32:36 +00001212 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 if (type->tp_itemsize || base->tp_itemsize) {
1214 /* If itemsize is involved, stricter rules */
1215 return t_size != b_size ||
1216 type->tp_itemsize != base->tp_itemsize;
1217 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001218 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1219 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1220 t_size -= sizeof(PyObject *);
1221 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1222 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1223 t_size -= sizeof(PyObject *);
1224
1225 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001226}
1227
1228static PyTypeObject *
1229solid_base(PyTypeObject *type)
1230{
1231 PyTypeObject *base;
1232
1233 if (type->tp_base)
1234 base = solid_base(type->tp_base);
1235 else
1236 base = &PyBaseObject_Type;
1237 if (extra_ivars(type, base))
1238 return type;
1239 else
1240 return base;
1241}
1242
Jeremy Hylton938ace62002-07-17 16:30:39 +00001243static void object_dealloc(PyObject *);
1244static int object_init(PyObject *, PyObject *, PyObject *);
1245static int update_slot(PyTypeObject *, PyObject *);
1246static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001247
1248static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001249subtype_dict(PyObject *obj, void *context)
1250{
1251 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1252 PyObject *dict;
1253
1254 if (dictptr == NULL) {
1255 PyErr_SetString(PyExc_AttributeError,
1256 "This object has no __dict__");
1257 return NULL;
1258 }
1259 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001260 if (dict == NULL)
1261 *dictptr = dict = PyDict_New();
1262 Py_XINCREF(dict);
1263 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001264}
1265
Guido van Rossum6661be32001-10-26 04:26:12 +00001266static int
1267subtype_setdict(PyObject *obj, PyObject *value, void *context)
1268{
1269 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1270 PyObject *dict;
1271
1272 if (dictptr == NULL) {
1273 PyErr_SetString(PyExc_AttributeError,
1274 "This object has no __dict__");
1275 return -1;
1276 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001277 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001278 PyErr_SetString(PyExc_TypeError,
1279 "__dict__ must be set to a dictionary");
1280 return -1;
1281 }
1282 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001283 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001284 *dictptr = value;
1285 Py_XDECREF(dict);
1286 return 0;
1287}
1288
Guido van Rossumad47da02002-08-12 19:05:44 +00001289static PyObject *
1290subtype_getweakref(PyObject *obj, void *context)
1291{
1292 PyObject **weaklistptr;
1293 PyObject *result;
1294
1295 if (obj->ob_type->tp_weaklistoffset == 0) {
1296 PyErr_SetString(PyExc_AttributeError,
1297 "This object has no __weaklist__");
1298 return NULL;
1299 }
1300 assert(obj->ob_type->tp_weaklistoffset > 0);
1301 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001302 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001303 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001304 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001305 if (*weaklistptr == NULL)
1306 result = Py_None;
1307 else
1308 result = *weaklistptr;
1309 Py_INCREF(result);
1310 return result;
1311}
1312
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001313static PyGetSetDef subtype_getsets[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001314 /* Not all objects have these attributes!
1315 The descriptor's __get__ method may raise AttributeError. */
1316 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001317 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001318 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001319 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001320 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001321};
1322
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001323/* bozo: __getstate__ that raises TypeError */
1324
1325static PyObject *
1326bozo_func(PyObject *self, PyObject *args)
1327{
1328 PyErr_SetString(PyExc_TypeError,
1329 "a class that defines __slots__ without "
1330 "defining __getstate__ cannot be pickled");
1331 return NULL;
1332}
1333
Neal Norwitz93c1e232002-03-31 16:06:11 +00001334static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001335
1336static PyObject *bozo_obj = NULL;
1337
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001338static int
1339valid_identifier(PyObject *s)
1340{
Guido van Rossum03013a02002-07-16 14:30:28 +00001341 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001342 int i, n;
1343
1344 if (!PyString_Check(s)) {
1345 PyErr_SetString(PyExc_TypeError,
1346 "__slots__ must be strings");
1347 return 0;
1348 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001349 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001350 n = PyString_GET_SIZE(s);
1351 /* We must reject an empty name. As a hack, we bump the
1352 length to 1 so that the loop will balk on the trailing \0. */
1353 if (n == 0)
1354 n = 1;
1355 for (i = 0; i < n; i++, p++) {
1356 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1357 PyErr_SetString(PyExc_TypeError,
1358 "__slots__ must be identifiers");
1359 return 0;
1360 }
1361 }
1362 return 1;
1363}
1364
Martin v. Löwisd919a592002-10-14 21:07:28 +00001365#ifdef Py_USING_UNICODE
1366/* Replace Unicode objects in slots. */
1367
1368static PyObject *
1369_unicode_to_string(PyObject *slots, int nslots)
1370{
1371 PyObject *tmp = slots;
1372 PyObject *o, *o1;
1373 int i;
1374 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1375 for (i = 0; i < nslots; i++) {
1376 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1377 if (tmp == slots) {
1378 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1379 if (tmp == NULL)
1380 return NULL;
1381 }
1382 o1 = _PyUnicode_AsDefaultEncodedString
1383 (o, NULL);
1384 if (o1 == NULL) {
1385 Py_DECREF(tmp);
1386 return 0;
1387 }
1388 Py_INCREF(o1);
1389 Py_DECREF(o);
1390 PyTuple_SET_ITEM(tmp, i, o1);
1391 }
1392 }
1393 return tmp;
1394}
1395#endif
1396
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001397static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001398type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1399{
1400 PyObject *name, *bases, *dict;
1401 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001402 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001403 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001404 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001405 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001406 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001407 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001408
Tim Peters3abca122001-10-27 19:37:48 +00001409 assert(args != NULL && PyTuple_Check(args));
1410 assert(kwds == NULL || PyDict_Check(kwds));
1411
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001412 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001413 {
1414 const int nargs = PyTuple_GET_SIZE(args);
1415 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1416
1417 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1418 PyObject *x = PyTuple_GET_ITEM(args, 0);
1419 Py_INCREF(x->ob_type);
1420 return (PyObject *) x->ob_type;
1421 }
1422
1423 /* SF bug 475327 -- if that didn't trigger, we need 3
1424 arguments. but PyArg_ParseTupleAndKeywords below may give
1425 a msg saying type() needs exactly 3. */
1426 if (nargs + nkwds != 3) {
1427 PyErr_SetString(PyExc_TypeError,
1428 "type() takes 1 or 3 arguments");
1429 return NULL;
1430 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001431 }
1432
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001433 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001434 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1435 &name,
1436 &PyTuple_Type, &bases,
1437 &PyDict_Type, &dict))
1438 return NULL;
1439
1440 /* Determine the proper metatype to deal with this,
1441 and check for metatype conflicts while we're at it.
1442 Note that if some other metatype wins to contract,
1443 it's possible that its instances are not types. */
1444 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001445 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001446 for (i = 0; i < nbases; i++) {
1447 tmp = PyTuple_GET_ITEM(bases, i);
1448 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001449 if (tmptype == &PyClass_Type)
1450 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001451 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001452 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001453 if (PyType_IsSubtype(tmptype, winner)) {
1454 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001455 continue;
1456 }
1457 PyErr_SetString(PyExc_TypeError,
1458 "metatype conflict among bases");
1459 return NULL;
1460 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001461 if (winner != metatype) {
1462 if (winner->tp_new != type_new) /* Pass it to the winner */
1463 return winner->tp_new(winner, args, kwds);
1464 metatype = winner;
1465 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001466
1467 /* Adjust for empty tuple bases */
1468 if (nbases == 0) {
1469 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1470 if (bases == NULL)
1471 return NULL;
1472 nbases = 1;
1473 }
1474 else
1475 Py_INCREF(bases);
1476
1477 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1478
1479 /* Calculate best base, and check that all bases are type objects */
1480 base = best_base(bases);
1481 if (base == NULL)
1482 return NULL;
1483 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1484 PyErr_Format(PyExc_TypeError,
1485 "type '%.100s' is not an acceptable base type",
1486 base->tp_name);
1487 return NULL;
1488 }
1489
Tim Peters6d6c1a32001-08-02 04:15:00 +00001490 /* Check for a __slots__ sequence variable in dict, and count it */
1491 slots = PyDict_GetItemString(dict, "__slots__");
1492 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001493 add_dict = 0;
1494 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001495 may_add_dict = base->tp_dictoffset == 0;
1496 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1497 if (slots == NULL) {
1498 if (may_add_dict) {
1499 add_dict++;
1500 }
1501 if (may_add_weak) {
1502 add_weak++;
1503 }
1504 }
1505 else {
1506 /* Have slots */
1507
Tim Peters6d6c1a32001-08-02 04:15:00 +00001508 /* Make it into a tuple */
1509 if (PyString_Check(slots))
1510 slots = Py_BuildValue("(O)", slots);
1511 else
1512 slots = PySequence_Tuple(slots);
1513 if (slots == NULL)
1514 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001515 assert(PyTuple_Check(slots));
1516
1517 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001518 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001519 if (nslots > 0 && base->tp_itemsize != 0) {
1520 PyErr_Format(PyExc_TypeError,
1521 "nonempty __slots__ "
1522 "not supported for subtype of '%s'",
1523 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001524 bad_slots:
1525 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001526 return NULL;
1527 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001528
Martin v. Löwisd919a592002-10-14 21:07:28 +00001529#ifdef Py_USING_UNICODE
1530 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001531 if (tmp != slots) {
1532 Py_DECREF(slots);
1533 slots = tmp;
1534 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001535 if (!tmp)
1536 return NULL;
1537#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001538 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001539 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001540 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1541 char *s;
1542 if (!valid_identifier(tmp))
1543 goto bad_slots;
1544 assert(PyString_Check(tmp));
1545 s = PyString_AS_STRING(tmp);
1546 if (strcmp(s, "__dict__") == 0) {
1547 if (!may_add_dict || add_dict) {
1548 PyErr_SetString(PyExc_TypeError,
1549 "__dict__ slot disallowed: "
1550 "we already got one");
1551 goto bad_slots;
1552 }
1553 add_dict++;
1554 }
1555 if (strcmp(s, "__weakref__") == 0) {
1556 if (!may_add_weak || add_weak) {
1557 PyErr_SetString(PyExc_TypeError,
1558 "__weakref__ slot disallowed: "
1559 "either we already got one, "
1560 "or __itemsize__ != 0");
1561 goto bad_slots;
1562 }
1563 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001564 }
1565 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001566
Guido van Rossumad47da02002-08-12 19:05:44 +00001567 /* Copy slots into yet another tuple, demangling names */
1568 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001569 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001570 goto bad_slots;
1571 for (i = j = 0; i < nslots; i++) {
1572 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001573 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001574 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001575 s = PyString_AS_STRING(tmp);
1576 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1577 (add_weak && strcmp(s, "__weakref__") == 0))
1578 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001579 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001580 PyString_AS_STRING(tmp),
1581 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001582 {
1583 tmp = PyString_FromString(buffer);
1584 } else {
1585 Py_INCREF(tmp);
1586 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001587 PyTuple_SET_ITEM(newslots, j, tmp);
1588 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001589 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001590 assert(j == nslots - add_dict - add_weak);
1591 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001592 Py_DECREF(slots);
1593 slots = newslots;
1594
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001595 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001596 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001597 /* If not, provide a bozo that raises TypeError */
1598 if (bozo_obj == NULL) {
1599 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001600 if (bozo_obj == NULL)
1601 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001602 }
1603 if (PyDict_SetItemString(dict,
1604 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001605 bozo_obj) < 0)
1606 {
1607 Py_DECREF(bozo_obj);
1608 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001609 }
1610 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001611
1612 /* Secondary bases may provide weakrefs or dict */
1613 if (nbases > 1 &&
1614 ((may_add_dict && !add_dict) ||
1615 (may_add_weak && !add_weak))) {
1616 for (i = 0; i < nbases; i++) {
1617 tmp = PyTuple_GET_ITEM(bases, i);
1618 if (tmp == (PyObject *)base)
1619 continue; /* Skip primary base */
1620 if (PyClass_Check(tmp)) {
1621 /* Classic base class provides both */
1622 if (may_add_dict && !add_dict)
1623 add_dict++;
1624 if (may_add_weak && !add_weak)
1625 add_weak++;
1626 break;
1627 }
1628 assert(PyType_Check(tmp));
1629 tmptype = (PyTypeObject *)tmp;
1630 if (may_add_dict && !add_dict &&
1631 tmptype->tp_dictoffset != 0)
1632 add_dict++;
1633 if (may_add_weak && !add_weak &&
1634 tmptype->tp_weaklistoffset != 0)
1635 add_weak++;
1636 if (may_add_dict && !add_dict)
1637 continue;
1638 if (may_add_weak && !add_weak)
1639 continue;
1640 /* Nothing more to check */
1641 break;
1642 }
1643 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001644 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645
1646 /* XXX From here until type is safely allocated,
1647 "return NULL" may leak slots! */
1648
1649 /* Allocate the type object */
1650 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001651 if (type == NULL) {
1652 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001653 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001654 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655
1656 /* Keep name and slots alive in the extended type object */
1657 et = (etype *)type;
1658 Py_INCREF(name);
1659 et->name = name;
1660 et->slots = slots;
1661
Guido van Rossumdc91b992001-08-08 22:26:22 +00001662 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001663 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1664 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001665 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1666 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001667
1668 /* It's a new-style number unless it specifically inherits any
1669 old-style numeric behavior */
1670 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1671 (base->tp_as_number == NULL))
1672 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1673
1674 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001675 type->tp_as_number = &et->as_number;
1676 type->tp_as_sequence = &et->as_sequence;
1677 type->tp_as_mapping = &et->as_mapping;
1678 type->tp_as_buffer = &et->as_buffer;
1679 type->tp_name = PyString_AS_STRING(name);
1680
1681 /* Set tp_base and tp_bases */
1682 type->tp_bases = bases;
1683 Py_INCREF(base);
1684 type->tp_base = base;
1685
Guido van Rossum687ae002001-10-15 22:03:32 +00001686 /* Initialize tp_dict from passed-in dict */
1687 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688 if (dict == NULL) {
1689 Py_DECREF(type);
1690 return NULL;
1691 }
1692
Guido van Rossumc3542212001-08-16 09:18:56 +00001693 /* Set __module__ in the dict */
1694 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1695 tmp = PyEval_GetGlobals();
1696 if (tmp != NULL) {
1697 tmp = PyDict_GetItemString(tmp, "__name__");
1698 if (tmp != NULL) {
1699 if (PyDict_SetItemString(dict, "__module__",
1700 tmp) < 0)
1701 return NULL;
1702 }
1703 }
1704 }
1705
Tim Peters2f93e282001-10-04 05:27:00 +00001706 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001707 and is a string. The __doc__ accessor will first look for tp_doc;
1708 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001709 */
1710 {
1711 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1712 if (doc != NULL && PyString_Check(doc)) {
1713 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001714 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001715 if (type->tp_doc == NULL) {
1716 Py_DECREF(type);
1717 return NULL;
1718 }
1719 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1720 }
1721 }
1722
Tim Peters6d6c1a32001-08-02 04:15:00 +00001723 /* Special-case __new__: if it's a plain function,
1724 make it a static function */
1725 tmp = PyDict_GetItemString(dict, "__new__");
1726 if (tmp != NULL && PyFunction_Check(tmp)) {
1727 tmp = PyStaticMethod_New(tmp);
1728 if (tmp == NULL) {
1729 Py_DECREF(type);
1730 return NULL;
1731 }
1732 PyDict_SetItemString(dict, "__new__", tmp);
1733 Py_DECREF(tmp);
1734 }
1735
1736 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1737 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001738 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001739 if (slots != NULL) {
1740 for (i = 0; i < nslots; i++, mp++) {
1741 mp->name = PyString_AS_STRING(
1742 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001743 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001744 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001745 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001746 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001747 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001748 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001749 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001750 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001751 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001752 slotoffset += sizeof(PyObject *);
1753 }
1754 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001755 if (add_dict) {
1756 if (base->tp_itemsize)
1757 type->tp_dictoffset = -(long)sizeof(PyObject *);
1758 else
1759 type->tp_dictoffset = slotoffset;
1760 slotoffset += sizeof(PyObject *);
1761 }
1762 if (add_weak) {
1763 assert(!base->tp_itemsize);
1764 type->tp_weaklistoffset = slotoffset;
1765 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766 }
1767 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001768 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001769 type->tp_members = et->members;
Guido van Rossumad47da02002-08-12 19:05:44 +00001770 type->tp_getset = subtype_getsets;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771
1772 /* Special case some slots */
1773 if (type->tp_dictoffset != 0 || nslots > 0) {
1774 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1775 type->tp_getattro = PyObject_GenericGetAttr;
1776 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1777 type->tp_setattro = PyObject_GenericSetAttr;
1778 }
1779 type->tp_dealloc = subtype_dealloc;
1780
Guido van Rossum9475a232001-10-05 20:51:39 +00001781 /* Enable GC unless there are really no instance variables possible */
1782 if (!(type->tp_basicsize == sizeof(PyObject) &&
1783 type->tp_itemsize == 0))
1784 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1785
Tim Peters6d6c1a32001-08-02 04:15:00 +00001786 /* Always override allocation strategy to use regular heap */
1787 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001788 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001789 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001790 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001791 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001792 }
1793 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001794 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795
1796 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001797 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798 Py_DECREF(type);
1799 return NULL;
1800 }
1801
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001802 /* Put the proper slots in place */
1803 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001804
Tim Peters6d6c1a32001-08-02 04:15:00 +00001805 return (PyObject *)type;
1806}
1807
1808/* Internal API to look for a name through the MRO.
1809 This returns a borrowed reference, and doesn't set an exception! */
1810PyObject *
1811_PyType_Lookup(PyTypeObject *type, PyObject *name)
1812{
1813 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001814 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815
Guido van Rossum687ae002001-10-15 22:03:32 +00001816 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001817 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001818
1819 /* If mro is NULL, the type is either not yet initialized
1820 by PyType_Ready(), or already cleared by type_clear().
1821 Either way the safest thing to do is to return NULL. */
1822 if (mro == NULL)
1823 return NULL;
1824
Tim Peters6d6c1a32001-08-02 04:15:00 +00001825 assert(PyTuple_Check(mro));
1826 n = PyTuple_GET_SIZE(mro);
1827 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001828 base = PyTuple_GET_ITEM(mro, i);
1829 if (PyClass_Check(base))
1830 dict = ((PyClassObject *)base)->cl_dict;
1831 else {
1832 assert(PyType_Check(base));
1833 dict = ((PyTypeObject *)base)->tp_dict;
1834 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001835 assert(dict && PyDict_Check(dict));
1836 res = PyDict_GetItem(dict, name);
1837 if (res != NULL)
1838 return res;
1839 }
1840 return NULL;
1841}
1842
1843/* This is similar to PyObject_GenericGetAttr(),
1844 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1845static PyObject *
1846type_getattro(PyTypeObject *type, PyObject *name)
1847{
1848 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001849 PyObject *meta_attribute, *attribute;
1850 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851
1852 /* Initialize this type (we'll assume the metatype is initialized) */
1853 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001854 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855 return NULL;
1856 }
1857
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001858 /* No readable descriptor found yet */
1859 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001860
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001861 /* Look for the attribute in the metatype */
1862 meta_attribute = _PyType_Lookup(metatype, name);
1863
1864 if (meta_attribute != NULL) {
1865 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001866
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001867 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1868 /* Data descriptors implement tp_descr_set to intercept
1869 * writes. Assume the attribute is not overridden in
1870 * type's tp_dict (and bases): call the descriptor now.
1871 */
1872 return meta_get(meta_attribute, (PyObject *)type,
1873 (PyObject *)metatype);
1874 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001875 }
1876
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001877 /* No data descriptor found on metatype. Look in tp_dict of this
1878 * type and its bases */
1879 attribute = _PyType_Lookup(type, name);
1880 if (attribute != NULL) {
1881 /* Implement descriptor functionality, if any */
1882 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1883 if (local_get != NULL) {
1884 /* NULL 2nd argument indicates the descriptor was
1885 * found on the target object itself (or a base) */
1886 return local_get(attribute, (PyObject *)NULL,
1887 (PyObject *)type);
1888 }
Tim Peters34592512002-07-11 06:23:50 +00001889
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001890 Py_INCREF(attribute);
1891 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001892 }
1893
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001894 /* No attribute found in local __dict__ (or bases): use the
1895 * descriptor from the metatype, if any */
1896 if (meta_get != NULL)
1897 return meta_get(meta_attribute, (PyObject *)type,
1898 (PyObject *)metatype);
1899
1900 /* If an ordinary attribute was found on the metatype, return it now */
1901 if (meta_attribute != NULL) {
1902 Py_INCREF(meta_attribute);
1903 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001904 }
1905
1906 /* Give up */
1907 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001908 "type object '%.50s' has no attribute '%.400s'",
1909 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910 return NULL;
1911}
1912
1913static int
1914type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1915{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001916 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1917 PyErr_Format(
1918 PyExc_TypeError,
1919 "can't set attributes of built-in/extension type '%s'",
1920 type->tp_name);
1921 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001922 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001923 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1924 return -1;
1925 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926}
1927
1928static void
1929type_dealloc(PyTypeObject *type)
1930{
1931 etype *et;
1932
1933 /* Assert this is a heap-allocated type object */
1934 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001935 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001936 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001937 et = (etype *)type;
1938 Py_XDECREF(type->tp_base);
1939 Py_XDECREF(type->tp_dict);
1940 Py_XDECREF(type->tp_bases);
1941 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001942 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001943 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001944 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001945 Py_XDECREF(et->name);
1946 Py_XDECREF(et->slots);
1947 type->ob_type->tp_free((PyObject *)type);
1948}
1949
Guido van Rossum1c450732001-10-08 15:18:27 +00001950static PyObject *
1951type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1952{
1953 PyObject *list, *raw, *ref;
1954 int i, n;
1955
1956 list = PyList_New(0);
1957 if (list == NULL)
1958 return NULL;
1959 raw = type->tp_subclasses;
1960 if (raw == NULL)
1961 return list;
1962 assert(PyList_Check(raw));
1963 n = PyList_GET_SIZE(raw);
1964 for (i = 0; i < n; i++) {
1965 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001966 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001967 ref = PyWeakref_GET_OBJECT(ref);
1968 if (ref != Py_None) {
1969 if (PyList_Append(list, ref) < 0) {
1970 Py_DECREF(list);
1971 return NULL;
1972 }
1973 }
1974 }
1975 return list;
1976}
1977
Tim Peters6d6c1a32001-08-02 04:15:00 +00001978static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001979 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00001980 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00001981 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00001982 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001983 {0}
1984};
1985
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001986PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001988"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001989
Guido van Rossum048eb752001-10-02 21:24:57 +00001990static int
1991type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1992{
Guido van Rossum048eb752001-10-02 21:24:57 +00001993 int err;
1994
Guido van Rossuma3862092002-06-10 15:24:42 +00001995 /* Because of type_is_gc(), the collector only calls this
1996 for heaptypes. */
1997 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001998
1999#define VISIT(SLOT) \
2000 if (SLOT) { \
2001 err = visit((PyObject *)(SLOT), arg); \
2002 if (err) \
2003 return err; \
2004 }
2005
2006 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002007 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002008 VISIT(type->tp_mro);
2009 VISIT(type->tp_bases);
2010 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002011
2012 /* There's no need to visit type->tp_subclasses or
2013 ((etype *)type)->slots, because they can't be involved
2014 in cycles; tp_subclasses is a list of weak references,
2015 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002016
2017#undef VISIT
2018
2019 return 0;
2020}
2021
2022static int
2023type_clear(PyTypeObject *type)
2024{
Guido van Rossum048eb752001-10-02 21:24:57 +00002025 PyObject *tmp;
2026
Guido van Rossuma3862092002-06-10 15:24:42 +00002027 /* Because of type_is_gc(), the collector only calls this
2028 for heaptypes. */
2029 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002030
2031#define CLEAR(SLOT) \
2032 if (SLOT) { \
2033 tmp = (PyObject *)(SLOT); \
2034 SLOT = NULL; \
2035 Py_DECREF(tmp); \
2036 }
2037
Guido van Rossuma3862092002-06-10 15:24:42 +00002038 /* The only field we need to clear is tp_mro, which is part of a
2039 hard cycle (its first element is the class itself) that won't
2040 be broken otherwise (it's a tuple and tuples don't have a
2041 tp_clear handler). None of the other fields need to be
2042 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002043
Guido van Rossuma3862092002-06-10 15:24:42 +00002044 tp_dict:
2045 It is a dict, so the collector will call its tp_clear.
2046
2047 tp_cache:
2048 Not used; if it were, it would be a dict.
2049
2050 tp_bases, tp_base:
2051 If these are involved in a cycle, there must be at least
2052 one other, mutable object in the cycle, e.g. a base
2053 class's dict; the cycle will be broken that way.
2054
2055 tp_subclasses:
2056 A list of weak references can't be part of a cycle; and
2057 lists have their own tp_clear.
2058
2059 slots (in etype):
2060 A tuple of strings can't be part of a cycle.
2061 */
2062
2063 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002064
Guido van Rossum048eb752001-10-02 21:24:57 +00002065#undef CLEAR
2066
2067 return 0;
2068}
2069
2070static int
2071type_is_gc(PyTypeObject *type)
2072{
2073 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2074}
2075
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002076PyTypeObject PyType_Type = {
2077 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002078 0, /* ob_size */
2079 "type", /* tp_name */
2080 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002081 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002082 (destructor)type_dealloc, /* tp_dealloc */
2083 0, /* tp_print */
2084 0, /* tp_getattr */
2085 0, /* tp_setattr */
2086 type_compare, /* tp_compare */
2087 (reprfunc)type_repr, /* tp_repr */
2088 0, /* tp_as_number */
2089 0, /* tp_as_sequence */
2090 0, /* tp_as_mapping */
2091 (hashfunc)_Py_HashPointer, /* tp_hash */
2092 (ternaryfunc)type_call, /* tp_call */
2093 0, /* tp_str */
2094 (getattrofunc)type_getattro, /* tp_getattro */
2095 (setattrofunc)type_setattro, /* tp_setattro */
2096 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002097 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2098 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002099 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002100 (traverseproc)type_traverse, /* tp_traverse */
2101 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002103 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002104 0, /* tp_iter */
2105 0, /* tp_iternext */
2106 type_methods, /* tp_methods */
2107 type_members, /* tp_members */
2108 type_getsets, /* tp_getset */
2109 0, /* tp_base */
2110 0, /* tp_dict */
2111 0, /* tp_descr_get */
2112 0, /* tp_descr_set */
2113 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2114 0, /* tp_init */
2115 0, /* tp_alloc */
2116 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002117 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002118 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002119};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002120
2121
2122/* The base type of all types (eventually)... except itself. */
2123
2124static int
2125object_init(PyObject *self, PyObject *args, PyObject *kwds)
2126{
2127 return 0;
2128}
2129
2130static void
2131object_dealloc(PyObject *self)
2132{
2133 self->ob_type->tp_free(self);
2134}
2135
Guido van Rossum8e248182001-08-12 05:17:56 +00002136static PyObject *
2137object_repr(PyObject *self)
2138{
Guido van Rossum76e69632001-08-16 18:52:43 +00002139 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002140 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002141
Guido van Rossum76e69632001-08-16 18:52:43 +00002142 type = self->ob_type;
2143 mod = type_module(type, NULL);
2144 if (mod == NULL)
2145 PyErr_Clear();
2146 else if (!PyString_Check(mod)) {
2147 Py_DECREF(mod);
2148 mod = NULL;
2149 }
2150 name = type_name(type, NULL);
2151 if (name == NULL)
2152 return NULL;
2153 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002154 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002155 PyString_AS_STRING(mod),
2156 PyString_AS_STRING(name),
2157 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002158 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002159 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002160 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002161 Py_XDECREF(mod);
2162 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002163 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002164}
2165
Guido van Rossumb8f63662001-08-15 23:57:02 +00002166static PyObject *
2167object_str(PyObject *self)
2168{
2169 unaryfunc f;
2170
2171 f = self->ob_type->tp_repr;
2172 if (f == NULL)
2173 f = object_repr;
2174 return f(self);
2175}
2176
Guido van Rossum8e248182001-08-12 05:17:56 +00002177static long
2178object_hash(PyObject *self)
2179{
2180 return _Py_HashPointer(self);
2181}
Guido van Rossum8e248182001-08-12 05:17:56 +00002182
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002183static PyObject *
2184object_get_class(PyObject *self, void *closure)
2185{
2186 Py_INCREF(self->ob_type);
2187 return (PyObject *)(self->ob_type);
2188}
2189
2190static int
2191equiv_structs(PyTypeObject *a, PyTypeObject *b)
2192{
2193 return a == b ||
2194 (a != NULL &&
2195 b != NULL &&
2196 a->tp_basicsize == b->tp_basicsize &&
2197 a->tp_itemsize == b->tp_itemsize &&
2198 a->tp_dictoffset == b->tp_dictoffset &&
2199 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2200 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2201 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2202}
2203
2204static int
2205same_slots_added(PyTypeObject *a, PyTypeObject *b)
2206{
2207 PyTypeObject *base = a->tp_base;
2208 int size;
2209
2210 if (base != b->tp_base)
2211 return 0;
2212 if (equiv_structs(a, base) && equiv_structs(b, base))
2213 return 1;
2214 size = base->tp_basicsize;
2215 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2216 size += sizeof(PyObject *);
2217 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2218 size += sizeof(PyObject *);
2219 return size == a->tp_basicsize && size == b->tp_basicsize;
2220}
2221
2222static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002223compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2224{
2225 PyTypeObject *newbase, *oldbase;
2226
2227 if (new->tp_dealloc != old->tp_dealloc ||
2228 new->tp_free != old->tp_free)
2229 {
2230 PyErr_Format(PyExc_TypeError,
2231 "%s assignment: "
2232 "'%s' deallocator differs from '%s'",
2233 attr,
2234 new->tp_name,
2235 old->tp_name);
2236 return 0;
2237 }
2238 newbase = new;
2239 oldbase = old;
2240 while (equiv_structs(newbase, newbase->tp_base))
2241 newbase = newbase->tp_base;
2242 while (equiv_structs(oldbase, oldbase->tp_base))
2243 oldbase = oldbase->tp_base;
2244 if (newbase != oldbase &&
2245 (newbase->tp_base != oldbase->tp_base ||
2246 !same_slots_added(newbase, oldbase))) {
2247 PyErr_Format(PyExc_TypeError,
2248 "%s assignment: "
2249 "'%s' object layout differs from '%s'",
2250 attr,
2251 new->tp_name,
2252 old->tp_name);
2253 return 0;
2254 }
2255
2256 return 1;
2257}
2258
2259static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002260object_set_class(PyObject *self, PyObject *value, void *closure)
2261{
2262 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002263 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002264
Guido van Rossumb6b89422002-04-15 01:03:30 +00002265 if (value == NULL) {
2266 PyErr_SetString(PyExc_TypeError,
2267 "can't delete __class__ attribute");
2268 return -1;
2269 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002270 if (!PyType_Check(value)) {
2271 PyErr_Format(PyExc_TypeError,
2272 "__class__ must be set to new-style class, not '%s' object",
2273 value->ob_type->tp_name);
2274 return -1;
2275 }
2276 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002277 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2278 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2279 {
2280 PyErr_Format(PyExc_TypeError,
2281 "__class__ assignment: only for heap types");
2282 return -1;
2283 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002284 if (compatible_for_assignment(new, old, "__class__")) {
2285 Py_INCREF(new);
2286 self->ob_type = new;
2287 Py_DECREF(old);
2288 return 0;
2289 }
2290 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002291 return -1;
2292 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002293}
2294
2295static PyGetSetDef object_getsets[] = {
2296 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002297 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002298 {0}
2299};
2300
Guido van Rossum3926a632001-09-25 16:25:58 +00002301static PyObject *
2302object_reduce(PyObject *self, PyObject *args)
2303{
2304 /* Call copy_reg._reduce(self) */
2305 static PyObject *copy_reg_str;
2306 PyObject *copy_reg, *res;
2307
2308 if (!copy_reg_str) {
2309 copy_reg_str = PyString_InternFromString("copy_reg");
2310 if (copy_reg_str == NULL)
2311 return NULL;
2312 }
2313 copy_reg = PyImport_Import(copy_reg_str);
2314 if (!copy_reg)
2315 return NULL;
2316 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
2317 Py_DECREF(copy_reg);
2318 return res;
2319}
2320
2321static PyMethodDef object_methods[] = {
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002322 {"__reduce__", object_reduce, METH_NOARGS,
2323 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002324 {0}
2325};
2326
Tim Peters6d6c1a32001-08-02 04:15:00 +00002327PyTypeObject PyBaseObject_Type = {
2328 PyObject_HEAD_INIT(&PyType_Type)
2329 0, /* ob_size */
2330 "object", /* tp_name */
2331 sizeof(PyObject), /* tp_basicsize */
2332 0, /* tp_itemsize */
2333 (destructor)object_dealloc, /* tp_dealloc */
2334 0, /* tp_print */
2335 0, /* tp_getattr */
2336 0, /* tp_setattr */
2337 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002338 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002339 0, /* tp_as_number */
2340 0, /* tp_as_sequence */
2341 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002342 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002343 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002344 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002345 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002346 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002347 0, /* tp_as_buffer */
2348 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002349 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350 0, /* tp_traverse */
2351 0, /* tp_clear */
2352 0, /* tp_richcompare */
2353 0, /* tp_weaklistoffset */
2354 0, /* tp_iter */
2355 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002356 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002357 0, /* tp_members */
2358 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002359 0, /* tp_base */
2360 0, /* tp_dict */
2361 0, /* tp_descr_get */
2362 0, /* tp_descr_set */
2363 0, /* tp_dictoffset */
2364 object_init, /* tp_init */
2365 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00002366 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002367 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002368};
2369
2370
2371/* Initialize the __dict__ in a type object */
2372
Fred Drake7bf97152002-03-28 05:33:33 +00002373static PyObject *
2374create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
2375{
2376 PyObject *cfunc;
2377 PyObject *result;
2378
2379 cfunc = PyCFunction_New(meth, NULL);
2380 if (cfunc == NULL)
2381 return NULL;
2382 result = func(cfunc);
2383 Py_DECREF(cfunc);
2384 return result;
2385}
2386
Tim Peters6d6c1a32001-08-02 04:15:00 +00002387static int
2388add_methods(PyTypeObject *type, PyMethodDef *meth)
2389{
Guido van Rossum687ae002001-10-15 22:03:32 +00002390 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002391
2392 for (; meth->ml_name != NULL; meth++) {
2393 PyObject *descr;
2394 if (PyDict_GetItemString(dict, meth->ml_name))
2395 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002396 if (meth->ml_flags & METH_CLASS) {
2397 if (meth->ml_flags & METH_STATIC) {
2398 PyErr_SetString(PyExc_ValueError,
2399 "method cannot be both class and static");
2400 return -1;
2401 }
2402 descr = create_specialmethod(meth, PyClassMethod_New);
2403 }
2404 else if (meth->ml_flags & METH_STATIC) {
2405 descr = create_specialmethod(meth, PyStaticMethod_New);
2406 }
2407 else {
2408 descr = PyDescr_NewMethod(type, meth);
2409 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002410 if (descr == NULL)
2411 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002412 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002413 return -1;
2414 Py_DECREF(descr);
2415 }
2416 return 0;
2417}
2418
2419static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002420add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002421{
Guido van Rossum687ae002001-10-15 22:03:32 +00002422 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002423
2424 for (; memb->name != NULL; memb++) {
2425 PyObject *descr;
2426 if (PyDict_GetItemString(dict, memb->name))
2427 continue;
2428 descr = PyDescr_NewMember(type, memb);
2429 if (descr == NULL)
2430 return -1;
2431 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2432 return -1;
2433 Py_DECREF(descr);
2434 }
2435 return 0;
2436}
2437
2438static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002439add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002440{
Guido van Rossum687ae002001-10-15 22:03:32 +00002441 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002442
2443 for (; gsp->name != NULL; gsp++) {
2444 PyObject *descr;
2445 if (PyDict_GetItemString(dict, gsp->name))
2446 continue;
2447 descr = PyDescr_NewGetSet(type, gsp);
2448
2449 if (descr == NULL)
2450 return -1;
2451 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2452 return -1;
2453 Py_DECREF(descr);
2454 }
2455 return 0;
2456}
2457
Guido van Rossum13d52f02001-08-10 21:24:08 +00002458static void
2459inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002460{
2461 int oldsize, newsize;
2462
Guido van Rossum13d52f02001-08-10 21:24:08 +00002463 /* Special flag magic */
2464 if (!type->tp_as_buffer && base->tp_as_buffer) {
2465 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2466 type->tp_flags |=
2467 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2468 }
2469 if (!type->tp_as_sequence && base->tp_as_sequence) {
2470 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2471 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2472 }
2473 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2474 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2475 if ((!type->tp_as_number && base->tp_as_number) ||
2476 (!type->tp_as_sequence && base->tp_as_sequence)) {
2477 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2478 if (!type->tp_as_number && !type->tp_as_sequence) {
2479 type->tp_flags |= base->tp_flags &
2480 Py_TPFLAGS_HAVE_INPLACEOPS;
2481 }
2482 }
2483 /* Wow */
2484 }
2485 if (!type->tp_as_number && base->tp_as_number) {
2486 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2487 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2488 }
2489
2490 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002491 oldsize = base->tp_basicsize;
2492 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2493 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2494 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002495 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2496 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002497 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002498 if (type->tp_traverse == NULL)
2499 type->tp_traverse = base->tp_traverse;
2500 if (type->tp_clear == NULL)
2501 type->tp_clear = base->tp_clear;
2502 }
2503 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002504 /* The condition below could use some explanation.
2505 It appears that tp_new is not inherited for static types
2506 whose base class is 'object'; this seems to be a precaution
2507 so that old extension types don't suddenly become
2508 callable (object.__new__ wouldn't insure the invariants
2509 that the extension type's own factory function ensures).
2510 Heap types, of course, are under our control, so they do
2511 inherit tp_new; static extension types that specify some
2512 other built-in type as the default are considered
2513 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002514 if (base != &PyBaseObject_Type ||
2515 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2516 if (type->tp_new == NULL)
2517 type->tp_new = base->tp_new;
2518 }
2519 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002520 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002521
2522 /* Copy other non-function slots */
2523
2524#undef COPYVAL
2525#define COPYVAL(SLOT) \
2526 if (type->SLOT == 0) type->SLOT = base->SLOT
2527
2528 COPYVAL(tp_itemsize);
2529 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2530 COPYVAL(tp_weaklistoffset);
2531 }
2532 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2533 COPYVAL(tp_dictoffset);
2534 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002535}
2536
2537static void
2538inherit_slots(PyTypeObject *type, PyTypeObject *base)
2539{
2540 PyTypeObject *basebase;
2541
2542#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002543#undef COPYSLOT
2544#undef COPYNUM
2545#undef COPYSEQ
2546#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002547#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002548
2549#define SLOTDEFINED(SLOT) \
2550 (base->SLOT != 0 && \
2551 (basebase == NULL || base->SLOT != basebase->SLOT))
2552
Tim Peters6d6c1a32001-08-02 04:15:00 +00002553#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002554 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002555
2556#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2557#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2558#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002559#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002560
Guido van Rossum13d52f02001-08-10 21:24:08 +00002561 /* This won't inherit indirect slots (from tp_as_number etc.)
2562 if type doesn't provide the space. */
2563
2564 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2565 basebase = base->tp_base;
2566 if (basebase->tp_as_number == NULL)
2567 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002568 COPYNUM(nb_add);
2569 COPYNUM(nb_subtract);
2570 COPYNUM(nb_multiply);
2571 COPYNUM(nb_divide);
2572 COPYNUM(nb_remainder);
2573 COPYNUM(nb_divmod);
2574 COPYNUM(nb_power);
2575 COPYNUM(nb_negative);
2576 COPYNUM(nb_positive);
2577 COPYNUM(nb_absolute);
2578 COPYNUM(nb_nonzero);
2579 COPYNUM(nb_invert);
2580 COPYNUM(nb_lshift);
2581 COPYNUM(nb_rshift);
2582 COPYNUM(nb_and);
2583 COPYNUM(nb_xor);
2584 COPYNUM(nb_or);
2585 COPYNUM(nb_coerce);
2586 COPYNUM(nb_int);
2587 COPYNUM(nb_long);
2588 COPYNUM(nb_float);
2589 COPYNUM(nb_oct);
2590 COPYNUM(nb_hex);
2591 COPYNUM(nb_inplace_add);
2592 COPYNUM(nb_inplace_subtract);
2593 COPYNUM(nb_inplace_multiply);
2594 COPYNUM(nb_inplace_divide);
2595 COPYNUM(nb_inplace_remainder);
2596 COPYNUM(nb_inplace_power);
2597 COPYNUM(nb_inplace_lshift);
2598 COPYNUM(nb_inplace_rshift);
2599 COPYNUM(nb_inplace_and);
2600 COPYNUM(nb_inplace_xor);
2601 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002602 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2603 COPYNUM(nb_true_divide);
2604 COPYNUM(nb_floor_divide);
2605 COPYNUM(nb_inplace_true_divide);
2606 COPYNUM(nb_inplace_floor_divide);
2607 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002608 }
2609
Guido van Rossum13d52f02001-08-10 21:24:08 +00002610 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2611 basebase = base->tp_base;
2612 if (basebase->tp_as_sequence == NULL)
2613 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002614 COPYSEQ(sq_length);
2615 COPYSEQ(sq_concat);
2616 COPYSEQ(sq_repeat);
2617 COPYSEQ(sq_item);
2618 COPYSEQ(sq_slice);
2619 COPYSEQ(sq_ass_item);
2620 COPYSEQ(sq_ass_slice);
2621 COPYSEQ(sq_contains);
2622 COPYSEQ(sq_inplace_concat);
2623 COPYSEQ(sq_inplace_repeat);
2624 }
2625
Guido van Rossum13d52f02001-08-10 21:24:08 +00002626 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2627 basebase = base->tp_base;
2628 if (basebase->tp_as_mapping == NULL)
2629 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002630 COPYMAP(mp_length);
2631 COPYMAP(mp_subscript);
2632 COPYMAP(mp_ass_subscript);
2633 }
2634
Tim Petersfc57ccb2001-10-12 02:38:24 +00002635 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2636 basebase = base->tp_base;
2637 if (basebase->tp_as_buffer == NULL)
2638 basebase = NULL;
2639 COPYBUF(bf_getreadbuffer);
2640 COPYBUF(bf_getwritebuffer);
2641 COPYBUF(bf_getsegcount);
2642 COPYBUF(bf_getcharbuffer);
2643 }
2644
Guido van Rossum13d52f02001-08-10 21:24:08 +00002645 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002646
Tim Peters6d6c1a32001-08-02 04:15:00 +00002647 COPYSLOT(tp_dealloc);
2648 COPYSLOT(tp_print);
2649 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2650 type->tp_getattr = base->tp_getattr;
2651 type->tp_getattro = base->tp_getattro;
2652 }
2653 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2654 type->tp_setattr = base->tp_setattr;
2655 type->tp_setattro = base->tp_setattro;
2656 }
2657 /* tp_compare see tp_richcompare */
2658 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002659 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002660 COPYSLOT(tp_call);
2661 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002662 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002663 if (type->tp_compare == NULL &&
2664 type->tp_richcompare == NULL &&
2665 type->tp_hash == NULL)
2666 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667 type->tp_compare = base->tp_compare;
2668 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002669 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002670 }
2671 }
2672 else {
2673 COPYSLOT(tp_compare);
2674 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002675 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2676 COPYSLOT(tp_iter);
2677 COPYSLOT(tp_iternext);
2678 }
2679 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2680 COPYSLOT(tp_descr_get);
2681 COPYSLOT(tp_descr_set);
2682 COPYSLOT(tp_dictoffset);
2683 COPYSLOT(tp_init);
2684 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002685 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002686 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002687 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002688}
2689
Jeremy Hylton938ace62002-07-17 16:30:39 +00002690static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002691
Tim Peters6d6c1a32001-08-02 04:15:00 +00002692int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002693PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002694{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002695 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696 PyTypeObject *base;
2697 int i, n;
2698
Guido van Rossumcab05802002-06-10 15:29:03 +00002699 if (type->tp_flags & Py_TPFLAGS_READY) {
2700 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002701 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002702 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002703 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002704
2705 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002706
2707 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2708 base = type->tp_base;
2709 if (base == NULL && type != &PyBaseObject_Type)
2710 base = type->tp_base = &PyBaseObject_Type;
2711
Guido van Rossum323a9cf2002-08-14 17:26:30 +00002712 /* Initialize the base class */
2713 if (base && base->tp_dict == NULL) {
2714 if (PyType_Ready(base) < 0)
2715 goto error;
2716 }
2717
Guido van Rossum0986d822002-04-08 01:38:42 +00002718 /* Initialize ob_type if NULL. This means extensions that want to be
2719 compilable separately on Windows can call PyType_Ready() instead of
2720 initializing the ob_type field of their type objects. */
2721 if (type->ob_type == NULL)
2722 type->ob_type = base->ob_type;
2723
Tim Peters6d6c1a32001-08-02 04:15:00 +00002724 /* Initialize tp_bases */
2725 bases = type->tp_bases;
2726 if (bases == NULL) {
2727 if (base == NULL)
2728 bases = PyTuple_New(0);
2729 else
2730 bases = Py_BuildValue("(O)", base);
2731 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002732 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002733 type->tp_bases = bases;
2734 }
2735
Guido van Rossum687ae002001-10-15 22:03:32 +00002736 /* Initialize tp_dict */
2737 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002738 if (dict == NULL) {
2739 dict = PyDict_New();
2740 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002741 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002742 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002743 }
2744
Guido van Rossum687ae002001-10-15 22:03:32 +00002745 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002746 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002747 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748 if (type->tp_methods != NULL) {
2749 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002750 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751 }
2752 if (type->tp_members != NULL) {
2753 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002754 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755 }
2756 if (type->tp_getset != NULL) {
2757 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002758 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759 }
2760
Tim Peters6d6c1a32001-08-02 04:15:00 +00002761 /* Calculate method resolution order */
2762 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002763 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002764 }
2765
Guido van Rossum13d52f02001-08-10 21:24:08 +00002766 /* Inherit special flags from dominant base */
2767 if (type->tp_base != NULL)
2768 inherit_special(type, type->tp_base);
2769
Tim Peters6d6c1a32001-08-02 04:15:00 +00002770 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002771 bases = type->tp_mro;
2772 assert(bases != NULL);
2773 assert(PyTuple_Check(bases));
2774 n = PyTuple_GET_SIZE(bases);
2775 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002776 PyObject *b = PyTuple_GET_ITEM(bases, i);
2777 if (PyType_Check(b))
2778 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002779 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002781 /* if the type dictionary doesn't contain a __doc__, set it from
2782 the tp_doc slot.
2783 */
2784 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2785 if (type->tp_doc != NULL) {
2786 PyObject *doc = PyString_FromString(type->tp_doc);
2787 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2788 Py_DECREF(doc);
2789 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002790 PyDict_SetItemString(type->tp_dict,
2791 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002792 }
2793 }
2794
Guido van Rossum13d52f02001-08-10 21:24:08 +00002795 /* Some more special stuff */
2796 base = type->tp_base;
2797 if (base != NULL) {
2798 if (type->tp_as_number == NULL)
2799 type->tp_as_number = base->tp_as_number;
2800 if (type->tp_as_sequence == NULL)
2801 type->tp_as_sequence = base->tp_as_sequence;
2802 if (type->tp_as_mapping == NULL)
2803 type->tp_as_mapping = base->tp_as_mapping;
2804 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002805
Guido van Rossum1c450732001-10-08 15:18:27 +00002806 /* Link into each base class's list of subclasses */
2807 bases = type->tp_bases;
2808 n = PyTuple_GET_SIZE(bases);
2809 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002810 PyObject *b = PyTuple_GET_ITEM(bases, i);
2811 if (PyType_Check(b) &&
2812 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002813 goto error;
2814 }
2815
Guido van Rossum13d52f02001-08-10 21:24:08 +00002816 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002817 assert(type->tp_dict != NULL);
2818 type->tp_flags =
2819 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002820 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002821
2822 error:
2823 type->tp_flags &= ~Py_TPFLAGS_READYING;
2824 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002825}
2826
Guido van Rossum1c450732001-10-08 15:18:27 +00002827static int
2828add_subclass(PyTypeObject *base, PyTypeObject *type)
2829{
2830 int i;
2831 PyObject *list, *ref, *new;
2832
2833 list = base->tp_subclasses;
2834 if (list == NULL) {
2835 base->tp_subclasses = list = PyList_New(0);
2836 if (list == NULL)
2837 return -1;
2838 }
2839 assert(PyList_Check(list));
2840 new = PyWeakref_NewRef((PyObject *)type, NULL);
2841 i = PyList_GET_SIZE(list);
2842 while (--i >= 0) {
2843 ref = PyList_GET_ITEM(list, i);
2844 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00002845 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2846 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00002847 }
2848 i = PyList_Append(list, new);
2849 Py_DECREF(new);
2850 return i;
2851}
2852
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002853static void
2854remove_subclass(PyTypeObject *base, PyTypeObject *type)
2855{
2856 int i;
2857 PyObject *list, *ref;
2858
2859 list = base->tp_subclasses;
2860 if (list == NULL) {
2861 return;
2862 }
2863 assert(PyList_Check(list));
2864 i = PyList_GET_SIZE(list);
2865 while (--i >= 0) {
2866 ref = PyList_GET_ITEM(list, i);
2867 assert(PyWeakref_CheckRef(ref));
2868 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
2869 /* this can't fail, right? */
2870 PySequence_DelItem(list, i);
2871 return;
2872 }
2873 }
2874}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002875
2876/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2877
2878/* There's a wrapper *function* for each distinct function typedef used
2879 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2880 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2881 Most tables have only one entry; the tables for binary operators have two
2882 entries, one regular and one with reversed arguments. */
2883
2884static PyObject *
2885wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2886{
2887 inquiry func = (inquiry)wrapped;
2888 int res;
2889
2890 if (!PyArg_ParseTuple(args, ""))
2891 return NULL;
2892 res = (*func)(self);
2893 if (res == -1 && PyErr_Occurred())
2894 return NULL;
2895 return PyInt_FromLong((long)res);
2896}
2897
Tim Peters6d6c1a32001-08-02 04:15:00 +00002898static PyObject *
2899wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2900{
2901 binaryfunc func = (binaryfunc)wrapped;
2902 PyObject *other;
2903
2904 if (!PyArg_ParseTuple(args, "O", &other))
2905 return NULL;
2906 return (*func)(self, other);
2907}
2908
2909static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002910wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2911{
2912 binaryfunc func = (binaryfunc)wrapped;
2913 PyObject *other;
2914
2915 if (!PyArg_ParseTuple(args, "O", &other))
2916 return NULL;
2917 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002918 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002919 Py_INCREF(Py_NotImplemented);
2920 return Py_NotImplemented;
2921 }
2922 return (*func)(self, other);
2923}
2924
2925static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002926wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2927{
2928 binaryfunc func = (binaryfunc)wrapped;
2929 PyObject *other;
2930
2931 if (!PyArg_ParseTuple(args, "O", &other))
2932 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002933 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002934 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002935 Py_INCREF(Py_NotImplemented);
2936 return Py_NotImplemented;
2937 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002938 return (*func)(other, self);
2939}
2940
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002941static PyObject *
2942wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2943{
2944 coercion func = (coercion)wrapped;
2945 PyObject *other, *res;
2946 int ok;
2947
2948 if (!PyArg_ParseTuple(args, "O", &other))
2949 return NULL;
2950 ok = func(&self, &other);
2951 if (ok < 0)
2952 return NULL;
2953 if (ok > 0) {
2954 Py_INCREF(Py_NotImplemented);
2955 return Py_NotImplemented;
2956 }
2957 res = PyTuple_New(2);
2958 if (res == NULL) {
2959 Py_DECREF(self);
2960 Py_DECREF(other);
2961 return NULL;
2962 }
2963 PyTuple_SET_ITEM(res, 0, self);
2964 PyTuple_SET_ITEM(res, 1, other);
2965 return res;
2966}
2967
Tim Peters6d6c1a32001-08-02 04:15:00 +00002968static PyObject *
2969wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2970{
2971 ternaryfunc func = (ternaryfunc)wrapped;
2972 PyObject *other;
2973 PyObject *third = Py_None;
2974
2975 /* Note: This wrapper only works for __pow__() */
2976
2977 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2978 return NULL;
2979 return (*func)(self, other, third);
2980}
2981
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002982static PyObject *
2983wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2984{
2985 ternaryfunc func = (ternaryfunc)wrapped;
2986 PyObject *other;
2987 PyObject *third = Py_None;
2988
2989 /* Note: This wrapper only works for __pow__() */
2990
2991 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2992 return NULL;
2993 return (*func)(other, self, third);
2994}
2995
Tim Peters6d6c1a32001-08-02 04:15:00 +00002996static PyObject *
2997wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
2998{
2999 unaryfunc func = (unaryfunc)wrapped;
3000
3001 if (!PyArg_ParseTuple(args, ""))
3002 return NULL;
3003 return (*func)(self);
3004}
3005
Tim Peters6d6c1a32001-08-02 04:15:00 +00003006static PyObject *
3007wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3008{
3009 intargfunc func = (intargfunc)wrapped;
3010 int i;
3011
3012 if (!PyArg_ParseTuple(args, "i", &i))
3013 return NULL;
3014 return (*func)(self, i);
3015}
3016
Guido van Rossum5d815f32001-08-17 21:57:47 +00003017static int
3018getindex(PyObject *self, PyObject *arg)
3019{
3020 int i;
3021
3022 i = PyInt_AsLong(arg);
3023 if (i == -1 && PyErr_Occurred())
3024 return -1;
3025 if (i < 0) {
3026 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3027 if (sq && sq->sq_length) {
3028 int n = (*sq->sq_length)(self);
3029 if (n < 0)
3030 return -1;
3031 i += n;
3032 }
3033 }
3034 return i;
3035}
3036
3037static PyObject *
3038wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3039{
3040 intargfunc func = (intargfunc)wrapped;
3041 PyObject *arg;
3042 int i;
3043
Guido van Rossumf4593e02001-10-03 12:09:30 +00003044 if (PyTuple_GET_SIZE(args) == 1) {
3045 arg = PyTuple_GET_ITEM(args, 0);
3046 i = getindex(self, arg);
3047 if (i == -1 && PyErr_Occurred())
3048 return NULL;
3049 return (*func)(self, i);
3050 }
3051 PyArg_ParseTuple(args, "O", &arg);
3052 assert(PyErr_Occurred());
3053 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003054}
3055
Tim Peters6d6c1a32001-08-02 04:15:00 +00003056static PyObject *
3057wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3058{
3059 intintargfunc func = (intintargfunc)wrapped;
3060 int i, j;
3061
3062 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3063 return NULL;
3064 return (*func)(self, i, j);
3065}
3066
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003068wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069{
3070 intobjargproc func = (intobjargproc)wrapped;
3071 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003072 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003073
Guido van Rossum5d815f32001-08-17 21:57:47 +00003074 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3075 return NULL;
3076 i = getindex(self, arg);
3077 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003078 return NULL;
3079 res = (*func)(self, i, value);
3080 if (res == -1 && PyErr_Occurred())
3081 return NULL;
3082 Py_INCREF(Py_None);
3083 return Py_None;
3084}
3085
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003086static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003087wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003088{
3089 intobjargproc func = (intobjargproc)wrapped;
3090 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003091 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003092
Guido van Rossum5d815f32001-08-17 21:57:47 +00003093 if (!PyArg_ParseTuple(args, "O", &arg))
3094 return NULL;
3095 i = getindex(self, arg);
3096 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003097 return NULL;
3098 res = (*func)(self, i, NULL);
3099 if (res == -1 && PyErr_Occurred())
3100 return NULL;
3101 Py_INCREF(Py_None);
3102 return Py_None;
3103}
3104
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105static PyObject *
3106wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3107{
3108 intintobjargproc func = (intintobjargproc)wrapped;
3109 int i, j, res;
3110 PyObject *value;
3111
3112 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3113 return NULL;
3114 res = (*func)(self, i, j, value);
3115 if (res == -1 && PyErr_Occurred())
3116 return NULL;
3117 Py_INCREF(Py_None);
3118 return Py_None;
3119}
3120
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003121static PyObject *
3122wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3123{
3124 intintobjargproc func = (intintobjargproc)wrapped;
3125 int i, j, res;
3126
3127 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3128 return NULL;
3129 res = (*func)(self, i, j, NULL);
3130 if (res == -1 && PyErr_Occurred())
3131 return NULL;
3132 Py_INCREF(Py_None);
3133 return Py_None;
3134}
3135
Tim Peters6d6c1a32001-08-02 04:15:00 +00003136/* XXX objobjproc is a misnomer; should be objargpred */
3137static PyObject *
3138wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3139{
3140 objobjproc func = (objobjproc)wrapped;
3141 int res;
3142 PyObject *value;
3143
3144 if (!PyArg_ParseTuple(args, "O", &value))
3145 return NULL;
3146 res = (*func)(self, value);
3147 if (res == -1 && PyErr_Occurred())
3148 return NULL;
3149 return PyInt_FromLong((long)res);
3150}
3151
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152static PyObject *
3153wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3154{
3155 objobjargproc func = (objobjargproc)wrapped;
3156 int res;
3157 PyObject *key, *value;
3158
3159 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3160 return NULL;
3161 res = (*func)(self, key, value);
3162 if (res == -1 && PyErr_Occurred())
3163 return NULL;
3164 Py_INCREF(Py_None);
3165 return Py_None;
3166}
3167
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003168static PyObject *
3169wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3170{
3171 objobjargproc func = (objobjargproc)wrapped;
3172 int res;
3173 PyObject *key;
3174
3175 if (!PyArg_ParseTuple(args, "O", &key))
3176 return NULL;
3177 res = (*func)(self, key, NULL);
3178 if (res == -1 && PyErr_Occurred())
3179 return NULL;
3180 Py_INCREF(Py_None);
3181 return Py_None;
3182}
3183
Tim Peters6d6c1a32001-08-02 04:15:00 +00003184static PyObject *
3185wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3186{
3187 cmpfunc func = (cmpfunc)wrapped;
3188 int res;
3189 PyObject *other;
3190
3191 if (!PyArg_ParseTuple(args, "O", &other))
3192 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003193 if (other->ob_type->tp_compare != func &&
3194 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003195 PyErr_Format(
3196 PyExc_TypeError,
3197 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3198 self->ob_type->tp_name,
3199 self->ob_type->tp_name,
3200 other->ob_type->tp_name);
3201 return NULL;
3202 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003203 res = (*func)(self, other);
3204 if (PyErr_Occurred())
3205 return NULL;
3206 return PyInt_FromLong((long)res);
3207}
3208
Tim Peters6d6c1a32001-08-02 04:15:00 +00003209static PyObject *
3210wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3211{
3212 setattrofunc func = (setattrofunc)wrapped;
3213 int res;
3214 PyObject *name, *value;
3215
3216 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3217 return NULL;
3218 res = (*func)(self, name, value);
3219 if (res < 0)
3220 return NULL;
3221 Py_INCREF(Py_None);
3222 return Py_None;
3223}
3224
3225static PyObject *
3226wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3227{
3228 setattrofunc func = (setattrofunc)wrapped;
3229 int res;
3230 PyObject *name;
3231
3232 if (!PyArg_ParseTuple(args, "O", &name))
3233 return NULL;
3234 res = (*func)(self, name, NULL);
3235 if (res < 0)
3236 return NULL;
3237 Py_INCREF(Py_None);
3238 return Py_None;
3239}
3240
Tim Peters6d6c1a32001-08-02 04:15:00 +00003241static PyObject *
3242wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3243{
3244 hashfunc func = (hashfunc)wrapped;
3245 long res;
3246
3247 if (!PyArg_ParseTuple(args, ""))
3248 return NULL;
3249 res = (*func)(self);
3250 if (res == -1 && PyErr_Occurred())
3251 return NULL;
3252 return PyInt_FromLong(res);
3253}
3254
Tim Peters6d6c1a32001-08-02 04:15:00 +00003255static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003256wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003257{
3258 ternaryfunc func = (ternaryfunc)wrapped;
3259
Guido van Rossumc8e56452001-10-22 00:43:43 +00003260 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003261}
3262
Tim Peters6d6c1a32001-08-02 04:15:00 +00003263static PyObject *
3264wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3265{
3266 richcmpfunc func = (richcmpfunc)wrapped;
3267 PyObject *other;
3268
3269 if (!PyArg_ParseTuple(args, "O", &other))
3270 return NULL;
3271 return (*func)(self, other, op);
3272}
3273
3274#undef RICHCMP_WRAPPER
3275#define RICHCMP_WRAPPER(NAME, OP) \
3276static PyObject * \
3277richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3278{ \
3279 return wrap_richcmpfunc(self, args, wrapped, OP); \
3280}
3281
Jack Jansen8e938b42001-08-08 15:29:49 +00003282RICHCMP_WRAPPER(lt, Py_LT)
3283RICHCMP_WRAPPER(le, Py_LE)
3284RICHCMP_WRAPPER(eq, Py_EQ)
3285RICHCMP_WRAPPER(ne, Py_NE)
3286RICHCMP_WRAPPER(gt, Py_GT)
3287RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003288
Tim Peters6d6c1a32001-08-02 04:15:00 +00003289static PyObject *
3290wrap_next(PyObject *self, PyObject *args, void *wrapped)
3291{
3292 unaryfunc func = (unaryfunc)wrapped;
3293 PyObject *res;
3294
3295 if (!PyArg_ParseTuple(args, ""))
3296 return NULL;
3297 res = (*func)(self);
3298 if (res == NULL && !PyErr_Occurred())
3299 PyErr_SetNone(PyExc_StopIteration);
3300 return res;
3301}
3302
Tim Peters6d6c1a32001-08-02 04:15:00 +00003303static PyObject *
3304wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3305{
3306 descrgetfunc func = (descrgetfunc)wrapped;
3307 PyObject *obj;
3308 PyObject *type = NULL;
3309
3310 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3311 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003312 return (*func)(self, obj, type);
3313}
3314
Tim Peters6d6c1a32001-08-02 04:15:00 +00003315static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003316wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317{
3318 descrsetfunc func = (descrsetfunc)wrapped;
3319 PyObject *obj, *value;
3320 int ret;
3321
3322 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3323 return NULL;
3324 ret = (*func)(self, obj, value);
3325 if (ret < 0)
3326 return NULL;
3327 Py_INCREF(Py_None);
3328 return Py_None;
3329}
Guido van Rossum22b13872002-08-06 21:41:44 +00003330
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003331static PyObject *
3332wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3333{
3334 descrsetfunc func = (descrsetfunc)wrapped;
3335 PyObject *obj;
3336 int ret;
3337
3338 if (!PyArg_ParseTuple(args, "O", &obj))
3339 return NULL;
3340 ret = (*func)(self, obj, NULL);
3341 if (ret < 0)
3342 return NULL;
3343 Py_INCREF(Py_None);
3344 return Py_None;
3345}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003346
Tim Peters6d6c1a32001-08-02 04:15:00 +00003347static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003348wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003349{
3350 initproc func = (initproc)wrapped;
3351
Guido van Rossumc8e56452001-10-22 00:43:43 +00003352 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003353 return NULL;
3354 Py_INCREF(Py_None);
3355 return Py_None;
3356}
3357
Tim Peters6d6c1a32001-08-02 04:15:00 +00003358static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003359tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003360{
Barry Warsaw60f01882001-08-22 19:24:42 +00003361 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003362 PyObject *arg0, *res;
3363
3364 if (self == NULL || !PyType_Check(self))
3365 Py_FatalError("__new__() called with non-type 'self'");
3366 type = (PyTypeObject *)self;
3367 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003368 PyErr_Format(PyExc_TypeError,
3369 "%s.__new__(): not enough arguments",
3370 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003371 return NULL;
3372 }
3373 arg0 = PyTuple_GET_ITEM(args, 0);
3374 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003375 PyErr_Format(PyExc_TypeError,
3376 "%s.__new__(X): X is not a type object (%s)",
3377 type->tp_name,
3378 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003379 return NULL;
3380 }
3381 subtype = (PyTypeObject *)arg0;
3382 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003383 PyErr_Format(PyExc_TypeError,
3384 "%s.__new__(%s): %s is not a subtype of %s",
3385 type->tp_name,
3386 subtype->tp_name,
3387 subtype->tp_name,
3388 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003389 return NULL;
3390 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003391
3392 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003393 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003394 most derived base that's not a heap type is this type. */
3395 staticbase = subtype;
3396 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3397 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003398 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003399 PyErr_Format(PyExc_TypeError,
3400 "%s.__new__(%s) is not safe, use %s.__new__()",
3401 type->tp_name,
3402 subtype->tp_name,
3403 staticbase == NULL ? "?" : staticbase->tp_name);
3404 return NULL;
3405 }
3406
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003407 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3408 if (args == NULL)
3409 return NULL;
3410 res = type->tp_new(subtype, args, kwds);
3411 Py_DECREF(args);
3412 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413}
3414
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003415static struct PyMethodDef tp_new_methoddef[] = {
3416 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003417 PyDoc_STR("T.__new__(S, ...) -> "
3418 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419 {0}
3420};
3421
3422static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003423add_tp_new_wrapper(PyTypeObject *type)
3424{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003425 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003426
Guido van Rossum687ae002001-10-15 22:03:32 +00003427 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003428 return 0;
3429 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003430 if (func == NULL)
3431 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003432 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003433}
3434
Guido van Rossumf040ede2001-08-07 16:40:56 +00003435/* Slot wrappers that call the corresponding __foo__ slot. See comments
3436 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003437
Guido van Rossumdc91b992001-08-08 22:26:22 +00003438#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003439static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003440FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003442 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003443 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003444}
3445
Guido van Rossumdc91b992001-08-08 22:26:22 +00003446#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003447static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003448FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003449{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003450 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003451 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003452}
3453
Guido van Rossumdc91b992001-08-08 22:26:22 +00003454
3455#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003456static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003457FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003458{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003459 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003460 int do_other = self->ob_type != other->ob_type && \
3461 other->ob_type->tp_as_number != NULL && \
3462 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003463 if (self->ob_type->tp_as_number != NULL && \
3464 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3465 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003466 if (do_other && \
3467 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
3468 r = call_maybe( \
3469 other, ROPSTR, &rcache_str, "(O)", self); \
3470 if (r != Py_NotImplemented) \
3471 return r; \
3472 Py_DECREF(r); \
3473 do_other = 0; \
3474 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003475 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003476 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003477 if (r != Py_NotImplemented || \
3478 other->ob_type == self->ob_type) \
3479 return r; \
3480 Py_DECREF(r); \
3481 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003482 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003483 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003484 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003485 } \
3486 Py_INCREF(Py_NotImplemented); \
3487 return Py_NotImplemented; \
3488}
3489
3490#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3491 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3492
3493#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3494static PyObject * \
3495FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3496{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003497 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003498 return call_method(self, OPSTR, &cache_str, \
3499 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003500}
3501
3502static int
3503slot_sq_length(PyObject *self)
3504{
Guido van Rossum2730b132001-08-28 18:22:14 +00003505 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003506 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003507 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003508
3509 if (res == NULL)
3510 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003511 len = (int)PyInt_AsLong(res);
3512 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003513 if (len == -1 && PyErr_Occurred())
3514 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003515 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003516 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003517 "__len__() should return >= 0");
3518 return -1;
3519 }
Guido van Rossum26111622001-10-01 16:42:49 +00003520 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003521}
3522
Guido van Rossumdc91b992001-08-08 22:26:22 +00003523SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3524SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003525
3526/* Super-optimized version of slot_sq_item.
3527 Other slots could do the same... */
3528static PyObject *
3529slot_sq_item(PyObject *self, int i)
3530{
3531 static PyObject *getitem_str;
3532 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3533 descrgetfunc f;
3534
3535 if (getitem_str == NULL) {
3536 getitem_str = PyString_InternFromString("__getitem__");
3537 if (getitem_str == NULL)
3538 return NULL;
3539 }
3540 func = _PyType_Lookup(self->ob_type, getitem_str);
3541 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003542 if ((f = func->ob_type->tp_descr_get) == NULL)
3543 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003544 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003545 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003546 if (func == NULL) {
3547 return NULL;
3548 }
3549 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003550 ival = PyInt_FromLong(i);
3551 if (ival != NULL) {
3552 args = PyTuple_New(1);
3553 if (args != NULL) {
3554 PyTuple_SET_ITEM(args, 0, ival);
3555 retval = PyObject_Call(func, args, NULL);
3556 Py_XDECREF(args);
3557 Py_XDECREF(func);
3558 return retval;
3559 }
3560 }
3561 }
3562 else {
3563 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3564 }
3565 Py_XDECREF(args);
3566 Py_XDECREF(ival);
3567 Py_XDECREF(func);
3568 return NULL;
3569}
3570
Guido van Rossumdc91b992001-08-08 22:26:22 +00003571SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003572
3573static int
3574slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3575{
3576 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003577 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003578
3579 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003580 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003581 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003582 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003583 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003584 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585 if (res == NULL)
3586 return -1;
3587 Py_DECREF(res);
3588 return 0;
3589}
3590
3591static int
3592slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3593{
3594 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003595 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003596
3597 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003598 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003599 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003600 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003601 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003602 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003603 if (res == NULL)
3604 return -1;
3605 Py_DECREF(res);
3606 return 0;
3607}
3608
3609static int
3610slot_sq_contains(PyObject *self, PyObject *value)
3611{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003612 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003613 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003614
Guido van Rossum55f20992001-10-01 17:18:22 +00003615 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003616
3617 if (func != NULL) {
3618 args = Py_BuildValue("(O)", value);
3619 if (args == NULL)
3620 res = NULL;
3621 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003622 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003623 Py_DECREF(args);
3624 }
3625 Py_DECREF(func);
3626 if (res == NULL)
3627 return -1;
3628 return PyObject_IsTrue(res);
3629 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003630 else if (PyErr_Occurred())
3631 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003632 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003633 return _PySequence_IterSearch(self, value,
3634 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003635 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003636}
3637
Guido van Rossumdc91b992001-08-08 22:26:22 +00003638SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3639SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003640
3641#define slot_mp_length slot_sq_length
3642
Guido van Rossumdc91b992001-08-08 22:26:22 +00003643SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003644
3645static int
3646slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3647{
3648 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003649 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003650
3651 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003652 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003653 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003654 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003655 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003656 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003657 if (res == NULL)
3658 return -1;
3659 Py_DECREF(res);
3660 return 0;
3661}
3662
Guido van Rossumdc91b992001-08-08 22:26:22 +00003663SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3664SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3665SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3666SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3667SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3668SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3669
Jeremy Hylton938ace62002-07-17 16:30:39 +00003670static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003671
3672SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3673 nb_power, "__pow__", "__rpow__")
3674
3675static PyObject *
3676slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3677{
Guido van Rossum2730b132001-08-28 18:22:14 +00003678 static PyObject *pow_str;
3679
Guido van Rossumdc91b992001-08-08 22:26:22 +00003680 if (modulus == Py_None)
3681 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003682 /* Three-arg power doesn't use __rpow__. But ternary_op
3683 can call this when the second argument's type uses
3684 slot_nb_power, so check before calling self.__pow__. */
3685 if (self->ob_type->tp_as_number != NULL &&
3686 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3687 return call_method(self, "__pow__", &pow_str,
3688 "(OO)", other, modulus);
3689 }
3690 Py_INCREF(Py_NotImplemented);
3691 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003692}
3693
3694SLOT0(slot_nb_negative, "__neg__")
3695SLOT0(slot_nb_positive, "__pos__")
3696SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003697
3698static int
3699slot_nb_nonzero(PyObject *self)
3700{
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003701 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003702 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003703
Guido van Rossum55f20992001-10-01 17:18:22 +00003704 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003705 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003706 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003707 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003708 func = lookup_maybe(self, "__len__", &len_str);
3709 if (func == NULL) {
3710 if (PyErr_Occurred())
3711 return -1;
3712 else
3713 return 1;
3714 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003715 }
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003716 args = res = PyTuple_New(0);
3717 if (args != NULL) {
3718 res = PyObject_Call(func, args, NULL);
3719 Py_DECREF(args);
3720 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003721 Py_DECREF(func);
3722 if (res == NULL)
3723 return -1;
3724 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725}
3726
Guido van Rossumdc91b992001-08-08 22:26:22 +00003727SLOT0(slot_nb_invert, "__invert__")
3728SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3729SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3730SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3731SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3732SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003733
3734static int
3735slot_nb_coerce(PyObject **a, PyObject **b)
3736{
3737 static PyObject *coerce_str;
3738 PyObject *self = *a, *other = *b;
3739
3740 if (self->ob_type->tp_as_number != NULL &&
3741 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3742 PyObject *r;
3743 r = call_maybe(
3744 self, "__coerce__", &coerce_str, "(O)", other);
3745 if (r == NULL)
3746 return -1;
3747 if (r == Py_NotImplemented) {
3748 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003749 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003750 else {
3751 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3752 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003753 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003754 Py_DECREF(r);
3755 return -1;
3756 }
3757 *a = PyTuple_GET_ITEM(r, 0);
3758 Py_INCREF(*a);
3759 *b = PyTuple_GET_ITEM(r, 1);
3760 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003761 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003762 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003763 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003764 }
3765 if (other->ob_type->tp_as_number != NULL &&
3766 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3767 PyObject *r;
3768 r = call_maybe(
3769 other, "__coerce__", &coerce_str, "(O)", self);
3770 if (r == NULL)
3771 return -1;
3772 if (r == Py_NotImplemented) {
3773 Py_DECREF(r);
3774 return 1;
3775 }
3776 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3777 PyErr_SetString(PyExc_TypeError,
3778 "__coerce__ didn't return a 2-tuple");
3779 Py_DECREF(r);
3780 return -1;
3781 }
3782 *a = PyTuple_GET_ITEM(r, 1);
3783 Py_INCREF(*a);
3784 *b = PyTuple_GET_ITEM(r, 0);
3785 Py_INCREF(*b);
3786 Py_DECREF(r);
3787 return 0;
3788 }
3789 return 1;
3790}
3791
Guido van Rossumdc91b992001-08-08 22:26:22 +00003792SLOT0(slot_nb_int, "__int__")
3793SLOT0(slot_nb_long, "__long__")
3794SLOT0(slot_nb_float, "__float__")
3795SLOT0(slot_nb_oct, "__oct__")
3796SLOT0(slot_nb_hex, "__hex__")
3797SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3798SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3799SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3800SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3801SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003802SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003803SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3804SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3805SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3806SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3807SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3808SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3809 "__floordiv__", "__rfloordiv__")
3810SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3811SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3812SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003813
3814static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003815half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003816{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003817 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003818 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003819 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003820
Guido van Rossum60718732001-08-28 17:47:51 +00003821 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003822 if (func == NULL) {
3823 PyErr_Clear();
3824 }
3825 else {
3826 args = Py_BuildValue("(O)", other);
3827 if (args == NULL)
3828 res = NULL;
3829 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003830 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003831 Py_DECREF(args);
3832 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003833 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003834 if (res != Py_NotImplemented) {
3835 if (res == NULL)
3836 return -2;
3837 c = PyInt_AsLong(res);
3838 Py_DECREF(res);
3839 if (c == -1 && PyErr_Occurred())
3840 return -2;
3841 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3842 }
3843 Py_DECREF(res);
3844 }
3845 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003846}
3847
Guido van Rossumab3b0342001-09-18 20:38:53 +00003848/* This slot is published for the benefit of try_3way_compare in object.c */
3849int
3850_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003851{
3852 int c;
3853
Guido van Rossumab3b0342001-09-18 20:38:53 +00003854 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003855 c = half_compare(self, other);
3856 if (c <= 1)
3857 return c;
3858 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003859 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003860 c = half_compare(other, self);
3861 if (c < -1)
3862 return -2;
3863 if (c <= 1)
3864 return -c;
3865 }
3866 return (void *)self < (void *)other ? -1 :
3867 (void *)self > (void *)other ? 1 : 0;
3868}
3869
3870static PyObject *
3871slot_tp_repr(PyObject *self)
3872{
3873 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003874 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003875
Guido van Rossum60718732001-08-28 17:47:51 +00003876 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003877 if (func != NULL) {
3878 res = PyEval_CallObject(func, NULL);
3879 Py_DECREF(func);
3880 return res;
3881 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003882 PyErr_Clear();
3883 return PyString_FromFormat("<%s object at %p>",
3884 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003885}
3886
3887static PyObject *
3888slot_tp_str(PyObject *self)
3889{
3890 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003891 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003892
Guido van Rossum60718732001-08-28 17:47:51 +00003893 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003894 if (func != NULL) {
3895 res = PyEval_CallObject(func, NULL);
3896 Py_DECREF(func);
3897 return res;
3898 }
3899 else {
3900 PyErr_Clear();
3901 return slot_tp_repr(self);
3902 }
3903}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003904
3905static long
3906slot_tp_hash(PyObject *self)
3907{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003908 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003909 static PyObject *hash_str, *eq_str, *cmp_str;
3910
Tim Peters6d6c1a32001-08-02 04:15:00 +00003911 long h;
3912
Guido van Rossum60718732001-08-28 17:47:51 +00003913 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003914
3915 if (func != NULL) {
3916 res = PyEval_CallObject(func, NULL);
3917 Py_DECREF(func);
3918 if (res == NULL)
3919 return -1;
3920 h = PyInt_AsLong(res);
3921 }
3922 else {
3923 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003924 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003925 if (func == NULL) {
3926 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003927 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003928 }
3929 if (func != NULL) {
3930 Py_DECREF(func);
3931 PyErr_SetString(PyExc_TypeError, "unhashable type");
3932 return -1;
3933 }
3934 PyErr_Clear();
3935 h = _Py_HashPointer((void *)self);
3936 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003937 if (h == -1 && !PyErr_Occurred())
3938 h = -2;
3939 return h;
3940}
3941
3942static PyObject *
3943slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3944{
Guido van Rossum60718732001-08-28 17:47:51 +00003945 static PyObject *call_str;
3946 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003947 PyObject *res;
3948
3949 if (meth == NULL)
3950 return NULL;
3951 res = PyObject_Call(meth, args, kwds);
3952 Py_DECREF(meth);
3953 return res;
3954}
3955
Guido van Rossum14a6f832001-10-17 13:59:09 +00003956/* There are two slot dispatch functions for tp_getattro.
3957
3958 - slot_tp_getattro() is used when __getattribute__ is overridden
3959 but no __getattr__ hook is present;
3960
3961 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3962
Guido van Rossumc334df52002-04-04 23:44:47 +00003963 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3964 detects the absence of __getattr__ and then installs the simpler slot if
3965 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003966
Tim Peters6d6c1a32001-08-02 04:15:00 +00003967static PyObject *
3968slot_tp_getattro(PyObject *self, PyObject *name)
3969{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003970 static PyObject *getattribute_str = NULL;
3971 return call_method(self, "__getattribute__", &getattribute_str,
3972 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973}
3974
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003975static PyObject *
3976slot_tp_getattr_hook(PyObject *self, PyObject *name)
3977{
3978 PyTypeObject *tp = self->ob_type;
3979 PyObject *getattr, *getattribute, *res;
3980 static PyObject *getattribute_str = NULL;
3981 static PyObject *getattr_str = NULL;
3982
3983 if (getattr_str == NULL) {
3984 getattr_str = PyString_InternFromString("__getattr__");
3985 if (getattr_str == NULL)
3986 return NULL;
3987 }
3988 if (getattribute_str == NULL) {
3989 getattribute_str =
3990 PyString_InternFromString("__getattribute__");
3991 if (getattribute_str == NULL)
3992 return NULL;
3993 }
3994 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003995 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003996 /* No __getattr__ hook: use a simpler dispatcher */
3997 tp->tp_getattro = slot_tp_getattro;
3998 return slot_tp_getattro(self, name);
3999 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004000 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004001 if (getattribute == NULL ||
4002 (getattribute->ob_type == &PyWrapperDescr_Type &&
4003 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4004 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004005 res = PyObject_GenericGetAttr(self, name);
4006 else
4007 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004008 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004009 PyErr_Clear();
4010 res = PyObject_CallFunction(getattr, "OO", self, name);
4011 }
4012 return res;
4013}
4014
Tim Peters6d6c1a32001-08-02 04:15:00 +00004015static int
4016slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4017{
4018 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004019 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004020
4021 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004022 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004023 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004024 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004025 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004026 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004027 if (res == NULL)
4028 return -1;
4029 Py_DECREF(res);
4030 return 0;
4031}
4032
4033/* Map rich comparison operators to their __xx__ namesakes */
4034static char *name_op[] = {
4035 "__lt__",
4036 "__le__",
4037 "__eq__",
4038 "__ne__",
4039 "__gt__",
4040 "__ge__",
4041};
4042
4043static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004044half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004045{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004046 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004047 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004048
Guido van Rossum60718732001-08-28 17:47:51 +00004049 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004050 if (func == NULL) {
4051 PyErr_Clear();
4052 Py_INCREF(Py_NotImplemented);
4053 return Py_NotImplemented;
4054 }
4055 args = Py_BuildValue("(O)", other);
4056 if (args == NULL)
4057 res = NULL;
4058 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004059 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004060 Py_DECREF(args);
4061 }
4062 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004063 return res;
4064}
4065
Guido van Rossumb8f63662001-08-15 23:57:02 +00004066/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4067static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4068
4069static PyObject *
4070slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4071{
4072 PyObject *res;
4073
4074 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4075 res = half_richcompare(self, other, op);
4076 if (res != Py_NotImplemented)
4077 return res;
4078 Py_DECREF(res);
4079 }
4080 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4081 res = half_richcompare(other, self, swapped_op[op]);
4082 if (res != Py_NotImplemented) {
4083 return res;
4084 }
4085 Py_DECREF(res);
4086 }
4087 Py_INCREF(Py_NotImplemented);
4088 return Py_NotImplemented;
4089}
4090
4091static PyObject *
4092slot_tp_iter(PyObject *self)
4093{
4094 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004095 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004096
Guido van Rossum60718732001-08-28 17:47:51 +00004097 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004098 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004099 PyObject *args;
4100 args = res = PyTuple_New(0);
4101 if (args != NULL) {
4102 res = PyObject_Call(func, args, NULL);
4103 Py_DECREF(args);
4104 }
4105 Py_DECREF(func);
4106 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004107 }
4108 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004109 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004110 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004111 PyErr_SetString(PyExc_TypeError,
4112 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004113 return NULL;
4114 }
4115 Py_DECREF(func);
4116 return PySeqIter_New(self);
4117}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004118
4119static PyObject *
4120slot_tp_iternext(PyObject *self)
4121{
Guido van Rossum2730b132001-08-28 18:22:14 +00004122 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004123 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004124}
4125
Guido van Rossum1a493502001-08-17 16:47:50 +00004126static PyObject *
4127slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4128{
4129 PyTypeObject *tp = self->ob_type;
4130 PyObject *get;
4131 static PyObject *get_str = NULL;
4132
4133 if (get_str == NULL) {
4134 get_str = PyString_InternFromString("__get__");
4135 if (get_str == NULL)
4136 return NULL;
4137 }
4138 get = _PyType_Lookup(tp, get_str);
4139 if (get == NULL) {
4140 /* Avoid further slowdowns */
4141 if (tp->tp_descr_get == slot_tp_descr_get)
4142 tp->tp_descr_get = NULL;
4143 Py_INCREF(self);
4144 return self;
4145 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004146 if (obj == NULL)
4147 obj = Py_None;
4148 if (type == NULL)
4149 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004150 return PyObject_CallFunction(get, "OOO", self, obj, type);
4151}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004152
4153static int
4154slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4155{
Guido van Rossum2c252392001-08-24 10:13:31 +00004156 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004157 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004158
4159 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004160 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004161 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004162 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004163 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004164 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004165 if (res == NULL)
4166 return -1;
4167 Py_DECREF(res);
4168 return 0;
4169}
4170
4171static int
4172slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4173{
Guido van Rossum60718732001-08-28 17:47:51 +00004174 static PyObject *init_str;
4175 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004176 PyObject *res;
4177
4178 if (meth == NULL)
4179 return -1;
4180 res = PyObject_Call(meth, args, kwds);
4181 Py_DECREF(meth);
4182 if (res == NULL)
4183 return -1;
4184 Py_DECREF(res);
4185 return 0;
4186}
4187
4188static PyObject *
4189slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4190{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004191 static PyObject *new_str;
4192 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004193 PyObject *newargs, *x;
4194 int i, n;
4195
Guido van Rossum7bed2132002-08-08 21:57:53 +00004196 if (new_str == NULL) {
4197 new_str = PyString_InternFromString("__new__");
4198 if (new_str == NULL)
4199 return NULL;
4200 }
4201 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004202 if (func == NULL)
4203 return NULL;
4204 assert(PyTuple_Check(args));
4205 n = PyTuple_GET_SIZE(args);
4206 newargs = PyTuple_New(n+1);
4207 if (newargs == NULL)
4208 return NULL;
4209 Py_INCREF(type);
4210 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4211 for (i = 0; i < n; i++) {
4212 x = PyTuple_GET_ITEM(args, i);
4213 Py_INCREF(x);
4214 PyTuple_SET_ITEM(newargs, i+1, x);
4215 }
4216 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004217 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004218 Py_DECREF(func);
4219 return x;
4220}
4221
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004222static void
4223slot_tp_del(PyObject *self)
4224{
4225 static PyObject *del_str = NULL;
4226 PyObject *del, *res;
4227 PyObject *error_type, *error_value, *error_traceback;
4228
4229 /* Temporarily resurrect the object. */
4230 assert(self->ob_refcnt == 0);
4231 self->ob_refcnt = 1;
4232
4233 /* Save the current exception, if any. */
4234 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4235
4236 /* Execute __del__ method, if any. */
4237 del = lookup_maybe(self, "__del__", &del_str);
4238 if (del != NULL) {
4239 res = PyEval_CallObject(del, NULL);
4240 if (res == NULL)
4241 PyErr_WriteUnraisable(del);
4242 else
4243 Py_DECREF(res);
4244 Py_DECREF(del);
4245 }
4246
4247 /* Restore the saved exception. */
4248 PyErr_Restore(error_type, error_value, error_traceback);
4249
4250 /* Undo the temporary resurrection; can't use DECREF here, it would
4251 * cause a recursive call.
4252 */
4253 assert(self->ob_refcnt > 0);
4254 if (--self->ob_refcnt == 0)
4255 return; /* this is the normal path out */
4256
4257 /* __del__ resurrected it! Make it look like the original Py_DECREF
4258 * never happened.
4259 */
4260 {
4261 int refcnt = self->ob_refcnt;
4262 _Py_NewReference(self);
4263 self->ob_refcnt = refcnt;
4264 }
4265 assert(!PyType_IS_GC(self->ob_type) ||
4266 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4267 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4268 * _Py_NewReference bumped it again, so that's a wash.
4269 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4270 * chain, so no more to do there either.
4271 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4272 * _Py_NewReference bumped tp_allocs: both of those need to be
4273 * undone.
4274 */
4275#ifdef COUNT_ALLOCS
4276 --self->ob_type->tp_frees;
4277 --self->ob_type->tp_allocs;
4278#endif
4279}
4280
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004281
4282/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4283 functions. The offsets here are relative to the 'etype' structure, which
4284 incorporates the additional structures used for numbers, sequences and
4285 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4286 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004287 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4288 terminated with an all-zero entry. (This table is further initialized and
4289 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004290
Guido van Rossum6d204072001-10-21 00:44:31 +00004291typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004292
4293#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004294#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004295#undef ETSLOT
4296#undef SQSLOT
4297#undef MPSLOT
4298#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004299#undef UNSLOT
4300#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004301#undef BINSLOT
4302#undef RBINSLOT
4303
Guido van Rossum6d204072001-10-21 00:44:31 +00004304#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004305 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4306 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004307#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4308 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004309 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004310#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004311 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4312 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004313#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4314 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4315#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4316 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4317#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4318 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4319#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4320 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4321 "x." NAME "() <==> " DOC)
4322#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4323 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4324 "x." NAME "(y) <==> x" DOC "y")
4325#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4326 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4327 "x." NAME "(y) <==> x" DOC "y")
4328#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4329 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4330 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004331
4332static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004333 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4334 "x.__len__() <==> len(x)"),
4335 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4336 "x.__add__(y) <==> x+y"),
4337 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4338 "x.__mul__(n) <==> x*n"),
4339 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4340 "x.__rmul__(n) <==> n*x"),
4341 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4342 "x.__getitem__(y) <==> x[y]"),
4343 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4344 "x.__getslice__(i, j) <==> x[i:j]"),
4345 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4346 "x.__setitem__(i, y) <==> x[i]=y"),
4347 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4348 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004349 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004350 wrap_intintobjargproc,
4351 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4352 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4353 "x.__delslice__(i, j) <==> del x[i:j]"),
4354 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4355 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004356 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004357 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004358 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004359 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004360
Guido van Rossum6d204072001-10-21 00:44:31 +00004361 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4362 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004363 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004364 wrap_binaryfunc,
4365 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004366 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004367 wrap_objobjargproc,
4368 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004369 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004370 wrap_delitem,
4371 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004372
Guido van Rossum6d204072001-10-21 00:44:31 +00004373 BINSLOT("__add__", nb_add, slot_nb_add,
4374 "+"),
4375 RBINSLOT("__radd__", nb_add, slot_nb_add,
4376 "+"),
4377 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4378 "-"),
4379 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4380 "-"),
4381 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4382 "*"),
4383 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4384 "*"),
4385 BINSLOT("__div__", nb_divide, slot_nb_divide,
4386 "/"),
4387 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4388 "/"),
4389 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4390 "%"),
4391 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4392 "%"),
4393 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4394 "divmod(x, y)"),
4395 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4396 "divmod(y, x)"),
4397 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4398 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4399 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4400 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4401 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4402 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4403 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4404 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004405 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004406 "x != 0"),
4407 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4408 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4409 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4410 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4411 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4412 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4413 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4414 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4415 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4416 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4417 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4418 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4419 "x.__coerce__(y) <==> coerce(x, y)"),
4420 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4421 "int(x)"),
4422 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4423 "long(x)"),
4424 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4425 "float(x)"),
4426 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4427 "oct(x)"),
4428 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4429 "hex(x)"),
4430 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4431 wrap_binaryfunc, "+"),
4432 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4433 wrap_binaryfunc, "-"),
4434 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4435 wrap_binaryfunc, "*"),
4436 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4437 wrap_binaryfunc, "/"),
4438 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4439 wrap_binaryfunc, "%"),
4440 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004441 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004442 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4443 wrap_binaryfunc, "<<"),
4444 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4445 wrap_binaryfunc, ">>"),
4446 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4447 wrap_binaryfunc, "&"),
4448 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4449 wrap_binaryfunc, "^"),
4450 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4451 wrap_binaryfunc, "|"),
4452 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4453 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4454 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4455 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4456 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4457 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4458 IBSLOT("__itruediv__", nb_inplace_true_divide,
4459 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004460
Guido van Rossum6d204072001-10-21 00:44:31 +00004461 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4462 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004463 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004464 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4465 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004466 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004467 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4468 "x.__cmp__(y) <==> cmp(x,y)"),
4469 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4470 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004471 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4472 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004473 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004474 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4475 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4476 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4477 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4478 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4479 "x.__setattr__('name', value) <==> x.name = value"),
4480 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4481 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4482 "x.__delattr__('name') <==> del x.name"),
4483 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4484 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4485 "x.__lt__(y) <==> x<y"),
4486 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4487 "x.__le__(y) <==> x<=y"),
4488 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4489 "x.__eq__(y) <==> x==y"),
4490 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4491 "x.__ne__(y) <==> x!=y"),
4492 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4493 "x.__gt__(y) <==> x>y"),
4494 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4495 "x.__ge__(y) <==> x>=y"),
4496 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4497 "x.__iter__() <==> iter(x)"),
4498 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4499 "x.next() -> the next value, or raise StopIteration"),
4500 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4501 "descr.__get__(obj[, type]) -> value"),
4502 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4503 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004504 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4505 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004506 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004507 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004508 "see x.__class__.__doc__ for signature",
4509 PyWrapperFlag_KEYWORDS),
4510 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004511 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004512 {NULL}
4513};
4514
Guido van Rossumc334df52002-04-04 23:44:47 +00004515/* Given a type pointer and an offset gotten from a slotdef entry, return a
4516 pointer to the actual slot. This is not quite the same as simply adding
4517 the offset to the type pointer, since it takes care to indirect through the
4518 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4519 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004520static void **
4521slotptr(PyTypeObject *type, int offset)
4522{
4523 char *ptr;
4524
Guido van Rossum09638c12002-06-13 19:17:46 +00004525 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004526 assert(offset >= 0);
4527 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004528 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004529 ptr = (void *)type->tp_as_sequence;
4530 offset -= offsetof(etype, as_sequence);
4531 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004532 else if (offset >= offsetof(etype, as_mapping)) {
4533 ptr = (void *)type->tp_as_mapping;
4534 offset -= offsetof(etype, as_mapping);
4535 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004536 else if (offset >= offsetof(etype, as_number)) {
4537 ptr = (void *)type->tp_as_number;
4538 offset -= offsetof(etype, as_number);
4539 }
4540 else {
4541 ptr = (void *)type;
4542 }
4543 if (ptr != NULL)
4544 ptr += offset;
4545 return (void **)ptr;
4546}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004547
Guido van Rossumc334df52002-04-04 23:44:47 +00004548/* Length of array of slotdef pointers used to store slots with the
4549 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4550 the same __name__, for any __name__. Since that's a static property, it is
4551 appropriate to declare fixed-size arrays for this. */
4552#define MAX_EQUIV 10
4553
4554/* Return a slot pointer for a given name, but ONLY if the attribute has
4555 exactly one slot function. The name must be an interned string. */
4556static void **
4557resolve_slotdups(PyTypeObject *type, PyObject *name)
4558{
4559 /* XXX Maybe this could be optimized more -- but is it worth it? */
4560
4561 /* pname and ptrs act as a little cache */
4562 static PyObject *pname;
4563 static slotdef *ptrs[MAX_EQUIV];
4564 slotdef *p, **pp;
4565 void **res, **ptr;
4566
4567 if (pname != name) {
4568 /* Collect all slotdefs that match name into ptrs. */
4569 pname = name;
4570 pp = ptrs;
4571 for (p = slotdefs; p->name_strobj; p++) {
4572 if (p->name_strobj == name)
4573 *pp++ = p;
4574 }
4575 *pp = NULL;
4576 }
4577
4578 /* Look in all matching slots of the type; if exactly one of these has
4579 a filled-in slot, return its value. Otherwise return NULL. */
4580 res = NULL;
4581 for (pp = ptrs; *pp; pp++) {
4582 ptr = slotptr(type, (*pp)->offset);
4583 if (ptr == NULL || *ptr == NULL)
4584 continue;
4585 if (res != NULL)
4586 return NULL;
4587 res = ptr;
4588 }
4589 return res;
4590}
4591
4592/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4593 does some incredibly complex thinking and then sticks something into the
4594 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4595 interests, and then stores a generic wrapper or a specific function into
4596 the slot.) Return a pointer to the next slotdef with a different offset,
4597 because that's convenient for fixup_slot_dispatchers(). */
4598static slotdef *
4599update_one_slot(PyTypeObject *type, slotdef *p)
4600{
4601 PyObject *descr;
4602 PyWrapperDescrObject *d;
4603 void *generic = NULL, *specific = NULL;
4604 int use_generic = 0;
4605 int offset = p->offset;
4606 void **ptr = slotptr(type, offset);
4607
4608 if (ptr == NULL) {
4609 do {
4610 ++p;
4611 } while (p->offset == offset);
4612 return p;
4613 }
4614 do {
4615 descr = _PyType_Lookup(type, p->name_strobj);
4616 if (descr == NULL)
4617 continue;
4618 if (descr->ob_type == &PyWrapperDescr_Type) {
4619 void **tptr = resolve_slotdups(type, p->name_strobj);
4620 if (tptr == NULL || tptr == ptr)
4621 generic = p->function;
4622 d = (PyWrapperDescrObject *)descr;
4623 if (d->d_base->wrapper == p->wrapper &&
4624 PyType_IsSubtype(type, d->d_type))
4625 {
4626 if (specific == NULL ||
4627 specific == d->d_wrapped)
4628 specific = d->d_wrapped;
4629 else
4630 use_generic = 1;
4631 }
4632 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004633 else if (descr->ob_type == &PyCFunction_Type &&
4634 PyCFunction_GET_FUNCTION(descr) ==
4635 (PyCFunction)tp_new_wrapper &&
4636 strcmp(p->name, "__new__") == 0)
4637 {
4638 /* The __new__ wrapper is not a wrapper descriptor,
4639 so must be special-cased differently.
4640 If we don't do this, creating an instance will
4641 always use slot_tp_new which will look up
4642 __new__ in the MRO which will call tp_new_wrapper
4643 which will look through the base classes looking
4644 for a static base and call its tp_new (usually
4645 PyType_GenericNew), after performing various
4646 sanity checks and constructing a new argument
4647 list. Cut all that nonsense short -- this speeds
4648 up instance creation tremendously. */
4649 specific = type->tp_new;
4650 /* XXX I'm not 100% sure that there isn't a hole
4651 in this reasoning that requires additional
4652 sanity checks. I'll buy the first person to
4653 point out a bug in this reasoning a beer. */
4654 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004655 else {
4656 use_generic = 1;
4657 generic = p->function;
4658 }
4659 } while ((++p)->offset == offset);
4660 if (specific && !use_generic)
4661 *ptr = specific;
4662 else
4663 *ptr = generic;
4664 return p;
4665}
4666
Guido van Rossum22b13872002-08-06 21:41:44 +00004667static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004668 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004669
Guido van Rossumc334df52002-04-04 23:44:47 +00004670/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4671 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004672static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004673update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004674{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004675 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004676
Guido van Rossumc334df52002-04-04 23:44:47 +00004677 for (pp = pp0; *pp; pp++)
4678 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004679 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004680}
4681
Guido van Rossumc334df52002-04-04 23:44:47 +00004682/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4683 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004684static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004685recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004686{
4687 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004688 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004689 int i, n;
4690
4691 subclasses = type->tp_subclasses;
4692 if (subclasses == NULL)
4693 return 0;
4694 assert(PyList_Check(subclasses));
4695 n = PyList_GET_SIZE(subclasses);
4696 for (i = 0; i < n; i++) {
4697 ref = PyList_GET_ITEM(subclasses, i);
4698 assert(PyWeakref_CheckRef(ref));
4699 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004700 assert(subclass != NULL);
4701 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004702 continue;
4703 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004704 /* Avoid recursing down into unaffected classes */
4705 dict = subclass->tp_dict;
4706 if (dict != NULL && PyDict_Check(dict) &&
4707 PyDict_GetItem(dict, name) != NULL)
4708 continue;
4709 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004710 return -1;
4711 }
4712 return 0;
4713}
4714
Guido van Rossumc334df52002-04-04 23:44:47 +00004715/* Comparison function for qsort() to compare slotdefs by their offset, and
4716 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004717static int
4718slotdef_cmp(const void *aa, const void *bb)
4719{
4720 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4721 int c = a->offset - b->offset;
4722 if (c != 0)
4723 return c;
4724 else
4725 return a - b;
4726}
4727
Guido van Rossumc334df52002-04-04 23:44:47 +00004728/* Initialize the slotdefs table by adding interned string objects for the
4729 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004730static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004731init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004732{
4733 slotdef *p;
4734 static int initialized = 0;
4735
4736 if (initialized)
4737 return;
4738 for (p = slotdefs; p->name; p++) {
4739 p->name_strobj = PyString_InternFromString(p->name);
4740 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004741 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004742 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004743 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4744 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004745 initialized = 1;
4746}
4747
Guido van Rossumc334df52002-04-04 23:44:47 +00004748/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004749static int
4750update_slot(PyTypeObject *type, PyObject *name)
4751{
Guido van Rossumc334df52002-04-04 23:44:47 +00004752 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004753 slotdef *p;
4754 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004755 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004756
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004757 init_slotdefs();
4758 pp = ptrs;
4759 for (p = slotdefs; p->name; p++) {
4760 /* XXX assume name is interned! */
4761 if (p->name_strobj == name)
4762 *pp++ = p;
4763 }
4764 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004765 for (pp = ptrs; *pp; pp++) {
4766 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004767 offset = p->offset;
4768 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004769 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004770 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004771 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004772 if (ptrs[0] == NULL)
4773 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004774 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004775}
4776
Guido van Rossumc334df52002-04-04 23:44:47 +00004777/* Store the proper functions in the slot dispatches at class (type)
4778 definition time, based upon which operations the class overrides in its
4779 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004780static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004781fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004782{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004783 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004784
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004785 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004786 for (p = slotdefs; p->name; )
4787 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004788}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004789
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004790static void
4791update_all_slots(PyTypeObject* type)
4792{
4793 slotdef *p;
4794
4795 init_slotdefs();
4796 for (p = slotdefs; p->name; p++) {
4797 /* update_slot returns int but can't actually fail */
4798 update_slot(type, p->name_strobj);
4799 }
4800}
4801
Guido van Rossum6d204072001-10-21 00:44:31 +00004802/* This function is called by PyType_Ready() to populate the type's
4803 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004804 function slot (like tp_repr) that's defined in the type, one or more
4805 corresponding descriptors are added in the type's tp_dict dictionary
4806 under the appropriate name (like __repr__). Some function slots
4807 cause more than one descriptor to be added (for example, the nb_add
4808 slot adds both __add__ and __radd__ descriptors) and some function
4809 slots compete for the same descriptor (for example both sq_item and
4810 mp_subscript generate a __getitem__ descriptor).
4811
4812 In the latter case, the first slotdef entry encoutered wins. Since
4813 slotdef entries are sorted by the offset of the slot in the etype
4814 struct, this gives us some control over disambiguating between
4815 competing slots: the members of struct etype are listed from most
4816 general to least general, so the most general slot is preferred. In
4817 particular, because as_mapping comes before as_sequence, for a type
4818 that defines both mp_subscript and sq_item, mp_subscript wins.
4819
4820 This only adds new descriptors and doesn't overwrite entries in
4821 tp_dict that were previously defined. The descriptors contain a
4822 reference to the C function they must call, so that it's safe if they
4823 are copied into a subtype's __dict__ and the subtype has a different
4824 C function in its slot -- calling the method defined by the
4825 descriptor will call the C function that was used to create it,
4826 rather than the C function present in the slot when it is called.
4827 (This is important because a subtype may have a C function in the
4828 slot that calls the method from the dictionary, and we want to avoid
4829 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004830
4831static int
4832add_operators(PyTypeObject *type)
4833{
4834 PyObject *dict = type->tp_dict;
4835 slotdef *p;
4836 PyObject *descr;
4837 void **ptr;
4838
4839 init_slotdefs();
4840 for (p = slotdefs; p->name; p++) {
4841 if (p->wrapper == NULL)
4842 continue;
4843 ptr = slotptr(type, p->offset);
4844 if (!ptr || !*ptr)
4845 continue;
4846 if (PyDict_GetItem(dict, p->name_strobj))
4847 continue;
4848 descr = PyDescr_NewWrapper(type, p, *ptr);
4849 if (descr == NULL)
4850 return -1;
4851 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4852 return -1;
4853 Py_DECREF(descr);
4854 }
4855 if (type->tp_new != NULL) {
4856 if (add_tp_new_wrapper(type) < 0)
4857 return -1;
4858 }
4859 return 0;
4860}
4861
Guido van Rossum705f0f52001-08-24 16:47:00 +00004862
4863/* Cooperative 'super' */
4864
4865typedef struct {
4866 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004867 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004868 PyObject *obj;
4869} superobject;
4870
Guido van Rossum6f799372001-09-20 20:46:19 +00004871static PyMemberDef super_members[] = {
4872 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4873 "the class invoking super()"},
4874 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4875 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004876 {0}
4877};
4878
Guido van Rossum705f0f52001-08-24 16:47:00 +00004879static void
4880super_dealloc(PyObject *self)
4881{
4882 superobject *su = (superobject *)self;
4883
Guido van Rossum048eb752001-10-02 21:24:57 +00004884 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004885 Py_XDECREF(su->obj);
4886 Py_XDECREF(su->type);
4887 self->ob_type->tp_free(self);
4888}
4889
4890static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004891super_repr(PyObject *self)
4892{
4893 superobject *su = (superobject *)self;
4894
4895 if (su->obj)
4896 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004897 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004898 su->type ? su->type->tp_name : "NULL",
4899 su->obj->ob_type->tp_name);
4900 else
4901 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004902 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004903 su->type ? su->type->tp_name : "NULL");
4904}
4905
4906static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004907super_getattro(PyObject *self, PyObject *name)
4908{
4909 superobject *su = (superobject *)self;
4910
4911 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004912 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004913 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004914 descrgetfunc f;
4915 int i, n;
4916
Guido van Rossum155db9a2002-04-02 17:53:47 +00004917 starttype = su->obj->ob_type;
4918 mro = starttype->tp_mro;
4919
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004920 if (mro == NULL)
4921 n = 0;
4922 else {
4923 assert(PyTuple_Check(mro));
4924 n = PyTuple_GET_SIZE(mro);
4925 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004926 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004927 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004928 break;
4929 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004930 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004931 starttype = (PyTypeObject *)(su->obj);
4932 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004933 if (mro == NULL)
4934 n = 0;
4935 else {
4936 assert(PyTuple_Check(mro));
4937 n = PyTuple_GET_SIZE(mro);
4938 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004939 for (i = 0; i < n; i++) {
4940 if ((PyObject *)(su->type) ==
4941 PyTuple_GET_ITEM(mro, i))
4942 break;
4943 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004944 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004945 i++;
4946 res = NULL;
4947 for (; i < n; i++) {
4948 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004949 if (PyType_Check(tmp))
4950 dict = ((PyTypeObject *)tmp)->tp_dict;
4951 else if (PyClass_Check(tmp))
4952 dict = ((PyClassObject *)tmp)->cl_dict;
4953 else
4954 continue;
4955 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004956 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004957 Py_INCREF(res);
4958 f = res->ob_type->tp_descr_get;
4959 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004960 tmp = f(res, su->obj,
4961 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004962 Py_DECREF(res);
4963 res = tmp;
4964 }
4965 return res;
4966 }
4967 }
4968 }
4969 return PyObject_GenericGetAttr(self, name);
4970}
4971
Guido van Rossum5b443c62001-12-03 15:38:28 +00004972static int
4973supercheck(PyTypeObject *type, PyObject *obj)
4974{
4975 if (!PyType_IsSubtype(obj->ob_type, type) &&
4976 !(PyType_Check(obj) &&
4977 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4978 PyErr_SetString(PyExc_TypeError,
4979 "super(type, obj): "
4980 "obj must be an instance or subtype of type");
4981 return -1;
4982 }
4983 else
4984 return 0;
4985}
4986
Guido van Rossum705f0f52001-08-24 16:47:00 +00004987static PyObject *
4988super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4989{
4990 superobject *su = (superobject *)self;
4991 superobject *new;
4992
4993 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4994 /* Not binding to an object, or already bound */
4995 Py_INCREF(self);
4996 return self;
4997 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00004998 if (su->ob_type != &PySuper_Type)
4999 /* If su is an instance of a subclass of super,
5000 call its type */
5001 return PyObject_CallFunction((PyObject *)su->ob_type,
5002 "OO", su->type, obj);
5003 else {
5004 /* Inline the common case */
5005 if (supercheck(su->type, obj) < 0)
5006 return NULL;
5007 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5008 NULL, NULL);
5009 if (new == NULL)
5010 return NULL;
5011 Py_INCREF(su->type);
5012 Py_INCREF(obj);
5013 new->type = su->type;
5014 new->obj = obj;
5015 return (PyObject *)new;
5016 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005017}
5018
5019static int
5020super_init(PyObject *self, PyObject *args, PyObject *kwds)
5021{
5022 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005023 PyTypeObject *type;
5024 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005025
5026 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5027 return -1;
5028 if (obj == Py_None)
5029 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005030 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005031 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005032 Py_INCREF(type);
5033 Py_XINCREF(obj);
5034 su->type = type;
5035 su->obj = obj;
5036 return 0;
5037}
5038
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005039PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005040"super(type) -> unbound super object\n"
5041"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005042"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005043"Typical use to call a cooperative superclass method:\n"
5044"class C(B):\n"
5045" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005046" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005047
Guido van Rossum048eb752001-10-02 21:24:57 +00005048static int
5049super_traverse(PyObject *self, visitproc visit, void *arg)
5050{
5051 superobject *su = (superobject *)self;
5052 int err;
5053
5054#define VISIT(SLOT) \
5055 if (SLOT) { \
5056 err = visit((PyObject *)(SLOT), arg); \
5057 if (err) \
5058 return err; \
5059 }
5060
5061 VISIT(su->obj);
5062 VISIT(su->type);
5063
5064#undef VISIT
5065
5066 return 0;
5067}
5068
Guido van Rossum705f0f52001-08-24 16:47:00 +00005069PyTypeObject PySuper_Type = {
5070 PyObject_HEAD_INIT(&PyType_Type)
5071 0, /* ob_size */
5072 "super", /* tp_name */
5073 sizeof(superobject), /* tp_basicsize */
5074 0, /* tp_itemsize */
5075 /* methods */
5076 super_dealloc, /* tp_dealloc */
5077 0, /* tp_print */
5078 0, /* tp_getattr */
5079 0, /* tp_setattr */
5080 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005081 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005082 0, /* tp_as_number */
5083 0, /* tp_as_sequence */
5084 0, /* tp_as_mapping */
5085 0, /* tp_hash */
5086 0, /* tp_call */
5087 0, /* tp_str */
5088 super_getattro, /* tp_getattro */
5089 0, /* tp_setattro */
5090 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005091 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5092 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005093 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005094 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005095 0, /* tp_clear */
5096 0, /* tp_richcompare */
5097 0, /* tp_weaklistoffset */
5098 0, /* tp_iter */
5099 0, /* tp_iternext */
5100 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005101 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005102 0, /* tp_getset */
5103 0, /* tp_base */
5104 0, /* tp_dict */
5105 super_descr_get, /* tp_descr_get */
5106 0, /* tp_descr_set */
5107 0, /* tp_dictoffset */
5108 super_init, /* tp_init */
5109 PyType_GenericAlloc, /* tp_alloc */
5110 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005111 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005112};