blob: 949cef58eeeb2a3b2e36c5015134725966e78da2 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
8/* The *real* layout of a type object when allocated on the heap */
9/* XXX Should we publish this in a header file? */
10typedef struct {
Guido van Rossum09638c12002-06-13 19:17:46 +000011 /* Note: there's a dependency on the order of these members
12 in slotptr() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000013 PyTypeObject type;
14 PyNumberMethods as_number;
Guido van Rossum9923ffe2002-06-04 19:52:53 +000015 PyMappingMethods as_mapping;
Guido van Rossum09638c12002-06-13 19:17:46 +000016 PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
17 so that the mapping wins when both
18 the mapping and the sequence define
19 a given operator (e.g. __getitem__).
20 see add_operators() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000021 PyBufferProcs as_buffer;
22 PyObject *name, *slots;
23 PyMemberDef members[1];
24} etype;
25
Guido van Rossum6f799372001-09-20 20:46:19 +000026static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000027 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
28 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
29 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000030 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000031 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
32 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
33 {"__dictoffset__", T_LONG,
34 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000035 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
36 {0}
37};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000038
Guido van Rossumc0b618a1997-05-02 03:12:38 +000039static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000040type_name(PyTypeObject *type, void *context)
41{
42 char *s;
43
44 s = strrchr(type->tp_name, '.');
45 if (s == NULL)
46 s = type->tp_name;
47 else
48 s++;
49 return PyString_FromString(s);
50}
51
Michael W. Hudson98bbc492002-11-26 14:47:27 +000052static int
53type_set_name(PyTypeObject *type, PyObject *value, void *context)
54{
55 etype* et;
56
57 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
58 PyErr_Format(PyExc_TypeError,
59 "can't set %s.__name__", type->tp_name);
60 return -1;
61 }
62 if (!value) {
63 PyErr_Format(PyExc_TypeError,
64 "can't delete %s.__name__", type->tp_name);
65 return -1;
66 }
67 if (!PyString_Check(value)) {
68 PyErr_Format(PyExc_TypeError,
69 "can only assign string to %s.__name__, not '%s'",
70 type->tp_name, value->ob_type->tp_name);
71 return -1;
72 }
73 if (strlen(PyString_AS_STRING(value))
74 != (size_t)PyString_GET_SIZE(value)) {
75 PyErr_Format(PyExc_ValueError,
76 "__name__ must not contain null bytes");
77 return -1;
78 }
79
80 et = (etype*)type;
81
82 Py_INCREF(value);
83
84 Py_DECREF(et->name);
85 et->name = value;
86
87 type->tp_name = PyString_AS_STRING(value);
88
89 return 0;
90}
91
Guido van Rossumc3542212001-08-16 09:18:56 +000092static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000093type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000094{
Guido van Rossumc3542212001-08-16 09:18:56 +000095 PyObject *mod;
96 char *s;
97
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(type->tp_name,
101 (int)(s - type->tp_name));
102 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
103 return PyString_FromString("__builtin__");
Guido van Rossum687ae002001-10-15 22:03:32 +0000104 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000105 if (mod != NULL) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000106 Py_INCREF(mod);
107 return mod;
108 }
109 PyErr_SetString(PyExc_AttributeError, "__module__");
110 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000111}
112
Guido van Rossum3926a632001-09-25 16:25:58 +0000113static int
114type_set_module(PyTypeObject *type, PyObject *value, void *context)
115{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000116 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000117 PyErr_Format(PyExc_TypeError,
118 "can't set %s.__module__", type->tp_name);
119 return -1;
120 }
121 if (!value) {
122 PyErr_Format(PyExc_TypeError,
123 "can't delete %s.__module__", type->tp_name);
124 return -1;
125 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000126
Guido van Rossum3926a632001-09-25 16:25:58 +0000127 return PyDict_SetItemString(type->tp_dict, "__module__", value);
128}
129
Tim Peters6d6c1a32001-08-02 04:15:00 +0000130static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000131type_get_bases(PyTypeObject *type, void *context)
132{
133 Py_INCREF(type->tp_bases);
134 return type->tp_bases;
135}
136
137static PyTypeObject *best_base(PyObject *);
138static int mro_internal(PyTypeObject *);
139static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
140static int add_subclass(PyTypeObject*, PyTypeObject*);
141static void remove_subclass(PyTypeObject *, PyTypeObject *);
142static void update_all_slots(PyTypeObject *);
143
144static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000145mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000146{
147 PyTypeObject *subclass;
148 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000149 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000150
151 subclasses = type->tp_subclasses;
152 if (subclasses == NULL)
153 return 0;
154 assert(PyList_Check(subclasses));
155 n = PyList_GET_SIZE(subclasses);
156 for (i = 0; i < n; i++) {
157 ref = PyList_GET_ITEM(subclasses, i);
158 assert(PyWeakref_CheckRef(ref));
159 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
160 assert(subclass != NULL);
161 if ((PyObject *)subclass == Py_None)
162 continue;
163 assert(PyType_Check(subclass));
164 old_mro = subclass->tp_mro;
165 if (mro_internal(subclass) < 0) {
166 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000167 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000168 }
169 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000170 PyObject* tuple;
171 tuple = Py_BuildValue("OO", subclass, old_mro);
172 if (!tuple)
173 return -1;
174 if (PyList_Append(temp, tuple) < 0)
175 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000176 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000177 if (mro_subclasses(subclass, temp) < 0)
178 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000179 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000180 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000181}
182
183static int
184type_set_bases(PyTypeObject *type, PyObject *value, void *context)
185{
186 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000187 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000188 PyTypeObject *new_base, *old_base;
189 PyObject *old_bases, *old_mro;
190
191 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
192 PyErr_Format(PyExc_TypeError,
193 "can't set %s.__bases__", type->tp_name);
194 return -1;
195 }
196 if (!value) {
197 PyErr_Format(PyExc_TypeError,
198 "can't delete %s.__bases__", type->tp_name);
199 return -1;
200 }
201 if (!PyTuple_Check(value)) {
202 PyErr_Format(PyExc_TypeError,
203 "can only assign tuple to %s.__bases__, not %s",
204 type->tp_name, value->ob_type->tp_name);
205 return -1;
206 }
207 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
208 ob = PyTuple_GET_ITEM(value, i);
209 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
210 PyErr_Format(
211 PyExc_TypeError,
212 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
213 type->tp_name, ob->ob_type->tp_name);
214 return -1;
215 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000216 if (PyType_Check(ob)) {
217 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
218 PyErr_SetString(PyExc_TypeError,
219 "a __bases__ item causes an inheritance cycle");
220 return -1;
221 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000222 }
223 }
224
225 new_base = best_base(value);
226
227 if (!new_base) {
228 return -1;
229 }
230
231 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
232 return -1;
233
234 Py_INCREF(new_base);
235 Py_INCREF(value);
236
237 old_bases = type->tp_bases;
238 old_base = type->tp_base;
239 old_mro = type->tp_mro;
240
241 type->tp_bases = value;
242 type->tp_base = new_base;
243
244 if (mro_internal(type) < 0) {
245 type->tp_bases = old_bases;
246 type->tp_base = old_base;
247 type->tp_mro = old_mro;
248
249 Py_DECREF(value);
250 Py_DECREF(new_base);
251
252 return -1;
253 }
254
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000255 temp = PyList_New(0);
256
257 r = mro_subclasses(type, temp);
258
259 if (r < 0) {
260 for (i = 0; i < PyList_Size(temp); i++) {
261 PyTypeObject* cls;
262 PyObject* mro;
263 PyArg_ParseTuple(PyList_GetItem(temp, i),
264 "OO", &cls, &mro);
265 Py_DECREF(cls->tp_mro);
266 cls->tp_mro = mro;
267 Py_INCREF(cls->tp_mro);
268 }
269 Py_DECREF(temp);
270 return r;
271 }
272
273 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000274
275 /* any base that was in __bases__ but now isn't, we
276 need to remove |type| from it's tp_subclasses.
277 conversely, any class now in __bases__ that wasn't
278 needs to have |type| added to it's subclasses. */
279
280 /* for now, sod that: just remove from all old_bases,
281 add to all new_bases */
282
283 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
284 ob = PyTuple_GET_ITEM(old_bases, i);
285 if (PyType_Check(ob)) {
286 remove_subclass(
287 (PyTypeObject*)ob, type);
288 }
289 }
290
291 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
292 ob = PyTuple_GET_ITEM(value, i);
293 if (PyType_Check(ob)) {
294 if (add_subclass((PyTypeObject*)ob, type) < 0)
295 r = -1;
296 }
297 }
298
299 update_all_slots(type);
300
301 Py_DECREF(old_bases);
302 Py_DECREF(old_base);
303 Py_DECREF(old_mro);
304
305 return r;
306}
307
308static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000309type_dict(PyTypeObject *type, void *context)
310{
311 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312 Py_INCREF(Py_None);
313 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000314 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000315 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000316}
317
Tim Peters24008312002-03-17 18:56:20 +0000318static PyObject *
319type_get_doc(PyTypeObject *type, void *context)
320{
321 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000322 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000323 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000324 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000325 if (result == NULL) {
326 result = Py_None;
327 Py_INCREF(result);
328 }
329 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000330 result = result->ob_type->tp_descr_get(result, NULL,
331 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000332 }
333 else {
334 Py_INCREF(result);
335 }
Tim Peters24008312002-03-17 18:56:20 +0000336 return result;
337}
338
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000339static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000340 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
341 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000342 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000343 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000344 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000345 {0}
346};
347
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000348static int
349type_compare(PyObject *v, PyObject *w)
350{
351 /* This is called with type objects only. So we
352 can just compare the addresses. */
353 Py_uintptr_t vv = (Py_uintptr_t)v;
354 Py_uintptr_t ww = (Py_uintptr_t)w;
355 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
356}
357
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000358static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000359type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000360{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000361 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000362 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000363
364 mod = type_module(type, NULL);
365 if (mod == NULL)
366 PyErr_Clear();
367 else if (!PyString_Check(mod)) {
368 Py_DECREF(mod);
369 mod = NULL;
370 }
371 name = type_name(type, NULL);
372 if (name == NULL)
373 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000374
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000375 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
376 kind = "class";
377 else
378 kind = "type";
379
Barry Warsaw7ce36942001-08-24 18:34:26 +0000380 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000381 rtn = PyString_FromFormat("<%s '%s.%s'>",
382 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000383 PyString_AS_STRING(mod),
384 PyString_AS_STRING(name));
385 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000386 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000387 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000388
Guido van Rossumc3542212001-08-16 09:18:56 +0000389 Py_XDECREF(mod);
390 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000391 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000392}
393
Tim Peters6d6c1a32001-08-02 04:15:00 +0000394static PyObject *
395type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
396{
397 PyObject *obj;
398
399 if (type->tp_new == NULL) {
400 PyErr_Format(PyExc_TypeError,
401 "cannot create '%.100s' instances",
402 type->tp_name);
403 return NULL;
404 }
405
Tim Peters3f996e72001-09-13 19:18:27 +0000406 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000407 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000408 /* Ugly exception: when the call was type(something),
409 don't call tp_init on the result. */
410 if (type == &PyType_Type &&
411 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
412 (kwds == NULL ||
413 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
414 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000415 /* If the returned object is not an instance of type,
416 it won't be initialized. */
417 if (!PyType_IsSubtype(obj->ob_type, type))
418 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000419 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000420 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
421 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000422 type->tp_init(obj, args, kwds) < 0) {
423 Py_DECREF(obj);
424 obj = NULL;
425 }
426 }
427 return obj;
428}
429
430PyObject *
431PyType_GenericAlloc(PyTypeObject *type, int nitems)
432{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000433 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000434 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000435
436 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000437 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000438 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000439 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000440
Neil Schemenauerc806c882001-08-29 23:54:54 +0000441 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000442 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000443
Neil Schemenauerc806c882001-08-29 23:54:54 +0000444 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000445
Tim Peters6d6c1a32001-08-02 04:15:00 +0000446 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
447 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000448
Tim Peters6d6c1a32001-08-02 04:15:00 +0000449 if (type->tp_itemsize == 0)
450 PyObject_INIT(obj, type);
451 else
452 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000453
Tim Peters6d6c1a32001-08-02 04:15:00 +0000454 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000455 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000456 return obj;
457}
458
459PyObject *
460PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
461{
462 return type->tp_alloc(type, 0);
463}
464
Guido van Rossum9475a232001-10-05 20:51:39 +0000465/* Helpers for subtyping */
466
467static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000468traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
469{
470 int i, n;
471 PyMemberDef *mp;
472
473 n = type->ob_size;
474 mp = ((etype *)type)->members;
475 for (i = 0; i < n; i++, mp++) {
476 if (mp->type == T_OBJECT_EX) {
477 char *addr = (char *)self + mp->offset;
478 PyObject *obj = *(PyObject **)addr;
479 if (obj != NULL) {
480 int err = visit(obj, arg);
481 if (err)
482 return err;
483 }
484 }
485 }
486 return 0;
487}
488
489static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000490subtype_traverse(PyObject *self, visitproc visit, void *arg)
491{
492 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000493 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000494
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000495 /* Find the nearest base with a different tp_traverse,
496 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000497 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000498 base = type;
499 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
500 if (base->ob_size) {
501 int err = traverse_slots(base, self, visit, arg);
502 if (err)
503 return err;
504 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000505 base = base->tp_base;
506 assert(base);
507 }
508
509 if (type->tp_dictoffset != base->tp_dictoffset) {
510 PyObject **dictptr = _PyObject_GetDictPtr(self);
511 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000512 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000513 if (err)
514 return err;
515 }
516 }
517
Guido van Rossuma3862092002-06-10 15:24:42 +0000518 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
519 /* For a heaptype, the instances count as references
520 to the type. Traverse the type so the collector
521 can find cycles involving this link. */
522 int err = visit((PyObject *)type, arg);
523 if (err)
524 return err;
525 }
526
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000527 if (basetraverse)
528 return basetraverse(self, visit, arg);
529 return 0;
530}
531
532static void
533clear_slots(PyTypeObject *type, PyObject *self)
534{
535 int i, n;
536 PyMemberDef *mp;
537
538 n = type->ob_size;
539 mp = ((etype *)type)->members;
540 for (i = 0; i < n; i++, mp++) {
541 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
542 char *addr = (char *)self + mp->offset;
543 PyObject *obj = *(PyObject **)addr;
544 if (obj != NULL) {
545 Py_DECREF(obj);
546 *(PyObject **)addr = NULL;
547 }
548 }
549 }
550}
551
552static int
553subtype_clear(PyObject *self)
554{
555 PyTypeObject *type, *base;
556 inquiry baseclear;
557
558 /* Find the nearest base with a different tp_clear
559 and clear slots while we're at it */
560 type = self->ob_type;
561 base = type;
562 while ((baseclear = base->tp_clear) == subtype_clear) {
563 if (base->ob_size)
564 clear_slots(base, self);
565 base = base->tp_base;
566 assert(base);
567 }
568
Guido van Rossuma3862092002-06-10 15:24:42 +0000569 /* There's no need to clear the instance dict (if any);
570 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000571
572 if (baseclear)
573 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000574 return 0;
575}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000576
577static void
578subtype_dealloc(PyObject *self)
579{
Guido van Rossum14227b42001-12-06 02:35:58 +0000580 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000581 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000582
Guido van Rossum22b13872002-08-06 21:41:44 +0000583 /* Extract the type; we expect it to be a heap type */
584 type = self->ob_type;
585 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000586
Guido van Rossum22b13872002-08-06 21:41:44 +0000587 /* Test whether the type has GC exactly once */
588
589 if (!PyType_IS_GC(type)) {
590 /* It's really rare to find a dynamic type that doesn't have
591 GC; it can only happen when deriving from 'object' and not
592 adding any slots or instance variables. This allows
593 certain simplifications: there's no need to call
594 clear_slots(), or DECREF the dict, or clear weakrefs. */
595
596 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000597 if (type->tp_del) {
598 type->tp_del(self);
599 if (self->ob_refcnt > 0)
600 return;
601 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000602
603 /* Find the nearest base with a different tp_dealloc */
604 base = type;
605 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
606 assert(base->ob_size == 0);
607 base = base->tp_base;
608 assert(base);
609 }
610
611 /* Call the base tp_dealloc() */
612 assert(basedealloc);
613 basedealloc(self);
614
615 /* Can't reference self beyond this point */
616 Py_DECREF(type);
617
618 /* Done */
619 return;
620 }
621
622 /* We get here only if the type has GC */
623
624 /* UnTrack and re-Track around the trashcan macro, alas */
Guido van Rossum0906e072002-08-07 20:42:09 +0000625 PyObject_GC_UnTrack(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000626 Py_TRASHCAN_SAFE_BEGIN(self);
627 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
628
629 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000630 if (type->tp_del) {
631 type->tp_del(self);
632 if (self->ob_refcnt > 0)
633 goto endlabel;
634 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000635
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000636 /* Find the nearest base with a different tp_dealloc
637 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000638 base = type;
639 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
640 if (base->ob_size)
641 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000642 base = base->tp_base;
643 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000644 }
645
Tim Peters6d6c1a32001-08-02 04:15:00 +0000646 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000647 if (type->tp_dictoffset && !base->tp_dictoffset) {
648 PyObject **dictptr = _PyObject_GetDictPtr(self);
649 if (dictptr != NULL) {
650 PyObject *dict = *dictptr;
651 if (dict != NULL) {
652 Py_DECREF(dict);
653 *dictptr = NULL;
654 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000655 }
656 }
657
Guido van Rossum9676b222001-08-17 20:32:36 +0000658 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000659 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000660 PyObject_ClearWeakRefs(self);
661
Tim Peters6d6c1a32001-08-02 04:15:00 +0000662 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000663 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000664 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000665
666 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000667 assert(basedealloc);
668 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000669
670 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000671 Py_DECREF(type);
672
Guido van Rossum0906e072002-08-07 20:42:09 +0000673 endlabel:
Guido van Rossum22b13872002-08-06 21:41:44 +0000674 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675}
676
Jeremy Hylton938ace62002-07-17 16:30:39 +0000677static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000678
Tim Peters6d6c1a32001-08-02 04:15:00 +0000679/* type test with subclassing support */
680
681int
682PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
683{
684 PyObject *mro;
685
Guido van Rossum9478d072001-09-07 18:52:13 +0000686 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
687 return b == a || b == &PyBaseObject_Type;
688
Tim Peters6d6c1a32001-08-02 04:15:00 +0000689 mro = a->tp_mro;
690 if (mro != NULL) {
691 /* Deal with multiple inheritance without recursion
692 by walking the MRO tuple */
693 int i, n;
694 assert(PyTuple_Check(mro));
695 n = PyTuple_GET_SIZE(mro);
696 for (i = 0; i < n; i++) {
697 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
698 return 1;
699 }
700 return 0;
701 }
702 else {
703 /* a is not completely initilized yet; follow tp_base */
704 do {
705 if (a == b)
706 return 1;
707 a = a->tp_base;
708 } while (a != NULL);
709 return b == &PyBaseObject_Type;
710 }
711}
712
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000713/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000714 without looking in the instance dictionary
715 (so we can't use PyObject_GetAttr) but still binding
716 it to the instance. The arguments are the object,
717 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000718 static variable used to cache the interned Python string.
719
720 Two variants:
721
722 - lookup_maybe() returns NULL without raising an exception
723 when the _PyType_Lookup() call fails;
724
725 - lookup_method() always raises an exception upon errors.
726*/
Guido van Rossum60718732001-08-28 17:47:51 +0000727
728static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000729lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000730{
731 PyObject *res;
732
733 if (*attrobj == NULL) {
734 *attrobj = PyString_InternFromString(attrstr);
735 if (*attrobj == NULL)
736 return NULL;
737 }
738 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000739 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000740 descrgetfunc f;
741 if ((f = res->ob_type->tp_descr_get) == NULL)
742 Py_INCREF(res);
743 else
744 res = f(res, self, (PyObject *)(self->ob_type));
745 }
746 return res;
747}
748
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000749static PyObject *
750lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
751{
752 PyObject *res = lookup_maybe(self, attrstr, attrobj);
753 if (res == NULL && !PyErr_Occurred())
754 PyErr_SetObject(PyExc_AttributeError, *attrobj);
755 return res;
756}
757
Guido van Rossum2730b132001-08-28 18:22:14 +0000758/* A variation of PyObject_CallMethod that uses lookup_method()
759 instead of PyObject_GetAttrString(). This uses the same convention
760 as lookup_method to cache the interned name string object. */
761
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000762static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000763call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
764{
765 va_list va;
766 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000767 va_start(va, format);
768
Guido van Rossumda21c012001-10-03 00:50:18 +0000769 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000770 if (func == NULL) {
771 va_end(va);
772 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000773 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000774 return NULL;
775 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000776
777 if (format && *format)
778 args = Py_VaBuildValue(format, va);
779 else
780 args = PyTuple_New(0);
781
782 va_end(va);
783
784 if (args == NULL)
785 return NULL;
786
787 assert(PyTuple_Check(args));
788 retval = PyObject_Call(func, args, NULL);
789
790 Py_DECREF(args);
791 Py_DECREF(func);
792
793 return retval;
794}
795
796/* Clone of call_method() that returns NotImplemented when the lookup fails. */
797
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000798static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000799call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
800{
801 va_list va;
802 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000803 va_start(va, format);
804
Guido van Rossumda21c012001-10-03 00:50:18 +0000805 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000806 if (func == NULL) {
807 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000808 if (!PyErr_Occurred()) {
809 Py_INCREF(Py_NotImplemented);
810 return Py_NotImplemented;
811 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000812 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000813 }
814
815 if (format && *format)
816 args = Py_VaBuildValue(format, va);
817 else
818 args = PyTuple_New(0);
819
820 va_end(va);
821
Guido van Rossum717ce002001-09-14 16:58:08 +0000822 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000823 return NULL;
824
Guido van Rossum717ce002001-09-14 16:58:08 +0000825 assert(PyTuple_Check(args));
826 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000827
828 Py_DECREF(args);
829 Py_DECREF(func);
830
831 return retval;
832}
833
Tim Petersa91e9642001-11-14 23:32:33 +0000834static int
835fill_classic_mro(PyObject *mro, PyObject *cls)
836{
837 PyObject *bases, *base;
838 int i, n;
839
840 assert(PyList_Check(mro));
841 assert(PyClass_Check(cls));
842 i = PySequence_Contains(mro, cls);
843 if (i < 0)
844 return -1;
845 if (!i) {
846 if (PyList_Append(mro, cls) < 0)
847 return -1;
848 }
849 bases = ((PyClassObject *)cls)->cl_bases;
850 assert(bases && PyTuple_Check(bases));
851 n = PyTuple_GET_SIZE(bases);
852 for (i = 0; i < n; i++) {
853 base = PyTuple_GET_ITEM(bases, i);
854 if (fill_classic_mro(mro, base) < 0)
855 return -1;
856 }
857 return 0;
858}
859
860static PyObject *
861classic_mro(PyObject *cls)
862{
863 PyObject *mro;
864
865 assert(PyClass_Check(cls));
866 mro = PyList_New(0);
867 if (mro != NULL) {
868 if (fill_classic_mro(mro, cls) == 0)
869 return mro;
870 Py_DECREF(mro);
871 }
872 return NULL;
873}
874
Guido van Rossum1f121312002-11-14 19:49:16 +0000875/*
876 Method resolution order algorithm C3 described in
877 "A Monotonic Superclass Linearization for Dylan",
878 by Kim Barrett, Bob Cassel, Paul Haahr,
879 David A. Moon, Keith Playford, and P. Tucker Withington.
880 (OOPSLA 1996)
881
Guido van Rossum98f33732002-11-25 21:36:54 +0000882 Some notes about the rules implied by C3:
883
884 No duplicate bases.
885 It isn't legal to repeat a class in a list of base classes.
886
887 The next three properties are the 3 constraints in "C3".
888
889 Local precendece order.
890 If A precedes B in C's MRO, then A will precede B in the MRO of all
891 subclasses of C.
892
893 Monotonicity.
894 The MRO of a class must be an extension without reordering of the
895 MRO of each of its superclasses.
896
897 Extended Precedence Graph (EPG).
898 Linearization is consistent if there is a path in the EPG from
899 each class to all its successors in the linearization. See
900 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000901 */
902
903static int
904tail_contains(PyObject *list, int whence, PyObject *o) {
905 int j, size;
906 size = PyList_GET_SIZE(list);
907
908 for (j = whence+1; j < size; j++) {
909 if (PyList_GET_ITEM(list, j) == o)
910 return 1;
911 }
912 return 0;
913}
914
Guido van Rossum98f33732002-11-25 21:36:54 +0000915static PyObject *
916class_name(PyObject *cls)
917{
918 PyObject *name = PyObject_GetAttrString(cls, "__name__");
919 if (name == NULL) {
920 PyErr_Clear();
921 Py_XDECREF(name);
922 name = PyObject_Repr(cls);
923 }
924 if (name == NULL)
925 return NULL;
926 if (!PyString_Check(name)) {
927 Py_DECREF(name);
928 return NULL;
929 }
930 return name;
931}
932
933static int
934check_duplicates(PyObject *list)
935{
936 int i, j, n;
937 /* Let's use a quadratic time algorithm,
938 assuming that the bases lists is short.
939 */
940 n = PyList_GET_SIZE(list);
941 for (i = 0; i < n; i++) {
942 PyObject *o = PyList_GET_ITEM(list, i);
943 for (j = i + 1; j < n; j++) {
944 if (PyList_GET_ITEM(list, j) == o) {
945 o = class_name(o);
946 PyErr_Format(PyExc_TypeError,
947 "duplicate base class %s",
948 o ? PyString_AS_STRING(o) : "?");
949 Py_XDECREF(o);
950 return -1;
951 }
952 }
953 }
954 return 0;
955}
956
957/* Raise a TypeError for an MRO order disagreement.
958
959 It's hard to produce a good error message. In the absence of better
960 insight into error reporting, report the classes that were candidates
961 to be put next into the MRO. There is some conflict between the
962 order in which they should be put in the MRO, but it's hard to
963 diagnose what constraint can't be satisfied.
964*/
965
966static void
967set_mro_error(PyObject *to_merge, int *remain)
968{
969 int i, n, off, to_merge_size;
970 char buf[1000];
971 PyObject *k, *v;
972 PyObject *set = PyDict_New();
973
974 to_merge_size = PyList_GET_SIZE(to_merge);
975 for (i = 0; i < to_merge_size; i++) {
976 PyObject *L = PyList_GET_ITEM(to_merge, i);
977 if (remain[i] < PyList_GET_SIZE(L)) {
978 PyObject *c = PyList_GET_ITEM(L, remain[i]);
979 if (PyDict_SetItem(set, c, Py_None) < 0)
980 return;
981 }
982 }
983 n = PyDict_Size(set);
984
985 off = PyOS_snprintf(buf, sizeof(buf), "MRO conflict among bases");
986 i = 0;
987 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
988 PyObject *name = class_name(k);
989 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
990 name ? PyString_AS_STRING(name) : "?");
991 Py_XDECREF(name);
992 if (--n && off+1 < sizeof(buf)) {
993 buf[off++] = ',';
994 buf[off] = '\0';
995 }
996 }
997 PyErr_SetString(PyExc_TypeError, buf);
998 Py_DECREF(set);
999}
1000
Guido van Rossum1f121312002-11-14 19:49:16 +00001001static int
1002pmerge(PyObject *acc, PyObject* to_merge) {
1003 int i, j, to_merge_size;
1004 int *remain;
1005 int ok, empty_cnt;
1006
1007 to_merge_size = PyList_GET_SIZE(to_merge);
1008
Guido van Rossum98f33732002-11-25 21:36:54 +00001009 /* remain stores an index into each sublist of to_merge.
1010 remain[i] is the index of the next base in to_merge[i]
1011 that is not included in acc.
1012 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001013 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1014 if (remain == NULL)
1015 return -1;
1016 for (i = 0; i < to_merge_size; i++)
1017 remain[i] = 0;
1018
1019 again:
1020 empty_cnt = 0;
1021 for (i = 0; i < to_merge_size; i++) {
1022 PyObject *candidate;
1023
1024 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1025
1026 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1027 empty_cnt++;
1028 continue;
1029 }
1030
Guido van Rossum98f33732002-11-25 21:36:54 +00001031 /* Choose next candidate for MRO.
1032
1033 The input sequences alone can determine the choice.
1034 If not, choose the class which appears in the MRO
1035 of the earliest direct superclass of the new class.
1036 */
1037
Guido van Rossum1f121312002-11-14 19:49:16 +00001038 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1039 for (j = 0; j < to_merge_size; j++) {
1040 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001041 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001042 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001043 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001044 }
1045 ok = PyList_Append(acc, candidate);
1046 if (ok < 0) {
1047 PyMem_Free(remain);
1048 return -1;
1049 }
1050 for (j = 0; j < to_merge_size; j++) {
1051 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1052 if (PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1053 remain[j]++;
1054 }
1055 }
1056 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001057 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001058 }
1059
Guido van Rossum98f33732002-11-25 21:36:54 +00001060 if (empty_cnt == to_merge_size) {
1061 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001062 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001063 }
1064 set_mro_error(to_merge, remain);
1065 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001066 return -1;
1067}
1068
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069static PyObject *
1070mro_implementation(PyTypeObject *type)
1071{
1072 int i, n, ok;
1073 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001074 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075
Guido van Rossum63517572002-06-18 16:44:57 +00001076 if(type->tp_dict == NULL) {
1077 if(PyType_Ready(type) < 0)
1078 return NULL;
1079 }
1080
Guido van Rossum98f33732002-11-25 21:36:54 +00001081 /* Find a superclass linearization that honors the constraints
1082 of the explicit lists of bases and the constraints implied by
1083 each base class.
1084
1085 to_merge is a list of lists, where each list is a superclass
1086 linearization implied by a base class. The last element of
1087 to_merge is the declared list of bases.
1088 */
1089
Tim Peters6d6c1a32001-08-02 04:15:00 +00001090 bases = type->tp_bases;
1091 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001092
1093 to_merge = PyList_New(n+1);
1094 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001095 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001096
Tim Peters6d6c1a32001-08-02 04:15:00 +00001097 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001098 PyObject *base = PyTuple_GET_ITEM(bases, i);
1099 PyObject *parentMRO;
1100 if (PyType_Check(base))
1101 parentMRO = PySequence_List(
1102 ((PyTypeObject*)base)->tp_mro);
1103 else
1104 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001105 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001106 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001107 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001108 }
1109
1110 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001111 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001112
1113 bases_aslist = PySequence_List(bases);
1114 if (bases_aslist == NULL) {
1115 Py_DECREF(to_merge);
1116 return NULL;
1117 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001118 /* This is just a basic sanity check. */
1119 if (check_duplicates(bases_aslist) < 0) {
1120 Py_DECREF(to_merge);
1121 Py_DECREF(bases_aslist);
1122 return NULL;
1123 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001124 PyList_SET_ITEM(to_merge, n, bases_aslist);
1125
1126 result = Py_BuildValue("[O]", (PyObject *)type);
1127 if (result == NULL) {
1128 Py_DECREF(to_merge);
1129 return NULL;
1130 }
1131
1132 ok = pmerge(result, to_merge);
1133 Py_DECREF(to_merge);
1134 if (ok < 0) {
1135 Py_DECREF(result);
1136 return NULL;
1137 }
1138
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139 return result;
1140}
1141
1142static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001143mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001144{
1145 PyTypeObject *type = (PyTypeObject *)self;
1146
Tim Peters6d6c1a32001-08-02 04:15:00 +00001147 return mro_implementation(type);
1148}
1149
1150static int
1151mro_internal(PyTypeObject *type)
1152{
1153 PyObject *mro, *result, *tuple;
1154
1155 if (type->ob_type == &PyType_Type) {
1156 result = mro_implementation(type);
1157 }
1158 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001159 static PyObject *mro_str;
1160 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161 if (mro == NULL)
1162 return -1;
1163 result = PyObject_CallObject(mro, NULL);
1164 Py_DECREF(mro);
1165 }
1166 if (result == NULL)
1167 return -1;
1168 tuple = PySequence_Tuple(result);
1169 Py_DECREF(result);
1170 type->tp_mro = tuple;
1171 return 0;
1172}
1173
1174
1175/* Calculate the best base amongst multiple base classes.
1176 This is the first one that's on the path to the "solid base". */
1177
1178static PyTypeObject *
1179best_base(PyObject *bases)
1180{
1181 int i, n;
1182 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001183 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001184
1185 assert(PyTuple_Check(bases));
1186 n = PyTuple_GET_SIZE(bases);
1187 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001188 base = NULL;
1189 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001190 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001191 base_proto = PyTuple_GET_ITEM(bases, i);
1192 if (PyClass_Check(base_proto))
1193 continue;
1194 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 PyErr_SetString(
1196 PyExc_TypeError,
1197 "bases must be types");
1198 return NULL;
1199 }
Tim Petersa91e9642001-11-14 23:32:33 +00001200 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001201 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001202 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 return NULL;
1204 }
1205 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001206 if (winner == NULL) {
1207 winner = candidate;
1208 base = base_i;
1209 }
1210 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211 ;
1212 else if (PyType_IsSubtype(candidate, winner)) {
1213 winner = candidate;
1214 base = base_i;
1215 }
1216 else {
1217 PyErr_SetString(
1218 PyExc_TypeError,
1219 "multiple bases have "
1220 "instance lay-out conflict");
1221 return NULL;
1222 }
1223 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001224 if (base == NULL)
1225 PyErr_SetString(PyExc_TypeError,
1226 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001227 return base;
1228}
1229
1230static int
1231extra_ivars(PyTypeObject *type, PyTypeObject *base)
1232{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001233 size_t t_size = type->tp_basicsize;
1234 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001235
Guido van Rossum9676b222001-08-17 20:32:36 +00001236 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 if (type->tp_itemsize || base->tp_itemsize) {
1238 /* If itemsize is involved, stricter rules */
1239 return t_size != b_size ||
1240 type->tp_itemsize != base->tp_itemsize;
1241 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001242 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1243 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1244 t_size -= sizeof(PyObject *);
1245 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1246 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1247 t_size -= sizeof(PyObject *);
1248
1249 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001250}
1251
1252static PyTypeObject *
1253solid_base(PyTypeObject *type)
1254{
1255 PyTypeObject *base;
1256
1257 if (type->tp_base)
1258 base = solid_base(type->tp_base);
1259 else
1260 base = &PyBaseObject_Type;
1261 if (extra_ivars(type, base))
1262 return type;
1263 else
1264 return base;
1265}
1266
Jeremy Hylton938ace62002-07-17 16:30:39 +00001267static void object_dealloc(PyObject *);
1268static int object_init(PyObject *, PyObject *, PyObject *);
1269static int update_slot(PyTypeObject *, PyObject *);
1270static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001271
1272static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001273subtype_dict(PyObject *obj, void *context)
1274{
1275 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1276 PyObject *dict;
1277
1278 if (dictptr == NULL) {
1279 PyErr_SetString(PyExc_AttributeError,
1280 "This object has no __dict__");
1281 return NULL;
1282 }
1283 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001284 if (dict == NULL)
1285 *dictptr = dict = PyDict_New();
1286 Py_XINCREF(dict);
1287 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001288}
1289
Guido van Rossum6661be32001-10-26 04:26:12 +00001290static int
1291subtype_setdict(PyObject *obj, PyObject *value, void *context)
1292{
1293 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1294 PyObject *dict;
1295
1296 if (dictptr == NULL) {
1297 PyErr_SetString(PyExc_AttributeError,
1298 "This object has no __dict__");
1299 return -1;
1300 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001301 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001302 PyErr_SetString(PyExc_TypeError,
1303 "__dict__ must be set to a dictionary");
1304 return -1;
1305 }
1306 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001307 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001308 *dictptr = value;
1309 Py_XDECREF(dict);
1310 return 0;
1311}
1312
Guido van Rossumad47da02002-08-12 19:05:44 +00001313static PyObject *
1314subtype_getweakref(PyObject *obj, void *context)
1315{
1316 PyObject **weaklistptr;
1317 PyObject *result;
1318
1319 if (obj->ob_type->tp_weaklistoffset == 0) {
1320 PyErr_SetString(PyExc_AttributeError,
1321 "This object has no __weaklist__");
1322 return NULL;
1323 }
1324 assert(obj->ob_type->tp_weaklistoffset > 0);
1325 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001326 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001327 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001328 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001329 if (*weaklistptr == NULL)
1330 result = Py_None;
1331 else
1332 result = *weaklistptr;
1333 Py_INCREF(result);
1334 return result;
1335}
1336
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001337static PyGetSetDef subtype_getsets[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001338 /* Not all objects have these attributes!
1339 The descriptor's __get__ method may raise AttributeError. */
1340 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001341 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001342 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001343 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001344 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001345};
1346
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001347/* bozo: __getstate__ that raises TypeError */
1348
1349static PyObject *
1350bozo_func(PyObject *self, PyObject *args)
1351{
1352 PyErr_SetString(PyExc_TypeError,
1353 "a class that defines __slots__ without "
1354 "defining __getstate__ cannot be pickled");
1355 return NULL;
1356}
1357
Neal Norwitz93c1e232002-03-31 16:06:11 +00001358static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001359
1360static PyObject *bozo_obj = NULL;
1361
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001362static int
1363valid_identifier(PyObject *s)
1364{
Guido van Rossum03013a02002-07-16 14:30:28 +00001365 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001366 int i, n;
1367
1368 if (!PyString_Check(s)) {
1369 PyErr_SetString(PyExc_TypeError,
1370 "__slots__ must be strings");
1371 return 0;
1372 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001373 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001374 n = PyString_GET_SIZE(s);
1375 /* We must reject an empty name. As a hack, we bump the
1376 length to 1 so that the loop will balk on the trailing \0. */
1377 if (n == 0)
1378 n = 1;
1379 for (i = 0; i < n; i++, p++) {
1380 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1381 PyErr_SetString(PyExc_TypeError,
1382 "__slots__ must be identifiers");
1383 return 0;
1384 }
1385 }
1386 return 1;
1387}
1388
Martin v. Löwisd919a592002-10-14 21:07:28 +00001389#ifdef Py_USING_UNICODE
1390/* Replace Unicode objects in slots. */
1391
1392static PyObject *
1393_unicode_to_string(PyObject *slots, int nslots)
1394{
1395 PyObject *tmp = slots;
1396 PyObject *o, *o1;
1397 int i;
1398 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1399 for (i = 0; i < nslots; i++) {
1400 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1401 if (tmp == slots) {
1402 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1403 if (tmp == NULL)
1404 return NULL;
1405 }
1406 o1 = _PyUnicode_AsDefaultEncodedString
1407 (o, NULL);
1408 if (o1 == NULL) {
1409 Py_DECREF(tmp);
1410 return 0;
1411 }
1412 Py_INCREF(o1);
1413 Py_DECREF(o);
1414 PyTuple_SET_ITEM(tmp, i, o1);
1415 }
1416 }
1417 return tmp;
1418}
1419#endif
1420
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001421static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001422type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1423{
1424 PyObject *name, *bases, *dict;
1425 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001426 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001427 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001428 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001429 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001430 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001431 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001432
Tim Peters3abca122001-10-27 19:37:48 +00001433 assert(args != NULL && PyTuple_Check(args));
1434 assert(kwds == NULL || PyDict_Check(kwds));
1435
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001436 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001437 {
1438 const int nargs = PyTuple_GET_SIZE(args);
1439 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1440
1441 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1442 PyObject *x = PyTuple_GET_ITEM(args, 0);
1443 Py_INCREF(x->ob_type);
1444 return (PyObject *) x->ob_type;
1445 }
1446
1447 /* SF bug 475327 -- if that didn't trigger, we need 3
1448 arguments. but PyArg_ParseTupleAndKeywords below may give
1449 a msg saying type() needs exactly 3. */
1450 if (nargs + nkwds != 3) {
1451 PyErr_SetString(PyExc_TypeError,
1452 "type() takes 1 or 3 arguments");
1453 return NULL;
1454 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001455 }
1456
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001457 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1459 &name,
1460 &PyTuple_Type, &bases,
1461 &PyDict_Type, &dict))
1462 return NULL;
1463
1464 /* Determine the proper metatype to deal with this,
1465 and check for metatype conflicts while we're at it.
1466 Note that if some other metatype wins to contract,
1467 it's possible that its instances are not types. */
1468 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001469 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470 for (i = 0; i < nbases; i++) {
1471 tmp = PyTuple_GET_ITEM(bases, i);
1472 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001473 if (tmptype == &PyClass_Type)
1474 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001475 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001477 if (PyType_IsSubtype(tmptype, winner)) {
1478 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001479 continue;
1480 }
1481 PyErr_SetString(PyExc_TypeError,
1482 "metatype conflict among bases");
1483 return NULL;
1484 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001485 if (winner != metatype) {
1486 if (winner->tp_new != type_new) /* Pass it to the winner */
1487 return winner->tp_new(winner, args, kwds);
1488 metatype = winner;
1489 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001490
1491 /* Adjust for empty tuple bases */
1492 if (nbases == 0) {
1493 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1494 if (bases == NULL)
1495 return NULL;
1496 nbases = 1;
1497 }
1498 else
1499 Py_INCREF(bases);
1500
1501 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1502
1503 /* Calculate best base, and check that all bases are type objects */
1504 base = best_base(bases);
1505 if (base == NULL)
1506 return NULL;
1507 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1508 PyErr_Format(PyExc_TypeError,
1509 "type '%.100s' is not an acceptable base type",
1510 base->tp_name);
1511 return NULL;
1512 }
1513
Tim Peters6d6c1a32001-08-02 04:15:00 +00001514 /* Check for a __slots__ sequence variable in dict, and count it */
1515 slots = PyDict_GetItemString(dict, "__slots__");
1516 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001517 add_dict = 0;
1518 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001519 may_add_dict = base->tp_dictoffset == 0;
1520 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1521 if (slots == NULL) {
1522 if (may_add_dict) {
1523 add_dict++;
1524 }
1525 if (may_add_weak) {
1526 add_weak++;
1527 }
1528 }
1529 else {
1530 /* Have slots */
1531
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532 /* Make it into a tuple */
1533 if (PyString_Check(slots))
1534 slots = Py_BuildValue("(O)", slots);
1535 else
1536 slots = PySequence_Tuple(slots);
1537 if (slots == NULL)
1538 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001539 assert(PyTuple_Check(slots));
1540
1541 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001542 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001543 if (nslots > 0 && base->tp_itemsize != 0) {
1544 PyErr_Format(PyExc_TypeError,
1545 "nonempty __slots__ "
1546 "not supported for subtype of '%s'",
1547 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001548 bad_slots:
1549 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001550 return NULL;
1551 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001552
Martin v. Löwisd919a592002-10-14 21:07:28 +00001553#ifdef Py_USING_UNICODE
1554 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001555 if (tmp != slots) {
1556 Py_DECREF(slots);
1557 slots = tmp;
1558 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001559 if (!tmp)
1560 return NULL;
1561#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001562 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001563 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001564 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1565 char *s;
1566 if (!valid_identifier(tmp))
1567 goto bad_slots;
1568 assert(PyString_Check(tmp));
1569 s = PyString_AS_STRING(tmp);
1570 if (strcmp(s, "__dict__") == 0) {
1571 if (!may_add_dict || add_dict) {
1572 PyErr_SetString(PyExc_TypeError,
1573 "__dict__ slot disallowed: "
1574 "we already got one");
1575 goto bad_slots;
1576 }
1577 add_dict++;
1578 }
1579 if (strcmp(s, "__weakref__") == 0) {
1580 if (!may_add_weak || add_weak) {
1581 PyErr_SetString(PyExc_TypeError,
1582 "__weakref__ slot disallowed: "
1583 "either we already got one, "
1584 "or __itemsize__ != 0");
1585 goto bad_slots;
1586 }
1587 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588 }
1589 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001590
Guido van Rossumad47da02002-08-12 19:05:44 +00001591 /* Copy slots into yet another tuple, demangling names */
1592 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001593 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001594 goto bad_slots;
1595 for (i = j = 0; i < nslots; i++) {
1596 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001597 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001598 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001599 s = PyString_AS_STRING(tmp);
1600 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1601 (add_weak && strcmp(s, "__weakref__") == 0))
1602 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001603 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001604 PyString_AS_STRING(tmp),
1605 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001606 {
1607 tmp = PyString_FromString(buffer);
1608 } else {
1609 Py_INCREF(tmp);
1610 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001611 PyTuple_SET_ITEM(newslots, j, tmp);
1612 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001613 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001614 assert(j == nslots - add_dict - add_weak);
1615 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001616 Py_DECREF(slots);
1617 slots = newslots;
1618
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001619 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001620 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001621 /* If not, provide a bozo that raises TypeError */
1622 if (bozo_obj == NULL) {
1623 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001624 if (bozo_obj == NULL)
1625 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001626 }
1627 if (PyDict_SetItemString(dict,
1628 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001629 bozo_obj) < 0)
1630 {
1631 Py_DECREF(bozo_obj);
1632 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001633 }
1634 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001635
1636 /* Secondary bases may provide weakrefs or dict */
1637 if (nbases > 1 &&
1638 ((may_add_dict && !add_dict) ||
1639 (may_add_weak && !add_weak))) {
1640 for (i = 0; i < nbases; i++) {
1641 tmp = PyTuple_GET_ITEM(bases, i);
1642 if (tmp == (PyObject *)base)
1643 continue; /* Skip primary base */
1644 if (PyClass_Check(tmp)) {
1645 /* Classic base class provides both */
1646 if (may_add_dict && !add_dict)
1647 add_dict++;
1648 if (may_add_weak && !add_weak)
1649 add_weak++;
1650 break;
1651 }
1652 assert(PyType_Check(tmp));
1653 tmptype = (PyTypeObject *)tmp;
1654 if (may_add_dict && !add_dict &&
1655 tmptype->tp_dictoffset != 0)
1656 add_dict++;
1657 if (may_add_weak && !add_weak &&
1658 tmptype->tp_weaklistoffset != 0)
1659 add_weak++;
1660 if (may_add_dict && !add_dict)
1661 continue;
1662 if (may_add_weak && !add_weak)
1663 continue;
1664 /* Nothing more to check */
1665 break;
1666 }
1667 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001668 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001669
1670 /* XXX From here until type is safely allocated,
1671 "return NULL" may leak slots! */
1672
1673 /* Allocate the type object */
1674 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001675 if (type == NULL) {
1676 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001678 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679
1680 /* Keep name and slots alive in the extended type object */
1681 et = (etype *)type;
1682 Py_INCREF(name);
1683 et->name = name;
1684 et->slots = slots;
1685
Guido van Rossumdc91b992001-08-08 22:26:22 +00001686 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001687 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1688 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001689 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1690 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001691
1692 /* It's a new-style number unless it specifically inherits any
1693 old-style numeric behavior */
1694 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1695 (base->tp_as_number == NULL))
1696 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1697
1698 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001699 type->tp_as_number = &et->as_number;
1700 type->tp_as_sequence = &et->as_sequence;
1701 type->tp_as_mapping = &et->as_mapping;
1702 type->tp_as_buffer = &et->as_buffer;
1703 type->tp_name = PyString_AS_STRING(name);
1704
1705 /* Set tp_base and tp_bases */
1706 type->tp_bases = bases;
1707 Py_INCREF(base);
1708 type->tp_base = base;
1709
Guido van Rossum687ae002001-10-15 22:03:32 +00001710 /* Initialize tp_dict from passed-in dict */
1711 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001712 if (dict == NULL) {
1713 Py_DECREF(type);
1714 return NULL;
1715 }
1716
Guido van Rossumc3542212001-08-16 09:18:56 +00001717 /* Set __module__ in the dict */
1718 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1719 tmp = PyEval_GetGlobals();
1720 if (tmp != NULL) {
1721 tmp = PyDict_GetItemString(tmp, "__name__");
1722 if (tmp != NULL) {
1723 if (PyDict_SetItemString(dict, "__module__",
1724 tmp) < 0)
1725 return NULL;
1726 }
1727 }
1728 }
1729
Tim Peters2f93e282001-10-04 05:27:00 +00001730 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001731 and is a string. The __doc__ accessor will first look for tp_doc;
1732 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001733 */
1734 {
1735 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1736 if (doc != NULL && PyString_Check(doc)) {
1737 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001738 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001739 if (type->tp_doc == NULL) {
1740 Py_DECREF(type);
1741 return NULL;
1742 }
1743 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1744 }
1745 }
1746
Tim Peters6d6c1a32001-08-02 04:15:00 +00001747 /* Special-case __new__: if it's a plain function,
1748 make it a static function */
1749 tmp = PyDict_GetItemString(dict, "__new__");
1750 if (tmp != NULL && PyFunction_Check(tmp)) {
1751 tmp = PyStaticMethod_New(tmp);
1752 if (tmp == NULL) {
1753 Py_DECREF(type);
1754 return NULL;
1755 }
1756 PyDict_SetItemString(dict, "__new__", tmp);
1757 Py_DECREF(tmp);
1758 }
1759
1760 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1761 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001762 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001763 if (slots != NULL) {
1764 for (i = 0; i < nslots; i++, mp++) {
1765 mp->name = PyString_AS_STRING(
1766 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001767 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001769 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001770 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001771 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001772 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001773 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001774 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001775 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776 slotoffset += sizeof(PyObject *);
1777 }
1778 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001779 if (add_dict) {
1780 if (base->tp_itemsize)
1781 type->tp_dictoffset = -(long)sizeof(PyObject *);
1782 else
1783 type->tp_dictoffset = slotoffset;
1784 slotoffset += sizeof(PyObject *);
1785 }
1786 if (add_weak) {
1787 assert(!base->tp_itemsize);
1788 type->tp_weaklistoffset = slotoffset;
1789 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001790 }
1791 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001792 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001793 type->tp_members = et->members;
Guido van Rossumad47da02002-08-12 19:05:44 +00001794 type->tp_getset = subtype_getsets;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795
1796 /* Special case some slots */
1797 if (type->tp_dictoffset != 0 || nslots > 0) {
1798 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1799 type->tp_getattro = PyObject_GenericGetAttr;
1800 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1801 type->tp_setattro = PyObject_GenericSetAttr;
1802 }
1803 type->tp_dealloc = subtype_dealloc;
1804
Guido van Rossum9475a232001-10-05 20:51:39 +00001805 /* Enable GC unless there are really no instance variables possible */
1806 if (!(type->tp_basicsize == sizeof(PyObject) &&
1807 type->tp_itemsize == 0))
1808 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1809
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810 /* Always override allocation strategy to use regular heap */
1811 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001812 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001813 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001814 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001815 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001816 }
1817 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001818 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001819
1820 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001821 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001822 Py_DECREF(type);
1823 return NULL;
1824 }
1825
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001826 /* Put the proper slots in place */
1827 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001828
Tim Peters6d6c1a32001-08-02 04:15:00 +00001829 return (PyObject *)type;
1830}
1831
1832/* Internal API to look for a name through the MRO.
1833 This returns a borrowed reference, and doesn't set an exception! */
1834PyObject *
1835_PyType_Lookup(PyTypeObject *type, PyObject *name)
1836{
1837 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001838 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001839
Guido van Rossum687ae002001-10-15 22:03:32 +00001840 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001841 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001842
1843 /* If mro is NULL, the type is either not yet initialized
1844 by PyType_Ready(), or already cleared by type_clear().
1845 Either way the safest thing to do is to return NULL. */
1846 if (mro == NULL)
1847 return NULL;
1848
Tim Peters6d6c1a32001-08-02 04:15:00 +00001849 assert(PyTuple_Check(mro));
1850 n = PyTuple_GET_SIZE(mro);
1851 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001852 base = PyTuple_GET_ITEM(mro, i);
1853 if (PyClass_Check(base))
1854 dict = ((PyClassObject *)base)->cl_dict;
1855 else {
1856 assert(PyType_Check(base));
1857 dict = ((PyTypeObject *)base)->tp_dict;
1858 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859 assert(dict && PyDict_Check(dict));
1860 res = PyDict_GetItem(dict, name);
1861 if (res != NULL)
1862 return res;
1863 }
1864 return NULL;
1865}
1866
1867/* This is similar to PyObject_GenericGetAttr(),
1868 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1869static PyObject *
1870type_getattro(PyTypeObject *type, PyObject *name)
1871{
1872 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001873 PyObject *meta_attribute, *attribute;
1874 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001875
1876 /* Initialize this type (we'll assume the metatype is initialized) */
1877 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001878 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879 return NULL;
1880 }
1881
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001882 /* No readable descriptor found yet */
1883 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001884
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001885 /* Look for the attribute in the metatype */
1886 meta_attribute = _PyType_Lookup(metatype, name);
1887
1888 if (meta_attribute != NULL) {
1889 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001890
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001891 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1892 /* Data descriptors implement tp_descr_set to intercept
1893 * writes. Assume the attribute is not overridden in
1894 * type's tp_dict (and bases): call the descriptor now.
1895 */
1896 return meta_get(meta_attribute, (PyObject *)type,
1897 (PyObject *)metatype);
1898 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001899 }
1900
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001901 /* No data descriptor found on metatype. Look in tp_dict of this
1902 * type and its bases */
1903 attribute = _PyType_Lookup(type, name);
1904 if (attribute != NULL) {
1905 /* Implement descriptor functionality, if any */
1906 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1907 if (local_get != NULL) {
1908 /* NULL 2nd argument indicates the descriptor was
1909 * found on the target object itself (or a base) */
1910 return local_get(attribute, (PyObject *)NULL,
1911 (PyObject *)type);
1912 }
Tim Peters34592512002-07-11 06:23:50 +00001913
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001914 Py_INCREF(attribute);
1915 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001916 }
1917
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001918 /* No attribute found in local __dict__ (or bases): use the
1919 * descriptor from the metatype, if any */
1920 if (meta_get != NULL)
1921 return meta_get(meta_attribute, (PyObject *)type,
1922 (PyObject *)metatype);
1923
1924 /* If an ordinary attribute was found on the metatype, return it now */
1925 if (meta_attribute != NULL) {
1926 Py_INCREF(meta_attribute);
1927 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001928 }
1929
1930 /* Give up */
1931 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001932 "type object '%.50s' has no attribute '%.400s'",
1933 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001934 return NULL;
1935}
1936
1937static int
1938type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1939{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001940 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1941 PyErr_Format(
1942 PyExc_TypeError,
1943 "can't set attributes of built-in/extension type '%s'",
1944 type->tp_name);
1945 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001946 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001947 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1948 return -1;
1949 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001950}
1951
1952static void
1953type_dealloc(PyTypeObject *type)
1954{
1955 etype *et;
1956
1957 /* Assert this is a heap-allocated type object */
1958 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001959 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001960 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001961 et = (etype *)type;
1962 Py_XDECREF(type->tp_base);
1963 Py_XDECREF(type->tp_dict);
1964 Py_XDECREF(type->tp_bases);
1965 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001966 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001967 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001968 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001969 Py_XDECREF(et->name);
1970 Py_XDECREF(et->slots);
1971 type->ob_type->tp_free((PyObject *)type);
1972}
1973
Guido van Rossum1c450732001-10-08 15:18:27 +00001974static PyObject *
1975type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1976{
1977 PyObject *list, *raw, *ref;
1978 int i, n;
1979
1980 list = PyList_New(0);
1981 if (list == NULL)
1982 return NULL;
1983 raw = type->tp_subclasses;
1984 if (raw == NULL)
1985 return list;
1986 assert(PyList_Check(raw));
1987 n = PyList_GET_SIZE(raw);
1988 for (i = 0; i < n; i++) {
1989 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00001990 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00001991 ref = PyWeakref_GET_OBJECT(ref);
1992 if (ref != Py_None) {
1993 if (PyList_Append(list, ref) < 0) {
1994 Py_DECREF(list);
1995 return NULL;
1996 }
1997 }
1998 }
1999 return list;
2000}
2001
Tim Peters6d6c1a32001-08-02 04:15:00 +00002002static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002003 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002004 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002005 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002006 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002007 {0}
2008};
2009
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002010PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002011"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002012"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002013
Guido van Rossum048eb752001-10-02 21:24:57 +00002014static int
2015type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2016{
Guido van Rossum048eb752001-10-02 21:24:57 +00002017 int err;
2018
Guido van Rossuma3862092002-06-10 15:24:42 +00002019 /* Because of type_is_gc(), the collector only calls this
2020 for heaptypes. */
2021 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002022
2023#define VISIT(SLOT) \
2024 if (SLOT) { \
2025 err = visit((PyObject *)(SLOT), arg); \
2026 if (err) \
2027 return err; \
2028 }
2029
2030 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002031 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002032 VISIT(type->tp_mro);
2033 VISIT(type->tp_bases);
2034 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002035
2036 /* There's no need to visit type->tp_subclasses or
2037 ((etype *)type)->slots, because they can't be involved
2038 in cycles; tp_subclasses is a list of weak references,
2039 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002040
2041#undef VISIT
2042
2043 return 0;
2044}
2045
2046static int
2047type_clear(PyTypeObject *type)
2048{
Guido van Rossum048eb752001-10-02 21:24:57 +00002049 PyObject *tmp;
2050
Guido van Rossuma3862092002-06-10 15:24:42 +00002051 /* Because of type_is_gc(), the collector only calls this
2052 for heaptypes. */
2053 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002054
2055#define CLEAR(SLOT) \
2056 if (SLOT) { \
2057 tmp = (PyObject *)(SLOT); \
2058 SLOT = NULL; \
2059 Py_DECREF(tmp); \
2060 }
2061
Guido van Rossuma3862092002-06-10 15:24:42 +00002062 /* The only field we need to clear is tp_mro, which is part of a
2063 hard cycle (its first element is the class itself) that won't
2064 be broken otherwise (it's a tuple and tuples don't have a
2065 tp_clear handler). None of the other fields need to be
2066 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002067
Guido van Rossuma3862092002-06-10 15:24:42 +00002068 tp_dict:
2069 It is a dict, so the collector will call its tp_clear.
2070
2071 tp_cache:
2072 Not used; if it were, it would be a dict.
2073
2074 tp_bases, tp_base:
2075 If these are involved in a cycle, there must be at least
2076 one other, mutable object in the cycle, e.g. a base
2077 class's dict; the cycle will be broken that way.
2078
2079 tp_subclasses:
2080 A list of weak references can't be part of a cycle; and
2081 lists have their own tp_clear.
2082
2083 slots (in etype):
2084 A tuple of strings can't be part of a cycle.
2085 */
2086
2087 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002088
Guido van Rossum048eb752001-10-02 21:24:57 +00002089#undef CLEAR
2090
2091 return 0;
2092}
2093
2094static int
2095type_is_gc(PyTypeObject *type)
2096{
2097 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2098}
2099
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002100PyTypeObject PyType_Type = {
2101 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102 0, /* ob_size */
2103 "type", /* tp_name */
2104 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002105 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106 (destructor)type_dealloc, /* tp_dealloc */
2107 0, /* tp_print */
2108 0, /* tp_getattr */
2109 0, /* tp_setattr */
2110 type_compare, /* tp_compare */
2111 (reprfunc)type_repr, /* tp_repr */
2112 0, /* tp_as_number */
2113 0, /* tp_as_sequence */
2114 0, /* tp_as_mapping */
2115 (hashfunc)_Py_HashPointer, /* tp_hash */
2116 (ternaryfunc)type_call, /* tp_call */
2117 0, /* tp_str */
2118 (getattrofunc)type_getattro, /* tp_getattro */
2119 (setattrofunc)type_setattro, /* tp_setattro */
2120 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002121 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2122 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002123 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002124 (traverseproc)type_traverse, /* tp_traverse */
2125 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002126 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002127 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002128 0, /* tp_iter */
2129 0, /* tp_iternext */
2130 type_methods, /* tp_methods */
2131 type_members, /* tp_members */
2132 type_getsets, /* tp_getset */
2133 0, /* tp_base */
2134 0, /* tp_dict */
2135 0, /* tp_descr_get */
2136 0, /* tp_descr_set */
2137 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2138 0, /* tp_init */
2139 0, /* tp_alloc */
2140 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002141 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002142 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002143};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144
2145
2146/* The base type of all types (eventually)... except itself. */
2147
2148static int
2149object_init(PyObject *self, PyObject *args, PyObject *kwds)
2150{
2151 return 0;
2152}
2153
2154static void
2155object_dealloc(PyObject *self)
2156{
2157 self->ob_type->tp_free(self);
2158}
2159
Guido van Rossum8e248182001-08-12 05:17:56 +00002160static PyObject *
2161object_repr(PyObject *self)
2162{
Guido van Rossum76e69632001-08-16 18:52:43 +00002163 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002164 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002165
Guido van Rossum76e69632001-08-16 18:52:43 +00002166 type = self->ob_type;
2167 mod = type_module(type, NULL);
2168 if (mod == NULL)
2169 PyErr_Clear();
2170 else if (!PyString_Check(mod)) {
2171 Py_DECREF(mod);
2172 mod = NULL;
2173 }
2174 name = type_name(type, NULL);
2175 if (name == NULL)
2176 return NULL;
2177 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002178 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002179 PyString_AS_STRING(mod),
2180 PyString_AS_STRING(name),
2181 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002182 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002183 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002184 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002185 Py_XDECREF(mod);
2186 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002187 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002188}
2189
Guido van Rossumb8f63662001-08-15 23:57:02 +00002190static PyObject *
2191object_str(PyObject *self)
2192{
2193 unaryfunc f;
2194
2195 f = self->ob_type->tp_repr;
2196 if (f == NULL)
2197 f = object_repr;
2198 return f(self);
2199}
2200
Guido van Rossum8e248182001-08-12 05:17:56 +00002201static long
2202object_hash(PyObject *self)
2203{
2204 return _Py_HashPointer(self);
2205}
Guido van Rossum8e248182001-08-12 05:17:56 +00002206
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002207static PyObject *
2208object_get_class(PyObject *self, void *closure)
2209{
2210 Py_INCREF(self->ob_type);
2211 return (PyObject *)(self->ob_type);
2212}
2213
2214static int
2215equiv_structs(PyTypeObject *a, PyTypeObject *b)
2216{
2217 return a == b ||
2218 (a != NULL &&
2219 b != NULL &&
2220 a->tp_basicsize == b->tp_basicsize &&
2221 a->tp_itemsize == b->tp_itemsize &&
2222 a->tp_dictoffset == b->tp_dictoffset &&
2223 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2224 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2225 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2226}
2227
2228static int
2229same_slots_added(PyTypeObject *a, PyTypeObject *b)
2230{
2231 PyTypeObject *base = a->tp_base;
2232 int size;
2233
2234 if (base != b->tp_base)
2235 return 0;
2236 if (equiv_structs(a, base) && equiv_structs(b, base))
2237 return 1;
2238 size = base->tp_basicsize;
2239 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2240 size += sizeof(PyObject *);
2241 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2242 size += sizeof(PyObject *);
2243 return size == a->tp_basicsize && size == b->tp_basicsize;
2244}
2245
2246static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002247compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2248{
2249 PyTypeObject *newbase, *oldbase;
2250
2251 if (new->tp_dealloc != old->tp_dealloc ||
2252 new->tp_free != old->tp_free)
2253 {
2254 PyErr_Format(PyExc_TypeError,
2255 "%s assignment: "
2256 "'%s' deallocator differs from '%s'",
2257 attr,
2258 new->tp_name,
2259 old->tp_name);
2260 return 0;
2261 }
2262 newbase = new;
2263 oldbase = old;
2264 while (equiv_structs(newbase, newbase->tp_base))
2265 newbase = newbase->tp_base;
2266 while (equiv_structs(oldbase, oldbase->tp_base))
2267 oldbase = oldbase->tp_base;
2268 if (newbase != oldbase &&
2269 (newbase->tp_base != oldbase->tp_base ||
2270 !same_slots_added(newbase, oldbase))) {
2271 PyErr_Format(PyExc_TypeError,
2272 "%s assignment: "
2273 "'%s' object layout differs from '%s'",
2274 attr,
2275 new->tp_name,
2276 old->tp_name);
2277 return 0;
2278 }
2279
2280 return 1;
2281}
2282
2283static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002284object_set_class(PyObject *self, PyObject *value, void *closure)
2285{
2286 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002287 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002288
Guido van Rossumb6b89422002-04-15 01:03:30 +00002289 if (value == NULL) {
2290 PyErr_SetString(PyExc_TypeError,
2291 "can't delete __class__ attribute");
2292 return -1;
2293 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002294 if (!PyType_Check(value)) {
2295 PyErr_Format(PyExc_TypeError,
2296 "__class__ must be set to new-style class, not '%s' object",
2297 value->ob_type->tp_name);
2298 return -1;
2299 }
2300 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002301 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2302 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2303 {
2304 PyErr_Format(PyExc_TypeError,
2305 "__class__ assignment: only for heap types");
2306 return -1;
2307 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002308 if (compatible_for_assignment(new, old, "__class__")) {
2309 Py_INCREF(new);
2310 self->ob_type = new;
2311 Py_DECREF(old);
2312 return 0;
2313 }
2314 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002315 return -1;
2316 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002317}
2318
2319static PyGetSetDef object_getsets[] = {
2320 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002321 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322 {0}
2323};
2324
Guido van Rossum3926a632001-09-25 16:25:58 +00002325static PyObject *
2326object_reduce(PyObject *self, PyObject *args)
2327{
2328 /* Call copy_reg._reduce(self) */
2329 static PyObject *copy_reg_str;
2330 PyObject *copy_reg, *res;
2331
2332 if (!copy_reg_str) {
2333 copy_reg_str = PyString_InternFromString("copy_reg");
2334 if (copy_reg_str == NULL)
2335 return NULL;
2336 }
2337 copy_reg = PyImport_Import(copy_reg_str);
2338 if (!copy_reg)
2339 return NULL;
2340 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
2341 Py_DECREF(copy_reg);
2342 return res;
2343}
2344
2345static PyMethodDef object_methods[] = {
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002346 {"__reduce__", object_reduce, METH_NOARGS,
2347 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002348 {0}
2349};
2350
Tim Peters6d6c1a32001-08-02 04:15:00 +00002351PyTypeObject PyBaseObject_Type = {
2352 PyObject_HEAD_INIT(&PyType_Type)
2353 0, /* ob_size */
2354 "object", /* tp_name */
2355 sizeof(PyObject), /* tp_basicsize */
2356 0, /* tp_itemsize */
2357 (destructor)object_dealloc, /* tp_dealloc */
2358 0, /* tp_print */
2359 0, /* tp_getattr */
2360 0, /* tp_setattr */
2361 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002362 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002363 0, /* tp_as_number */
2364 0, /* tp_as_sequence */
2365 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002366 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002367 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002368 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002369 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002370 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002371 0, /* tp_as_buffer */
2372 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002373 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374 0, /* tp_traverse */
2375 0, /* tp_clear */
2376 0, /* tp_richcompare */
2377 0, /* tp_weaklistoffset */
2378 0, /* tp_iter */
2379 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002380 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002381 0, /* tp_members */
2382 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002383 0, /* tp_base */
2384 0, /* tp_dict */
2385 0, /* tp_descr_get */
2386 0, /* tp_descr_set */
2387 0, /* tp_dictoffset */
2388 object_init, /* tp_init */
2389 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00002390 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002391 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002392};
2393
2394
2395/* Initialize the __dict__ in a type object */
2396
Fred Drake7bf97152002-03-28 05:33:33 +00002397static PyObject *
2398create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
2399{
2400 PyObject *cfunc;
2401 PyObject *result;
2402
2403 cfunc = PyCFunction_New(meth, NULL);
2404 if (cfunc == NULL)
2405 return NULL;
2406 result = func(cfunc);
2407 Py_DECREF(cfunc);
2408 return result;
2409}
2410
Tim Peters6d6c1a32001-08-02 04:15:00 +00002411static int
2412add_methods(PyTypeObject *type, PyMethodDef *meth)
2413{
Guido van Rossum687ae002001-10-15 22:03:32 +00002414 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002415
2416 for (; meth->ml_name != NULL; meth++) {
2417 PyObject *descr;
2418 if (PyDict_GetItemString(dict, meth->ml_name))
2419 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002420 if (meth->ml_flags & METH_CLASS) {
2421 if (meth->ml_flags & METH_STATIC) {
2422 PyErr_SetString(PyExc_ValueError,
2423 "method cannot be both class and static");
2424 return -1;
2425 }
2426 descr = create_specialmethod(meth, PyClassMethod_New);
2427 }
2428 else if (meth->ml_flags & METH_STATIC) {
2429 descr = create_specialmethod(meth, PyStaticMethod_New);
2430 }
2431 else {
2432 descr = PyDescr_NewMethod(type, meth);
2433 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002434 if (descr == NULL)
2435 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002436 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002437 return -1;
2438 Py_DECREF(descr);
2439 }
2440 return 0;
2441}
2442
2443static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002444add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002445{
Guido van Rossum687ae002001-10-15 22:03:32 +00002446 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002447
2448 for (; memb->name != NULL; memb++) {
2449 PyObject *descr;
2450 if (PyDict_GetItemString(dict, memb->name))
2451 continue;
2452 descr = PyDescr_NewMember(type, memb);
2453 if (descr == NULL)
2454 return -1;
2455 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2456 return -1;
2457 Py_DECREF(descr);
2458 }
2459 return 0;
2460}
2461
2462static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002463add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002464{
Guido van Rossum687ae002001-10-15 22:03:32 +00002465 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002466
2467 for (; gsp->name != NULL; gsp++) {
2468 PyObject *descr;
2469 if (PyDict_GetItemString(dict, gsp->name))
2470 continue;
2471 descr = PyDescr_NewGetSet(type, gsp);
2472
2473 if (descr == NULL)
2474 return -1;
2475 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2476 return -1;
2477 Py_DECREF(descr);
2478 }
2479 return 0;
2480}
2481
Guido van Rossum13d52f02001-08-10 21:24:08 +00002482static void
2483inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484{
2485 int oldsize, newsize;
2486
Guido van Rossum13d52f02001-08-10 21:24:08 +00002487 /* Special flag magic */
2488 if (!type->tp_as_buffer && base->tp_as_buffer) {
2489 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2490 type->tp_flags |=
2491 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2492 }
2493 if (!type->tp_as_sequence && base->tp_as_sequence) {
2494 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2495 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2496 }
2497 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2498 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2499 if ((!type->tp_as_number && base->tp_as_number) ||
2500 (!type->tp_as_sequence && base->tp_as_sequence)) {
2501 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2502 if (!type->tp_as_number && !type->tp_as_sequence) {
2503 type->tp_flags |= base->tp_flags &
2504 Py_TPFLAGS_HAVE_INPLACEOPS;
2505 }
2506 }
2507 /* Wow */
2508 }
2509 if (!type->tp_as_number && base->tp_as_number) {
2510 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2511 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2512 }
2513
2514 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002515 oldsize = base->tp_basicsize;
2516 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2517 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2518 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002519 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2520 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002521 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002522 if (type->tp_traverse == NULL)
2523 type->tp_traverse = base->tp_traverse;
2524 if (type->tp_clear == NULL)
2525 type->tp_clear = base->tp_clear;
2526 }
2527 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002528 /* The condition below could use some explanation.
2529 It appears that tp_new is not inherited for static types
2530 whose base class is 'object'; this seems to be a precaution
2531 so that old extension types don't suddenly become
2532 callable (object.__new__ wouldn't insure the invariants
2533 that the extension type's own factory function ensures).
2534 Heap types, of course, are under our control, so they do
2535 inherit tp_new; static extension types that specify some
2536 other built-in type as the default are considered
2537 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002538 if (base != &PyBaseObject_Type ||
2539 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2540 if (type->tp_new == NULL)
2541 type->tp_new = base->tp_new;
2542 }
2543 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002544 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002545
2546 /* Copy other non-function slots */
2547
2548#undef COPYVAL
2549#define COPYVAL(SLOT) \
2550 if (type->SLOT == 0) type->SLOT = base->SLOT
2551
2552 COPYVAL(tp_itemsize);
2553 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2554 COPYVAL(tp_weaklistoffset);
2555 }
2556 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2557 COPYVAL(tp_dictoffset);
2558 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002559}
2560
2561static void
2562inherit_slots(PyTypeObject *type, PyTypeObject *base)
2563{
2564 PyTypeObject *basebase;
2565
2566#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002567#undef COPYSLOT
2568#undef COPYNUM
2569#undef COPYSEQ
2570#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002571#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002572
2573#define SLOTDEFINED(SLOT) \
2574 (base->SLOT != 0 && \
2575 (basebase == NULL || base->SLOT != basebase->SLOT))
2576
Tim Peters6d6c1a32001-08-02 04:15:00 +00002577#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002578 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002579
2580#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2581#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2582#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002583#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002584
Guido van Rossum13d52f02001-08-10 21:24:08 +00002585 /* This won't inherit indirect slots (from tp_as_number etc.)
2586 if type doesn't provide the space. */
2587
2588 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2589 basebase = base->tp_base;
2590 if (basebase->tp_as_number == NULL)
2591 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002592 COPYNUM(nb_add);
2593 COPYNUM(nb_subtract);
2594 COPYNUM(nb_multiply);
2595 COPYNUM(nb_divide);
2596 COPYNUM(nb_remainder);
2597 COPYNUM(nb_divmod);
2598 COPYNUM(nb_power);
2599 COPYNUM(nb_negative);
2600 COPYNUM(nb_positive);
2601 COPYNUM(nb_absolute);
2602 COPYNUM(nb_nonzero);
2603 COPYNUM(nb_invert);
2604 COPYNUM(nb_lshift);
2605 COPYNUM(nb_rshift);
2606 COPYNUM(nb_and);
2607 COPYNUM(nb_xor);
2608 COPYNUM(nb_or);
2609 COPYNUM(nb_coerce);
2610 COPYNUM(nb_int);
2611 COPYNUM(nb_long);
2612 COPYNUM(nb_float);
2613 COPYNUM(nb_oct);
2614 COPYNUM(nb_hex);
2615 COPYNUM(nb_inplace_add);
2616 COPYNUM(nb_inplace_subtract);
2617 COPYNUM(nb_inplace_multiply);
2618 COPYNUM(nb_inplace_divide);
2619 COPYNUM(nb_inplace_remainder);
2620 COPYNUM(nb_inplace_power);
2621 COPYNUM(nb_inplace_lshift);
2622 COPYNUM(nb_inplace_rshift);
2623 COPYNUM(nb_inplace_and);
2624 COPYNUM(nb_inplace_xor);
2625 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002626 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2627 COPYNUM(nb_true_divide);
2628 COPYNUM(nb_floor_divide);
2629 COPYNUM(nb_inplace_true_divide);
2630 COPYNUM(nb_inplace_floor_divide);
2631 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002632 }
2633
Guido van Rossum13d52f02001-08-10 21:24:08 +00002634 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2635 basebase = base->tp_base;
2636 if (basebase->tp_as_sequence == NULL)
2637 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002638 COPYSEQ(sq_length);
2639 COPYSEQ(sq_concat);
2640 COPYSEQ(sq_repeat);
2641 COPYSEQ(sq_item);
2642 COPYSEQ(sq_slice);
2643 COPYSEQ(sq_ass_item);
2644 COPYSEQ(sq_ass_slice);
2645 COPYSEQ(sq_contains);
2646 COPYSEQ(sq_inplace_concat);
2647 COPYSEQ(sq_inplace_repeat);
2648 }
2649
Guido van Rossum13d52f02001-08-10 21:24:08 +00002650 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2651 basebase = base->tp_base;
2652 if (basebase->tp_as_mapping == NULL)
2653 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002654 COPYMAP(mp_length);
2655 COPYMAP(mp_subscript);
2656 COPYMAP(mp_ass_subscript);
2657 }
2658
Tim Petersfc57ccb2001-10-12 02:38:24 +00002659 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2660 basebase = base->tp_base;
2661 if (basebase->tp_as_buffer == NULL)
2662 basebase = NULL;
2663 COPYBUF(bf_getreadbuffer);
2664 COPYBUF(bf_getwritebuffer);
2665 COPYBUF(bf_getsegcount);
2666 COPYBUF(bf_getcharbuffer);
2667 }
2668
Guido van Rossum13d52f02001-08-10 21:24:08 +00002669 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002670
Tim Peters6d6c1a32001-08-02 04:15:00 +00002671 COPYSLOT(tp_dealloc);
2672 COPYSLOT(tp_print);
2673 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2674 type->tp_getattr = base->tp_getattr;
2675 type->tp_getattro = base->tp_getattro;
2676 }
2677 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2678 type->tp_setattr = base->tp_setattr;
2679 type->tp_setattro = base->tp_setattro;
2680 }
2681 /* tp_compare see tp_richcompare */
2682 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002683 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002684 COPYSLOT(tp_call);
2685 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002686 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002687 if (type->tp_compare == NULL &&
2688 type->tp_richcompare == NULL &&
2689 type->tp_hash == NULL)
2690 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002691 type->tp_compare = base->tp_compare;
2692 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002693 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002694 }
2695 }
2696 else {
2697 COPYSLOT(tp_compare);
2698 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002699 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2700 COPYSLOT(tp_iter);
2701 COPYSLOT(tp_iternext);
2702 }
2703 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2704 COPYSLOT(tp_descr_get);
2705 COPYSLOT(tp_descr_set);
2706 COPYSLOT(tp_dictoffset);
2707 COPYSLOT(tp_init);
2708 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002709 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002710 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002711 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712}
2713
Jeremy Hylton938ace62002-07-17 16:30:39 +00002714static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002715
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002717PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002718{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002719 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002720 PyTypeObject *base;
2721 int i, n;
2722
Guido van Rossumcab05802002-06-10 15:29:03 +00002723 if (type->tp_flags & Py_TPFLAGS_READY) {
2724 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002725 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002726 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002727 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002728
2729 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730
2731 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2732 base = type->tp_base;
2733 if (base == NULL && type != &PyBaseObject_Type)
2734 base = type->tp_base = &PyBaseObject_Type;
2735
Guido van Rossum323a9cf2002-08-14 17:26:30 +00002736 /* Initialize the base class */
2737 if (base && base->tp_dict == NULL) {
2738 if (PyType_Ready(base) < 0)
2739 goto error;
2740 }
2741
Guido van Rossum0986d822002-04-08 01:38:42 +00002742 /* Initialize ob_type if NULL. This means extensions that want to be
2743 compilable separately on Windows can call PyType_Ready() instead of
2744 initializing the ob_type field of their type objects. */
2745 if (type->ob_type == NULL)
2746 type->ob_type = base->ob_type;
2747
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748 /* Initialize tp_bases */
2749 bases = type->tp_bases;
2750 if (bases == NULL) {
2751 if (base == NULL)
2752 bases = PyTuple_New(0);
2753 else
2754 bases = Py_BuildValue("(O)", base);
2755 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002756 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757 type->tp_bases = bases;
2758 }
2759
Guido van Rossum687ae002001-10-15 22:03:32 +00002760 /* Initialize tp_dict */
2761 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002762 if (dict == NULL) {
2763 dict = PyDict_New();
2764 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002765 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002766 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767 }
2768
Guido van Rossum687ae002001-10-15 22:03:32 +00002769 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002770 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002771 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772 if (type->tp_methods != NULL) {
2773 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002774 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002775 }
2776 if (type->tp_members != NULL) {
2777 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002778 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002779 }
2780 if (type->tp_getset != NULL) {
2781 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002782 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002783 }
2784
Tim Peters6d6c1a32001-08-02 04:15:00 +00002785 /* Calculate method resolution order */
2786 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002787 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788 }
2789
Guido van Rossum13d52f02001-08-10 21:24:08 +00002790 /* Inherit special flags from dominant base */
2791 if (type->tp_base != NULL)
2792 inherit_special(type, type->tp_base);
2793
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002795 bases = type->tp_mro;
2796 assert(bases != NULL);
2797 assert(PyTuple_Check(bases));
2798 n = PyTuple_GET_SIZE(bases);
2799 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002800 PyObject *b = PyTuple_GET_ITEM(bases, i);
2801 if (PyType_Check(b))
2802 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002803 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002804
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002805 /* if the type dictionary doesn't contain a __doc__, set it from
2806 the tp_doc slot.
2807 */
2808 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2809 if (type->tp_doc != NULL) {
2810 PyObject *doc = PyString_FromString(type->tp_doc);
2811 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2812 Py_DECREF(doc);
2813 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002814 PyDict_SetItemString(type->tp_dict,
2815 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002816 }
2817 }
2818
Guido van Rossum13d52f02001-08-10 21:24:08 +00002819 /* Some more special stuff */
2820 base = type->tp_base;
2821 if (base != NULL) {
2822 if (type->tp_as_number == NULL)
2823 type->tp_as_number = base->tp_as_number;
2824 if (type->tp_as_sequence == NULL)
2825 type->tp_as_sequence = base->tp_as_sequence;
2826 if (type->tp_as_mapping == NULL)
2827 type->tp_as_mapping = base->tp_as_mapping;
2828 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002829
Guido van Rossum1c450732001-10-08 15:18:27 +00002830 /* Link into each base class's list of subclasses */
2831 bases = type->tp_bases;
2832 n = PyTuple_GET_SIZE(bases);
2833 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002834 PyObject *b = PyTuple_GET_ITEM(bases, i);
2835 if (PyType_Check(b) &&
2836 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002837 goto error;
2838 }
2839
Guido van Rossum13d52f02001-08-10 21:24:08 +00002840 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002841 assert(type->tp_dict != NULL);
2842 type->tp_flags =
2843 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002844 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002845
2846 error:
2847 type->tp_flags &= ~Py_TPFLAGS_READYING;
2848 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002849}
2850
Guido van Rossum1c450732001-10-08 15:18:27 +00002851static int
2852add_subclass(PyTypeObject *base, PyTypeObject *type)
2853{
2854 int i;
2855 PyObject *list, *ref, *new;
2856
2857 list = base->tp_subclasses;
2858 if (list == NULL) {
2859 base->tp_subclasses = list = PyList_New(0);
2860 if (list == NULL)
2861 return -1;
2862 }
2863 assert(PyList_Check(list));
2864 new = PyWeakref_NewRef((PyObject *)type, NULL);
2865 i = PyList_GET_SIZE(list);
2866 while (--i >= 0) {
2867 ref = PyList_GET_ITEM(list, i);
2868 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00002869 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2870 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00002871 }
2872 i = PyList_Append(list, new);
2873 Py_DECREF(new);
2874 return i;
2875}
2876
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002877static void
2878remove_subclass(PyTypeObject *base, PyTypeObject *type)
2879{
2880 int i;
2881 PyObject *list, *ref;
2882
2883 list = base->tp_subclasses;
2884 if (list == NULL) {
2885 return;
2886 }
2887 assert(PyList_Check(list));
2888 i = PyList_GET_SIZE(list);
2889 while (--i >= 0) {
2890 ref = PyList_GET_ITEM(list, i);
2891 assert(PyWeakref_CheckRef(ref));
2892 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
2893 /* this can't fail, right? */
2894 PySequence_DelItem(list, i);
2895 return;
2896 }
2897 }
2898}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002899
2900/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2901
2902/* There's a wrapper *function* for each distinct function typedef used
2903 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2904 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2905 Most tables have only one entry; the tables for binary operators have two
2906 entries, one regular and one with reversed arguments. */
2907
2908static PyObject *
2909wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2910{
2911 inquiry func = (inquiry)wrapped;
2912 int res;
2913
2914 if (!PyArg_ParseTuple(args, ""))
2915 return NULL;
2916 res = (*func)(self);
2917 if (res == -1 && PyErr_Occurred())
2918 return NULL;
2919 return PyInt_FromLong((long)res);
2920}
2921
Tim Peters6d6c1a32001-08-02 04:15:00 +00002922static PyObject *
2923wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2924{
2925 binaryfunc func = (binaryfunc)wrapped;
2926 PyObject *other;
2927
2928 if (!PyArg_ParseTuple(args, "O", &other))
2929 return NULL;
2930 return (*func)(self, other);
2931}
2932
2933static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002934wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2935{
2936 binaryfunc func = (binaryfunc)wrapped;
2937 PyObject *other;
2938
2939 if (!PyArg_ParseTuple(args, "O", &other))
2940 return NULL;
2941 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002942 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002943 Py_INCREF(Py_NotImplemented);
2944 return Py_NotImplemented;
2945 }
2946 return (*func)(self, other);
2947}
2948
2949static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002950wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2951{
2952 binaryfunc func = (binaryfunc)wrapped;
2953 PyObject *other;
2954
2955 if (!PyArg_ParseTuple(args, "O", &other))
2956 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002957 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002958 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002959 Py_INCREF(Py_NotImplemented);
2960 return Py_NotImplemented;
2961 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962 return (*func)(other, self);
2963}
2964
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002965static PyObject *
2966wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2967{
2968 coercion func = (coercion)wrapped;
2969 PyObject *other, *res;
2970 int ok;
2971
2972 if (!PyArg_ParseTuple(args, "O", &other))
2973 return NULL;
2974 ok = func(&self, &other);
2975 if (ok < 0)
2976 return NULL;
2977 if (ok > 0) {
2978 Py_INCREF(Py_NotImplemented);
2979 return Py_NotImplemented;
2980 }
2981 res = PyTuple_New(2);
2982 if (res == NULL) {
2983 Py_DECREF(self);
2984 Py_DECREF(other);
2985 return NULL;
2986 }
2987 PyTuple_SET_ITEM(res, 0, self);
2988 PyTuple_SET_ITEM(res, 1, other);
2989 return res;
2990}
2991
Tim Peters6d6c1a32001-08-02 04:15:00 +00002992static PyObject *
2993wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
2994{
2995 ternaryfunc func = (ternaryfunc)wrapped;
2996 PyObject *other;
2997 PyObject *third = Py_None;
2998
2999 /* Note: This wrapper only works for __pow__() */
3000
3001 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3002 return NULL;
3003 return (*func)(self, other, third);
3004}
3005
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003006static PyObject *
3007wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3008{
3009 ternaryfunc func = (ternaryfunc)wrapped;
3010 PyObject *other;
3011 PyObject *third = Py_None;
3012
3013 /* Note: This wrapper only works for __pow__() */
3014
3015 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3016 return NULL;
3017 return (*func)(other, self, third);
3018}
3019
Tim Peters6d6c1a32001-08-02 04:15:00 +00003020static PyObject *
3021wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3022{
3023 unaryfunc func = (unaryfunc)wrapped;
3024
3025 if (!PyArg_ParseTuple(args, ""))
3026 return NULL;
3027 return (*func)(self);
3028}
3029
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030static PyObject *
3031wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3032{
3033 intargfunc func = (intargfunc)wrapped;
3034 int i;
3035
3036 if (!PyArg_ParseTuple(args, "i", &i))
3037 return NULL;
3038 return (*func)(self, i);
3039}
3040
Guido van Rossum5d815f32001-08-17 21:57:47 +00003041static int
3042getindex(PyObject *self, PyObject *arg)
3043{
3044 int i;
3045
3046 i = PyInt_AsLong(arg);
3047 if (i == -1 && PyErr_Occurred())
3048 return -1;
3049 if (i < 0) {
3050 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3051 if (sq && sq->sq_length) {
3052 int n = (*sq->sq_length)(self);
3053 if (n < 0)
3054 return -1;
3055 i += n;
3056 }
3057 }
3058 return i;
3059}
3060
3061static PyObject *
3062wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3063{
3064 intargfunc func = (intargfunc)wrapped;
3065 PyObject *arg;
3066 int i;
3067
Guido van Rossumf4593e02001-10-03 12:09:30 +00003068 if (PyTuple_GET_SIZE(args) == 1) {
3069 arg = PyTuple_GET_ITEM(args, 0);
3070 i = getindex(self, arg);
3071 if (i == -1 && PyErr_Occurred())
3072 return NULL;
3073 return (*func)(self, i);
3074 }
3075 PyArg_ParseTuple(args, "O", &arg);
3076 assert(PyErr_Occurred());
3077 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003078}
3079
Tim Peters6d6c1a32001-08-02 04:15:00 +00003080static PyObject *
3081wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3082{
3083 intintargfunc func = (intintargfunc)wrapped;
3084 int i, j;
3085
3086 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3087 return NULL;
3088 return (*func)(self, i, j);
3089}
3090
Tim Peters6d6c1a32001-08-02 04:15:00 +00003091static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003092wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003093{
3094 intobjargproc func = (intobjargproc)wrapped;
3095 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003096 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003097
Guido van Rossum5d815f32001-08-17 21:57:47 +00003098 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3099 return NULL;
3100 i = getindex(self, arg);
3101 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003102 return NULL;
3103 res = (*func)(self, i, value);
3104 if (res == -1 && PyErr_Occurred())
3105 return NULL;
3106 Py_INCREF(Py_None);
3107 return Py_None;
3108}
3109
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003110static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003111wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003112{
3113 intobjargproc func = (intobjargproc)wrapped;
3114 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003115 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003116
Guido van Rossum5d815f32001-08-17 21:57:47 +00003117 if (!PyArg_ParseTuple(args, "O", &arg))
3118 return NULL;
3119 i = getindex(self, arg);
3120 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003121 return NULL;
3122 res = (*func)(self, i, NULL);
3123 if (res == -1 && PyErr_Occurred())
3124 return NULL;
3125 Py_INCREF(Py_None);
3126 return Py_None;
3127}
3128
Tim Peters6d6c1a32001-08-02 04:15:00 +00003129static PyObject *
3130wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3131{
3132 intintobjargproc func = (intintobjargproc)wrapped;
3133 int i, j, res;
3134 PyObject *value;
3135
3136 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3137 return NULL;
3138 res = (*func)(self, i, j, value);
3139 if (res == -1 && PyErr_Occurred())
3140 return NULL;
3141 Py_INCREF(Py_None);
3142 return Py_None;
3143}
3144
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003145static PyObject *
3146wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3147{
3148 intintobjargproc func = (intintobjargproc)wrapped;
3149 int i, j, res;
3150
3151 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3152 return NULL;
3153 res = (*func)(self, i, j, NULL);
3154 if (res == -1 && PyErr_Occurred())
3155 return NULL;
3156 Py_INCREF(Py_None);
3157 return Py_None;
3158}
3159
Tim Peters6d6c1a32001-08-02 04:15:00 +00003160/* XXX objobjproc is a misnomer; should be objargpred */
3161static PyObject *
3162wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3163{
3164 objobjproc func = (objobjproc)wrapped;
3165 int res;
3166 PyObject *value;
3167
3168 if (!PyArg_ParseTuple(args, "O", &value))
3169 return NULL;
3170 res = (*func)(self, value);
3171 if (res == -1 && PyErr_Occurred())
3172 return NULL;
3173 return PyInt_FromLong((long)res);
3174}
3175
Tim Peters6d6c1a32001-08-02 04:15:00 +00003176static PyObject *
3177wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3178{
3179 objobjargproc func = (objobjargproc)wrapped;
3180 int res;
3181 PyObject *key, *value;
3182
3183 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3184 return NULL;
3185 res = (*func)(self, key, value);
3186 if (res == -1 && PyErr_Occurred())
3187 return NULL;
3188 Py_INCREF(Py_None);
3189 return Py_None;
3190}
3191
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003192static PyObject *
3193wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3194{
3195 objobjargproc func = (objobjargproc)wrapped;
3196 int res;
3197 PyObject *key;
3198
3199 if (!PyArg_ParseTuple(args, "O", &key))
3200 return NULL;
3201 res = (*func)(self, key, NULL);
3202 if (res == -1 && PyErr_Occurred())
3203 return NULL;
3204 Py_INCREF(Py_None);
3205 return Py_None;
3206}
3207
Tim Peters6d6c1a32001-08-02 04:15:00 +00003208static PyObject *
3209wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3210{
3211 cmpfunc func = (cmpfunc)wrapped;
3212 int res;
3213 PyObject *other;
3214
3215 if (!PyArg_ParseTuple(args, "O", &other))
3216 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003217 if (other->ob_type->tp_compare != func &&
3218 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003219 PyErr_Format(
3220 PyExc_TypeError,
3221 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3222 self->ob_type->tp_name,
3223 self->ob_type->tp_name,
3224 other->ob_type->tp_name);
3225 return NULL;
3226 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003227 res = (*func)(self, other);
3228 if (PyErr_Occurred())
3229 return NULL;
3230 return PyInt_FromLong((long)res);
3231}
3232
Tim Peters6d6c1a32001-08-02 04:15:00 +00003233static PyObject *
3234wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3235{
3236 setattrofunc func = (setattrofunc)wrapped;
3237 int res;
3238 PyObject *name, *value;
3239
3240 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3241 return NULL;
3242 res = (*func)(self, name, value);
3243 if (res < 0)
3244 return NULL;
3245 Py_INCREF(Py_None);
3246 return Py_None;
3247}
3248
3249static PyObject *
3250wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3251{
3252 setattrofunc func = (setattrofunc)wrapped;
3253 int res;
3254 PyObject *name;
3255
3256 if (!PyArg_ParseTuple(args, "O", &name))
3257 return NULL;
3258 res = (*func)(self, name, NULL);
3259 if (res < 0)
3260 return NULL;
3261 Py_INCREF(Py_None);
3262 return Py_None;
3263}
3264
Tim Peters6d6c1a32001-08-02 04:15:00 +00003265static PyObject *
3266wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3267{
3268 hashfunc func = (hashfunc)wrapped;
3269 long res;
3270
3271 if (!PyArg_ParseTuple(args, ""))
3272 return NULL;
3273 res = (*func)(self);
3274 if (res == -1 && PyErr_Occurred())
3275 return NULL;
3276 return PyInt_FromLong(res);
3277}
3278
Tim Peters6d6c1a32001-08-02 04:15:00 +00003279static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003280wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003281{
3282 ternaryfunc func = (ternaryfunc)wrapped;
3283
Guido van Rossumc8e56452001-10-22 00:43:43 +00003284 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003285}
3286
Tim Peters6d6c1a32001-08-02 04:15:00 +00003287static PyObject *
3288wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3289{
3290 richcmpfunc func = (richcmpfunc)wrapped;
3291 PyObject *other;
3292
3293 if (!PyArg_ParseTuple(args, "O", &other))
3294 return NULL;
3295 return (*func)(self, other, op);
3296}
3297
3298#undef RICHCMP_WRAPPER
3299#define RICHCMP_WRAPPER(NAME, OP) \
3300static PyObject * \
3301richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3302{ \
3303 return wrap_richcmpfunc(self, args, wrapped, OP); \
3304}
3305
Jack Jansen8e938b42001-08-08 15:29:49 +00003306RICHCMP_WRAPPER(lt, Py_LT)
3307RICHCMP_WRAPPER(le, Py_LE)
3308RICHCMP_WRAPPER(eq, Py_EQ)
3309RICHCMP_WRAPPER(ne, Py_NE)
3310RICHCMP_WRAPPER(gt, Py_GT)
3311RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003312
Tim Peters6d6c1a32001-08-02 04:15:00 +00003313static PyObject *
3314wrap_next(PyObject *self, PyObject *args, void *wrapped)
3315{
3316 unaryfunc func = (unaryfunc)wrapped;
3317 PyObject *res;
3318
3319 if (!PyArg_ParseTuple(args, ""))
3320 return NULL;
3321 res = (*func)(self);
3322 if (res == NULL && !PyErr_Occurred())
3323 PyErr_SetNone(PyExc_StopIteration);
3324 return res;
3325}
3326
Tim Peters6d6c1a32001-08-02 04:15:00 +00003327static PyObject *
3328wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3329{
3330 descrgetfunc func = (descrgetfunc)wrapped;
3331 PyObject *obj;
3332 PyObject *type = NULL;
3333
3334 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3335 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003336 return (*func)(self, obj, type);
3337}
3338
Tim Peters6d6c1a32001-08-02 04:15:00 +00003339static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003340wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003341{
3342 descrsetfunc func = (descrsetfunc)wrapped;
3343 PyObject *obj, *value;
3344 int ret;
3345
3346 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3347 return NULL;
3348 ret = (*func)(self, obj, value);
3349 if (ret < 0)
3350 return NULL;
3351 Py_INCREF(Py_None);
3352 return Py_None;
3353}
Guido van Rossum22b13872002-08-06 21:41:44 +00003354
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003355static PyObject *
3356wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3357{
3358 descrsetfunc func = (descrsetfunc)wrapped;
3359 PyObject *obj;
3360 int ret;
3361
3362 if (!PyArg_ParseTuple(args, "O", &obj))
3363 return NULL;
3364 ret = (*func)(self, obj, NULL);
3365 if (ret < 0)
3366 return NULL;
3367 Py_INCREF(Py_None);
3368 return Py_None;
3369}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003370
Tim Peters6d6c1a32001-08-02 04:15:00 +00003371static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003372wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003373{
3374 initproc func = (initproc)wrapped;
3375
Guido van Rossumc8e56452001-10-22 00:43:43 +00003376 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003377 return NULL;
3378 Py_INCREF(Py_None);
3379 return Py_None;
3380}
3381
Tim Peters6d6c1a32001-08-02 04:15:00 +00003382static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003383tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003384{
Barry Warsaw60f01882001-08-22 19:24:42 +00003385 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003386 PyObject *arg0, *res;
3387
3388 if (self == NULL || !PyType_Check(self))
3389 Py_FatalError("__new__() called with non-type 'self'");
3390 type = (PyTypeObject *)self;
3391 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003392 PyErr_Format(PyExc_TypeError,
3393 "%s.__new__(): not enough arguments",
3394 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003395 return NULL;
3396 }
3397 arg0 = PyTuple_GET_ITEM(args, 0);
3398 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003399 PyErr_Format(PyExc_TypeError,
3400 "%s.__new__(X): X is not a type object (%s)",
3401 type->tp_name,
3402 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003403 return NULL;
3404 }
3405 subtype = (PyTypeObject *)arg0;
3406 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003407 PyErr_Format(PyExc_TypeError,
3408 "%s.__new__(%s): %s is not a subtype of %s",
3409 type->tp_name,
3410 subtype->tp_name,
3411 subtype->tp_name,
3412 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003413 return NULL;
3414 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003415
3416 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003417 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003418 most derived base that's not a heap type is this type. */
3419 staticbase = subtype;
3420 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3421 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003422 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003423 PyErr_Format(PyExc_TypeError,
3424 "%s.__new__(%s) is not safe, use %s.__new__()",
3425 type->tp_name,
3426 subtype->tp_name,
3427 staticbase == NULL ? "?" : staticbase->tp_name);
3428 return NULL;
3429 }
3430
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003431 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3432 if (args == NULL)
3433 return NULL;
3434 res = type->tp_new(subtype, args, kwds);
3435 Py_DECREF(args);
3436 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003437}
3438
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003439static struct PyMethodDef tp_new_methoddef[] = {
3440 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003441 PyDoc_STR("T.__new__(S, ...) -> "
3442 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003443 {0}
3444};
3445
3446static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003447add_tp_new_wrapper(PyTypeObject *type)
3448{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003449 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003450
Guido van Rossum687ae002001-10-15 22:03:32 +00003451 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003452 return 0;
3453 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003454 if (func == NULL)
3455 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003456 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003457}
3458
Guido van Rossumf040ede2001-08-07 16:40:56 +00003459/* Slot wrappers that call the corresponding __foo__ slot. See comments
3460 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003461
Guido van Rossumdc91b992001-08-08 22:26:22 +00003462#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003463static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003464FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003465{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003466 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003467 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003468}
3469
Guido van Rossumdc91b992001-08-08 22:26:22 +00003470#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003471static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003472FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003474 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003475 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003476}
3477
Guido van Rossumdc91b992001-08-08 22:26:22 +00003478
3479#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003481FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003483 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003484 int do_other = self->ob_type != other->ob_type && \
3485 other->ob_type->tp_as_number != NULL && \
3486 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003487 if (self->ob_type->tp_as_number != NULL && \
3488 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3489 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003490 if (do_other && \
3491 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
3492 r = call_maybe( \
3493 other, ROPSTR, &rcache_str, "(O)", self); \
3494 if (r != Py_NotImplemented) \
3495 return r; \
3496 Py_DECREF(r); \
3497 do_other = 0; \
3498 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003499 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003500 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003501 if (r != Py_NotImplemented || \
3502 other->ob_type == self->ob_type) \
3503 return r; \
3504 Py_DECREF(r); \
3505 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003506 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003507 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003508 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003509 } \
3510 Py_INCREF(Py_NotImplemented); \
3511 return Py_NotImplemented; \
3512}
3513
3514#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3515 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3516
3517#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3518static PyObject * \
3519FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3520{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003521 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003522 return call_method(self, OPSTR, &cache_str, \
3523 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003524}
3525
3526static int
3527slot_sq_length(PyObject *self)
3528{
Guido van Rossum2730b132001-08-28 18:22:14 +00003529 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003530 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003531 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003532
3533 if (res == NULL)
3534 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003535 len = (int)PyInt_AsLong(res);
3536 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003537 if (len == -1 && PyErr_Occurred())
3538 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003539 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003540 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003541 "__len__() should return >= 0");
3542 return -1;
3543 }
Guido van Rossum26111622001-10-01 16:42:49 +00003544 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003545}
3546
Guido van Rossumdc91b992001-08-08 22:26:22 +00003547SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3548SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003549
3550/* Super-optimized version of slot_sq_item.
3551 Other slots could do the same... */
3552static PyObject *
3553slot_sq_item(PyObject *self, int i)
3554{
3555 static PyObject *getitem_str;
3556 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3557 descrgetfunc f;
3558
3559 if (getitem_str == NULL) {
3560 getitem_str = PyString_InternFromString("__getitem__");
3561 if (getitem_str == NULL)
3562 return NULL;
3563 }
3564 func = _PyType_Lookup(self->ob_type, getitem_str);
3565 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003566 if ((f = func->ob_type->tp_descr_get) == NULL)
3567 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003568 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003569 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003570 if (func == NULL) {
3571 return NULL;
3572 }
3573 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003574 ival = PyInt_FromLong(i);
3575 if (ival != NULL) {
3576 args = PyTuple_New(1);
3577 if (args != NULL) {
3578 PyTuple_SET_ITEM(args, 0, ival);
3579 retval = PyObject_Call(func, args, NULL);
3580 Py_XDECREF(args);
3581 Py_XDECREF(func);
3582 return retval;
3583 }
3584 }
3585 }
3586 else {
3587 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3588 }
3589 Py_XDECREF(args);
3590 Py_XDECREF(ival);
3591 Py_XDECREF(func);
3592 return NULL;
3593}
3594
Guido van Rossumdc91b992001-08-08 22:26:22 +00003595SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003596
3597static int
3598slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3599{
3600 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003601 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602
3603 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003604 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003605 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003606 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003607 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003608 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609 if (res == NULL)
3610 return -1;
3611 Py_DECREF(res);
3612 return 0;
3613}
3614
3615static int
3616slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3617{
3618 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003619 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003620
3621 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003622 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003623 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003625 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003626 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627 if (res == NULL)
3628 return -1;
3629 Py_DECREF(res);
3630 return 0;
3631}
3632
3633static int
3634slot_sq_contains(PyObject *self, PyObject *value)
3635{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003636 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003637 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003638
Guido van Rossum55f20992001-10-01 17:18:22 +00003639 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003640
3641 if (func != NULL) {
3642 args = Py_BuildValue("(O)", value);
3643 if (args == NULL)
3644 res = NULL;
3645 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003646 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003647 Py_DECREF(args);
3648 }
3649 Py_DECREF(func);
3650 if (res == NULL)
3651 return -1;
3652 return PyObject_IsTrue(res);
3653 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003654 else if (PyErr_Occurred())
3655 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003656 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003657 return _PySequence_IterSearch(self, value,
3658 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003659 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003660}
3661
Guido van Rossumdc91b992001-08-08 22:26:22 +00003662SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3663SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003664
3665#define slot_mp_length slot_sq_length
3666
Guido van Rossumdc91b992001-08-08 22:26:22 +00003667SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003668
3669static int
3670slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3671{
3672 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003673 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674
3675 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003676 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003677 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003678 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003679 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003680 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003681 if (res == NULL)
3682 return -1;
3683 Py_DECREF(res);
3684 return 0;
3685}
3686
Guido van Rossumdc91b992001-08-08 22:26:22 +00003687SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3688SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3689SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3690SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3691SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3692SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3693
Jeremy Hylton938ace62002-07-17 16:30:39 +00003694static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003695
3696SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3697 nb_power, "__pow__", "__rpow__")
3698
3699static PyObject *
3700slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3701{
Guido van Rossum2730b132001-08-28 18:22:14 +00003702 static PyObject *pow_str;
3703
Guido van Rossumdc91b992001-08-08 22:26:22 +00003704 if (modulus == Py_None)
3705 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003706 /* Three-arg power doesn't use __rpow__. But ternary_op
3707 can call this when the second argument's type uses
3708 slot_nb_power, so check before calling self.__pow__. */
3709 if (self->ob_type->tp_as_number != NULL &&
3710 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3711 return call_method(self, "__pow__", &pow_str,
3712 "(OO)", other, modulus);
3713 }
3714 Py_INCREF(Py_NotImplemented);
3715 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003716}
3717
3718SLOT0(slot_nb_negative, "__neg__")
3719SLOT0(slot_nb_positive, "__pos__")
3720SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003721
3722static int
3723slot_nb_nonzero(PyObject *self)
3724{
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003725 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003726 static PyObject *nonzero_str, *len_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003727
Guido van Rossum55f20992001-10-01 17:18:22 +00003728 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003729 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003730 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003731 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003732 func = lookup_maybe(self, "__len__", &len_str);
3733 if (func == NULL) {
3734 if (PyErr_Occurred())
3735 return -1;
3736 else
3737 return 1;
3738 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003739 }
Guido van Rossum84b2bed2002-08-16 17:01:09 +00003740 args = res = PyTuple_New(0);
3741 if (args != NULL) {
3742 res = PyObject_Call(func, args, NULL);
3743 Py_DECREF(args);
3744 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003745 Py_DECREF(func);
3746 if (res == NULL)
3747 return -1;
3748 return PyObject_IsTrue(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003749}
3750
Guido van Rossumdc91b992001-08-08 22:26:22 +00003751SLOT0(slot_nb_invert, "__invert__")
3752SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3753SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3754SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3755SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3756SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003757
3758static int
3759slot_nb_coerce(PyObject **a, PyObject **b)
3760{
3761 static PyObject *coerce_str;
3762 PyObject *self = *a, *other = *b;
3763
3764 if (self->ob_type->tp_as_number != NULL &&
3765 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3766 PyObject *r;
3767 r = call_maybe(
3768 self, "__coerce__", &coerce_str, "(O)", other);
3769 if (r == NULL)
3770 return -1;
3771 if (r == Py_NotImplemented) {
3772 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003773 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003774 else {
3775 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3776 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003777 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003778 Py_DECREF(r);
3779 return -1;
3780 }
3781 *a = PyTuple_GET_ITEM(r, 0);
3782 Py_INCREF(*a);
3783 *b = PyTuple_GET_ITEM(r, 1);
3784 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003785 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003786 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003787 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003788 }
3789 if (other->ob_type->tp_as_number != NULL &&
3790 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3791 PyObject *r;
3792 r = call_maybe(
3793 other, "__coerce__", &coerce_str, "(O)", self);
3794 if (r == NULL)
3795 return -1;
3796 if (r == Py_NotImplemented) {
3797 Py_DECREF(r);
3798 return 1;
3799 }
3800 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3801 PyErr_SetString(PyExc_TypeError,
3802 "__coerce__ didn't return a 2-tuple");
3803 Py_DECREF(r);
3804 return -1;
3805 }
3806 *a = PyTuple_GET_ITEM(r, 1);
3807 Py_INCREF(*a);
3808 *b = PyTuple_GET_ITEM(r, 0);
3809 Py_INCREF(*b);
3810 Py_DECREF(r);
3811 return 0;
3812 }
3813 return 1;
3814}
3815
Guido van Rossumdc91b992001-08-08 22:26:22 +00003816SLOT0(slot_nb_int, "__int__")
3817SLOT0(slot_nb_long, "__long__")
3818SLOT0(slot_nb_float, "__float__")
3819SLOT0(slot_nb_oct, "__oct__")
3820SLOT0(slot_nb_hex, "__hex__")
3821SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3822SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3823SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3824SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3825SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003826SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003827SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3828SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3829SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3830SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3831SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3832SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3833 "__floordiv__", "__rfloordiv__")
3834SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3835SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3836SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003837
3838static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003839half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003840{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003841 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003842 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003843 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003844
Guido van Rossum60718732001-08-28 17:47:51 +00003845 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003846 if (func == NULL) {
3847 PyErr_Clear();
3848 }
3849 else {
3850 args = Py_BuildValue("(O)", other);
3851 if (args == NULL)
3852 res = NULL;
3853 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003854 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003855 Py_DECREF(args);
3856 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003857 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003858 if (res != Py_NotImplemented) {
3859 if (res == NULL)
3860 return -2;
3861 c = PyInt_AsLong(res);
3862 Py_DECREF(res);
3863 if (c == -1 && PyErr_Occurred())
3864 return -2;
3865 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3866 }
3867 Py_DECREF(res);
3868 }
3869 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003870}
3871
Guido van Rossumab3b0342001-09-18 20:38:53 +00003872/* This slot is published for the benefit of try_3way_compare in object.c */
3873int
3874_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003875{
3876 int c;
3877
Guido van Rossumab3b0342001-09-18 20:38:53 +00003878 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003879 c = half_compare(self, other);
3880 if (c <= 1)
3881 return c;
3882 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003883 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003884 c = half_compare(other, self);
3885 if (c < -1)
3886 return -2;
3887 if (c <= 1)
3888 return -c;
3889 }
3890 return (void *)self < (void *)other ? -1 :
3891 (void *)self > (void *)other ? 1 : 0;
3892}
3893
3894static PyObject *
3895slot_tp_repr(PyObject *self)
3896{
3897 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003898 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003899
Guido van Rossum60718732001-08-28 17:47:51 +00003900 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003901 if (func != NULL) {
3902 res = PyEval_CallObject(func, NULL);
3903 Py_DECREF(func);
3904 return res;
3905 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003906 PyErr_Clear();
3907 return PyString_FromFormat("<%s object at %p>",
3908 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003909}
3910
3911static PyObject *
3912slot_tp_str(PyObject *self)
3913{
3914 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003915 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003916
Guido van Rossum60718732001-08-28 17:47:51 +00003917 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003918 if (func != NULL) {
3919 res = PyEval_CallObject(func, NULL);
3920 Py_DECREF(func);
3921 return res;
3922 }
3923 else {
3924 PyErr_Clear();
3925 return slot_tp_repr(self);
3926 }
3927}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003928
3929static long
3930slot_tp_hash(PyObject *self)
3931{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003932 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003933 static PyObject *hash_str, *eq_str, *cmp_str;
3934
Tim Peters6d6c1a32001-08-02 04:15:00 +00003935 long h;
3936
Guido van Rossum60718732001-08-28 17:47:51 +00003937 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003938
3939 if (func != NULL) {
3940 res = PyEval_CallObject(func, NULL);
3941 Py_DECREF(func);
3942 if (res == NULL)
3943 return -1;
3944 h = PyInt_AsLong(res);
3945 }
3946 else {
3947 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003948 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003949 if (func == NULL) {
3950 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003951 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003952 }
3953 if (func != NULL) {
3954 Py_DECREF(func);
3955 PyErr_SetString(PyExc_TypeError, "unhashable type");
3956 return -1;
3957 }
3958 PyErr_Clear();
3959 h = _Py_HashPointer((void *)self);
3960 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003961 if (h == -1 && !PyErr_Occurred())
3962 h = -2;
3963 return h;
3964}
3965
3966static PyObject *
3967slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3968{
Guido van Rossum60718732001-08-28 17:47:51 +00003969 static PyObject *call_str;
3970 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003971 PyObject *res;
3972
3973 if (meth == NULL)
3974 return NULL;
3975 res = PyObject_Call(meth, args, kwds);
3976 Py_DECREF(meth);
3977 return res;
3978}
3979
Guido van Rossum14a6f832001-10-17 13:59:09 +00003980/* There are two slot dispatch functions for tp_getattro.
3981
3982 - slot_tp_getattro() is used when __getattribute__ is overridden
3983 but no __getattr__ hook is present;
3984
3985 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3986
Guido van Rossumc334df52002-04-04 23:44:47 +00003987 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3988 detects the absence of __getattr__ and then installs the simpler slot if
3989 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00003990
Tim Peters6d6c1a32001-08-02 04:15:00 +00003991static PyObject *
3992slot_tp_getattro(PyObject *self, PyObject *name)
3993{
Guido van Rossum14a6f832001-10-17 13:59:09 +00003994 static PyObject *getattribute_str = NULL;
3995 return call_method(self, "__getattribute__", &getattribute_str,
3996 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003997}
3998
Guido van Rossum19c1cd52001-09-21 21:24:49 +00003999static PyObject *
4000slot_tp_getattr_hook(PyObject *self, PyObject *name)
4001{
4002 PyTypeObject *tp = self->ob_type;
4003 PyObject *getattr, *getattribute, *res;
4004 static PyObject *getattribute_str = NULL;
4005 static PyObject *getattr_str = NULL;
4006
4007 if (getattr_str == NULL) {
4008 getattr_str = PyString_InternFromString("__getattr__");
4009 if (getattr_str == NULL)
4010 return NULL;
4011 }
4012 if (getattribute_str == NULL) {
4013 getattribute_str =
4014 PyString_InternFromString("__getattribute__");
4015 if (getattribute_str == NULL)
4016 return NULL;
4017 }
4018 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004019 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004020 /* No __getattr__ hook: use a simpler dispatcher */
4021 tp->tp_getattro = slot_tp_getattro;
4022 return slot_tp_getattro(self, name);
4023 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004024 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004025 if (getattribute == NULL ||
4026 (getattribute->ob_type == &PyWrapperDescr_Type &&
4027 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4028 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004029 res = PyObject_GenericGetAttr(self, name);
4030 else
4031 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004032 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004033 PyErr_Clear();
4034 res = PyObject_CallFunction(getattr, "OO", self, name);
4035 }
4036 return res;
4037}
4038
Tim Peters6d6c1a32001-08-02 04:15:00 +00004039static int
4040slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4041{
4042 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004043 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004044
4045 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004046 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004047 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004048 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004049 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004050 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051 if (res == NULL)
4052 return -1;
4053 Py_DECREF(res);
4054 return 0;
4055}
4056
4057/* Map rich comparison operators to their __xx__ namesakes */
4058static char *name_op[] = {
4059 "__lt__",
4060 "__le__",
4061 "__eq__",
4062 "__ne__",
4063 "__gt__",
4064 "__ge__",
4065};
4066
4067static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004068half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004069{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004070 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004071 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004072
Guido van Rossum60718732001-08-28 17:47:51 +00004073 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004074 if (func == NULL) {
4075 PyErr_Clear();
4076 Py_INCREF(Py_NotImplemented);
4077 return Py_NotImplemented;
4078 }
4079 args = Py_BuildValue("(O)", other);
4080 if (args == NULL)
4081 res = NULL;
4082 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004083 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004084 Py_DECREF(args);
4085 }
4086 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004087 return res;
4088}
4089
Guido van Rossumb8f63662001-08-15 23:57:02 +00004090/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4091static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4092
4093static PyObject *
4094slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4095{
4096 PyObject *res;
4097
4098 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4099 res = half_richcompare(self, other, op);
4100 if (res != Py_NotImplemented)
4101 return res;
4102 Py_DECREF(res);
4103 }
4104 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4105 res = half_richcompare(other, self, swapped_op[op]);
4106 if (res != Py_NotImplemented) {
4107 return res;
4108 }
4109 Py_DECREF(res);
4110 }
4111 Py_INCREF(Py_NotImplemented);
4112 return Py_NotImplemented;
4113}
4114
4115static PyObject *
4116slot_tp_iter(PyObject *self)
4117{
4118 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004119 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004120
Guido van Rossum60718732001-08-28 17:47:51 +00004121 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004122 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004123 PyObject *args;
4124 args = res = PyTuple_New(0);
4125 if (args != NULL) {
4126 res = PyObject_Call(func, args, NULL);
4127 Py_DECREF(args);
4128 }
4129 Py_DECREF(func);
4130 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004131 }
4132 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004133 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004134 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004135 PyErr_SetString(PyExc_TypeError,
4136 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004137 return NULL;
4138 }
4139 Py_DECREF(func);
4140 return PySeqIter_New(self);
4141}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004142
4143static PyObject *
4144slot_tp_iternext(PyObject *self)
4145{
Guido van Rossum2730b132001-08-28 18:22:14 +00004146 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004147 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004148}
4149
Guido van Rossum1a493502001-08-17 16:47:50 +00004150static PyObject *
4151slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4152{
4153 PyTypeObject *tp = self->ob_type;
4154 PyObject *get;
4155 static PyObject *get_str = NULL;
4156
4157 if (get_str == NULL) {
4158 get_str = PyString_InternFromString("__get__");
4159 if (get_str == NULL)
4160 return NULL;
4161 }
4162 get = _PyType_Lookup(tp, get_str);
4163 if (get == NULL) {
4164 /* Avoid further slowdowns */
4165 if (tp->tp_descr_get == slot_tp_descr_get)
4166 tp->tp_descr_get = NULL;
4167 Py_INCREF(self);
4168 return self;
4169 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004170 if (obj == NULL)
4171 obj = Py_None;
4172 if (type == NULL)
4173 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004174 return PyObject_CallFunction(get, "OOO", self, obj, type);
4175}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004176
4177static int
4178slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4179{
Guido van Rossum2c252392001-08-24 10:13:31 +00004180 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004181 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004182
4183 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004184 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004185 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004186 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004187 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004188 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004189 if (res == NULL)
4190 return -1;
4191 Py_DECREF(res);
4192 return 0;
4193}
4194
4195static int
4196slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4197{
Guido van Rossum60718732001-08-28 17:47:51 +00004198 static PyObject *init_str;
4199 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004200 PyObject *res;
4201
4202 if (meth == NULL)
4203 return -1;
4204 res = PyObject_Call(meth, args, kwds);
4205 Py_DECREF(meth);
4206 if (res == NULL)
4207 return -1;
4208 Py_DECREF(res);
4209 return 0;
4210}
4211
4212static PyObject *
4213slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4214{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004215 static PyObject *new_str;
4216 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004217 PyObject *newargs, *x;
4218 int i, n;
4219
Guido van Rossum7bed2132002-08-08 21:57:53 +00004220 if (new_str == NULL) {
4221 new_str = PyString_InternFromString("__new__");
4222 if (new_str == NULL)
4223 return NULL;
4224 }
4225 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004226 if (func == NULL)
4227 return NULL;
4228 assert(PyTuple_Check(args));
4229 n = PyTuple_GET_SIZE(args);
4230 newargs = PyTuple_New(n+1);
4231 if (newargs == NULL)
4232 return NULL;
4233 Py_INCREF(type);
4234 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4235 for (i = 0; i < n; i++) {
4236 x = PyTuple_GET_ITEM(args, i);
4237 Py_INCREF(x);
4238 PyTuple_SET_ITEM(newargs, i+1, x);
4239 }
4240 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004241 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004242 Py_DECREF(func);
4243 return x;
4244}
4245
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004246static void
4247slot_tp_del(PyObject *self)
4248{
4249 static PyObject *del_str = NULL;
4250 PyObject *del, *res;
4251 PyObject *error_type, *error_value, *error_traceback;
4252
4253 /* Temporarily resurrect the object. */
4254 assert(self->ob_refcnt == 0);
4255 self->ob_refcnt = 1;
4256
4257 /* Save the current exception, if any. */
4258 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4259
4260 /* Execute __del__ method, if any. */
4261 del = lookup_maybe(self, "__del__", &del_str);
4262 if (del != NULL) {
4263 res = PyEval_CallObject(del, NULL);
4264 if (res == NULL)
4265 PyErr_WriteUnraisable(del);
4266 else
4267 Py_DECREF(res);
4268 Py_DECREF(del);
4269 }
4270
4271 /* Restore the saved exception. */
4272 PyErr_Restore(error_type, error_value, error_traceback);
4273
4274 /* Undo the temporary resurrection; can't use DECREF here, it would
4275 * cause a recursive call.
4276 */
4277 assert(self->ob_refcnt > 0);
4278 if (--self->ob_refcnt == 0)
4279 return; /* this is the normal path out */
4280
4281 /* __del__ resurrected it! Make it look like the original Py_DECREF
4282 * never happened.
4283 */
4284 {
4285 int refcnt = self->ob_refcnt;
4286 _Py_NewReference(self);
4287 self->ob_refcnt = refcnt;
4288 }
4289 assert(!PyType_IS_GC(self->ob_type) ||
4290 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4291 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4292 * _Py_NewReference bumped it again, so that's a wash.
4293 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4294 * chain, so no more to do there either.
4295 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4296 * _Py_NewReference bumped tp_allocs: both of those need to be
4297 * undone.
4298 */
4299#ifdef COUNT_ALLOCS
4300 --self->ob_type->tp_frees;
4301 --self->ob_type->tp_allocs;
4302#endif
4303}
4304
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004305
4306/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4307 functions. The offsets here are relative to the 'etype' structure, which
4308 incorporates the additional structures used for numbers, sequences and
4309 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4310 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004311 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4312 terminated with an all-zero entry. (This table is further initialized and
4313 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004314
Guido van Rossum6d204072001-10-21 00:44:31 +00004315typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004316
4317#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004318#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004319#undef ETSLOT
4320#undef SQSLOT
4321#undef MPSLOT
4322#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004323#undef UNSLOT
4324#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004325#undef BINSLOT
4326#undef RBINSLOT
4327
Guido van Rossum6d204072001-10-21 00:44:31 +00004328#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004329 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4330 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004331#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4332 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004333 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004334#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004335 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4336 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004337#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4338 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4339#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4340 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4341#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4342 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4343#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4344 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4345 "x." NAME "() <==> " DOC)
4346#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4347 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4348 "x." NAME "(y) <==> x" DOC "y")
4349#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4350 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4351 "x." NAME "(y) <==> x" DOC "y")
4352#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4353 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4354 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004355
4356static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004357 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4358 "x.__len__() <==> len(x)"),
4359 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4360 "x.__add__(y) <==> x+y"),
4361 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4362 "x.__mul__(n) <==> x*n"),
4363 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4364 "x.__rmul__(n) <==> n*x"),
4365 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4366 "x.__getitem__(y) <==> x[y]"),
4367 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4368 "x.__getslice__(i, j) <==> x[i:j]"),
4369 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4370 "x.__setitem__(i, y) <==> x[i]=y"),
4371 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4372 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004373 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004374 wrap_intintobjargproc,
4375 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4376 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4377 "x.__delslice__(i, j) <==> del x[i:j]"),
4378 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4379 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004380 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004381 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004382 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004383 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004384
Guido van Rossum6d204072001-10-21 00:44:31 +00004385 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4386 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004387 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004388 wrap_binaryfunc,
4389 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004390 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004391 wrap_objobjargproc,
4392 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004393 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004394 wrap_delitem,
4395 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004396
Guido van Rossum6d204072001-10-21 00:44:31 +00004397 BINSLOT("__add__", nb_add, slot_nb_add,
4398 "+"),
4399 RBINSLOT("__radd__", nb_add, slot_nb_add,
4400 "+"),
4401 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4402 "-"),
4403 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4404 "-"),
4405 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4406 "*"),
4407 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4408 "*"),
4409 BINSLOT("__div__", nb_divide, slot_nb_divide,
4410 "/"),
4411 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4412 "/"),
4413 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4414 "%"),
4415 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4416 "%"),
4417 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4418 "divmod(x, y)"),
4419 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4420 "divmod(y, x)"),
4421 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4422 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4423 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4424 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4425 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4426 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4427 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4428 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004429 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004430 "x != 0"),
4431 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4432 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4433 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4434 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4435 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4436 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4437 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4438 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4439 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4440 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4441 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4442 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4443 "x.__coerce__(y) <==> coerce(x, y)"),
4444 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4445 "int(x)"),
4446 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4447 "long(x)"),
4448 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4449 "float(x)"),
4450 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4451 "oct(x)"),
4452 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4453 "hex(x)"),
4454 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4455 wrap_binaryfunc, "+"),
4456 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4457 wrap_binaryfunc, "-"),
4458 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4459 wrap_binaryfunc, "*"),
4460 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4461 wrap_binaryfunc, "/"),
4462 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4463 wrap_binaryfunc, "%"),
4464 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004465 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004466 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4467 wrap_binaryfunc, "<<"),
4468 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4469 wrap_binaryfunc, ">>"),
4470 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4471 wrap_binaryfunc, "&"),
4472 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4473 wrap_binaryfunc, "^"),
4474 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4475 wrap_binaryfunc, "|"),
4476 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4477 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4478 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4479 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4480 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4481 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4482 IBSLOT("__itruediv__", nb_inplace_true_divide,
4483 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004484
Guido van Rossum6d204072001-10-21 00:44:31 +00004485 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4486 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004487 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004488 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4489 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004490 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004491 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4492 "x.__cmp__(y) <==> cmp(x,y)"),
4493 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4494 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004495 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4496 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004497 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004498 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4499 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4500 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4501 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4502 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4503 "x.__setattr__('name', value) <==> x.name = value"),
4504 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4505 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4506 "x.__delattr__('name') <==> del x.name"),
4507 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4508 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4509 "x.__lt__(y) <==> x<y"),
4510 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4511 "x.__le__(y) <==> x<=y"),
4512 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4513 "x.__eq__(y) <==> x==y"),
4514 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4515 "x.__ne__(y) <==> x!=y"),
4516 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4517 "x.__gt__(y) <==> x>y"),
4518 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4519 "x.__ge__(y) <==> x>=y"),
4520 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4521 "x.__iter__() <==> iter(x)"),
4522 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4523 "x.next() -> the next value, or raise StopIteration"),
4524 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4525 "descr.__get__(obj[, type]) -> value"),
4526 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4527 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004528 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4529 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004530 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004531 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004532 "see x.__class__.__doc__ for signature",
4533 PyWrapperFlag_KEYWORDS),
4534 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004535 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004536 {NULL}
4537};
4538
Guido van Rossumc334df52002-04-04 23:44:47 +00004539/* Given a type pointer and an offset gotten from a slotdef entry, return a
4540 pointer to the actual slot. This is not quite the same as simply adding
4541 the offset to the type pointer, since it takes care to indirect through the
4542 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4543 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004544static void **
4545slotptr(PyTypeObject *type, int offset)
4546{
4547 char *ptr;
4548
Guido van Rossum09638c12002-06-13 19:17:46 +00004549 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004550 assert(offset >= 0);
4551 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004552 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004553 ptr = (void *)type->tp_as_sequence;
4554 offset -= offsetof(etype, as_sequence);
4555 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004556 else if (offset >= offsetof(etype, as_mapping)) {
4557 ptr = (void *)type->tp_as_mapping;
4558 offset -= offsetof(etype, as_mapping);
4559 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004560 else if (offset >= offsetof(etype, as_number)) {
4561 ptr = (void *)type->tp_as_number;
4562 offset -= offsetof(etype, as_number);
4563 }
4564 else {
4565 ptr = (void *)type;
4566 }
4567 if (ptr != NULL)
4568 ptr += offset;
4569 return (void **)ptr;
4570}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004571
Guido van Rossumc334df52002-04-04 23:44:47 +00004572/* Length of array of slotdef pointers used to store slots with the
4573 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4574 the same __name__, for any __name__. Since that's a static property, it is
4575 appropriate to declare fixed-size arrays for this. */
4576#define MAX_EQUIV 10
4577
4578/* Return a slot pointer for a given name, but ONLY if the attribute has
4579 exactly one slot function. The name must be an interned string. */
4580static void **
4581resolve_slotdups(PyTypeObject *type, PyObject *name)
4582{
4583 /* XXX Maybe this could be optimized more -- but is it worth it? */
4584
4585 /* pname and ptrs act as a little cache */
4586 static PyObject *pname;
4587 static slotdef *ptrs[MAX_EQUIV];
4588 slotdef *p, **pp;
4589 void **res, **ptr;
4590
4591 if (pname != name) {
4592 /* Collect all slotdefs that match name into ptrs. */
4593 pname = name;
4594 pp = ptrs;
4595 for (p = slotdefs; p->name_strobj; p++) {
4596 if (p->name_strobj == name)
4597 *pp++ = p;
4598 }
4599 *pp = NULL;
4600 }
4601
4602 /* Look in all matching slots of the type; if exactly one of these has
4603 a filled-in slot, return its value. Otherwise return NULL. */
4604 res = NULL;
4605 for (pp = ptrs; *pp; pp++) {
4606 ptr = slotptr(type, (*pp)->offset);
4607 if (ptr == NULL || *ptr == NULL)
4608 continue;
4609 if (res != NULL)
4610 return NULL;
4611 res = ptr;
4612 }
4613 return res;
4614}
4615
4616/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4617 does some incredibly complex thinking and then sticks something into the
4618 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4619 interests, and then stores a generic wrapper or a specific function into
4620 the slot.) Return a pointer to the next slotdef with a different offset,
4621 because that's convenient for fixup_slot_dispatchers(). */
4622static slotdef *
4623update_one_slot(PyTypeObject *type, slotdef *p)
4624{
4625 PyObject *descr;
4626 PyWrapperDescrObject *d;
4627 void *generic = NULL, *specific = NULL;
4628 int use_generic = 0;
4629 int offset = p->offset;
4630 void **ptr = slotptr(type, offset);
4631
4632 if (ptr == NULL) {
4633 do {
4634 ++p;
4635 } while (p->offset == offset);
4636 return p;
4637 }
4638 do {
4639 descr = _PyType_Lookup(type, p->name_strobj);
4640 if (descr == NULL)
4641 continue;
4642 if (descr->ob_type == &PyWrapperDescr_Type) {
4643 void **tptr = resolve_slotdups(type, p->name_strobj);
4644 if (tptr == NULL || tptr == ptr)
4645 generic = p->function;
4646 d = (PyWrapperDescrObject *)descr;
4647 if (d->d_base->wrapper == p->wrapper &&
4648 PyType_IsSubtype(type, d->d_type))
4649 {
4650 if (specific == NULL ||
4651 specific == d->d_wrapped)
4652 specific = d->d_wrapped;
4653 else
4654 use_generic = 1;
4655 }
4656 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004657 else if (descr->ob_type == &PyCFunction_Type &&
4658 PyCFunction_GET_FUNCTION(descr) ==
4659 (PyCFunction)tp_new_wrapper &&
4660 strcmp(p->name, "__new__") == 0)
4661 {
4662 /* The __new__ wrapper is not a wrapper descriptor,
4663 so must be special-cased differently.
4664 If we don't do this, creating an instance will
4665 always use slot_tp_new which will look up
4666 __new__ in the MRO which will call tp_new_wrapper
4667 which will look through the base classes looking
4668 for a static base and call its tp_new (usually
4669 PyType_GenericNew), after performing various
4670 sanity checks and constructing a new argument
4671 list. Cut all that nonsense short -- this speeds
4672 up instance creation tremendously. */
4673 specific = type->tp_new;
4674 /* XXX I'm not 100% sure that there isn't a hole
4675 in this reasoning that requires additional
4676 sanity checks. I'll buy the first person to
4677 point out a bug in this reasoning a beer. */
4678 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004679 else {
4680 use_generic = 1;
4681 generic = p->function;
4682 }
4683 } while ((++p)->offset == offset);
4684 if (specific && !use_generic)
4685 *ptr = specific;
4686 else
4687 *ptr = generic;
4688 return p;
4689}
4690
Guido van Rossum22b13872002-08-06 21:41:44 +00004691static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004692 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004693
Guido van Rossumc334df52002-04-04 23:44:47 +00004694/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4695 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004696static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004697update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004698{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004699 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004700
Guido van Rossumc334df52002-04-04 23:44:47 +00004701 for (pp = pp0; *pp; pp++)
4702 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004703 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004704}
4705
Guido van Rossumc334df52002-04-04 23:44:47 +00004706/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4707 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004708static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004709recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004710{
4711 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004712 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004713 int i, n;
4714
4715 subclasses = type->tp_subclasses;
4716 if (subclasses == NULL)
4717 return 0;
4718 assert(PyList_Check(subclasses));
4719 n = PyList_GET_SIZE(subclasses);
4720 for (i = 0; i < n; i++) {
4721 ref = PyList_GET_ITEM(subclasses, i);
4722 assert(PyWeakref_CheckRef(ref));
4723 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004724 assert(subclass != NULL);
4725 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004726 continue;
4727 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004728 /* Avoid recursing down into unaffected classes */
4729 dict = subclass->tp_dict;
4730 if (dict != NULL && PyDict_Check(dict) &&
4731 PyDict_GetItem(dict, name) != NULL)
4732 continue;
4733 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004734 return -1;
4735 }
4736 return 0;
4737}
4738
Guido van Rossumc334df52002-04-04 23:44:47 +00004739/* Comparison function for qsort() to compare slotdefs by their offset, and
4740 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004741static int
4742slotdef_cmp(const void *aa, const void *bb)
4743{
4744 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4745 int c = a->offset - b->offset;
4746 if (c != 0)
4747 return c;
4748 else
4749 return a - b;
4750}
4751
Guido van Rossumc334df52002-04-04 23:44:47 +00004752/* Initialize the slotdefs table by adding interned string objects for the
4753 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004754static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004755init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004756{
4757 slotdef *p;
4758 static int initialized = 0;
4759
4760 if (initialized)
4761 return;
4762 for (p = slotdefs; p->name; p++) {
4763 p->name_strobj = PyString_InternFromString(p->name);
4764 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004765 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004766 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004767 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4768 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004769 initialized = 1;
4770}
4771
Guido van Rossumc334df52002-04-04 23:44:47 +00004772/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004773static int
4774update_slot(PyTypeObject *type, PyObject *name)
4775{
Guido van Rossumc334df52002-04-04 23:44:47 +00004776 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004777 slotdef *p;
4778 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004779 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004780
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004781 init_slotdefs();
4782 pp = ptrs;
4783 for (p = slotdefs; p->name; p++) {
4784 /* XXX assume name is interned! */
4785 if (p->name_strobj == name)
4786 *pp++ = p;
4787 }
4788 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004789 for (pp = ptrs; *pp; pp++) {
4790 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004791 offset = p->offset;
4792 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004793 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004794 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004795 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004796 if (ptrs[0] == NULL)
4797 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004798 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004799}
4800
Guido van Rossumc334df52002-04-04 23:44:47 +00004801/* Store the proper functions in the slot dispatches at class (type)
4802 definition time, based upon which operations the class overrides in its
4803 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004804static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004805fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004806{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004807 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004808
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004809 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004810 for (p = slotdefs; p->name; )
4811 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004812}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004813
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004814static void
4815update_all_slots(PyTypeObject* type)
4816{
4817 slotdef *p;
4818
4819 init_slotdefs();
4820 for (p = slotdefs; p->name; p++) {
4821 /* update_slot returns int but can't actually fail */
4822 update_slot(type, p->name_strobj);
4823 }
4824}
4825
Guido van Rossum6d204072001-10-21 00:44:31 +00004826/* This function is called by PyType_Ready() to populate the type's
4827 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004828 function slot (like tp_repr) that's defined in the type, one or more
4829 corresponding descriptors are added in the type's tp_dict dictionary
4830 under the appropriate name (like __repr__). Some function slots
4831 cause more than one descriptor to be added (for example, the nb_add
4832 slot adds both __add__ and __radd__ descriptors) and some function
4833 slots compete for the same descriptor (for example both sq_item and
4834 mp_subscript generate a __getitem__ descriptor).
4835
4836 In the latter case, the first slotdef entry encoutered wins. Since
4837 slotdef entries are sorted by the offset of the slot in the etype
4838 struct, this gives us some control over disambiguating between
4839 competing slots: the members of struct etype are listed from most
4840 general to least general, so the most general slot is preferred. In
4841 particular, because as_mapping comes before as_sequence, for a type
4842 that defines both mp_subscript and sq_item, mp_subscript wins.
4843
4844 This only adds new descriptors and doesn't overwrite entries in
4845 tp_dict that were previously defined. The descriptors contain a
4846 reference to the C function they must call, so that it's safe if they
4847 are copied into a subtype's __dict__ and the subtype has a different
4848 C function in its slot -- calling the method defined by the
4849 descriptor will call the C function that was used to create it,
4850 rather than the C function present in the slot when it is called.
4851 (This is important because a subtype may have a C function in the
4852 slot that calls the method from the dictionary, and we want to avoid
4853 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004854
4855static int
4856add_operators(PyTypeObject *type)
4857{
4858 PyObject *dict = type->tp_dict;
4859 slotdef *p;
4860 PyObject *descr;
4861 void **ptr;
4862
4863 init_slotdefs();
4864 for (p = slotdefs; p->name; p++) {
4865 if (p->wrapper == NULL)
4866 continue;
4867 ptr = slotptr(type, p->offset);
4868 if (!ptr || !*ptr)
4869 continue;
4870 if (PyDict_GetItem(dict, p->name_strobj))
4871 continue;
4872 descr = PyDescr_NewWrapper(type, p, *ptr);
4873 if (descr == NULL)
4874 return -1;
4875 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4876 return -1;
4877 Py_DECREF(descr);
4878 }
4879 if (type->tp_new != NULL) {
4880 if (add_tp_new_wrapper(type) < 0)
4881 return -1;
4882 }
4883 return 0;
4884}
4885
Guido van Rossum705f0f52001-08-24 16:47:00 +00004886
4887/* Cooperative 'super' */
4888
4889typedef struct {
4890 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004891 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004892 PyObject *obj;
4893} superobject;
4894
Guido van Rossum6f799372001-09-20 20:46:19 +00004895static PyMemberDef super_members[] = {
4896 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4897 "the class invoking super()"},
4898 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4899 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004900 {0}
4901};
4902
Guido van Rossum705f0f52001-08-24 16:47:00 +00004903static void
4904super_dealloc(PyObject *self)
4905{
4906 superobject *su = (superobject *)self;
4907
Guido van Rossum048eb752001-10-02 21:24:57 +00004908 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004909 Py_XDECREF(su->obj);
4910 Py_XDECREF(su->type);
4911 self->ob_type->tp_free(self);
4912}
4913
4914static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004915super_repr(PyObject *self)
4916{
4917 superobject *su = (superobject *)self;
4918
4919 if (su->obj)
4920 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004921 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004922 su->type ? su->type->tp_name : "NULL",
4923 su->obj->ob_type->tp_name);
4924 else
4925 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004926 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004927 su->type ? su->type->tp_name : "NULL");
4928}
4929
4930static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004931super_getattro(PyObject *self, PyObject *name)
4932{
4933 superobject *su = (superobject *)self;
4934
4935 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004936 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004937 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004938 descrgetfunc f;
4939 int i, n;
4940
Guido van Rossum155db9a2002-04-02 17:53:47 +00004941 starttype = su->obj->ob_type;
4942 mro = starttype->tp_mro;
4943
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004944 if (mro == NULL)
4945 n = 0;
4946 else {
4947 assert(PyTuple_Check(mro));
4948 n = PyTuple_GET_SIZE(mro);
4949 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004950 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004951 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004952 break;
4953 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004954 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004955 starttype = (PyTypeObject *)(su->obj);
4956 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004957 if (mro == NULL)
4958 n = 0;
4959 else {
4960 assert(PyTuple_Check(mro));
4961 n = PyTuple_GET_SIZE(mro);
4962 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004963 for (i = 0; i < n; i++) {
4964 if ((PyObject *)(su->type) ==
4965 PyTuple_GET_ITEM(mro, i))
4966 break;
4967 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004968 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004969 i++;
4970 res = NULL;
4971 for (; i < n; i++) {
4972 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004973 if (PyType_Check(tmp))
4974 dict = ((PyTypeObject *)tmp)->tp_dict;
4975 else if (PyClass_Check(tmp))
4976 dict = ((PyClassObject *)tmp)->cl_dict;
4977 else
4978 continue;
4979 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004980 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004981 Py_INCREF(res);
4982 f = res->ob_type->tp_descr_get;
4983 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004984 tmp = f(res, su->obj,
4985 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004986 Py_DECREF(res);
4987 res = tmp;
4988 }
4989 return res;
4990 }
4991 }
4992 }
4993 return PyObject_GenericGetAttr(self, name);
4994}
4995
Guido van Rossum5b443c62001-12-03 15:38:28 +00004996static int
4997supercheck(PyTypeObject *type, PyObject *obj)
4998{
4999 if (!PyType_IsSubtype(obj->ob_type, type) &&
5000 !(PyType_Check(obj) &&
5001 PyType_IsSubtype((PyTypeObject *)obj, type))) {
5002 PyErr_SetString(PyExc_TypeError,
5003 "super(type, obj): "
5004 "obj must be an instance or subtype of type");
5005 return -1;
5006 }
5007 else
5008 return 0;
5009}
5010
Guido van Rossum705f0f52001-08-24 16:47:00 +00005011static PyObject *
5012super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5013{
5014 superobject *su = (superobject *)self;
5015 superobject *new;
5016
5017 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5018 /* Not binding to an object, or already bound */
5019 Py_INCREF(self);
5020 return self;
5021 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005022 if (su->ob_type != &PySuper_Type)
5023 /* If su is an instance of a subclass of super,
5024 call its type */
5025 return PyObject_CallFunction((PyObject *)su->ob_type,
5026 "OO", su->type, obj);
5027 else {
5028 /* Inline the common case */
5029 if (supercheck(su->type, obj) < 0)
5030 return NULL;
5031 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5032 NULL, NULL);
5033 if (new == NULL)
5034 return NULL;
5035 Py_INCREF(su->type);
5036 Py_INCREF(obj);
5037 new->type = su->type;
5038 new->obj = obj;
5039 return (PyObject *)new;
5040 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005041}
5042
5043static int
5044super_init(PyObject *self, PyObject *args, PyObject *kwds)
5045{
5046 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005047 PyTypeObject *type;
5048 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005049
5050 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5051 return -1;
5052 if (obj == Py_None)
5053 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005054 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005055 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005056 Py_INCREF(type);
5057 Py_XINCREF(obj);
5058 su->type = type;
5059 su->obj = obj;
5060 return 0;
5061}
5062
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005063PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005064"super(type) -> unbound super object\n"
5065"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005066"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005067"Typical use to call a cooperative superclass method:\n"
5068"class C(B):\n"
5069" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005070" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005071
Guido van Rossum048eb752001-10-02 21:24:57 +00005072static int
5073super_traverse(PyObject *self, visitproc visit, void *arg)
5074{
5075 superobject *su = (superobject *)self;
5076 int err;
5077
5078#define VISIT(SLOT) \
5079 if (SLOT) { \
5080 err = visit((PyObject *)(SLOT), arg); \
5081 if (err) \
5082 return err; \
5083 }
5084
5085 VISIT(su->obj);
5086 VISIT(su->type);
5087
5088#undef VISIT
5089
5090 return 0;
5091}
5092
Guido van Rossum705f0f52001-08-24 16:47:00 +00005093PyTypeObject PySuper_Type = {
5094 PyObject_HEAD_INIT(&PyType_Type)
5095 0, /* ob_size */
5096 "super", /* tp_name */
5097 sizeof(superobject), /* tp_basicsize */
5098 0, /* tp_itemsize */
5099 /* methods */
5100 super_dealloc, /* tp_dealloc */
5101 0, /* tp_print */
5102 0, /* tp_getattr */
5103 0, /* tp_setattr */
5104 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005105 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005106 0, /* tp_as_number */
5107 0, /* tp_as_sequence */
5108 0, /* tp_as_mapping */
5109 0, /* tp_hash */
5110 0, /* tp_call */
5111 0, /* tp_str */
5112 super_getattro, /* tp_getattro */
5113 0, /* tp_setattro */
5114 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005115 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5116 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005117 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005118 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005119 0, /* tp_clear */
5120 0, /* tp_richcompare */
5121 0, /* tp_weaklistoffset */
5122 0, /* tp_iter */
5123 0, /* tp_iternext */
5124 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005125 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005126 0, /* tp_getset */
5127 0, /* tp_base */
5128 0, /* tp_dict */
5129 super_descr_get, /* tp_descr_get */
5130 0, /* tp_descr_set */
5131 0, /* tp_dictoffset */
5132 super_init, /* tp_init */
5133 PyType_GenericAlloc, /* tp_alloc */
5134 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005135 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005136};