blob: 82237c870cd6d4f27f2b398166c7e837d4508199 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
8/* The *real* layout of a type object when allocated on the heap */
9/* XXX Should we publish this in a header file? */
10typedef struct {
Guido van Rossum09638c12002-06-13 19:17:46 +000011 /* Note: there's a dependency on the order of these members
12 in slotptr() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000013 PyTypeObject type;
14 PyNumberMethods as_number;
Guido van Rossum9923ffe2002-06-04 19:52:53 +000015 PyMappingMethods as_mapping;
Guido van Rossum09638c12002-06-13 19:17:46 +000016 PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
17 so that the mapping wins when both
18 the mapping and the sequence define
19 a given operator (e.g. __getitem__).
20 see add_operators() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000021 PyBufferProcs as_buffer;
22 PyObject *name, *slots;
23 PyMemberDef members[1];
24} etype;
25
Guido van Rossum6f799372001-09-20 20:46:19 +000026static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000027 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
28 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
29 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000030 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000031 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
32 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
33 {"__dictoffset__", T_LONG,
34 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000035 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
36 {0}
37};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000038
Guido van Rossumc0b618a1997-05-02 03:12:38 +000039static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000040type_name(PyTypeObject *type, void *context)
41{
42 char *s;
43
44 s = strrchr(type->tp_name, '.');
45 if (s == NULL)
46 s = type->tp_name;
47 else
48 s++;
49 return PyString_FromString(s);
50}
51
Michael W. Hudson98bbc492002-11-26 14:47:27 +000052static int
53type_set_name(PyTypeObject *type, PyObject *value, void *context)
54{
55 etype* et;
56
57 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
58 PyErr_Format(PyExc_TypeError,
59 "can't set %s.__name__", type->tp_name);
60 return -1;
61 }
62 if (!value) {
63 PyErr_Format(PyExc_TypeError,
64 "can't delete %s.__name__", type->tp_name);
65 return -1;
66 }
67 if (!PyString_Check(value)) {
68 PyErr_Format(PyExc_TypeError,
69 "can only assign string to %s.__name__, not '%s'",
70 type->tp_name, value->ob_type->tp_name);
71 return -1;
72 }
73 if (strlen(PyString_AS_STRING(value))
74 != (size_t)PyString_GET_SIZE(value)) {
75 PyErr_Format(PyExc_ValueError,
76 "__name__ must not contain null bytes");
77 return -1;
78 }
79
80 et = (etype*)type;
81
82 Py_INCREF(value);
83
84 Py_DECREF(et->name);
85 et->name = value;
86
87 type->tp_name = PyString_AS_STRING(value);
88
89 return 0;
90}
91
Guido van Rossumc3542212001-08-16 09:18:56 +000092static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000093type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000094{
Guido van Rossumc3542212001-08-16 09:18:56 +000095 PyObject *mod;
96 char *s;
97
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(type->tp_name,
101 (int)(s - type->tp_name));
102 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
103 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +0000104 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000105 if (mod != NULL) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000106 Py_INCREF(mod);
107 return mod;
108 }
109 PyErr_SetString(PyExc_AttributeError, "__module__");
110 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000111}
112
Guido van Rossum3926a632001-09-25 16:25:58 +0000113static int
114type_set_module(PyTypeObject *type, PyObject *value, void *context)
115{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000116 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000117 PyErr_Format(PyExc_TypeError,
118 "can't set %s.__module__", type->tp_name);
119 return -1;
120 }
121 if (!value) {
122 PyErr_Format(PyExc_TypeError,
123 "can't delete %s.__module__", type->tp_name);
124 return -1;
125 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000126
Guido van Rossum3926a632001-09-25 16:25:58 +0000127 return PyDict_SetItemString(type->tp_dict, "__module__", value);
128}
129
Tim Peters6d6c1a32001-08-02 04:15:00 +0000130static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000131type_get_bases(PyTypeObject *type, void *context)
132{
133 Py_INCREF(type->tp_bases);
134 return type->tp_bases;
135}
136
137static PyTypeObject *best_base(PyObject *);
138static int mro_internal(PyTypeObject *);
139static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
140static int add_subclass(PyTypeObject*, PyTypeObject*);
141static void remove_subclass(PyTypeObject *, PyTypeObject *);
142static void update_all_slots(PyTypeObject *);
143
144static int
145mro_subclasses(PyTypeObject *type)
146{
147 PyTypeObject *subclass;
148 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudsonac74f5d2002-11-26 17:49:11 +0000149 int i, n, r = 0;
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;
167 r = -1;
168 }
169 else {
170 Py_DECREF(old_mro);
171 }
172 if (mro_subclasses(subclass) < 0)
173 r = -1;
174 }
175 return r;
176}
177
178static int
179type_set_bases(PyTypeObject *type, PyObject *value, void *context)
180{
181 int i, r = 0;
182 PyObject* ob;
183 PyTypeObject *new_base, *old_base;
184 PyObject *old_bases, *old_mro;
185
186 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
187 PyErr_Format(PyExc_TypeError,
188 "can't set %s.__bases__", type->tp_name);
189 return -1;
190 }
191 if (!value) {
192 PyErr_Format(PyExc_TypeError,
193 "can't delete %s.__bases__", type->tp_name);
194 return -1;
195 }
196 if (!PyTuple_Check(value)) {
197 PyErr_Format(PyExc_TypeError,
198 "can only assign tuple to %s.__bases__, not %s",
199 type->tp_name, value->ob_type->tp_name);
200 return -1;
201 }
202 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
203 ob = PyTuple_GET_ITEM(value, i);
204 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
205 PyErr_Format(
206 PyExc_TypeError,
207 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
208 type->tp_name, ob->ob_type->tp_name);
209 return -1;
210 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000211 if (PyType_Check(ob)) {
212 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
213 PyErr_SetString(PyExc_TypeError,
214 "a __bases__ item causes an inheritance cycle");
215 return -1;
216 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000217 }
218 }
219
220 new_base = best_base(value);
221
222 if (!new_base) {
223 return -1;
224 }
225
226 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
227 return -1;
228
229 Py_INCREF(new_base);
230 Py_INCREF(value);
231
232 old_bases = type->tp_bases;
233 old_base = type->tp_base;
234 old_mro = type->tp_mro;
235
236 type->tp_bases = value;
237 type->tp_base = new_base;
238
239 if (mro_internal(type) < 0) {
240 type->tp_bases = old_bases;
241 type->tp_base = old_base;
242 type->tp_mro = old_mro;
243
244 Py_DECREF(value);
245 Py_DECREF(new_base);
246
247 return -1;
248 }
249
250 if (mro_subclasses(type) < 0)
251 r = -1;
252
253 /* any base that was in __bases__ but now isn't, we
254 need to remove |type| from it's tp_subclasses.
255 conversely, any class now in __bases__ that wasn't
256 needs to have |type| added to it's subclasses. */
257
258 /* for now, sod that: just remove from all old_bases,
259 add to all new_bases */
260
261 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
262 ob = PyTuple_GET_ITEM(old_bases, i);
263 if (PyType_Check(ob)) {
264 remove_subclass(
265 (PyTypeObject*)ob, type);
266 }
267 }
268
269 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
270 ob = PyTuple_GET_ITEM(value, i);
271 if (PyType_Check(ob)) {
272 if (add_subclass((PyTypeObject*)ob, type) < 0)
273 r = -1;
274 }
275 }
276
277 update_all_slots(type);
278
279 Py_DECREF(old_bases);
280 Py_DECREF(old_base);
281 Py_DECREF(old_mro);
282
283 return r;
284}
285
286static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000287type_dict(PyTypeObject *type, void *context)
288{
289 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290 Py_INCREF(Py_None);
291 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000292 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000293 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000294}
295
Tim Peters24008312002-03-17 18:56:20 +0000296static PyObject *
297type_get_doc(PyTypeObject *type, void *context)
298{
299 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000300 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000301 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000302 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000303 if (result == NULL) {
304 result = Py_None;
305 Py_INCREF(result);
306 }
307 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000308 result = result->ob_type->tp_descr_get(result, NULL,
309 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000310 }
311 else {
312 Py_INCREF(result);
313 }
Tim Peters24008312002-03-17 18:56:20 +0000314 return result;
315}
316
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000317static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000318 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
319 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000320 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000321 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000322 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000323 {0}
324};
325
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000326static int
327type_compare(PyObject *v, PyObject *w)
328{
329 /* This is called with type objects only. So we
330 can just compare the addresses. */
331 Py_uintptr_t vv = (Py_uintptr_t)v;
332 Py_uintptr_t ww = (Py_uintptr_t)w;
333 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
334}
335
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000336static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000337type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000339 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000340 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000341
342 mod = type_module(type, NULL);
343 if (mod == NULL)
344 PyErr_Clear();
345 else if (!PyString_Check(mod)) {
346 Py_DECREF(mod);
347 mod = NULL;
348 }
349 name = type_name(type, NULL);
350 if (name == NULL)
351 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000352
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000353 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
354 kind = "class";
355 else
356 kind = "type";
357
Barry Warsaw7ce36942001-08-24 18:34:26 +0000358 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000359 rtn = PyString_FromFormat("<%s '%s.%s'>",
360 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000361 PyString_AS_STRING(mod),
362 PyString_AS_STRING(name));
363 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000364 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000365 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000366
Guido van Rossumc3542212001-08-16 09:18:56 +0000367 Py_XDECREF(mod);
368 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000369 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000370}
371
Tim Peters6d6c1a32001-08-02 04:15:00 +0000372static PyObject *
373type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
374{
375 PyObject *obj;
376
377 if (type->tp_new == NULL) {
378 PyErr_Format(PyExc_TypeError,
379 "cannot create '%.100s' instances",
380 type->tp_name);
381 return NULL;
382 }
383
Tim Peters3f996e72001-09-13 19:18:27 +0000384 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000385 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000386 /* Ugly exception: when the call was type(something),
387 don't call tp_init on the result. */
388 if (type == &PyType_Type &&
389 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
390 (kwds == NULL ||
391 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
392 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000393 /* If the returned object is not an instance of type,
394 it won't be initialized. */
395 if (!PyType_IsSubtype(obj->ob_type, type))
396 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000397 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000398 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
399 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000400 type->tp_init(obj, args, kwds) < 0) {
401 Py_DECREF(obj);
402 obj = NULL;
403 }
404 }
405 return obj;
406}
407
408PyObject *
409PyType_GenericAlloc(PyTypeObject *type, int nitems)
410{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000411 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000412 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000413
414 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000415 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000416 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000417 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000418
Neil Schemenauerc806c882001-08-29 23:54:54 +0000419 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000420 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000421
Neil Schemenauerc806c882001-08-29 23:54:54 +0000422 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000423
Tim Peters6d6c1a32001-08-02 04:15:00 +0000424 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
425 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000426
Tim Peters6d6c1a32001-08-02 04:15:00 +0000427 if (type->tp_itemsize == 0)
428 PyObject_INIT(obj, type);
429 else
430 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000431
Tim Peters6d6c1a32001-08-02 04:15:00 +0000432 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000433 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000434 return obj;
435}
436
437PyObject *
438PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
439{
440 return type->tp_alloc(type, 0);
441}
442
Guido van Rossum9475a232001-10-05 20:51:39 +0000443/* Helpers for subtyping */
444
445static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000446traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
447{
448 int i, n;
449 PyMemberDef *mp;
450
451 n = type->ob_size;
452 mp = ((etype *)type)->members;
453 for (i = 0; i < n; i++, mp++) {
454 if (mp->type == T_OBJECT_EX) {
455 char *addr = (char *)self + mp->offset;
456 PyObject *obj = *(PyObject **)addr;
457 if (obj != NULL) {
458 int err = visit(obj, arg);
459 if (err)
460 return err;
461 }
462 }
463 }
464 return 0;
465}
466
467static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000468subtype_traverse(PyObject *self, visitproc visit, void *arg)
469{
470 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000471 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000472
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000473 /* Find the nearest base with a different tp_traverse,
474 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000475 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000476 base = type;
477 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
478 if (base->ob_size) {
479 int err = traverse_slots(base, self, visit, arg);
480 if (err)
481 return err;
482 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000483 base = base->tp_base;
484 assert(base);
485 }
486
487 if (type->tp_dictoffset != base->tp_dictoffset) {
488 PyObject **dictptr = _PyObject_GetDictPtr(self);
489 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000490 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000491 if (err)
492 return err;
493 }
494 }
495
Guido van Rossuma3862092002-06-10 15:24:42 +0000496 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
497 /* For a heaptype, the instances count as references
498 to the type. Traverse the type so the collector
499 can find cycles involving this link. */
500 int err = visit((PyObject *)type, arg);
501 if (err)
502 return err;
503 }
504
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000505 if (basetraverse)
506 return basetraverse(self, visit, arg);
507 return 0;
508}
509
510static void
511clear_slots(PyTypeObject *type, PyObject *self)
512{
513 int i, n;
514 PyMemberDef *mp;
515
516 n = type->ob_size;
517 mp = ((etype *)type)->members;
518 for (i = 0; i < n; i++, mp++) {
519 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
520 char *addr = (char *)self + mp->offset;
521 PyObject *obj = *(PyObject **)addr;
522 if (obj != NULL) {
523 Py_DECREF(obj);
524 *(PyObject **)addr = NULL;
525 }
526 }
527 }
528}
529
530static int
531subtype_clear(PyObject *self)
532{
533 PyTypeObject *type, *base;
534 inquiry baseclear;
535
536 /* Find the nearest base with a different tp_clear
537 and clear slots while we're at it */
538 type = self->ob_type;
539 base = type;
540 while ((baseclear = base->tp_clear) == subtype_clear) {
541 if (base->ob_size)
542 clear_slots(base, self);
543 base = base->tp_base;
544 assert(base);
545 }
546
Guido van Rossuma3862092002-06-10 15:24:42 +0000547 /* There's no need to clear the instance dict (if any);
548 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000549
550 if (baseclear)
551 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000552 return 0;
553}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000554
555static void
556subtype_dealloc(PyObject *self)
557{
Guido van Rossum14227b42001-12-06 02:35:58 +0000558 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000559 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000560
Guido van Rossum22b13872002-08-06 21:41:44 +0000561 /* Extract the type; we expect it to be a heap type */
562 type = self->ob_type;
563 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000564
Guido van Rossum22b13872002-08-06 21:41:44 +0000565 /* Test whether the type has GC exactly once */
566
567 if (!PyType_IS_GC(type)) {
568 /* It's really rare to find a dynamic type that doesn't have
569 GC; it can only happen when deriving from 'object' and not
570 adding any slots or instance variables. This allows
571 certain simplifications: there's no need to call
572 clear_slots(), or DECREF the dict, or clear weakrefs. */
573
574 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000575 if (type->tp_del) {
576 type->tp_del(self);
577 if (self->ob_refcnt > 0)
578 return;
579 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000580
581 /* Find the nearest base with a different tp_dealloc */
582 base = type;
583 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
584 assert(base->ob_size == 0);
585 base = base->tp_base;
586 assert(base);
587 }
588
589 /* Call the base tp_dealloc() */
590 assert(basedealloc);
591 basedealloc(self);
592
593 /* Can't reference self beyond this point */
594 Py_DECREF(type);
595
596 /* Done */
597 return;
598 }
599
600 /* We get here only if the type has GC */
601
602 /* UnTrack and re-Track around the trashcan macro, alas */
Guido van Rossum0906e072002-08-07 20:42:09 +0000603 PyObject_GC_UnTrack(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000604 Py_TRASHCAN_SAFE_BEGIN(self);
605 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
606
607 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000608 if (type->tp_del) {
609 type->tp_del(self);
610 if (self->ob_refcnt > 0)
611 goto endlabel;
612 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000613
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000614 /* Find the nearest base with a different tp_dealloc
615 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000616 base = type;
617 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
618 if (base->ob_size)
619 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000620 base = base->tp_base;
621 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000622 }
623
Tim Peters6d6c1a32001-08-02 04:15:00 +0000624 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000625 if (type->tp_dictoffset && !base->tp_dictoffset) {
626 PyObject **dictptr = _PyObject_GetDictPtr(self);
627 if (dictptr != NULL) {
628 PyObject *dict = *dictptr;
629 if (dict != NULL) {
630 Py_DECREF(dict);
631 *dictptr = NULL;
632 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000633 }
634 }
635
Guido van Rossum9676b222001-08-17 20:32:36 +0000636 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000637 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000638 PyObject_ClearWeakRefs(self);
639
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000641 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000642 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000643
644 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000645 assert(basedealloc);
646 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000647
648 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000649 Py_DECREF(type);
650
Guido van Rossum0906e072002-08-07 20:42:09 +0000651 endlabel:
Guido van Rossum22b13872002-08-06 21:41:44 +0000652 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000653}
654
Jeremy Hylton938ace62002-07-17 16:30:39 +0000655static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000656
Tim Peters6d6c1a32001-08-02 04:15:00 +0000657/* type test with subclassing support */
658
659int
660PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
661{
662 PyObject *mro;
663
Guido van Rossum9478d072001-09-07 18:52:13 +0000664 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
665 return b == a || b == &PyBaseObject_Type;
666
Tim Peters6d6c1a32001-08-02 04:15:00 +0000667 mro = a->tp_mro;
668 if (mro != NULL) {
669 /* Deal with multiple inheritance without recursion
670 by walking the MRO tuple */
671 int i, n;
672 assert(PyTuple_Check(mro));
673 n = PyTuple_GET_SIZE(mro);
674 for (i = 0; i < n; i++) {
675 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
676 return 1;
677 }
678 return 0;
679 }
680 else {
681 /* a is not completely initilized yet; follow tp_base */
682 do {
683 if (a == b)
684 return 1;
685 a = a->tp_base;
686 } while (a != NULL);
687 return b == &PyBaseObject_Type;
688 }
689}
690
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000691/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000692 without looking in the instance dictionary
693 (so we can't use PyObject_GetAttr) but still binding
694 it to the instance. The arguments are the object,
695 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000696 static variable used to cache the interned Python string.
697
698 Two variants:
699
700 - lookup_maybe() returns NULL without raising an exception
701 when the _PyType_Lookup() call fails;
702
703 - lookup_method() always raises an exception upon errors.
704*/
Guido van Rossum60718732001-08-28 17:47:51 +0000705
706static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000707lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000708{
709 PyObject *res;
710
711 if (*attrobj == NULL) {
712 *attrobj = PyString_InternFromString(attrstr);
713 if (*attrobj == NULL)
714 return NULL;
715 }
716 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000717 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000718 descrgetfunc f;
719 if ((f = res->ob_type->tp_descr_get) == NULL)
720 Py_INCREF(res);
721 else
722 res = f(res, self, (PyObject *)(self->ob_type));
723 }
724 return res;
725}
726
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000727static PyObject *
728lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
729{
730 PyObject *res = lookup_maybe(self, attrstr, attrobj);
731 if (res == NULL && !PyErr_Occurred())
732 PyErr_SetObject(PyExc_AttributeError, *attrobj);
733 return res;
734}
735
Guido van Rossum2730b132001-08-28 18:22:14 +0000736/* A variation of PyObject_CallMethod that uses lookup_method()
737 instead of PyObject_GetAttrString(). This uses the same convention
738 as lookup_method to cache the interned name string object. */
739
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000740static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000741call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
742{
743 va_list va;
744 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000745 va_start(va, format);
746
Guido van Rossumda21c012001-10-03 00:50:18 +0000747 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000748 if (func == NULL) {
749 va_end(va);
750 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000751 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000752 return NULL;
753 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000754
755 if (format && *format)
756 args = Py_VaBuildValue(format, va);
757 else
758 args = PyTuple_New(0);
759
760 va_end(va);
761
762 if (args == NULL)
763 return NULL;
764
765 assert(PyTuple_Check(args));
766 retval = PyObject_Call(func, args, NULL);
767
768 Py_DECREF(args);
769 Py_DECREF(func);
770
771 return retval;
772}
773
774/* Clone of call_method() that returns NotImplemented when the lookup fails. */
775
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000776static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000777call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
778{
779 va_list va;
780 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000781 va_start(va, format);
782
Guido van Rossumda21c012001-10-03 00:50:18 +0000783 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000784 if (func == NULL) {
785 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000786 if (!PyErr_Occurred()) {
787 Py_INCREF(Py_NotImplemented);
788 return Py_NotImplemented;
789 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000790 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000791 }
792
793 if (format && *format)
794 args = Py_VaBuildValue(format, va);
795 else
796 args = PyTuple_New(0);
797
798 va_end(va);
799
Guido van Rossum717ce002001-09-14 16:58:08 +0000800 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000801 return NULL;
802
Guido van Rossum717ce002001-09-14 16:58:08 +0000803 assert(PyTuple_Check(args));
804 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000805
806 Py_DECREF(args);
807 Py_DECREF(func);
808
809 return retval;
810}
811
Tim Petersa91e9642001-11-14 23:32:33 +0000812static int
813fill_classic_mro(PyObject *mro, PyObject *cls)
814{
815 PyObject *bases, *base;
816 int i, n;
817
818 assert(PyList_Check(mro));
819 assert(PyClass_Check(cls));
820 i = PySequence_Contains(mro, cls);
821 if (i < 0)
822 return -1;
823 if (!i) {
824 if (PyList_Append(mro, cls) < 0)
825 return -1;
826 }
827 bases = ((PyClassObject *)cls)->cl_bases;
828 assert(bases && PyTuple_Check(bases));
829 n = PyTuple_GET_SIZE(bases);
830 for (i = 0; i < n; i++) {
831 base = PyTuple_GET_ITEM(bases, i);
832 if (fill_classic_mro(mro, base) < 0)
833 return -1;
834 }
835 return 0;
836}
837
838static PyObject *
839classic_mro(PyObject *cls)
840{
841 PyObject *mro;
842
843 assert(PyClass_Check(cls));
844 mro = PyList_New(0);
845 if (mro != NULL) {
846 if (fill_classic_mro(mro, cls) == 0)
847 return mro;
848 Py_DECREF(mro);
849 }
850 return NULL;
851}
852
Guido van Rossum1f121312002-11-14 19:49:16 +0000853/*
854 Method resolution order algorithm C3 described in
855 "A Monotonic Superclass Linearization for Dylan",
856 by Kim Barrett, Bob Cassel, Paul Haahr,
857 David A. Moon, Keith Playford, and P. Tucker Withington.
858 (OOPSLA 1996)
859
Guido van Rossum98f33732002-11-25 21:36:54 +0000860 Some notes about the rules implied by C3:
861
862 No duplicate bases.
863 It isn't legal to repeat a class in a list of base classes.
864
865 The next three properties are the 3 constraints in "C3".
866
867 Local precendece order.
868 If A precedes B in C's MRO, then A will precede B in the MRO of all
869 subclasses of C.
870
871 Monotonicity.
872 The MRO of a class must be an extension without reordering of the
873 MRO of each of its superclasses.
874
875 Extended Precedence Graph (EPG).
876 Linearization is consistent if there is a path in the EPG from
877 each class to all its successors in the linearization. See
878 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000879 */
880
881static int
882tail_contains(PyObject *list, int whence, PyObject *o) {
883 int j, size;
884 size = PyList_GET_SIZE(list);
885
886 for (j = whence+1; j < size; j++) {
887 if (PyList_GET_ITEM(list, j) == o)
888 return 1;
889 }
890 return 0;
891}
892
Guido van Rossum98f33732002-11-25 21:36:54 +0000893static PyObject *
894class_name(PyObject *cls)
895{
896 PyObject *name = PyObject_GetAttrString(cls, "__name__");
897 if (name == NULL) {
898 PyErr_Clear();
899 Py_XDECREF(name);
900 name = PyObject_Repr(cls);
901 }
902 if (name == NULL)
903 return NULL;
904 if (!PyString_Check(name)) {
905 Py_DECREF(name);
906 return NULL;
907 }
908 return name;
909}
910
911static int
912check_duplicates(PyObject *list)
913{
914 int i, j, n;
915 /* Let's use a quadratic time algorithm,
916 assuming that the bases lists is short.
917 */
918 n = PyList_GET_SIZE(list);
919 for (i = 0; i < n; i++) {
920 PyObject *o = PyList_GET_ITEM(list, i);
921 for (j = i + 1; j < n; j++) {
922 if (PyList_GET_ITEM(list, j) == o) {
923 o = class_name(o);
924 PyErr_Format(PyExc_TypeError,
925 "duplicate base class %s",
926 o ? PyString_AS_STRING(o) : "?");
927 Py_XDECREF(o);
928 return -1;
929 }
930 }
931 }
932 return 0;
933}
934
935/* Raise a TypeError for an MRO order disagreement.
936
937 It's hard to produce a good error message. In the absence of better
938 insight into error reporting, report the classes that were candidates
939 to be put next into the MRO. There is some conflict between the
940 order in which they should be put in the MRO, but it's hard to
941 diagnose what constraint can't be satisfied.
942*/
943
944static void
945set_mro_error(PyObject *to_merge, int *remain)
946{
947 int i, n, off, to_merge_size;
948 char buf[1000];
949 PyObject *k, *v;
950 PyObject *set = PyDict_New();
951
952 to_merge_size = PyList_GET_SIZE(to_merge);
953 for (i = 0; i < to_merge_size; i++) {
954 PyObject *L = PyList_GET_ITEM(to_merge, i);
955 if (remain[i] < PyList_GET_SIZE(L)) {
956 PyObject *c = PyList_GET_ITEM(L, remain[i]);
957 if (PyDict_SetItem(set, c, Py_None) < 0)
958 return;
959 }
960 }
961 n = PyDict_Size(set);
962
963 off = PyOS_snprintf(buf, sizeof(buf), "MRO conflict among bases");
964 i = 0;
965 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
966 PyObject *name = class_name(k);
967 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
968 name ? PyString_AS_STRING(name) : "?");
969 Py_XDECREF(name);
970 if (--n && off+1 < sizeof(buf)) {
971 buf[off++] = ',';
972 buf[off] = '\0';
973 }
974 }
975 PyErr_SetString(PyExc_TypeError, buf);
976 Py_DECREF(set);
977}
978
Guido van Rossum1f121312002-11-14 19:49:16 +0000979static int
980pmerge(PyObject *acc, PyObject* to_merge) {
981 int i, j, to_merge_size;
982 int *remain;
983 int ok, empty_cnt;
984
985 to_merge_size = PyList_GET_SIZE(to_merge);
986
Guido van Rossum98f33732002-11-25 21:36:54 +0000987 /* remain stores an index into each sublist of to_merge.
988 remain[i] is the index of the next base in to_merge[i]
989 that is not included in acc.
990 */
Guido van Rossum1f121312002-11-14 19:49:16 +0000991 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
992 if (remain == NULL)
993 return -1;
994 for (i = 0; i < to_merge_size; i++)
995 remain[i] = 0;
996
997 again:
998 empty_cnt = 0;
999 for (i = 0; i < to_merge_size; i++) {
1000 PyObject *candidate;
1001
1002 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1003
1004 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1005 empty_cnt++;
1006 continue;
1007 }
1008
Guido van Rossum98f33732002-11-25 21:36:54 +00001009 /* Choose next candidate for MRO.
1010
1011 The input sequences alone can determine the choice.
1012 If not, choose the class which appears in the MRO
1013 of the earliest direct superclass of the new class.
1014 */
1015
Guido van Rossum1f121312002-11-14 19:49:16 +00001016 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1017 for (j = 0; j < to_merge_size; j++) {
1018 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001019 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001020 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001021 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001022 }
1023 ok = PyList_Append(acc, candidate);
1024 if (ok < 0) {
1025 PyMem_Free(remain);
1026 return -1;
1027 }
1028 for (j = 0; j < to_merge_size; j++) {
1029 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1030 if (PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1031 remain[j]++;
1032 }
1033 }
1034 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001035 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001036 }
1037
Guido van Rossum98f33732002-11-25 21:36:54 +00001038 if (empty_cnt == to_merge_size) {
1039 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001040 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001041 }
1042 set_mro_error(to_merge, remain);
1043 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001044 return -1;
1045}
1046
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047static PyObject *
1048mro_implementation(PyTypeObject *type)
1049{
1050 int i, n, ok;
1051 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001052 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001053
Guido van Rossum63517572002-06-18 16:44:57 +00001054 if(type->tp_dict == NULL) {
1055 if(PyType_Ready(type) < 0)
1056 return NULL;
1057 }
1058
Guido van Rossum98f33732002-11-25 21:36:54 +00001059 /* Find a superclass linearization that honors the constraints
1060 of the explicit lists of bases and the constraints implied by
1061 each base class.
1062
1063 to_merge is a list of lists, where each list is a superclass
1064 linearization implied by a base class. The last element of
1065 to_merge is the declared list of bases.
1066 */
1067
Tim Peters6d6c1a32001-08-02 04:15:00 +00001068 bases = type->tp_bases;
1069 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001070
1071 to_merge = PyList_New(n+1);
1072 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001073 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001074
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001076 PyObject *base = PyTuple_GET_ITEM(bases, i);
1077 PyObject *parentMRO;
1078 if (PyType_Check(base))
1079 parentMRO = PySequence_List(
1080 ((PyTypeObject*)base)->tp_mro);
1081 else
1082 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001084 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001085 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001086 }
1087
1088 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001089 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001090
1091 bases_aslist = PySequence_List(bases);
1092 if (bases_aslist == NULL) {
1093 Py_DECREF(to_merge);
1094 return NULL;
1095 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001096 /* This is just a basic sanity check. */
1097 if (check_duplicates(bases_aslist) < 0) {
1098 Py_DECREF(to_merge);
1099 Py_DECREF(bases_aslist);
1100 return NULL;
1101 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001102 PyList_SET_ITEM(to_merge, n, bases_aslist);
1103
1104 result = Py_BuildValue("[O]", (PyObject *)type);
1105 if (result == NULL) {
1106 Py_DECREF(to_merge);
1107 return NULL;
1108 }
1109
1110 ok = pmerge(result, to_merge);
1111 Py_DECREF(to_merge);
1112 if (ok < 0) {
1113 Py_DECREF(result);
1114 return NULL;
1115 }
1116
Tim Peters6d6c1a32001-08-02 04:15:00 +00001117 return result;
1118}
1119
1120static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001121mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122{
1123 PyTypeObject *type = (PyTypeObject *)self;
1124
Tim Peters6d6c1a32001-08-02 04:15:00 +00001125 return mro_implementation(type);
1126}
1127
1128static int
1129mro_internal(PyTypeObject *type)
1130{
1131 PyObject *mro, *result, *tuple;
1132
1133 if (type->ob_type == &PyType_Type) {
1134 result = mro_implementation(type);
1135 }
1136 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001137 static PyObject *mro_str;
1138 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139 if (mro == NULL)
1140 return -1;
1141 result = PyObject_CallObject(mro, NULL);
1142 Py_DECREF(mro);
1143 }
1144 if (result == NULL)
1145 return -1;
1146 tuple = PySequence_Tuple(result);
1147 Py_DECREF(result);
1148 type->tp_mro = tuple;
1149 return 0;
1150}
1151
1152
1153/* Calculate the best base amongst multiple base classes.
1154 This is the first one that's on the path to the "solid base". */
1155
1156static PyTypeObject *
1157best_base(PyObject *bases)
1158{
1159 int i, n;
1160 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001161 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001162
1163 assert(PyTuple_Check(bases));
1164 n = PyTuple_GET_SIZE(bases);
1165 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001166 base = NULL;
1167 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001169 base_proto = PyTuple_GET_ITEM(bases, i);
1170 if (PyClass_Check(base_proto))
1171 continue;
1172 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173 PyErr_SetString(
1174 PyExc_TypeError,
1175 "bases must be types");
1176 return NULL;
1177 }
Tim Petersa91e9642001-11-14 23:32:33 +00001178 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001179 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001180 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001181 return NULL;
1182 }
1183 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001184 if (winner == NULL) {
1185 winner = candidate;
1186 base = base_i;
1187 }
1188 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 ;
1190 else if (PyType_IsSubtype(candidate, winner)) {
1191 winner = candidate;
1192 base = base_i;
1193 }
1194 else {
1195 PyErr_SetString(
1196 PyExc_TypeError,
1197 "multiple bases have "
1198 "instance lay-out conflict");
1199 return NULL;
1200 }
1201 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001202 if (base == NULL)
1203 PyErr_SetString(PyExc_TypeError,
1204 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001205 return base;
1206}
1207
1208static int
1209extra_ivars(PyTypeObject *type, PyTypeObject *base)
1210{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001211 size_t t_size = type->tp_basicsize;
1212 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213
Guido van Rossum9676b222001-08-17 20:32:36 +00001214 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215 if (type->tp_itemsize || base->tp_itemsize) {
1216 /* If itemsize is involved, stricter rules */
1217 return t_size != b_size ||
1218 type->tp_itemsize != base->tp_itemsize;
1219 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001220 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1221 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1222 t_size -= sizeof(PyObject *);
1223 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1224 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1225 t_size -= sizeof(PyObject *);
1226
1227 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001228}
1229
1230static PyTypeObject *
1231solid_base(PyTypeObject *type)
1232{
1233 PyTypeObject *base;
1234
1235 if (type->tp_base)
1236 base = solid_base(type->tp_base);
1237 else
1238 base = &PyBaseObject_Type;
1239 if (extra_ivars(type, base))
1240 return type;
1241 else
1242 return base;
1243}
1244
Jeremy Hylton938ace62002-07-17 16:30:39 +00001245static void object_dealloc(PyObject *);
1246static int object_init(PyObject *, PyObject *, PyObject *);
1247static int update_slot(PyTypeObject *, PyObject *);
1248static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249
1250static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001251subtype_dict(PyObject *obj, void *context)
1252{
1253 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1254 PyObject *dict;
1255
1256 if (dictptr == NULL) {
1257 PyErr_SetString(PyExc_AttributeError,
1258 "This object has no __dict__");
1259 return NULL;
1260 }
1261 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001262 if (dict == NULL)
1263 *dictptr = dict = PyDict_New();
1264 Py_XINCREF(dict);
1265 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001266}
1267
Guido van Rossum6661be32001-10-26 04:26:12 +00001268static int
1269subtype_setdict(PyObject *obj, PyObject *value, void *context)
1270{
1271 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1272 PyObject *dict;
1273
1274 if (dictptr == NULL) {
1275 PyErr_SetString(PyExc_AttributeError,
1276 "This object has no __dict__");
1277 return -1;
1278 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001279 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001280 PyErr_SetString(PyExc_TypeError,
1281 "__dict__ must be set to a dictionary");
1282 return -1;
1283 }
1284 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001285 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001286 *dictptr = value;
1287 Py_XDECREF(dict);
1288 return 0;
1289}
1290
Guido van Rossumad47da02002-08-12 19:05:44 +00001291static PyObject *
1292subtype_getweakref(PyObject *obj, void *context)
1293{
1294 PyObject **weaklistptr;
1295 PyObject *result;
1296
1297 if (obj->ob_type->tp_weaklistoffset == 0) {
1298 PyErr_SetString(PyExc_AttributeError,
1299 "This object has no __weaklist__");
1300 return NULL;
1301 }
1302 assert(obj->ob_type->tp_weaklistoffset > 0);
1303 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001304 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001305 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001306 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001307 if (*weaklistptr == NULL)
1308 result = Py_None;
1309 else
1310 result = *weaklistptr;
1311 Py_INCREF(result);
1312 return result;
1313}
1314
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001315static PyGetSetDef subtype_getsets[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001316 /* Not all objects have these attributes!
1317 The descriptor's __get__ method may raise AttributeError. */
1318 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001319 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001320 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001321 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001322 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001323};
1324
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001325/* bozo: __getstate__ that raises TypeError */
1326
1327static PyObject *
1328bozo_func(PyObject *self, PyObject *args)
1329{
1330 PyErr_SetString(PyExc_TypeError,
1331 "a class that defines __slots__ without "
1332 "defining __getstate__ cannot be pickled");
1333 return NULL;
1334}
1335
Neal Norwitz93c1e232002-03-31 16:06:11 +00001336static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001337
1338static PyObject *bozo_obj = NULL;
1339
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001340static int
1341valid_identifier(PyObject *s)
1342{
Guido van Rossum03013a02002-07-16 14:30:28 +00001343 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001344 int i, n;
1345
1346 if (!PyString_Check(s)) {
1347 PyErr_SetString(PyExc_TypeError,
1348 "__slots__ must be strings");
1349 return 0;
1350 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001351 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001352 n = PyString_GET_SIZE(s);
1353 /* We must reject an empty name. As a hack, we bump the
1354 length to 1 so that the loop will balk on the trailing \0. */
1355 if (n == 0)
1356 n = 1;
1357 for (i = 0; i < n; i++, p++) {
1358 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1359 PyErr_SetString(PyExc_TypeError,
1360 "__slots__ must be identifiers");
1361 return 0;
1362 }
1363 }
1364 return 1;
1365}
1366
Martin v. Löwisd919a592002-10-14 21:07:28 +00001367#ifdef Py_USING_UNICODE
1368/* Replace Unicode objects in slots. */
1369
1370static PyObject *
1371_unicode_to_string(PyObject *slots, int nslots)
1372{
1373 PyObject *tmp = slots;
1374 PyObject *o, *o1;
1375 int i;
1376 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1377 for (i = 0; i < nslots; i++) {
1378 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1379 if (tmp == slots) {
1380 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1381 if (tmp == NULL)
1382 return NULL;
1383 }
1384 o1 = _PyUnicode_AsDefaultEncodedString
1385 (o, NULL);
1386 if (o1 == NULL) {
1387 Py_DECREF(tmp);
1388 return 0;
1389 }
1390 Py_INCREF(o1);
1391 Py_DECREF(o);
1392 PyTuple_SET_ITEM(tmp, i, o1);
1393 }
1394 }
1395 return tmp;
1396}
1397#endif
1398
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001399static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001400type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1401{
1402 PyObject *name, *bases, *dict;
1403 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001404 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001405 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001406 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001407 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001408 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001409 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001410
Tim Peters3abca122001-10-27 19:37:48 +00001411 assert(args != NULL && PyTuple_Check(args));
1412 assert(kwds == NULL || PyDict_Check(kwds));
1413
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001414 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001415 {
1416 const int nargs = PyTuple_GET_SIZE(args);
1417 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1418
1419 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1420 PyObject *x = PyTuple_GET_ITEM(args, 0);
1421 Py_INCREF(x->ob_type);
1422 return (PyObject *) x->ob_type;
1423 }
1424
1425 /* SF bug 475327 -- if that didn't trigger, we need 3
1426 arguments. but PyArg_ParseTupleAndKeywords below may give
1427 a msg saying type() needs exactly 3. */
1428 if (nargs + nkwds != 3) {
1429 PyErr_SetString(PyExc_TypeError,
1430 "type() takes 1 or 3 arguments");
1431 return NULL;
1432 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001433 }
1434
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001435 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001436 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1437 &name,
1438 &PyTuple_Type, &bases,
1439 &PyDict_Type, &dict))
1440 return NULL;
1441
1442 /* Determine the proper metatype to deal with this,
1443 and check for metatype conflicts while we're at it.
1444 Note that if some other metatype wins to contract,
1445 it's possible that its instances are not types. */
1446 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001447 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001448 for (i = 0; i < nbases; i++) {
1449 tmp = PyTuple_GET_ITEM(bases, i);
1450 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001451 if (tmptype == &PyClass_Type)
1452 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001453 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001454 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001455 if (PyType_IsSubtype(tmptype, winner)) {
1456 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001457 continue;
1458 }
1459 PyErr_SetString(PyExc_TypeError,
1460 "metatype conflict among bases");
1461 return NULL;
1462 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001463 if (winner != metatype) {
1464 if (winner->tp_new != type_new) /* Pass it to the winner */
1465 return winner->tp_new(winner, args, kwds);
1466 metatype = winner;
1467 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468
1469 /* Adjust for empty tuple bases */
1470 if (nbases == 0) {
1471 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1472 if (bases == NULL)
1473 return NULL;
1474 nbases = 1;
1475 }
1476 else
1477 Py_INCREF(bases);
1478
1479 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1480
1481 /* Calculate best base, and check that all bases are type objects */
1482 base = best_base(bases);
1483 if (base == NULL)
1484 return NULL;
1485 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1486 PyErr_Format(PyExc_TypeError,
1487 "type '%.100s' is not an acceptable base type",
1488 base->tp_name);
1489 return NULL;
1490 }
1491
Tim Peters6d6c1a32001-08-02 04:15:00 +00001492 /* Check for a __slots__ sequence variable in dict, and count it */
1493 slots = PyDict_GetItemString(dict, "__slots__");
1494 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001495 add_dict = 0;
1496 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001497 may_add_dict = base->tp_dictoffset == 0;
1498 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1499 if (slots == NULL) {
1500 if (may_add_dict) {
1501 add_dict++;
1502 }
1503 if (may_add_weak) {
1504 add_weak++;
1505 }
1506 }
1507 else {
1508 /* Have slots */
1509
Tim Peters6d6c1a32001-08-02 04:15:00 +00001510 /* Make it into a tuple */
1511 if (PyString_Check(slots))
1512 slots = Py_BuildValue("(O)", slots);
1513 else
1514 slots = PySequence_Tuple(slots);
1515 if (slots == NULL)
1516 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001517 assert(PyTuple_Check(slots));
1518
1519 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001520 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001521 if (nslots > 0 && base->tp_itemsize != 0) {
1522 PyErr_Format(PyExc_TypeError,
1523 "nonempty __slots__ "
1524 "not supported for subtype of '%s'",
1525 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001526 bad_slots:
1527 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001528 return NULL;
1529 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001530
Martin v. Löwisd919a592002-10-14 21:07:28 +00001531#ifdef Py_USING_UNICODE
1532 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001533 if (tmp != slots) {
1534 Py_DECREF(slots);
1535 slots = tmp;
1536 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001537 if (!tmp)
1538 return NULL;
1539#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001540 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001541 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001542 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1543 char *s;
1544 if (!valid_identifier(tmp))
1545 goto bad_slots;
1546 assert(PyString_Check(tmp));
1547 s = PyString_AS_STRING(tmp);
1548 if (strcmp(s, "__dict__") == 0) {
1549 if (!may_add_dict || add_dict) {
1550 PyErr_SetString(PyExc_TypeError,
1551 "__dict__ slot disallowed: "
1552 "we already got one");
1553 goto bad_slots;
1554 }
1555 add_dict++;
1556 }
1557 if (strcmp(s, "__weakref__") == 0) {
1558 if (!may_add_weak || add_weak) {
1559 PyErr_SetString(PyExc_TypeError,
1560 "__weakref__ slot disallowed: "
1561 "either we already got one, "
1562 "or __itemsize__ != 0");
1563 goto bad_slots;
1564 }
1565 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001566 }
1567 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001568
Guido van Rossumad47da02002-08-12 19:05:44 +00001569 /* Copy slots into yet another tuple, demangling names */
1570 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001571 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001572 goto bad_slots;
1573 for (i = j = 0; i < nslots; i++) {
1574 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001575 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001576 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001577 s = PyString_AS_STRING(tmp);
1578 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1579 (add_weak && strcmp(s, "__weakref__") == 0))
1580 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001581 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001582 PyString_AS_STRING(tmp),
1583 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001584 {
1585 tmp = PyString_FromString(buffer);
1586 } else {
1587 Py_INCREF(tmp);
1588 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001589 PyTuple_SET_ITEM(newslots, j, tmp);
1590 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001591 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001592 assert(j == nslots - add_dict - add_weak);
1593 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001594 Py_DECREF(slots);
1595 slots = newslots;
1596
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001597 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001598 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001599 /* If not, provide a bozo that raises TypeError */
1600 if (bozo_obj == NULL) {
1601 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001602 if (bozo_obj == NULL)
1603 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001604 }
1605 if (PyDict_SetItemString(dict,
1606 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001607 bozo_obj) < 0)
1608 {
1609 Py_DECREF(bozo_obj);
1610 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001611 }
1612 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001613
1614 /* Secondary bases may provide weakrefs or dict */
1615 if (nbases > 1 &&
1616 ((may_add_dict && !add_dict) ||
1617 (may_add_weak && !add_weak))) {
1618 for (i = 0; i < nbases; i++) {
1619 tmp = PyTuple_GET_ITEM(bases, i);
1620 if (tmp == (PyObject *)base)
1621 continue; /* Skip primary base */
1622 if (PyClass_Check(tmp)) {
1623 /* Classic base class provides both */
1624 if (may_add_dict && !add_dict)
1625 add_dict++;
1626 if (may_add_weak && !add_weak)
1627 add_weak++;
1628 break;
1629 }
1630 assert(PyType_Check(tmp));
1631 tmptype = (PyTypeObject *)tmp;
1632 if (may_add_dict && !add_dict &&
1633 tmptype->tp_dictoffset != 0)
1634 add_dict++;
1635 if (may_add_weak && !add_weak &&
1636 tmptype->tp_weaklistoffset != 0)
1637 add_weak++;
1638 if (may_add_dict && !add_dict)
1639 continue;
1640 if (may_add_weak && !add_weak)
1641 continue;
1642 /* Nothing more to check */
1643 break;
1644 }
1645 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001646 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001647
1648 /* XXX From here until type is safely allocated,
1649 "return NULL" may leak slots! */
1650
1651 /* Allocate the type object */
1652 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001653 if (type == NULL) {
1654 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001656 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657
1658 /* Keep name and slots alive in the extended type object */
1659 et = (etype *)type;
1660 Py_INCREF(name);
1661 et->name = name;
1662 et->slots = slots;
1663
Guido van Rossumdc91b992001-08-08 22:26:22 +00001664 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001665 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1666 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001667 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1668 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001669
1670 /* It's a new-style number unless it specifically inherits any
1671 old-style numeric behavior */
1672 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1673 (base->tp_as_number == NULL))
1674 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1675
1676 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677 type->tp_as_number = &et->as_number;
1678 type->tp_as_sequence = &et->as_sequence;
1679 type->tp_as_mapping = &et->as_mapping;
1680 type->tp_as_buffer = &et->as_buffer;
1681 type->tp_name = PyString_AS_STRING(name);
1682
1683 /* Set tp_base and tp_bases */
1684 type->tp_bases = bases;
1685 Py_INCREF(base);
1686 type->tp_base = base;
1687
Guido van Rossum687ae002001-10-15 22:03:32 +00001688 /* Initialize tp_dict from passed-in dict */
1689 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690 if (dict == NULL) {
1691 Py_DECREF(type);
1692 return NULL;
1693 }
1694
Guido van Rossumc3542212001-08-16 09:18:56 +00001695 /* Set __module__ in the dict */
1696 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1697 tmp = PyEval_GetGlobals();
1698 if (tmp != NULL) {
1699 tmp = PyDict_GetItemString(tmp, "__name__");
1700 if (tmp != NULL) {
1701 if (PyDict_SetItemString(dict, "__module__",
1702 tmp) < 0)
1703 return NULL;
1704 }
1705 }
1706 }
1707
Tim Peters2f93e282001-10-04 05:27:00 +00001708 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001709 and is a string. The __doc__ accessor will first look for tp_doc;
1710 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001711 */
1712 {
1713 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1714 if (doc != NULL && PyString_Check(doc)) {
1715 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001716 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001717 if (type->tp_doc == NULL) {
1718 Py_DECREF(type);
1719 return NULL;
1720 }
1721 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1722 }
1723 }
1724
Tim Peters6d6c1a32001-08-02 04:15:00 +00001725 /* Special-case __new__: if it's a plain function,
1726 make it a static function */
1727 tmp = PyDict_GetItemString(dict, "__new__");
1728 if (tmp != NULL && PyFunction_Check(tmp)) {
1729 tmp = PyStaticMethod_New(tmp);
1730 if (tmp == NULL) {
1731 Py_DECREF(type);
1732 return NULL;
1733 }
1734 PyDict_SetItemString(dict, "__new__", tmp);
1735 Py_DECREF(tmp);
1736 }
1737
1738 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1739 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001740 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001741 if (slots != NULL) {
1742 for (i = 0; i < nslots; i++, mp++) {
1743 mp->name = PyString_AS_STRING(
1744 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001745 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001746 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001747 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001748 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001749 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001750 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001751 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001752 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001753 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001754 slotoffset += sizeof(PyObject *);
1755 }
1756 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001757 if (add_dict) {
1758 if (base->tp_itemsize)
1759 type->tp_dictoffset = -(long)sizeof(PyObject *);
1760 else
1761 type->tp_dictoffset = slotoffset;
1762 slotoffset += sizeof(PyObject *);
1763 }
1764 if (add_weak) {
1765 assert(!base->tp_itemsize);
1766 type->tp_weaklistoffset = slotoffset;
1767 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768 }
1769 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001770 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001771 type->tp_members = et->members;
Guido van Rossumad47da02002-08-12 19:05:44 +00001772 type->tp_getset = subtype_getsets;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001773
1774 /* Special case some slots */
1775 if (type->tp_dictoffset != 0 || nslots > 0) {
1776 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1777 type->tp_getattro = PyObject_GenericGetAttr;
1778 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1779 type->tp_setattro = PyObject_GenericSetAttr;
1780 }
1781 type->tp_dealloc = subtype_dealloc;
1782
Guido van Rossum9475a232001-10-05 20:51:39 +00001783 /* Enable GC unless there are really no instance variables possible */
1784 if (!(type->tp_basicsize == sizeof(PyObject) &&
1785 type->tp_itemsize == 0))
1786 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1787
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 /* Always override allocation strategy to use regular heap */
1789 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001790 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001791 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001792 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001793 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001794 }
1795 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001796 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001797
1798 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001799 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001800 Py_DECREF(type);
1801 return NULL;
1802 }
1803
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001804 /* Put the proper slots in place */
1805 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001806
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807 return (PyObject *)type;
1808}
1809
1810/* Internal API to look for a name through the MRO.
1811 This returns a borrowed reference, and doesn't set an exception! */
1812PyObject *
1813_PyType_Lookup(PyTypeObject *type, PyObject *name)
1814{
1815 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001816 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001817
Guido van Rossum687ae002001-10-15 22:03:32 +00001818 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001819 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001820
1821 /* If mro is NULL, the type is either not yet initialized
1822 by PyType_Ready(), or already cleared by type_clear().
1823 Either way the safest thing to do is to return NULL. */
1824 if (mro == NULL)
1825 return NULL;
1826
Tim Peters6d6c1a32001-08-02 04:15:00 +00001827 assert(PyTuple_Check(mro));
1828 n = PyTuple_GET_SIZE(mro);
1829 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001830 base = PyTuple_GET_ITEM(mro, i);
1831 if (PyClass_Check(base))
1832 dict = ((PyClassObject *)base)->cl_dict;
1833 else {
1834 assert(PyType_Check(base));
1835 dict = ((PyTypeObject *)base)->tp_dict;
1836 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001837 assert(dict && PyDict_Check(dict));
1838 res = PyDict_GetItem(dict, name);
1839 if (res != NULL)
1840 return res;
1841 }
1842 return NULL;
1843}
1844
1845/* This is similar to PyObject_GenericGetAttr(),
1846 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1847static PyObject *
1848type_getattro(PyTypeObject *type, PyObject *name)
1849{
1850 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001851 PyObject *meta_attribute, *attribute;
1852 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853
1854 /* Initialize this type (we'll assume the metatype is initialized) */
1855 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001856 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001857 return NULL;
1858 }
1859
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001860 /* No readable descriptor found yet */
1861 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001862
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001863 /* Look for the attribute in the metatype */
1864 meta_attribute = _PyType_Lookup(metatype, name);
1865
1866 if (meta_attribute != NULL) {
1867 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001868
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001869 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1870 /* Data descriptors implement tp_descr_set to intercept
1871 * writes. Assume the attribute is not overridden in
1872 * type's tp_dict (and bases): call the descriptor now.
1873 */
1874 return meta_get(meta_attribute, (PyObject *)type,
1875 (PyObject *)metatype);
1876 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001877 }
1878
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001879 /* No data descriptor found on metatype. Look in tp_dict of this
1880 * type and its bases */
1881 attribute = _PyType_Lookup(type, name);
1882 if (attribute != NULL) {
1883 /* Implement descriptor functionality, if any */
1884 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1885 if (local_get != NULL) {
1886 /* NULL 2nd argument indicates the descriptor was
1887 * found on the target object itself (or a base) */
1888 return local_get(attribute, (PyObject *)NULL,
1889 (PyObject *)type);
1890 }
Tim Peters34592512002-07-11 06:23:50 +00001891
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001892 Py_INCREF(attribute);
1893 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001894 }
1895
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001896 /* No attribute found in local __dict__ (or bases): use the
1897 * descriptor from the metatype, if any */
1898 if (meta_get != NULL)
1899 return meta_get(meta_attribute, (PyObject *)type,
1900 (PyObject *)metatype);
1901
1902 /* If an ordinary attribute was found on the metatype, return it now */
1903 if (meta_attribute != NULL) {
1904 Py_INCREF(meta_attribute);
1905 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906 }
1907
1908 /* Give up */
1909 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001910 "type object '%.50s' has no attribute '%.400s'",
1911 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001912 return NULL;
1913}
1914
1915static int
1916type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1917{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001918 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1919 PyErr_Format(
1920 PyExc_TypeError,
1921 "can't set attributes of built-in/extension type '%s'",
1922 type->tp_name);
1923 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001924 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001925 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1926 return -1;
1927 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001928}
1929
1930static void
1931type_dealloc(PyTypeObject *type)
1932{
1933 etype *et;
1934
1935 /* Assert this is a heap-allocated type object */
1936 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001937 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001938 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001939 et = (etype *)type;
1940 Py_XDECREF(type->tp_base);
1941 Py_XDECREF(type->tp_dict);
1942 Py_XDECREF(type->tp_bases);
1943 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001944 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001945 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001946 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001947 Py_XDECREF(et->name);
1948 Py_XDECREF(et->slots);
1949 type->ob_type->tp_free((PyObject *)type);
1950}
1951
Guido van Rossum1c450732001-10-08 15:18:27 +00001952static PyObject *
1953type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1954{
1955 PyObject *list, *raw, *ref;
1956 int i, n;
1957
1958 list = PyList_New(0);
1959 if (list == NULL)
1960 return NULL;
1961 raw = type->tp_subclasses;
1962 if (raw == NULL)
1963 return list;
1964 assert(PyList_Check(raw));
1965 n = PyList_GET_SIZE(raw);
1966 for (i = 0; i < n; i++) {
1967 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001968 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001969 ref = PyWeakref_GET_OBJECT(ref);
1970 if (ref != Py_None) {
1971 if (PyList_Append(list, ref) < 0) {
1972 Py_DECREF(list);
1973 return NULL;
1974 }
1975 }
1976 }
1977 return list;
1978}
1979
Tim Peters6d6c1a32001-08-02 04:15:00 +00001980static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001981 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00001982 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00001983 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00001984 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00001985 {0}
1986};
1987
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001988PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001989"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001990"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001991
Guido van Rossum048eb752001-10-02 21:24:57 +00001992static int
1993type_traverse(PyTypeObject *type, visitproc visit, void *arg)
1994{
Guido van Rossum048eb752001-10-02 21:24:57 +00001995 int err;
1996
Guido van Rossuma3862092002-06-10 15:24:42 +00001997 /* Because of type_is_gc(), the collector only calls this
1998 for heaptypes. */
1999 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002000
2001#define VISIT(SLOT) \
2002 if (SLOT) { \
2003 err = visit((PyObject *)(SLOT), arg); \
2004 if (err) \
2005 return err; \
2006 }
2007
2008 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002009 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002010 VISIT(type->tp_mro);
2011 VISIT(type->tp_bases);
2012 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002013
2014 /* There's no need to visit type->tp_subclasses or
2015 ((etype *)type)->slots, because they can't be involved
2016 in cycles; tp_subclasses is a list of weak references,
2017 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002018
2019#undef VISIT
2020
2021 return 0;
2022}
2023
2024static int
2025type_clear(PyTypeObject *type)
2026{
Guido van Rossum048eb752001-10-02 21:24:57 +00002027 PyObject *tmp;
2028
Guido van Rossuma3862092002-06-10 15:24:42 +00002029 /* Because of type_is_gc(), the collector only calls this
2030 for heaptypes. */
2031 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002032
2033#define CLEAR(SLOT) \
2034 if (SLOT) { \
2035 tmp = (PyObject *)(SLOT); \
2036 SLOT = NULL; \
2037 Py_DECREF(tmp); \
2038 }
2039
Guido van Rossuma3862092002-06-10 15:24:42 +00002040 /* The only field we need to clear is tp_mro, which is part of a
2041 hard cycle (its first element is the class itself) that won't
2042 be broken otherwise (it's a tuple and tuples don't have a
2043 tp_clear handler). None of the other fields need to be
2044 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002045
Guido van Rossuma3862092002-06-10 15:24:42 +00002046 tp_dict:
2047 It is a dict, so the collector will call its tp_clear.
2048
2049 tp_cache:
2050 Not used; if it were, it would be a dict.
2051
2052 tp_bases, tp_base:
2053 If these are involved in a cycle, there must be at least
2054 one other, mutable object in the cycle, e.g. a base
2055 class's dict; the cycle will be broken that way.
2056
2057 tp_subclasses:
2058 A list of weak references can't be part of a cycle; and
2059 lists have their own tp_clear.
2060
2061 slots (in etype):
2062 A tuple of strings can't be part of a cycle.
2063 */
2064
2065 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002066
Guido van Rossum048eb752001-10-02 21:24:57 +00002067#undef CLEAR
2068
2069 return 0;
2070}
2071
2072static int
2073type_is_gc(PyTypeObject *type)
2074{
2075 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2076}
2077
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002078PyTypeObject PyType_Type = {
2079 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002080 0, /* ob_size */
2081 "type", /* tp_name */
2082 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002083 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002084 (destructor)type_dealloc, /* tp_dealloc */
2085 0, /* tp_print */
2086 0, /* tp_getattr */
2087 0, /* tp_setattr */
2088 type_compare, /* tp_compare */
2089 (reprfunc)type_repr, /* tp_repr */
2090 0, /* tp_as_number */
2091 0, /* tp_as_sequence */
2092 0, /* tp_as_mapping */
2093 (hashfunc)_Py_HashPointer, /* tp_hash */
2094 (ternaryfunc)type_call, /* tp_call */
2095 0, /* tp_str */
2096 (getattrofunc)type_getattro, /* tp_getattro */
2097 (setattrofunc)type_setattro, /* tp_setattro */
2098 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002099 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2100 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002102 (traverseproc)type_traverse, /* tp_traverse */
2103 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002104 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002105 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106 0, /* tp_iter */
2107 0, /* tp_iternext */
2108 type_methods, /* tp_methods */
2109 type_members, /* tp_members */
2110 type_getsets, /* tp_getset */
2111 0, /* tp_base */
2112 0, /* tp_dict */
2113 0, /* tp_descr_get */
2114 0, /* tp_descr_set */
2115 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2116 0, /* tp_init */
2117 0, /* tp_alloc */
2118 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002119 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002120 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002121};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002122
2123
2124/* The base type of all types (eventually)... except itself. */
2125
2126static int
2127object_init(PyObject *self, PyObject *args, PyObject *kwds)
2128{
2129 return 0;
2130}
2131
2132static void
2133object_dealloc(PyObject *self)
2134{
2135 self->ob_type->tp_free(self);
2136}
2137
Guido van Rossum8e248182001-08-12 05:17:56 +00002138static PyObject *
2139object_repr(PyObject *self)
2140{
Guido van Rossum76e69632001-08-16 18:52:43 +00002141 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002142 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002143
Guido van Rossum76e69632001-08-16 18:52:43 +00002144 type = self->ob_type;
2145 mod = type_module(type, NULL);
2146 if (mod == NULL)
2147 PyErr_Clear();
2148 else if (!PyString_Check(mod)) {
2149 Py_DECREF(mod);
2150 mod = NULL;
2151 }
2152 name = type_name(type, NULL);
2153 if (name == NULL)
2154 return NULL;
2155 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002156 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002157 PyString_AS_STRING(mod),
2158 PyString_AS_STRING(name),
2159 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002160 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002161 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002162 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002163 Py_XDECREF(mod);
2164 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002165 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002166}
2167
Guido van Rossumb8f63662001-08-15 23:57:02 +00002168static PyObject *
2169object_str(PyObject *self)
2170{
2171 unaryfunc f;
2172
2173 f = self->ob_type->tp_repr;
2174 if (f == NULL)
2175 f = object_repr;
2176 return f(self);
2177}
2178
Guido van Rossum8e248182001-08-12 05:17:56 +00002179static long
2180object_hash(PyObject *self)
2181{
2182 return _Py_HashPointer(self);
2183}
Guido van Rossum8e248182001-08-12 05:17:56 +00002184
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002185static PyObject *
2186object_get_class(PyObject *self, void *closure)
2187{
2188 Py_INCREF(self->ob_type);
2189 return (PyObject *)(self->ob_type);
2190}
2191
2192static int
2193equiv_structs(PyTypeObject *a, PyTypeObject *b)
2194{
2195 return a == b ||
2196 (a != NULL &&
2197 b != NULL &&
2198 a->tp_basicsize == b->tp_basicsize &&
2199 a->tp_itemsize == b->tp_itemsize &&
2200 a->tp_dictoffset == b->tp_dictoffset &&
2201 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2202 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2203 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2204}
2205
2206static int
2207same_slots_added(PyTypeObject *a, PyTypeObject *b)
2208{
2209 PyTypeObject *base = a->tp_base;
2210 int size;
2211
2212 if (base != b->tp_base)
2213 return 0;
2214 if (equiv_structs(a, base) && equiv_structs(b, base))
2215 return 1;
2216 size = base->tp_basicsize;
2217 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2218 size += sizeof(PyObject *);
2219 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2220 size += sizeof(PyObject *);
2221 return size == a->tp_basicsize && size == b->tp_basicsize;
2222}
2223
2224static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002225compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2226{
2227 PyTypeObject *newbase, *oldbase;
2228
2229 if (new->tp_dealloc != old->tp_dealloc ||
2230 new->tp_free != old->tp_free)
2231 {
2232 PyErr_Format(PyExc_TypeError,
2233 "%s assignment: "
2234 "'%s' deallocator differs from '%s'",
2235 attr,
2236 new->tp_name,
2237 old->tp_name);
2238 return 0;
2239 }
2240 newbase = new;
2241 oldbase = old;
2242 while (equiv_structs(newbase, newbase->tp_base))
2243 newbase = newbase->tp_base;
2244 while (equiv_structs(oldbase, oldbase->tp_base))
2245 oldbase = oldbase->tp_base;
2246 if (newbase != oldbase &&
2247 (newbase->tp_base != oldbase->tp_base ||
2248 !same_slots_added(newbase, oldbase))) {
2249 PyErr_Format(PyExc_TypeError,
2250 "%s assignment: "
2251 "'%s' object layout differs from '%s'",
2252 attr,
2253 new->tp_name,
2254 old->tp_name);
2255 return 0;
2256 }
2257
2258 return 1;
2259}
2260
2261static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002262object_set_class(PyObject *self, PyObject *value, void *closure)
2263{
2264 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002265 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002266
Guido van Rossumb6b89422002-04-15 01:03:30 +00002267 if (value == NULL) {
2268 PyErr_SetString(PyExc_TypeError,
2269 "can't delete __class__ attribute");
2270 return -1;
2271 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002272 if (!PyType_Check(value)) {
2273 PyErr_Format(PyExc_TypeError,
2274 "__class__ must be set to new-style class, not '%s' object",
2275 value->ob_type->tp_name);
2276 return -1;
2277 }
2278 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002279 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2280 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2281 {
2282 PyErr_Format(PyExc_TypeError,
2283 "__class__ assignment: only for heap types");
2284 return -1;
2285 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002286 if (compatible_for_assignment(new, old, "__class__")) {
2287 Py_INCREF(new);
2288 self->ob_type = new;
2289 Py_DECREF(old);
2290 return 0;
2291 }
2292 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002293 return -1;
2294 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002295}
2296
2297static PyGetSetDef object_getsets[] = {
2298 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002299 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002300 {0}
2301};
2302
Guido van Rossum3926a632001-09-25 16:25:58 +00002303static PyObject *
2304object_reduce(PyObject *self, PyObject *args)
2305{
2306 /* Call copy_reg._reduce(self) */
2307 static PyObject *copy_reg_str;
2308 PyObject *copy_reg, *res;
2309
2310 if (!copy_reg_str) {
2311 copy_reg_str = PyString_InternFromString("copy_reg");
2312 if (copy_reg_str == NULL)
2313 return NULL;
2314 }
2315 copy_reg = PyImport_Import(copy_reg_str);
2316 if (!copy_reg)
2317 return NULL;
2318 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
2319 Py_DECREF(copy_reg);
2320 return res;
2321}
2322
2323static PyMethodDef object_methods[] = {
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002324 {"__reduce__", object_reduce, METH_NOARGS,
2325 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002326 {0}
2327};
2328
Tim Peters6d6c1a32001-08-02 04:15:00 +00002329PyTypeObject PyBaseObject_Type = {
2330 PyObject_HEAD_INIT(&PyType_Type)
2331 0, /* ob_size */
2332 "object", /* tp_name */
2333 sizeof(PyObject), /* tp_basicsize */
2334 0, /* tp_itemsize */
2335 (destructor)object_dealloc, /* tp_dealloc */
2336 0, /* tp_print */
2337 0, /* tp_getattr */
2338 0, /* tp_setattr */
2339 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002340 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341 0, /* tp_as_number */
2342 0, /* tp_as_sequence */
2343 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002344 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002345 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002346 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002347 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002348 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002349 0, /* tp_as_buffer */
2350 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002351 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002352 0, /* tp_traverse */
2353 0, /* tp_clear */
2354 0, /* tp_richcompare */
2355 0, /* tp_weaklistoffset */
2356 0, /* tp_iter */
2357 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002358 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002359 0, /* tp_members */
2360 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002361 0, /* tp_base */
2362 0, /* tp_dict */
2363 0, /* tp_descr_get */
2364 0, /* tp_descr_set */
2365 0, /* tp_dictoffset */
2366 object_init, /* tp_init */
2367 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00002368 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002369 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002370};
2371
2372
2373/* Initialize the __dict__ in a type object */
2374
Fred Drake7bf97152002-03-28 05:33:33 +00002375static PyObject *
2376create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
2377{
2378 PyObject *cfunc;
2379 PyObject *result;
2380
2381 cfunc = PyCFunction_New(meth, NULL);
2382 if (cfunc == NULL)
2383 return NULL;
2384 result = func(cfunc);
2385 Py_DECREF(cfunc);
2386 return result;
2387}
2388
Tim Peters6d6c1a32001-08-02 04:15:00 +00002389static int
2390add_methods(PyTypeObject *type, PyMethodDef *meth)
2391{
Guido van Rossum687ae002001-10-15 22:03:32 +00002392 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002393
2394 for (; meth->ml_name != NULL; meth++) {
2395 PyObject *descr;
2396 if (PyDict_GetItemString(dict, meth->ml_name))
2397 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002398 if (meth->ml_flags & METH_CLASS) {
2399 if (meth->ml_flags & METH_STATIC) {
2400 PyErr_SetString(PyExc_ValueError,
2401 "method cannot be both class and static");
2402 return -1;
2403 }
2404 descr = create_specialmethod(meth, PyClassMethod_New);
2405 }
2406 else if (meth->ml_flags & METH_STATIC) {
2407 descr = create_specialmethod(meth, PyStaticMethod_New);
2408 }
2409 else {
2410 descr = PyDescr_NewMethod(type, meth);
2411 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002412 if (descr == NULL)
2413 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002414 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002415 return -1;
2416 Py_DECREF(descr);
2417 }
2418 return 0;
2419}
2420
2421static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002422add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002423{
Guido van Rossum687ae002001-10-15 22:03:32 +00002424 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002425
2426 for (; memb->name != NULL; memb++) {
2427 PyObject *descr;
2428 if (PyDict_GetItemString(dict, memb->name))
2429 continue;
2430 descr = PyDescr_NewMember(type, memb);
2431 if (descr == NULL)
2432 return -1;
2433 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2434 return -1;
2435 Py_DECREF(descr);
2436 }
2437 return 0;
2438}
2439
2440static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002441add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002442{
Guido van Rossum687ae002001-10-15 22:03:32 +00002443 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002444
2445 for (; gsp->name != NULL; gsp++) {
2446 PyObject *descr;
2447 if (PyDict_GetItemString(dict, gsp->name))
2448 continue;
2449 descr = PyDescr_NewGetSet(type, gsp);
2450
2451 if (descr == NULL)
2452 return -1;
2453 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2454 return -1;
2455 Py_DECREF(descr);
2456 }
2457 return 0;
2458}
2459
Guido van Rossum13d52f02001-08-10 21:24:08 +00002460static void
2461inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002462{
2463 int oldsize, newsize;
2464
Guido van Rossum13d52f02001-08-10 21:24:08 +00002465 /* Special flag magic */
2466 if (!type->tp_as_buffer && base->tp_as_buffer) {
2467 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2468 type->tp_flags |=
2469 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2470 }
2471 if (!type->tp_as_sequence && base->tp_as_sequence) {
2472 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2473 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2474 }
2475 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2476 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2477 if ((!type->tp_as_number && base->tp_as_number) ||
2478 (!type->tp_as_sequence && base->tp_as_sequence)) {
2479 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2480 if (!type->tp_as_number && !type->tp_as_sequence) {
2481 type->tp_flags |= base->tp_flags &
2482 Py_TPFLAGS_HAVE_INPLACEOPS;
2483 }
2484 }
2485 /* Wow */
2486 }
2487 if (!type->tp_as_number && base->tp_as_number) {
2488 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2489 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2490 }
2491
2492 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002493 oldsize = base->tp_basicsize;
2494 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2495 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2496 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002497 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2498 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002499 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002500 if (type->tp_traverse == NULL)
2501 type->tp_traverse = base->tp_traverse;
2502 if (type->tp_clear == NULL)
2503 type->tp_clear = base->tp_clear;
2504 }
2505 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002506 /* The condition below could use some explanation.
2507 It appears that tp_new is not inherited for static types
2508 whose base class is 'object'; this seems to be a precaution
2509 so that old extension types don't suddenly become
2510 callable (object.__new__ wouldn't insure the invariants
2511 that the extension type's own factory function ensures).
2512 Heap types, of course, are under our control, so they do
2513 inherit tp_new; static extension types that specify some
2514 other built-in type as the default are considered
2515 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002516 if (base != &PyBaseObject_Type ||
2517 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2518 if (type->tp_new == NULL)
2519 type->tp_new = base->tp_new;
2520 }
2521 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002522 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002523
2524 /* Copy other non-function slots */
2525
2526#undef COPYVAL
2527#define COPYVAL(SLOT) \
2528 if (type->SLOT == 0) type->SLOT = base->SLOT
2529
2530 COPYVAL(tp_itemsize);
2531 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2532 COPYVAL(tp_weaklistoffset);
2533 }
2534 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2535 COPYVAL(tp_dictoffset);
2536 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002537}
2538
2539static void
2540inherit_slots(PyTypeObject *type, PyTypeObject *base)
2541{
2542 PyTypeObject *basebase;
2543
2544#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002545#undef COPYSLOT
2546#undef COPYNUM
2547#undef COPYSEQ
2548#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002549#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002550
2551#define SLOTDEFINED(SLOT) \
2552 (base->SLOT != 0 && \
2553 (basebase == NULL || base->SLOT != basebase->SLOT))
2554
Tim Peters6d6c1a32001-08-02 04:15:00 +00002555#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002556 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002557
2558#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2559#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2560#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002561#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002562
Guido van Rossum13d52f02001-08-10 21:24:08 +00002563 /* This won't inherit indirect slots (from tp_as_number etc.)
2564 if type doesn't provide the space. */
2565
2566 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2567 basebase = base->tp_base;
2568 if (basebase->tp_as_number == NULL)
2569 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002570 COPYNUM(nb_add);
2571 COPYNUM(nb_subtract);
2572 COPYNUM(nb_multiply);
2573 COPYNUM(nb_divide);
2574 COPYNUM(nb_remainder);
2575 COPYNUM(nb_divmod);
2576 COPYNUM(nb_power);
2577 COPYNUM(nb_negative);
2578 COPYNUM(nb_positive);
2579 COPYNUM(nb_absolute);
2580 COPYNUM(nb_nonzero);
2581 COPYNUM(nb_invert);
2582 COPYNUM(nb_lshift);
2583 COPYNUM(nb_rshift);
2584 COPYNUM(nb_and);
2585 COPYNUM(nb_xor);
2586 COPYNUM(nb_or);
2587 COPYNUM(nb_coerce);
2588 COPYNUM(nb_int);
2589 COPYNUM(nb_long);
2590 COPYNUM(nb_float);
2591 COPYNUM(nb_oct);
2592 COPYNUM(nb_hex);
2593 COPYNUM(nb_inplace_add);
2594 COPYNUM(nb_inplace_subtract);
2595 COPYNUM(nb_inplace_multiply);
2596 COPYNUM(nb_inplace_divide);
2597 COPYNUM(nb_inplace_remainder);
2598 COPYNUM(nb_inplace_power);
2599 COPYNUM(nb_inplace_lshift);
2600 COPYNUM(nb_inplace_rshift);
2601 COPYNUM(nb_inplace_and);
2602 COPYNUM(nb_inplace_xor);
2603 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002604 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2605 COPYNUM(nb_true_divide);
2606 COPYNUM(nb_floor_divide);
2607 COPYNUM(nb_inplace_true_divide);
2608 COPYNUM(nb_inplace_floor_divide);
2609 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002610 }
2611
Guido van Rossum13d52f02001-08-10 21:24:08 +00002612 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2613 basebase = base->tp_base;
2614 if (basebase->tp_as_sequence == NULL)
2615 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616 COPYSEQ(sq_length);
2617 COPYSEQ(sq_concat);
2618 COPYSEQ(sq_repeat);
2619 COPYSEQ(sq_item);
2620 COPYSEQ(sq_slice);
2621 COPYSEQ(sq_ass_item);
2622 COPYSEQ(sq_ass_slice);
2623 COPYSEQ(sq_contains);
2624 COPYSEQ(sq_inplace_concat);
2625 COPYSEQ(sq_inplace_repeat);
2626 }
2627
Guido van Rossum13d52f02001-08-10 21:24:08 +00002628 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2629 basebase = base->tp_base;
2630 if (basebase->tp_as_mapping == NULL)
2631 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002632 COPYMAP(mp_length);
2633 COPYMAP(mp_subscript);
2634 COPYMAP(mp_ass_subscript);
2635 }
2636
Tim Petersfc57ccb2001-10-12 02:38:24 +00002637 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2638 basebase = base->tp_base;
2639 if (basebase->tp_as_buffer == NULL)
2640 basebase = NULL;
2641 COPYBUF(bf_getreadbuffer);
2642 COPYBUF(bf_getwritebuffer);
2643 COPYBUF(bf_getsegcount);
2644 COPYBUF(bf_getcharbuffer);
2645 }
2646
Guido van Rossum13d52f02001-08-10 21:24:08 +00002647 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002648
Tim Peters6d6c1a32001-08-02 04:15:00 +00002649 COPYSLOT(tp_dealloc);
2650 COPYSLOT(tp_print);
2651 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2652 type->tp_getattr = base->tp_getattr;
2653 type->tp_getattro = base->tp_getattro;
2654 }
2655 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2656 type->tp_setattr = base->tp_setattr;
2657 type->tp_setattro = base->tp_setattro;
2658 }
2659 /* tp_compare see tp_richcompare */
2660 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002661 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002662 COPYSLOT(tp_call);
2663 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002664 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002665 if (type->tp_compare == NULL &&
2666 type->tp_richcompare == NULL &&
2667 type->tp_hash == NULL)
2668 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002669 type->tp_compare = base->tp_compare;
2670 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002671 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002672 }
2673 }
2674 else {
2675 COPYSLOT(tp_compare);
2676 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002677 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2678 COPYSLOT(tp_iter);
2679 COPYSLOT(tp_iternext);
2680 }
2681 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2682 COPYSLOT(tp_descr_get);
2683 COPYSLOT(tp_descr_set);
2684 COPYSLOT(tp_dictoffset);
2685 COPYSLOT(tp_init);
2686 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002687 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002688 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002689 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002690}
2691
Jeremy Hylton938ace62002-07-17 16:30:39 +00002692static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002693
Tim Peters6d6c1a32001-08-02 04:15:00 +00002694int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002695PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002697 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698 PyTypeObject *base;
2699 int i, n;
2700
Guido van Rossumcab05802002-06-10 15:29:03 +00002701 if (type->tp_flags & Py_TPFLAGS_READY) {
2702 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002703 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002704 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002705 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002706
2707 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002708
2709 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2710 base = type->tp_base;
2711 if (base == NULL && type != &PyBaseObject_Type)
2712 base = type->tp_base = &PyBaseObject_Type;
2713
Guido van Rossum323a9cf2002-08-14 17:26:30 +00002714 /* Initialize the base class */
2715 if (base && base->tp_dict == NULL) {
2716 if (PyType_Ready(base) < 0)
2717 goto error;
2718 }
2719
Guido van Rossum0986d822002-04-08 01:38:42 +00002720 /* Initialize ob_type if NULL. This means extensions that want to be
2721 compilable separately on Windows can call PyType_Ready() instead of
2722 initializing the ob_type field of their type objects. */
2723 if (type->ob_type == NULL)
2724 type->ob_type = base->ob_type;
2725
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726 /* Initialize tp_bases */
2727 bases = type->tp_bases;
2728 if (bases == NULL) {
2729 if (base == NULL)
2730 bases = PyTuple_New(0);
2731 else
2732 bases = Py_BuildValue("(O)", base);
2733 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002734 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002735 type->tp_bases = bases;
2736 }
2737
Guido van Rossum687ae002001-10-15 22:03:32 +00002738 /* Initialize tp_dict */
2739 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002740 if (dict == NULL) {
2741 dict = PyDict_New();
2742 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002743 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002744 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745 }
2746
Guido van Rossum687ae002001-10-15 22:03:32 +00002747 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002749 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002750 if (type->tp_methods != NULL) {
2751 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002752 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002753 }
2754 if (type->tp_members != NULL) {
2755 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002756 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757 }
2758 if (type->tp_getset != NULL) {
2759 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002760 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002761 }
2762
Tim Peters6d6c1a32001-08-02 04:15:00 +00002763 /* Calculate method resolution order */
2764 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002765 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766 }
2767
Guido van Rossum13d52f02001-08-10 21:24:08 +00002768 /* Inherit special flags from dominant base */
2769 if (type->tp_base != NULL)
2770 inherit_special(type, type->tp_base);
2771
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002773 bases = type->tp_mro;
2774 assert(bases != NULL);
2775 assert(PyTuple_Check(bases));
2776 n = PyTuple_GET_SIZE(bases);
2777 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002778 PyObject *b = PyTuple_GET_ITEM(bases, i);
2779 if (PyType_Check(b))
2780 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002781 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002783 /* if the type dictionary doesn't contain a __doc__, set it from
2784 the tp_doc slot.
2785 */
2786 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2787 if (type->tp_doc != NULL) {
2788 PyObject *doc = PyString_FromString(type->tp_doc);
2789 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2790 Py_DECREF(doc);
2791 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002792 PyDict_SetItemString(type->tp_dict,
2793 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002794 }
2795 }
2796
Guido van Rossum13d52f02001-08-10 21:24:08 +00002797 /* Some more special stuff */
2798 base = type->tp_base;
2799 if (base != NULL) {
2800 if (type->tp_as_number == NULL)
2801 type->tp_as_number = base->tp_as_number;
2802 if (type->tp_as_sequence == NULL)
2803 type->tp_as_sequence = base->tp_as_sequence;
2804 if (type->tp_as_mapping == NULL)
2805 type->tp_as_mapping = base->tp_as_mapping;
2806 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002807
Guido van Rossum1c450732001-10-08 15:18:27 +00002808 /* Link into each base class's list of subclasses */
2809 bases = type->tp_bases;
2810 n = PyTuple_GET_SIZE(bases);
2811 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002812 PyObject *b = PyTuple_GET_ITEM(bases, i);
2813 if (PyType_Check(b) &&
2814 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002815 goto error;
2816 }
2817
Guido van Rossum13d52f02001-08-10 21:24:08 +00002818 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002819 assert(type->tp_dict != NULL);
2820 type->tp_flags =
2821 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002822 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002823
2824 error:
2825 type->tp_flags &= ~Py_TPFLAGS_READYING;
2826 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002827}
2828
Guido van Rossum1c450732001-10-08 15:18:27 +00002829static int
2830add_subclass(PyTypeObject *base, PyTypeObject *type)
2831{
2832 int i;
2833 PyObject *list, *ref, *new;
2834
2835 list = base->tp_subclasses;
2836 if (list == NULL) {
2837 base->tp_subclasses = list = PyList_New(0);
2838 if (list == NULL)
2839 return -1;
2840 }
2841 assert(PyList_Check(list));
2842 new = PyWeakref_NewRef((PyObject *)type, NULL);
2843 i = PyList_GET_SIZE(list);
2844 while (--i >= 0) {
2845 ref = PyList_GET_ITEM(list, i);
2846 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00002847 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2848 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00002849 }
2850 i = PyList_Append(list, new);
2851 Py_DECREF(new);
2852 return i;
2853}
2854
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002855static void
2856remove_subclass(PyTypeObject *base, PyTypeObject *type)
2857{
2858 int i;
2859 PyObject *list, *ref;
2860
2861 list = base->tp_subclasses;
2862 if (list == NULL) {
2863 return;
2864 }
2865 assert(PyList_Check(list));
2866 i = PyList_GET_SIZE(list);
2867 while (--i >= 0) {
2868 ref = PyList_GET_ITEM(list, i);
2869 assert(PyWeakref_CheckRef(ref));
2870 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
2871 /* this can't fail, right? */
2872 PySequence_DelItem(list, i);
2873 return;
2874 }
2875 }
2876}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002877
2878/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2879
2880/* There's a wrapper *function* for each distinct function typedef used
2881 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2882 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2883 Most tables have only one entry; the tables for binary operators have two
2884 entries, one regular and one with reversed arguments. */
2885
2886static PyObject *
2887wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2888{
2889 inquiry func = (inquiry)wrapped;
2890 int res;
2891
2892 if (!PyArg_ParseTuple(args, ""))
2893 return NULL;
2894 res = (*func)(self);
2895 if (res == -1 && PyErr_Occurred())
2896 return NULL;
2897 return PyInt_FromLong((long)res);
2898}
2899
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900static PyObject *
2901wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2902{
2903 binaryfunc func = (binaryfunc)wrapped;
2904 PyObject *other;
2905
2906 if (!PyArg_ParseTuple(args, "O", &other))
2907 return NULL;
2908 return (*func)(self, other);
2909}
2910
2911static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002912wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2913{
2914 binaryfunc func = (binaryfunc)wrapped;
2915 PyObject *other;
2916
2917 if (!PyArg_ParseTuple(args, "O", &other))
2918 return NULL;
2919 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002920 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002921 Py_INCREF(Py_NotImplemented);
2922 return Py_NotImplemented;
2923 }
2924 return (*func)(self, other);
2925}
2926
2927static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002928wrap_binaryfunc_r(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;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002935 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002936 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002937 Py_INCREF(Py_NotImplemented);
2938 return Py_NotImplemented;
2939 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002940 return (*func)(other, self);
2941}
2942
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002943static PyObject *
2944wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2945{
2946 coercion func = (coercion)wrapped;
2947 PyObject *other, *res;
2948 int ok;
2949
2950 if (!PyArg_ParseTuple(args, "O", &other))
2951 return NULL;
2952 ok = func(&self, &other);
2953 if (ok < 0)
2954 return NULL;
2955 if (ok > 0) {
2956 Py_INCREF(Py_NotImplemented);
2957 return Py_NotImplemented;
2958 }
2959 res = PyTuple_New(2);
2960 if (res == NULL) {
2961 Py_DECREF(self);
2962 Py_DECREF(other);
2963 return NULL;
2964 }
2965 PyTuple_SET_ITEM(res, 0, self);
2966 PyTuple_SET_ITEM(res, 1, other);
2967 return res;
2968}
2969
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970static PyObject *
2971wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2972{
2973 ternaryfunc func = (ternaryfunc)wrapped;
2974 PyObject *other;
2975 PyObject *third = Py_None;
2976
2977 /* Note: This wrapper only works for __pow__() */
2978
2979 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2980 return NULL;
2981 return (*func)(self, other, third);
2982}
2983
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00002984static PyObject *
2985wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2986{
2987 ternaryfunc func = (ternaryfunc)wrapped;
2988 PyObject *other;
2989 PyObject *third = Py_None;
2990
2991 /* Note: This wrapper only works for __pow__() */
2992
2993 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
2994 return NULL;
2995 return (*func)(other, self, third);
2996}
2997
Tim Peters6d6c1a32001-08-02 04:15:00 +00002998static PyObject *
2999wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3000{
3001 unaryfunc func = (unaryfunc)wrapped;
3002
3003 if (!PyArg_ParseTuple(args, ""))
3004 return NULL;
3005 return (*func)(self);
3006}
3007
Tim Peters6d6c1a32001-08-02 04:15:00 +00003008static PyObject *
3009wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3010{
3011 intargfunc func = (intargfunc)wrapped;
3012 int i;
3013
3014 if (!PyArg_ParseTuple(args, "i", &i))
3015 return NULL;
3016 return (*func)(self, i);
3017}
3018
Guido van Rossum5d815f32001-08-17 21:57:47 +00003019static int
3020getindex(PyObject *self, PyObject *arg)
3021{
3022 int i;
3023
3024 i = PyInt_AsLong(arg);
3025 if (i == -1 && PyErr_Occurred())
3026 return -1;
3027 if (i < 0) {
3028 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3029 if (sq && sq->sq_length) {
3030 int n = (*sq->sq_length)(self);
3031 if (n < 0)
3032 return -1;
3033 i += n;
3034 }
3035 }
3036 return i;
3037}
3038
3039static PyObject *
3040wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3041{
3042 intargfunc func = (intargfunc)wrapped;
3043 PyObject *arg;
3044 int i;
3045
Guido van Rossumf4593e02001-10-03 12:09:30 +00003046 if (PyTuple_GET_SIZE(args) == 1) {
3047 arg = PyTuple_GET_ITEM(args, 0);
3048 i = getindex(self, arg);
3049 if (i == -1 && PyErr_Occurred())
3050 return NULL;
3051 return (*func)(self, i);
3052 }
3053 PyArg_ParseTuple(args, "O", &arg);
3054 assert(PyErr_Occurred());
3055 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003056}
3057
Tim Peters6d6c1a32001-08-02 04:15:00 +00003058static PyObject *
3059wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3060{
3061 intintargfunc func = (intintargfunc)wrapped;
3062 int i, j;
3063
3064 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3065 return NULL;
3066 return (*func)(self, i, j);
3067}
3068
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003070wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003071{
3072 intobjargproc func = (intobjargproc)wrapped;
3073 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003074 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003075
Guido van Rossum5d815f32001-08-17 21:57:47 +00003076 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3077 return NULL;
3078 i = getindex(self, arg);
3079 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003080 return NULL;
3081 res = (*func)(self, i, value);
3082 if (res == -1 && PyErr_Occurred())
3083 return NULL;
3084 Py_INCREF(Py_None);
3085 return Py_None;
3086}
3087
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003088static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003089wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003090{
3091 intobjargproc func = (intobjargproc)wrapped;
3092 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003093 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003094
Guido van Rossum5d815f32001-08-17 21:57:47 +00003095 if (!PyArg_ParseTuple(args, "O", &arg))
3096 return NULL;
3097 i = getindex(self, arg);
3098 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003099 return NULL;
3100 res = (*func)(self, i, NULL);
3101 if (res == -1 && PyErr_Occurred())
3102 return NULL;
3103 Py_INCREF(Py_None);
3104 return Py_None;
3105}
3106
Tim Peters6d6c1a32001-08-02 04:15:00 +00003107static PyObject *
3108wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3109{
3110 intintobjargproc func = (intintobjargproc)wrapped;
3111 int i, j, res;
3112 PyObject *value;
3113
3114 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3115 return NULL;
3116 res = (*func)(self, i, j, value);
3117 if (res == -1 && PyErr_Occurred())
3118 return NULL;
3119 Py_INCREF(Py_None);
3120 return Py_None;
3121}
3122
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003123static PyObject *
3124wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3125{
3126 intintobjargproc func = (intintobjargproc)wrapped;
3127 int i, j, res;
3128
3129 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3130 return NULL;
3131 res = (*func)(self, i, j, NULL);
3132 if (res == -1 && PyErr_Occurred())
3133 return NULL;
3134 Py_INCREF(Py_None);
3135 return Py_None;
3136}
3137
Tim Peters6d6c1a32001-08-02 04:15:00 +00003138/* XXX objobjproc is a misnomer; should be objargpred */
3139static PyObject *
3140wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3141{
3142 objobjproc func = (objobjproc)wrapped;
3143 int res;
3144 PyObject *value;
3145
3146 if (!PyArg_ParseTuple(args, "O", &value))
3147 return NULL;
3148 res = (*func)(self, value);
3149 if (res == -1 && PyErr_Occurred())
3150 return NULL;
3151 return PyInt_FromLong((long)res);
3152}
3153
Tim Peters6d6c1a32001-08-02 04:15:00 +00003154static PyObject *
3155wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3156{
3157 objobjargproc func = (objobjargproc)wrapped;
3158 int res;
3159 PyObject *key, *value;
3160
3161 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3162 return NULL;
3163 res = (*func)(self, key, value);
3164 if (res == -1 && PyErr_Occurred())
3165 return NULL;
3166 Py_INCREF(Py_None);
3167 return Py_None;
3168}
3169
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003170static PyObject *
3171wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3172{
3173 objobjargproc func = (objobjargproc)wrapped;
3174 int res;
3175 PyObject *key;
3176
3177 if (!PyArg_ParseTuple(args, "O", &key))
3178 return NULL;
3179 res = (*func)(self, key, NULL);
3180 if (res == -1 && PyErr_Occurred())
3181 return NULL;
3182 Py_INCREF(Py_None);
3183 return Py_None;
3184}
3185
Tim Peters6d6c1a32001-08-02 04:15:00 +00003186static PyObject *
3187wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3188{
3189 cmpfunc func = (cmpfunc)wrapped;
3190 int res;
3191 PyObject *other;
3192
3193 if (!PyArg_ParseTuple(args, "O", &other))
3194 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003195 if (other->ob_type->tp_compare != func &&
3196 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003197 PyErr_Format(
3198 PyExc_TypeError,
3199 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3200 self->ob_type->tp_name,
3201 self->ob_type->tp_name,
3202 other->ob_type->tp_name);
3203 return NULL;
3204 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003205 res = (*func)(self, other);
3206 if (PyErr_Occurred())
3207 return NULL;
3208 return PyInt_FromLong((long)res);
3209}
3210
Tim Peters6d6c1a32001-08-02 04:15:00 +00003211static PyObject *
3212wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3213{
3214 setattrofunc func = (setattrofunc)wrapped;
3215 int res;
3216 PyObject *name, *value;
3217
3218 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3219 return NULL;
3220 res = (*func)(self, name, value);
3221 if (res < 0)
3222 return NULL;
3223 Py_INCREF(Py_None);
3224 return Py_None;
3225}
3226
3227static PyObject *
3228wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3229{
3230 setattrofunc func = (setattrofunc)wrapped;
3231 int res;
3232 PyObject *name;
3233
3234 if (!PyArg_ParseTuple(args, "O", &name))
3235 return NULL;
3236 res = (*func)(self, name, NULL);
3237 if (res < 0)
3238 return NULL;
3239 Py_INCREF(Py_None);
3240 return Py_None;
3241}
3242
Tim Peters6d6c1a32001-08-02 04:15:00 +00003243static PyObject *
3244wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3245{
3246 hashfunc func = (hashfunc)wrapped;
3247 long res;
3248
3249 if (!PyArg_ParseTuple(args, ""))
3250 return NULL;
3251 res = (*func)(self);
3252 if (res == -1 && PyErr_Occurred())
3253 return NULL;
3254 return PyInt_FromLong(res);
3255}
3256
Tim Peters6d6c1a32001-08-02 04:15:00 +00003257static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003258wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003259{
3260 ternaryfunc func = (ternaryfunc)wrapped;
3261
Guido van Rossumc8e56452001-10-22 00:43:43 +00003262 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003263}
3264
Tim Peters6d6c1a32001-08-02 04:15:00 +00003265static PyObject *
3266wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3267{
3268 richcmpfunc func = (richcmpfunc)wrapped;
3269 PyObject *other;
3270
3271 if (!PyArg_ParseTuple(args, "O", &other))
3272 return NULL;
3273 return (*func)(self, other, op);
3274}
3275
3276#undef RICHCMP_WRAPPER
3277#define RICHCMP_WRAPPER(NAME, OP) \
3278static PyObject * \
3279richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3280{ \
3281 return wrap_richcmpfunc(self, args, wrapped, OP); \
3282}
3283
Jack Jansen8e938b42001-08-08 15:29:49 +00003284RICHCMP_WRAPPER(lt, Py_LT)
3285RICHCMP_WRAPPER(le, Py_LE)
3286RICHCMP_WRAPPER(eq, Py_EQ)
3287RICHCMP_WRAPPER(ne, Py_NE)
3288RICHCMP_WRAPPER(gt, Py_GT)
3289RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003290
Tim Peters6d6c1a32001-08-02 04:15:00 +00003291static PyObject *
3292wrap_next(PyObject *self, PyObject *args, void *wrapped)
3293{
3294 unaryfunc func = (unaryfunc)wrapped;
3295 PyObject *res;
3296
3297 if (!PyArg_ParseTuple(args, ""))
3298 return NULL;
3299 res = (*func)(self);
3300 if (res == NULL && !PyErr_Occurred())
3301 PyErr_SetNone(PyExc_StopIteration);
3302 return res;
3303}
3304
Tim Peters6d6c1a32001-08-02 04:15:00 +00003305static PyObject *
3306wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3307{
3308 descrgetfunc func = (descrgetfunc)wrapped;
3309 PyObject *obj;
3310 PyObject *type = NULL;
3311
3312 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3313 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003314 return (*func)(self, obj, type);
3315}
3316
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003318wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003319{
3320 descrsetfunc func = (descrsetfunc)wrapped;
3321 PyObject *obj, *value;
3322 int ret;
3323
3324 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3325 return NULL;
3326 ret = (*func)(self, obj, value);
3327 if (ret < 0)
3328 return NULL;
3329 Py_INCREF(Py_None);
3330 return Py_None;
3331}
Guido van Rossum22b13872002-08-06 21:41:44 +00003332
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003333static PyObject *
3334wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3335{
3336 descrsetfunc func = (descrsetfunc)wrapped;
3337 PyObject *obj;
3338 int ret;
3339
3340 if (!PyArg_ParseTuple(args, "O", &obj))
3341 return NULL;
3342 ret = (*func)(self, obj, NULL);
3343 if (ret < 0)
3344 return NULL;
3345 Py_INCREF(Py_None);
3346 return Py_None;
3347}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003348
Tim Peters6d6c1a32001-08-02 04:15:00 +00003349static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003350wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003351{
3352 initproc func = (initproc)wrapped;
3353
Guido van Rossumc8e56452001-10-22 00:43:43 +00003354 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003355 return NULL;
3356 Py_INCREF(Py_None);
3357 return Py_None;
3358}
3359
Tim Peters6d6c1a32001-08-02 04:15:00 +00003360static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003361tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003362{
Barry Warsaw60f01882001-08-22 19:24:42 +00003363 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003364 PyObject *arg0, *res;
3365
3366 if (self == NULL || !PyType_Check(self))
3367 Py_FatalError("__new__() called with non-type 'self'");
3368 type = (PyTypeObject *)self;
3369 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003370 PyErr_Format(PyExc_TypeError,
3371 "%s.__new__(): not enough arguments",
3372 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003373 return NULL;
3374 }
3375 arg0 = PyTuple_GET_ITEM(args, 0);
3376 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003377 PyErr_Format(PyExc_TypeError,
3378 "%s.__new__(X): X is not a type object (%s)",
3379 type->tp_name,
3380 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003381 return NULL;
3382 }
3383 subtype = (PyTypeObject *)arg0;
3384 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003385 PyErr_Format(PyExc_TypeError,
3386 "%s.__new__(%s): %s is not a subtype of %s",
3387 type->tp_name,
3388 subtype->tp_name,
3389 subtype->tp_name,
3390 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003391 return NULL;
3392 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003393
3394 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003395 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003396 most derived base that's not a heap type is this type. */
3397 staticbase = subtype;
3398 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3399 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003400 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003401 PyErr_Format(PyExc_TypeError,
3402 "%s.__new__(%s) is not safe, use %s.__new__()",
3403 type->tp_name,
3404 subtype->tp_name,
3405 staticbase == NULL ? "?" : staticbase->tp_name);
3406 return NULL;
3407 }
3408
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003409 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3410 if (args == NULL)
3411 return NULL;
3412 res = type->tp_new(subtype, args, kwds);
3413 Py_DECREF(args);
3414 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003415}
3416
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003417static struct PyMethodDef tp_new_methoddef[] = {
3418 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003419 PyDoc_STR("T.__new__(S, ...) -> "
3420 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003421 {0}
3422};
3423
3424static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003425add_tp_new_wrapper(PyTypeObject *type)
3426{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003427 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003428
Guido van Rossum687ae002001-10-15 22:03:32 +00003429 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003430 return 0;
3431 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003432 if (func == NULL)
3433 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003434 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003435}
3436
Guido van Rossumf040ede2001-08-07 16:40:56 +00003437/* Slot wrappers that call the corresponding __foo__ slot. See comments
3438 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003439
Guido van Rossumdc91b992001-08-08 22:26:22 +00003440#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003442FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003443{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003444 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003445 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003446}
3447
Guido van Rossumdc91b992001-08-08 22:26:22 +00003448#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003449static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003450FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003451{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003452 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003453 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003454}
3455
Guido van Rossumdc91b992001-08-08 22:26:22 +00003456
3457#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003458static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003459FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003460{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003461 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003462 int do_other = self->ob_type != other->ob_type && \
3463 other->ob_type->tp_as_number != NULL && \
3464 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003465 if (self->ob_type->tp_as_number != NULL && \
3466 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3467 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003468 if (do_other && \
3469 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
3470 r = call_maybe( \
3471 other, ROPSTR, &rcache_str, "(O)", self); \
3472 if (r != Py_NotImplemented) \
3473 return r; \
3474 Py_DECREF(r); \
3475 do_other = 0; \
3476 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003477 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003478 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003479 if (r != Py_NotImplemented || \
3480 other->ob_type == self->ob_type) \
3481 return r; \
3482 Py_DECREF(r); \
3483 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003484 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003485 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003486 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003487 } \
3488 Py_INCREF(Py_NotImplemented); \
3489 return Py_NotImplemented; \
3490}
3491
3492#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3493 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3494
3495#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3496static PyObject * \
3497FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3498{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003499 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003500 return call_method(self, OPSTR, &cache_str, \
3501 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003502}
3503
3504static int
3505slot_sq_length(PyObject *self)
3506{
Guido van Rossum2730b132001-08-28 18:22:14 +00003507 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003508 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003509 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003510
3511 if (res == NULL)
3512 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003513 len = (int)PyInt_AsLong(res);
3514 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003515 if (len == -1 && PyErr_Occurred())
3516 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003517 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003518 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003519 "__len__() should return >= 0");
3520 return -1;
3521 }
Guido van Rossum26111622001-10-01 16:42:49 +00003522 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003523}
3524
Guido van Rossumdc91b992001-08-08 22:26:22 +00003525SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3526SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003527
3528/* Super-optimized version of slot_sq_item.
3529 Other slots could do the same... */
3530static PyObject *
3531slot_sq_item(PyObject *self, int i)
3532{
3533 static PyObject *getitem_str;
3534 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3535 descrgetfunc f;
3536
3537 if (getitem_str == NULL) {
3538 getitem_str = PyString_InternFromString("__getitem__");
3539 if (getitem_str == NULL)
3540 return NULL;
3541 }
3542 func = _PyType_Lookup(self->ob_type, getitem_str);
3543 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003544 if ((f = func->ob_type->tp_descr_get) == NULL)
3545 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003546 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003547 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003548 if (func == NULL) {
3549 return NULL;
3550 }
3551 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003552 ival = PyInt_FromLong(i);
3553 if (ival != NULL) {
3554 args = PyTuple_New(1);
3555 if (args != NULL) {
3556 PyTuple_SET_ITEM(args, 0, ival);
3557 retval = PyObject_Call(func, args, NULL);
3558 Py_XDECREF(args);
3559 Py_XDECREF(func);
3560 return retval;
3561 }
3562 }
3563 }
3564 else {
3565 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3566 }
3567 Py_XDECREF(args);
3568 Py_XDECREF(ival);
3569 Py_XDECREF(func);
3570 return NULL;
3571}
3572
Guido van Rossumdc91b992001-08-08 22:26:22 +00003573SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003574
3575static int
3576slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3577{
3578 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003579 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003580
3581 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003582 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003583 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003584 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003585 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003586 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003587 if (res == NULL)
3588 return -1;
3589 Py_DECREF(res);
3590 return 0;
3591}
3592
3593static int
3594slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3595{
3596 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003597 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003598
3599 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003600 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003601 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003603 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003604 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003605 if (res == NULL)
3606 return -1;
3607 Py_DECREF(res);
3608 return 0;
3609}
3610
3611static int
3612slot_sq_contains(PyObject *self, PyObject *value)
3613{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003614 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003615 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003616
Guido van Rossum55f20992001-10-01 17:18:22 +00003617 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003618
3619 if (func != NULL) {
3620 args = Py_BuildValue("(O)", value);
3621 if (args == NULL)
3622 res = NULL;
3623 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003624 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003625 Py_DECREF(args);
3626 }
3627 Py_DECREF(func);
3628 if (res == NULL)
3629 return -1;
3630 return PyObject_IsTrue(res);
3631 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003632 else if (PyErr_Occurred())
3633 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003634 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003635 return _PySequence_IterSearch(self, value,
3636 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003637 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003638}
3639
Guido van Rossumdc91b992001-08-08 22:26:22 +00003640SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3641SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003642
3643#define slot_mp_length slot_sq_length
3644
Guido van Rossumdc91b992001-08-08 22:26:22 +00003645SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003646
3647static int
3648slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3649{
3650 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003651 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003652
3653 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003654 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003655 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003656 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003657 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003658 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003659 if (res == NULL)
3660 return -1;
3661 Py_DECREF(res);
3662 return 0;
3663}
3664
Guido van Rossumdc91b992001-08-08 22:26:22 +00003665SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3666SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3667SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3668SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3669SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3670SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3671
Jeremy Hylton938ace62002-07-17 16:30:39 +00003672static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003673
3674SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3675 nb_power, "__pow__", "__rpow__")
3676
3677static PyObject *
3678slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3679{
Guido van Rossum2730b132001-08-28 18:22:14 +00003680 static PyObject *pow_str;
3681
Guido van Rossumdc91b992001-08-08 22:26:22 +00003682 if (modulus == Py_None)
3683 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003684 /* Three-arg power doesn't use __rpow__. But ternary_op
3685 can call this when the second argument's type uses
3686 slot_nb_power, so check before calling self.__pow__. */
3687 if (self->ob_type->tp_as_number != NULL &&
3688 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3689 return call_method(self, "__pow__", &pow_str,
3690 "(OO)", other, modulus);
3691 }
3692 Py_INCREF(Py_NotImplemented);
3693 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003694}
3695
3696SLOT0(slot_nb_negative, "__neg__")
3697SLOT0(slot_nb_positive, "__pos__")
3698SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003699
3700static int
3701slot_nb_nonzero(PyObject *self)
3702{
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003703 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003704 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003705
Guido van Rossum55f20992001-10-01 17:18:22 +00003706 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003707 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003708 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003709 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003710 func = lookup_maybe(self, "__len__", &len_str);
3711 if (func == NULL) {
3712 if (PyErr_Occurred())
3713 return -1;
3714 else
3715 return 1;
3716 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003717 }
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003718 args = res = PyTuple_New(0);
3719 if (args != NULL) {
3720 res = PyObject_Call(func, args, NULL);
3721 Py_DECREF(args);
3722 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003723 Py_DECREF(func);
3724 if (res == NULL)
3725 return -1;
3726 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003727}
3728
Guido van Rossumdc91b992001-08-08 22:26:22 +00003729SLOT0(slot_nb_invert, "__invert__")
3730SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3731SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3732SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3733SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3734SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003735
3736static int
3737slot_nb_coerce(PyObject **a, PyObject **b)
3738{
3739 static PyObject *coerce_str;
3740 PyObject *self = *a, *other = *b;
3741
3742 if (self->ob_type->tp_as_number != NULL &&
3743 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3744 PyObject *r;
3745 r = call_maybe(
3746 self, "__coerce__", &coerce_str, "(O)", other);
3747 if (r == NULL)
3748 return -1;
3749 if (r == Py_NotImplemented) {
3750 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003751 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003752 else {
3753 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3754 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003755 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003756 Py_DECREF(r);
3757 return -1;
3758 }
3759 *a = PyTuple_GET_ITEM(r, 0);
3760 Py_INCREF(*a);
3761 *b = PyTuple_GET_ITEM(r, 1);
3762 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003763 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003764 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003765 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003766 }
3767 if (other->ob_type->tp_as_number != NULL &&
3768 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3769 PyObject *r;
3770 r = call_maybe(
3771 other, "__coerce__", &coerce_str, "(O)", self);
3772 if (r == NULL)
3773 return -1;
3774 if (r == Py_NotImplemented) {
3775 Py_DECREF(r);
3776 return 1;
3777 }
3778 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3779 PyErr_SetString(PyExc_TypeError,
3780 "__coerce__ didn't return a 2-tuple");
3781 Py_DECREF(r);
3782 return -1;
3783 }
3784 *a = PyTuple_GET_ITEM(r, 1);
3785 Py_INCREF(*a);
3786 *b = PyTuple_GET_ITEM(r, 0);
3787 Py_INCREF(*b);
3788 Py_DECREF(r);
3789 return 0;
3790 }
3791 return 1;
3792}
3793
Guido van Rossumdc91b992001-08-08 22:26:22 +00003794SLOT0(slot_nb_int, "__int__")
3795SLOT0(slot_nb_long, "__long__")
3796SLOT0(slot_nb_float, "__float__")
3797SLOT0(slot_nb_oct, "__oct__")
3798SLOT0(slot_nb_hex, "__hex__")
3799SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3800SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3801SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3802SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3803SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003804SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003805SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3806SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3807SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3808SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3809SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3810SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3811 "__floordiv__", "__rfloordiv__")
3812SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3813SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3814SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003815
3816static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003817half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003818{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003819 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003820 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003821 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003822
Guido van Rossum60718732001-08-28 17:47:51 +00003823 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003824 if (func == NULL) {
3825 PyErr_Clear();
3826 }
3827 else {
3828 args = Py_BuildValue("(O)", other);
3829 if (args == NULL)
3830 res = NULL;
3831 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003832 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003833 Py_DECREF(args);
3834 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003835 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003836 if (res != Py_NotImplemented) {
3837 if (res == NULL)
3838 return -2;
3839 c = PyInt_AsLong(res);
3840 Py_DECREF(res);
3841 if (c == -1 && PyErr_Occurred())
3842 return -2;
3843 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3844 }
3845 Py_DECREF(res);
3846 }
3847 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848}
3849
Guido van Rossumab3b0342001-09-18 20:38:53 +00003850/* This slot is published for the benefit of try_3way_compare in object.c */
3851int
3852_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003853{
3854 int c;
3855
Guido van Rossumab3b0342001-09-18 20:38:53 +00003856 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003857 c = half_compare(self, other);
3858 if (c <= 1)
3859 return c;
3860 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003861 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003862 c = half_compare(other, self);
3863 if (c < -1)
3864 return -2;
3865 if (c <= 1)
3866 return -c;
3867 }
3868 return (void *)self < (void *)other ? -1 :
3869 (void *)self > (void *)other ? 1 : 0;
3870}
3871
3872static PyObject *
3873slot_tp_repr(PyObject *self)
3874{
3875 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003876 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003877
Guido van Rossum60718732001-08-28 17:47:51 +00003878 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003879 if (func != NULL) {
3880 res = PyEval_CallObject(func, NULL);
3881 Py_DECREF(func);
3882 return res;
3883 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003884 PyErr_Clear();
3885 return PyString_FromFormat("<%s object at %p>",
3886 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003887}
3888
3889static PyObject *
3890slot_tp_str(PyObject *self)
3891{
3892 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003893 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003894
Guido van Rossum60718732001-08-28 17:47:51 +00003895 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003896 if (func != NULL) {
3897 res = PyEval_CallObject(func, NULL);
3898 Py_DECREF(func);
3899 return res;
3900 }
3901 else {
3902 PyErr_Clear();
3903 return slot_tp_repr(self);
3904 }
3905}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003906
3907static long
3908slot_tp_hash(PyObject *self)
3909{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003910 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003911 static PyObject *hash_str, *eq_str, *cmp_str;
3912
Tim Peters6d6c1a32001-08-02 04:15:00 +00003913 long h;
3914
Guido van Rossum60718732001-08-28 17:47:51 +00003915 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003916
3917 if (func != NULL) {
3918 res = PyEval_CallObject(func, NULL);
3919 Py_DECREF(func);
3920 if (res == NULL)
3921 return -1;
3922 h = PyInt_AsLong(res);
3923 }
3924 else {
3925 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003926 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003927 if (func == NULL) {
3928 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003929 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003930 }
3931 if (func != NULL) {
3932 Py_DECREF(func);
3933 PyErr_SetString(PyExc_TypeError, "unhashable type");
3934 return -1;
3935 }
3936 PyErr_Clear();
3937 h = _Py_HashPointer((void *)self);
3938 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003939 if (h == -1 && !PyErr_Occurred())
3940 h = -2;
3941 return h;
3942}
3943
3944static PyObject *
3945slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3946{
Guido van Rossum60718732001-08-28 17:47:51 +00003947 static PyObject *call_str;
3948 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003949 PyObject *res;
3950
3951 if (meth == NULL)
3952 return NULL;
3953 res = PyObject_Call(meth, args, kwds);
3954 Py_DECREF(meth);
3955 return res;
3956}
3957
Guido van Rossum14a6f832001-10-17 13:59:09 +00003958/* There are two slot dispatch functions for tp_getattro.
3959
3960 - slot_tp_getattro() is used when __getattribute__ is overridden
3961 but no __getattr__ hook is present;
3962
3963 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3964
Guido van Rossumc334df52002-04-04 23:44:47 +00003965 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3966 detects the absence of __getattr__ and then installs the simpler slot if
3967 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003968
Tim Peters6d6c1a32001-08-02 04:15:00 +00003969static PyObject *
3970slot_tp_getattro(PyObject *self, PyObject *name)
3971{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003972 static PyObject *getattribute_str = NULL;
3973 return call_method(self, "__getattribute__", &getattribute_str,
3974 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003975}
3976
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003977static PyObject *
3978slot_tp_getattr_hook(PyObject *self, PyObject *name)
3979{
3980 PyTypeObject *tp = self->ob_type;
3981 PyObject *getattr, *getattribute, *res;
3982 static PyObject *getattribute_str = NULL;
3983 static PyObject *getattr_str = NULL;
3984
3985 if (getattr_str == NULL) {
3986 getattr_str = PyString_InternFromString("__getattr__");
3987 if (getattr_str == NULL)
3988 return NULL;
3989 }
3990 if (getattribute_str == NULL) {
3991 getattribute_str =
3992 PyString_InternFromString("__getattribute__");
3993 if (getattribute_str == NULL)
3994 return NULL;
3995 }
3996 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00003997 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00003998 /* No __getattr__ hook: use a simpler dispatcher */
3999 tp->tp_getattro = slot_tp_getattro;
4000 return slot_tp_getattro(self, name);
4001 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004002 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004003 if (getattribute == NULL ||
4004 (getattribute->ob_type == &PyWrapperDescr_Type &&
4005 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4006 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004007 res = PyObject_GenericGetAttr(self, name);
4008 else
4009 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004010 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004011 PyErr_Clear();
4012 res = PyObject_CallFunction(getattr, "OO", self, name);
4013 }
4014 return res;
4015}
4016
Tim Peters6d6c1a32001-08-02 04:15:00 +00004017static int
4018slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4019{
4020 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004021 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004022
4023 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004024 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004025 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004026 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004027 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004028 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004029 if (res == NULL)
4030 return -1;
4031 Py_DECREF(res);
4032 return 0;
4033}
4034
4035/* Map rich comparison operators to their __xx__ namesakes */
4036static char *name_op[] = {
4037 "__lt__",
4038 "__le__",
4039 "__eq__",
4040 "__ne__",
4041 "__gt__",
4042 "__ge__",
4043};
4044
4045static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004046half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004047{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004048 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004049 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004050
Guido van Rossum60718732001-08-28 17:47:51 +00004051 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004052 if (func == NULL) {
4053 PyErr_Clear();
4054 Py_INCREF(Py_NotImplemented);
4055 return Py_NotImplemented;
4056 }
4057 args = Py_BuildValue("(O)", other);
4058 if (args == NULL)
4059 res = NULL;
4060 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004061 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004062 Py_DECREF(args);
4063 }
4064 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004065 return res;
4066}
4067
Guido van Rossumb8f63662001-08-15 23:57:02 +00004068/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4069static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4070
4071static PyObject *
4072slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4073{
4074 PyObject *res;
4075
4076 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4077 res = half_richcompare(self, other, op);
4078 if (res != Py_NotImplemented)
4079 return res;
4080 Py_DECREF(res);
4081 }
4082 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4083 res = half_richcompare(other, self, swapped_op[op]);
4084 if (res != Py_NotImplemented) {
4085 return res;
4086 }
4087 Py_DECREF(res);
4088 }
4089 Py_INCREF(Py_NotImplemented);
4090 return Py_NotImplemented;
4091}
4092
4093static PyObject *
4094slot_tp_iter(PyObject *self)
4095{
4096 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004097 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004098
Guido van Rossum60718732001-08-28 17:47:51 +00004099 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004100 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004101 PyObject *args;
4102 args = res = PyTuple_New(0);
4103 if (args != NULL) {
4104 res = PyObject_Call(func, args, NULL);
4105 Py_DECREF(args);
4106 }
4107 Py_DECREF(func);
4108 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004109 }
4110 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004111 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004112 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004113 PyErr_SetString(PyExc_TypeError,
4114 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004115 return NULL;
4116 }
4117 Py_DECREF(func);
4118 return PySeqIter_New(self);
4119}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004120
4121static PyObject *
4122slot_tp_iternext(PyObject *self)
4123{
Guido van Rossum2730b132001-08-28 18:22:14 +00004124 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004125 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004126}
4127
Guido van Rossum1a493502001-08-17 16:47:50 +00004128static PyObject *
4129slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4130{
4131 PyTypeObject *tp = self->ob_type;
4132 PyObject *get;
4133 static PyObject *get_str = NULL;
4134
4135 if (get_str == NULL) {
4136 get_str = PyString_InternFromString("__get__");
4137 if (get_str == NULL)
4138 return NULL;
4139 }
4140 get = _PyType_Lookup(tp, get_str);
4141 if (get == NULL) {
4142 /* Avoid further slowdowns */
4143 if (tp->tp_descr_get == slot_tp_descr_get)
4144 tp->tp_descr_get = NULL;
4145 Py_INCREF(self);
4146 return self;
4147 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004148 if (obj == NULL)
4149 obj = Py_None;
4150 if (type == NULL)
4151 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004152 return PyObject_CallFunction(get, "OOO", self, obj, type);
4153}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004154
4155static int
4156slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4157{
Guido van Rossum2c252392001-08-24 10:13:31 +00004158 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004159 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004160
4161 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004162 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004163 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004164 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004165 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004166 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004167 if (res == NULL)
4168 return -1;
4169 Py_DECREF(res);
4170 return 0;
4171}
4172
4173static int
4174slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4175{
Guido van Rossum60718732001-08-28 17:47:51 +00004176 static PyObject *init_str;
4177 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004178 PyObject *res;
4179
4180 if (meth == NULL)
4181 return -1;
4182 res = PyObject_Call(meth, args, kwds);
4183 Py_DECREF(meth);
4184 if (res == NULL)
4185 return -1;
4186 Py_DECREF(res);
4187 return 0;
4188}
4189
4190static PyObject *
4191slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4192{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004193 static PyObject *new_str;
4194 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004195 PyObject *newargs, *x;
4196 int i, n;
4197
Guido van Rossum7bed2132002-08-08 21:57:53 +00004198 if (new_str == NULL) {
4199 new_str = PyString_InternFromString("__new__");
4200 if (new_str == NULL)
4201 return NULL;
4202 }
4203 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204 if (func == NULL)
4205 return NULL;
4206 assert(PyTuple_Check(args));
4207 n = PyTuple_GET_SIZE(args);
4208 newargs = PyTuple_New(n+1);
4209 if (newargs == NULL)
4210 return NULL;
4211 Py_INCREF(type);
4212 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4213 for (i = 0; i < n; i++) {
4214 x = PyTuple_GET_ITEM(args, i);
4215 Py_INCREF(x);
4216 PyTuple_SET_ITEM(newargs, i+1, x);
4217 }
4218 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004219 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004220 Py_DECREF(func);
4221 return x;
4222}
4223
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004224static void
4225slot_tp_del(PyObject *self)
4226{
4227 static PyObject *del_str = NULL;
4228 PyObject *del, *res;
4229 PyObject *error_type, *error_value, *error_traceback;
4230
4231 /* Temporarily resurrect the object. */
4232 assert(self->ob_refcnt == 0);
4233 self->ob_refcnt = 1;
4234
4235 /* Save the current exception, if any. */
4236 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4237
4238 /* Execute __del__ method, if any. */
4239 del = lookup_maybe(self, "__del__", &del_str);
4240 if (del != NULL) {
4241 res = PyEval_CallObject(del, NULL);
4242 if (res == NULL)
4243 PyErr_WriteUnraisable(del);
4244 else
4245 Py_DECREF(res);
4246 Py_DECREF(del);
4247 }
4248
4249 /* Restore the saved exception. */
4250 PyErr_Restore(error_type, error_value, error_traceback);
4251
4252 /* Undo the temporary resurrection; can't use DECREF here, it would
4253 * cause a recursive call.
4254 */
4255 assert(self->ob_refcnt > 0);
4256 if (--self->ob_refcnt == 0)
4257 return; /* this is the normal path out */
4258
4259 /* __del__ resurrected it! Make it look like the original Py_DECREF
4260 * never happened.
4261 */
4262 {
4263 int refcnt = self->ob_refcnt;
4264 _Py_NewReference(self);
4265 self->ob_refcnt = refcnt;
4266 }
4267 assert(!PyType_IS_GC(self->ob_type) ||
4268 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4269 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4270 * _Py_NewReference bumped it again, so that's a wash.
4271 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4272 * chain, so no more to do there either.
4273 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4274 * _Py_NewReference bumped tp_allocs: both of those need to be
4275 * undone.
4276 */
4277#ifdef COUNT_ALLOCS
4278 --self->ob_type->tp_frees;
4279 --self->ob_type->tp_allocs;
4280#endif
4281}
4282
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004283
4284/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4285 functions. The offsets here are relative to the 'etype' structure, which
4286 incorporates the additional structures used for numbers, sequences and
4287 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4288 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004289 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4290 terminated with an all-zero entry. (This table is further initialized and
4291 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004292
Guido van Rossum6d204072001-10-21 00:44:31 +00004293typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004294
4295#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004296#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004297#undef ETSLOT
4298#undef SQSLOT
4299#undef MPSLOT
4300#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004301#undef UNSLOT
4302#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004303#undef BINSLOT
4304#undef RBINSLOT
4305
Guido van Rossum6d204072001-10-21 00:44:31 +00004306#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004307 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4308 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004309#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4310 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004311 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004312#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004313 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4314 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004315#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4316 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4317#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4318 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4319#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4320 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4321#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4322 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4323 "x." NAME "() <==> " DOC)
4324#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4325 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4326 "x." NAME "(y) <==> x" DOC "y")
4327#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4328 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4329 "x." NAME "(y) <==> x" DOC "y")
4330#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4331 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4332 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004333
4334static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004335 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4336 "x.__len__() <==> len(x)"),
4337 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4338 "x.__add__(y) <==> x+y"),
4339 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4340 "x.__mul__(n) <==> x*n"),
4341 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4342 "x.__rmul__(n) <==> n*x"),
4343 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4344 "x.__getitem__(y) <==> x[y]"),
4345 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4346 "x.__getslice__(i, j) <==> x[i:j]"),
4347 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4348 "x.__setitem__(i, y) <==> x[i]=y"),
4349 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4350 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004351 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004352 wrap_intintobjargproc,
4353 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4354 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4355 "x.__delslice__(i, j) <==> del x[i:j]"),
4356 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4357 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004358 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004359 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004360 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004361 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004362
Guido van Rossum6d204072001-10-21 00:44:31 +00004363 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4364 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004365 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004366 wrap_binaryfunc,
4367 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004368 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004369 wrap_objobjargproc,
4370 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004371 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004372 wrap_delitem,
4373 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004374
Guido van Rossum6d204072001-10-21 00:44:31 +00004375 BINSLOT("__add__", nb_add, slot_nb_add,
4376 "+"),
4377 RBINSLOT("__radd__", nb_add, slot_nb_add,
4378 "+"),
4379 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4380 "-"),
4381 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4382 "-"),
4383 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4384 "*"),
4385 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4386 "*"),
4387 BINSLOT("__div__", nb_divide, slot_nb_divide,
4388 "/"),
4389 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4390 "/"),
4391 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4392 "%"),
4393 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4394 "%"),
4395 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4396 "divmod(x, y)"),
4397 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4398 "divmod(y, x)"),
4399 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4400 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4401 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4402 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4403 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4404 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4405 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4406 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004407 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004408 "x != 0"),
4409 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4410 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4411 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4412 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4413 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4414 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4415 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4416 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4417 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4418 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4419 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4420 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4421 "x.__coerce__(y) <==> coerce(x, y)"),
4422 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4423 "int(x)"),
4424 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4425 "long(x)"),
4426 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4427 "float(x)"),
4428 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4429 "oct(x)"),
4430 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4431 "hex(x)"),
4432 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4433 wrap_binaryfunc, "+"),
4434 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4435 wrap_binaryfunc, "-"),
4436 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4437 wrap_binaryfunc, "*"),
4438 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4439 wrap_binaryfunc, "/"),
4440 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4441 wrap_binaryfunc, "%"),
4442 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004443 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004444 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4445 wrap_binaryfunc, "<<"),
4446 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4447 wrap_binaryfunc, ">>"),
4448 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4449 wrap_binaryfunc, "&"),
4450 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4451 wrap_binaryfunc, "^"),
4452 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4453 wrap_binaryfunc, "|"),
4454 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4455 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4456 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4457 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4458 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4459 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4460 IBSLOT("__itruediv__", nb_inplace_true_divide,
4461 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004462
Guido van Rossum6d204072001-10-21 00:44:31 +00004463 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4464 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004465 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004466 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4467 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004468 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004469 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4470 "x.__cmp__(y) <==> cmp(x,y)"),
4471 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4472 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004473 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4474 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004475 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004476 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4477 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4478 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4479 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4480 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4481 "x.__setattr__('name', value) <==> x.name = value"),
4482 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4483 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4484 "x.__delattr__('name') <==> del x.name"),
4485 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4486 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4487 "x.__lt__(y) <==> x<y"),
4488 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4489 "x.__le__(y) <==> x<=y"),
4490 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4491 "x.__eq__(y) <==> x==y"),
4492 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4493 "x.__ne__(y) <==> x!=y"),
4494 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4495 "x.__gt__(y) <==> x>y"),
4496 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4497 "x.__ge__(y) <==> x>=y"),
4498 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4499 "x.__iter__() <==> iter(x)"),
4500 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4501 "x.next() -> the next value, or raise StopIteration"),
4502 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4503 "descr.__get__(obj[, type]) -> value"),
4504 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4505 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004506 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4507 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004508 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004509 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004510 "see x.__class__.__doc__ for signature",
4511 PyWrapperFlag_KEYWORDS),
4512 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004513 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004514 {NULL}
4515};
4516
Guido van Rossumc334df52002-04-04 23:44:47 +00004517/* Given a type pointer and an offset gotten from a slotdef entry, return a
4518 pointer to the actual slot. This is not quite the same as simply adding
4519 the offset to the type pointer, since it takes care to indirect through the
4520 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4521 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004522static void **
4523slotptr(PyTypeObject *type, int offset)
4524{
4525 char *ptr;
4526
Guido van Rossum09638c12002-06-13 19:17:46 +00004527 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004528 assert(offset >= 0);
4529 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004530 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004531 ptr = (void *)type->tp_as_sequence;
4532 offset -= offsetof(etype, as_sequence);
4533 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004534 else if (offset >= offsetof(etype, as_mapping)) {
4535 ptr = (void *)type->tp_as_mapping;
4536 offset -= offsetof(etype, as_mapping);
4537 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004538 else if (offset >= offsetof(etype, as_number)) {
4539 ptr = (void *)type->tp_as_number;
4540 offset -= offsetof(etype, as_number);
4541 }
4542 else {
4543 ptr = (void *)type;
4544 }
4545 if (ptr != NULL)
4546 ptr += offset;
4547 return (void **)ptr;
4548}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004549
Guido van Rossumc334df52002-04-04 23:44:47 +00004550/* Length of array of slotdef pointers used to store slots with the
4551 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4552 the same __name__, for any __name__. Since that's a static property, it is
4553 appropriate to declare fixed-size arrays for this. */
4554#define MAX_EQUIV 10
4555
4556/* Return a slot pointer for a given name, but ONLY if the attribute has
4557 exactly one slot function. The name must be an interned string. */
4558static void **
4559resolve_slotdups(PyTypeObject *type, PyObject *name)
4560{
4561 /* XXX Maybe this could be optimized more -- but is it worth it? */
4562
4563 /* pname and ptrs act as a little cache */
4564 static PyObject *pname;
4565 static slotdef *ptrs[MAX_EQUIV];
4566 slotdef *p, **pp;
4567 void **res, **ptr;
4568
4569 if (pname != name) {
4570 /* Collect all slotdefs that match name into ptrs. */
4571 pname = name;
4572 pp = ptrs;
4573 for (p = slotdefs; p->name_strobj; p++) {
4574 if (p->name_strobj == name)
4575 *pp++ = p;
4576 }
4577 *pp = NULL;
4578 }
4579
4580 /* Look in all matching slots of the type; if exactly one of these has
4581 a filled-in slot, return its value. Otherwise return NULL. */
4582 res = NULL;
4583 for (pp = ptrs; *pp; pp++) {
4584 ptr = slotptr(type, (*pp)->offset);
4585 if (ptr == NULL || *ptr == NULL)
4586 continue;
4587 if (res != NULL)
4588 return NULL;
4589 res = ptr;
4590 }
4591 return res;
4592}
4593
4594/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4595 does some incredibly complex thinking and then sticks something into the
4596 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4597 interests, and then stores a generic wrapper or a specific function into
4598 the slot.) Return a pointer to the next slotdef with a different offset,
4599 because that's convenient for fixup_slot_dispatchers(). */
4600static slotdef *
4601update_one_slot(PyTypeObject *type, slotdef *p)
4602{
4603 PyObject *descr;
4604 PyWrapperDescrObject *d;
4605 void *generic = NULL, *specific = NULL;
4606 int use_generic = 0;
4607 int offset = p->offset;
4608 void **ptr = slotptr(type, offset);
4609
4610 if (ptr == NULL) {
4611 do {
4612 ++p;
4613 } while (p->offset == offset);
4614 return p;
4615 }
4616 do {
4617 descr = _PyType_Lookup(type, p->name_strobj);
4618 if (descr == NULL)
4619 continue;
4620 if (descr->ob_type == &PyWrapperDescr_Type) {
4621 void **tptr = resolve_slotdups(type, p->name_strobj);
4622 if (tptr == NULL || tptr == ptr)
4623 generic = p->function;
4624 d = (PyWrapperDescrObject *)descr;
4625 if (d->d_base->wrapper == p->wrapper &&
4626 PyType_IsSubtype(type, d->d_type))
4627 {
4628 if (specific == NULL ||
4629 specific == d->d_wrapped)
4630 specific = d->d_wrapped;
4631 else
4632 use_generic = 1;
4633 }
4634 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004635 else if (descr->ob_type == &PyCFunction_Type &&
4636 PyCFunction_GET_FUNCTION(descr) ==
4637 (PyCFunction)tp_new_wrapper &&
4638 strcmp(p->name, "__new__") == 0)
4639 {
4640 /* The __new__ wrapper is not a wrapper descriptor,
4641 so must be special-cased differently.
4642 If we don't do this, creating an instance will
4643 always use slot_tp_new which will look up
4644 __new__ in the MRO which will call tp_new_wrapper
4645 which will look through the base classes looking
4646 for a static base and call its tp_new (usually
4647 PyType_GenericNew), after performing various
4648 sanity checks and constructing a new argument
4649 list. Cut all that nonsense short -- this speeds
4650 up instance creation tremendously. */
4651 specific = type->tp_new;
4652 /* XXX I'm not 100% sure that there isn't a hole
4653 in this reasoning that requires additional
4654 sanity checks. I'll buy the first person to
4655 point out a bug in this reasoning a beer. */
4656 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004657 else {
4658 use_generic = 1;
4659 generic = p->function;
4660 }
4661 } while ((++p)->offset == offset);
4662 if (specific && !use_generic)
4663 *ptr = specific;
4664 else
4665 *ptr = generic;
4666 return p;
4667}
4668
Guido van Rossum22b13872002-08-06 21:41:44 +00004669static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004670 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004671
Guido van Rossumc334df52002-04-04 23:44:47 +00004672/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4673 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004674static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004675update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004676{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004677 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004678
Guido van Rossumc334df52002-04-04 23:44:47 +00004679 for (pp = pp0; *pp; pp++)
4680 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004681 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004682}
4683
Guido van Rossumc334df52002-04-04 23:44:47 +00004684/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4685 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004686static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004687recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004688{
4689 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004690 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004691 int i, n;
4692
4693 subclasses = type->tp_subclasses;
4694 if (subclasses == NULL)
4695 return 0;
4696 assert(PyList_Check(subclasses));
4697 n = PyList_GET_SIZE(subclasses);
4698 for (i = 0; i < n; i++) {
4699 ref = PyList_GET_ITEM(subclasses, i);
4700 assert(PyWeakref_CheckRef(ref));
4701 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004702 assert(subclass != NULL);
4703 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004704 continue;
4705 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004706 /* Avoid recursing down into unaffected classes */
4707 dict = subclass->tp_dict;
4708 if (dict != NULL && PyDict_Check(dict) &&
4709 PyDict_GetItem(dict, name) != NULL)
4710 continue;
4711 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004712 return -1;
4713 }
4714 return 0;
4715}
4716
Guido van Rossumc334df52002-04-04 23:44:47 +00004717/* Comparison function for qsort() to compare slotdefs by their offset, and
4718 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004719static int
4720slotdef_cmp(const void *aa, const void *bb)
4721{
4722 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4723 int c = a->offset - b->offset;
4724 if (c != 0)
4725 return c;
4726 else
4727 return a - b;
4728}
4729
Guido van Rossumc334df52002-04-04 23:44:47 +00004730/* Initialize the slotdefs table by adding interned string objects for the
4731 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004732static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004733init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004734{
4735 slotdef *p;
4736 static int initialized = 0;
4737
4738 if (initialized)
4739 return;
4740 for (p = slotdefs; p->name; p++) {
4741 p->name_strobj = PyString_InternFromString(p->name);
4742 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004743 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004744 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004745 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4746 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004747 initialized = 1;
4748}
4749
Guido van Rossumc334df52002-04-04 23:44:47 +00004750/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004751static int
4752update_slot(PyTypeObject *type, PyObject *name)
4753{
Guido van Rossumc334df52002-04-04 23:44:47 +00004754 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004755 slotdef *p;
4756 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004757 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004758
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004759 init_slotdefs();
4760 pp = ptrs;
4761 for (p = slotdefs; p->name; p++) {
4762 /* XXX assume name is interned! */
4763 if (p->name_strobj == name)
4764 *pp++ = p;
4765 }
4766 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004767 for (pp = ptrs; *pp; pp++) {
4768 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004769 offset = p->offset;
4770 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004771 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004772 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004773 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004774 if (ptrs[0] == NULL)
4775 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004776 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004777}
4778
Guido van Rossumc334df52002-04-04 23:44:47 +00004779/* Store the proper functions in the slot dispatches at class (type)
4780 definition time, based upon which operations the class overrides in its
4781 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004782static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004783fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004784{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004785 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004786
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004787 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004788 for (p = slotdefs; p->name; )
4789 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004790}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004791
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004792static void
4793update_all_slots(PyTypeObject* type)
4794{
4795 slotdef *p;
4796
4797 init_slotdefs();
4798 for (p = slotdefs; p->name; p++) {
4799 /* update_slot returns int but can't actually fail */
4800 update_slot(type, p->name_strobj);
4801 }
4802}
4803
Guido van Rossum6d204072001-10-21 00:44:31 +00004804/* This function is called by PyType_Ready() to populate the type's
4805 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004806 function slot (like tp_repr) that's defined in the type, one or more
4807 corresponding descriptors are added in the type's tp_dict dictionary
4808 under the appropriate name (like __repr__). Some function slots
4809 cause more than one descriptor to be added (for example, the nb_add
4810 slot adds both __add__ and __radd__ descriptors) and some function
4811 slots compete for the same descriptor (for example both sq_item and
4812 mp_subscript generate a __getitem__ descriptor).
4813
4814 In the latter case, the first slotdef entry encoutered wins. Since
4815 slotdef entries are sorted by the offset of the slot in the etype
4816 struct, this gives us some control over disambiguating between
4817 competing slots: the members of struct etype are listed from most
4818 general to least general, so the most general slot is preferred. In
4819 particular, because as_mapping comes before as_sequence, for a type
4820 that defines both mp_subscript and sq_item, mp_subscript wins.
4821
4822 This only adds new descriptors and doesn't overwrite entries in
4823 tp_dict that were previously defined. The descriptors contain a
4824 reference to the C function they must call, so that it's safe if they
4825 are copied into a subtype's __dict__ and the subtype has a different
4826 C function in its slot -- calling the method defined by the
4827 descriptor will call the C function that was used to create it,
4828 rather than the C function present in the slot when it is called.
4829 (This is important because a subtype may have a C function in the
4830 slot that calls the method from the dictionary, and we want to avoid
4831 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004832
4833static int
4834add_operators(PyTypeObject *type)
4835{
4836 PyObject *dict = type->tp_dict;
4837 slotdef *p;
4838 PyObject *descr;
4839 void **ptr;
4840
4841 init_slotdefs();
4842 for (p = slotdefs; p->name; p++) {
4843 if (p->wrapper == NULL)
4844 continue;
4845 ptr = slotptr(type, p->offset);
4846 if (!ptr || !*ptr)
4847 continue;
4848 if (PyDict_GetItem(dict, p->name_strobj))
4849 continue;
4850 descr = PyDescr_NewWrapper(type, p, *ptr);
4851 if (descr == NULL)
4852 return -1;
4853 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4854 return -1;
4855 Py_DECREF(descr);
4856 }
4857 if (type->tp_new != NULL) {
4858 if (add_tp_new_wrapper(type) < 0)
4859 return -1;
4860 }
4861 return 0;
4862}
4863
Guido van Rossum705f0f52001-08-24 16:47:00 +00004864
4865/* Cooperative 'super' */
4866
4867typedef struct {
4868 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004869 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004870 PyObject *obj;
4871} superobject;
4872
Guido van Rossum6f799372001-09-20 20:46:19 +00004873static PyMemberDef super_members[] = {
4874 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4875 "the class invoking super()"},
4876 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4877 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004878 {0}
4879};
4880
Guido van Rossum705f0f52001-08-24 16:47:00 +00004881static void
4882super_dealloc(PyObject *self)
4883{
4884 superobject *su = (superobject *)self;
4885
Guido van Rossum048eb752001-10-02 21:24:57 +00004886 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004887 Py_XDECREF(su->obj);
4888 Py_XDECREF(su->type);
4889 self->ob_type->tp_free(self);
4890}
4891
4892static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004893super_repr(PyObject *self)
4894{
4895 superobject *su = (superobject *)self;
4896
4897 if (su->obj)
4898 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004899 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004900 su->type ? su->type->tp_name : "NULL",
4901 su->obj->ob_type->tp_name);
4902 else
4903 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004904 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004905 su->type ? su->type->tp_name : "NULL");
4906}
4907
4908static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004909super_getattro(PyObject *self, PyObject *name)
4910{
4911 superobject *su = (superobject *)self;
4912
4913 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004914 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004915 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004916 descrgetfunc f;
4917 int i, n;
4918
Guido van Rossum155db9a2002-04-02 17:53:47 +00004919 starttype = su->obj->ob_type;
4920 mro = starttype->tp_mro;
4921
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004922 if (mro == NULL)
4923 n = 0;
4924 else {
4925 assert(PyTuple_Check(mro));
4926 n = PyTuple_GET_SIZE(mro);
4927 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004928 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004929 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004930 break;
4931 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004932 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004933 starttype = (PyTypeObject *)(su->obj);
4934 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004935 if (mro == NULL)
4936 n = 0;
4937 else {
4938 assert(PyTuple_Check(mro));
4939 n = PyTuple_GET_SIZE(mro);
4940 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004941 for (i = 0; i < n; i++) {
4942 if ((PyObject *)(su->type) ==
4943 PyTuple_GET_ITEM(mro, i))
4944 break;
4945 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004946 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004947 i++;
4948 res = NULL;
4949 for (; i < n; i++) {
4950 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004951 if (PyType_Check(tmp))
4952 dict = ((PyTypeObject *)tmp)->tp_dict;
4953 else if (PyClass_Check(tmp))
4954 dict = ((PyClassObject *)tmp)->cl_dict;
4955 else
4956 continue;
4957 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004958 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004959 Py_INCREF(res);
4960 f = res->ob_type->tp_descr_get;
4961 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004962 tmp = f(res, su->obj,
4963 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004964 Py_DECREF(res);
4965 res = tmp;
4966 }
4967 return res;
4968 }
4969 }
4970 }
4971 return PyObject_GenericGetAttr(self, name);
4972}
4973
Guido van Rossum5b443c62001-12-03 15:38:28 +00004974static int
4975supercheck(PyTypeObject *type, PyObject *obj)
4976{
4977 if (!PyType_IsSubtype(obj->ob_type, type) &&
4978 !(PyType_Check(obj) &&
4979 PyType_IsSubtype((PyTypeObject *)obj, type))) {
4980 PyErr_SetString(PyExc_TypeError,
4981 "super(type, obj): "
4982 "obj must be an instance or subtype of type");
4983 return -1;
4984 }
4985 else
4986 return 0;
4987}
4988
Guido van Rossum705f0f52001-08-24 16:47:00 +00004989static PyObject *
4990super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4991{
4992 superobject *su = (superobject *)self;
4993 superobject *new;
4994
4995 if (obj == NULL || obj == Py_None || su->obj != NULL) {
4996 /* Not binding to an object, or already bound */
4997 Py_INCREF(self);
4998 return self;
4999 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005000 if (su->ob_type != &PySuper_Type)
5001 /* If su is an instance of a subclass of super,
5002 call its type */
5003 return PyObject_CallFunction((PyObject *)su->ob_type,
5004 "OO", su->type, obj);
5005 else {
5006 /* Inline the common case */
5007 if (supercheck(su->type, obj) < 0)
5008 return NULL;
5009 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5010 NULL, NULL);
5011 if (new == NULL)
5012 return NULL;
5013 Py_INCREF(su->type);
5014 Py_INCREF(obj);
5015 new->type = su->type;
5016 new->obj = obj;
5017 return (PyObject *)new;
5018 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005019}
5020
5021static int
5022super_init(PyObject *self, PyObject *args, PyObject *kwds)
5023{
5024 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005025 PyTypeObject *type;
5026 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005027
5028 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5029 return -1;
5030 if (obj == Py_None)
5031 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005032 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005033 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005034 Py_INCREF(type);
5035 Py_XINCREF(obj);
5036 su->type = type;
5037 su->obj = obj;
5038 return 0;
5039}
5040
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005041PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005042"super(type) -> unbound super object\n"
5043"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005044"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005045"Typical use to call a cooperative superclass method:\n"
5046"class C(B):\n"
5047" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005048" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005049
Guido van Rossum048eb752001-10-02 21:24:57 +00005050static int
5051super_traverse(PyObject *self, visitproc visit, void *arg)
5052{
5053 superobject *su = (superobject *)self;
5054 int err;
5055
5056#define VISIT(SLOT) \
5057 if (SLOT) { \
5058 err = visit((PyObject *)(SLOT), arg); \
5059 if (err) \
5060 return err; \
5061 }
5062
5063 VISIT(su->obj);
5064 VISIT(su->type);
5065
5066#undef VISIT
5067
5068 return 0;
5069}
5070
Guido van Rossum705f0f52001-08-24 16:47:00 +00005071PyTypeObject PySuper_Type = {
5072 PyObject_HEAD_INIT(&PyType_Type)
5073 0, /* ob_size */
5074 "super", /* tp_name */
5075 sizeof(superobject), /* tp_basicsize */
5076 0, /* tp_itemsize */
5077 /* methods */
5078 super_dealloc, /* tp_dealloc */
5079 0, /* tp_print */
5080 0, /* tp_getattr */
5081 0, /* tp_setattr */
5082 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005083 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005084 0, /* tp_as_number */
5085 0, /* tp_as_sequence */
5086 0, /* tp_as_mapping */
5087 0, /* tp_hash */
5088 0, /* tp_call */
5089 0, /* tp_str */
5090 super_getattro, /* tp_getattro */
5091 0, /* tp_setattro */
5092 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005093 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5094 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005095 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005096 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005097 0, /* tp_clear */
5098 0, /* tp_richcompare */
5099 0, /* tp_weaklistoffset */
5100 0, /* tp_iter */
5101 0, /* tp_iternext */
5102 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005103 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005104 0, /* tp_getset */
5105 0, /* tp_base */
5106 0, /* tp_dict */
5107 super_descr_get, /* tp_descr_get */
5108 0, /* tp_descr_set */
5109 0, /* tp_dictoffset */
5110 super_init, /* tp_init */
5111 PyType_GenericAlloc, /* tp_alloc */
5112 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005113 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005114};