blob: d83ff8cab58ba8a2776a3a28870806f25434f103 [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
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000145mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000146{
147 PyTypeObject *subclass;
148 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000149 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000150
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;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000167 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000168 }
169 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000170 PyObject* tuple;
171 tuple = Py_BuildValue("OO", subclass, old_mro);
172 if (!tuple)
173 return -1;
174 if (PyList_Append(temp, tuple) < 0)
175 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000176 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000177 if (mro_subclasses(subclass, temp) < 0)
178 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000179 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000180 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000181}
182
183static int
184type_set_bases(PyTypeObject *type, PyObject *value, void *context)
185{
186 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000187 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000188 PyTypeObject *new_base, *old_base;
189 PyObject *old_bases, *old_mro;
190
191 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
192 PyErr_Format(PyExc_TypeError,
193 "can't set %s.__bases__", type->tp_name);
194 return -1;
195 }
196 if (!value) {
197 PyErr_Format(PyExc_TypeError,
198 "can't delete %s.__bases__", type->tp_name);
199 return -1;
200 }
201 if (!PyTuple_Check(value)) {
202 PyErr_Format(PyExc_TypeError,
203 "can only assign tuple to %s.__bases__, not %s",
204 type->tp_name, value->ob_type->tp_name);
205 return -1;
206 }
207 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
208 ob = PyTuple_GET_ITEM(value, i);
209 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
210 PyErr_Format(
211 PyExc_TypeError,
212 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
213 type->tp_name, ob->ob_type->tp_name);
214 return -1;
215 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000216 if (PyType_Check(ob)) {
217 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
218 PyErr_SetString(PyExc_TypeError,
219 "a __bases__ item causes an inheritance cycle");
220 return -1;
221 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000222 }
223 }
224
225 new_base = best_base(value);
226
227 if (!new_base) {
228 return -1;
229 }
230
231 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
232 return -1;
233
234 Py_INCREF(new_base);
235 Py_INCREF(value);
236
237 old_bases = type->tp_bases;
238 old_base = type->tp_base;
239 old_mro = type->tp_mro;
240
241 type->tp_bases = value;
242 type->tp_base = new_base;
243
244 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000245 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000246 }
247
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000248 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000249 if (!temp)
250 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000251
252 r = mro_subclasses(type, temp);
253
254 if (r < 0) {
255 for (i = 0; i < PyList_Size(temp); i++) {
256 PyTypeObject* cls;
257 PyObject* mro;
258 PyArg_ParseTuple(PyList_GetItem(temp, i),
259 "OO", &cls, &mro);
260 Py_DECREF(cls->tp_mro);
261 cls->tp_mro = mro;
262 Py_INCREF(cls->tp_mro);
263 }
264 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000265 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000266 }
267
268 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000269
270 /* any base that was in __bases__ but now isn't, we
271 need to remove |type| from it's tp_subclasses.
272 conversely, any class now in __bases__ that wasn't
273 needs to have |type| added to it's subclasses. */
274
275 /* for now, sod that: just remove from all old_bases,
276 add to all new_bases */
277
278 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
279 ob = PyTuple_GET_ITEM(old_bases, i);
280 if (PyType_Check(ob)) {
281 remove_subclass(
282 (PyTypeObject*)ob, type);
283 }
284 }
285
286 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
287 ob = PyTuple_GET_ITEM(value, i);
288 if (PyType_Check(ob)) {
289 if (add_subclass((PyTypeObject*)ob, type) < 0)
290 r = -1;
291 }
292 }
293
294 update_all_slots(type);
295
296 Py_DECREF(old_bases);
297 Py_DECREF(old_base);
298 Py_DECREF(old_mro);
299
300 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000301
302 bail:
303 type->tp_bases = old_bases;
304 type->tp_base = old_base;
305 type->tp_mro = old_mro;
306
307 Py_DECREF(value);
308 Py_DECREF(new_base);
309
310 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000311}
312
313static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000314type_dict(PyTypeObject *type, void *context)
315{
316 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000317 Py_INCREF(Py_None);
318 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000319 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000320 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000321}
322
Tim Peters24008312002-03-17 18:56:20 +0000323static PyObject *
324type_get_doc(PyTypeObject *type, void *context)
325{
326 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000327 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000328 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000329 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000330 if (result == NULL) {
331 result = Py_None;
332 Py_INCREF(result);
333 }
334 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000335 result = result->ob_type->tp_descr_get(result, NULL,
336 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000337 }
338 else {
339 Py_INCREF(result);
340 }
Tim Peters24008312002-03-17 18:56:20 +0000341 return result;
342}
343
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000344static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000345 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
346 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000347 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000348 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000349 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000350 {0}
351};
352
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000353static int
354type_compare(PyObject *v, PyObject *w)
355{
356 /* This is called with type objects only. So we
357 can just compare the addresses. */
358 Py_uintptr_t vv = (Py_uintptr_t)v;
359 Py_uintptr_t ww = (Py_uintptr_t)w;
360 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
361}
362
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000363static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000364type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000365{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000366 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000367 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000368
369 mod = type_module(type, NULL);
370 if (mod == NULL)
371 PyErr_Clear();
372 else if (!PyString_Check(mod)) {
373 Py_DECREF(mod);
374 mod = NULL;
375 }
376 name = type_name(type, NULL);
377 if (name == NULL)
378 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000379
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000380 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
381 kind = "class";
382 else
383 kind = "type";
384
Barry Warsaw7ce36942001-08-24 18:34:26 +0000385 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000386 rtn = PyString_FromFormat("<%s '%s.%s'>",
387 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000388 PyString_AS_STRING(mod),
389 PyString_AS_STRING(name));
390 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000391 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000392 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000393
Guido van Rossumc3542212001-08-16 09:18:56 +0000394 Py_XDECREF(mod);
395 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000396 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000397}
398
Tim Peters6d6c1a32001-08-02 04:15:00 +0000399static PyObject *
400type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
401{
402 PyObject *obj;
403
404 if (type->tp_new == NULL) {
405 PyErr_Format(PyExc_TypeError,
406 "cannot create '%.100s' instances",
407 type->tp_name);
408 return NULL;
409 }
410
Tim Peters3f996e72001-09-13 19:18:27 +0000411 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000412 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000413 /* Ugly exception: when the call was type(something),
414 don't call tp_init on the result. */
415 if (type == &PyType_Type &&
416 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
417 (kwds == NULL ||
418 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
419 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000420 /* If the returned object is not an instance of type,
421 it won't be initialized. */
422 if (!PyType_IsSubtype(obj->ob_type, type))
423 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000424 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000425 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
426 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000427 type->tp_init(obj, args, kwds) < 0) {
428 Py_DECREF(obj);
429 obj = NULL;
430 }
431 }
432 return obj;
433}
434
435PyObject *
436PyType_GenericAlloc(PyTypeObject *type, int nitems)
437{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000438 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000439 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000440
441 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000442 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000443 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000444 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000445
Neil Schemenauerc806c882001-08-29 23:54:54 +0000446 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000447 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000448
Neil Schemenauerc806c882001-08-29 23:54:54 +0000449 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000450
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
452 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000453
Tim Peters6d6c1a32001-08-02 04:15:00 +0000454 if (type->tp_itemsize == 0)
455 PyObject_INIT(obj, type);
456 else
457 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000458
Tim Peters6d6c1a32001-08-02 04:15:00 +0000459 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000460 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 return obj;
462}
463
464PyObject *
465PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
466{
467 return type->tp_alloc(type, 0);
468}
469
Guido van Rossum9475a232001-10-05 20:51:39 +0000470/* Helpers for subtyping */
471
472static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000473traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
474{
475 int i, n;
476 PyMemberDef *mp;
477
478 n = type->ob_size;
479 mp = ((etype *)type)->members;
480 for (i = 0; i < n; i++, mp++) {
481 if (mp->type == T_OBJECT_EX) {
482 char *addr = (char *)self + mp->offset;
483 PyObject *obj = *(PyObject **)addr;
484 if (obj != NULL) {
485 int err = visit(obj, arg);
486 if (err)
487 return err;
488 }
489 }
490 }
491 return 0;
492}
493
494static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000495subtype_traverse(PyObject *self, visitproc visit, void *arg)
496{
497 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000498 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000499
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000500 /* Find the nearest base with a different tp_traverse,
501 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000502 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000503 base = type;
504 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
505 if (base->ob_size) {
506 int err = traverse_slots(base, self, visit, arg);
507 if (err)
508 return err;
509 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000510 base = base->tp_base;
511 assert(base);
512 }
513
514 if (type->tp_dictoffset != base->tp_dictoffset) {
515 PyObject **dictptr = _PyObject_GetDictPtr(self);
516 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000517 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000518 if (err)
519 return err;
520 }
521 }
522
Guido van Rossuma3862092002-06-10 15:24:42 +0000523 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
524 /* For a heaptype, the instances count as references
525 to the type. Traverse the type so the collector
526 can find cycles involving this link. */
527 int err = visit((PyObject *)type, arg);
528 if (err)
529 return err;
530 }
531
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000532 if (basetraverse)
533 return basetraverse(self, visit, arg);
534 return 0;
535}
536
537static void
538clear_slots(PyTypeObject *type, PyObject *self)
539{
540 int i, n;
541 PyMemberDef *mp;
542
543 n = type->ob_size;
544 mp = ((etype *)type)->members;
545 for (i = 0; i < n; i++, mp++) {
546 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
547 char *addr = (char *)self + mp->offset;
548 PyObject *obj = *(PyObject **)addr;
549 if (obj != NULL) {
550 Py_DECREF(obj);
551 *(PyObject **)addr = NULL;
552 }
553 }
554 }
555}
556
557static int
558subtype_clear(PyObject *self)
559{
560 PyTypeObject *type, *base;
561 inquiry baseclear;
562
563 /* Find the nearest base with a different tp_clear
564 and clear slots while we're at it */
565 type = self->ob_type;
566 base = type;
567 while ((baseclear = base->tp_clear) == subtype_clear) {
568 if (base->ob_size)
569 clear_slots(base, self);
570 base = base->tp_base;
571 assert(base);
572 }
573
Guido van Rossuma3862092002-06-10 15:24:42 +0000574 /* There's no need to clear the instance dict (if any);
575 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000576
577 if (baseclear)
578 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000579 return 0;
580}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000581
582static void
583subtype_dealloc(PyObject *self)
584{
Guido van Rossum14227b42001-12-06 02:35:58 +0000585 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000586 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587
Guido van Rossum22b13872002-08-06 21:41:44 +0000588 /* Extract the type; we expect it to be a heap type */
589 type = self->ob_type;
590 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000591
Guido van Rossum22b13872002-08-06 21:41:44 +0000592 /* Test whether the type has GC exactly once */
593
594 if (!PyType_IS_GC(type)) {
595 /* It's really rare to find a dynamic type that doesn't have
596 GC; it can only happen when deriving from 'object' and not
597 adding any slots or instance variables. This allows
598 certain simplifications: there's no need to call
599 clear_slots(), or DECREF the dict, or clear weakrefs. */
600
601 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000602 if (type->tp_del) {
603 type->tp_del(self);
604 if (self->ob_refcnt > 0)
605 return;
606 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000607
608 /* Find the nearest base with a different tp_dealloc */
609 base = type;
610 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
611 assert(base->ob_size == 0);
612 base = base->tp_base;
613 assert(base);
614 }
615
616 /* Call the base tp_dealloc() */
617 assert(basedealloc);
618 basedealloc(self);
619
620 /* Can't reference self beyond this point */
621 Py_DECREF(type);
622
623 /* Done */
624 return;
625 }
626
627 /* We get here only if the type has GC */
628
629 /* UnTrack and re-Track around the trashcan macro, alas */
Guido van Rossum0906e072002-08-07 20:42:09 +0000630 PyObject_GC_UnTrack(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000631 Py_TRASHCAN_SAFE_BEGIN(self);
632 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
633
634 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000635 if (type->tp_del) {
636 type->tp_del(self);
637 if (self->ob_refcnt > 0)
638 goto endlabel;
639 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000640
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000641 /* Find the nearest base with a different tp_dealloc
642 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000643 base = type;
644 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
645 if (base->ob_size)
646 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000647 base = base->tp_base;
648 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000649 }
650
Tim Peters6d6c1a32001-08-02 04:15:00 +0000651 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000652 if (type->tp_dictoffset && !base->tp_dictoffset) {
653 PyObject **dictptr = _PyObject_GetDictPtr(self);
654 if (dictptr != NULL) {
655 PyObject *dict = *dictptr;
656 if (dict != NULL) {
657 Py_DECREF(dict);
658 *dictptr = NULL;
659 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000660 }
661 }
662
Guido van Rossum9676b222001-08-17 20:32:36 +0000663 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000664 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000665 PyObject_ClearWeakRefs(self);
666
Tim Peters6d6c1a32001-08-02 04:15:00 +0000667 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000668 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000669 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000670
671 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000672 assert(basedealloc);
673 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674
675 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000676 Py_DECREF(type);
677
Guido van Rossum0906e072002-08-07 20:42:09 +0000678 endlabel:
Guido van Rossum22b13872002-08-06 21:41:44 +0000679 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000680}
681
Jeremy Hylton938ace62002-07-17 16:30:39 +0000682static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000683
Tim Peters6d6c1a32001-08-02 04:15:00 +0000684/* type test with subclassing support */
685
686int
687PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
688{
689 PyObject *mro;
690
Guido van Rossum9478d072001-09-07 18:52:13 +0000691 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
692 return b == a || b == &PyBaseObject_Type;
693
Tim Peters6d6c1a32001-08-02 04:15:00 +0000694 mro = a->tp_mro;
695 if (mro != NULL) {
696 /* Deal with multiple inheritance without recursion
697 by walking the MRO tuple */
698 int i, n;
699 assert(PyTuple_Check(mro));
700 n = PyTuple_GET_SIZE(mro);
701 for (i = 0; i < n; i++) {
702 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
703 return 1;
704 }
705 return 0;
706 }
707 else {
708 /* a is not completely initilized yet; follow tp_base */
709 do {
710 if (a == b)
711 return 1;
712 a = a->tp_base;
713 } while (a != NULL);
714 return b == &PyBaseObject_Type;
715 }
716}
717
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000718/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000719 without looking in the instance dictionary
720 (so we can't use PyObject_GetAttr) but still binding
721 it to the instance. The arguments are the object,
722 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000723 static variable used to cache the interned Python string.
724
725 Two variants:
726
727 - lookup_maybe() returns NULL without raising an exception
728 when the _PyType_Lookup() call fails;
729
730 - lookup_method() always raises an exception upon errors.
731*/
Guido van Rossum60718732001-08-28 17:47:51 +0000732
733static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000734lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000735{
736 PyObject *res;
737
738 if (*attrobj == NULL) {
739 *attrobj = PyString_InternFromString(attrstr);
740 if (*attrobj == NULL)
741 return NULL;
742 }
743 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000744 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000745 descrgetfunc f;
746 if ((f = res->ob_type->tp_descr_get) == NULL)
747 Py_INCREF(res);
748 else
749 res = f(res, self, (PyObject *)(self->ob_type));
750 }
751 return res;
752}
753
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000754static PyObject *
755lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
756{
757 PyObject *res = lookup_maybe(self, attrstr, attrobj);
758 if (res == NULL && !PyErr_Occurred())
759 PyErr_SetObject(PyExc_AttributeError, *attrobj);
760 return res;
761}
762
Guido van Rossum2730b132001-08-28 18:22:14 +0000763/* A variation of PyObject_CallMethod that uses lookup_method()
764 instead of PyObject_GetAttrString(). This uses the same convention
765 as lookup_method to cache the interned name string object. */
766
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000767static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000768call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
769{
770 va_list va;
771 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000772 va_start(va, format);
773
Guido van Rossumda21c012001-10-03 00:50:18 +0000774 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000775 if (func == NULL) {
776 va_end(va);
777 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000778 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000779 return NULL;
780 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000781
782 if (format && *format)
783 args = Py_VaBuildValue(format, va);
784 else
785 args = PyTuple_New(0);
786
787 va_end(va);
788
789 if (args == NULL)
790 return NULL;
791
792 assert(PyTuple_Check(args));
793 retval = PyObject_Call(func, args, NULL);
794
795 Py_DECREF(args);
796 Py_DECREF(func);
797
798 return retval;
799}
800
801/* Clone of call_method() that returns NotImplemented when the lookup fails. */
802
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000803static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000804call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
805{
806 va_list va;
807 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000808 va_start(va, format);
809
Guido van Rossumda21c012001-10-03 00:50:18 +0000810 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000811 if (func == NULL) {
812 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000813 if (!PyErr_Occurred()) {
814 Py_INCREF(Py_NotImplemented);
815 return Py_NotImplemented;
816 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000817 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000818 }
819
820 if (format && *format)
821 args = Py_VaBuildValue(format, va);
822 else
823 args = PyTuple_New(0);
824
825 va_end(va);
826
Guido van Rossum717ce002001-09-14 16:58:08 +0000827 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000828 return NULL;
829
Guido van Rossum717ce002001-09-14 16:58:08 +0000830 assert(PyTuple_Check(args));
831 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000832
833 Py_DECREF(args);
834 Py_DECREF(func);
835
836 return retval;
837}
838
Tim Petersa91e9642001-11-14 23:32:33 +0000839static int
840fill_classic_mro(PyObject *mro, PyObject *cls)
841{
842 PyObject *bases, *base;
843 int i, n;
844
845 assert(PyList_Check(mro));
846 assert(PyClass_Check(cls));
847 i = PySequence_Contains(mro, cls);
848 if (i < 0)
849 return -1;
850 if (!i) {
851 if (PyList_Append(mro, cls) < 0)
852 return -1;
853 }
854 bases = ((PyClassObject *)cls)->cl_bases;
855 assert(bases && PyTuple_Check(bases));
856 n = PyTuple_GET_SIZE(bases);
857 for (i = 0; i < n; i++) {
858 base = PyTuple_GET_ITEM(bases, i);
859 if (fill_classic_mro(mro, base) < 0)
860 return -1;
861 }
862 return 0;
863}
864
865static PyObject *
866classic_mro(PyObject *cls)
867{
868 PyObject *mro;
869
870 assert(PyClass_Check(cls));
871 mro = PyList_New(0);
872 if (mro != NULL) {
873 if (fill_classic_mro(mro, cls) == 0)
874 return mro;
875 Py_DECREF(mro);
876 }
877 return NULL;
878}
879
Guido van Rossum1f121312002-11-14 19:49:16 +0000880/*
881 Method resolution order algorithm C3 described in
882 "A Monotonic Superclass Linearization for Dylan",
883 by Kim Barrett, Bob Cassel, Paul Haahr,
884 David A. Moon, Keith Playford, and P. Tucker Withington.
885 (OOPSLA 1996)
886
Guido van Rossum98f33732002-11-25 21:36:54 +0000887 Some notes about the rules implied by C3:
888
889 No duplicate bases.
890 It isn't legal to repeat a class in a list of base classes.
891
892 The next three properties are the 3 constraints in "C3".
893
894 Local precendece order.
895 If A precedes B in C's MRO, then A will precede B in the MRO of all
896 subclasses of C.
897
898 Monotonicity.
899 The MRO of a class must be an extension without reordering of the
900 MRO of each of its superclasses.
901
902 Extended Precedence Graph (EPG).
903 Linearization is consistent if there is a path in the EPG from
904 each class to all its successors in the linearization. See
905 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000906 */
907
908static int
909tail_contains(PyObject *list, int whence, PyObject *o) {
910 int j, size;
911 size = PyList_GET_SIZE(list);
912
913 for (j = whence+1; j < size; j++) {
914 if (PyList_GET_ITEM(list, j) == o)
915 return 1;
916 }
917 return 0;
918}
919
Guido van Rossum98f33732002-11-25 21:36:54 +0000920static PyObject *
921class_name(PyObject *cls)
922{
923 PyObject *name = PyObject_GetAttrString(cls, "__name__");
924 if (name == NULL) {
925 PyErr_Clear();
926 Py_XDECREF(name);
927 name = PyObject_Repr(cls);
928 }
929 if (name == NULL)
930 return NULL;
931 if (!PyString_Check(name)) {
932 Py_DECREF(name);
933 return NULL;
934 }
935 return name;
936}
937
938static int
939check_duplicates(PyObject *list)
940{
941 int i, j, n;
942 /* Let's use a quadratic time algorithm,
943 assuming that the bases lists is short.
944 */
945 n = PyList_GET_SIZE(list);
946 for (i = 0; i < n; i++) {
947 PyObject *o = PyList_GET_ITEM(list, i);
948 for (j = i + 1; j < n; j++) {
949 if (PyList_GET_ITEM(list, j) == o) {
950 o = class_name(o);
951 PyErr_Format(PyExc_TypeError,
952 "duplicate base class %s",
953 o ? PyString_AS_STRING(o) : "?");
954 Py_XDECREF(o);
955 return -1;
956 }
957 }
958 }
959 return 0;
960}
961
962/* Raise a TypeError for an MRO order disagreement.
963
964 It's hard to produce a good error message. In the absence of better
965 insight into error reporting, report the classes that were candidates
966 to be put next into the MRO. There is some conflict between the
967 order in which they should be put in the MRO, but it's hard to
968 diagnose what constraint can't be satisfied.
969*/
970
971static void
972set_mro_error(PyObject *to_merge, int *remain)
973{
974 int i, n, off, to_merge_size;
975 char buf[1000];
976 PyObject *k, *v;
977 PyObject *set = PyDict_New();
978
979 to_merge_size = PyList_GET_SIZE(to_merge);
980 for (i = 0; i < to_merge_size; i++) {
981 PyObject *L = PyList_GET_ITEM(to_merge, i);
982 if (remain[i] < PyList_GET_SIZE(L)) {
983 PyObject *c = PyList_GET_ITEM(L, remain[i]);
984 if (PyDict_SetItem(set, c, Py_None) < 0)
985 return;
986 }
987 }
988 n = PyDict_Size(set);
989
990 off = PyOS_snprintf(buf, sizeof(buf), "MRO conflict among bases");
991 i = 0;
992 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
993 PyObject *name = class_name(k);
994 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
995 name ? PyString_AS_STRING(name) : "?");
996 Py_XDECREF(name);
997 if (--n && off+1 < sizeof(buf)) {
998 buf[off++] = ',';
999 buf[off] = '\0';
1000 }
1001 }
1002 PyErr_SetString(PyExc_TypeError, buf);
1003 Py_DECREF(set);
1004}
1005
Guido van Rossum1f121312002-11-14 19:49:16 +00001006static int
1007pmerge(PyObject *acc, PyObject* to_merge) {
1008 int i, j, to_merge_size;
1009 int *remain;
1010 int ok, empty_cnt;
1011
1012 to_merge_size = PyList_GET_SIZE(to_merge);
1013
Guido van Rossum98f33732002-11-25 21:36:54 +00001014 /* remain stores an index into each sublist of to_merge.
1015 remain[i] is the index of the next base in to_merge[i]
1016 that is not included in acc.
1017 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001018 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1019 if (remain == NULL)
1020 return -1;
1021 for (i = 0; i < to_merge_size; i++)
1022 remain[i] = 0;
1023
1024 again:
1025 empty_cnt = 0;
1026 for (i = 0; i < to_merge_size; i++) {
1027 PyObject *candidate;
1028
1029 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1030
1031 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1032 empty_cnt++;
1033 continue;
1034 }
1035
Guido van Rossum98f33732002-11-25 21:36:54 +00001036 /* Choose next candidate for MRO.
1037
1038 The input sequences alone can determine the choice.
1039 If not, choose the class which appears in the MRO
1040 of the earliest direct superclass of the new class.
1041 */
1042
Guido van Rossum1f121312002-11-14 19:49:16 +00001043 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1044 for (j = 0; j < to_merge_size; j++) {
1045 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001046 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001047 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001048 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001049 }
1050 ok = PyList_Append(acc, candidate);
1051 if (ok < 0) {
1052 PyMem_Free(remain);
1053 return -1;
1054 }
1055 for (j = 0; j < to_merge_size; j++) {
1056 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1057 if (PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1058 remain[j]++;
1059 }
1060 }
1061 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001062 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001063 }
1064
Guido van Rossum98f33732002-11-25 21:36:54 +00001065 if (empty_cnt == to_merge_size) {
1066 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001067 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001068 }
1069 set_mro_error(to_merge, remain);
1070 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001071 return -1;
1072}
1073
Tim Peters6d6c1a32001-08-02 04:15:00 +00001074static PyObject *
1075mro_implementation(PyTypeObject *type)
1076{
1077 int i, n, ok;
1078 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001079 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001080
Guido van Rossum63517572002-06-18 16:44:57 +00001081 if(type->tp_dict == NULL) {
1082 if(PyType_Ready(type) < 0)
1083 return NULL;
1084 }
1085
Guido van Rossum98f33732002-11-25 21:36:54 +00001086 /* Find a superclass linearization that honors the constraints
1087 of the explicit lists of bases and the constraints implied by
1088 each base class.
1089
1090 to_merge is a list of lists, where each list is a superclass
1091 linearization implied by a base class. The last element of
1092 to_merge is the declared list of bases.
1093 */
1094
Tim Peters6d6c1a32001-08-02 04:15:00 +00001095 bases = type->tp_bases;
1096 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001097
1098 to_merge = PyList_New(n+1);
1099 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001100 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001101
Tim Peters6d6c1a32001-08-02 04:15:00 +00001102 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001103 PyObject *base = PyTuple_GET_ITEM(bases, i);
1104 PyObject *parentMRO;
1105 if (PyType_Check(base))
1106 parentMRO = PySequence_List(
1107 ((PyTypeObject*)base)->tp_mro);
1108 else
1109 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001110 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001111 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001113 }
1114
1115 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001116 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001117
1118 bases_aslist = PySequence_List(bases);
1119 if (bases_aslist == NULL) {
1120 Py_DECREF(to_merge);
1121 return NULL;
1122 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001123 /* This is just a basic sanity check. */
1124 if (check_duplicates(bases_aslist) < 0) {
1125 Py_DECREF(to_merge);
1126 Py_DECREF(bases_aslist);
1127 return NULL;
1128 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001129 PyList_SET_ITEM(to_merge, n, bases_aslist);
1130
1131 result = Py_BuildValue("[O]", (PyObject *)type);
1132 if (result == NULL) {
1133 Py_DECREF(to_merge);
1134 return NULL;
1135 }
1136
1137 ok = pmerge(result, to_merge);
1138 Py_DECREF(to_merge);
1139 if (ok < 0) {
1140 Py_DECREF(result);
1141 return NULL;
1142 }
1143
Tim Peters6d6c1a32001-08-02 04:15:00 +00001144 return result;
1145}
1146
1147static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001148mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001149{
1150 PyTypeObject *type = (PyTypeObject *)self;
1151
Tim Peters6d6c1a32001-08-02 04:15:00 +00001152 return mro_implementation(type);
1153}
1154
1155static int
1156mro_internal(PyTypeObject *type)
1157{
1158 PyObject *mro, *result, *tuple;
1159
1160 if (type->ob_type == &PyType_Type) {
1161 result = mro_implementation(type);
1162 }
1163 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001164 static PyObject *mro_str;
1165 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001166 if (mro == NULL)
1167 return -1;
1168 result = PyObject_CallObject(mro, NULL);
1169 Py_DECREF(mro);
1170 }
1171 if (result == NULL)
1172 return -1;
1173 tuple = PySequence_Tuple(result);
1174 Py_DECREF(result);
1175 type->tp_mro = tuple;
1176 return 0;
1177}
1178
1179
1180/* Calculate the best base amongst multiple base classes.
1181 This is the first one that's on the path to the "solid base". */
1182
1183static PyTypeObject *
1184best_base(PyObject *bases)
1185{
1186 int i, n;
1187 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001188 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189
1190 assert(PyTuple_Check(bases));
1191 n = PyTuple_GET_SIZE(bases);
1192 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001193 base = NULL;
1194 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001196 base_proto = PyTuple_GET_ITEM(bases, i);
1197 if (PyClass_Check(base_proto))
1198 continue;
1199 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001200 PyErr_SetString(
1201 PyExc_TypeError,
1202 "bases must be types");
1203 return NULL;
1204 }
Tim Petersa91e9642001-11-14 23:32:33 +00001205 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001206 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001207 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001208 return NULL;
1209 }
1210 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001211 if (winner == NULL) {
1212 winner = candidate;
1213 base = base_i;
1214 }
1215 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 ;
1217 else if (PyType_IsSubtype(candidate, winner)) {
1218 winner = candidate;
1219 base = base_i;
1220 }
1221 else {
1222 PyErr_SetString(
1223 PyExc_TypeError,
1224 "multiple bases have "
1225 "instance lay-out conflict");
1226 return NULL;
1227 }
1228 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001229 if (base == NULL)
1230 PyErr_SetString(PyExc_TypeError,
1231 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232 return base;
1233}
1234
1235static int
1236extra_ivars(PyTypeObject *type, PyTypeObject *base)
1237{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001238 size_t t_size = type->tp_basicsize;
1239 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001240
Guido van Rossum9676b222001-08-17 20:32:36 +00001241 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242 if (type->tp_itemsize || base->tp_itemsize) {
1243 /* If itemsize is involved, stricter rules */
1244 return t_size != b_size ||
1245 type->tp_itemsize != base->tp_itemsize;
1246 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001247 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1248 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1249 t_size -= sizeof(PyObject *);
1250 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1251 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1252 t_size -= sizeof(PyObject *);
1253
1254 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255}
1256
1257static PyTypeObject *
1258solid_base(PyTypeObject *type)
1259{
1260 PyTypeObject *base;
1261
1262 if (type->tp_base)
1263 base = solid_base(type->tp_base);
1264 else
1265 base = &PyBaseObject_Type;
1266 if (extra_ivars(type, base))
1267 return type;
1268 else
1269 return base;
1270}
1271
Jeremy Hylton938ace62002-07-17 16:30:39 +00001272static void object_dealloc(PyObject *);
1273static int object_init(PyObject *, PyObject *, PyObject *);
1274static int update_slot(PyTypeObject *, PyObject *);
1275static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001276
1277static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001278subtype_dict(PyObject *obj, void *context)
1279{
1280 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1281 PyObject *dict;
1282
1283 if (dictptr == NULL) {
1284 PyErr_SetString(PyExc_AttributeError,
1285 "This object has no __dict__");
1286 return NULL;
1287 }
1288 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001289 if (dict == NULL)
1290 *dictptr = dict = PyDict_New();
1291 Py_XINCREF(dict);
1292 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001293}
1294
Guido van Rossum6661be32001-10-26 04:26:12 +00001295static int
1296subtype_setdict(PyObject *obj, PyObject *value, void *context)
1297{
1298 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1299 PyObject *dict;
1300
1301 if (dictptr == NULL) {
1302 PyErr_SetString(PyExc_AttributeError,
1303 "This object has no __dict__");
1304 return -1;
1305 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001306 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001307 PyErr_SetString(PyExc_TypeError,
1308 "__dict__ must be set to a dictionary");
1309 return -1;
1310 }
1311 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001312 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001313 *dictptr = value;
1314 Py_XDECREF(dict);
1315 return 0;
1316}
1317
Guido van Rossumad47da02002-08-12 19:05:44 +00001318static PyObject *
1319subtype_getweakref(PyObject *obj, void *context)
1320{
1321 PyObject **weaklistptr;
1322 PyObject *result;
1323
1324 if (obj->ob_type->tp_weaklistoffset == 0) {
1325 PyErr_SetString(PyExc_AttributeError,
1326 "This object has no __weaklist__");
1327 return NULL;
1328 }
1329 assert(obj->ob_type->tp_weaklistoffset > 0);
1330 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001331 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001332 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001333 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001334 if (*weaklistptr == NULL)
1335 result = Py_None;
1336 else
1337 result = *weaklistptr;
1338 Py_INCREF(result);
1339 return result;
1340}
1341
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001342static PyGetSetDef subtype_getsets[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001343 /* Not all objects have these attributes!
1344 The descriptor's __get__ method may raise AttributeError. */
1345 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001346 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001347 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001348 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001349 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001350};
1351
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001352/* bozo: __getstate__ that raises TypeError */
1353
1354static PyObject *
1355bozo_func(PyObject *self, PyObject *args)
1356{
1357 PyErr_SetString(PyExc_TypeError,
1358 "a class that defines __slots__ without "
1359 "defining __getstate__ cannot be pickled");
1360 return NULL;
1361}
1362
Neal Norwitz93c1e232002-03-31 16:06:11 +00001363static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001364
1365static PyObject *bozo_obj = NULL;
1366
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001367static int
1368valid_identifier(PyObject *s)
1369{
Guido van Rossum03013a02002-07-16 14:30:28 +00001370 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001371 int i, n;
1372
1373 if (!PyString_Check(s)) {
1374 PyErr_SetString(PyExc_TypeError,
1375 "__slots__ must be strings");
1376 return 0;
1377 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001378 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001379 n = PyString_GET_SIZE(s);
1380 /* We must reject an empty name. As a hack, we bump the
1381 length to 1 so that the loop will balk on the trailing \0. */
1382 if (n == 0)
1383 n = 1;
1384 for (i = 0; i < n; i++, p++) {
1385 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1386 PyErr_SetString(PyExc_TypeError,
1387 "__slots__ must be identifiers");
1388 return 0;
1389 }
1390 }
1391 return 1;
1392}
1393
Martin v. Löwisd919a592002-10-14 21:07:28 +00001394#ifdef Py_USING_UNICODE
1395/* Replace Unicode objects in slots. */
1396
1397static PyObject *
1398_unicode_to_string(PyObject *slots, int nslots)
1399{
1400 PyObject *tmp = slots;
1401 PyObject *o, *o1;
1402 int i;
1403 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1404 for (i = 0; i < nslots; i++) {
1405 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1406 if (tmp == slots) {
1407 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1408 if (tmp == NULL)
1409 return NULL;
1410 }
1411 o1 = _PyUnicode_AsDefaultEncodedString
1412 (o, NULL);
1413 if (o1 == NULL) {
1414 Py_DECREF(tmp);
1415 return 0;
1416 }
1417 Py_INCREF(o1);
1418 Py_DECREF(o);
1419 PyTuple_SET_ITEM(tmp, i, o1);
1420 }
1421 }
1422 return tmp;
1423}
1424#endif
1425
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001426static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001427type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1428{
1429 PyObject *name, *bases, *dict;
1430 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001431 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001432 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001433 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001434 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001435 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001436 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001437
Tim Peters3abca122001-10-27 19:37:48 +00001438 assert(args != NULL && PyTuple_Check(args));
1439 assert(kwds == NULL || PyDict_Check(kwds));
1440
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001441 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001442 {
1443 const int nargs = PyTuple_GET_SIZE(args);
1444 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1445
1446 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1447 PyObject *x = PyTuple_GET_ITEM(args, 0);
1448 Py_INCREF(x->ob_type);
1449 return (PyObject *) x->ob_type;
1450 }
1451
1452 /* SF bug 475327 -- if that didn't trigger, we need 3
1453 arguments. but PyArg_ParseTupleAndKeywords below may give
1454 a msg saying type() needs exactly 3. */
1455 if (nargs + nkwds != 3) {
1456 PyErr_SetString(PyExc_TypeError,
1457 "type() takes 1 or 3 arguments");
1458 return NULL;
1459 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001460 }
1461
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001462 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1464 &name,
1465 &PyTuple_Type, &bases,
1466 &PyDict_Type, &dict))
1467 return NULL;
1468
1469 /* Determine the proper metatype to deal with this,
1470 and check for metatype conflicts while we're at it.
1471 Note that if some other metatype wins to contract,
1472 it's possible that its instances are not types. */
1473 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001474 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001475 for (i = 0; i < nbases; i++) {
1476 tmp = PyTuple_GET_ITEM(bases, i);
1477 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001478 if (tmptype == &PyClass_Type)
1479 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001480 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001481 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001482 if (PyType_IsSubtype(tmptype, winner)) {
1483 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484 continue;
1485 }
1486 PyErr_SetString(PyExc_TypeError,
1487 "metatype conflict among bases");
1488 return NULL;
1489 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001490 if (winner != metatype) {
1491 if (winner->tp_new != type_new) /* Pass it to the winner */
1492 return winner->tp_new(winner, args, kwds);
1493 metatype = winner;
1494 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001495
1496 /* Adjust for empty tuple bases */
1497 if (nbases == 0) {
1498 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1499 if (bases == NULL)
1500 return NULL;
1501 nbases = 1;
1502 }
1503 else
1504 Py_INCREF(bases);
1505
1506 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1507
1508 /* Calculate best base, and check that all bases are type objects */
1509 base = best_base(bases);
1510 if (base == NULL)
1511 return NULL;
1512 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1513 PyErr_Format(PyExc_TypeError,
1514 "type '%.100s' is not an acceptable base type",
1515 base->tp_name);
1516 return NULL;
1517 }
1518
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519 /* Check for a __slots__ sequence variable in dict, and count it */
1520 slots = PyDict_GetItemString(dict, "__slots__");
1521 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001522 add_dict = 0;
1523 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001524 may_add_dict = base->tp_dictoffset == 0;
1525 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1526 if (slots == NULL) {
1527 if (may_add_dict) {
1528 add_dict++;
1529 }
1530 if (may_add_weak) {
1531 add_weak++;
1532 }
1533 }
1534 else {
1535 /* Have slots */
1536
Tim Peters6d6c1a32001-08-02 04:15:00 +00001537 /* Make it into a tuple */
1538 if (PyString_Check(slots))
1539 slots = Py_BuildValue("(O)", slots);
1540 else
1541 slots = PySequence_Tuple(slots);
1542 if (slots == NULL)
1543 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001544 assert(PyTuple_Check(slots));
1545
1546 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001547 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001548 if (nslots > 0 && base->tp_itemsize != 0) {
1549 PyErr_Format(PyExc_TypeError,
1550 "nonempty __slots__ "
1551 "not supported for subtype of '%s'",
1552 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001553 bad_slots:
1554 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001555 return NULL;
1556 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001557
Martin v. Löwisd919a592002-10-14 21:07:28 +00001558#ifdef Py_USING_UNICODE
1559 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001560 if (tmp != slots) {
1561 Py_DECREF(slots);
1562 slots = tmp;
1563 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001564 if (!tmp)
1565 return NULL;
1566#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001567 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001568 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001569 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1570 char *s;
1571 if (!valid_identifier(tmp))
1572 goto bad_slots;
1573 assert(PyString_Check(tmp));
1574 s = PyString_AS_STRING(tmp);
1575 if (strcmp(s, "__dict__") == 0) {
1576 if (!may_add_dict || add_dict) {
1577 PyErr_SetString(PyExc_TypeError,
1578 "__dict__ slot disallowed: "
1579 "we already got one");
1580 goto bad_slots;
1581 }
1582 add_dict++;
1583 }
1584 if (strcmp(s, "__weakref__") == 0) {
1585 if (!may_add_weak || add_weak) {
1586 PyErr_SetString(PyExc_TypeError,
1587 "__weakref__ slot disallowed: "
1588 "either we already got one, "
1589 "or __itemsize__ != 0");
1590 goto bad_slots;
1591 }
1592 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001593 }
1594 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001595
Guido van Rossumad47da02002-08-12 19:05:44 +00001596 /* Copy slots into yet another tuple, demangling names */
1597 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001598 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001599 goto bad_slots;
1600 for (i = j = 0; i < nslots; i++) {
1601 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001602 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001603 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001604 s = PyString_AS_STRING(tmp);
1605 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1606 (add_weak && strcmp(s, "__weakref__") == 0))
1607 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001608 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001609 PyString_AS_STRING(tmp),
1610 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001611 {
1612 tmp = PyString_FromString(buffer);
1613 } else {
1614 Py_INCREF(tmp);
1615 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001616 PyTuple_SET_ITEM(newslots, j, tmp);
1617 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001618 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001619 assert(j == nslots - add_dict - add_weak);
1620 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001621 Py_DECREF(slots);
1622 slots = newslots;
1623
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001624 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001625 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001626 /* If not, provide a bozo that raises TypeError */
1627 if (bozo_obj == NULL) {
1628 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001629 if (bozo_obj == NULL)
1630 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001631 }
1632 if (PyDict_SetItemString(dict,
1633 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001634 bozo_obj) < 0)
1635 {
1636 Py_DECREF(bozo_obj);
1637 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001638 }
1639 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001640
1641 /* Secondary bases may provide weakrefs or dict */
1642 if (nbases > 1 &&
1643 ((may_add_dict && !add_dict) ||
1644 (may_add_weak && !add_weak))) {
1645 for (i = 0; i < nbases; i++) {
1646 tmp = PyTuple_GET_ITEM(bases, i);
1647 if (tmp == (PyObject *)base)
1648 continue; /* Skip primary base */
1649 if (PyClass_Check(tmp)) {
1650 /* Classic base class provides both */
1651 if (may_add_dict && !add_dict)
1652 add_dict++;
1653 if (may_add_weak && !add_weak)
1654 add_weak++;
1655 break;
1656 }
1657 assert(PyType_Check(tmp));
1658 tmptype = (PyTypeObject *)tmp;
1659 if (may_add_dict && !add_dict &&
1660 tmptype->tp_dictoffset != 0)
1661 add_dict++;
1662 if (may_add_weak && !add_weak &&
1663 tmptype->tp_weaklistoffset != 0)
1664 add_weak++;
1665 if (may_add_dict && !add_dict)
1666 continue;
1667 if (may_add_weak && !add_weak)
1668 continue;
1669 /* Nothing more to check */
1670 break;
1671 }
1672 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001673 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674
1675 /* XXX From here until type is safely allocated,
1676 "return NULL" may leak slots! */
1677
1678 /* Allocate the type object */
1679 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001680 if (type == NULL) {
1681 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001682 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001683 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684
1685 /* Keep name and slots alive in the extended type object */
1686 et = (etype *)type;
1687 Py_INCREF(name);
1688 et->name = name;
1689 et->slots = slots;
1690
Guido van Rossumdc91b992001-08-08 22:26:22 +00001691 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001692 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1693 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001694 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1695 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001696
1697 /* It's a new-style number unless it specifically inherits any
1698 old-style numeric behavior */
1699 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1700 (base->tp_as_number == NULL))
1701 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1702
1703 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001704 type->tp_as_number = &et->as_number;
1705 type->tp_as_sequence = &et->as_sequence;
1706 type->tp_as_mapping = &et->as_mapping;
1707 type->tp_as_buffer = &et->as_buffer;
1708 type->tp_name = PyString_AS_STRING(name);
1709
1710 /* Set tp_base and tp_bases */
1711 type->tp_bases = bases;
1712 Py_INCREF(base);
1713 type->tp_base = base;
1714
Guido van Rossum687ae002001-10-15 22:03:32 +00001715 /* Initialize tp_dict from passed-in dict */
1716 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717 if (dict == NULL) {
1718 Py_DECREF(type);
1719 return NULL;
1720 }
1721
Guido van Rossumc3542212001-08-16 09:18:56 +00001722 /* Set __module__ in the dict */
1723 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1724 tmp = PyEval_GetGlobals();
1725 if (tmp != NULL) {
1726 tmp = PyDict_GetItemString(tmp, "__name__");
1727 if (tmp != NULL) {
1728 if (PyDict_SetItemString(dict, "__module__",
1729 tmp) < 0)
1730 return NULL;
1731 }
1732 }
1733 }
1734
Tim Peters2f93e282001-10-04 05:27:00 +00001735 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001736 and is a string. The __doc__ accessor will first look for tp_doc;
1737 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001738 */
1739 {
1740 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1741 if (doc != NULL && PyString_Check(doc)) {
1742 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001743 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001744 if (type->tp_doc == NULL) {
1745 Py_DECREF(type);
1746 return NULL;
1747 }
1748 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1749 }
1750 }
1751
Tim Peters6d6c1a32001-08-02 04:15:00 +00001752 /* Special-case __new__: if it's a plain function,
1753 make it a static function */
1754 tmp = PyDict_GetItemString(dict, "__new__");
1755 if (tmp != NULL && PyFunction_Check(tmp)) {
1756 tmp = PyStaticMethod_New(tmp);
1757 if (tmp == NULL) {
1758 Py_DECREF(type);
1759 return NULL;
1760 }
1761 PyDict_SetItemString(dict, "__new__", tmp);
1762 Py_DECREF(tmp);
1763 }
1764
1765 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1766 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001767 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768 if (slots != NULL) {
1769 for (i = 0; i < nslots; i++, mp++) {
1770 mp->name = PyString_AS_STRING(
1771 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001772 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001773 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001774 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001775 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001776 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001777 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001778 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001779 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001780 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001781 slotoffset += sizeof(PyObject *);
1782 }
1783 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001784 if (add_dict) {
1785 if (base->tp_itemsize)
1786 type->tp_dictoffset = -(long)sizeof(PyObject *);
1787 else
1788 type->tp_dictoffset = slotoffset;
1789 slotoffset += sizeof(PyObject *);
1790 }
1791 if (add_weak) {
1792 assert(!base->tp_itemsize);
1793 type->tp_weaklistoffset = slotoffset;
1794 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795 }
1796 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001797 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001798 type->tp_members = et->members;
Guido van Rossumad47da02002-08-12 19:05:44 +00001799 type->tp_getset = subtype_getsets;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001800
1801 /* Special case some slots */
1802 if (type->tp_dictoffset != 0 || nslots > 0) {
1803 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1804 type->tp_getattro = PyObject_GenericGetAttr;
1805 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1806 type->tp_setattro = PyObject_GenericSetAttr;
1807 }
1808 type->tp_dealloc = subtype_dealloc;
1809
Guido van Rossum9475a232001-10-05 20:51:39 +00001810 /* Enable GC unless there are really no instance variables possible */
1811 if (!(type->tp_basicsize == sizeof(PyObject) &&
1812 type->tp_itemsize == 0))
1813 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1814
Tim Peters6d6c1a32001-08-02 04:15:00 +00001815 /* Always override allocation strategy to use regular heap */
1816 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001817 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001818 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001819 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001820 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001821 }
1822 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001823 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001824
1825 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001826 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001827 Py_DECREF(type);
1828 return NULL;
1829 }
1830
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001831 /* Put the proper slots in place */
1832 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001833
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834 return (PyObject *)type;
1835}
1836
1837/* Internal API to look for a name through the MRO.
1838 This returns a borrowed reference, and doesn't set an exception! */
1839PyObject *
1840_PyType_Lookup(PyTypeObject *type, PyObject *name)
1841{
1842 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001843 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844
Guido van Rossum687ae002001-10-15 22:03:32 +00001845 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001846 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001847
1848 /* If mro is NULL, the type is either not yet initialized
1849 by PyType_Ready(), or already cleared by type_clear().
1850 Either way the safest thing to do is to return NULL. */
1851 if (mro == NULL)
1852 return NULL;
1853
Tim Peters6d6c1a32001-08-02 04:15:00 +00001854 assert(PyTuple_Check(mro));
1855 n = PyTuple_GET_SIZE(mro);
1856 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001857 base = PyTuple_GET_ITEM(mro, i);
1858 if (PyClass_Check(base))
1859 dict = ((PyClassObject *)base)->cl_dict;
1860 else {
1861 assert(PyType_Check(base));
1862 dict = ((PyTypeObject *)base)->tp_dict;
1863 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001864 assert(dict && PyDict_Check(dict));
1865 res = PyDict_GetItem(dict, name);
1866 if (res != NULL)
1867 return res;
1868 }
1869 return NULL;
1870}
1871
1872/* This is similar to PyObject_GenericGetAttr(),
1873 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1874static PyObject *
1875type_getattro(PyTypeObject *type, PyObject *name)
1876{
1877 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001878 PyObject *meta_attribute, *attribute;
1879 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001880
1881 /* Initialize this type (we'll assume the metatype is initialized) */
1882 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001883 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001884 return NULL;
1885 }
1886
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001887 /* No readable descriptor found yet */
1888 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001889
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001890 /* Look for the attribute in the metatype */
1891 meta_attribute = _PyType_Lookup(metatype, name);
1892
1893 if (meta_attribute != NULL) {
1894 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001895
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001896 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1897 /* Data descriptors implement tp_descr_set to intercept
1898 * writes. Assume the attribute is not overridden in
1899 * type's tp_dict (and bases): call the descriptor now.
1900 */
1901 return meta_get(meta_attribute, (PyObject *)type,
1902 (PyObject *)metatype);
1903 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001904 }
1905
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001906 /* No data descriptor found on metatype. Look in tp_dict of this
1907 * type and its bases */
1908 attribute = _PyType_Lookup(type, name);
1909 if (attribute != NULL) {
1910 /* Implement descriptor functionality, if any */
1911 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1912 if (local_get != NULL) {
1913 /* NULL 2nd argument indicates the descriptor was
1914 * found on the target object itself (or a base) */
1915 return local_get(attribute, (PyObject *)NULL,
1916 (PyObject *)type);
1917 }
Tim Peters34592512002-07-11 06:23:50 +00001918
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001919 Py_INCREF(attribute);
1920 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001921 }
1922
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001923 /* No attribute found in local __dict__ (or bases): use the
1924 * descriptor from the metatype, if any */
1925 if (meta_get != NULL)
1926 return meta_get(meta_attribute, (PyObject *)type,
1927 (PyObject *)metatype);
1928
1929 /* If an ordinary attribute was found on the metatype, return it now */
1930 if (meta_attribute != NULL) {
1931 Py_INCREF(meta_attribute);
1932 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001933 }
1934
1935 /* Give up */
1936 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001937 "type object '%.50s' has no attribute '%.400s'",
1938 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001939 return NULL;
1940}
1941
1942static int
1943type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1944{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001945 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1946 PyErr_Format(
1947 PyExc_TypeError,
1948 "can't set attributes of built-in/extension type '%s'",
1949 type->tp_name);
1950 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001951 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001952 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1953 return -1;
1954 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001955}
1956
1957static void
1958type_dealloc(PyTypeObject *type)
1959{
1960 etype *et;
1961
1962 /* Assert this is a heap-allocated type object */
1963 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001964 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001965 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001966 et = (etype *)type;
1967 Py_XDECREF(type->tp_base);
1968 Py_XDECREF(type->tp_dict);
1969 Py_XDECREF(type->tp_bases);
1970 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001971 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001972 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001973 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001974 Py_XDECREF(et->name);
1975 Py_XDECREF(et->slots);
1976 type->ob_type->tp_free((PyObject *)type);
1977}
1978
Guido van Rossum1c450732001-10-08 15:18:27 +00001979static PyObject *
1980type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1981{
1982 PyObject *list, *raw, *ref;
1983 int i, n;
1984
1985 list = PyList_New(0);
1986 if (list == NULL)
1987 return NULL;
1988 raw = type->tp_subclasses;
1989 if (raw == NULL)
1990 return list;
1991 assert(PyList_Check(raw));
1992 n = PyList_GET_SIZE(raw);
1993 for (i = 0; i < n; i++) {
1994 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001995 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001996 ref = PyWeakref_GET_OBJECT(ref);
1997 if (ref != Py_None) {
1998 if (PyList_Append(list, ref) < 0) {
1999 Py_DECREF(list);
2000 return NULL;
2001 }
2002 }
2003 }
2004 return list;
2005}
2006
Tim Peters6d6c1a32001-08-02 04:15:00 +00002007static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002008 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002009 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002010 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002011 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012 {0}
2013};
2014
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002015PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002017"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002018
Guido van Rossum048eb752001-10-02 21:24:57 +00002019static int
2020type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2021{
Guido van Rossum048eb752001-10-02 21:24:57 +00002022 int err;
2023
Guido van Rossuma3862092002-06-10 15:24:42 +00002024 /* Because of type_is_gc(), the collector only calls this
2025 for heaptypes. */
2026 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002027
2028#define VISIT(SLOT) \
2029 if (SLOT) { \
2030 err = visit((PyObject *)(SLOT), arg); \
2031 if (err) \
2032 return err; \
2033 }
2034
2035 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002036 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002037 VISIT(type->tp_mro);
2038 VISIT(type->tp_bases);
2039 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002040
2041 /* There's no need to visit type->tp_subclasses or
2042 ((etype *)type)->slots, because they can't be involved
2043 in cycles; tp_subclasses is a list of weak references,
2044 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002045
2046#undef VISIT
2047
2048 return 0;
2049}
2050
2051static int
2052type_clear(PyTypeObject *type)
2053{
Guido van Rossum048eb752001-10-02 21:24:57 +00002054 PyObject *tmp;
2055
Guido van Rossuma3862092002-06-10 15:24:42 +00002056 /* Because of type_is_gc(), the collector only calls this
2057 for heaptypes. */
2058 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002059
2060#define CLEAR(SLOT) \
2061 if (SLOT) { \
2062 tmp = (PyObject *)(SLOT); \
2063 SLOT = NULL; \
2064 Py_DECREF(tmp); \
2065 }
2066
Guido van Rossuma3862092002-06-10 15:24:42 +00002067 /* The only field we need to clear is tp_mro, which is part of a
2068 hard cycle (its first element is the class itself) that won't
2069 be broken otherwise (it's a tuple and tuples don't have a
2070 tp_clear handler). None of the other fields need to be
2071 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002072
Guido van Rossuma3862092002-06-10 15:24:42 +00002073 tp_dict:
2074 It is a dict, so the collector will call its tp_clear.
2075
2076 tp_cache:
2077 Not used; if it were, it would be a dict.
2078
2079 tp_bases, tp_base:
2080 If these are involved in a cycle, there must be at least
2081 one other, mutable object in the cycle, e.g. a base
2082 class's dict; the cycle will be broken that way.
2083
2084 tp_subclasses:
2085 A list of weak references can't be part of a cycle; and
2086 lists have their own tp_clear.
2087
2088 slots (in etype):
2089 A tuple of strings can't be part of a cycle.
2090 */
2091
2092 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002093
Guido van Rossum048eb752001-10-02 21:24:57 +00002094#undef CLEAR
2095
2096 return 0;
2097}
2098
2099static int
2100type_is_gc(PyTypeObject *type)
2101{
2102 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2103}
2104
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002105PyTypeObject PyType_Type = {
2106 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002107 0, /* ob_size */
2108 "type", /* tp_name */
2109 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002110 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002111 (destructor)type_dealloc, /* tp_dealloc */
2112 0, /* tp_print */
2113 0, /* tp_getattr */
2114 0, /* tp_setattr */
2115 type_compare, /* tp_compare */
2116 (reprfunc)type_repr, /* tp_repr */
2117 0, /* tp_as_number */
2118 0, /* tp_as_sequence */
2119 0, /* tp_as_mapping */
2120 (hashfunc)_Py_HashPointer, /* tp_hash */
2121 (ternaryfunc)type_call, /* tp_call */
2122 0, /* tp_str */
2123 (getattrofunc)type_getattro, /* tp_getattro */
2124 (setattrofunc)type_setattro, /* tp_setattro */
2125 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002126 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2127 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002128 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002129 (traverseproc)type_traverse, /* tp_traverse */
2130 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002131 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002132 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002133 0, /* tp_iter */
2134 0, /* tp_iternext */
2135 type_methods, /* tp_methods */
2136 type_members, /* tp_members */
2137 type_getsets, /* tp_getset */
2138 0, /* tp_base */
2139 0, /* tp_dict */
2140 0, /* tp_descr_get */
2141 0, /* tp_descr_set */
2142 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2143 0, /* tp_init */
2144 0, /* tp_alloc */
2145 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002146 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002147 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002148};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002149
2150
2151/* The base type of all types (eventually)... except itself. */
2152
2153static int
2154object_init(PyObject *self, PyObject *args, PyObject *kwds)
2155{
2156 return 0;
2157}
2158
2159static void
2160object_dealloc(PyObject *self)
2161{
2162 self->ob_type->tp_free(self);
2163}
2164
Guido van Rossum8e248182001-08-12 05:17:56 +00002165static PyObject *
2166object_repr(PyObject *self)
2167{
Guido van Rossum76e69632001-08-16 18:52:43 +00002168 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002169 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002170
Guido van Rossum76e69632001-08-16 18:52:43 +00002171 type = self->ob_type;
2172 mod = type_module(type, NULL);
2173 if (mod == NULL)
2174 PyErr_Clear();
2175 else if (!PyString_Check(mod)) {
2176 Py_DECREF(mod);
2177 mod = NULL;
2178 }
2179 name = type_name(type, NULL);
2180 if (name == NULL)
2181 return NULL;
2182 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002183 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002184 PyString_AS_STRING(mod),
2185 PyString_AS_STRING(name),
2186 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002187 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002188 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002189 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002190 Py_XDECREF(mod);
2191 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002192 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002193}
2194
Guido van Rossumb8f63662001-08-15 23:57:02 +00002195static PyObject *
2196object_str(PyObject *self)
2197{
2198 unaryfunc f;
2199
2200 f = self->ob_type->tp_repr;
2201 if (f == NULL)
2202 f = object_repr;
2203 return f(self);
2204}
2205
Guido van Rossum8e248182001-08-12 05:17:56 +00002206static long
2207object_hash(PyObject *self)
2208{
2209 return _Py_HashPointer(self);
2210}
Guido van Rossum8e248182001-08-12 05:17:56 +00002211
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002212static PyObject *
2213object_get_class(PyObject *self, void *closure)
2214{
2215 Py_INCREF(self->ob_type);
2216 return (PyObject *)(self->ob_type);
2217}
2218
2219static int
2220equiv_structs(PyTypeObject *a, PyTypeObject *b)
2221{
2222 return a == b ||
2223 (a != NULL &&
2224 b != NULL &&
2225 a->tp_basicsize == b->tp_basicsize &&
2226 a->tp_itemsize == b->tp_itemsize &&
2227 a->tp_dictoffset == b->tp_dictoffset &&
2228 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2229 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2230 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2231}
2232
2233static int
2234same_slots_added(PyTypeObject *a, PyTypeObject *b)
2235{
2236 PyTypeObject *base = a->tp_base;
2237 int size;
2238
2239 if (base != b->tp_base)
2240 return 0;
2241 if (equiv_structs(a, base) && equiv_structs(b, base))
2242 return 1;
2243 size = base->tp_basicsize;
2244 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2245 size += sizeof(PyObject *);
2246 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2247 size += sizeof(PyObject *);
2248 return size == a->tp_basicsize && size == b->tp_basicsize;
2249}
2250
2251static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002252compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2253{
2254 PyTypeObject *newbase, *oldbase;
2255
2256 if (new->tp_dealloc != old->tp_dealloc ||
2257 new->tp_free != old->tp_free)
2258 {
2259 PyErr_Format(PyExc_TypeError,
2260 "%s assignment: "
2261 "'%s' deallocator differs from '%s'",
2262 attr,
2263 new->tp_name,
2264 old->tp_name);
2265 return 0;
2266 }
2267 newbase = new;
2268 oldbase = old;
2269 while (equiv_structs(newbase, newbase->tp_base))
2270 newbase = newbase->tp_base;
2271 while (equiv_structs(oldbase, oldbase->tp_base))
2272 oldbase = oldbase->tp_base;
2273 if (newbase != oldbase &&
2274 (newbase->tp_base != oldbase->tp_base ||
2275 !same_slots_added(newbase, oldbase))) {
2276 PyErr_Format(PyExc_TypeError,
2277 "%s assignment: "
2278 "'%s' object layout differs from '%s'",
2279 attr,
2280 new->tp_name,
2281 old->tp_name);
2282 return 0;
2283 }
2284
2285 return 1;
2286}
2287
2288static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002289object_set_class(PyObject *self, PyObject *value, void *closure)
2290{
2291 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002292 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002293
Guido van Rossumb6b89422002-04-15 01:03:30 +00002294 if (value == NULL) {
2295 PyErr_SetString(PyExc_TypeError,
2296 "can't delete __class__ attribute");
2297 return -1;
2298 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002299 if (!PyType_Check(value)) {
2300 PyErr_Format(PyExc_TypeError,
2301 "__class__ must be set to new-style class, not '%s' object",
2302 value->ob_type->tp_name);
2303 return -1;
2304 }
2305 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002306 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2307 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2308 {
2309 PyErr_Format(PyExc_TypeError,
2310 "__class__ assignment: only for heap types");
2311 return -1;
2312 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002313 if (compatible_for_assignment(new, old, "__class__")) {
2314 Py_INCREF(new);
2315 self->ob_type = new;
2316 Py_DECREF(old);
2317 return 0;
2318 }
2319 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002320 return -1;
2321 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002322}
2323
2324static PyGetSetDef object_getsets[] = {
2325 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002326 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002327 {0}
2328};
2329
Guido van Rossum3926a632001-09-25 16:25:58 +00002330static PyObject *
2331object_reduce(PyObject *self, PyObject *args)
2332{
2333 /* Call copy_reg._reduce(self) */
2334 static PyObject *copy_reg_str;
2335 PyObject *copy_reg, *res;
2336
2337 if (!copy_reg_str) {
2338 copy_reg_str = PyString_InternFromString("copy_reg");
2339 if (copy_reg_str == NULL)
2340 return NULL;
2341 }
2342 copy_reg = PyImport_Import(copy_reg_str);
2343 if (!copy_reg)
2344 return NULL;
2345 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
2346 Py_DECREF(copy_reg);
2347 return res;
2348}
2349
2350static PyMethodDef object_methods[] = {
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002351 {"__reduce__", object_reduce, METH_NOARGS,
2352 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002353 {0}
2354};
2355
Tim Peters6d6c1a32001-08-02 04:15:00 +00002356PyTypeObject PyBaseObject_Type = {
2357 PyObject_HEAD_INIT(&PyType_Type)
2358 0, /* ob_size */
2359 "object", /* tp_name */
2360 sizeof(PyObject), /* tp_basicsize */
2361 0, /* tp_itemsize */
2362 (destructor)object_dealloc, /* tp_dealloc */
2363 0, /* tp_print */
2364 0, /* tp_getattr */
2365 0, /* tp_setattr */
2366 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002367 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002368 0, /* tp_as_number */
2369 0, /* tp_as_sequence */
2370 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002371 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002372 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002373 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002375 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002376 0, /* tp_as_buffer */
2377 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002378 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002379 0, /* tp_traverse */
2380 0, /* tp_clear */
2381 0, /* tp_richcompare */
2382 0, /* tp_weaklistoffset */
2383 0, /* tp_iter */
2384 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002385 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002386 0, /* tp_members */
2387 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002388 0, /* tp_base */
2389 0, /* tp_dict */
2390 0, /* tp_descr_get */
2391 0, /* tp_descr_set */
2392 0, /* tp_dictoffset */
2393 object_init, /* tp_init */
2394 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00002395 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002396 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002397};
2398
2399
2400/* Initialize the __dict__ in a type object */
2401
Fred Drake7bf97152002-03-28 05:33:33 +00002402static PyObject *
2403create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
2404{
2405 PyObject *cfunc;
2406 PyObject *result;
2407
2408 cfunc = PyCFunction_New(meth, NULL);
2409 if (cfunc == NULL)
2410 return NULL;
2411 result = func(cfunc);
2412 Py_DECREF(cfunc);
2413 return result;
2414}
2415
Tim Peters6d6c1a32001-08-02 04:15:00 +00002416static int
2417add_methods(PyTypeObject *type, PyMethodDef *meth)
2418{
Guido van Rossum687ae002001-10-15 22:03:32 +00002419 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002420
2421 for (; meth->ml_name != NULL; meth++) {
2422 PyObject *descr;
2423 if (PyDict_GetItemString(dict, meth->ml_name))
2424 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002425 if (meth->ml_flags & METH_CLASS) {
2426 if (meth->ml_flags & METH_STATIC) {
2427 PyErr_SetString(PyExc_ValueError,
2428 "method cannot be both class and static");
2429 return -1;
2430 }
2431 descr = create_specialmethod(meth, PyClassMethod_New);
2432 }
2433 else if (meth->ml_flags & METH_STATIC) {
2434 descr = create_specialmethod(meth, PyStaticMethod_New);
2435 }
2436 else {
2437 descr = PyDescr_NewMethod(type, meth);
2438 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002439 if (descr == NULL)
2440 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002441 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002442 return -1;
2443 Py_DECREF(descr);
2444 }
2445 return 0;
2446}
2447
2448static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002449add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002450{
Guido van Rossum687ae002001-10-15 22:03:32 +00002451 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002452
2453 for (; memb->name != NULL; memb++) {
2454 PyObject *descr;
2455 if (PyDict_GetItemString(dict, memb->name))
2456 continue;
2457 descr = PyDescr_NewMember(type, memb);
2458 if (descr == NULL)
2459 return -1;
2460 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2461 return -1;
2462 Py_DECREF(descr);
2463 }
2464 return 0;
2465}
2466
2467static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002468add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002469{
Guido van Rossum687ae002001-10-15 22:03:32 +00002470 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002471
2472 for (; gsp->name != NULL; gsp++) {
2473 PyObject *descr;
2474 if (PyDict_GetItemString(dict, gsp->name))
2475 continue;
2476 descr = PyDescr_NewGetSet(type, gsp);
2477
2478 if (descr == NULL)
2479 return -1;
2480 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2481 return -1;
2482 Py_DECREF(descr);
2483 }
2484 return 0;
2485}
2486
Guido van Rossum13d52f02001-08-10 21:24:08 +00002487static void
2488inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002489{
2490 int oldsize, newsize;
2491
Guido van Rossum13d52f02001-08-10 21:24:08 +00002492 /* Special flag magic */
2493 if (!type->tp_as_buffer && base->tp_as_buffer) {
2494 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2495 type->tp_flags |=
2496 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2497 }
2498 if (!type->tp_as_sequence && base->tp_as_sequence) {
2499 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2500 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2501 }
2502 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2503 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2504 if ((!type->tp_as_number && base->tp_as_number) ||
2505 (!type->tp_as_sequence && base->tp_as_sequence)) {
2506 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2507 if (!type->tp_as_number && !type->tp_as_sequence) {
2508 type->tp_flags |= base->tp_flags &
2509 Py_TPFLAGS_HAVE_INPLACEOPS;
2510 }
2511 }
2512 /* Wow */
2513 }
2514 if (!type->tp_as_number && base->tp_as_number) {
2515 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2516 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2517 }
2518
2519 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002520 oldsize = base->tp_basicsize;
2521 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2522 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2523 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002524 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2525 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002526 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002527 if (type->tp_traverse == NULL)
2528 type->tp_traverse = base->tp_traverse;
2529 if (type->tp_clear == NULL)
2530 type->tp_clear = base->tp_clear;
2531 }
2532 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002533 /* The condition below could use some explanation.
2534 It appears that tp_new is not inherited for static types
2535 whose base class is 'object'; this seems to be a precaution
2536 so that old extension types don't suddenly become
2537 callable (object.__new__ wouldn't insure the invariants
2538 that the extension type's own factory function ensures).
2539 Heap types, of course, are under our control, so they do
2540 inherit tp_new; static extension types that specify some
2541 other built-in type as the default are considered
2542 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002543 if (base != &PyBaseObject_Type ||
2544 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2545 if (type->tp_new == NULL)
2546 type->tp_new = base->tp_new;
2547 }
2548 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002549 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002550
2551 /* Copy other non-function slots */
2552
2553#undef COPYVAL
2554#define COPYVAL(SLOT) \
2555 if (type->SLOT == 0) type->SLOT = base->SLOT
2556
2557 COPYVAL(tp_itemsize);
2558 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2559 COPYVAL(tp_weaklistoffset);
2560 }
2561 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2562 COPYVAL(tp_dictoffset);
2563 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002564}
2565
2566static void
2567inherit_slots(PyTypeObject *type, PyTypeObject *base)
2568{
2569 PyTypeObject *basebase;
2570
2571#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002572#undef COPYSLOT
2573#undef COPYNUM
2574#undef COPYSEQ
2575#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002576#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002577
2578#define SLOTDEFINED(SLOT) \
2579 (base->SLOT != 0 && \
2580 (basebase == NULL || base->SLOT != basebase->SLOT))
2581
Tim Peters6d6c1a32001-08-02 04:15:00 +00002582#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002583 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002584
2585#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2586#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2587#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002588#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589
Guido van Rossum13d52f02001-08-10 21:24:08 +00002590 /* This won't inherit indirect slots (from tp_as_number etc.)
2591 if type doesn't provide the space. */
2592
2593 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2594 basebase = base->tp_base;
2595 if (basebase->tp_as_number == NULL)
2596 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002597 COPYNUM(nb_add);
2598 COPYNUM(nb_subtract);
2599 COPYNUM(nb_multiply);
2600 COPYNUM(nb_divide);
2601 COPYNUM(nb_remainder);
2602 COPYNUM(nb_divmod);
2603 COPYNUM(nb_power);
2604 COPYNUM(nb_negative);
2605 COPYNUM(nb_positive);
2606 COPYNUM(nb_absolute);
2607 COPYNUM(nb_nonzero);
2608 COPYNUM(nb_invert);
2609 COPYNUM(nb_lshift);
2610 COPYNUM(nb_rshift);
2611 COPYNUM(nb_and);
2612 COPYNUM(nb_xor);
2613 COPYNUM(nb_or);
2614 COPYNUM(nb_coerce);
2615 COPYNUM(nb_int);
2616 COPYNUM(nb_long);
2617 COPYNUM(nb_float);
2618 COPYNUM(nb_oct);
2619 COPYNUM(nb_hex);
2620 COPYNUM(nb_inplace_add);
2621 COPYNUM(nb_inplace_subtract);
2622 COPYNUM(nb_inplace_multiply);
2623 COPYNUM(nb_inplace_divide);
2624 COPYNUM(nb_inplace_remainder);
2625 COPYNUM(nb_inplace_power);
2626 COPYNUM(nb_inplace_lshift);
2627 COPYNUM(nb_inplace_rshift);
2628 COPYNUM(nb_inplace_and);
2629 COPYNUM(nb_inplace_xor);
2630 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002631 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2632 COPYNUM(nb_true_divide);
2633 COPYNUM(nb_floor_divide);
2634 COPYNUM(nb_inplace_true_divide);
2635 COPYNUM(nb_inplace_floor_divide);
2636 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002637 }
2638
Guido van Rossum13d52f02001-08-10 21:24:08 +00002639 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2640 basebase = base->tp_base;
2641 if (basebase->tp_as_sequence == NULL)
2642 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002643 COPYSEQ(sq_length);
2644 COPYSEQ(sq_concat);
2645 COPYSEQ(sq_repeat);
2646 COPYSEQ(sq_item);
2647 COPYSEQ(sq_slice);
2648 COPYSEQ(sq_ass_item);
2649 COPYSEQ(sq_ass_slice);
2650 COPYSEQ(sq_contains);
2651 COPYSEQ(sq_inplace_concat);
2652 COPYSEQ(sq_inplace_repeat);
2653 }
2654
Guido van Rossum13d52f02001-08-10 21:24:08 +00002655 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2656 basebase = base->tp_base;
2657 if (basebase->tp_as_mapping == NULL)
2658 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002659 COPYMAP(mp_length);
2660 COPYMAP(mp_subscript);
2661 COPYMAP(mp_ass_subscript);
2662 }
2663
Tim Petersfc57ccb2001-10-12 02:38:24 +00002664 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2665 basebase = base->tp_base;
2666 if (basebase->tp_as_buffer == NULL)
2667 basebase = NULL;
2668 COPYBUF(bf_getreadbuffer);
2669 COPYBUF(bf_getwritebuffer);
2670 COPYBUF(bf_getsegcount);
2671 COPYBUF(bf_getcharbuffer);
2672 }
2673
Guido van Rossum13d52f02001-08-10 21:24:08 +00002674 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002675
Tim Peters6d6c1a32001-08-02 04:15:00 +00002676 COPYSLOT(tp_dealloc);
2677 COPYSLOT(tp_print);
2678 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2679 type->tp_getattr = base->tp_getattr;
2680 type->tp_getattro = base->tp_getattro;
2681 }
2682 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2683 type->tp_setattr = base->tp_setattr;
2684 type->tp_setattro = base->tp_setattro;
2685 }
2686 /* tp_compare see tp_richcompare */
2687 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002688 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002689 COPYSLOT(tp_call);
2690 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002691 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002692 if (type->tp_compare == NULL &&
2693 type->tp_richcompare == NULL &&
2694 type->tp_hash == NULL)
2695 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696 type->tp_compare = base->tp_compare;
2697 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002698 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002699 }
2700 }
2701 else {
2702 COPYSLOT(tp_compare);
2703 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002704 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2705 COPYSLOT(tp_iter);
2706 COPYSLOT(tp_iternext);
2707 }
2708 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2709 COPYSLOT(tp_descr_get);
2710 COPYSLOT(tp_descr_set);
2711 COPYSLOT(tp_dictoffset);
2712 COPYSLOT(tp_init);
2713 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002715 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717}
2718
Jeremy Hylton938ace62002-07-17 16:30:39 +00002719static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002720
Tim Peters6d6c1a32001-08-02 04:15:00 +00002721int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002722PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002724 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725 PyTypeObject *base;
2726 int i, n;
2727
Guido van Rossumcab05802002-06-10 15:29:03 +00002728 if (type->tp_flags & Py_TPFLAGS_READY) {
2729 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002730 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002731 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002732 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002733
2734 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002735
2736 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2737 base = type->tp_base;
2738 if (base == NULL && type != &PyBaseObject_Type)
2739 base = type->tp_base = &PyBaseObject_Type;
2740
Guido van Rossum323a9cf2002-08-14 17:26:30 +00002741 /* Initialize the base class */
2742 if (base && base->tp_dict == NULL) {
2743 if (PyType_Ready(base) < 0)
2744 goto error;
2745 }
2746
Guido van Rossum0986d822002-04-08 01:38:42 +00002747 /* Initialize ob_type if NULL. This means extensions that want to be
2748 compilable separately on Windows can call PyType_Ready() instead of
2749 initializing the ob_type field of their type objects. */
2750 if (type->ob_type == NULL)
2751 type->ob_type = base->ob_type;
2752
Tim Peters6d6c1a32001-08-02 04:15:00 +00002753 /* Initialize tp_bases */
2754 bases = type->tp_bases;
2755 if (bases == NULL) {
2756 if (base == NULL)
2757 bases = PyTuple_New(0);
2758 else
2759 bases = Py_BuildValue("(O)", base);
2760 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002761 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002762 type->tp_bases = bases;
2763 }
2764
Guido van Rossum687ae002001-10-15 22:03:32 +00002765 /* Initialize tp_dict */
2766 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767 if (dict == NULL) {
2768 dict = PyDict_New();
2769 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002770 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002771 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772 }
2773
Guido van Rossum687ae002001-10-15 22:03:32 +00002774 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002775 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002776 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002777 if (type->tp_methods != NULL) {
2778 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002779 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780 }
2781 if (type->tp_members != NULL) {
2782 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002783 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784 }
2785 if (type->tp_getset != NULL) {
2786 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002787 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788 }
2789
Tim Peters6d6c1a32001-08-02 04:15:00 +00002790 /* Calculate method resolution order */
2791 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002792 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002793 }
2794
Guido van Rossum13d52f02001-08-10 21:24:08 +00002795 /* Inherit special flags from dominant base */
2796 if (type->tp_base != NULL)
2797 inherit_special(type, type->tp_base);
2798
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002800 bases = type->tp_mro;
2801 assert(bases != NULL);
2802 assert(PyTuple_Check(bases));
2803 n = PyTuple_GET_SIZE(bases);
2804 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002805 PyObject *b = PyTuple_GET_ITEM(bases, i);
2806 if (PyType_Check(b))
2807 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002808 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002809
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002810 /* if the type dictionary doesn't contain a __doc__, set it from
2811 the tp_doc slot.
2812 */
2813 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2814 if (type->tp_doc != NULL) {
2815 PyObject *doc = PyString_FromString(type->tp_doc);
2816 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2817 Py_DECREF(doc);
2818 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002819 PyDict_SetItemString(type->tp_dict,
2820 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002821 }
2822 }
2823
Guido van Rossum13d52f02001-08-10 21:24:08 +00002824 /* Some more special stuff */
2825 base = type->tp_base;
2826 if (base != NULL) {
2827 if (type->tp_as_number == NULL)
2828 type->tp_as_number = base->tp_as_number;
2829 if (type->tp_as_sequence == NULL)
2830 type->tp_as_sequence = base->tp_as_sequence;
2831 if (type->tp_as_mapping == NULL)
2832 type->tp_as_mapping = base->tp_as_mapping;
2833 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002834
Guido van Rossum1c450732001-10-08 15:18:27 +00002835 /* Link into each base class's list of subclasses */
2836 bases = type->tp_bases;
2837 n = PyTuple_GET_SIZE(bases);
2838 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002839 PyObject *b = PyTuple_GET_ITEM(bases, i);
2840 if (PyType_Check(b) &&
2841 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002842 goto error;
2843 }
2844
Guido van Rossum13d52f02001-08-10 21:24:08 +00002845 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002846 assert(type->tp_dict != NULL);
2847 type->tp_flags =
2848 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002849 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002850
2851 error:
2852 type->tp_flags &= ~Py_TPFLAGS_READYING;
2853 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002854}
2855
Guido van Rossum1c450732001-10-08 15:18:27 +00002856static int
2857add_subclass(PyTypeObject *base, PyTypeObject *type)
2858{
2859 int i;
2860 PyObject *list, *ref, *new;
2861
2862 list = base->tp_subclasses;
2863 if (list == NULL) {
2864 base->tp_subclasses = list = PyList_New(0);
2865 if (list == NULL)
2866 return -1;
2867 }
2868 assert(PyList_Check(list));
2869 new = PyWeakref_NewRef((PyObject *)type, NULL);
2870 i = PyList_GET_SIZE(list);
2871 while (--i >= 0) {
2872 ref = PyList_GET_ITEM(list, i);
2873 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00002874 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2875 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00002876 }
2877 i = PyList_Append(list, new);
2878 Py_DECREF(new);
2879 return i;
2880}
2881
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002882static void
2883remove_subclass(PyTypeObject *base, PyTypeObject *type)
2884{
2885 int i;
2886 PyObject *list, *ref;
2887
2888 list = base->tp_subclasses;
2889 if (list == NULL) {
2890 return;
2891 }
2892 assert(PyList_Check(list));
2893 i = PyList_GET_SIZE(list);
2894 while (--i >= 0) {
2895 ref = PyList_GET_ITEM(list, i);
2896 assert(PyWeakref_CheckRef(ref));
2897 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
2898 /* this can't fail, right? */
2899 PySequence_DelItem(list, i);
2900 return;
2901 }
2902 }
2903}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002904
2905/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2906
2907/* There's a wrapper *function* for each distinct function typedef used
2908 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2909 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2910 Most tables have only one entry; the tables for binary operators have two
2911 entries, one regular and one with reversed arguments. */
2912
2913static PyObject *
2914wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2915{
2916 inquiry func = (inquiry)wrapped;
2917 int res;
2918
2919 if (!PyArg_ParseTuple(args, ""))
2920 return NULL;
2921 res = (*func)(self);
2922 if (res == -1 && PyErr_Occurred())
2923 return NULL;
2924 return PyInt_FromLong((long)res);
2925}
2926
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927static PyObject *
2928wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2929{
2930 binaryfunc func = (binaryfunc)wrapped;
2931 PyObject *other;
2932
2933 if (!PyArg_ParseTuple(args, "O", &other))
2934 return NULL;
2935 return (*func)(self, other);
2936}
2937
2938static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002939wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2940{
2941 binaryfunc func = (binaryfunc)wrapped;
2942 PyObject *other;
2943
2944 if (!PyArg_ParseTuple(args, "O", &other))
2945 return NULL;
2946 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002947 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002948 Py_INCREF(Py_NotImplemented);
2949 return Py_NotImplemented;
2950 }
2951 return (*func)(self, other);
2952}
2953
2954static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002955wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2956{
2957 binaryfunc func = (binaryfunc)wrapped;
2958 PyObject *other;
2959
2960 if (!PyArg_ParseTuple(args, "O", &other))
2961 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002962 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002963 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002964 Py_INCREF(Py_NotImplemented);
2965 return Py_NotImplemented;
2966 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002967 return (*func)(other, self);
2968}
2969
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002970static PyObject *
2971wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2972{
2973 coercion func = (coercion)wrapped;
2974 PyObject *other, *res;
2975 int ok;
2976
2977 if (!PyArg_ParseTuple(args, "O", &other))
2978 return NULL;
2979 ok = func(&self, &other);
2980 if (ok < 0)
2981 return NULL;
2982 if (ok > 0) {
2983 Py_INCREF(Py_NotImplemented);
2984 return Py_NotImplemented;
2985 }
2986 res = PyTuple_New(2);
2987 if (res == NULL) {
2988 Py_DECREF(self);
2989 Py_DECREF(other);
2990 return NULL;
2991 }
2992 PyTuple_SET_ITEM(res, 0, self);
2993 PyTuple_SET_ITEM(res, 1, other);
2994 return res;
2995}
2996
Tim Peters6d6c1a32001-08-02 04:15:00 +00002997static PyObject *
2998wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2999{
3000 ternaryfunc func = (ternaryfunc)wrapped;
3001 PyObject *other;
3002 PyObject *third = Py_None;
3003
3004 /* Note: This wrapper only works for __pow__() */
3005
3006 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3007 return NULL;
3008 return (*func)(self, other, third);
3009}
3010
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003011static PyObject *
3012wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3013{
3014 ternaryfunc func = (ternaryfunc)wrapped;
3015 PyObject *other;
3016 PyObject *third = Py_None;
3017
3018 /* Note: This wrapper only works for __pow__() */
3019
3020 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3021 return NULL;
3022 return (*func)(other, self, third);
3023}
3024
Tim Peters6d6c1a32001-08-02 04:15:00 +00003025static PyObject *
3026wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3027{
3028 unaryfunc func = (unaryfunc)wrapped;
3029
3030 if (!PyArg_ParseTuple(args, ""))
3031 return NULL;
3032 return (*func)(self);
3033}
3034
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035static PyObject *
3036wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3037{
3038 intargfunc func = (intargfunc)wrapped;
3039 int i;
3040
3041 if (!PyArg_ParseTuple(args, "i", &i))
3042 return NULL;
3043 return (*func)(self, i);
3044}
3045
Guido van Rossum5d815f32001-08-17 21:57:47 +00003046static int
3047getindex(PyObject *self, PyObject *arg)
3048{
3049 int i;
3050
3051 i = PyInt_AsLong(arg);
3052 if (i == -1 && PyErr_Occurred())
3053 return -1;
3054 if (i < 0) {
3055 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3056 if (sq && sq->sq_length) {
3057 int n = (*sq->sq_length)(self);
3058 if (n < 0)
3059 return -1;
3060 i += n;
3061 }
3062 }
3063 return i;
3064}
3065
3066static PyObject *
3067wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3068{
3069 intargfunc func = (intargfunc)wrapped;
3070 PyObject *arg;
3071 int i;
3072
Guido van Rossumf4593e02001-10-03 12:09:30 +00003073 if (PyTuple_GET_SIZE(args) == 1) {
3074 arg = PyTuple_GET_ITEM(args, 0);
3075 i = getindex(self, arg);
3076 if (i == -1 && PyErr_Occurred())
3077 return NULL;
3078 return (*func)(self, i);
3079 }
3080 PyArg_ParseTuple(args, "O", &arg);
3081 assert(PyErr_Occurred());
3082 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003083}
3084
Tim Peters6d6c1a32001-08-02 04:15:00 +00003085static PyObject *
3086wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3087{
3088 intintargfunc func = (intintargfunc)wrapped;
3089 int i, j;
3090
3091 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3092 return NULL;
3093 return (*func)(self, i, j);
3094}
3095
Tim Peters6d6c1a32001-08-02 04:15:00 +00003096static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003097wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098{
3099 intobjargproc func = (intobjargproc)wrapped;
3100 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003101 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003102
Guido van Rossum5d815f32001-08-17 21:57:47 +00003103 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3104 return NULL;
3105 i = getindex(self, arg);
3106 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003107 return NULL;
3108 res = (*func)(self, i, value);
3109 if (res == -1 && PyErr_Occurred())
3110 return NULL;
3111 Py_INCREF(Py_None);
3112 return Py_None;
3113}
3114
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003115static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003116wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003117{
3118 intobjargproc func = (intobjargproc)wrapped;
3119 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003120 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003121
Guido van Rossum5d815f32001-08-17 21:57:47 +00003122 if (!PyArg_ParseTuple(args, "O", &arg))
3123 return NULL;
3124 i = getindex(self, arg);
3125 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003126 return NULL;
3127 res = (*func)(self, i, NULL);
3128 if (res == -1 && PyErr_Occurred())
3129 return NULL;
3130 Py_INCREF(Py_None);
3131 return Py_None;
3132}
3133
Tim Peters6d6c1a32001-08-02 04:15:00 +00003134static PyObject *
3135wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3136{
3137 intintobjargproc func = (intintobjargproc)wrapped;
3138 int i, j, res;
3139 PyObject *value;
3140
3141 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3142 return NULL;
3143 res = (*func)(self, i, j, value);
3144 if (res == -1 && PyErr_Occurred())
3145 return NULL;
3146 Py_INCREF(Py_None);
3147 return Py_None;
3148}
3149
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003150static PyObject *
3151wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3152{
3153 intintobjargproc func = (intintobjargproc)wrapped;
3154 int i, j, res;
3155
3156 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3157 return NULL;
3158 res = (*func)(self, i, j, NULL);
3159 if (res == -1 && PyErr_Occurred())
3160 return NULL;
3161 Py_INCREF(Py_None);
3162 return Py_None;
3163}
3164
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165/* XXX objobjproc is a misnomer; should be objargpred */
3166static PyObject *
3167wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3168{
3169 objobjproc func = (objobjproc)wrapped;
3170 int res;
3171 PyObject *value;
3172
3173 if (!PyArg_ParseTuple(args, "O", &value))
3174 return NULL;
3175 res = (*func)(self, value);
3176 if (res == -1 && PyErr_Occurred())
3177 return NULL;
3178 return PyInt_FromLong((long)res);
3179}
3180
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181static PyObject *
3182wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3183{
3184 objobjargproc func = (objobjargproc)wrapped;
3185 int res;
3186 PyObject *key, *value;
3187
3188 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3189 return NULL;
3190 res = (*func)(self, key, value);
3191 if (res == -1 && PyErr_Occurred())
3192 return NULL;
3193 Py_INCREF(Py_None);
3194 return Py_None;
3195}
3196
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003197static PyObject *
3198wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3199{
3200 objobjargproc func = (objobjargproc)wrapped;
3201 int res;
3202 PyObject *key;
3203
3204 if (!PyArg_ParseTuple(args, "O", &key))
3205 return NULL;
3206 res = (*func)(self, key, NULL);
3207 if (res == -1 && PyErr_Occurred())
3208 return NULL;
3209 Py_INCREF(Py_None);
3210 return Py_None;
3211}
3212
Tim Peters6d6c1a32001-08-02 04:15:00 +00003213static PyObject *
3214wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3215{
3216 cmpfunc func = (cmpfunc)wrapped;
3217 int res;
3218 PyObject *other;
3219
3220 if (!PyArg_ParseTuple(args, "O", &other))
3221 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003222 if (other->ob_type->tp_compare != func &&
3223 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003224 PyErr_Format(
3225 PyExc_TypeError,
3226 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3227 self->ob_type->tp_name,
3228 self->ob_type->tp_name,
3229 other->ob_type->tp_name);
3230 return NULL;
3231 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003232 res = (*func)(self, other);
3233 if (PyErr_Occurred())
3234 return NULL;
3235 return PyInt_FromLong((long)res);
3236}
3237
Tim Peters6d6c1a32001-08-02 04:15:00 +00003238static PyObject *
3239wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3240{
3241 setattrofunc func = (setattrofunc)wrapped;
3242 int res;
3243 PyObject *name, *value;
3244
3245 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3246 return NULL;
3247 res = (*func)(self, name, value);
3248 if (res < 0)
3249 return NULL;
3250 Py_INCREF(Py_None);
3251 return Py_None;
3252}
3253
3254static PyObject *
3255wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3256{
3257 setattrofunc func = (setattrofunc)wrapped;
3258 int res;
3259 PyObject *name;
3260
3261 if (!PyArg_ParseTuple(args, "O", &name))
3262 return NULL;
3263 res = (*func)(self, name, NULL);
3264 if (res < 0)
3265 return NULL;
3266 Py_INCREF(Py_None);
3267 return Py_None;
3268}
3269
Tim Peters6d6c1a32001-08-02 04:15:00 +00003270static PyObject *
3271wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3272{
3273 hashfunc func = (hashfunc)wrapped;
3274 long res;
3275
3276 if (!PyArg_ParseTuple(args, ""))
3277 return NULL;
3278 res = (*func)(self);
3279 if (res == -1 && PyErr_Occurred())
3280 return NULL;
3281 return PyInt_FromLong(res);
3282}
3283
Tim Peters6d6c1a32001-08-02 04:15:00 +00003284static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003285wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003286{
3287 ternaryfunc func = (ternaryfunc)wrapped;
3288
Guido van Rossumc8e56452001-10-22 00:43:43 +00003289 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003290}
3291
Tim Peters6d6c1a32001-08-02 04:15:00 +00003292static PyObject *
3293wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3294{
3295 richcmpfunc func = (richcmpfunc)wrapped;
3296 PyObject *other;
3297
3298 if (!PyArg_ParseTuple(args, "O", &other))
3299 return NULL;
3300 return (*func)(self, other, op);
3301}
3302
3303#undef RICHCMP_WRAPPER
3304#define RICHCMP_WRAPPER(NAME, OP) \
3305static PyObject * \
3306richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3307{ \
3308 return wrap_richcmpfunc(self, args, wrapped, OP); \
3309}
3310
Jack Jansen8e938b42001-08-08 15:29:49 +00003311RICHCMP_WRAPPER(lt, Py_LT)
3312RICHCMP_WRAPPER(le, Py_LE)
3313RICHCMP_WRAPPER(eq, Py_EQ)
3314RICHCMP_WRAPPER(ne, Py_NE)
3315RICHCMP_WRAPPER(gt, Py_GT)
3316RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317
Tim Peters6d6c1a32001-08-02 04:15:00 +00003318static PyObject *
3319wrap_next(PyObject *self, PyObject *args, void *wrapped)
3320{
3321 unaryfunc func = (unaryfunc)wrapped;
3322 PyObject *res;
3323
3324 if (!PyArg_ParseTuple(args, ""))
3325 return NULL;
3326 res = (*func)(self);
3327 if (res == NULL && !PyErr_Occurred())
3328 PyErr_SetNone(PyExc_StopIteration);
3329 return res;
3330}
3331
Tim Peters6d6c1a32001-08-02 04:15:00 +00003332static PyObject *
3333wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3334{
3335 descrgetfunc func = (descrgetfunc)wrapped;
3336 PyObject *obj;
3337 PyObject *type = NULL;
3338
3339 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3340 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003341 return (*func)(self, obj, type);
3342}
3343
Tim Peters6d6c1a32001-08-02 04:15:00 +00003344static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003345wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003346{
3347 descrsetfunc func = (descrsetfunc)wrapped;
3348 PyObject *obj, *value;
3349 int ret;
3350
3351 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3352 return NULL;
3353 ret = (*func)(self, obj, value);
3354 if (ret < 0)
3355 return NULL;
3356 Py_INCREF(Py_None);
3357 return Py_None;
3358}
Guido van Rossum22b13872002-08-06 21:41:44 +00003359
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003360static PyObject *
3361wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3362{
3363 descrsetfunc func = (descrsetfunc)wrapped;
3364 PyObject *obj;
3365 int ret;
3366
3367 if (!PyArg_ParseTuple(args, "O", &obj))
3368 return NULL;
3369 ret = (*func)(self, obj, NULL);
3370 if (ret < 0)
3371 return NULL;
3372 Py_INCREF(Py_None);
3373 return Py_None;
3374}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003375
Tim Peters6d6c1a32001-08-02 04:15:00 +00003376static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003377wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003378{
3379 initproc func = (initproc)wrapped;
3380
Guido van Rossumc8e56452001-10-22 00:43:43 +00003381 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003382 return NULL;
3383 Py_INCREF(Py_None);
3384 return Py_None;
3385}
3386
Tim Peters6d6c1a32001-08-02 04:15:00 +00003387static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003388tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003389{
Barry Warsaw60f01882001-08-22 19:24:42 +00003390 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003391 PyObject *arg0, *res;
3392
3393 if (self == NULL || !PyType_Check(self))
3394 Py_FatalError("__new__() called with non-type 'self'");
3395 type = (PyTypeObject *)self;
3396 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003397 PyErr_Format(PyExc_TypeError,
3398 "%s.__new__(): not enough arguments",
3399 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003400 return NULL;
3401 }
3402 arg0 = PyTuple_GET_ITEM(args, 0);
3403 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003404 PyErr_Format(PyExc_TypeError,
3405 "%s.__new__(X): X is not a type object (%s)",
3406 type->tp_name,
3407 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003408 return NULL;
3409 }
3410 subtype = (PyTypeObject *)arg0;
3411 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003412 PyErr_Format(PyExc_TypeError,
3413 "%s.__new__(%s): %s is not a subtype of %s",
3414 type->tp_name,
3415 subtype->tp_name,
3416 subtype->tp_name,
3417 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003418 return NULL;
3419 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003420
3421 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003422 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003423 most derived base that's not a heap type is this type. */
3424 staticbase = subtype;
3425 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3426 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003427 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003428 PyErr_Format(PyExc_TypeError,
3429 "%s.__new__(%s) is not safe, use %s.__new__()",
3430 type->tp_name,
3431 subtype->tp_name,
3432 staticbase == NULL ? "?" : staticbase->tp_name);
3433 return NULL;
3434 }
3435
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003436 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3437 if (args == NULL)
3438 return NULL;
3439 res = type->tp_new(subtype, args, kwds);
3440 Py_DECREF(args);
3441 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003442}
3443
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003444static struct PyMethodDef tp_new_methoddef[] = {
3445 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003446 PyDoc_STR("T.__new__(S, ...) -> "
3447 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003448 {0}
3449};
3450
3451static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003452add_tp_new_wrapper(PyTypeObject *type)
3453{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003454 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003455
Guido van Rossum687ae002001-10-15 22:03:32 +00003456 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003457 return 0;
3458 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003459 if (func == NULL)
3460 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003461 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003462}
3463
Guido van Rossumf040ede2001-08-07 16:40:56 +00003464/* Slot wrappers that call the corresponding __foo__ slot. See comments
3465 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003466
Guido van Rossumdc91b992001-08-08 22:26:22 +00003467#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003468static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003469FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003470{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003471 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003472 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473}
3474
Guido van Rossumdc91b992001-08-08 22:26:22 +00003475#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003476static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003477FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003478{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003479 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003480 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481}
3482
Guido van Rossumdc91b992001-08-08 22:26:22 +00003483
3484#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003485static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003486FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003487{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003488 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003489 int do_other = self->ob_type != other->ob_type && \
3490 other->ob_type->tp_as_number != NULL && \
3491 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003492 if (self->ob_type->tp_as_number != NULL && \
3493 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3494 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003495 if (do_other && \
3496 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
3497 r = call_maybe( \
3498 other, ROPSTR, &rcache_str, "(O)", self); \
3499 if (r != Py_NotImplemented) \
3500 return r; \
3501 Py_DECREF(r); \
3502 do_other = 0; \
3503 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003504 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003505 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003506 if (r != Py_NotImplemented || \
3507 other->ob_type == self->ob_type) \
3508 return r; \
3509 Py_DECREF(r); \
3510 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003511 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003512 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003513 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003514 } \
3515 Py_INCREF(Py_NotImplemented); \
3516 return Py_NotImplemented; \
3517}
3518
3519#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3520 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3521
3522#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3523static PyObject * \
3524FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3525{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003526 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003527 return call_method(self, OPSTR, &cache_str, \
3528 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003529}
3530
3531static int
3532slot_sq_length(PyObject *self)
3533{
Guido van Rossum2730b132001-08-28 18:22:14 +00003534 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003535 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003536 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537
3538 if (res == NULL)
3539 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003540 len = (int)PyInt_AsLong(res);
3541 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003542 if (len == -1 && PyErr_Occurred())
3543 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003544 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003545 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003546 "__len__() should return >= 0");
3547 return -1;
3548 }
Guido van Rossum26111622001-10-01 16:42:49 +00003549 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003550}
3551
Guido van Rossumdc91b992001-08-08 22:26:22 +00003552SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3553SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003554
3555/* Super-optimized version of slot_sq_item.
3556 Other slots could do the same... */
3557static PyObject *
3558slot_sq_item(PyObject *self, int i)
3559{
3560 static PyObject *getitem_str;
3561 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3562 descrgetfunc f;
3563
3564 if (getitem_str == NULL) {
3565 getitem_str = PyString_InternFromString("__getitem__");
3566 if (getitem_str == NULL)
3567 return NULL;
3568 }
3569 func = _PyType_Lookup(self->ob_type, getitem_str);
3570 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003571 if ((f = func->ob_type->tp_descr_get) == NULL)
3572 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003573 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003574 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003575 if (func == NULL) {
3576 return NULL;
3577 }
3578 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003579 ival = PyInt_FromLong(i);
3580 if (ival != NULL) {
3581 args = PyTuple_New(1);
3582 if (args != NULL) {
3583 PyTuple_SET_ITEM(args, 0, ival);
3584 retval = PyObject_Call(func, args, NULL);
3585 Py_XDECREF(args);
3586 Py_XDECREF(func);
3587 return retval;
3588 }
3589 }
3590 }
3591 else {
3592 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3593 }
3594 Py_XDECREF(args);
3595 Py_XDECREF(ival);
3596 Py_XDECREF(func);
3597 return NULL;
3598}
3599
Guido van Rossumdc91b992001-08-08 22:26:22 +00003600SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003601
3602static int
3603slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3604{
3605 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003606 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607
3608 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003609 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003610 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003611 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003612 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003613 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003614 if (res == NULL)
3615 return -1;
3616 Py_DECREF(res);
3617 return 0;
3618}
3619
3620static int
3621slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3622{
3623 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003624 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625
3626 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003627 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003628 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003629 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003630 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003631 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632 if (res == NULL)
3633 return -1;
3634 Py_DECREF(res);
3635 return 0;
3636}
3637
3638static int
3639slot_sq_contains(PyObject *self, PyObject *value)
3640{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003641 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003642 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003643
Guido van Rossum55f20992001-10-01 17:18:22 +00003644 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003645
3646 if (func != NULL) {
3647 args = Py_BuildValue("(O)", value);
3648 if (args == NULL)
3649 res = NULL;
3650 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003651 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003652 Py_DECREF(args);
3653 }
3654 Py_DECREF(func);
3655 if (res == NULL)
3656 return -1;
3657 return PyObject_IsTrue(res);
3658 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003659 else if (PyErr_Occurred())
3660 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003661 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003662 return _PySequence_IterSearch(self, value,
3663 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003664 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003665}
3666
Guido van Rossumdc91b992001-08-08 22:26:22 +00003667SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3668SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003669
3670#define slot_mp_length slot_sq_length
3671
Guido van Rossumdc91b992001-08-08 22:26:22 +00003672SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673
3674static int
3675slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3676{
3677 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003678 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003679
3680 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003681 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003682 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003684 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003685 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003686 if (res == NULL)
3687 return -1;
3688 Py_DECREF(res);
3689 return 0;
3690}
3691
Guido van Rossumdc91b992001-08-08 22:26:22 +00003692SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3693SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3694SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3695SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3696SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3697SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3698
Jeremy Hylton938ace62002-07-17 16:30:39 +00003699static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003700
3701SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3702 nb_power, "__pow__", "__rpow__")
3703
3704static PyObject *
3705slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3706{
Guido van Rossum2730b132001-08-28 18:22:14 +00003707 static PyObject *pow_str;
3708
Guido van Rossumdc91b992001-08-08 22:26:22 +00003709 if (modulus == Py_None)
3710 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003711 /* Three-arg power doesn't use __rpow__. But ternary_op
3712 can call this when the second argument's type uses
3713 slot_nb_power, so check before calling self.__pow__. */
3714 if (self->ob_type->tp_as_number != NULL &&
3715 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3716 return call_method(self, "__pow__", &pow_str,
3717 "(OO)", other, modulus);
3718 }
3719 Py_INCREF(Py_NotImplemented);
3720 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003721}
3722
3723SLOT0(slot_nb_negative, "__neg__")
3724SLOT0(slot_nb_positive, "__pos__")
3725SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726
3727static int
3728slot_nb_nonzero(PyObject *self)
3729{
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003730 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003731 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732
Guido van Rossum55f20992001-10-01 17:18:22 +00003733 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003734 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003735 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003736 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003737 func = lookup_maybe(self, "__len__", &len_str);
3738 if (func == NULL) {
3739 if (PyErr_Occurred())
3740 return -1;
3741 else
3742 return 1;
3743 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003744 }
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003745 args = res = PyTuple_New(0);
3746 if (args != NULL) {
3747 res = PyObject_Call(func, args, NULL);
3748 Py_DECREF(args);
3749 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003750 Py_DECREF(func);
3751 if (res == NULL)
3752 return -1;
3753 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003754}
3755
Guido van Rossumdc91b992001-08-08 22:26:22 +00003756SLOT0(slot_nb_invert, "__invert__")
3757SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3758SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3759SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3760SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3761SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003762
3763static int
3764slot_nb_coerce(PyObject **a, PyObject **b)
3765{
3766 static PyObject *coerce_str;
3767 PyObject *self = *a, *other = *b;
3768
3769 if (self->ob_type->tp_as_number != NULL &&
3770 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3771 PyObject *r;
3772 r = call_maybe(
3773 self, "__coerce__", &coerce_str, "(O)", other);
3774 if (r == NULL)
3775 return -1;
3776 if (r == Py_NotImplemented) {
3777 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003778 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003779 else {
3780 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3781 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003782 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003783 Py_DECREF(r);
3784 return -1;
3785 }
3786 *a = PyTuple_GET_ITEM(r, 0);
3787 Py_INCREF(*a);
3788 *b = PyTuple_GET_ITEM(r, 1);
3789 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003790 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003791 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003792 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003793 }
3794 if (other->ob_type->tp_as_number != NULL &&
3795 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3796 PyObject *r;
3797 r = call_maybe(
3798 other, "__coerce__", &coerce_str, "(O)", self);
3799 if (r == NULL)
3800 return -1;
3801 if (r == Py_NotImplemented) {
3802 Py_DECREF(r);
3803 return 1;
3804 }
3805 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3806 PyErr_SetString(PyExc_TypeError,
3807 "__coerce__ didn't return a 2-tuple");
3808 Py_DECREF(r);
3809 return -1;
3810 }
3811 *a = PyTuple_GET_ITEM(r, 1);
3812 Py_INCREF(*a);
3813 *b = PyTuple_GET_ITEM(r, 0);
3814 Py_INCREF(*b);
3815 Py_DECREF(r);
3816 return 0;
3817 }
3818 return 1;
3819}
3820
Guido van Rossumdc91b992001-08-08 22:26:22 +00003821SLOT0(slot_nb_int, "__int__")
3822SLOT0(slot_nb_long, "__long__")
3823SLOT0(slot_nb_float, "__float__")
3824SLOT0(slot_nb_oct, "__oct__")
3825SLOT0(slot_nb_hex, "__hex__")
3826SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3827SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3828SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3829SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3830SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003831SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003832SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3833SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3834SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3835SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3836SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3837SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3838 "__floordiv__", "__rfloordiv__")
3839SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3840SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3841SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003842
3843static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003844half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003845{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003846 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003847 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003848 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003849
Guido van Rossum60718732001-08-28 17:47:51 +00003850 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003851 if (func == NULL) {
3852 PyErr_Clear();
3853 }
3854 else {
3855 args = Py_BuildValue("(O)", other);
3856 if (args == NULL)
3857 res = NULL;
3858 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003859 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003860 Py_DECREF(args);
3861 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003862 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003863 if (res != Py_NotImplemented) {
3864 if (res == NULL)
3865 return -2;
3866 c = PyInt_AsLong(res);
3867 Py_DECREF(res);
3868 if (c == -1 && PyErr_Occurred())
3869 return -2;
3870 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3871 }
3872 Py_DECREF(res);
3873 }
3874 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003875}
3876
Guido van Rossumab3b0342001-09-18 20:38:53 +00003877/* This slot is published for the benefit of try_3way_compare in object.c */
3878int
3879_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003880{
3881 int c;
3882
Guido van Rossumab3b0342001-09-18 20:38:53 +00003883 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003884 c = half_compare(self, other);
3885 if (c <= 1)
3886 return c;
3887 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003888 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003889 c = half_compare(other, self);
3890 if (c < -1)
3891 return -2;
3892 if (c <= 1)
3893 return -c;
3894 }
3895 return (void *)self < (void *)other ? -1 :
3896 (void *)self > (void *)other ? 1 : 0;
3897}
3898
3899static PyObject *
3900slot_tp_repr(PyObject *self)
3901{
3902 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003903 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003904
Guido van Rossum60718732001-08-28 17:47:51 +00003905 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003906 if (func != NULL) {
3907 res = PyEval_CallObject(func, NULL);
3908 Py_DECREF(func);
3909 return res;
3910 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003911 PyErr_Clear();
3912 return PyString_FromFormat("<%s object at %p>",
3913 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003914}
3915
3916static PyObject *
3917slot_tp_str(PyObject *self)
3918{
3919 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003920 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003921
Guido van Rossum60718732001-08-28 17:47:51 +00003922 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003923 if (func != NULL) {
3924 res = PyEval_CallObject(func, NULL);
3925 Py_DECREF(func);
3926 return res;
3927 }
3928 else {
3929 PyErr_Clear();
3930 return slot_tp_repr(self);
3931 }
3932}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003933
3934static long
3935slot_tp_hash(PyObject *self)
3936{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003937 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003938 static PyObject *hash_str, *eq_str, *cmp_str;
3939
Tim Peters6d6c1a32001-08-02 04:15:00 +00003940 long h;
3941
Guido van Rossum60718732001-08-28 17:47:51 +00003942 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003943
3944 if (func != NULL) {
3945 res = PyEval_CallObject(func, NULL);
3946 Py_DECREF(func);
3947 if (res == NULL)
3948 return -1;
3949 h = PyInt_AsLong(res);
3950 }
3951 else {
3952 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003953 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003954 if (func == NULL) {
3955 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003956 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003957 }
3958 if (func != NULL) {
3959 Py_DECREF(func);
3960 PyErr_SetString(PyExc_TypeError, "unhashable type");
3961 return -1;
3962 }
3963 PyErr_Clear();
3964 h = _Py_HashPointer((void *)self);
3965 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003966 if (h == -1 && !PyErr_Occurred())
3967 h = -2;
3968 return h;
3969}
3970
3971static PyObject *
3972slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3973{
Guido van Rossum60718732001-08-28 17:47:51 +00003974 static PyObject *call_str;
3975 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003976 PyObject *res;
3977
3978 if (meth == NULL)
3979 return NULL;
3980 res = PyObject_Call(meth, args, kwds);
3981 Py_DECREF(meth);
3982 return res;
3983}
3984
Guido van Rossum14a6f832001-10-17 13:59:09 +00003985/* There are two slot dispatch functions for tp_getattro.
3986
3987 - slot_tp_getattro() is used when __getattribute__ is overridden
3988 but no __getattr__ hook is present;
3989
3990 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3991
Guido van Rossumc334df52002-04-04 23:44:47 +00003992 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3993 detects the absence of __getattr__ and then installs the simpler slot if
3994 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003995
Tim Peters6d6c1a32001-08-02 04:15:00 +00003996static PyObject *
3997slot_tp_getattro(PyObject *self, PyObject *name)
3998{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003999 static PyObject *getattribute_str = NULL;
4000 return call_method(self, "__getattribute__", &getattribute_str,
4001 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004002}
4003
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004004static PyObject *
4005slot_tp_getattr_hook(PyObject *self, PyObject *name)
4006{
4007 PyTypeObject *tp = self->ob_type;
4008 PyObject *getattr, *getattribute, *res;
4009 static PyObject *getattribute_str = NULL;
4010 static PyObject *getattr_str = NULL;
4011
4012 if (getattr_str == NULL) {
4013 getattr_str = PyString_InternFromString("__getattr__");
4014 if (getattr_str == NULL)
4015 return NULL;
4016 }
4017 if (getattribute_str == NULL) {
4018 getattribute_str =
4019 PyString_InternFromString("__getattribute__");
4020 if (getattribute_str == NULL)
4021 return NULL;
4022 }
4023 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004024 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004025 /* No __getattr__ hook: use a simpler dispatcher */
4026 tp->tp_getattro = slot_tp_getattro;
4027 return slot_tp_getattro(self, name);
4028 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004029 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004030 if (getattribute == NULL ||
4031 (getattribute->ob_type == &PyWrapperDescr_Type &&
4032 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4033 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004034 res = PyObject_GenericGetAttr(self, name);
4035 else
4036 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004037 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004038 PyErr_Clear();
4039 res = PyObject_CallFunction(getattr, "OO", self, name);
4040 }
4041 return res;
4042}
4043
Tim Peters6d6c1a32001-08-02 04:15:00 +00004044static int
4045slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4046{
4047 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004048 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004049
4050 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004051 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004052 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004053 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004054 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004055 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004056 if (res == NULL)
4057 return -1;
4058 Py_DECREF(res);
4059 return 0;
4060}
4061
4062/* Map rich comparison operators to their __xx__ namesakes */
4063static char *name_op[] = {
4064 "__lt__",
4065 "__le__",
4066 "__eq__",
4067 "__ne__",
4068 "__gt__",
4069 "__ge__",
4070};
4071
4072static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004073half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004074{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004075 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004076 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004077
Guido van Rossum60718732001-08-28 17:47:51 +00004078 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004079 if (func == NULL) {
4080 PyErr_Clear();
4081 Py_INCREF(Py_NotImplemented);
4082 return Py_NotImplemented;
4083 }
4084 args = Py_BuildValue("(O)", other);
4085 if (args == NULL)
4086 res = NULL;
4087 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004088 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004089 Py_DECREF(args);
4090 }
4091 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004092 return res;
4093}
4094
Guido van Rossumb8f63662001-08-15 23:57:02 +00004095/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4096static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4097
4098static PyObject *
4099slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4100{
4101 PyObject *res;
4102
4103 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4104 res = half_richcompare(self, other, op);
4105 if (res != Py_NotImplemented)
4106 return res;
4107 Py_DECREF(res);
4108 }
4109 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4110 res = half_richcompare(other, self, swapped_op[op]);
4111 if (res != Py_NotImplemented) {
4112 return res;
4113 }
4114 Py_DECREF(res);
4115 }
4116 Py_INCREF(Py_NotImplemented);
4117 return Py_NotImplemented;
4118}
4119
4120static PyObject *
4121slot_tp_iter(PyObject *self)
4122{
4123 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004124 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004125
Guido van Rossum60718732001-08-28 17:47:51 +00004126 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004127 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004128 PyObject *args;
4129 args = res = PyTuple_New(0);
4130 if (args != NULL) {
4131 res = PyObject_Call(func, args, NULL);
4132 Py_DECREF(args);
4133 }
4134 Py_DECREF(func);
4135 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004136 }
4137 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004138 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004139 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004140 PyErr_SetString(PyExc_TypeError,
4141 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004142 return NULL;
4143 }
4144 Py_DECREF(func);
4145 return PySeqIter_New(self);
4146}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004147
4148static PyObject *
4149slot_tp_iternext(PyObject *self)
4150{
Guido van Rossum2730b132001-08-28 18:22:14 +00004151 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004152 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004153}
4154
Guido van Rossum1a493502001-08-17 16:47:50 +00004155static PyObject *
4156slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4157{
4158 PyTypeObject *tp = self->ob_type;
4159 PyObject *get;
4160 static PyObject *get_str = NULL;
4161
4162 if (get_str == NULL) {
4163 get_str = PyString_InternFromString("__get__");
4164 if (get_str == NULL)
4165 return NULL;
4166 }
4167 get = _PyType_Lookup(tp, get_str);
4168 if (get == NULL) {
4169 /* Avoid further slowdowns */
4170 if (tp->tp_descr_get == slot_tp_descr_get)
4171 tp->tp_descr_get = NULL;
4172 Py_INCREF(self);
4173 return self;
4174 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004175 if (obj == NULL)
4176 obj = Py_None;
4177 if (type == NULL)
4178 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004179 return PyObject_CallFunction(get, "OOO", self, obj, type);
4180}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004181
4182static int
4183slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4184{
Guido van Rossum2c252392001-08-24 10:13:31 +00004185 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004186 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004187
4188 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004189 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004190 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004191 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004192 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004193 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004194 if (res == NULL)
4195 return -1;
4196 Py_DECREF(res);
4197 return 0;
4198}
4199
4200static int
4201slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4202{
Guido van Rossum60718732001-08-28 17:47:51 +00004203 static PyObject *init_str;
4204 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205 PyObject *res;
4206
4207 if (meth == NULL)
4208 return -1;
4209 res = PyObject_Call(meth, args, kwds);
4210 Py_DECREF(meth);
4211 if (res == NULL)
4212 return -1;
4213 Py_DECREF(res);
4214 return 0;
4215}
4216
4217static PyObject *
4218slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4219{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004220 static PyObject *new_str;
4221 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004222 PyObject *newargs, *x;
4223 int i, n;
4224
Guido van Rossum7bed2132002-08-08 21:57:53 +00004225 if (new_str == NULL) {
4226 new_str = PyString_InternFromString("__new__");
4227 if (new_str == NULL)
4228 return NULL;
4229 }
4230 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004231 if (func == NULL)
4232 return NULL;
4233 assert(PyTuple_Check(args));
4234 n = PyTuple_GET_SIZE(args);
4235 newargs = PyTuple_New(n+1);
4236 if (newargs == NULL)
4237 return NULL;
4238 Py_INCREF(type);
4239 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4240 for (i = 0; i < n; i++) {
4241 x = PyTuple_GET_ITEM(args, i);
4242 Py_INCREF(x);
4243 PyTuple_SET_ITEM(newargs, i+1, x);
4244 }
4245 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004246 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004247 Py_DECREF(func);
4248 return x;
4249}
4250
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004251static void
4252slot_tp_del(PyObject *self)
4253{
4254 static PyObject *del_str = NULL;
4255 PyObject *del, *res;
4256 PyObject *error_type, *error_value, *error_traceback;
4257
4258 /* Temporarily resurrect the object. */
4259 assert(self->ob_refcnt == 0);
4260 self->ob_refcnt = 1;
4261
4262 /* Save the current exception, if any. */
4263 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4264
4265 /* Execute __del__ method, if any. */
4266 del = lookup_maybe(self, "__del__", &del_str);
4267 if (del != NULL) {
4268 res = PyEval_CallObject(del, NULL);
4269 if (res == NULL)
4270 PyErr_WriteUnraisable(del);
4271 else
4272 Py_DECREF(res);
4273 Py_DECREF(del);
4274 }
4275
4276 /* Restore the saved exception. */
4277 PyErr_Restore(error_type, error_value, error_traceback);
4278
4279 /* Undo the temporary resurrection; can't use DECREF here, it would
4280 * cause a recursive call.
4281 */
4282 assert(self->ob_refcnt > 0);
4283 if (--self->ob_refcnt == 0)
4284 return; /* this is the normal path out */
4285
4286 /* __del__ resurrected it! Make it look like the original Py_DECREF
4287 * never happened.
4288 */
4289 {
4290 int refcnt = self->ob_refcnt;
4291 _Py_NewReference(self);
4292 self->ob_refcnt = refcnt;
4293 }
4294 assert(!PyType_IS_GC(self->ob_type) ||
4295 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4296 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4297 * _Py_NewReference bumped it again, so that's a wash.
4298 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4299 * chain, so no more to do there either.
4300 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4301 * _Py_NewReference bumped tp_allocs: both of those need to be
4302 * undone.
4303 */
4304#ifdef COUNT_ALLOCS
4305 --self->ob_type->tp_frees;
4306 --self->ob_type->tp_allocs;
4307#endif
4308}
4309
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004310
4311/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4312 functions. The offsets here are relative to the 'etype' structure, which
4313 incorporates the additional structures used for numbers, sequences and
4314 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4315 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004316 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4317 terminated with an all-zero entry. (This table is further initialized and
4318 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004319
Guido van Rossum6d204072001-10-21 00:44:31 +00004320typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004321
4322#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004323#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004324#undef ETSLOT
4325#undef SQSLOT
4326#undef MPSLOT
4327#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004328#undef UNSLOT
4329#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004330#undef BINSLOT
4331#undef RBINSLOT
4332
Guido van Rossum6d204072001-10-21 00:44:31 +00004333#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004334 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4335 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004336#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4337 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004338 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004339#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004340 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4341 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004342#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4343 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4344#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4345 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4346#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4347 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4348#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4349 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4350 "x." NAME "() <==> " DOC)
4351#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4352 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4353 "x." NAME "(y) <==> x" DOC "y")
4354#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4355 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4356 "x." NAME "(y) <==> x" DOC "y")
4357#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4358 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4359 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004360
4361static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004362 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4363 "x.__len__() <==> len(x)"),
4364 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4365 "x.__add__(y) <==> x+y"),
4366 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4367 "x.__mul__(n) <==> x*n"),
4368 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4369 "x.__rmul__(n) <==> n*x"),
4370 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4371 "x.__getitem__(y) <==> x[y]"),
4372 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4373 "x.__getslice__(i, j) <==> x[i:j]"),
4374 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4375 "x.__setitem__(i, y) <==> x[i]=y"),
4376 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4377 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004378 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004379 wrap_intintobjargproc,
4380 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4381 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4382 "x.__delslice__(i, j) <==> del x[i:j]"),
4383 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4384 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004385 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004386 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004387 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004388 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004389
Guido van Rossum6d204072001-10-21 00:44:31 +00004390 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4391 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004392 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004393 wrap_binaryfunc,
4394 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004395 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004396 wrap_objobjargproc,
4397 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004398 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004399 wrap_delitem,
4400 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004401
Guido van Rossum6d204072001-10-21 00:44:31 +00004402 BINSLOT("__add__", nb_add, slot_nb_add,
4403 "+"),
4404 RBINSLOT("__radd__", nb_add, slot_nb_add,
4405 "+"),
4406 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4407 "-"),
4408 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4409 "-"),
4410 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4411 "*"),
4412 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4413 "*"),
4414 BINSLOT("__div__", nb_divide, slot_nb_divide,
4415 "/"),
4416 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4417 "/"),
4418 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4419 "%"),
4420 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4421 "%"),
4422 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4423 "divmod(x, y)"),
4424 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4425 "divmod(y, x)"),
4426 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4427 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4428 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4429 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4430 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4431 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4432 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4433 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004434 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004435 "x != 0"),
4436 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4437 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4438 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4439 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4440 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4441 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4442 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4443 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4444 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4445 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4446 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4447 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4448 "x.__coerce__(y) <==> coerce(x, y)"),
4449 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4450 "int(x)"),
4451 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4452 "long(x)"),
4453 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4454 "float(x)"),
4455 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4456 "oct(x)"),
4457 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4458 "hex(x)"),
4459 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4460 wrap_binaryfunc, "+"),
4461 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4462 wrap_binaryfunc, "-"),
4463 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4464 wrap_binaryfunc, "*"),
4465 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4466 wrap_binaryfunc, "/"),
4467 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4468 wrap_binaryfunc, "%"),
4469 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004470 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004471 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4472 wrap_binaryfunc, "<<"),
4473 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4474 wrap_binaryfunc, ">>"),
4475 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4476 wrap_binaryfunc, "&"),
4477 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4478 wrap_binaryfunc, "^"),
4479 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4480 wrap_binaryfunc, "|"),
4481 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4482 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4483 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4484 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4485 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4486 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4487 IBSLOT("__itruediv__", nb_inplace_true_divide,
4488 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004489
Guido van Rossum6d204072001-10-21 00:44:31 +00004490 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4491 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004492 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004493 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4494 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004495 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004496 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4497 "x.__cmp__(y) <==> cmp(x,y)"),
4498 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4499 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004500 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4501 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004502 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004503 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4504 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4505 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4506 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4507 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4508 "x.__setattr__('name', value) <==> x.name = value"),
4509 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4510 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4511 "x.__delattr__('name') <==> del x.name"),
4512 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4513 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4514 "x.__lt__(y) <==> x<y"),
4515 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4516 "x.__le__(y) <==> x<=y"),
4517 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4518 "x.__eq__(y) <==> x==y"),
4519 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4520 "x.__ne__(y) <==> x!=y"),
4521 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4522 "x.__gt__(y) <==> x>y"),
4523 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4524 "x.__ge__(y) <==> x>=y"),
4525 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4526 "x.__iter__() <==> iter(x)"),
4527 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4528 "x.next() -> the next value, or raise StopIteration"),
4529 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4530 "descr.__get__(obj[, type]) -> value"),
4531 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4532 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004533 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4534 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004535 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004536 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004537 "see x.__class__.__doc__ for signature",
4538 PyWrapperFlag_KEYWORDS),
4539 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004540 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004541 {NULL}
4542};
4543
Guido van Rossumc334df52002-04-04 23:44:47 +00004544/* Given a type pointer and an offset gotten from a slotdef entry, return a
4545 pointer to the actual slot. This is not quite the same as simply adding
4546 the offset to the type pointer, since it takes care to indirect through the
4547 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4548 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004549static void **
4550slotptr(PyTypeObject *type, int offset)
4551{
4552 char *ptr;
4553
Guido van Rossum09638c12002-06-13 19:17:46 +00004554 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004555 assert(offset >= 0);
4556 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004557 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004558 ptr = (void *)type->tp_as_sequence;
4559 offset -= offsetof(etype, as_sequence);
4560 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004561 else if (offset >= offsetof(etype, as_mapping)) {
4562 ptr = (void *)type->tp_as_mapping;
4563 offset -= offsetof(etype, as_mapping);
4564 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004565 else if (offset >= offsetof(etype, as_number)) {
4566 ptr = (void *)type->tp_as_number;
4567 offset -= offsetof(etype, as_number);
4568 }
4569 else {
4570 ptr = (void *)type;
4571 }
4572 if (ptr != NULL)
4573 ptr += offset;
4574 return (void **)ptr;
4575}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004576
Guido van Rossumc334df52002-04-04 23:44:47 +00004577/* Length of array of slotdef pointers used to store slots with the
4578 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4579 the same __name__, for any __name__. Since that's a static property, it is
4580 appropriate to declare fixed-size arrays for this. */
4581#define MAX_EQUIV 10
4582
4583/* Return a slot pointer for a given name, but ONLY if the attribute has
4584 exactly one slot function. The name must be an interned string. */
4585static void **
4586resolve_slotdups(PyTypeObject *type, PyObject *name)
4587{
4588 /* XXX Maybe this could be optimized more -- but is it worth it? */
4589
4590 /* pname and ptrs act as a little cache */
4591 static PyObject *pname;
4592 static slotdef *ptrs[MAX_EQUIV];
4593 slotdef *p, **pp;
4594 void **res, **ptr;
4595
4596 if (pname != name) {
4597 /* Collect all slotdefs that match name into ptrs. */
4598 pname = name;
4599 pp = ptrs;
4600 for (p = slotdefs; p->name_strobj; p++) {
4601 if (p->name_strobj == name)
4602 *pp++ = p;
4603 }
4604 *pp = NULL;
4605 }
4606
4607 /* Look in all matching slots of the type; if exactly one of these has
4608 a filled-in slot, return its value. Otherwise return NULL. */
4609 res = NULL;
4610 for (pp = ptrs; *pp; pp++) {
4611 ptr = slotptr(type, (*pp)->offset);
4612 if (ptr == NULL || *ptr == NULL)
4613 continue;
4614 if (res != NULL)
4615 return NULL;
4616 res = ptr;
4617 }
4618 return res;
4619}
4620
4621/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4622 does some incredibly complex thinking and then sticks something into the
4623 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4624 interests, and then stores a generic wrapper or a specific function into
4625 the slot.) Return a pointer to the next slotdef with a different offset,
4626 because that's convenient for fixup_slot_dispatchers(). */
4627static slotdef *
4628update_one_slot(PyTypeObject *type, slotdef *p)
4629{
4630 PyObject *descr;
4631 PyWrapperDescrObject *d;
4632 void *generic = NULL, *specific = NULL;
4633 int use_generic = 0;
4634 int offset = p->offset;
4635 void **ptr = slotptr(type, offset);
4636
4637 if (ptr == NULL) {
4638 do {
4639 ++p;
4640 } while (p->offset == offset);
4641 return p;
4642 }
4643 do {
4644 descr = _PyType_Lookup(type, p->name_strobj);
4645 if (descr == NULL)
4646 continue;
4647 if (descr->ob_type == &PyWrapperDescr_Type) {
4648 void **tptr = resolve_slotdups(type, p->name_strobj);
4649 if (tptr == NULL || tptr == ptr)
4650 generic = p->function;
4651 d = (PyWrapperDescrObject *)descr;
4652 if (d->d_base->wrapper == p->wrapper &&
4653 PyType_IsSubtype(type, d->d_type))
4654 {
4655 if (specific == NULL ||
4656 specific == d->d_wrapped)
4657 specific = d->d_wrapped;
4658 else
4659 use_generic = 1;
4660 }
4661 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004662 else if (descr->ob_type == &PyCFunction_Type &&
4663 PyCFunction_GET_FUNCTION(descr) ==
4664 (PyCFunction)tp_new_wrapper &&
4665 strcmp(p->name, "__new__") == 0)
4666 {
4667 /* The __new__ wrapper is not a wrapper descriptor,
4668 so must be special-cased differently.
4669 If we don't do this, creating an instance will
4670 always use slot_tp_new which will look up
4671 __new__ in the MRO which will call tp_new_wrapper
4672 which will look through the base classes looking
4673 for a static base and call its tp_new (usually
4674 PyType_GenericNew), after performing various
4675 sanity checks and constructing a new argument
4676 list. Cut all that nonsense short -- this speeds
4677 up instance creation tremendously. */
4678 specific = type->tp_new;
4679 /* XXX I'm not 100% sure that there isn't a hole
4680 in this reasoning that requires additional
4681 sanity checks. I'll buy the first person to
4682 point out a bug in this reasoning a beer. */
4683 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004684 else {
4685 use_generic = 1;
4686 generic = p->function;
4687 }
4688 } while ((++p)->offset == offset);
4689 if (specific && !use_generic)
4690 *ptr = specific;
4691 else
4692 *ptr = generic;
4693 return p;
4694}
4695
Guido van Rossum22b13872002-08-06 21:41:44 +00004696static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004697 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004698
Guido van Rossumc334df52002-04-04 23:44:47 +00004699/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4700 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004701static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004702update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004703{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004704 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004705
Guido van Rossumc334df52002-04-04 23:44:47 +00004706 for (pp = pp0; *pp; pp++)
4707 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004708 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004709}
4710
Guido van Rossumc334df52002-04-04 23:44:47 +00004711/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4712 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004713static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004714recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004715{
4716 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004717 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004718 int i, n;
4719
4720 subclasses = type->tp_subclasses;
4721 if (subclasses == NULL)
4722 return 0;
4723 assert(PyList_Check(subclasses));
4724 n = PyList_GET_SIZE(subclasses);
4725 for (i = 0; i < n; i++) {
4726 ref = PyList_GET_ITEM(subclasses, i);
4727 assert(PyWeakref_CheckRef(ref));
4728 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004729 assert(subclass != NULL);
4730 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004731 continue;
4732 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004733 /* Avoid recursing down into unaffected classes */
4734 dict = subclass->tp_dict;
4735 if (dict != NULL && PyDict_Check(dict) &&
4736 PyDict_GetItem(dict, name) != NULL)
4737 continue;
4738 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004739 return -1;
4740 }
4741 return 0;
4742}
4743
Guido van Rossumc334df52002-04-04 23:44:47 +00004744/* Comparison function for qsort() to compare slotdefs by their offset, and
4745 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004746static int
4747slotdef_cmp(const void *aa, const void *bb)
4748{
4749 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4750 int c = a->offset - b->offset;
4751 if (c != 0)
4752 return c;
4753 else
4754 return a - b;
4755}
4756
Guido van Rossumc334df52002-04-04 23:44:47 +00004757/* Initialize the slotdefs table by adding interned string objects for the
4758 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004759static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004760init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004761{
4762 slotdef *p;
4763 static int initialized = 0;
4764
4765 if (initialized)
4766 return;
4767 for (p = slotdefs; p->name; p++) {
4768 p->name_strobj = PyString_InternFromString(p->name);
4769 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004770 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004771 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004772 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4773 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004774 initialized = 1;
4775}
4776
Guido van Rossumc334df52002-04-04 23:44:47 +00004777/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004778static int
4779update_slot(PyTypeObject *type, PyObject *name)
4780{
Guido van Rossumc334df52002-04-04 23:44:47 +00004781 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004782 slotdef *p;
4783 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004784 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004785
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004786 init_slotdefs();
4787 pp = ptrs;
4788 for (p = slotdefs; p->name; p++) {
4789 /* XXX assume name is interned! */
4790 if (p->name_strobj == name)
4791 *pp++ = p;
4792 }
4793 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004794 for (pp = ptrs; *pp; pp++) {
4795 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004796 offset = p->offset;
4797 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004798 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004799 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004800 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004801 if (ptrs[0] == NULL)
4802 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004803 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004804}
4805
Guido van Rossumc334df52002-04-04 23:44:47 +00004806/* Store the proper functions in the slot dispatches at class (type)
4807 definition time, based upon which operations the class overrides in its
4808 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004809static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004810fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004811{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004812 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004813
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004814 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004815 for (p = slotdefs; p->name; )
4816 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004817}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004818
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004819static void
4820update_all_slots(PyTypeObject* type)
4821{
4822 slotdef *p;
4823
4824 init_slotdefs();
4825 for (p = slotdefs; p->name; p++) {
4826 /* update_slot returns int but can't actually fail */
4827 update_slot(type, p->name_strobj);
4828 }
4829}
4830
Guido van Rossum6d204072001-10-21 00:44:31 +00004831/* This function is called by PyType_Ready() to populate the type's
4832 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004833 function slot (like tp_repr) that's defined in the type, one or more
4834 corresponding descriptors are added in the type's tp_dict dictionary
4835 under the appropriate name (like __repr__). Some function slots
4836 cause more than one descriptor to be added (for example, the nb_add
4837 slot adds both __add__ and __radd__ descriptors) and some function
4838 slots compete for the same descriptor (for example both sq_item and
4839 mp_subscript generate a __getitem__ descriptor).
4840
4841 In the latter case, the first slotdef entry encoutered wins. Since
4842 slotdef entries are sorted by the offset of the slot in the etype
4843 struct, this gives us some control over disambiguating between
4844 competing slots: the members of struct etype are listed from most
4845 general to least general, so the most general slot is preferred. In
4846 particular, because as_mapping comes before as_sequence, for a type
4847 that defines both mp_subscript and sq_item, mp_subscript wins.
4848
4849 This only adds new descriptors and doesn't overwrite entries in
4850 tp_dict that were previously defined. The descriptors contain a
4851 reference to the C function they must call, so that it's safe if they
4852 are copied into a subtype's __dict__ and the subtype has a different
4853 C function in its slot -- calling the method defined by the
4854 descriptor will call the C function that was used to create it,
4855 rather than the C function present in the slot when it is called.
4856 (This is important because a subtype may have a C function in the
4857 slot that calls the method from the dictionary, and we want to avoid
4858 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004859
4860static int
4861add_operators(PyTypeObject *type)
4862{
4863 PyObject *dict = type->tp_dict;
4864 slotdef *p;
4865 PyObject *descr;
4866 void **ptr;
4867
4868 init_slotdefs();
4869 for (p = slotdefs; p->name; p++) {
4870 if (p->wrapper == NULL)
4871 continue;
4872 ptr = slotptr(type, p->offset);
4873 if (!ptr || !*ptr)
4874 continue;
4875 if (PyDict_GetItem(dict, p->name_strobj))
4876 continue;
4877 descr = PyDescr_NewWrapper(type, p, *ptr);
4878 if (descr == NULL)
4879 return -1;
4880 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4881 return -1;
4882 Py_DECREF(descr);
4883 }
4884 if (type->tp_new != NULL) {
4885 if (add_tp_new_wrapper(type) < 0)
4886 return -1;
4887 }
4888 return 0;
4889}
4890
Guido van Rossum705f0f52001-08-24 16:47:00 +00004891
4892/* Cooperative 'super' */
4893
4894typedef struct {
4895 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004896 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004897 PyObject *obj;
4898} superobject;
4899
Guido van Rossum6f799372001-09-20 20:46:19 +00004900static PyMemberDef super_members[] = {
4901 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4902 "the class invoking super()"},
4903 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4904 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004905 {0}
4906};
4907
Guido van Rossum705f0f52001-08-24 16:47:00 +00004908static void
4909super_dealloc(PyObject *self)
4910{
4911 superobject *su = (superobject *)self;
4912
Guido van Rossum048eb752001-10-02 21:24:57 +00004913 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004914 Py_XDECREF(su->obj);
4915 Py_XDECREF(su->type);
4916 self->ob_type->tp_free(self);
4917}
4918
4919static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004920super_repr(PyObject *self)
4921{
4922 superobject *su = (superobject *)self;
4923
4924 if (su->obj)
4925 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004926 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004927 su->type ? su->type->tp_name : "NULL",
4928 su->obj->ob_type->tp_name);
4929 else
4930 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004931 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004932 su->type ? su->type->tp_name : "NULL");
4933}
4934
4935static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004936super_getattro(PyObject *self, PyObject *name)
4937{
4938 superobject *su = (superobject *)self;
4939
4940 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004941 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004942 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004943 descrgetfunc f;
4944 int i, n;
4945
Guido van Rossum155db9a2002-04-02 17:53:47 +00004946 starttype = su->obj->ob_type;
4947 mro = starttype->tp_mro;
4948
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004949 if (mro == NULL)
4950 n = 0;
4951 else {
4952 assert(PyTuple_Check(mro));
4953 n = PyTuple_GET_SIZE(mro);
4954 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004955 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004956 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004957 break;
4958 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004959 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004960 starttype = (PyTypeObject *)(su->obj);
4961 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004962 if (mro == NULL)
4963 n = 0;
4964 else {
4965 assert(PyTuple_Check(mro));
4966 n = PyTuple_GET_SIZE(mro);
4967 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004968 for (i = 0; i < n; i++) {
4969 if ((PyObject *)(su->type) ==
4970 PyTuple_GET_ITEM(mro, i))
4971 break;
4972 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004973 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004974 i++;
4975 res = NULL;
4976 for (; i < n; i++) {
4977 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004978 if (PyType_Check(tmp))
4979 dict = ((PyTypeObject *)tmp)->tp_dict;
4980 else if (PyClass_Check(tmp))
4981 dict = ((PyClassObject *)tmp)->cl_dict;
4982 else
4983 continue;
4984 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004985 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004986 Py_INCREF(res);
4987 f = res->ob_type->tp_descr_get;
4988 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004989 tmp = f(res, su->obj,
4990 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004991 Py_DECREF(res);
4992 res = tmp;
4993 }
4994 return res;
4995 }
4996 }
4997 }
4998 return PyObject_GenericGetAttr(self, name);
4999}
5000
Guido van Rossum5b443c62001-12-03 15:38:28 +00005001static int
5002supercheck(PyTypeObject *type, PyObject *obj)
5003{
5004 if (!PyType_IsSubtype(obj->ob_type, type) &&
5005 !(PyType_Check(obj) &&
5006 PyType_IsSubtype((PyTypeObject *)obj, type))) {
5007 PyErr_SetString(PyExc_TypeError,
5008 "super(type, obj): "
5009 "obj must be an instance or subtype of type");
5010 return -1;
5011 }
5012 else
5013 return 0;
5014}
5015
Guido van Rossum705f0f52001-08-24 16:47:00 +00005016static PyObject *
5017super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5018{
5019 superobject *su = (superobject *)self;
5020 superobject *new;
5021
5022 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5023 /* Not binding to an object, or already bound */
5024 Py_INCREF(self);
5025 return self;
5026 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005027 if (su->ob_type != &PySuper_Type)
5028 /* If su is an instance of a subclass of super,
5029 call its type */
5030 return PyObject_CallFunction((PyObject *)su->ob_type,
5031 "OO", su->type, obj);
5032 else {
5033 /* Inline the common case */
5034 if (supercheck(su->type, obj) < 0)
5035 return NULL;
5036 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5037 NULL, NULL);
5038 if (new == NULL)
5039 return NULL;
5040 Py_INCREF(su->type);
5041 Py_INCREF(obj);
5042 new->type = su->type;
5043 new->obj = obj;
5044 return (PyObject *)new;
5045 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005046}
5047
5048static int
5049super_init(PyObject *self, PyObject *args, PyObject *kwds)
5050{
5051 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005052 PyTypeObject *type;
5053 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005054
5055 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5056 return -1;
5057 if (obj == Py_None)
5058 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005059 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005060 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005061 Py_INCREF(type);
5062 Py_XINCREF(obj);
5063 su->type = type;
5064 su->obj = obj;
5065 return 0;
5066}
5067
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005068PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005069"super(type) -> unbound super object\n"
5070"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005071"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005072"Typical use to call a cooperative superclass method:\n"
5073"class C(B):\n"
5074" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005075" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005076
Guido van Rossum048eb752001-10-02 21:24:57 +00005077static int
5078super_traverse(PyObject *self, visitproc visit, void *arg)
5079{
5080 superobject *su = (superobject *)self;
5081 int err;
5082
5083#define VISIT(SLOT) \
5084 if (SLOT) { \
5085 err = visit((PyObject *)(SLOT), arg); \
5086 if (err) \
5087 return err; \
5088 }
5089
5090 VISIT(su->obj);
5091 VISIT(su->type);
5092
5093#undef VISIT
5094
5095 return 0;
5096}
5097
Guido van Rossum705f0f52001-08-24 16:47:00 +00005098PyTypeObject PySuper_Type = {
5099 PyObject_HEAD_INIT(&PyType_Type)
5100 0, /* ob_size */
5101 "super", /* tp_name */
5102 sizeof(superobject), /* tp_basicsize */
5103 0, /* tp_itemsize */
5104 /* methods */
5105 super_dealloc, /* tp_dealloc */
5106 0, /* tp_print */
5107 0, /* tp_getattr */
5108 0, /* tp_setattr */
5109 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005110 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005111 0, /* tp_as_number */
5112 0, /* tp_as_sequence */
5113 0, /* tp_as_mapping */
5114 0, /* tp_hash */
5115 0, /* tp_call */
5116 0, /* tp_str */
5117 super_getattro, /* tp_getattro */
5118 0, /* tp_setattro */
5119 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005120 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5121 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005122 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005123 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005124 0, /* tp_clear */
5125 0, /* tp_richcompare */
5126 0, /* tp_weaklistoffset */
5127 0, /* tp_iter */
5128 0, /* tp_iternext */
5129 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005130 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005131 0, /* tp_getset */
5132 0, /* tp_base */
5133 0, /* tp_dict */
5134 super_descr_get, /* tp_descr_get */
5135 0, /* tp_descr_set */
5136 0, /* tp_dictoffset */
5137 super_init, /* tp_init */
5138 PyType_GenericAlloc, /* tp_alloc */
5139 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005140 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005141};